/*
	Example Usage:
	$('#homecarousel').infiniteCarousel({showArrows: false, pagination: true, auto:true, speed:500, pause: 5000});
	
	Example External Calls
	<a href="#" class="next" target="homecarousel">Next</a>
	<a href="#" class="prev" target="homecarousel">Previous</a>
	<a href="1" class="goto" target="carousel1">Skip to Slide 1</a>
*/


$(document).ready(function () {	
	// External Hooks Via Dom Classes on page ready
	$(".goto").click(function(event){
		event.preventDefault();
		var slide = $(this).attr("href");
		var target = $(this).attr("target");
		$('#' + target).trigger("goto",slide);
	});
	
	$(".prev").click(function(event){
		event.preventDefault();
		var target = $(this).attr("target");
		$('#' + target).trigger("prev");
	});
	
	$(".next").click(function(event){
		event.preventDefault();
		var target = $(this).attr("target");
		$('#' + target).trigger("next");
	});
	
});

(function() {
    $.fn.infiniteCarousel = function(options) {
        function repeat(str, n) {
            return new Array(n + 1).join(str);
        }

        var defaults = {
            speed: 800,
            auto: false,
            pause: 2000,
            showArrows: true,
            pagination: true,
            paginationType: "numeric", /* numeric, title, alt */
            paginationArrows: false
        };

        var options = $.extend(defaults, options);

        return this.each(function() {
            var $this = $(this),
				$wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(999999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first'),
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth);

            $this.data('pages', Math.ceil($items.length / visible));
            $this.data('currentPage', 1);

            /* TASKS */



            // add the numeric navigation
            if (options.pagination) {
                var temphtml = '<ol class="pagination ' + options.paginationType + '"></ol>';
                $this.append(temphtml);

                var numitems = $("li", $this).length;
                for (var i = 0; i < numitems; i++) {
                    var navLabel = String(i + 1);
                    if (options.paginationType == "alt") {
                        navLabel = $($items[i]).find('img').attr("alt");
                    }
                    else if (options.paginationType == "title") {
                        navLabel = $($items[i]).find('a').attr("title");
                    }


                    $(document.createElement("li"))
						.addClass('pagination' + (i + 1))
						.html('<a rel=' + i + ' href=""><span>' + navLabel + '</span></a>')
						.appendTo($(".pagination", $this))
						.click(function(event) {
						    event.preventDefault();
						    event.stopPropagation();
						    gotoPage(parseInt($("a", $(this)).attr('rel')) + 1);
						    return false;
						});
                };

                if (numitems == 1) {
                    $(".pagination", $this).hide();
                }

                if (options.paginationArrows) {
                    $(".pagination", $this).prepend('<li class="back"><a href="#" class="back">&lt;</a></li>');
                    $(".pagination", $this).append('<li class="forward"><a href="#" class="forward">&gt;</a></li>');
                }
                $('.pagination1', $this).addClass('current');
            }

            // insert the back and forward link
            if (options.showArrows && $items.length > 1) {
                $wrapper.after('<a href="#" class="arrow back"></a><a href="#" class="arrow forward"></a>');
            }

            // create the carousel padding on left and right (cloned) for seamless animation
            $items.filter(':first').before($items.slice(-(visible)).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, (visible)).clone().addClass('cloned'));
            $items = $slider.find('> li');

            // reset scroll
            $wrapper.scrollLeft(singleWidth * (visible));


            // paging and Animation function
            function gotoPage(page) {

                $('.current', $this).removeClass('current');

                if (page > ($this.data('pages'))) {
                    $('.pagination1', $this).addClass('current');
                } else if (page < 1) {
                    $('.pagination' + $this.data('pages'), $this).addClass('current');
                } else {
                    $('.pagination' + page, $this).addClass('current');
                }

                var dir = page < $this.data('currentPage') ? -1 : 1,
                    n = Math.abs($this.data('currentPage') - page),
                	left = singleWidth * dir * visible * n;

                function trace(msg) {
                    if (typeof (jsTrace) != 'undefined') {
                        jsTrace.send(msg);
                    }
                }
                //trace($slider.css("left"));
                // Animate Slider
                $wrapper.filter(':not(:animated)').animate(
					{ scrollLeft: '+=' + left }, // what we are animating
					{
					duration: options.speed, // how fast we are animating
					easing: 'swing', // the type of easing
					complete: function() { // the callback
					    // if page == last page - then reset position
					    if (page > ($this.data('pages')) || $wrapper.scrollLeft() >= ((singleWidth * numitems) + singleWidth)) {
					        var xvalue = (singleWidth * (visible)) >= (singleWidth * (numitems)) ? singleWidth : (singleWidth * (visible));
					        $wrapper.scrollLeft(xvalue);
					        page = 1;
					    } else if (page < 1) {
					        page = $this.data('pages');
					        $wrapper.scrollLeft(singleWidth * ($this.data('pages')));
					    }
					    $this.data('currentPage', page);

					}
	});
            }

            // AUTOMATIC Scrolling
            if (options.auto && numitems > 1) {
                var autoscrolling = true;

                $this.hover(
					function() {
					    autoscrolling = false;
					}, function() {
					    autoscrolling = true;
					}
				);


                setInterval(function() {
                    if (autoscrolling) {
                        $this.trigger('next');
                    }
                }, options.pause);
            }


            // bind triggers and hooks
            $('a.back', this).click(function() {
                gotoPage(parseInt($this.data('currentPage')) - 1);
                return false;
            });

            $('a.forward', this).click(function() {
                gotoPage(parseInt($this.data('currentPage')) + 1);
                return false;
            });

            $(this).bind('goto', function(event, page) {
                event.stopPropagation();
                gotoPage(page);
                return false;
            });


            $(this).bind('next', function() {
                gotoPage(parseInt($this.data('currentPage')) + 1);
            });

            $(this).bind('prev', function() {
                gotoPage(parseInt($this.data('currentPage')) - 1);
            });

        });
    };




})(jQuery);
