//menu Accordion
//author: Marghoob Suleman
//Date: 05th Aug, 2009
//Version: 1.0
//web: www.giftlelo.com | www.marghoobsuleman.com
;(function($){
	$.fn.msAccordion = function(options) {
		_isrunning = false;
		options = $.extend({
					currentDiv:'1',
					previousDiv:'',
					defaultid:0,
					currentcounter:0,
					intervalid:0,
					autodelay:0,
					event:"click",
					alldivs_array:new Array()
			}, options);
		$(this).addClass("accordionWrapper");
		$(this).css({overflow:"hidden"});
		var elementid = $(this).attr("id");
		var allDivs = this.children();	
		/*
		if(options.autodelay>0)  {
			$("#"+ elementid +" > div").bind("mouseenter", function(){ pause(); });
			$("#"+ elementid +" > div").bind("mouseleave", function(){startPlay(); });
		}		
		*/
		allDivs.each(function(current) {
			 var iCurrent = current;
			 var sTitleID = elementid+"_msTitle_"+(iCurrent);
			 var sContentID = sTitleID+"_msContent_"+(iCurrent);
			 var currentDiv = allDivs[iCurrent];
			 var totalChild = currentDiv.childNodes.length;
			 var titleDiv = $(currentDiv).find("div.title");
			 titleDiv.attr("id", sTitleID);
			 var contentDiv = $(currentDiv).find("div.content");
			 contentDiv.attr("id", sContentID);
			 options.alldivs_array.push(sTitleID);			 
			 $("#"+sTitleID).bind(options.event, function(){ pause(); openMe(sTitleID);});
		});	
		//open default
		openMe(elementid+"_msTitle_"+options.defaultid);
		if(options.autodelay>0) {startPlay();};		
		function openMe(id) {
			//window.console.log(id);
			if(!_isrunning) 
			{	  				
				_isrunning = true;
				var sTitleID = id;
				var iCurrent = sTitleID.split("_")[sTitleID.split("_").length-1];
				options.currentcounter = iCurrent;
				var sContentID = id+"_msContent_"+iCurrent;
				//window.console.log(sContentID);
				if(sContentID!=options.previousDiv)		
				{
				   if($("#"+sContentID).css("display")=="none") 
					{		
						if(options.previousDiv!="") { closeMe(options.previousDiv); };
						$("#"+sContentID).animate({width: 'toggle'}, 1500, onComplete);								
						options.currentDiv = sContentID;
						options.previousDiv = options.currentDiv;				
					}  else {
						_isrunning = false;
					}
				} else {
					 _isrunning = false;
				}
			}			
		};
		function onComplete() {
			//window.console.log(options.currentcounter);
			_isrunning = false;
		};
		function closeMe(div) {				
			$("#"+div).animate({width: 'toggle'},1500);				
		};	
		
		function startPlay() {
			options.intervalid = window.setInterval(play, options.autodelay * 2000);
		};
		
		function play() {
			var sTitleId = options.alldivs_array[options.currentcounter];
			openMe(sTitleId);
			options.currentcounter++;
			if(options.currentcounter==options.alldivs_array.length) {options.currentcounter = 0;}
		};
		
		function pause() {	   			
			window.clearInterval(options.intervalid);
		};
		
		}
})(jQuery);
