var first_run = true;
var body = '';
var matchesHl = [];
var matchesGl = [];
var matchesTld = [];
var resultsNumber = 0;
var lang = $('html')[0].lang.split('-');
var loc = '';
var loadingDiv = '<div class="loading-div">' +
    '<div class="preloader-showbox showbox loading">\n' +
    '    <div class="loader">\n' +
    '        <svg class="circular" viewBox="25 25 50 50">\n' +
    '            <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10"/>\n' +
    '        </svg>\n' +
    '    </div>\n' +
    '</div>\n' +
    '<div id="seo-loading-text" class="loading-text">Processing your request. Please wait...</div>'
    '</div>';

var errorPopUp = '<div id="seo-error-pop-up" class="seo-error-pop-up-container seo-hidden">' +
    '<span id="close-pop-up-button" class="close-pop-up-button">X</span>' +
        '<div class="seo-error-pop-up-content">' +
            '<div class="seo-error-pop-up-image"><img src="' + chrome.runtime.getURL('icons/notFound.png') + '"></div> ' +
            '<div class="seo-error-pop-up-text">' +
                '<span id="seo-error-text-1"></span>' +
            '</div> ' +
        '</div> ' +
    '</div>'
var startCrawl = false;


chrome.runtime.onMessage.addListener(gotMessage);

chrome.storage.sync.get(['token'], function (result) {
    var token = result.token;
    if (token) {
        // checkIAmMaster();
        }
});

checkIAmMaster();

