﻿// gallery plugin for  Similac 2011.03.08
$.fn.disableSelection = function() {
    $(this).attr('unselectable', 'on')
           .css('-moz-user-select', 'none')
           .each(function() { 
               this.onselectstart = function() { return false; };
            });
};

(function ($) {

    $.fn.extend({
        similac_gallery: function (options) {
        
        var defaults = {
            tag:"gallery"
        };
        $.extend(defaults, options);

        var obj = null;
        var name = null;
        var lock = 0;
        var rulerCanvas = null;
        var galleryCanvas = null;
        var period = Math.ceil(options.rulerViewPortSize / 2) - 1;
        var periodGallery = Math.ceil(options.galleryViewPortSize / 2) - 1;
        var currentItemId = period + 1;
        var size = options.data.length;
        var selectedItemPlate=null;
       
        var rtl = $("body").css("direction") === "rtl";
        var align = rtl ? "right" : "left";

        /* ===================
        Here it starts 
        =================== */

        return this.each(function () {
            var o = options;

            obj = $(this);
            obj.disableSelection();
            name = options.tag;
            obj.addClass("gallery");

            obj.append(build());

            buildRuler();

            obj.find(".pager-viewport").append(rulerCanvas);
            rulerCanvas.parent().width(options.rulerItemWidth * options.rulerViewPortSize);

            setCurrentRulerItem();
            setMiddleRullerLegend();

            buildGallery();
            obj.find(".viewport").append(galleryCanvas);
            galleryCanvas.parent().width(options.galleryItemWidth * options.galleryViewPortSize);

            syncGallery();

        });

        function setMiddleRullerLegend(){
            var item = currentItem();

            var top = item.position().top;
            
            selectedItemPlate.css("top", top - 13);
            selectedItemPlate.css(align,  rtl? getRight(item) + options.selectedItemPlateOffset: getLeft(item) + options.selectedItemPlateOffset);
            selectedItemPlate.find("ins").html(item.find("ins").html());

        }

        // Init 
        // ****
        function syncGallery() {
            var item = currentGalleryItem();
            galleryCanvas.find(".current").removeClass("current");
            item.addClass("current");

            var l =  parseInt(galleryCanvas.css(align));
            var offset = -item.index() + periodGallery;
            galleryCanvas.css(align, l + offset * options.galleryItemWidth);
            
            galleryCanvas.find(".current img").css({
                width: options.imgeSizeZoomedIn, height:options.imgeSizeZoomedIn
            });

            var t = item.find("a").clone().html(selectedItemPlate.find("ins").text());  
            selectedItemPlate.find("ins").html("").append(t);
        }

        // BULDING
        // *******

        function buildGallery() {
            galleryCanvas = $("<ul/>");

            for (var i = 1; i <= size; i++) {
                var data = options.data[i - 1];
                var item = $("<li/>").append($("<a/>")).width(options.galleryItemWidth);
                item.attr("id", name + "_" + i);
                item.find("a").append($("<img/>")).attr("href", data.Link);
                
                var img =  item.find("img");
                img.attr("src", options.imageDir.replace("{0}", options.data[i - 1].Image));
                img.attr("alt", data.Title);
                img.attr("title", data.Title);

                item.appendTo(galleryCanvas);
                
                item.click(function () { galleryItemClicked($(this)); });
            }
        }

        function buildRuler() {
            rulerCanvas = $("<ul/>");
            for (var i = 1; i <= size; i++) {
                var item = $("<li/>").width(options.rulerItemWidth);
                item.append($("<ins/>"));
                item.find("ins").html(i);
                item.attr("id", name + i);
                item.appendTo(rulerCanvas);
                
                item.click(function () { rulerItemClicked($(this)); });
            }
        }

        function build() {
            var layout = $("#gallery-layout").clone(); 

            var backBtn = layout.find(".back");
            var nextBtn =  layout.find(".next");
            nextBtn.click(next);
            backBtn.click(back);

            selectedItemPlate = layout.find(".selected-item-plate");

            return layout.children();
        }

        // NAVIGATION
        // **********

        function next() {
            if (lock) return;
            currentItemId--;

            fixCurrentItemId();
            setCurrentRulerItem();

            slide(1);
        }

        function back() {
            if (lock) return;
            currentItemId++;

            fixCurrentItemId();
            setCurrentRulerItem();

            slide(-1);
        }

        function rulerItemClicked(item) {
            if (lock) return;

            var id = parseInt(item.attr("id").replace(name, ""));
            if (id === currentItemId) return;

            var steps = currentItem().index() - item.index();

            currentItemId = id;
            setCurrentRulerItem();

            slide(steps);
        }

        function galleryItemClicked() {
            obj.trigger("clicked", [options.data[currentItemId]]);
        }

        // SLIDE 
        function slide(steps) {
            if (lock) return;
            lock = 1;

            var cloned = [];
            var l = 0;
            var dir = steps > 0 ? 1 : -1;
            var start = (parseInt(currentItemId) + steps) + -dir * period;
            steps = Math.abs(steps);

            var toClone = [];
            for (var i = 1; i <= steps; i++) {
                var idx = dir === 1 ? isToBeClonedForword(start - i) : isToBeClonedBack(start + i);
                if (idx != null) {
                    toClone.push(idx);
                }
            }

            for (var idx in toClone) {
                var item = itemById(toClone[idx]);

                cloned.push(item);

                if (dir === 1) {
                    rulerCanvas.prepend(item.clone(true));
                    var l = rtl? getRight(rulerCanvas): getLeft(rulerCanvas);
                    rulerCanvas.css(rtl > 0? "right": "left", l - options.rulerItemWidth);
                } else {
                    rulerCanvas.append(item.clone(true));
                }
            }

            l = rtl? getRight(rulerCanvas): getLeft(rulerCanvas);
            var offest = parseInt( l + dir * steps * options.rulerItemWidth);
            rulerCanvas.animate({
                right: rtl? offest: 0,
                left: rtl? 0:offest
            }, 1000, function () {
                clearCloned($(cloned), dir === -1);
                
                var item = currentItem();

                var n = item.find("ins").html();
                var gItem = galleryCanvas.find("li[id=" + name + "_" + n +"]");
                var t = gItem.find("a").clone().html(n);  

                selectedItemPlate.find("ins").html("").append(t);

                lock = 0;
                setGalleryItem();
            });
        }

        // Routines
        function isToBeClonedForword(item) {
            if (item < 1) {
                item = size + item;
            }

            var o = itemById(item);

            if (o.index() < currentItem().index()) {
                item = null;
            }

            return item;
        }

        function isToBeClonedBack(item) {
            if (item > size) {
                item = item - size;
            }
            var o = itemById(item);

            if (o.index() > currentItem().index()) {
                item = null;
            }

            return item;
        }

        function fixCurrentItemId() {
            if (currentItemId > size) {
                currentItemId = 1;
            }

            if (currentItemId < 1) {
                currentItemId = size;
            }
        }

        function setCurrentRulerItem() {
            rulerCanvas.find(".current").removeClass("current");
            currentItem().addClass("current");
            
            rulerCanvas.find(".last").removeClass("last");
            $(rulerCanvas.children()[currentItem().index() + period]).addClass("last");

       }

        function clearCloned(cloned, fix) {
            cloned.each(function () {
                $(this).remove();
                if (fix) {
                    var l = rtl? getRight(rulerCanvas): getLeft(rulerCanvas);
                    rulerCanvas.css(rtl? "right": "left", l + options.rulerItemWidth);
                }
            });
        }

        function currentItem() {
            return rulerCanvas.find("#" + name + currentItemId);
        }

        function itemById(id) {
            return rulerCanvas.find("#" + name + id);
        }

        // Gallery

        function setGalleryItem() {
            var item = currentGalleryItem();
            var current = galleryCanvas.find(".current");
            
            var w = item.find("img").width();
            var h = item.find("img").height();
           
            current.removeClass("current");
            current.find("img").css({
                width :w,
                height:h
            });

            item.addClass("current");

            var steps = current.index() - item.index();

            slideGallery(steps);
        }

        // Slide
        function slideGallery(steps) {
            var cloned = [];
            var l = 0;
            var dir = steps > 0 ? 1 : -1;
            var start = (parseInt(currentItemId) + steps) + -dir * period;
            steps = Math.abs(steps);

            var toClone = [];
            for (var i = 1; i <= steps; i++) {
                var idx = dir === 1 ? isToBeClonedForwordGallery(start - i) : isToBeClonedBackGallery(start + i);
                if (idx != null) {
                    toClone.push(idx);
                }
            }

            for (var idx in toClone) {
                var item = galleryItemById(toClone[idx]);

                cloned.push(item);

                if (dir === 1) {
                    galleryCanvas.prepend(item.clone(true));
                    var l = rtl? getRight(galleryCanvas): getLeft(galleryCanvas);
                    galleryCanvas.css(rtl > 0? "right": "left", l - options.galleryItemWidth);
                } else {
                    galleryCanvas.append(item.clone(true));
                }
            }

            var l = rtl? getRight(galleryCanvas): getLeft(galleryCanvas);
            var offest = parseInt(l + dir * steps * options.galleryItemWidth);

            galleryCanvas.animate({
                right: rtl? offest: 0,
                left: rtl? 0:offest
            }, 500, function () {
                if ($(cloned).length) {
                    clearGalleryCloned($(cloned), dir === -1);
                }
                galleryCanvas.find(".current img").animate(
                {
                    width: options.imgeSizeZoomedIn,
                    height: options.imgeSizeZoomedIn
                }, 200, function () {
                    obj.trigger("changed", [options.data[parseInt(currentItemId)]]);
                });
            });
        }

        function clearGalleryCloned(cloned, fix) {
            cloned.each(function () {
                $(this).remove();
                if (fix) {
                    var l = rtl? getRight(galleryCanvas): getLeft(galleryCanvas);
                    galleryCanvas.css(rtl > 0? "right": "left", l + options.galleryItemWidth);
                }
            });
        }

        function galleryItemById(id) {
            return galleryCanvas.find("#" + name + "_" + id);
        }
        function currentGalleryItem() {
            return galleryCanvas.find("#" + name + "_" + currentItemId);
        }

        function isToBeClonedForwordGallery(item) {
            if (item < 1) {
                item = size + item;
            }

            var o = galleryItemById(item);

            if (o.index() < currentGalleryItem().index()) {
                item = null;
            }

            return item;
        }

        function isToBeClonedBackGallery(item) {
            if (item > size) {
                item = item - size;
            }
            var o = galleryItemById(item);

            if (o.index() > currentGalleryItem().index()) {
                item = null;
            }

            return item;
        }
        function getRight(item){ 
            return item.parent().width() - getLeft(item) - item.width();
        }
        function getLeft(item){ 
            return item.position().left;
        }
    }
});

})(jQuery);

