// jQuery.noConflict();

(function($, w, d, h, b) {
    "use strict"; 
    var globach = 1;
    var saveTimes = 0,copyFlag=false;
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width:220
        });
    }
    if (config.isSupportMultiChannel) {
        $(".isShowMultiChannel").show();
        // 初始化通道数
        $("#channel").empty(); //Channel
        if(config.deviceInfo.VideoInputChannels > 1 && config.deviceInfo.VideoInputChannels <= 2){
            $("#channel").append('<option class="option" value="1">' + $.i18n.prop("i18n-tracking") + '</option>');
            $("#channel").append('<option class="option" value="2">' + $.i18n.prop("i18n-panoramic") + '</option>');
            $("#coppyInds").append('<option class="option" value="1">' + $.i18n.prop("i18n-tracking") + '</option>');
            $("#coppyInds").append('<option class="option" value="2">' + $.i18n.prop("i18n-panoramic") + '</option>');
        } else {
            for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                $("#channel").append('<option class="option" value="' + i + '">' + i + '</option>');
                if (i != 1) {
                    $("#coppyInds").append('<option class="option" value="' + i + '">' + i + '</option>');
                }
            }
            
        }
        $("#channel").val("1").trigger('change.select2');
        $("#channel").change(function() {
            var chid = $(this).val() * 1;
            globach = chid;
            $("#coppyInds").empty();
            $("#coppyInds").append('<option class="option" value="00">' + $.i18n.prop("i18n-video-all") + '</option>');
    
            if(config.deviceInfo.VideoInputChannels > 1 && config.deviceInfo.VideoInputChannels <= 2){
                $("#coppyInds").append('<option class="option" value="1">' + $.i18n.prop("i18n-tracking") + '</option>');
                $("#coppyInds").append('<option class="option" value="2">' + $.i18n.prop("i18n-panoramic") + '</option>');
            } else {
                for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                    if (i != chid) {
                        $("#coppyInds").append('<option class="option" value="' + i + '">' + i + '</option>');
                    }
                }
            }

            var ipcsrc = w.cam_addr + "Snapshot/"+globach+"/RemoteImageCapture?ImageFormat=2?";
            motionjpeg("#motionjpeg", ipcsrc);
            getcover(function(vars) {
                var keys = Object.keys(vars);

                for (var i = 0; i < keys.length; i++) {
                    var k = keys[i],
                        v = vars[k],
                        j = i + 1;
                    var win = $("#" + k);
                    var check = $("#check" + j)[0];

                    check.checked = v.enable;

                    win.css({
                        top: parseInt(v.top * video_div, 10),
                        left: parseInt(v.left * video_div, 10),
                        width: parseInt(v.width * video_div, 10),
                        height: parseInt(v.height * video_div, 10),
                        display: (v.enable) ? "block" : "none"
                    });

                }
            },chid);
        });
        // 复制到
        $("#copyTo").click(function () {
            copyFlag = true;
            if ($("#coppyInds").val() == "00") {
                for (var i = 1; i <= config.deviceInfo.VideoInputChannels; i++) {
                    if ("admin" == config.user || "super_admin" == config.user) {
                        submit(i);
                    } else {
                        $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
                    }
                }
            } else {
                if ("admin" == config.user || "super_admin" == config.user) {
                    submit($("#channel").val() - 0);
                    submit($("#coppyInds").val() - 0);
                } else {
                    $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
                }
            }
        })
    } else {
        $(".isShowMultiChannel").hide();
    }
    getresolution(function(resolution) {
        if (!(resolution && typeof resolution.width === "number" &&
                typeof resolution.height === "number")) {
            alert("!RESOLUTION ERROR!");
            return;
        }
        
        w.video_heigth = 491;
        w.video_width = parseInt(491 * (resolution.width / resolution.height));
        w.video_div = video_heigth / resolution.height;
        w.video_mult = resolution.height / video_heigth;
        var bl = getRatio();
        var ppi = window.innerWidth;
        if (ppi < 1920) {
            if (bl > 100) {
                video_width = (video_width * 100 / bl)*0.75 ;
                video_heigth = (video_heigth * 100 / bl) * 0.75;
                $("#mjpie").width(video_width);
            } 
        }
        
        $(function() { // $(document).ready(f)
            $("#display").prepend(
                    $(
                        '<img alt="ipCamera" id="motionjpeg" src="' +
                        w.cam_addr + 'Snapshot/1/RemoteImageCapture?ImageFormat=2?" />'
                    ).css({
                        width: video_width,
                        height: video_heigth
                    })
                )
                .css({
                    width: video_width,
                    height: video_heigth
                });
                $("#controls,.btn-centers").css({
                    width: video_width,
                });
            insertControls();
            motionjpeg("#motionjpeg"); //@TODO: decomment
            insertDrags();
            getcover(function(vars) {
                var keys = Object.keys(vars);

                for (var i = 0; i < keys.length; i++) {
                    var k = keys[i],
                        v = vars[k],
                        j = i + 1;
                    var win = $("#" + k);
                    var check = $("#check" + j)[0];

                    check.checked = v.enable;

                    win.css({
                        top: parseInt(v.top * video_div, 10),
                        left: parseInt(v.left * video_div, 10),
                        width: parseInt(v.width * video_div, 10),
                        height: parseInt(v.height * video_div, 10),
                        display: (v.enable) ? "block" : "none"
                    });

                }
            });
        });
    });

    function insertDrags() {
        var display = $("#display"),
            maxleft = 280;

        for (var i = 4; i > 0; i--) {
            $('<div id="window' + i + '" class="window" style="display:none">' +
                    i + '.</div>'
                ).css("left", (maxleft -= 70) + "px").css("z-index", i)
                .prependTo(display);
        }

        $(".window").resizable({
            containment: "#display"
        }).draggable({
            containment: "#display"
        });
    }

    function submit(ch) {
        ch = ch || 1;
        var w, i, check, cyXml, win, pos;
        cyXml = "<?xml version='1.0' encoding='UTF-8' ?><Mosaic Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><Enable>" + $("#pzenable").is(":checked") + "</Enable><MosaicRegionList Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
        for (i = 1; i < 5; i++) {
            win = $("#window" + i);
            pos = win.position();
            check = $("#check" + i);
            if (!check.length) continue;
            check = check[0];
            if (check.checked == 1) {
                cyXml += "<Region Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>";
                cyXml += "<ID>" + i + "</ID>";
                cyXml += "<TopLeftX>" + parseInt(pos.left * video_mult, 10) + "</TopLeftX>";
                cyXml += "<TopLeftY>" + parseInt(pos.top * video_mult, 10) + "</TopLeftY>";
                cyXml += "<BottomRightX>" + parseInt((win.width() + pos.left) * video_mult, 10) + "</BottomRightX>";
                cyXml += "<BottomRightY>" + parseInt((win.height() + pos.top) * video_mult, 10) + "</BottomRightY>";
                cyXml += "</Region>";
            }
        }
        cyXml += "</MosaicRegionList></Mosaic>";
        $.ajax({
            type: "PUT",
            url: setURL(ch),
            async: true,
            processData: true,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                if (copyFlag) {
                  //保证复制时候保存成功只显示一次
                  saveTimes++;
                  if (saveTimes == config.deviceInfo.VideoInputChannels) {
                    SaveState(xhr);
                    saveTimes = 0;
                  }
                } else {
                  SaveState(xhr);
                }
            }
        });
    }

    function insertControls() {
        var controls = $("#controls");

        for (var i = 1; i < 5; i++) {
            $('<div id="control' + i + '" class="control"><input id="check' +
                i + '" type="checkbox" class="check" style="margin:0"/>' +
                ' <span class="text-span"> '+ $.i18n.prop('i18n-region') + i + '</span> enabled'
            ).appendTo(controls);
        }
        $("#save").button();

        $("#controls .check").each(function(i) {
            i++; // Convert to 1-N index

            $(this).click(function() {
                $("#window" + i).toggle();
            });
        });

        $("#pzsave").click(function () {
            copyFlag = false;
            if ("admin" == window.config.user || "super_admin" == window.config.user) {
                submit($("#channel").val());
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
            }
        });
    }
}(jQuery, window, document, window.location.href, document.body));