function gotMessage(message, sender, sendResponse) {
    let msg = {
        txt : ''
    }
    switch(message.txt) {

        case 'info':
            $('iframe#right-frame').contents().find('#seo-loading-text').html(message.info);
            // $('iframe#right-frame').contents().find('html').css('zoom', 0.7);
            break;

        case 'createButton':
            createButton(message.user_id);
            break;

        case 'error':
            $('#seo-error-pop-up').removeClass('seo-hidden');
            document.getElementById('seo-error-text-1').innerText = message.error_msg;
            if(typeof $('#check-if-iam-loggedin') != "undefined"){
                $('#check-if-iam-loggedin').addClass('seo-hidden');
            }

            window.document.getElementById("close-pop-up-button").addEventListener("click", function(){
                $('#seo-error-pop-up').addClass('seo-hidden');
            });
            break;

        case 'setBody':

            if(first_run == false){
                return false;
            }

            first_run = false;
            var style = ' style ="    z-index: 9999;\n' +
                '    margin-top: 0;\n' +
                // '    margin-bottom: 5px;\n' +
                '    margin-bottom: 4px;\n' +
                '    width: 100%;"'+
                '    padding-left: 10px;"';

            msg.txt = 'setBody';
            $('head').append('<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Roboto:400,700" rel="stylesheet">');
            $('#searchform').css('position', 'relative');
            body = $('body').html();

            if(!message.html){
                message.html = message.error_msg;
            }

            $('body').addClass('seo-body-container');
            $('body').html(errorPopUp +
                    '<input type="checkbox" id="sync-scroll"/> ' +
                    '<label for="sync-scroll" class="seo-lock-scroll-label seo-hidden">' +
                        '<div class="seo-locked-scroll seo-hidden"><img src="'+ chrome.runtime.getURL('icons/lock-close.png') + '"> Scroll</div>' +
                        '<div class="seo-unlocked-scroll"><img src="'+ chrome.runtime.getURL('icons/lock-open.png') + '"> Scroll</div>' +
                    '</label>'+
                    '<div id="placeholder-google" style="display: none"></div> ' +
                    '<div class="seo-checker-header">' +
                        '<div class="seo-header-container">' +
                            '<img src="'+ chrome.runtime.getURL('icons/iconSeo.png') + '">' +
                            '<span class="seo-header-text">SERP Rank Discrepancy Checker</span> ' +
                            '<div id="seoHeaderSiteContainer" class="seo-site-select-header seo-hidden">' +
                                '<label class="seo-label" for="headerSeoWebsites">Campaign:</label> ' +
                                '<select id="headerSeoWebsites">' + message.html + '</select>' +
                            '</div> ' +
                        '</div> ' +
                    '</div> '+
                '<div class="seo-rank-checker-container">' +
                    '<div id="left-div">' +
                        '<div class="seo-sections-bar seo-blue-bar"></div> ' +
                        '<div class="seo-left-header"> ' +
                            '<div class="seo-title">Your Browser</div>' +
                            '<div id="search-summary" class="seo-search-result-div">' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                            '</div>' +
                        '</div>'+
                        '<iframe id="left-frame" style="width: 100%;" src="' + window.location.href + '"></iframe> ' +
                    '</div>' +
                    '<div id="right-div">' +
                        '<div class="seo-pop-up-serp-select">' +
                            '<div class="seo-pop-up-title">Configuration</div>' +
                            '<div class="seo-pop-up-container">' +
                                '<label class="seo-label" for="seoWebsites">Campaign:</label><select id="seoWebsites"> ' + message.html  + '</select>'+
                                '<label class="seo-label seo-label-2" for="radio-container">SERP Source:</label>' +
                                '<div id="radio-container">' +
                                    '<input type="radio" id="r1" name="serp" value="giveMeSERPPage" checked="true"> <label id="label-for-r1" for="r1" class="seo-selected">Latest SERP</label><span id="serp-time"></span><br>\n' +
                                    '<input type="radio" id="r2" name="serp" value="recrawl"><label id="label-for-r2" for="r2"> Real-time Crawl</label><br>' +
                                '</div>' +
                                '<button id="getSerp">Start Analysis</button>' +
                            '</div> ' +
                        '</div> ' +
                        '<div class="seo-sections-bar seo-green-bar"></div> ' +
                        '<div class="seo-right-header"> ' +
                            '<div class="seo-title">Our Crawler</div>' +
                            '<div id="serp-summary"  class="seo-search-result-div">' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                                '<div class="seo-placehoder-search-params"></div> ' +
                            '</div>'+
                            '<div class="seo-error_container seo-hidden"></div> ' +
                        '</div>'+
                    '<iframe id="right-frame" style=" width: 100%;" src="">' +
                    '</iframe>' +
                    '</div>' +
                '</div>' +
                '<div id="footer-rank-checker" class="seo-footer-container seo-hidden">'+
                '<span id="seo-footer-span" class="seo-bottom-text"></span>' +
                '<div id="crawlNow" class="seo-footer-button">Crawl Now</div>' +
                '<div id="giveMeSERPPage" class="seo-footer-link seo-hidden">View Latest SERP: Updated at <span id="serpTimeSpan"></span></div>' +
                '</div>'
            );
            $('#left-frame').on('load', function () {
                // $('#left-frame').contents().find('html').css('zoom', 0.7);
                $('iframe#left-frame').contents().find('input[name="q"]')[0].addEventListener('change',
                    function() {
                        var search = getSearch();
                        var url = new URL(window.location.href);
                        url.searchParams.set("q", search);
                        window.location.href = url.href;
                    });

                $("iframe#left-frame").contents().scroll(function() {
                    if(document.getElementById('sync-scroll').checked == true){
                        $("iframe#right-frame").contents().scrollTop($("iframe#left-frame").contents().scrollTop());
                    }
                });
            });
            $.get(chrome.runtime.getURL('emptyPagePlaceholder.html'), function (data) {
                $("iframe#right-frame").contents().find('head').append(data.substring(data.indexOf("<style>"), data.indexOf('<title>')-1));
                $("iframe#right-frame").contents().find('body').append(data.substring(data.indexOf("<body>")+6, data.indexOf('</body>')-1));
            });
            $("iframe#right-frame").contents().find('body').addClass('c2VvbW9uaXRvcmV4dGVuc2lvbmNo-body');
            if (!message.error_msg) {
                $("#seoWebsites").chosen().find('html');
                document.getElementById("serp-time").textContent = $('#seoWebsites').find(":selected").attr('timeCrawl');

                $('#seoWebsites').on('change', function () {
                    msg.action      = 'giveMeSERPTime';
                    msg.siteId      = $('#seoWebsites').find(":selected").val();
                    msg.ksId        = $('#seoWebsites').find(":selected").attr('kws');
                    $('#headerSeoWebsites').find(":selected").removeAttr('selected');
                    let headerSelect = $('#headerSeoWebsites');
                    let selectedIndex = $('#seoWebsites')[0].selectedIndex;

                    $($(headerSelect)[0][selectedIndex]).attr('selected', 'selected');
                    $(headerSelect).trigger("liszt:updated");
                    chrome.runtime.sendMessage(msg);
                });

                window.document.getElementById("r1").addEventListener("change",
                    function() {
                        if ($("#r1").checked){
                            $("#r1").checked = false;
                            $("#r2").checked = true;
                            $('#label-for-r1').removeClass('seo-selected');
                            if(!$('#label-for-r2').hasClass('seo-selected')) {
                                $('#label-for-r2').addClass('seo-selected');
                            }
                        }
                    }, false);

                window.document.getElementById("sync-scroll").addEventListener("change",
                    function() {
                        if(document.getElementById('sync-scroll').checked == true){
                            $('.seo-locked-scroll').removeClass('seo-hidden');
                            $('.seo-unlocked-scroll').addClass('seo-hidden');
                        }else{
                            $('.seo-locked-scroll').addClass('seo-hidden');
                            $('.seo-unlocked-scroll').removeClass('seo-hidden');
                        }
                    });

                window.document.getElementById("r2").addEventListener("change",
                    function() {
                        if ($("#r2").checked){
                            $("#r2").checked = false;
                            $("#r1").checked = true;
                            $('#label-for-r2').removeClass('seo-selected');
                            if(!$('#label-for-r1').hasClass('seo-selected')) {
                                $('#label-for-r1').addClass('seo-selected');
                            }
                        }
                    }, false);

                        window.document.getElementById("getSerp").addEventListener("click",
                    function() {
                        $('.seo-pop-up-serp-select').addClass('seo-hidden');
                        $('iframe#right-frame').contents().find('head').html('<style>' + loaderCss + '</style>');
                        $('iframe#right-frame').contents().find('body').html(loadingDiv);
                        // $('iframe#right-frame').contents().find('html').css('zoom', 0.7);

                        var msg = {
                            action: $('input[name=serp]:checked').val(),
                        };
                        msg.siteId      = $('#seoWebsites').find(":selected").val();
                        msg.ksId        = $('#seoWebsites').find(":selected").attr('kws');
                        msg.search      = getSearch();

                        $('#headerSeoWebsites').attr('action-serp', msg.action);
                        chrome.runtime.sendMessage(msg);
                    }, false);

                        window.document.getElementById("crawlNow").addEventListener("click",
                    function() {
                        $('iframe#right-frame').contents().find('head').html('<style>' + loaderCss + '</style>');
                        $('iframe#right-frame').contents().find('body').html(loadingDiv);
                        // $('iframe#right-frame').contents().find('html').css('zoom', 0.7);
                        var msg = {
                            action: 'recrawl',
                        };
                        msg.siteId      = $('#headerSeoWebsites').find(":selected").val();
                        msg.ksId        = $('#headerSeoWebsites').find(":selected").attr('kws');
                        msg.search      = getSearch();
                        $('#headerSeoWebsites').attr('action-serp', msg.action);
                        chrome.runtime.sendMessage(msg);
                    }, false);

                        window.document.getElementById("giveMeSERPPage").addEventListener("click",
                    function() {
                        $('iframe#right-frame').contents().find('head').html('<style>' + loaderCss + '</style>');
                        $('iframe#right-frame').contents().find('body').html(loadingDiv);
                        // $('iframe#right-frame').contents().find('html').css('zoom', 0.7);
                        var msg = {
                            action: 'giveMeSERPPage',
                        };
                        msg.siteId      = $('#headerSeoWebsites').find(":selected").val();
                        msg.ksId        = $('#headerSeoWebsites').find(":selected").attr('kws');
                        msg.search      = getSearch();
                        $('#headerSeoWebsites').attr('action-serp', msg.action);
                        chrome.runtime.sendMessage(msg);
                    }, false);
            }else{
                $('.seo-error_container').innerText(message.error_msg);
                if($('.seo-error_container').hasClass('seo-hidden')) {
                    $('.seo-error_container').removeClass('seo-hidden');
                }
            }
            regexHlResult = /(^&amp;)?hl=([^\-"]+?)&/.exec(body);
            regexGlResult = /&amp;gl=([^\-]+?)[&\"]/.exec(body);

            if(regexHlResult != null){
                matchesHl = regexHlResult;
            }

            if(regexGlResult != null){
                matchesGl = regexGlResult;
            }

            console.log('lang => ', lang);
            console.log('GL => ', matchesGl);
            console.log('HL => ', matchesHl);

            if(typeof matchesHl[1] == 'undefined'){
                matchesHl[1] = lang[0];
            }

            if (typeof matchesGl[1] == 'undefined'){
                if(typeof lang[1] == 'undefined') {
                    matchesGl[1] = lang[0];
                }else{
                    matchesGl[1] = lang[1];
                }
            }
            if(typeof matchesHl[1] == 'undefined'){
                matchesHl[1] = 'N/A';
            }
            if (typeof matchesGl[1] == 'undefined'){
                matchesGl[1] = 'N/A';
            }
            matchesTld = new RegExp('google\.([a-z\.]{2,})\/').exec(document.getElementById('left-frame').src);
            resultsNumber = getResultsNumber();
            let location = $(body).find('#swml span:nth-child(2)');
            loc = $(location[0])[0].outerText;
        break;

        case 'set_SERP':

            if(message.data.new_crawl == true){
                if(!$('#crawlNow').hasClass('seo-hidden')) {
                    $('#crawlNow').addClass('seo-hidden');
                }
                $('#giveMeSERPPage').removeClass('seo-hidden');
                $('#serpTimeSpan').html(message.data.serpTime);
                $('#seo-footer-span').html('Crawler snapshot captured at ' + message.data.crawlTime + '.');
            }else{
                $('#giveMeSERPPage').addClass('seo-hidden');
                $('#crawlNow').removeClass('seo-hidden');
                $('#seo-footer-span').html('Crawler snapshot from ' + message.data.crawlTime + '. Click "Crawl Now" to get real-time results.');
            }


            var spans = '';
            var query_g = '';

            if (matchesHl[1].toLowerCase() !== message.data.hl.toLowerCase()) {
                spans = '<div id="hl-container" class="seo-search-params seo-red-search-result" title="This parameter is different from the one set for our crawler. Please update it by clicking on the language box.">' +
                        '   <label for="your-hl">Language: </label>' +
                        '   <span id="your-hl" class="seo-first-letter-uppercase" data-val="' + matchesHl[1] + '">' + matchesHl[1] + '</span>' +
                        '   <img class="seo-red-icon" src="' + chrome.runtime.getURL('icons/redExclamation.png') + '">' +
                        '</div>';
            } else {
                spans = '<div id="hl-container" class="seo-search-params"  title="testhL">' +
                        '   <label for="your-hl">Language: </label>' +
                        '   <span id="your-hl" class="seo-first-letter-uppercase" data-val="' + matchesHl[1] + '">' + matchesHl[1] + '</span>' +
                        '</div>';
            }

            if (matchesGl[1].toLowerCase() !== message.data.gl.toLowerCase()) {
                spans += '<div id="gl-container" class="seo-search-params seo-red-search-result" title="This parameter is different from the one set for our crawler. Please update it by clicking on the box below.">' +
                        '   <label for="your-gl">Country: </label>' +
                        '   <span id="your-gl" class="seo-first-letter-uppercase" data-val="' + matchesGl[1] + '">' + matchesGl[1] + '</span>' +
                        '   <img class="seo-red-icon" src="' + chrome.runtime.getURL('icons/redExclamation.png') + '">' +
                        '</div>';
                query_g += '&gl='+message.data.gl;
            } else {
                spans += '<div id="gl-container" class="seo-search-params">' +
                        '   <label for="your-gl">Country: </label>' +
                        '   <span id="your-gl" class="seo-first-letter-uppercase" data-val="' + matchesGl[1] + '">' + matchesGl[1] + '</span>' +
                        '</div>';
            }

            // if (matchesTld[1].toLowerCase() !== message.data.tld.toLowerCase()) {
            //     spans += '<span class="search-params seo-red-search-result">TLD = ' + matchesTld[1] + '</span>';
            // } else {
            //     spans += '<span class="search-params">TLD = ' + matchesTld[1] + '</span>';
            // }

            if (resultsNumber != 100) {
                spans += '<div id="num-container" class="seo-search-params seo-red-search-result"  title="This parameter is different from the one set for our crawler. Please update it by clicking on the box below."">' +
                            '<label for="your-num">Results/Page: </label>' +
                            '<span id="your-num" class="seo-first-letter-uppercase" data-val="' + resultsNumber + '">' + resultsNumber + '</span>' +
                            '   <img class="seo-red-icon" src="' + chrome.runtime.getURL('icons/redExclamation.png') + '">' +
                        '</div>';
            }else{
                spans += '<div id="num-container" class="seo-search-params">' +
                        '   <label for="your-num">Results/Page:</label>' +
                        '   <span id="your-num" class="seo-first-letter-uppercase" data-val="' + resultsNumber + '">' + resultsNumber + '</span>' +
                        '</div>';

            }

            if (message.isIncognito == false) {
                spans += '<div class="seo-search-params seo-red-search-result" title="This parameter is different from the one set for our crawler. You can activate the incognito mode by selecting CTRL + SHIFT +N .">' +
                        '   <label for="your-incognito">Incognito Mode Off </label>' +
                        '   <img class="seo-red-icon" src="' + chrome.runtime.getURL('icons/redExclamation.png') + '">' +
                        // '   <span class="seo-first-letter-uppercase">' + message.isIncognito + '</span>' +
                        '</div>';
            } else {
                spans += '<div class="seo-search-params">' +
                        '   <label for="your-incognito">Incognito Mode On </label>' +
                        '   <span class="seo-first-letter-uppercase">' + message.isIncognito + '</span>' +
                        '</div>';
            }

            if (new RegExp('<a[^>]* href="https:\/\/accounts.google.com\/ServiceLogin([^"]*)', 'i').exec(body)) {
                spans += '<div class="seo-search-params">' +
                        '   <label for="your-login">Logged Out </label>' +
                        // '   <span class="first-letter-uppercase">false</span>' +
                        '</div>';
            } else {
                spans += '<div class="seo-search-params seo-red-search-result" title="This parameter is different from the one set for our crawler. Please log out form your google account.">' +
                        '   <label for="your-login">Logged In </label>' +
                        '   <img class="seo-red-icon" src="' + chrome.runtime.getURL('icons/redExclamation.png') + '">' +
                        // '   <span id="your-login" class="first-letter-uppercase">true</span>' +
                    '</div>';
            }

            if(loc != message.data.location) {
                spans += '<div id="uule-container" class="seo-search-params seo-orange-search-result"  title="This parameter is different from the one set for our crawler. Please update it by clicking on the box below.">' +
                    '   <label for="your-uule">Location: </label>' +
                    '   <span id="your-uule" class="first-letter-uppercase" value="' + loc + '">' + loc + '</span>' +
                    '</div>';
            }else {
                spans += '<div id="uule-container" class="seo-search-params"  title="testLocation">' +
                    '   <label for="your-uule">Location: </label>' +
                    '   <span id="your-uule" class="first-letter-uppercase" value="' + loc + '">' + loc + '</span>' +
                    '</div>';
            }
            // query_g += '&uule='+message.data.uule;


            $("#search-summary").html(spans);
            $("#serp-summary").html(
                '<div class="seo-search-params">' +
                '   <label for="our-hl">Language: </label>' +
                '   <span id="our-hl" class="seo-first-letter-uppercase" data-val="' + message.data.hl + '">' + message.data.hl + '</span>' +
                '</div>' +
                '<div class="seo-search-params">' +
                '   <label for="our-gl">Country: </label>' +
                '   <span id="our-gl" class="seo-first-letter-uppercase" data-val="' + message.data.gl + '">' + message.data.gl + '</span>' +
                '</div>' +
                // '<span class="seo-search-params">TLD = ' + message.data.tld + '</span>' +
                '<div class="seo-search-params">' +
                '   <label for="our-num">Resuls/Page: </label>' +
                '   <span id="our-num" class="seo-first-letter-uppercase" data-val="100">100</span>' +
                '</div>' +
                '<div class="seo-search-params"><label for="our-incognito">Incognito Mode </label>' +
                '   <span id="our-incognito" class="seo-first-letter-uppercase">On</span>' +
                '</div>' +
                '<div class="seo-search-params">' +
                '   <label for="our-login">Logged Out </label>' +
                // '   <span id="our-login" class="seo-first-letter-uppercase">false</span>' +
                '</div>' +
                '<div class="seo-search-params">' +
                '   <label for="our-uule">Location: </label>' +
                '   <span id="our-uule" class="seo-first-letter-uppercase" data-uule = "' + message.data.uule + '" data-val="' + message.data.location + '">' + message.data.location + '</span>' +
                '</div>'
            );

            // Properly set iframe content while maintaining document structure
            var $frameDoc = $("iframe#right-frame").contents();
            
            // Clear existing content but maintain structure
            $frameDoc.find('head').empty();
            $frameDoc.find('body').empty();

            // // Add styles to head
            // $frameDoc.find('head').append('<style>body { zoom: 0.7; }</style>');
            
            // Add watermark image and content to body
            var watermarkImg = $('<img>', {
                src: chrome.runtime.getURL('icons/logo-seomonitor.png'),
                css: {
                    'position': 'fixed',
                    'opacity': '0.3',
                    '-moz-transform': 'rotate(90deg)',
                    '-webkit-transform': 'rotate(90deg)',
                    '-o-transform': 'rotate(90deg)',
                    '-ms-transform': 'rotate(90deg)',
                    'z-index': '999',
                    'top': '43vh',
                    'width': '97vw',
                    'left': '80vw'
                }
            });
            
            $frameDoc.find('body').append(watermarkImg);
            $frameDoc.find('body').append(message.data.html);
            
            // Hide Google bar
            $frameDoc.find('#gb').css('display', 'none');

            $("iframe#right-frame").contents().scroll(function() {
                if(document.getElementById('sync-scroll').checked == true){
                    $("iframe#left-frame").contents().scrollTop($("iframe#right-frame").contents().scrollTop());
                }
            });

            $('#seoHeaderSiteContainer').removeClass('seo-hidden');
            $('#headerSeoWebsites').chosen();

            $('#headerSeoWebsites').on('change', function () {
                msg.action      = $('#headerSeoWebsites').attr('action-serp');
                msg.siteId      = $('#headerSeoWebsites').find(":selected").val();
                msg.ksId        = $('#headerSeoWebsites').find(":selected").attr('kws');
                chrome.runtime.sendMessage(msg);
            });

            $('.seo-lock-scroll-label').removeClass('seo-hidden');

            window.document.getElementById("hl-container").addEventListener("click",
                function() {
                    let elem = $('#your-hl');
                    if(elem.closest('div').hasClass('seo-red-search-result')) {
                        let ourHl = $('#our-hl');
                        elem.closest('div')[0]._tippy.destroy();
                        elem.closest('div').attr('title', '');
                        elem.closest('div').find('.seo-red-icon').addClass('seo-hidden');
                        matchesHl[1] = ourHl.attr('data-val');
                        changeSearch('hl', ourHl.attr('data-val'));
                    }
                }, false);

            window.document.getElementById("gl-container").addEventListener("click",
                function() {
                    let elem = $('#your-gl');
                    if(elem.closest('div').hasClass('seo-red-search-result')) {
                        let ourGl = $('#our-gl');
                        elem.closest('div').find('.seo-red-icon').addClass('seo-hidden');
                        elem.closest('div')[0]._tippy.destroy();
                        elem.closest('div').attr('title', '');
                        matchesGl[1] = ourGl.attr('data-val');
                        changeSearch('gl', ourGl.attr('data-val'));
                    }
                }, false);

            if($('#footer-rank-checker').hasClass('seo-hidden')){
                $('#footer-rank-checker').removeClass('seo-hidden');
            }

            window.document.getElementById("num-container").addEventListener("click",
                function() {
                    let elem = $('#your-num');
                    if(elem.closest('div').hasClass('seo-red-search-result')) {
                        elem.closest('div')[0]._tippy.destroy();
                        elem.closest('div').attr('title', '');
                        let ourNum = $('#our-num');
                        elem.closest('div').find('.seo-red-icon').addClass('seo-hidden');
                        resultsNumber = ourNum.attr('data-val');
                        changeSearch('num', ourNum.attr('data-val'));
                    }
                }, false);

            window.document.getElementById("uule-container").addEventListener("click",
                function() {
                    let elem = $('#your-uule');
                    if(elem.closest('div').hasClass('seo-orange-search-result')) {
                        elem.closest('div')[0]._tippy.destroy();
                        elem.closest('div').attr('title', '');
                        let ourUule = $('#our-uule');
                        elem.closest('div').find('.seo-red-icon').addClass('seo-hidden');
                        loc = ourUule.attr('data-val');
                        changeSearch('uule', ourUule.attr('data-uule'));
                    }
                }, false);

            tippy(document.querySelectorAll('.seo-red-search-result'), {
                arrow: true,
                theme: 'light',
                size: 'large',
                animation: 'perspective',
                interactive: true
            });

            tippy(document.querySelectorAll('.seo-orange-search-result'), {
                arrow: true,
                theme: 'light',
                size: 'large',
                animation: 'perspective',
                interactive: true
            });
            break;

        default:
            msg.action = 'getSearch';
            msg.seach = search = getSearch();
            // chrome.runtime.sendMessage(msg);
        break;
    }
}

function checkIAmMaster(){
    if(/^https?:\/\/(www\.)?google\.[a-z]+\/search/i.test(window.location.href)) {
        chrome.runtime.sendMessage({action: 'init'});
    }
}

function createButton(user_id){
    if ($.isNumeric(user_id)) {
        if(/^https?:\/\/(www\.)?google\.[a-z]+\/search/i.test(window.location.href)){
            $('head').append('<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Roboto:400,700" rel="stylesheet">');
            if($('#check-if-iam-loggedin').length == 0) {
                $('body').append('<button class="seo-give-me-button" id="check-if-iam-loggedin">' +
                    '<img class="seo-button-image" src="' + chrome.runtime.getURL('icons/iconSeo.png') + '"><span class="seo-button-text"> SERP Discrepancy Checker</span></button>' +
                    errorPopUp
                );
                document.getElementById("check-if-iam-loggedin").onclick = function() {
                    var el = document.getElementById("check-if-iam-loggedin");
                    if(document.getElementById("check-if-iam-loggedin").getAttribute('class').includes('seo-disabled')){
                        return false;
                    }
                    $(el).addClass('seo-disabled');
                    $(el).text('Processing...');
                    var search = getSearch();
                    var message = {
                        action: 'getSearch',
                        search: search
                    };

                    chrome.runtime.sendMessage(message);
                }
            }
        }
    }
}
//
// function getSitesbykw(el) {
//     if(document.getElementById("check-if-iam-loggedin").getAttribute('class').includes('seo-disabled')){
//         return false;
//     }
//     $(el).addClass('seo-disabled');
//     $(el).text('Please wait...a bit');
//     var search = getSearch();
//     var message = {
//         action: 'getSearch',
//         search: search
//     };
//
//     chrome.runtime.sendMessage(message);
// }


function getSearch(){
    if(typeof document.getElementsByName('q')[0] != 'undefined'){
        var search = document.getElementsByName('q')[0].value;
    } else {
        var search = $('iframe#left-frame').contents().find('input[name="q"]')[0].value;
    }
    if(typeof search == 'undefined'){
        url_string = window.location.href;
        var url = new URL(url_string);
        search = url.searchParams.get("q");
    }
    return search;
}

function getResultsNumber(){
    var number = 10;
    url_string = window.location.href;
    var url = new URL(url_string);
     if (url.searchParams.get("num")){
         number = url.searchParams.get("num");
     }else{
         var res = $(body).find('.srg .g');
         number = res.length;
     }


        var ar= [10,20,30,40,50,100];
     var closest, closestDiff, currentDiff;
    if(ar.length) {
        closest = ar[0];
        loop_numbers:
        for (var i = 0 ; i < ar.length; i++) {
            currentDiff = number - ar[i];
            if (currentDiff <= 0) {
                closest = ar[i];
                break loop_numbers;
            }else {
                closest = 100;
            }
            closestDiff = null;
            currentDiff = null;
        }
    }
    return closest;
}


function changeSearch (search_param, value){

    let query_g = '';
    let url_string = $('#left-frame').attr('src');
    let url = new URL(url_string);
    let search = url.searchParams.get(search_param);
    if(search) {
        return false;
    }
    if($('#your-'+search_param).closest('div').hasClass('seo-red-search-result') || $('#your-'+search_param).closest('div').hasClass('seo-orange-search-result')){
        query_g = '&' + search_param + '=' + value;
        $('#left-frame').attr('src' , $('#left-frame').attr('src') + query_g);
        if(search_param === 'uule') {
            $('#your-'+search_param).closest('div').removeClass('seo-orange-search-result');
            document.getElementById('your-' + search_param).innerText = document.getElementById('our-' + search_param).innerText;
        } else {
            document.getElementById('your-' + search_param).innerText = value;
            $('#your-' + search_param).closest('div').removeClass('seo-red-search-result');
        }
    }

    $("iframe#left-frame").contents().scroll(function() {
        if(document.getElementById('sync-scroll').checked == true){
            $("iframe#right-frame").contents().scrollTop($("iframe#left-frame").contents().scrollTop());
        }
    });
}


var loaderCss =
    '.c2VvbW9uaXRvcmV4dGVuc2lvbmNo-body{background-color: #FFFFFF;}' +
    '.loading-div{' +
    '    display: flex;\n' +
    '    align-items: center;\n' +
    '    height: -webkit-fill-available;\n' +
    '    flex-direction: column;\n' +
    '    justify-content: center;' +
    '    background-color: #FFFFFF;'+
    '}'+
    '.loading-text{' +
    '   text-align: center;\n' +
    '   font-size: 4vw;' +
    '   font-family: Helvetica, SansSerif;' +
    '}'+
    ' /*demo-specific*/\n' +
    '.showbox {\n' +
    '    position: relative;\n' +
    '    top: 0;\n' +
    '    bottom: 0;\n' +
    '    left: 0;\n' +
    '    right: 0;\n' +
    '    padding: 5%;\n' +
    '}\n' +
    '\n' +
    ' /*end demo-specific*/\n' +
    '\n' +
    '   .loader {\n' +
    '       position: relative;\n' +
    '       margin: 0 auto;\n' +
    '       width: 15vw;\n' +
    '   }\n' +
    '\n' +
    '.loader::before {\n' +
    '    content: \'\';\n' +
    '    display: block;\n' +
    '    padding-top: 100%;\n' +
    '}\n' +
    '\n' +
    '.loader.small {\n' +
    ' width:18px;\n' +
    '}\n' +
    '\n' +
    '.circular {\n' +
    '    animation: rotate 2s linear infinite;\n' +
    '    height: 100%;\n' +
    '    transform-origin: center center;\n' +
    '    width: 100%;\n' +
    '    position: absolute;\n' +
    '    top: 0;\n' +
    '    bottom: 0;\n' +
    '    left: 0;\n' +
    '    right: 0;\n' +
    '    margin: auto;\n' +
    '}\n' +
    '\n' +
    '.path {\n' +
    '    stroke-dasharray: 1, 200;\n' +
    '    stroke-dashoffset: 0;\n' +
    '    animation: dash 1.5s ease-in-out infinite, color 6s ease-in-out infinite;\n' +
    '    stroke-linecap: round;\n' +
    '}\n' +
    '\n' +
    '@keyframes rotate {\n' +
    '    100% {\n' +
    '        transform: rotate(360deg);\n' +
    '    }\n' +
    '}\n' +
    '\n' +
    '@keyframes dash {\n' +
    '    0% {\n' +
    '        stroke-dasharray: 1, 200;\n' +
    '        stroke-dashoffset: 0;\n' +
    '    }\n' +
    '    50% {\n' +
    '        stroke-dasharray: 89, 200;\n' +
    '        stroke-dashoffset: -35px;\n' +
    '    }\n' +
    '    100% {\n' +
    '        stroke-dasharray: 89, 200;\n' +
    '        stroke-dashoffset: -124px;\n' +
    '    }\n' +
    '}\n' +
    '\n' +
    '@keyframes color {\n' +
    '    100%,\n' +
    '    0% {\n' +
    '        stroke: #75cb2b;\n' +
    '    }\n' +
    '    40% {\n' +
    '        stroke: #75cb2b;\n' +
    '    }\n' +
    '    66% {\n' +
    '        stroke: #75cb2b;\n' +
    '    }\n' +
    '    80%,\n' +
    '    90% {\n' +
    '        stroke: #75cb2b;\n' +
    '    }\n' +
    '}';
