﻿var visibleItems = 5;
var currentPosition = 0;
var carouselGroups = [];

$j(document).ready(function() {

    function initCarousel() {
        var item_width = $j('.carouselRendererItem').outerWidth();
		var max_left = null; 
        // VML items are not clickable by default (even the children are not clickable < IE 8) so this fix becomes critical

        $j('.carouselRendererItem').children('a').each(function() {
            var destURL = $j(this).attr('href');
            $j(this).children().children().css('cursor', 'pointer');
            $j(this).children().children().bind('click', function() {
                window.location = destURL;
            });
        });

        // Get the width of the carousel based on the amount of items in the system, make it negative for comparison purposes.
        totalWidth = ($j('.carouselRendererItem').size() * $j('.carouselRendererItem').outerWidth() * -1)
        totalImages = $j('.carouselRendererItem').size();
        overflowedImages = totalImages - visibleItems;
        if (overflowedImages < 0) {
            $j('#carouselRendererLeft').hide();
            $j('#carouselRendererRight').hide();
        } else {
            $j('#carouselRendererLeft').fadeIn(200);
            $j('#carouselRendererRight').fadeIn(200);
        }
        //move the last list item before the first item. The purpose of this is if the user clicks previous he will be able to see the last item.
        //$j('#carousel_ul li:first').before($j('#carousel_ul li:last'));
        //when user clicks the image for sliding right
        $j('#carouselRendererRight').unbind();

        $j('#carouselRendererRight').click(function() {

            //calculate the new left indent of the unordered list
            var left_indent = parseInt($j('#carouselRenderer').css('left')) - item_width;

            //make the sliding effect using jquery's anumate function '
            if (totalImages - currentPosition > visibleItems && (parseInt($j('#carouselRenderer').css('left')) % item_width) == 0) {
                $j('#carouselRenderer').animate({ 'left': left_indent }, { queue: false, duration: 500 }, function() {
                    //get the first list item and put it after the last list item (that's how the infinite effects is made) '
                    $j('.carouselRendererItem:last').after($j('.carouselRendererItem:first'));

                    //and get the left indent to the default -210px
                    $j('#carouselRenderer').css({ 'left': '-210px' });
                });
                currentPosition++;
                $j('#carouselRendererLeft').show();
            } else {
				if (!max_left) max_left = left_indent + item_width;
				$j('#carouselRenderer')
					.append(
						$j('#carouselRenderer li.carouselRendererItem:first').css('left', item_width + 'px').animate({ 'left': 0 }, { queue: false, duration: 500 })
					)
					.css('left', (max_left + item_width) + 'px')
					.animate({ 'left': max_left }, { queue: false, duration: 500 });
			}
            if (currentPosition + visibleItems == totalImages) {
                //$j('#carouselRendererRight').hide();
            }
            selectCurrentCarouselGroup(currentPosition, 'right');
        });

        //when user clicks the image for sliding left
        $j('#carouselRendererLeft').unbind();

        $j('#carouselRendererLeft').click(function() {

            /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
            var left_indent = parseInt($j('#carouselRenderer').css('left')) + item_width;
            if (currentPosition != 0 && (parseInt($j('#carouselRenderer').css('left')) % item_width) == 0) {
                $j('#carouselRenderer').animate({ 'left': left_indent }, { queue: false, duration: 500 }, function() {

                    /* when sliding to left we are moving the last item before the first item */
                    $j('.carouselRendererItem:first').before($j('.carouselRendererItem:last'));

                    /* and again, when we make that change we are setting the left indent of our unordered list to the default -210px */
                    $j('#carouselRenderer').css({ 'left': '-210px' });
                });
                currentPosition--;
                $j('#carouselRendererRight').show();
            } else {
				$j('#carouselRenderer')
					.prepend(
						$j('#carouselRenderer li.carouselRendererItem:last').css('left', -item_width + 'px').animate({ 'left': 0 }, { queue: false, duration: 500 })
					)
					.css('left', -item_width + 'px')
					.animate({ 'left': 0 }, { queue: false, duration: 500 });
			}
            if (currentPosition + visibleItems == totalImages) {
                //$j('#carouselRendererRight').hide();
            }
            if (currentPosition == 0) {
                //$j('#carouselRendererLeft').hide();
            }
            selectCurrentCarouselGroup(currentPosition, 'left');
        });
    }
    initCarousel();
    function selectCurrentCarouselGroup(currentPosition, direction) {
        // If currentPosition = border activate new group + deactivate group from direction
        $j.each(carouselGroups, function(i) {
            if (this > 0) {
                if (currentPosition == this || currentPosition == this - 1) {
                    if (direction == "left") {
                        var nextGroupIndex = i;
                    } else {
                        var nextGroupIndex = i + 1;
                    }
                    var groups = $j('.categoryLink');
                    var re = /[0-9]/gi;
                    clearActiveCategories();
                    var newImg = $j(groups[nextGroupIndex]).children('img').attr('src').replace(re, 2);
                    $j(groups[nextGroupIndex]).children('img').attr('src', newImg);
                    $j(groups[nextGroupIndex]).children('img').addClass('selectedCategory');
                }
            }
        });
    }
    function clearActiveCategories() {
        $j('.categoryLink').each(function(i) {
            var re = /[0-9]/gi;
            var inactiveSrc = $j(this).children('img').attr('src').replace(re, 0);
            $j(this).children('img').attr('src', inactiveSrc);
            $j(this).children('img').removeClass('selectedCategory');
        });
    }

    // Jump to groups.
    $j('.categoryLink').each(function(i) {
        $j(this).bind("mouseover", function(e) {
            var re = /[0-9]/gi;
            var hoverSrc = $j(this).children('img').attr('src').replace(re, 1);
            if (!$j(this).children('img').hasClass('selectedCategory')) $j(this).children('img').attr('src', hoverSrc);
        });
        $j(this).bind("mouseout", function(e) {
            var re = /[0-9]/gi;
            var hoverSrc = $j(this).children('img').attr('src').replace(re, 0);
            if (!$j(this).children('img').hasClass('selectedCategory')) $j(this).children('img').attr('src', hoverSrc);
        });
        $j(this).bind("click", function(e) {
            var buttomImg = $j(this).children('img');

            var re = /[0-9]/gi;
            var activeSrc = $j(this).children('img').attr('src').replace(re, 2);
            clearActiveCategories();
            $j(this).children('img').attr('src', activeSrc);
            $j(this).children('img').addClass('selectedCategory');
            var totalSlides = 0;
            var item_width = $j('.carouselRendererItem').outerWidth();
            for (y = 1; y < i + 1; y++) {
                totalSlides = totalSlides + $j('.marker:nth-child(' + y + ')').children().size();
            }
            var xOffset = item_width * totalSlides
            currentPosition = totalSlides;
            if (currentPosition == 0) {
                // show right hide left for group 1 only.
                $j('#carouselRendererRight').show();
                $j('#carouselRendererLeft').hide();
            } else {
                $j('#carouselRendererRight').show();
                $j('#carouselRendererLeft').show();
            }
            if (xOffset < 0) xOffset = 0;
            $j('#carouselRenderer').animate({ 'left': "-" + xOffset }, { queue: false, duration: 1000 }, function() {

                $j('.carouselRendererItem:first').before($j('.carouselRendererItem:last'));

                $j('#carouselRenderer').css({ 'left': '-210px' });
            });
        });
    });
    // Find out how many objects are in each carousel group

    var iterator = 0;
    $j('.marker').each(function() {
        carouselGroups[iterator] = $j(this).children().length;
        iterator++;
    });

    $j.each(carouselGroups, function(i) {
        if (i > 0 && carouselGroups[i] != 0) {
            for (y = i - 1; y < i; y++) {
                carouselGroups[i] = carouselGroups[i] + carouselGroups[y];
            }
        }
    });

});

