/*
	
	KD Tiles
	Author: Nuno Albuquerque 
	Version: 2010.10.26
	
*/

(function ( $ ) {

	var $tilesContainer,
		tilesCount,
		indexNum,
		itemCount,
		itemsAry,
		maxHorizontalTiles,
		autoPlayEnabled,
		autoPlayTimerId,
		$this,
		origLogoTop;
	
	// Primary tile containers
	var tileContainersAry = [];
		
	// This contains a multi dimensional array containing stacks of inner tile divs. 
	var innerTileStackAry = [];
	
	
	// Default plugin defaults
	var defaults = {
		'startIndex'			:0,
		'autoPlayDelay'			:5000,
		'autoPlay'				:true,
		'transitionDelay'		:300,
		'randomizeTranstion'	:true,
		'tileWidth'				:240,
		'tileHeight'			:256,
		'maxHorizontalTiles'	:4, // Horizontal rotating tiles
		'logoId'				:"", // If logo is passed in, it gets hidden when the indexNum equals startIndex (avoids redundant logos)
		'numTotalTiles'			:8, 
		'tilesContainer'		:"",
		'preloadTileImages'		:true
	}
	
	var methods = {
	
		init: function ( options ) {
		
			return this.each(function(){
			
				// set initial values
				$this= $(this);
				itemsAry = [];
				origLogoTop	=	0;
				autoPlayTimerId = 0;
				autoPlayEnabled = false;
					
				// If options exist, merge them
				// with our default
				if ( options ) { 
					$.extend( defaults, options );
				}
								
				// Cache some variables / values
				$tilesContainer = $( defaults.tilesContainer );
				indexNum = defaults.startIndex;
				itemsAry = $this.find( 'li' );
				itemCount = itemsAry.length;
				tilesCount = defaults.numTotalTiles;
				origLogoTop = $( defaults.logoId ).position().top;
				
				
				// Preload images
				if(defaults.preloadTileImages === true) methods.preloadTileImages();
				
				// Create tile container divs
				for ( var i =0; i < tilesCount; i++ ) {
					var d = $( "<div></div>" );
					$( $tilesContainer ).append( d );
					tileContainersAry.push( d );
				}

				
				// Bind Roll Overs to Items
				$(itemsAry).hover(function (){
					var thisIndex = $(itemsAry).index(this);
					if(thisIndex != indexNum) methods.goTo(thisIndex);
					methods.disableAutoPlay();
				},function (){
					methods.beginAutoLoop();
				})
				methods.enableAutoPlay();
				methods.goTo( defaults.startIndex );
				
			})
			
		},
		
		destroy: function ( ) {
			clearTimeout(autoPlayTimerId);
		},
		goNext: function ( ) {
			methods.goTo( indexNum+1 )
		},
		goPrev: function ( ) {
			methods.goTo( indexNum-1 )
		},
		goTo: function ( val ) {
			if( val < 0 ){
				val = itemCount-1;
			}else if ( val > itemCount-1 ){
				val = 0;
			}
			indexNum = val;
			doTransition();
		},
		beginAutoLoop : function( ) {
			if( defaults.autoPlay ){
				methods.enableAutoPlay();
				autoPlayTimerId = setTimeout( function (){ methods.goNext(); }, defaults.autoPlayDelay );
			}
		},
		enableAutoPlay : function () {
			if(defaults.autoPlay)
			{
				autoPlayEnabled = true;
			}
		},
		disableAutoPlay : function () {
			if(defaults.autoPlay)
			{
				autoPlayEnabled = false;
				clearTimeout( autoPlayTimerId );
			}
		},
		preloadTileImages: function () {
			var i;
			for(var i=0; i < itemsAry.length; i++)
			{
				var image = $('<img />').attr({
					src: 'images/brands/' + $( itemsAry[i] ).find( 'a' ).attr( 'rel' ),
					style: 'display:none;'
					});
				$('body').append(image);
			}
		}
	
	}
	
	function doTransition(e){
	
		// Remove any existing timers
		clearTimeout(autoPlayTimerId);
		
		// Remove selected class from items
		$(itemsAry).each(function (index){
			$(this).removeClass('selected')}
		)
		
		// Add selected class to selected index
		$(itemsAry[indexNum]).addClass('selected');
		
		// Create the Image URL based on the a.class attribute
		var imgUrl = "images/brands/" + $( itemsAry[indexNum] ).find( 'a' ).attr( 'rel' );
		
		var innertiles = [];
		
		var i;
		 
		// Loop all the tile containers and create new inner tiles
		for (i=0; i < tilesCount; i++ ) {
			
			// Find background position based on height, width, and index of tile
			var	xOffset = (i>(defaults.maxHorizontalTiles-1)) ? -((i-defaults.maxHorizontalTiles)*defaults.tileWidth): -(i*defaults.tileWidth);
			var yOffset = (i>(defaults.maxHorizontalTiles-1)) ? -(defaults.tileHeight) : 0;
			var styleStr = "background-position:"+ xOffset +"px " + yOffset + "px";
			var innertile = $( "<div class='inner-tile' style='"+ styleStr +"; background-image: url( " + imgUrl + ");'></div>");

			$( tileContainersAry )[i].prepend( innertile );
			innertiles.push( innertile );
		}
		
		innerTileStackAry.unshift( innertiles );

		// Clean up stacks
		if ( innerTileStackAry.length > 1 ) {
			var itemsToRemove = innerTileStackAry.pop();

			$( itemsToRemove ).each( function ( index ){
				var thistile = itemsToRemove[index];
				var fdelay = ( defaults.randomizeTranstion ) ? Math.random()*300:index*defaults.transitionDelay ; 
				$( thistile ).delay( fdelay ).fadeOut( 300,function (){ $( thistile ).remove(); } );
			})

		}

		if ( autoPlayEnabled ) {
			methods.beginAutoLoop();
		}

		if ( indexNum == itemCount-1 )	{
			$(defaults.logoId).animate({top:"-200px"});

		} else {
			$( defaults.logoId ).animate( { top:origLogoTop+"px" } );
		}

	}

	
	$.fn.tiles = function ( method ){
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.tiles' );
		}    
	}
	

})(jQuery);
