﻿$(function () {

    if (typeof (SVG) == 'undefined') { SVG = {}; }
    if (typeof (SVG.FlyerBoard) == 'undefined') { SVG.FlyerBoard = {}; }

    SVG.FlyerBoard.init = function (canvasDiv, options) {

        if (options.Canvas) { $.extend(SVG.FlyerBoard.Canvas, options.Canvas); }
        if (options.Images) { $.extend(SVG.FlyerBoard.Images, options.Images); }

        SVG.AjaxLoading.PreventDefault = true;
        this.BuildFlyerBoard(canvasDiv);
        this.GetAllFlyers();

    };

    SVG.FlyerBoard.BuildFlyerBoard = function (outterDiv) {
        SVG.FlyerBoard.Canvas.Build(outterDiv);
        $(document).bind('cbox_open', function () { $(document).unbind("mousemove"); });
    };

    SVG.FlyerBoard.GetAllFlyers = function () {
        var URL = SVG.URLS.GetAllFlyerBoardImages;
        this.GetImages(URL);
    };

    SVG.FlyerBoard.GetThisWeekFlyers = function () {
        var URL = SVG.URLS.GetThisWeekFlyerBoardImages;
        this.GetImages(URL);
    };

    SVG.FlyerBoard.GetNextWeekFlyers = function () {
        var URL = SVG.URLS.GetNextWeekFlyerBoardImages;
        this.GetImages(URL);
    };

    SVG.FlyerBoard.GetImages = function (URL) {

        SVG.FlyerBoard.Canvas.Block("Loading...", true);

        $.getJSON(URL, function (images) {
            SVG.FlyerBoard.Images.Clear();
            SVG.FlyerBoard.AddImages(images);
            SVG.FlyerBoard.Canvas.SetHeaderText("<h4><b>Events (" + images.length + ")</b></h4>");
        });
    };

    SVG.FlyerBoard.AddImages = function (images) {
        var imageCount = images.length;
        for (var i = 0; i < imageCount; i++) {
            var image = images[i];
            SVG.FlyerBoard.Images.Add(image);
        }

        var checkLoaded = setInterval(checkImagesLoaded, 200);

        function checkImagesLoaded() {
            var timer = 0;
            if (SVG.FlyerBoard.Images.ImagesLoaded >= imageCount) {
                clearInterval(checkLoaded);
                SVG.FlyerBoard.Canvas.Unblock();
                clearTimeout(timer);
            } else {
                //@note: removes loading screen if all else fails
                timer = setTimeout(function () {
                    clearInterval(checkLoaded);
                    SVG.FlyerBoard.Canvas.Unblock();
                    clearTimeout(timer);
                }, 20000);
            }
        }

    };

});
