(function(w, $) {
    "use strict";
    var baseurl = w.cgi_addr;
    w.getcover = function getcover(cb, channel) {
        channel = channel || 1;
        //getMosaic
        if ("function" !== typeof cb) return;
        $.ajax({
            method: "GET",
            async: true,
            url: setURL(channel),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            }
        }).done(function(res) {
            if ("true" == $(res).find('Mosaic').eq(0).find('Enable').eq(0).text()) {
                $("#pzenable").prop("checked", true);
            }
            var windows = {};
            var obj = varsToObj(res,channel);
            var keys = Object.keys(obj);
            console.log(keys,'keys');
            var dict = {
                show: "enable",
                x: "left",
                y: "top",
                w: "width",
                h: "height"
            }

            var regx = /^([^\d]+)_(\d)$/;
            var numeric = /^[\+\-]?\d+(?:\.\d+)?$/;
            var i, k, n, prop, match;
            for (i = 0; i < keys.length; i++) {
                k = keys[i];
                match = regx.exec(k);
                n = parseInt(match[2], 10);
                prop = match[1];

                windows["window" + n] = windows["window" + n] || {};
                windows["window" + n][dict[prop]] =
                    (numeric.test(obj[k])) ? Number(obj[k]) : obj[k];

                windows["window" + n].region = n;
                windows["window" + n].enable = !!windows["window" + n].enable;
                windows["window" + n].color = "000000";
            }
            // var bl = getRatio();
            // if (bl > 100) { 
            //     for (let key in windows) {
            //         const window = windows[key];
            //         window.left = (window.left * 100 / bl) * 0.75;
            //         window.top = (window.top * 100 / bl) * 0.75;
            //         window.width = (window.width * 100 / bl) * 0.75;
            //         window.height = (window.height * 100 / bl) * 0.75;
            //     }
            // }
            // console.log(windows,'windows');
            cb(windows);
        });
    };

    w.getresolution = function getresolution(cb) {
        //getResolution
        if ("function" !== typeof cb) return;
        cb({
            width: 703,
            height: 575
        });
    };

    w.setmdattr = function setmdattr(w, cb) {
        var cmd = "setmdattr";

        // console.log("SETMDATTR: window" + w.name + " : " + JSON.stringify(w));

        $.ajax({
            method: "GET",
            async: true,
            url: baseurl,
            data: {
                cmd: cmd,
                "-s": w.sensitivity,
                "-name": w.name,
                "-x": parseInt(w.left, 10),
                "-y": parseInt(w.top, 10),
                "-w": parseInt(w.width, 10),
                "-h": parseInt(w.height, 10),
                "-enable": +w.enable
            }
        }).done(cb);
    };

    w.getmdattr = function getmdattr(cb) {
        //getMotion

        if ("function" !== typeof cb) return;

        $.ajax({
            method: "GET",
            async: true,
            url: motionurl,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            }
        }).done(function(res) {
            $("#moEnable").val($(res).find('Motion').eq(0).find('Enable').eq(0).text());
            changeMotion();
            $("#moSens").val($(res).find('Motion').eq(0).find('Senstive').eq(0).text());
            if ("true" == $(res).find('Motion').eq(0).find('Mail').eq(0).find('Enable').eq(0).text()) {
                $("#moEmail").prop('checked', true);
            } else {
                $("#moEmail").prop('checked', false);
            }
            if ("true" == $(res).find('Motion').eq(0).find('Snapshot').eq(0).find('Enable').eq(0).text()) {
                $("#moCap").prop('checked', true);
            } else {
                $("#moCap").prop('checked', false);
            }

            if ("true" == $(res).find('Motion').eq(0).find('Ftp').eq(0).find('Enable').eq(0).text()) {
                $("#moftp").prop('checked', true);
            } else {
                $("#moftp").prop('checked', false);
            }

            if ("true" == $(res).find('Motion').eq(0).find('PTZ').eq(0).find('Enable').eq(0).text()) {
                $("#moPtz").prop('checked', true);
            } else {
                $("#moPtz").prop('checked', false);
            }
            if ("true" == $(res).find('Motion').eq(0).find('Schedule').eq(0).find('AllDay').eq(0).text()) {
                $("#scAllDay").prop('checked', true);
            } else {
                $("#scAllDay").prop('checked', false);
            }

            var windows = {};
            var obj = varsToObjMotion(res);

            var keys = Object.keys(obj);

            var dict = {
                show: "enable",
                x: "left",
                y: "top",
                w: "width",
                h: "height"
            }

            var regx = /^([^\d]+)_(\d)$/;
            var numeric = /^[\+\-]?\d+(?:\.\d+)?$/;
            var i, k, n, prop, match;
            for (i = 0; i < keys.length; i++) {
                k = keys[i];
                match = regx.exec(k);
                n = parseInt(match[2], 10);
                prop = match[1];

                windows["window" + n] = windows["window" + n] || {};
                windows["window" + n][dict[prop]] =
                    (numeric.test(obj[k])) ? Number(obj[k]) : obj[k];

                windows["window" + n].region = n;
                windows["window" + n].enable = !!windows["window" + n].enable;


            }

            cb(windows);
        });
    };

    function changeMotion() {
        if ($("#moEnable").val() == "true") {
            $("tr#moID").show();
        } else {
            $("tr#moID").hide();
        }
    }

    function varsToObj(vars, ch) {
        ch = ch || 1;
        var obj = {};
        $.ajax({
            method: "GET",
            async: false,
            url: setURL(ch),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            }
        }).done(function(res) {
            var tr = $(res).find("Mosaic").eq(0).find("MosaicRegionList").eq(0).find("Region");
            var k = tr.length;
            for (var i = 0; i < k; i++) { //
                var j = i + 1;
                obj["show_" + j] = JSON.parse(1);
                obj["x_" + j] = JSON.parse(tr.eq(i).find("TopLeftX").eq(0).text());
                obj["y_" + j] = JSON.parse(tr.eq(i).find("TopLeftY").eq(0).text());
                obj["w_" + j] = JSON.parse(parseInt(tr.eq(i).find("BottomRightX").eq(0).text()) - parseInt(tr.eq(i).find("TopLeftX").eq(0).text()));
                obj["h_" + j] = JSON.parse(parseInt(tr.eq(i).find("BottomRightY").eq(0).text()) - parseInt(tr.eq(i).find("TopLeftY").eq(0).text()));
            }
            for (var i = k + 1; i < 5; i++) {
                obj["show_" + i] = JSON.parse(0);
                obj["x_" + i] = JSON.parse(0);
                obj["y_" + i] = JSON.parse(0);
                obj["w_" + i] = JSON.parse(196);
                obj["h_" + i] = JSON.parse(196);
            }
        });
        console.log(obj,'obj');
        return obj;
    }

    function varsToObjMotion(vars) {
        var obj = {};
        $.ajax({
            method: "GET",
            async: false,
            url: motionurl,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            }
        }).done(function(res) {
            var tr = $(res).find('Motion').eq(0).find('MotionRegionList').eq(0).find('Region');
            var k = tr.length;
            for (var i = 0; i < k; i++) { //
                var j = i + 1;
                obj["show_" + j] = JSON.parse(1);
                obj["x_" + j] = JSON.parse(tr.eq(i).find("TopLeftX").eq(0).text());
                obj["y_" + j] = JSON.parse(tr.eq(i).find("TopLeftY").eq(0).text());
                obj["w_" + j] = JSON.parse(parseInt(tr.eq(i).find("BottomRightX").eq(0).text()) - parseInt(tr.eq(i).find("TopLeftX").eq(0).text()));
                obj["h_" + j] = JSON.parse(parseInt(tr.eq(i).find("BottomRightY").eq(0).text()) - parseInt(tr.eq(i).find("TopLeftY").eq(0).text()));
            }
            for (var i = k + 1; i < 5; i++) {
                obj["show_" + i] = JSON.parse(0);
                obj["x_" + i] = JSON.parse(0);
                obj["y_" + i] = JSON.parse(0);
                obj["w_" + i] = JSON.parse(196);
                obj["h_" + i] = JSON.parse(196);
            }
        });
        return obj;
    }

}(window, jQuery));