/**
 * Ceylon Cold Stores Product Animation
 * Author:			Vipula Saman
 * Date:			11.19.2010
 * URL:				http://www.vipula.me
 * Version:			1.0
 *
 * jQuery powered animation module which will animate images in a carousel manner. with mouse click event
 * animation. System includes a preloading system which will first perload all the images before initial
 * display of them.
 */
(function($){
    $.fn.SlideControl = function(options){
    
        var defaults = {
            transitionSpeed: 5000,
            nextButtonId: "nextBtn",
            previousButtonId: "preBtn",
            nextButtonName: "Next",
            previousButtonName: "Previous",
            continuous: true,
            imageCount: 5, // This always has to be a odd number
            imgPositions: null,
            fullImgWidth: 140,
            fullImgHeight: 430,
            leftImgMargin: -100,
            rightImgMargin: 650,
            productType: "sd"
        };
        var options = $.extend(defaults, options);
        
        var obj = $(this);
        /**
         * Animation Control Object
         */
        function slideControl(){
            this.objInstance = null;
            var getInstance = function(){
                if (!this.objInstance) {
                    this.objInstance = createInstance();
                }
                return this.objInstance;
            }
            var createInstance = function(){
            
                // [top, left, height, width]
                var _imgPositions = options.imgPositions;
                var imgObjLength = $(".bottleContainer img", obj).length;
                var pObj = $(".bottleContainer", obj);
                var status = true;
                
                return {
                    // Prepare the HTML dom with custom attributes and ID's
                    processHTML: function(){
                        var _addIndex = function(){
                            $("img", pObj).each(function(e){
                                $(this).attr("index", e);
                                var name = $(this).attr("alt");
                                name = name.split(' ').join('');
                                name = name.toLowerCase();
                                $('#productDetailsWrapper div:eq(' + e + ')').attr("alt", name);
                            });
                        };
                        var _createDataSets = function(){
                        
                        };
                        var _addStyles = function(){
                            var s = 0;
                            $("img", pObj).each(function(e){
                                if (e >= 0 && e <= (options.imageCount - 1)) {
                                    $(this).css({
                                        top: '' + _imgPositions[s][0] + 'px',
                                        left: '' + _imgPositions[s][1] + 'px',
                                        height: '' + _imgPositions[s][2] + 'px',
                                        width: '' + _imgPositions[s][3] + 'px'
                                    });
                                    if (s == 0) {
                                        $(this).attr("f", 1);
                                    }
                                    else 
                                        if (s == (options.imageCount - 1)) {
                                            $(this).attr("l", 1);
                                        }
                                    s++;
                                }
                                else {
                                    $(this).hide();
                                }
                            });
                        };
                        return {
                            prepare: function(){
                                _addIndex();
                                _createDataSets();
                                _addStyles();
                            }
                        }
                    }(window),
                    // Start the Animation
                    animate: function(){
                        /**
                         * Add Navigation buttons
                         */
                        var _addButtons = function(){
                            var next = $('<span id="' + options.nextButtonId + '"><a href="javascript:void(0);">' + options.nextButtonName + '</a></span>');
                            var previous = $('<span id="' + options.previousButtonId + '"><a href="javascript:void(0);">' + options.previousButtonName + '</a></span>');
                            obj.append(previous).append(next);
                        };
                        /**
                         * Button Click Control for Forward and backward
                         */
                        var _btnClick = function(){
                            var ts = imgObjLength;
                            
                            $(document).ready(function(){
                                var start = setTimeout(function(){
                                    $('#' + options.nextButtonId).trigger("click");
                                }, 50);
                            });
                            
                            /**
                             * Next Button Click
                             */
                            $('#' + options.nextButtonId).click(function(){
                                animeRIGHT(0, null);
                            });
                            /**
                             * Previous Button Click
                             */
                            $('#' + options.previousButtonId).click(function(){
                                animeLEFT(0, null);
                            });
                            /**
                             *    Mouse click on bottle control
                             */
                           /* $("img", pObj).click(function(){
                                var activeImage = $(this);
                                $("img", pObj).each(function(){
                                    if (parseInt(activeImage.attr("index")) == parseInt($(this).attr("index"))) {
                                        $(this).attr("active", true);
                                    }
                                    else {
                                        $(this).removeAttr("active");
                                    }
                                })
                                var fIndex = parseInt($("img[f~=1]", pObj).attr("index"));
                                var lIndex = parseInt($("img[l~=1]", pObj).attr("index"));
                                var i = 0;
                                while (i < options.imageCount) {
                                    if ($('img[index~=' + (fIndex + i) + ']', pObj).attr("active") == "true") {
                                        if (options.imageCount % 2 == 1) {
                                            var cIndex = (parseInt(options.imageCount / 2) + 1) - 1;
                                            if (i < cIndex) {
                                                var count = (cIndex - i);
                                                animeLEFT(count, $(this));
                                            }
                                            else 
                                                if (i > cIndex) {
                                                    var count = ((cIndex - i) * -1);
                                                    animeRIGHT(count, $(this));
                                                }
                                                else 
                                                    if (i == cIndex) {
                                                        $(this).css("z-index", "9999").animate({
                                                            left: '' + (parseInt($(this).css("left")) - 10) + 'px',
                                                            height: '' + options.fullImgHeight + 'px',
                                                            width: '' + options.fullImgWidth + 'px',
                                                            top: '10px'
                                                        }, 300);
                                                        lightBox(true);
                                                        imageSwap($(this));
                                                    }
                                        }
                                    }
                                    i++;
                                }
                            }); */
                            /**
                             * Recursive function animate to right
                             * @param {Object} number of clicks
                             */
                            function animeRIGHT(count, tObj){
                                if (status) {
                                    forward();
                                    count--;
                                }
                                var rTime = setTimeout(function(){
                                    if (count <= 0) {
                                        clearTimeout(rTime);
                                        if (tObj) {
                                            tObj.css("z-index", "9999").animate({
                                                left: '' + (parseInt(tObj.css("left")) - 10) + 'px',
                                                height: '' + options.fullImgHeight + 'px',
                                                width: '' + options.fullImgWidth + 'px',
                                                top: '10px'
                                            }, 300, function(){
                                                $(this).css("z-index", "9999");
                                            });
                                            lightBox(true);
                                            imageSwap(tObj);
                                        }
                                    }
                                    else {
                                        animeRIGHT(count, tObj);
                                    }
                                }, options.transitionSpeed);
                            }
                            /**
                             * Recursive function animate to left
                             * @param {Object} number of clicks
                             */
                            function animeLEFT(count, tObj){
                                if (status) {
                                    backward();
                                    count--;
                                }
                                var lTime = setTimeout(function(){
                                    if (count <= 0) {
                                        clearTimeout(lTime);
                                        if (tObj) {
                                            tObj.css("z-index", "9999").animate({
                                                left: '' + (parseInt(tObj.css("left")) - 10) + 'px',
                                                height: '' + options.fullImgHeight + 'px',
                                                width: '' + options.fullImgWidth + 'px',
                                                top: '10px'
                                            }, 300, function(){
                                                $(this).css("z-index", "9999");
                                            });
                                            lightBox(true);
                                            imageSwap(tObj);
                                        }
                                    }
                                    else {
                                        animeLEFT(count, tObj);
                                    }
                                }, options.transitionSpeed);
                            }
                            
                            /**
                             * Move bottles forward animation function
                             */
                            var forward = function(){
                                status = false;
                                lightBox(status);
                                $("img", pObj).each(function(){
                                    if (parseInt($(this).attr("f")) != 1) {
                                        $(this).attr("index", (parseInt($("img:last", pObj).attr("index")) + 1));
                                        pObj.append($(this));
                                    }
                                    else {
                                        return false;
                                    }
                                });
                                var li = parseInt($("img[l~=1]", pObj).attr("index")) + 1;
                                var fi = (li - options.imageCount) + 1;
                                $("img[f~=1]", pObj).removeAttr("f");
                                $('img[index~=' + fi + ']').attr("f", 1);
                                var f = parseInt($("img[f~=1]", pObj).attr("index"));
                                $("img[l~=1]", pObj).removeAttr("l");
                                $('img[index~=' + li + ']').attr("l", 1);
                                var l = parseInt($("img[l~=1]", pObj).attr("index"));
                                $('img[index~=' + (f - 1) + ']', pObj).animate({
                                    left: '' + options.leftImgMargin + 'px',
                                    top: '0px'
                                }, options.transitionSpeed, "linear");
                                $('img[l~=1]', pObj).show().css({
                                    left: '' + options.rightImgMargin + 'px',
                                    height: '' + _imgPositions[(options.imageCount - 1)][2] + 'px',
                                    width: '' + _imgPositions[(options.imageCount - 1)][3] + 'px'
                                });
                                for (var i = 0; i < options.imageCount; i++) {
                                    if (i == 0) {
                                        $('img[index~=' + f + ']', pObj).animate({
                                            top: '' + _imgPositions[i][0] + 'px',
                                            left: '' + _imgPositions[i][1] + 'px',
                                            height: '' + _imgPositions[i][2] + 'px',
                                            width: '' + _imgPositions[i][3] + 'px'
                                        }, options.transitionSpeed, "linear", function(){
                                            status = true;
                                            getProductDetails($(this), "right");
                                        });
                                    }
                                    else {
                                        $('img[index~=' + f + ']', pObj).animate({
                                            top: '' + _imgPositions[i][0] + 'px',
                                            left: '' + _imgPositions[i][1] + 'px',
                                            height: '' + _imgPositions[i][2] + 'px',
                                            width: '' + _imgPositions[i][3] + 'px'
                                        }, options.transitionSpeed, "linear", function(){
                                            $(this).css("z-index", "0");
                                        });
                                    }
                                    f = f + 1;
                                }
                            };
                            
                            /**
                             * Move bottles backward animation function
                             */
                            var backward = function(){
                                status = false;
                                lightBox(status);
                                for (var i = 0; i <= (parseInt($("img:last", pObj).attr("index")) - parseInt($("img[l~=1]", pObj).attr("index"))); i++) {
                                    var fi = parseInt($("img:first", pObj).attr("index")) - 1;
                                    $("img:last", pObj).attr("index", fi).removeAttr("style").css({
                                        left: '' + options.leftImgMargin + 'px',
                                        height: '' + _imgPositions[0][2] + 'px',
                                        width: '' + _imgPositions[0][3] + 'px'
                                    });
                                    pObj.prepend($("img:last", pObj));
                                }
                                var li = parseInt($("img[l~=1]", pObj).attr("index")) - 1;
                                var fi = (li + 1) - options.imageCount;
                                $("img[f~=1]", pObj).removeAttr("f");
                                $('img[index~=' + fi + ']').attr("f", 1);
                                var f = parseInt($("img[f~=1]", pObj).attr("index"));
                                $("img[l~=1]", pObj).removeAttr("l");
                                $('img[index~=' + li + ']').attr("l", 1);
                                var l = parseInt($("img[l~=1]", pObj).attr("index"));
                                $('img[index~=' + (l + 1) + ']', pObj).animate({
                                    left: '' + options.rightImgMargin + 'px',
                                    top: '0px'
                                }, options.transitionSpeed, "linear");
                                for (var i = (options.imageCount - 1); i >= 0; i--) {
                                    if (i == 0) {
                                        $('img[index~=' + l + ']', pObj).animate({
                                            top: '' + _imgPositions[i][0] + 'px',
                                            left: '' + _imgPositions[i][1] + 'px',
                                            height: '' + _imgPositions[i][2] + 'px',
                                            width: '' + _imgPositions[i][3] + 'px'
                                        }, options.transitionSpeed, "linear", function(){
                                            status = true;
                                            getProductDetails($(this), "left");
                                        });
                                    }
                                    else {
                                        $('img[index~=' + l + ']', pObj).animate({
                                            top: '' + _imgPositions[i][0] + 'px',
                                            left: '' + _imgPositions[i][1] + 'px',
                                            height: '' + _imgPositions[i][2] + 'px',
                                            width: '' + _imgPositions[i][3] + 'px'
                                        }, options.transitionSpeed, "linear", function(){
                                            $(this).css("z-index", "0");
                                        });
                                    }
                                    l = l - 1;
                                }
                            };
                            
                            /**
                             * Get Product details
                             * @param {Object} obj
                             * @param {Object} direction
                             */
                            var getProductDetails = function(iobjn, direction){
                                $(".itemListInfo", obj).fadeIn("slow");
                                $("#bottleTitle", obj).fadeIn();
                                if (direction == "right") {
                                    var cIndex = parseInt(iobjn.attr("index")) + (parseInt(options.imageCount / 2));
                                    var imageName = $('img[index~=' + cIndex + ']', pObj).attr("alt");
                                    var imageNames = $('img[index~=' + cIndex + ']', pObj).attr("icount");
                                    imageNames = imageNames.split(",");
                                    var src = $('img[index~=' + cIndex + ']', pObj).attr("src");
                                    src = src.split(".");
                                    src = src[0].split("-");
                                    if (src.length > 1) 
                                        src.splice(src.length - 1, 1);
                                    src = src.toString().replace(/,/gi, "-");
                                    src = src.split("/");
                                    var imgName = src[(src.length - 1)];
                                    src.splice(src.length - 1, 1);
                                    src = src.toString().replace(/,/gi, "/");
                                    var newname = imageName;
                                    newname = newname.split(' ').join('');
                                    newname = newname.toLowerCase();
                                    var oldname = $('img[index~=' + (cIndex - 1) + ']', obj).attr("alt");
                                    oldname = oldname.split(' ').join('');
                                    oldname = oldname.toLowerCase();
                                    $('#productDetailsWrapper div[alt~=' + oldname + ']').fadeOut(100, function(){
                                        $('#productDetailsWrapper div[alt~=' + newname + ']', obj).fadeIn(100);
                                    });
                                    $("#bottleTitle", obj).html(imageName);
                                    $('img[index~=' + (cIndex - 1) + ']', pObj).css("z-index", "0");
                                    $('img[index~=' + cIndex + ']', pObj).css("z-index", "9999");
                                    $('img[index~=' + (cIndex + 1) + ']', pObj).css("z-index", "0");
                                    $(".bottleList", obj).empty();
                                    for (var i = 0; i < imageNames.length; i++) {
                                        if (imageNames[i] != "null") {
                                            var image = $('<img src="../images/' + src + '/thumb/' + imgName + '-' + imageNames[i] + '.jpg" alt="' + imageName + '" />');
                                            $(".bottleList", obj).append(image);
                                        }
                                        else {
                                            $(".bottleList", obj).html("No Products available.");
                                        }
                                    }
                                }
                                else 
                                    if (direction == "left") {
                                        var cIndex = parseInt(iobjn.attr("index")) + (parseInt(options.imageCount / 2));
                                        var imageName = $('img[index~=' + cIndex + ']', pObj).attr("alt");
                                        var imageNames = $('img[index~=' + cIndex + ']', pObj).attr("icount");
                                        imageNames = imageNames.split(",");
                                        var src = $('img[index~=' + cIndex + ']', pObj).attr("src");
                                        src = src.split(".");
                                        src = src[0].split("-");
                                        if (src.length > 1) 
                                            src.splice(src.length - 1, 1);
                                        src = src.toString().replace(/,/gi, "-");
                                        src = src.split("/");
                                        var imgName = src[(src.length - 1)];
                                        src.splice(src.length - 1, 1);
                                        src = src.toString().replace(/,/gi, "/");
                                        var newname = imageName;
                                        newname = newname.split(' ').join('');
                                        newname = newname.toLowerCase();
                                        var oldname = $('img[index~=' + (cIndex + 1) + ']', obj).attr("alt");
                                        oldname = oldname.split(' ').join('');
                                        oldname = oldname.toLowerCase();
                                        $('#productDetailsWrapper div[alt~=' + oldname + ']').fadeOut(100, function(){
                                            $('#productDetailsWrapper div[alt~=' + newname + ']', obj).fadeIn(100);
                                        });
                                        $("#bottleTitle", obj).html(imageName);
                                        $('img[index~=' + cIndex + ']', pObj).css("z-index", "9999");
                                        $(".bottleList", obj).empty();
                                        for (var i = 0; i < imageNames.length; i++) {
                                            if (imageNames[i] != "null") {
                                                var image = $('<img src="../images/' + src + '/thumb/' + imgName + '-' + imageNames[i] + '.jpg" alt="' + imageName + '" />');
                                                $(".bottleList", obj).append(image);
                                            }
                                            else {
                                                $(".bottleList", obj).html("No Products available.");
                                            }
                                        }
                                    }
                            };
                            
                            /**
                             * Create A div overlay to emulate the lightbox effect
                             */
                            var lightBox = function(b){
                                if (b) {
                                    $("#lightBox", obj).remove();
                                    var lBox = $('<div id="lightBox" status="1"><span class="closeLB">Close</span><span class="bottlenext">next</span><span class="bottleprevious">previous</span></div>');
                                    pObj.append(lBox);
                                    $("#lightBox", obj).fadeIn(300);
                                    $('#' + options.nextButtonId + ', #' + options.previousButtonId + '').fadeOut(300);
                                }
                                else {
                                    $("#lightBox", obj).fadeOut(300, function(){
                                        $("#lightBox", obj).remove();
                                        $('#' + options.nextButtonId + ', #' + options.previousButtonId + '').fadeIn(300);
                                    });
                                }
                                $(".closeLB", obj).click(function(){
                                    $("#lightBox", obj).fadeOut(300, function(){
                                        $("#lightBox", obj).remove();
                                    });
                                    animeRIGHT(0, null);
                                });
                            };
                            
                            /**
                             * Change images to the available image count
                             */
                            var imageSwap = function(iObj){
                                var imageCount = iObj.attr("icount");
                                var src = iObj.attr("src");
                                src = src.split(".");
                                src = src[0].split("-");
                                if (src.length > 1) 
                                    src.splice(src.length - 1, 1);
                                src = src.toString().replace(/,/gi, "-");
                                imageCount = imageCount.split(",");
                                
                                var icount = 0;
                                $(".bottlenext", obj).click(function(){
                                    icount = icount > 0 ? icount - 1 : icount = (imageCount.length - 1);
                                    iObj.attr("src", '/images/load.gif').css({
                                        height: 30,
                                        left: 298,
                                        top: 195,
                                        width: 30
                                    });
                                    imageLoader(iObj, 'next');
                                });
                                $(".bottleprevious", obj).click(function(){
                                    icount = icount < (imageCount.length - 1) ? icount + 1 : icount = 0;
                                    iObj.attr("src", '/images/load.gif').css({
                                        height: 30,
                                        left: 298,
                                        top: 195,
                                        width: 30
                                    });
                                    imageLoader(iObj, 'previous');
                                });
                                
                                /**
                                 * Check if the src of the image object is active and preloads it
                                 * if the src is false will load the next image
                                 * @param {Object} thisobj
                                 * @param {Object} direction
                                 */
                                var imageLoader = function(thisobj, direction){
                                    var img = new Image();
                                    img.onload = function(){
                                        if (options.productType == "sd") {
                                            thisobj.attr("src", '' + src + '-' + imageCount[icount] + '.png').css({
                                                height: 430,
                                                left: 244,
                                                top: 10,
                                                width: 140
                                            });
                                        }
                                        else 
                                            if (options.productType == "icecream") {
                                                thisobj.attr("src", '' + src + '-' + imageCount[icount] + '.png').css({
                                                    height: this.height,
                                                    left: 160,
                                                    top: 38,
                                                    width: this.width
                                                });
                                            }
                                    };
                                    img.onerror = function(){
                                        if (direction == "next") {
                                            $(".bottlenext").trigger('click');
                                        }
                                        else 
                                            if (direction == "previous") {
                                                $(".bottleprevious").trigger('click');
                                            }
                                    };
                                    img.src = '' + src + '-' + imageCount[icount] + '.png';
                                };
                            };
                            
                            
                        };
                        
                        /**
                         * Mouse Scroll Control OBJ
                         */
                        var _mouseScroll = {
                            hookEvent: function(element, eventName, callback){
                                if (typeof(element) == "string") 
                                    element = document.getElementById(element);
                                if (element == null) 
                                    return;
                                if (element.addEventListener) {
                                    if (eventName == 'mousewheel') 
                                        element.addEventListener('DOMMouseScroll', callback, false);
                                    element.addEventListener(eventName, callback, false);
                                }
                                else 
                                    if (element.attachEvent) 
                                        element.attachEvent("on" + eventName, callback);
                            },
                            cancelEvent: function(e){
                                e = e ? e : window.event;
                                if (e.stopPropagation) 
                                    e.stopPropagation();
                                if (e.preventDefault) 
                                    e.preventDefault();
                                e.cancelBubble = true;
                                e.cancel = true;
                                e.returnValue = false;
                                return false;
                            },
                            eventTrigger: function(e){
                                e = e ? e : window.event;
                                var raw = e.detail ? e.detail : e.wheelDelta;
                                if (raw > 0) {
                                    if ($("#lightBox", obj).html() == null) {
                                        $('#' + options.nextButtonId).trigger('click');
                                    }
                                }
                                else {
                                    if ($("#lightBox", obj).html() == null) {
                                        $('#' + options.previousButtonId).trigger('click');
                                    }
                                }
                                _mouseScroll.cancelEvent(e);
                            }
                        };
                        
                        return {
                            start: function(){
                                _addButtons();
                                _btnClick();
                                _mouseScroll.hookEvent(obj.attr("id"), 'mousewheel', _mouseScroll.eventTrigger);
                            }
                        }
                    }(window)
                }
            }
            return getInstance();
        }
        
        var sControl = new slideControl();
        sControl.processHTML.prepare();
        sControl.animate.start();
    };
})(jQuery);

