/*
 * IO RandomTeaser Module
 */

(function($){
	$.fn.IORandomTeaser = function(options){

		//Attibutes
			var defaults = {
				cookieName: null
			};

			options = $.extend(defaults, options),
					teaserID = 0,
					teaserCount = 0,
					cookieContent = null,
					cookieContent2 = null,
					containers = {},
					containerID = 0,
					containerCount = 0,
					theContent = "",
					resultJSON = {},
					isFirst = true;

		return this.each(function(){

			obj = $(this);
			containerCount = $("."+obj.attr("class")).length;
			

			function getJSONContentsFromCoookie(cookiename){
				cookieContent = $.cookie(cookiename);

				if(cookieContent != null){
					//split 1st level
					containers = cookieContent.split(",");

					for(var i = 0; i < containers.length; i++){

						//split 2nd level
						var teaser = containers[i].split("=");

						//check if the value is a number
						if(!isNaN(teaser[1])){
							//fill into result JSON Object
							resultJSON[i] = {teaserId: teaser[1]};
						}else{
							resultJSON[i] = null;
						}
					}
				}


				if(containers.length < containerCount){
					for(var j = 0; j < containerCount; j++){
						if(resultJSON[j] == undefined){
							resultJSON[j] = null;
						}
					}
				}
				
				return resultJSON;
			}

			
			cookieContent2 = getJSONContentsFromCoookie(options.cookieName);


			//Check if there is a Cookie containing the teaserID
			if(cookieContent2[containerID] != null){

				//Get the teasers id from the cookie's content'
				teaserID = cookieContent2[containerID].teaserId;

				//Show the Teaser and Hide all it's siblings
				obj.children().eq(teaserID).show().siblings().hide();

			}else{
				//Get the real number of teasers inside the random teaser container
				teaserCount = obj.children().length;

				//Generate a random number to define the teaser to be displayed
				teaserID = Math.floor(Math.random() * teaserCount);

				//Show the Teaser and Hide all it's siblings
				obj.children().eq(teaserID).show().siblings().hide();

				//
				theContent += (isFirst)? "" : ",";
				theContent += "teaserID_"+containerID+"="+teaserID;

			}

			isFirst = false;
			containerID++;

			if(theContent != "" && containerID >= containerCount){
				$.cookie(options.cookieName, theContent);
			}

		});
	};
})(jQuery);
