//by Valerio Proietti (http://mad4milk.net). MIT-style license.
//accordion.js - depends on prototype.js or prototype.lite.js + moo.fx.js
//version 2.0

//heavily modified by weaver for use in suiteFX plugin to Softpress Freeway

if (typeof Effect == 'undefined') 	throw("accordion functions require inclusion of script.aculo.us' effects.js library!");


sFX_Accordion = Class.create();
sFX_Accordion.prototype = {
	setOptions: function(options){
		this.options = Object.extend({
			onStart:		function(){},
			onComplete:		function(){},
			transition:		Effect.Transitions.sinoidal,
			duration: 		500,
			unit: 			'px',
			wait: 			true,
			fps: 			50
		}, options || {});
	},
	
	extendOptions: function(options){
		this.setOptions(options);
		Object.extend(this.options, Object.extend({
			start:			'open-first',
			fixedHeight:	false,
			fixedWidth:		false,
			alwaysHide:		false,
			wait:			false,
			onActive:		function(){},
			onBackground:	function(){},
			height:			true,
			opacity:		true,
			width:			false,
			
			closeLinkClass:	'accCloseLink',
			dummyLinkClass:	'accLink',
			contentWrapperClass:
							'accContentWrapper',
			
			openDelay:		false, //expects number in milliseconds, if you want to delay opening of accordion on page load
			openItem:		false, //expects a number, other than '0' (as 'open first' handles this already) or an id value of the accordion item to open
			openEvent:		'click', //can either be 'click' or 'mouseover', the actual syntax here will determine the final event
			
			localCookie:	false,
			globalCookie:	false,
			prefixCrumb:	'cookieCrumb_' //this must match accordion _vars.code file in action bundle
		}, options || {}));
	},

	initialize: function(options){
		this.now = {};
		
		this.widths = [];
		
		this.elements = $A(options.content);
		this.togglers = $A(options.toggle);
//alert(';;'+this.elements);
		//this.setOptions(options);
		this.extendOptions(options);
//alert(this.options.toSource());
		this.previousClick = 'nan';
		this.togglers.each(function(tog, i){
//add dummy link stuff
			var togLinks = $A(tog.select('.'+this.options.dummyLinkClass));
			togLinks.each(function(link , j){
				//sets href to equivalent toggler
				link.writeAttribute('href','#'+tog.identify());
				//sets close 'click' event
				link.writeAttribute('onclick','event.returnValue = false; return false;');
				//link.observe('click',function(e){e.stop();}.bindAsEventListener(this));
			}.bind(this));
			if(!togLinks.length && tog.up().hasClassName(this.options.dummyLinkClass)){
				//sets href to equivalent toggler
				tog.up().writeAttribute('href','#'+tog.identify());
				//sets close 'click' event
				//tog.up().writeAttribute('onclick','event.returnValue = false; return false;');
				tog.up().observe('click',function(e){e.stop();}.bindAsEventListener(this));
			}
//alert(tog);
//build event operations
			var togEvent = this.options.openEvent;
//alert(togEvent);
			tog.observe(togEvent,function(){
				this.showThisHideOpen(i);
			}.bind(this));
		}.bind(this));
		this.h = {}; this.w = {}; this.o = {};
		this.elements.each(function(el, i){
//add close link stuff
			var closeLink = el.down('.'+this.options.closeLinkClass);
			if(closeLink){
				//sets href to equivalent toggler
				closeLink.writeAttribute('href','#'+this.togglers[i].identify());
				//sets close 'click' event
				//closeLink.observe('click',function(){this.showThisHideOpen(-1);}.bind(this));
				closeLink.observe('click',function(e){e.stop();this.showThisHideOpen(-1);}.bindAsEventListener(this));
			}
			
			this.widths[i] = parseFloat(el.getWidth());
			
			this.now[i+1] = {};
			if(this.options.height){
				el.style.height = '0';
				el.style.overflow = 'hidden';
			}
			if(this.options.opacity){
				this.setStyle(el,'opacity',0,i);
				el.setStyle({'visibility':'visible'}); //undoes some dynamic css statements, does not appear to cause content flash
			}
			if(this.options.width){
				this.setStyle(el,'marginLeft',el.getWidth()*-1,i);
				var tempE = el.up(0);
				if(tempE && tempE.hasClassName(this.options.contentWrapperClass)){
					this.setStyle(tempE,'width',0,i);
				}
			}
		}.bind(this));
		
		var skipOpener = false;
//run cookie check routine here
		if(this.options.globalCookie){
			//check for presence existing value
			var cGlobal = Get_Cookie(this.options.globalCookie);
			if(null != cGlobal){
//alert('cookie: '+cGlobal+parseInt(cGlobal));
				if(!isNaN(cGlobal)){
					if(cGlobal == -1){
//alert('skipped');
						this.options.start = 'all-closed';
						return;
					}
					this.showThisHideOpen(cGlobal);
					skipOpener = true;
				}else{
					//try to find an item to open
					this.elements.each(function(el, i){
//alert(typeof(el) + ' :: ' + typeof(this.elements[i]));
						if(el.hasClassName(this.options.prefixCrumb + cGlobal)){
							this.showThisHideOpen(i);
							skipOpener = true;
						}
						return;
					}.bind(this));
				}
			}
//alert(cGlobal);
		}else if(this.options.localCookie){
			//check for existence of local cookie
			var cLocal = Get_Cookie(this.options.localCookie);
//alert('['+(null != cLocal)+']');
			if(null != cLocal){
				if(!isNaN(cLocal)){
					if(cLocal == -1){
//alert('skipped');
						this.options.start = 'all-closed';
						return;
					}
//alert('[A'+!isNaN(cLocal)+'A]');
					this.showThisHideOpen(cLocal);
					skipOpener = true;
				}else{
//alert('[B_elsey_B]');
					//try to find an item to open
					this.elements.each(function(el, i){
						if(el.hasClassName(this.options.prefixCrumb + cLocal)){
//alert('[C'+el.className+'C]');
							this.showThisHideOpen(i);
							skipOpener = true;
							throw $break;
						}
						return;
					}.bind(this));
				}
			}
		}
		
		//in its own loop since the above cookie checks may have failed
		if(this.options.openItem && !skipOpener){
			//look through elements for matching id value
			//if/when found, showThisHideOpen(i) with appropriate delay value
			this.elements.each(function(el, i){
				if(this.options.openItem == el.id){


					//this.showThisHideOpen(i);
					(function(i){this.showThisHideOpen(i);}).bind(this).delay(this.options.openDelay/1000,i);


					skipOpener = true;
					throw $break;
				}
				return;
			}.bind(this));
		}
//alert(skipOpener);
		if(!skipOpener){
			switch(this.options.start){
				case 'first-open':
					this.elements[0].style.height = this.elements[0].scrollHeight+'px';
					this.setStyle(this.elements[0],'opacity',1);
					
					(function(i){this.showThisHideOpen(i);}).bind(this).delay(this.options.openDelay/1000,0);
					//this.showThisHideOpen(0); //just to force routine to create cookies and such
					
					break;
				case 'open-first':
//alert('opening first item');
					(function(i){this.showThisHideOpen(i);}).bind(this).delay(this.options.openDelay/1000,0);
					//this.showThisHideOpen(0);
					break;
				
				//can add additional cses
				case 'all-closed':
//alert('all-closed: \n\t LOCAL: ' + this.options.localCookie + '\n\t GLOBAL: ' + this.options.globalCookie);
					this.showThisHideOpen(-1); //again, just to force creation of cookies and such
					break;
			}
		}else{
//alert('opener skipped for: \n\t LOCAL: ' + this.options.localCookie + '\n\t GLOBAL: ' + this.options.globalCookie);
		}
//alert('cookie: '+typeof((this.options.globalCookie)));
	},
	
	setNow: function(){
		for (var i in this.from){
			var iFrom = this.from[i];
			var iTo = this.to[i];
			var iNow = this.now[i] = {};
			for (var p in iFrom) iNow[p] = this.compute(iFrom[p], iTo[p]);
		}
	},

	custom: function(objObjs){
		if (this.timer && this.options.wait) return;
		var from = {};
		var to = {};
		for (var i in objObjs){
			var iProps = objObjs[i];
			var iFrom = from[i] = {};
			var iTo = to[i] = {};
			for (var prop in iProps){
				iFrom[prop] = iProps[prop][0];
				iTo[prop] = iProps[prop][1];
			}
		}
		return this._start(from, to);
	},

	hideThis: function(i){
		if (this.options.height){
			this.h = {'height': [this.elements[i].offsetHeight, 0]};
		}else{
			this.h = {'height': [this.elements[i].offsetHeight, this.elements[i].offsetHeight]};
		}
		//if (this.options.width) this.w = {'width': [this.elements[i].offsetWidth, 0]};
		if (this.options.width){
			//this.elements[i].setStyle({'width':this.elements[i].getWidth()+'px'});
			this.w = {'marginLeft': [parseFloat(this.elements[i].getStyle('marginLeft')),(this.elements[i].getWidth()*-1)]};
//alert(parseFloat(this.elements[i].getStyle('marginLeft')));
		}
		if (this.options.opacity) this.o = {'opacity': [this.elements[i].getOpacity(), 0]};
		//if (this.options.opacity) this.o = {'opacity': [this.now[i+1]['opacity'] || 1, 0]};
	},

	showThis: function(i){
//alert('showing: '+i);
		if (this.options.height){
			this.h = {'height': [this.elements[i].offsetHeight, this.options.fixedHeight || this.elements[i].scrollHeight]};
		}else{
			this.h = {'height': [this.elements[i].offsetHeight, this.options.fixedHeight || this.elements[i].scrollHeight]}
		}
		//if (this.options.width) this.w = {'width': [this.elements[i].offsetWidth, this.options.fixedWidth || this.elements[i].scrollWidth]};
		if (this.options.width){
			this.w = {'marginLeft': [(this.elements[i].getWidth()*-1),0]};
		}
		if (this.options.opacity) this.o = {'opacity': [this.elements[i].getOpacity(), 1]};
		//if (this.options.opacity) this.o = {'opacity': [this.now[i+1]['opacity'] || 0, 1]};
	},
	
	trigger: function(args){
		//loop through elements to try to find id value, and return i index of found value, or just return
		var settings = Object.extend({
			id:				false, //trigger by id
			index:			false, //can open by index number as well
			behavior:		'click' //'click' == default behavior, others might be: 'forceOpen', 'forceClose'
		}, args || {});
		
		//run force close, as this is not dependant on id
		if(settings.behavior == 'forceClose'){
			this.showThisHideOpen(-1);
			return;
		}
		
		
		if(settings.id === false && settings.index === false){
			//perhaps run a loop for a 'forceOpen' check that would simply open index[0]
			if(settings.behavior == 'forceOpen'){
				this.showThisHideOpen(0);
			}
			
			return false;
		}
		
		//determine index value to use
		var iToTrigger = settings.index; //take a default stance
		if(settings.id){
			this.elements.each(function(el,i){
				if(el.id == settings.id){
					iToTrigger = i;
					throw $break;
				}
			}.bind(this));
		}
		
		if(iToTrigger === false) return false; //final exit loop
		
		
		if(settings.behavior == 'click'){
			this.showThisHideOpen(iToTrigger);
		}
		if(settings.behavior == 'forceOpen'){
			var tempAllowClose = this.options.alwaysHide;
			this.options.alwaysHide = false;
			this.previousClick = 'nan';
			this.showThisHideOpen(iToTrigger);
//alert('opening; '+i);
			this.options.alwaysHide = tempAllowClose;
		}
		
		return;
	},
	
	showThisHideOpen: function(iToShow){
		this.iShowing = false;
//alert('showThisHideOpen: '+iToShow);
		if (iToShow != this.previousClick || this.options.alwaysHide){
			this.previousClick = iToShow;
			var objObjs = {};
			var err = false;
			var madeInactive = false;
			this.elements.each(function(el, i){
				this.now[i] = this.now[i] || {};
				if (i != iToShow){

//alert('xxx');
					this.hideThis(i);
				} else if (this.options.alwaysHide){
					if(this.options.height){
						if(el.offsetHeight == el.scrollHeight){
							this.hideThis(i);
							madeInactive = true;
						}else{
							this.showThis(i);
						}
					}else if(this.options.opacity){
						if(!!el.getOpacity()){
							this.hideThis(i);
							madeInactive = true;
						}else{
							this.showThis(i);
						}
					}else if(this.options.width){
//alert(el.getStyle('marginLeft'));
						if(parseFloat(el.getStyle('marginLeft')) == 0){
							this.hideThis(i);
							madeInactive = true;
						}else{
							this.showThis(i);
						}
//					}
					
//					if (el.offsetHeight == el.scrollHeight){
//alert(!!el.getOpacity());
//						if(!this.options.height && this.options.opacity){
//							if(!!el.getOpacity()){
//								this.hideThis(i);
//								madeInactive = true;
//							}else{
//								this.showThis(i);
//							}
//						}else{
//							this.hideThis(i);
//							madeInactive = true;
//						}
//					} else if (el.offsetHeight == 0){
//						this.showThis(i);
					} else {
						err = true;
					}
				} else if (this.options.wait && this.timer){

//alert('yyy');
					this.previousClick = 'nan';
					err = true;
				} else {
//alert('zzz');
					this.showThis(i);
				}
				objObjs[i+1] = Object.extend(this.h, Object.extend(this.o, this.w));
//alert(objObjs.toSource());
			}.bind(this));
//alert('iToShow: '+typeof(iToShow));


			if(madeInactive || iToShow == -1 || iToShow == null || typeof(iToShow) == undefined){
				//alert('closed accordion/toggle');
				var cValue = -1;
			}else{
				//alert('opened: '+iToShow);
				var cValue = iToShow;
				//add check to try to find a CookieCrumb value
				if(this.elements[iToShow]){
					$w(this.elements[iToShow].className).each(function(el,i){
				//alert(this.options.prefixCrumb + '\n' + el.substring(0,this.options.prefixCrumb.length) + ' :: ' + (el.substring(0,this.options.prefixCrumb.length)==this.options.prefixCrumb) + ' :: ' + el.substr(this.options.prefixCrumb.length));
						if(el.substring(0,this.options.prefixCrumb.length) == this.options.prefixCrumb){
							cValue = el.substr(this.options.prefixCrumb.length);
				//alert(cValue);
							return;
						}
					}.bind(this));
				}
			}
			
			if(this.options.globalCookie){
				//Set_Cookie(this.options.globalCookie, cValue);
				Set_Cookie({name:this.options.globalCookie,value:cValue});
			}else if(this.options.localCookie){
			//alert(document.location.pathname);
				//Set_Cookie(this.options.localCookie, cValue, null);
			//alert(cValue);
				//Set_Cookie({name:this.options.localCookie,value:cValue,path:document.location.pathname});
				Set_Cookie({name:this.options.localCookie,value:cValue});
			}


			if (err) return;
			if (!madeInactive){
				this.options.onActive.call(this, this.togglers[iToShow], iToShow);
				this.iShowing = iToShow; //this becomes available for most if not all items to draw upon
			}else{
				//update width
				this.widths[iToShow] = parseFloat(this.elements[iToShow].getWidth());
			}
			this.togglers.each(function(tog, i){
				if (i != iToShow || madeInactive) this.options.onBackground.call(this, tog, i);
			}.bind(this));
			return this.custom(objObjs);
		}
	},
	
	increase: function(){
		for (var i in this.now){
			var iNow = this.now[i];
			for (var p in iNow) this.setStyle(this.elements[parseInt(i)-1], p, iNow[p], parseInt(i)-1);
		}
	},
	
	//included from FX.BASE if/when Proto alternative cannot be found
	_start: function(from, to){
		if (!this.options.wait) this.clearTimer();
		if (this.timer) return;
		setTimeout(this.options.onStart.bind(this, this.element), 10);
		this.from = from;
		this.to = to;
		this.time = new Date().getTime();
		this.timer = setInterval(this.step.bind(this), Math.round(1000/this.options.fps));
		return this;
	},
	
	clearTimer: function(){
		clearInterval(this.timer);
		this.timer = null;
		return this;
	},
	
	step: function(){
		var time = new Date().getTime();
		if (time < this.time + this.options.duration){
			this.cTime = time - this.time;
			this.setNow();
		} else {
			setTimeout(function(el){
//alert(this.iShowing);
				if(typeof(this.iShowing) != 'undefined' && parseInt(this.iShowing)>-1 && this.elements[this.iShowing]){
					//make height auto
					this.elements[this.iShowing].setStyle({'height':'auto'});
					//make width auto
					this.elements[this.iShowing].setStyle({'width':'auto'});
					//reassign width to this.widths
					this.widths[this.iShowing] = parseFloat(this.elements[this.iShowing].getWidth());
				}
				this.options.onComplete(el);
				
			}.bind(this, this.element), 10);
			this.clearTimer();
			this.now = this.to;
		}
		this.increase();
	},
	
	compute: function(from, to){
		var change = to - from;
		var pos = this.cTime/this.options.duration;
		var per = this.options.transition(pos);
//alert('compute: '+from+' :: '+to);
		return from + (change * per);
		//return this.options.transition(this.cTime, from, change, this.options.duration);
	},
	
	setStyle: function(e, p, v, i){
		//alert([p]);
		if (p == 'opacity'){
			e.setOpacity(v);
		}else{
			if(p == 'marginLeft' || p == 'marginRight'){
				//look for and set container width value
//alert(this.from[] + ' :: ' + this.to[iNow] + ' :: ' + p);
				
				//alert(this.widths[e]);
				//alert(i + ' :: ' + this.elements[i]);
				if(typeof(i) != undefined && this.elements[i] && this.widths[i]){
					var x = this.widths[i] - Math.abs(v);
				}else{
					var x = e.getWidth() - Math.abs(v);
				}
				
				var tempE = e.up(0);
				if(tempE && tempE.hasClassName(this.options.contentWrapperClass)){
					//var x = this.widths[e] - Math.abs(v);
					tempE.setStyle({'width':x+this.options.unit});
				}
			}
			var tempObj = {};
			tempObj[p] = v + this.options.unit;
			e.setStyle(tempObj);
		}
	}
}





