/**
 * @author Martin 
 */

// "hs" is the prefix of all public methods in this class
// alert($("div#" + parentID).data("elements")[0]);

(function($){
	//Config vars
	var durIn						=	1000;
	var durOut					=	600;
	var children				=	new Array();
	var animTimeOut			= 6000;
	var parentID				=	'';
	var currentElement	= '';
	var arrSize					= '';
	
	//Plugin begins
	
	//Process all enabled containers
	$.fn.hsProcessElements = function(){
				parentID			=	$(this).attr("id");
		var getChildren		=	$(this).find("div.slideItem");
		var allChildren		=	getChildren.length;	
		
		//Do we have more than one element?
		if(allChildren > 1){
			
			var i = 0;
			
			//Set the first element to be the size of the arr
			children[0]	=	allChildren;
			
			//For each child element
			getChildren.each(function(){
				
				//Generate new ID and set it as attribute
				var newItemID	=	parentID + "-" + i;
				$(this).attr("id",newItemID);
				
				//Fill the next cell in our arr with the newly generated ID
				i++;
				children[i]	=	newItemID;
			});
			
			//Show the first element
			$("div#" + parentID + "-" + 0).show();
			
			//Set the arr with childrend as property of the parent container
 			$("div#" + parentID).data("elements", children);
			arrSize					=	$(this).data("elements")[0];
			currentElement	=	0;
 			$("div#" + parentID).hsStartAnimate(arrSize,currentElement,0);
		
		}else{
			//If no the getChildren arr will contain only 1 element
			//and we will show it.
			getChildren.show();
		}
	};

	//Loop elements
	$.fn.hsLoopElements = function(arrSize,currentElement){
		var j		= 0;
		var pID	=	$(this).attr("id");
		
		if($.browser.msie){// Oh mighty IE can you please render this properly
			$(this).find("div.slideItem").slideUp(durOut);
		}else{
			$(this).find("div.slideItem").fadeOut(durOut);
		}

		if(currentElement >= arrSize - 1){
			newElem = 0;
			$("div#" + pID + "-" + 0).delay(durOut).fadeIn(durIn);
			$("div#" + pID).hsStartAnimate(arrSize,newElem,0);	
		}else{
			newElem = parseInt(currentElement + 1);
			$("div#" + pID + "-" + newElem).delay(durOut).fadeIn(durIn);
			$("div#" + pID).hsStartAnimate(arrSize,newElem,0);	
		}
	};

	//Start animation - prototype fn
	$.fn.hsStartAnimate = function(arrSize,currentElement,loop){
		clearTimeout(timeout);
		if(loop == 0){
			var	pID				=	$(this).attr("id");
			var timeout		=	setTimeout(function(){
				$("div#" + pID).hsLoopElements(arrSize,currentElement);
				clearTimeout(timeout);
			},animTimeOut);
		}else{
			return false;
		}
	};
	
	//Init - prototype fn
	$.fn.HomePageSliderInit = function(){
		return this.each(function(){
			$(this).hsProcessElements();
		});
	};	
})(jQuery);
