/*
topSlide.js

original from anythingSlider v1.2
By Chris Coyier: http://css-tricks.com
with major improvements by Doug Neiner: http://pixelgraphics.us/
based on work by Remy Sharp: http://jqueryfordesigners.com/

*/

(function($){
	
	$.anythingSlider = function(el, options){
		// To avoid scope issues, use 'base' instead of 'this'
		// to reference this class from internal events and functions.
		var base = this;
		
		// Access to jQuery and DOM versions of element
		base.$el = $(el);
		base.el = el; 

		// Set up a few defaults
		base.currentPage = 1;
		base.timer = null;
		base.playing = false;

		// Add a reverse reference to the DOM object
		base.$el.data("AnythingSlider", base);
		
		//base.options = $.anythingSlider.defaults;//$.extend({},$.anythingSlider.defaults, options);
		base.options = {
			easing: "easeOutQuart",        // Anything other than "linear" or "swing" requires the easing plugin
			autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
			startStopped: false,            // If autoPlay is on, this can force it to start stopped
			pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
			delay: 5000,                    // How long between slide transitions in AutoPlay mode
			animationTime: 1250,             // How long the slide transition takes
			itemMoveWidth: 580,             // How long the ad item moves
			tabMoveWidth: 187.1,               // How long the ad tab moves
			imagePath: "/images/top/swf/",   // Path of image files
			jsonFile: "/js/top/topSlide.json"   // Path of json file
		};

		base.init = function(){
			// Build the navigation if needed
			base.$wrapper = $("<div class='wrapper'></div>").appendTo(base.$el);
			base.$slider  = $("<div class='slider'></div>").appendTo(base.$wrapper);
			base.$nav = $("<div class='nav'></div>").appendTo(base.$el);
			base.$navslider = $("<div class='navslider'></div>").appendTo(base.$nav);
			var json = $.ajax({url:base.options.jsonFile, async:false});
			eval("base.ads = " + json.responseText);
			
			// Randomized index 
			var n = base.ads.length;
			var n = base.ads.length;
			while (n){
				if(!base.ads[--n].enabled){
					base.ads.splice(n,1);
				}
			}
			var n = base.ads.length;
			while (n) {  
				var m = Math.floor(Math.random()*n);
				var t = base.ads[--n];
				base.ads[n] = base.ads[m];
				base.ads[m] = t;
			}
			
			var n = base.ads.length;
			for(var i=0; i < n; i++){
				var index = i;
				if(base.ads[index].enabled){
					var $a = $('<a  class="item" href="'+ base.ads[index].link + '"></a>');
					$a.append('<img src="' + base.options.imagePath + base.ads[index].image + '" />');
					base.$slider.append($a);
				}
					if(base.ads[index].enabled){
						$img = $('<img class="tab" src="' + base.options.imagePath + base.ads[index].tab + '" />');
						base.$navslider.append($img);
					}
			}
			
			// Get the details
			base.$items   = base.$slider.find('.item');
			base.$itemFirst = base.$items.filter(':first');
			base.itemWidth = base.options.itemMoveWidth;
			base.pages = base.$items.length;
		
			base.$tabs = base.$navslider.find('.tab');
			base.$tabFirst = base.$tabs.filter(':first');
			base.tabWidth = base.options.tabMoveWidth;//base.$tabFirst.outerWidth();
			
			// Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
			// This supports the "infinite" scrolling
			base.$items.filter(':first').before(base.$items.filter(':last').clone().addClass('cloned'));
			base.$items.filter(':last' ).after(base.$items.filter(':lt('+ 2 + ')').clone().addClass('cloned'));
			base.$tabs.filter(':first').before(base.$tabs.filter(':gt('+ (base.$tabs.length - 2) + ')').clone().addClass('cloned'));
			base.$tabs.filter(':last' ).after(base.$tabs.filter(':lt('+ 4 + ')').clone().addClass('cloned'));

			// We just added two items, time to re-cache the list
			base.$items = base.$wrapper.find('.item'); // reselect
			base.$tabs = base.$nav.find('.tab'); // reselect
			
			// Setup our forward/backward navigation
			base.buildNextBackButtons();
		
			// If autoPlay functionality is included, then initialize the settings
			if(base.options.autoPlay) {
				base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
				base.startStop(base.playing);
			};
			
			// If pauseOnHover then add hover effects
			if(base.options.pauseOnHover) {
				base.$el.hover(function(e){
					base.clearTimer();
				}, function(e){
					base.startStop(true);
					e.preventDefault();
				});
			}
			
			base.$tabs.click(function(e){
				base.gotoPage(base.$tabs.index(this));
				base.startStop(true);
				e.preventDefault();
			});
			
			base.setCurrentPage(1);
		};

		base.gotoPage = function(page, autoplay){
			// When autoplay isn't passed, we stop the timer
			if(autoplay !== true) autoplay = false;
			if(!autoplay) base.startStop(false);
			
			if(typeof(page) == "undefined" || page == null) {
				page = 1;
				base.setCurrentPage(1);
			};
			
			// Just check for bounds
			if(page > base.pages + 2) page = base.pages;
			if(page < 0 ) page = 1;

			var dir = page < base.currentPage ? -1 : 1,
				n = Math.abs(base.currentPage - page),
				itemleft = base.itemWidth * dir * n,
				tableft = base.tabWidth * dir * n;

			base.$wrapper.filter(':not(:animated)').animate(
				{ scrollLeft : '+=' + itemleft }, base.options.animationTime, base.options.easing, function () {
					if (page == 0) {
						base.$wrapper.scrollLeft(base.itemWidth * base.pages);
						page = base.pages;
					} else if (page > base.pages) {
						base.$wrapper.scrollLeft(base.itemWidth);
						// reset back to start position
						page = page % base.pages;
					};
					base.setCurrentPage(page);
				}
			);

			base.$nav.filter(':not(:animated)').animate(
				{ scrollLeft : '+=' + tableft }, base.options.animationTime, base.options.easing, function () {
					if (page == 0) {
						base.$nav.scrollLeft(base.tabWidth * base.pages);
					} else if (page > base.pages) {
						base.$nav.scrollLeft(base.tabWidth);
					};
					base.setCurrentPage(page);
				}
			);
		};
		
		base.setCurrentPage = function(page, move){
			// Set visual
			base.$nav.find('.cur').removeClass('cur');
			$(base.$tabs[page]).addClass('cur');	

			// [ON Image]
			var n = $(base.$tabs).length;
			for(var i=0; i < n; i++){
				$(base.$tabs[i]).attr('src', $(base.$tabs[i]).attr('src').replace('_on',''));
			}
			$(base.$tabs[page]).attr('src', $(base.$tabs[page]).attr('src').replace(/(\.gif|\.jpg|\.png)/g,'_on$1'));

			// Only change left if move does not equal false
			if(move !== false) {
				base.$wrapper.scrollLeft(base.itemWidth * page);
				base.$nav.scrollLeft(base.tabWidth * page);
			}

			// Update local variable
			base.currentPage = page;
		};
		
		base.goForward = function(autoplay){
			if(autoplay !== true) autoplay = false;
			base.gotoPage(base.currentPage + 1, autoplay);
		};
		
		base.goBack = function(){
			base.gotoPage(base.currentPage - 1);
		};
		
		// Creates the Forward/Backward buttons
		base.buildNextBackButtons = function(){
			var $forward = $('<a class="arrow forward"></a>'),
				$back    = $('<a class="arrow back"></a>');
				
			// Bind to the forward and back buttons
			$back.click(function(e){
				base.goBack();
				e.preventDefault();
			});

			$forward.click(function(e){
				base.goForward();
				e.preventDefault();
			});

			// Append elements to page
			base.$wrapper.after($back);
			base.$wrapper.after($forward);
		};
		
		// Handles stopping and playing the slideshow
		// Pass startStop(false) to stop and startStop(true) to play
		base.startStop = function(playing){
			if(playing !== true) playing = false; // Default if not supplied is false
			
			// Update variable
			base.playing = playing;
			
			if(playing){
				base.clearTimer(); // Just in case this was triggered twice in a row
				base.timer = window.setInterval(function(){
					base.goForward(true);
				}, base.options.delay);
			} else {
				base.clearTimer();
			};
		};
		
		base.clearTimer = function(){
			// Clear the timer only if it is set
			if(base.timer) window.clearInterval(base.timer);
		};
		
		// Trigger the initialization
        base.init();
    };

	
	//
	$.fn.anythingSlider = function(options){
		return this.each(function(i){			
				(new $.anythingSlider(this, options));
		});
    };

})(jQuery);

