var imagesLoaded = 0;
var preloadDelay = 200;
var intervalID = 0;
var lensSize = 300;
var deepZoom = true;
var showLens = false;
var imgBoard = new Image();
var imgBoardBig = new Image();

imgBoard.onload = increaseImageMeter;
imgBoard.src = "images/board_big_37.jpg";

imgBoardBig.onload = increaseImageMeter;
imgBoardBig.src = "images/board_big_100.jpg";

function increaseImageMeter() {
    imagesLoaded++
}

$(document).ready(function () {


    var resizeTime = 100;     // total duration of the resize effect, 0 is instant
    var resizeDelay = 100;    // time to wait before checking the window size again
    // the shorter the time, the more reactive it will be.
    // short or 0 times could cause problems with old browsers.

    function createTooltips(wrapper) {
        var myAreas = [];
        var myOptions = $('#imgBoard').mapster('get_options');
        $("#divBoardWrapper area").each(function () {
            var $area = $(this);
            var id = $area.prop('alt');
            var $divID = $("#" + id, wrapper);
            var $h4 = $divID.children("h4:first");
            var area = {
                key: id,
                toolTip: $h4.text()
            };
            myAreas.push(area);
            $area.prop('title ', $h4.text());
        });
        myOptions.areas = myAreas;
        $('#imgBoard').mapster('set_options', myOptions);
    }

    // Resize the map to fit within the boundaries provided
    function imgRealSize(img) {
        var $img = $(img);
        if ($img.prop('naturalWidth') == undefined) {
            var $tmpImg = $('<img/>').attr('src', $img.attr('src'));
            $img.prop('naturalWidth', $tmpImg[0].width);
            $img.prop('naturalHeight', $tmpImg[0].height);
        }
        return { 'width': $img.prop('naturalWidth'), 'height': $img.prop('naturalHeight') }
    }

    function resize(maxWidth, maxHeight) {
        var image = $('#imgBoard'),
            imgWidth = image.width(),
            imgHeight = image.height(),
            newWidth = 0,
            newHeight = 0;

        if (imgWidth / maxWidth > imgHeight / maxHeight) {
            newWidth = maxWidth;
        } else {
            newHeight = maxHeight;
        }

        var imgSize = imgRealSize(image);
        if (maxWidth > imgSize.width)
            maxWidth = imgSize.width;

        newWidth = maxWidth;
        image.mapster('resize', newWidth, 0, resizeTime);

        //var ez = $('#imgBoard').data('elevateZoom');	
        ////ez.changeZoomLevel(ez.currentZoomLevel);
        //var options = ez.options;
        //var elem = ez.elem;
        //$(".zoomContainer").remove();
        //$(elem).elevateZoom(options);

        //var clickEvent = jQuery.Event("mousewheel", { pageX: 0, pageY: 0 });
        //$(".zoomContainer").trigger(clickEvent);


        //newHeight = maxHeight;
        //image.mapster('resize', 0, newHeight, resizeTime);
    }

    // Track window resizing events, but only actually call the map resize when the
    // window isn't being resized any more

    function onWindowResize() {

        var curWidth = $('#divBoardWrapper').innerWidth(),
            curHeight = $(window).height(),
            checking = false;
        if (checking) {
            return;
        }
        checking = true;
        window.setTimeout(function () {
            var newWidth = $('#divBoardWrapper').innerWidth(),
                newHeight = $(window).height();
            if (newWidth === curWidth &&
                newHeight === curHeight) {
                resize(newWidth, newHeight);
            }
            checking = false;
        }, resizeDelay);
    }

    $.fn.createImageZoom = function ($imgZoom, deepZoom) {
        if (deepZoom == null)
            deepZoom = false;
        $imgZoom.elevateZoom(
            {
                zoomType: "lens",
                lensShape: "round",
                lensSize: 300,
                containLensZoom: true,
                responsive: true,
                scrollZoom: deepZoom,
                zoomLevel: 1,
                maxZoomLevel: 2, 
                minZoomLevel: 1,
            }
        );
    }

    $.fn.createImageEvent = function ($imgZoom) {
        $imgZoom.off();//remove all events
        $imgZoom.click(function (e) {
            console.log(this.id + " -> " + e.pageX + "," + e.pageY);
            var x = e.pageX - $(this).offset().left;
            var y = e.pageY - $(this).offset().top;
            console.log("offset -> " + x + "," + y);
            $("#divBoardWrapper area").each(function () {
                var $area = $(this);
                if (this.shape == "rect") {
                    if (containsPoint(x, y, this.coords)) {
                        //var key = $(this).data("key");
                        var key = $area.prop('alt');
                        var content = $("#" + key).html();
                        showPopup(content);
                        console.log(key);
                        return false;
                    }
                } else {
                    if (this.shape == "circle") {
                        if (containsPointCircle(x, y, this.coords)) {
                            //var key = $(this).data("key");
                            var key = $area.prop('alt');
                            var content = $("#" + key).html();
                            showPopup(content);
                            console.log(key);
                            return false;
                        }
                    }
                }
            });
            //return false;
        });
    }

    function showPopup(message) {
        var magnificPopup = $.magnificPopup.instance;

        $('.open-popup-link').magnificPopup('open');
        magnificPopup.items = [{
            src: '<div class="white-popup">' + message + '</div>', // can be a HTML string, jQuery object, or CSS selector
            type: 'inline'
        }];
        magnificPopup.updateItemHTML(); // updates the popup content. Useful after you change "items" array    
    }

    function containsPoint(pointX, pointY, coords) {
        var arrCoords = coords.split(",");
        var x1 = parseInt(arrCoords[0]);
        var y1 = parseInt(arrCoords[1]);
        var x2 = parseInt(arrCoords[2]);
        var y2 = parseInt(arrCoords[3]);

        return x1 <= pointX && pointX <= x2 && y1 <= pointY && pointY <= y2;
    }

    function containsPointCircle(x, y, coords) {
        var arrCoords = coords.split(",");
        var cx = parseInt(arrCoords[0]);
        var cy = parseInt(arrCoords[1]);
        var r = parseInt(arrCoords[2]);
        var dx = Math.abs(x - cx);
        if (dx > r) return false;
        var dy = Math.abs(y - cy);
        if (dy > r) return false;
        if (dx + dy <= r) return true;
        return (dx * dx + dy * dy <= r * r);
    }

    function setHighlightBoard(state) {
        if (state)
            $('area').mapster('select');
        else
            $('area').mapster('deselect');
    }

    function changeLensSize(newSize) {
        var ez = $('#imgBoard').data('elevateZoom');
        if (ez == null)
            return;
        var options = ez.options;
        ez.options.lensSize = newSize;
        options.lensSize = newSize;
        $(".zoomLens").css("border-top-left-radius", String(options.lensSize / 2 + options.borderSize) + "px");
        $(".zoomLens").css("border-top-right-radius", String(options.lensSize / 2 + options.borderSize) + "px");
        $(".zoomLens").css("border-bottom-left-radius", String(options.lensSize / 2 + options.borderSize) + "px");
        $(".zoomLens").css("border-bottom-right-radius", String(options.lensSize / 2 + options.borderSize) + "px");
        $(".zoomLens").css({ width: String(options.lensSize) + 'px', height: String(options.lensSize) + 'px' });
    }

    function createLeftPanelContent() {
        $('#cbHiglightBoard').iCheck({
            checkboxClass: 'icheckbox_square-grey',
            radioClass: 'iradio_square-grey',
            increaseArea: '20%' // optional
        })
        .on('ifChanged', function (event) {
            //alert(this.checked);
            setHighlightBoard(this.checked);

        });
        $('#cbShowLens').iCheck({
            checkboxClass: 'icheckbox_square-grey',
            radioClass: 'iradio_square-grey',
            increaseArea: '20%' // optional
        })
        .on('ifChanged', function (event) {
            //alert(this.checked);
            showLens = this.checked;
            if (this.checked) {
                $.fn.createImageZoom($("#imgBoard"), deepZoom);
                $.fn.createImageEvent($("#imgBoard"));
            }
            else {
                $(".zoomContainer").remove();

            }
            $('#divSliderWrapper').toggleClass("hidden");
        });

        $('#sliderZoom').rangeslider({
            polyfill: false,
            // Callback function
            onSlide: function (position, value) {
                lensSize = value;
                changeLensSize(value);
            },
        });


        // Bypass Chrome bug for calculating dimensions
        // of non DOM visible objects
        //window.setTimeout(function () {
        //    var range = $('#sliderZoom').data("plugin_rangeslider");
        //    range.value = lensSize;
        //    range.update(false, false);
        //    //$('#sliderZoom').rangeslider({
        //    //    polyfill: false,
        //    //    // Callback function
        //    //    onSlide: function (position, value) {
        //    //        lensSize = value;
        //    //        changeLensSize(value);
        //    //    },
        //    //});
        //}, 300);


        $('#cdDeepZoom').iCheck({
            checkboxClass: 'icheckbox_square-grey',
            radioClass: 'iradio_square-grey',
            increaseArea: '20%' // optional
        })
        .on('ifChanged', function (event) {
            $(".zoomContainer").remove();
            $("#imgBoard").off();
            deepZoom = this.checked
            $.fn.createImageZoom($("#imgBoard"), deepZoom);
            $.fn.createImageEvent($("#imgBoard"));
            changeLensSize(lensSize);
        });

        $("#btnClose").click(function () {
            var extruder = $("#leftPanel").data("mbExtruder");
            extruder.closeMbExtruder();
            extruder.removeAttr("isOpened");
        });


        $("#btnInfo").click(function () {
            var extruder = $("#leftPanel").data("mbExtruder");
            extruder.closeMbExtruder();
            extruder.removeAttr("isOpened");
            window.open("info/index_DS_II.html", "_blank");
        });

    }

    function createJQplugins() {
        $(window).bind('resize', onWindowResize);

        $('#imgBoard').mapster({
            mapKey: 'alt',
            fadeInterval: 50,
            fillColor: '4da6ff',
            fillOpacity: 0.4,
            stroke: true,
            strokeWidth: 2,
            strokeColor: '0066cc',
            strokeOpacity: 0.8,
            showToolTip: true,
            toolTipContainer: "<div class='tooltip-popup'></div>",
            //singleSelect: true,
        });

        $('.open-popup-link').magnificPopup({
            type: 'inline',
            // Delay in milliseconds before popup is removed
            removalDelay: 300,
            // Class that is added to popup wrapper and background
            // make it unique to apply your CSS animations just to this exact popup
            mainClass: 'mfp-fade',
            midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href.
        });

        $("area").off("click");
        $("area").click(function (e) {
            var $area = $(this);
            var key = $area.prop('alt');
            var content = $("#" + key).html();
            showPopup(content);
            console.log(key);
            return false;
        });


        $("#leftPanel").buildMbExtruder({
            top:0,
            position: "left",
            width: 300,
            extruderOpacity: 1,
            hidePanelsOnClose: true,
            accordionPanels: false,
            onExtOpen: function () {
                var range = $('#sliderZoom').data("plugin_rangeslider");
                range.value = lensSize;
                range.update(false, false);
            },
            onExtContentLoad: function () {
                createLeftPanelContent();
            },
            onExtClose: function () {

            }
        });

        createTooltips($("#popupWrapper"));
    }

    intervalID = window.setInterval(function () {
        console.log("Images loaded -> " + imagesLoaded);
        if (imagesLoaded >= 2) {
            window.clearInterval(intervalID);
            $("#divLoading").hide();
            //$("#imgBoard").prop('src', 'images/board_big_100.jpg');
            $("#imgBoard").show();
            $("#leftPanel").show();
            window.setTimeout(function () {
                createJQplugins();
            }, preloadDelay);
        }
    }, preloadDelay);





});