/* STORAGE:

document.observe('dom:loaded',function(){

	//sFXacc_jar_39_86 = new sFX_Accordion({toggle:$$('.sFXtoggle_item1'),content:$$('.sFXcontent_item1'),height:true,opacity:true,alwaysHide:true,duration:375,start:'all-closed',wait:true,openDelay:0,localCookie:'jar_39_8627_78',prefixCrumb:'cookieCrumb_'});;
//$$('.accLink').each(function(el,i){el.writeAttribute('href','#item155_61');el.writeAttribute('onclick','event.returnValue = false; return false;')});
	$('accLink_close').observe('click',function(){
	
	//alert($('item18_52').getWidth()+'px');
	
	//$('item18_52').morph('margin-left:-'+$('item18_52').getWidth()+'px');$('item195_25').morph('width:0px;')
	//"alert($('item18_52').getWidth());$('item18_52').setStyle({width:$('item18_52').getWidth()+'px'});$('item195_25').morph('width:0px;');"
	//"alert($('item18_52').getWidth());$('item18_52').setStyle({width:$('item18_52').getWidth()+'px'});$('item195_25').morph('width:0px;');"
	
	new Effect.Parallel([
		new Effect.Morph('item18_52', {
			sync: true,
			style: 'margin-left:-'+$('item18_52').getWidth()+'px'
		}), 
		new Effect.Morph('item195_25', {
			sync: true,
			style: 'width:0px'
		})
	], { 
		duration: .5
	});

	
	});
	
	
	$('accLink_open').observe('click',function(){
	
	//alert($('item18_52').getWidth()+'px');
	
	//$('item18_52').morph('margin-left:0');$('item195_25').morph('width:'+$('item18_52').getWidth()+'px')
	//"alert($('item18_52').getWidth());$('item18_52').setStyle({width:$('item18_52').getWidth()+'px'});$('item195_25').morph('width:0px;');"
	//"alert($('item18_52').getWidth());$('item18_52').setStyle({width:$('item18_52').getWidth()+'px'});$('item195_25').morph('width:0px;');"
	
	
	new Effect.Parallel([
		new Effect.Morph('item18_52', {
			sync: true,
			style: 'margin-left:0px'
		}), 
		new Effect.Morph('item195_25', {
			sync: true,
			style: 'width:'+$('item18_52').getWidth()+'px'
		})
	], { 
		duration: .5
	});
	
	});
});


*/

