﻿/* Replaced Scotts version to allow paging*/

/*Created 6/4/09 wojan*/
(function($) {
    $.fn.carousel = function(options) {

        if (!options) options = {};
        var defaults = {
            placeholder: "data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAEBMgA7"
        };
        var ccount = 0;
        //for each carousel found
        this.each(function() {
            ccount++;
            var carousel = $(this);
            carousel.size = { width: options.width || carousel.width(), height: options.height || carousel.height() }
            wrapAndResize(carousel);
            carousel.show();
        });

        function wrapAndResize(carousel) {
            //equalize the li height and width
            carousel.children().each(function() {
                var li = $(this);
                li.width(carousel.size.width);
                li.height(carousel.size.height);
            });

            //add the initial loading indicator
            carousel.loadingImg = new Image();
            carousel.loadingImg.src = options.placeholder || defaults.placeholder;
            carousel.loadingImg.className = 'loadingImg';

            //resize images to fit
            carousel.imgCount = resizeImgs(carousel);


            //wrap in div
            carousel.container = $('<div id="carousel' + ccount + '" class="carousel-container">')
                          .css({ height: carousel.size.height, width: carousel.size.width, margin: '0', padding: '0', overflow: 'hidden', position: 'relative' });
            carousel.wrap(carousel.container);
            carousel.container = carousel.parent();

            carousel.container.prepend($(carousel.loadingImg));

            hookupPaging(carousel);
        }

        function hookupPaging(carousel) {

            // Controls html to append
            var controlsHtml = '<ul class="controls">';
            // Add link to previous pages
            controlsHtml += '<li><a href="javascript:void(0)">Prev</a></li>';
            for (var i = 1; i <= carousel.imgCount + 1; i++) {
                controlsHtml += '<li><a href="javascript:void(0)">' + i + '</a></li>';
            }
            // Add link to next page
            controlsHtml += '<li><a href="javascript:void(0)">Next</a></li>';
            controlsHtml += '</ul>';

            var controls = carousel.container.prepend(controlsHtml).find('ul.controls');
            controls.hide();

            //Disable Prev href since we are on the first page
            controls.find('li:first a').removeAttr('href');

            //If number of images <= 5 disable Next href
            if (carousel.imgCount <= 5) {
                controls.find('li:first a').removeAttr('href');
                controls.find('li:last a').removeAttr('href');
            }
            // Hide all the links since need display only the first 5 images
            for (var i = 6; i <= carousel.imgCount + 1; i++) {
                var someStr = 'li:eq(' + i + ')';
                controls.find(someStr).hide();
            }
            controls.find('li:eq(1) a').addClass('active'); //make first item active

            // hookup click events
            controls.find('li a').click(function(event) {
                var formerActive = controls.find('li a.active');
                formerActive.removeClass('active');

                var active = active = $(this);
                active.addClass('active');

                var currentIndex = parseInt(formerActive.text());
                var newIndex = parseInt(active.text());

                if (active.text() == "Next") {
                    //Add href to "Prev" link 
                    controls.find('li:eq(0) a').attr('href', 'javascript:void(0)');
                    active.removeClass('active');

                    //determine links to hide 
                    var x = parseInt(currentIndex / 6);
                    var startHideIndex = (5 * x) + 1;
                    var endHideIndex = (5 * x) + 5;


                    if (endHideIndex >= carousel.imgCount + 1) {
                        newIndex = currentIndex;
                        formerActive.addClass('active');
                    }
                    else {
                        //hide everything from 1 to x
                        for (var i = startHideIndex; i <= endHideIndex; i++) {
                            var controlToHide = 'li:eq(' + i + ')';
                            controls.find(controlToHide).hide();
                        }

                        x = (x * 5) + 5;
                        var lastIndex;
                        // determine last Index
                        if (carousel.imgCount + 1 > x + 5)
                            lastIndex = x + 5;
                        else {
                            lastIndex = carousel.imgCount + 1;
                            active.removeAttr('href');
                        }

                        //show everything from current index to last index
                        for (var i = x + 1; i <= lastIndex; i++) {
                            var contrlToShow = 'li:eq(' + i + ')';
                            controls.find(contrlToShow).show();

                            //make first item active  
                            if (i == x + 1) {
                                contrlToShow = contrlToShow + " a";
                                controls.find(contrlToShow).addClass('active');
                            }
                        }
                        newIndex = x + 1;
                    }

                }
                else if (active.text() == "Prev") {
                    // Add href to "Next"
                    controls.find('li:last a').attr('href', 'javascript:void(0)');
                    active.removeClass('active');

                    // dertermine what to show what to hide
                    var x = parseInt(currentIndex / 5);
                    if (parseInt(currentIndex % 5) == 0) {
                        x = x - 1;
                    }

                    // If current index is the first index (Prev): - do nothing
                    if (x == 0) {
                        currentIndex = 0;
                        newIndex = 0;
                        formerActive.addClass('active');
                    }
                    else {
                        // dertermne what to hide
                        var startHideIndex = (5 * x) + 1;
                        var endHideIndex = (5 * x) + 5;
                        if (carousel.imgCount + 1 < endHideIndex)
                            endHideIndex = carousel.imgCount + 1;

                        for (var i = startHideIndex; i <= endHideIndex; i++) {
                            var controlToHide = 'li:eq(' + i + ')';
                            controls.find(controlToHide).hide();
                        }

                        // dertermine what to show
                        var lastShowIndex = x * 5;
                        var beginIndex = x * 5 - 4;
                        if (beginIndex == 1) {
                            active.removeAttr('href');
                        }
                        for (var i = beginIndex; i <= lastShowIndex; i++) {
                            var controlToShow = 'li:eq(' + i + ')';
                            controls.find(controlToShow).show();

                            //make first item active 
                            if (i == beginIndex) {
                                controlToShow = controlToShow + " a";
                                //alert('Making first element active' + someStr);
                                controls.find(controlToShow).addClass('active');
                            }
                        }
                        newIndex = beginIndex;
                    }
                }
                var moveSteps = newIndex - currentIndex;
                if (!moveSteps) { return false; }
                var direction = (moveSteps > 0) ? '-=' : '+=';

                var move = 0;
                var bottom = Math.min(currentIndex, newIndex);
                var top = Math.max(currentIndex, newIndex);

                while (bottom < top) {
                    move += carousel.size.width;
                    bottom++;
                }

                carousel.animate({ marginLeft: direction + move }, 500);

                return false;
            });
            controls.show(300);
        }

        function resizeImgs(el) {
            var width = options.width || el.width();
            // Change height to accomodate links (Prev 1 2 3 4 5 Next) and image title
            var height = (options.height - 42) || (el.height() - 42);

            var i = -1;
            //get all the images
            var images = el.find('IMG');
            var imagesLoaded = 0;
            var totalWidth = 0; //total width
            images.each(function() {
                i++;
                var image = $(this);

                // Swap the img@src with the placeholder
                var src = image.attr('src');
                image.attr('src', options.placeholder || defaults.placeholder);

                var img = new Image();
                img.onerror = function() {
                    if (typeof (console) != 'undefined')
                        console.log('error resizing ' + img.src)

                    var container = el.parent();
                    $(container.children()[1]).remove();
                    container.find('ul.controls').show(300);
                };

                img.onload = function() {

                    // Check if the loaded image is wide or tall
                    var is_tall = this.height > this.width * height / width;
                    if (is_tall) {
                        size = height * this.width / this.height;
                        margin = (width - size) / 2;
                    } else {
                        size = width * this.height / this.width;
                        margin = (height - size) / 2;
                    }
                    if (margin < 0) margin = 0;

                    // Adjust margin-* with the current value
                    var adjuster = function(name, margin) {
                        var current = image.css(name);
                        if (current && current.match(/^(\d+)px$/)) {
                            return parseInt(RegExp.$1) + margin;
                        }
                        return margin;
                    };

                    // Update margin and width/height CSS properties
                    if (is_tall) {
                        totalWidth += size;
                        image.css({
                            height: height,
                            width: size,
                            "margin-left": adjuster("margin-left", margin),
                            "margin-right": adjuster("margin-right", margin)
                        });
                    } else {
                        totalWidth += width;
                        image.css({
                            width: width,
                            height: size,
                            "margin-top": adjuster("margin-top", margin),
                            "margin-bottom": adjuster("margin-bottom", margin)
                        });
                    }

                    // Finally shoves the loaded img@src
                    image.attr("src", this.src);

                    imagesLoaded++;

                    if (images.length == imagesLoaded) {//all images loaded
                        el.width(images.length * el.size.width);
                        var container = el.parent();
                        $(el.loadingImg).hide();
                        container.find('ul.controls').show(300);
                    }
                };

                // load the target image to trigger onload
                img.src = src;

            }); //img each



            return i;
        }; //end resizeImgs

    };
})(jQuery);


