/*global jQuery, window, document, navigator, console, debug, Image */
(function ($) {
    var defaultSettings = {
        mainImageSelector: ".main",
        thumbnailListSelector: ".thumbs",
        mainImageWidth: 160,
        transitionType: "fade",
        transitionDuration: 250,            // Speed of fade-in and fade-out
        imageClick: null,                   // handler for clicking the hero image
        loadImagesFromThumbnails: false,    // If the thumbnails are wrapped by anchors, fetch the Images URLs from the anchor HREFs
        thumbnailCount: 0,                  // number of thumbnails to display under hero image
        showStatus: true,
        isLandscapeView: false,
        showThumbnailCursor: true,
        defaultImageIndex: 0,
        popupFromThumbnails: false,
        postbackOnThumbnails: false,
        showImageOnClick: false
    };
    var imageClickHandler;
    function formatNumber(nbr) {
        return (nbr < 10 ? "0" : "") + nbr;
    }

    function setupGallery(thmbsList, settings, container) {
        var currentIndex = 0, leftIndex = 0, photoCount,
            transitionDistance, isAnimating = false,

            showImage = function (index) {
                var itemDiv = container.find(settings.mainImageSelector);

                if (index === currentIndex) {
                    return;
                }

                container.find(".thumb-slider li>a").each(function (i, a) {
                    var lnk = $(a), lnkIndx = parseInt(lnk.attr("index"), 10);
                    if (lnkIndx === currentIndex) {
                        lnk.parent().removeClass("active");
                    } else if (lnkIndx === index) {
                        lnk.parent().addClass("active");
                    }
                });

                if (settings.transitionType === "fade") {
                    itemDiv.find("a:eq(" + index + ")").show().fadeTo(settings.transitionDuration, 1, function () { $(this).show(); });
                    itemDiv.find("a:eq(" + currentIndex + ")").stop().fadeTo(settings.transitionDuration, 0, function () { $(this).hide(); });
                } else {
                    itemDiv.find("a:eq(" + currentIndex + ")").hide();
                    itemDiv.find("a:eq(" + index + ")").show();
                }

                itemDiv.height(itemDiv.find("a:eq(" + index + ")").find('img').height());

                if (settings.showStatus) {
                    container.find(".status .current").text(formatNumber(index + 1));
                }

                itemDiv.data("currentIndex", index);
                currentIndex = index;
            },

            displayPicture = function (ev) {
                var a = $(ev.target);
                if (!a.is("a")) {
                    // is a child of the thumbnail link
                    a = a.parent();
                }

                showImage(parseInt(a.attr("index"), 10));
            },

        moveCarousel = function (direction) {
            return function () {
                var isNext = direction === "next",
                        nextIndex = leftIndex + ((isNext ? 1 : -1) * settings.thumbnailCount),
                        listLeft = parseInt(thmbsList.css("left"), 10),
                        dir = (isNext ? "-=" : "+=") + transitionDistance + "px",
                        slice, lastIndex, newList;

                if (isAnimating) {
                    return;
                }

                if (nextIndex >= photoCount) {
                    leftIndex = nextIndex - photoCount;
                } else if (nextIndex < 0) {
                    leftIndex = nextIndex + photoCount;
                } else {
                    leftIndex = nextIndex;
                }

                isAnimating = true;
                thmbsList.animate({ left: dir }, settings.transitionDuration, null,
                             function () {
                                 isAnimating = false;
                                 listLeft = parseInt(thmbsList.css("left"), 10);

                                 // Hide or show the thumbnail buttons depending on the position of the thumbnail list.
                                 if (leftIndex >= (photoCount - settings.thumbnailCount)) {
                                     container.find("a.next").hide().next("span.next").css("display", "block");
                                 } else {
                                     container.find("a.next").show().next("span.next").hide();
                                 }

                                 if (leftIndex > 0) {
                                     container.find("a.prev").show().prev("span.prev").hide();
                                 } else {
                                     container.find("a.prev").hide().prev("span.prev").css("display", "block");
                                 }
                             });
                if (settings.defaultImageIndex == 0)
                    if (!settings.popupFromThumbnails && !settings.postbackOnThumbnails && !settings.showImageOnClick)
                        showImage(leftIndex);

                return false;
            };
        },

        setupGalleryPrevNextButton = function () {
            var itemDiv = container.find(settings.mainImageSelector);
            itemDiv.append('<div class="navPrev"><div class="button"></div></div>');
            itemDiv.append('<div class="navNext"><div class="button"></div></div>');

            itemDiv.find('.navPrev').click(function () {
                goPrevPhoto();
            });
            itemDiv.find('.navNext').click(function () {
                goNextPhoto();
            });

            // also register for the arrow key press
            $(document).keydown(function (e) {
                switch (e.keyCode) {
                    case 37:
                        goPrevPhoto();
                        break;
                    case 39:
                        goNextPhoto();
                        break;
                }
            });
        },

        goPrevPhoto = function () {
            if (thmbsList.is(':animated')) {
                return false;
            }
            currentThumb = thmbsList.find("li.active").prev().find("a");
            if (currentThumb.length == 0) {// hit the first photo
                lastThumb = thmbsList.find("li a:eq(" + (photoCount - 1) + ")")
                if (lastThumb.attr('href') != 'javascript:;')
                    window.location = lastThumb.attr('href');
                else {
                    lastThumb.trigger('mousedown');
                    count = 0;
                    while (leftIndex + settings.thumbnailCount < photoCount) {
                        isAnimating = false;
                        moveCarousel("next")();
                        if (count > 2) {
                            break;
                        }
                        count++;
                    }
                }
            }
            else {
                if (currentThumb.attr('href') != 'javascript:;')
                    window.location = currentThumb.attr('href');
                else {
                    // trigger an artificial click event
                    currentThumb.trigger('mousedown');
                    if (currentIndex < leftIndex) {
                        moveCarousel("prev")();
                    }
                }
            }
        },

        goNextPhoto = function () {
            if (thmbsList.is(':animated')) {
                return false;
            }
            currentThumb = thmbsList.find("li.active").next().find("a");
            if (currentThumb.length == 0) {// hit the last photo
                firstThumb = thmbsList.find("li a:eq(0)");
                if (firstThumb.attr('href') != 'javascript:;')
                    window.location = firstThumb.attr('href');
                else {
                    firstThumb.trigger('mousedown');
                    count = 0;
                    while (leftIndex > 0) {
                        isAnimating = false;
                        moveCarousel("prev")();
                        if (count > 2) {
                            break;
                        }
                        count++;
                    }
                }
            }
            else {
                if (currentThumb.attr('href') != 'javascript:;')
                    window.location = currentThumb.attr('href');
                else {
                    // trigger an artificial click event                                        
                    currentThumb.trigger('mousedown');
                    if (currentIndex > leftIndex + settings.thumbnailCount - 1) {
                        moveCarousel("next")();
                    }
                }
            }
        },

        getThumbnailInfo = function () {
            var thumb = thmbsList.find("li:first"),
                    container = thmbsList.parent(),
                    infoObj = {
                        thumbWidth: thumb.outerWidth(true),
                        thumbHeight: thumb.outerHeight(true),
                        containerWidth: container.outerWidth(true),
                        containerHeight: container.outerHeight(true),
                        columns: 0,
                        rows: 0,
                        thumbnailsInView: 0
                    };

            infoObj.columns = Math.round(infoObj.containerWidth / infoObj.thumbWidth);
            infoObj.rows = Math.round(infoObj.containerHeight / infoObj.thumbHeight);
            infoObj.thumbnailsInView = Math.round(infoObj.columns * infoObj.rows);

            return infoObj;
        },

            adjustThumnbailsPos = function () {
                if (settings.defaultImageIndex === 0)
                    return;
                thmbsList.css("visibility", "hidden");
                var count = 0;
                while (settings.defaultImageIndex > leftIndex + settings.thumbnailCount - 1) {
                    isAnimating = false;
                    moveCarousel("next")();
                }
                settings.defaultImageIndex = 0;
                setTimeout(function () {
                    thmbsList.css("visibility", "visible");
                }, 1000);
            },

            setupThumbnails = function () {
                var div = thmbsList.wrap("<div></div>").parent(),
                        thmbs = thmbsList.find("li"),
                            thmbSlider, thmbSliderWidth,
                            thumbInfo, thmbRack, thmbRackWidth, startIndex, count;

                photoCount = thmbs.length;

                thmbSlider = div.wrap("<div/>").parent().addClass("thumb-slider");
                transitionDistance = div.outerWidth();

                thmbs.find("a").each(function (i, a) {
                    $(a).attr("index", i);
                    $(a).attr("trackdata", "&EventType=M&MediaType=P&Seq=" + i + "&Name=" + escape($(a).find('img').attr('src')));
                });

                if (settings.popupFromThumbnails && imageClickHandler !== undefined) {
                    thmbs.find("a").click(imageClickHandler);
                }
                // change image on hover
                if (!settings.showImageOnClick && !settings.postbackOnThumbnails && !settings.popupFromThumbnails) {
                    thmbs.find("a").mouseenter(displayPicture);
                }
                // chnage image on click
                if (settings.showImageOnClick && !settings.postbackOnThumbnails) {
                    thmbs.find("a").mousedown(displayPicture);
                }
                //add href to trigger postback on thumbnails
                if (settings.postbackOnThumbnails) {
                    thmbs.find('a').each(function (i, a) {
                        $(a).attr('href', window.location.href.replace(/index=(\d+)/, 'index=' + $(a).attr('index')));
                    });
                }

                thmbsList.css("visibility", "visible");

                thumbInfo = getThumbnailInfo();

                if (settings.thumbnailCount === 0) {
                    settings.thumbnailCount = thumbInfo.thumbnailsInView;
                }

                // move thumbnail position inside the slider
                adjustThumnbailsPos();

                if (photoCount > settings.thumbnailCount) {
                    thmbSlider
                        .prepend("<a href='javascript:;' class='prev'>Previous</a>")
                        .prepend("<span class='prev'>Previous</span>")
                        .append("<a href='javascript:;' class='next'>Next</a>")
                        .append("<span class='next'>Next</span>")
                        .find("a.prev").click(moveCarousel("prev")).hide()
                        .end()
                        .find("a.next").click(moveCarousel("next"))
                        .next("span.next").hide();

                    if (!settings.isLandscapeView) {
                        thmbSliderWidth = thumbInfo.thumbWidth * thmbs.length;

                        if ($.browser.msie && parseInt($.browser.version, 10) === 6) {
                            //                            thmbSliderWidth += thmbsList.parent().outerWidth(true);
                            thmbSliderWidth += Math.abs(thumbInfo.containerWidth - thmbSliderWidth);
                        }

                    } else {
                        thmbRackWidth = thmbsList.outerWidth();

                        settings.thumbnailListSelector = ".thumbs-slider-landscape";
                        div = thmbsList.wrap("<div></div>").parent().addClass("thumbs-slider-landscape");

                        startIndex = settings.thumbnailCount;

                        if (settings.thumbnailCount > 0) {
                            while (startIndex < photoCount) {
                                count = 0;
                                thmbRack = $("<ul></ul>").appendTo(div).css("visibility", "visible").addClass("thumbs").width(thmbRackWidth)
                                .append($.grep(thmbs,
                                    function (li) {
                                        var index = parseInt($(li).find("a").attr("index"), 10);
                                        if (index >= startIndex && index < photoCount && count < settings.thumbnailCount) {
                                            count += 1;
                                            return true;
                                        }
                                    })
                                );
                                startIndex += settings.thumbnailCount;
                            }
                        }

                        thmbSliderWidth = thmbRackWidth * div.find("ul").length;
                        thmbsList = div.css({ "overflow": "hidden", "float": "left", "position": "absolute" });
                    }

                    thmbsList.width(thmbSliderWidth);
                } else {
                    thmbSlider.prepend("<span class='prev'>Previous</span>")
                                .append("<span class='next'>Next</span>");
                }
            };

        currentIndex = settings.defaultImageIndex;
        setupThumbnails();
        setupGalleryPrevNextButton();
    }

    $.fn.miniGallery = function (options) {
        var settings = $.extend({}, defaultSettings, options),
            hi = this.find(settings.mainImageSelector),
            thmbsList = this.find(settings.thumbnailListSelector),
            photoCount = thmbsList.find("li").length,
            canImageClick = (typeof settings.imageClick === "function"),
            height, width, isStaticImage,
            checkImageHeight = function (img) {
                if (img.height > img.width && !settings.showImageOnClick) {
                    $(img).css("height", height + "px").removeAttr("width");
                } else {
                    img.removeAttribute("height");
                    img.width = width;
                }
            };

        if (photoCount < 1) {
            return;
        }

        if (settings.loadImagesFromThumbnails) {
            hi.empty();
            isStaticImage = settings.popupFromThumbnails || settings.postbackOnThumbnails;
            height = parseInt(hi.css("height")) || 0;
            width = settings.mainImageWidth || hi.width();

            // Load main images
            thmbsList.find("li>a").each(function (i, a) {
                var img = new Image(),
                    imgSrc = a.href,
                    imgAlt = $(a).find('img')[0].alt,
                    lnk = $("<a href='javascript:;'></a>").css("opacity", (i == settings.defaultImageIndex ? "1" : "0"));

                a.href = "javascript:;";

                if (settings.showThumbnailCursor) {
                    $(a).append("<span>&nbsp;</span>");
                }

                if (isStaticImage && i == settings.defaultImageIndex) {
                    lnk.appendTo(hi);
                    if ($.browser.msie) {
                        img.onload = function () {
                            checkImageHeight(img);
                            lnk.append(img);
                        };
                        img.src = imgSrc;
                        img.alt = imgAlt;
                    } else {
                        img.onload = function () {
                            checkImageHeight(img);
                        }
                        img.src = imgSrc;
                        img.alt = imgAlt;
                        img.width = width;
                        lnk.append(img);
                    }
                } else if (!isStaticImage) {
                    lnk.appendTo(hi);
                    img.width = width;
                    if (settings.showImageOnClick && i == settings.defaultImageIndex) {
                        img.onload = function () {
                            height = Math.max(height, img.height);
                            hi.css("height", height + "px");
                        };
                    }
                    img.src = imgSrc;
                    img.alt = imgAlt;
                    lnk.append(img);
                }
            });

            if (canImageClick) {
                imageClickHandler = function (ev) {
                    settings.imageClick(ev, hi.data("currentIndex"));
                };

                hi.hover(function () { $(this).find("span").show(); }, function () { $(this).find("span").hide(); })
                    .append("<span>Open Gallery</span>").click(imageClickHandler);
            }
        }

        if (settings.showStatus) {
            hi.after("<p class='status'>Image <var class='current'>" + formatNumber(Number(settings.defaultImageIndex) + 1) + "</var> of <var class='total'>" +
				formatNumber(photoCount) + "</var></p>");
        }

        if (isStaticImage) {
            hi.data("currentIndex", settings.defaultImageIndex).css("position", "relative");
            if (settings.showImageOnClick) {
                hi.css("height", "auto");
            }
        } else {
            hi.data("currentIndex", settings.defaultImageIndex).css("position", "relative")
                .find("a").css({ "position": "absolute", "top": "0px", "left": "0px" });
        }

        thmbsList.find("li").eq(settings.defaultImageIndex).addClass("active");

        this.find(".loading").remove();

        setupGallery(thmbsList, settings, this);

        return this;
    };

    $.fn.simpleGallery = function (imageUrls, settings) {
        var thumbs, html = [];
        settings = $.extend(settings, $.fn.simpleGallery.defaultSettings);

        // Ensure imageUrls is an array even if undefined
        imageUrls = imageUrls || [];

        this.append('<div class="loading">loading...</div><div class="main"></div>');

        if (imageUrls.length) {
            thumbs = $('<ul class="thumbs"></ul>').appendTo(this);
            $.each(imageUrls, function (i) {
                html.push('<li><a href="' + imageUrls[i] + '"><img src="' + imageUrls[i] + '?size=thumb" alt=""/></a></li>');
            });
            thumbs.append(html.join(""));
            this.miniGallery({
                mainImageWidth: settings.imageWidth,
                thumbnailCount: settings.thumbnailCount,
                loadImagesFromThumbnails: true
            });
        }

        return this;
    };

    $.fn.simpleGallery.defaultSettings = {
        imageWidth: 440,
        thumbnailCount: 4
    };

} (jQuery));
