// accordion.js v2.0
//
// Copyright (c) 2007 stickmanlabs
// Author: Kevin P Miller | http://www.stickmanlabs.com
// 
// Accordion is freely distributable under the terms of an MIT-style license.
//
// I don't care what you think about the file size...
//   Be a pro: 
//	    http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
//      http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files
//

/*-----------------------------------------------------------------------------------------------*/

if (typeof COOKIE == "undefined") {
    var COOKIE = {
        create : function (name,value,days) {
        	if (days) {
        		var date = new Date();
        		date.setTime(date.getTime()+(days*24*60*60*1000));
        		var expires = "; expires="+date.toGMTString();
        	} else {
                var expires = "";
            }
        	document.cookie = name+"="+value+expires+"; path=/";
        },
        read : function (name) {
        	var nameEQ = name + "=";
        	var ca = document.cookie.split(';');
        	for(var i=0;i < ca.length;i++) {
        		var c = ca[i];
        		while (c.charAt(0)==' ') c = c.substring(1,c.length);
        		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        	}
        	return null;
        },
        erase : function (name) {
        	createCookie(name,"",-1);
        }
    }
}

if (typeof Effect == 'undefined') 
	throw("accordion.js requires including script.aculo.us' effects.js library!");

var accordion = Class.create();
accordion.prototype = {

	//
	//  Setup the Variables
	//
	showAccordion : null,
	currentAccordion : null,
	duration : null,
	effects : [],
	animating : false,
	accordions : null,
    scrollBars : new Array(),
	startingHeights : new Array(),
	//  
	//  Initialize the accordions
	//
	initialize: function(div, options) {
        var container;
        if(typeof div == "string") {
            var container = $(div);
    
            if (!container) {
                throw(+" doesn't exist!");
                return false;
            }
        } else {
            container = div;
        }
        
        var resets = $$('a.reset_accordion[rel="'+container.readAttribute('id')+'"]');
        if(resets.length>0) {
            var reset = resets[0];
            reset.onclick = function() { return false; };
            reset.observe('click', this._resetAccordion.bind(this), false);        
        }
        
		this.options = Object.extend({
            lockCurrent : true,
            defaultAccordion : -1,
			resizeSpeed : 8,
			classNames : {
				toggle : 'accordion_toggle',
				toggleActive : 'accordion_toggle_active',
				content : 'accordion_content'
			},
			defaultSize : {
				height : null,
				width : null
			},
            rememberState : false,
			direction : 'vertical',
			onEvent : 'click',
            clickToLock : false,
            scrollBarOptions : null,
            showAll : false
		}, options || {});
		
		this.duration = ((11-this.options.resizeSpeed)*0.15);
        
        this.accordions = container.select('.'+this.options.classNames.toggle);
		this.startingHeights = new Array();
		
		this.accordions.each(function(accordion, acc_index) {
			Event.observe(accordion, this.options.onEvent, this.activate.bind(this, accordion, acc_index), false);
			if (this.options.onEvent == 'click') {
                accordion.childElements().each(function(acc) {
                    acc.setStyle({cursor:'pointer'});
                });
                accordion.setStyle({cursor:'pointer'});
                accordion.onclick = function() {return false;};
			}
            
            if(this.options.clickToLock && this.options.onEvent == 'mouseover') {
                Event.observe(accordion, 'click', this.lock.bind(this, accordion, acc_index), false);
            }
            
            if(this.options.scrollBarOptions) {
                this.options.scrollBarOptions.containerHeight = this.options.defaultSize.height;                
                this.scrollBars[acc_index] = new Scrollable(accordion.next(0), this.options.scrollBarOptions);

                if(this.scrollBars[acc_index].scrollBar) {                    
                   this.scrollBars[acc_index].scrollBar.setStyle({display:'none'});
                }
			}
            var options = $H({});
            
            if(this.options.showAll && this.options.startingSize) {
                options.update({height:this.options.startingSize.height + "px"});
            } else if(this.options.defaultSize.height) {
                options.update({height:this.options.defaultSize.height + "px"});
            }
			
			var mod = accordion.next();
			var startingHeight = mod.getHeight();
			
			this.startingHeights.push(startingHeight);
			
            if(!this.options.showAll) {
                if (this.options.direction == 'horizontal') {
                    options.update({width: '0px'});
                } else {
                    options.update({height: '0px'});
                } 
                options.update({display: 'none'});
            }
            
			//this.currentAccordion = $(accordion.next(0)).setStyle(options.toObject());			
			$(accordion.next(0)).setStyle(options.toObject());			
		}.bind(this));
        
        this.cookieName = div+'.'+this.options.classNames.toggle +'_state';
        
        var acc_state = COOKIE.read(this.cookieName);
        if(this.options.rememberState && acc_state) {
            this.activate(container.select('.'+this.options.classNames.toggle)[acc_state], acc_state);
        }else if (this.options.defaultAccordion > -1) {
            this.activate(container.select('.'+this.options.classNames.toggle)[this.options.defaultAccordion],this.options.defaultAccordion);
        }
	},
	
    lock : function(accordion, acc_index) {
        if(accordion.hasClassName('locked')) {
            accordion.removeClassName('locked');
        } else if(accordion.hasClassName('opened')) {
            accordion.addClassName('locked');
        }
    },
    
	//
	//  Activate an accordion
	//
	activate : function(accordion, acc_index) {
        if(accordion.hasClassName('locked')) return false;
		if (this.animating) {
			return false;
		}
        
        if(this.options.lockCurrent && accordion.next(0) == this.currentAccordion) {
            return false;
        }
        
        if (acc_index!=null && this.options.rememberState) {
            COOKIE.create(this.cookieName, acc_index, 10);
        }
                
		this.effects = [];
	
		this.currentAccordion = $(accordion.next(0));

		this.currentAccordion.setStyle({
			display:'block'
		});		
		
		this.currentAccordion.previous(0).addClassName(this.options.classNames.toggleActive);

		if (this.options.direction == 'horizontal') {
			this.scaling = $H({
				scaleX: true,
				scaleY: false
			});
		} else {
			this.scaling = $H({
				scaleX: false,
				scaleY: true
			});			
		}
        
		if (this.currentAccordion == this.showAccordion) {
		  this.deactivate();
		} else {
		  this._handleAccordion(acc_index);
		}
	},
	// 
	// Deactivate an active accordion
	//
	deactivate : function() {
		var options = $H({
            duration: this.duration,
			scaleContent: false,
			transition: Effect.Transitions.sinoidal,
			queue: {
				position: 'end', 
				scope: 'accordionAnimation'
			},
			scaleMode: { 
				originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : this.currentAccordion.scrollHeight,
				originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : this.currentAccordion.scrollWidth
			},
			afterFinish: function() {
				this.showAccordion.setStyle({
                    display: 'none'
                });
				this.showAccordion = null;
				this.animating = false;
			}.bind(this)
		});    
        options.update(this.scaling);
        
        this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);    
        new Effect.Scale(this.showAccordion, 0, options.toObject());
	},

    _resetAccordion : function() {
        if(this.options.showAll) {
			
        	for(var i = 0; i < this.accordions.length; i++) {
			
				var startingHeight;
				if(typeof this.options.startingSize != "undefined") {				
					startingHeight = this.options.startingSize.height;
				} else {
					startingHeight =  this.startingHeights[i];
				}
                
				
				var acc = this.accordions[i].next(0);
                this.accordions[i].removeClassName('opened');
                this.accordions[i].removeClassName('locked');
                var options = $H({
        			sync: true,
        			scaleFrom: (acc.getHeight()/startingHeight) * 100,
        			scaleContent: false,
        			transition: Effect.Transitions.sinoidal,
        			scaleMode: { 
        				originalHeight: startingHeight
        			}
        		});
				                
        		options.update(this.scaling);
        		
        		this.effects.push(
        			new Effect.Scale(acc, 100, options.toObject())
        		);
            }

            new Effect.Parallel(this.effects, {
                duration: this.duration,
                queue: {
                    position: 'end', 
                    scope: 'accordionAnimation'
                },
                beforeStart: function(acc) {
                    acc.setStyle({display:'block'});
                    this.animating = true;
                }.bind(this, acc),
                afterFinish: function(acc, acc_index) {
                    this.animating = false;				
                }.bind(this, acc)
            });
            this.currentAccordion = null;
            this.showAccordion = null;
            COOKIE.erase(this.cookieName);       
        }
    },
    
  //
  // Handle the open/close actions of the accordion
  //
	_handleAccordion : function(acc_index) {
        var originalHeight = this.options.defaultSize.height ? this.options.defaultSize.height : this.startingHeights[acc_index];
        var originalWidth = this.options.defaultSize.width ? this.options.defaultSize.width : this.currentAccordion.scrollWidth;
        

				
		var options = $H({
			sync: true,
			scaleFrom: (this.currentAccordion.getHeight() / originalHeight) * 100,
			scaleContent: false,
			transition: Effect.Transitions.sinoidal,
			scaleMode: { 
				originalHeight: originalHeight,
				originalWidth: originalWidth
			}
		});
        
		options.update(this.scaling);
		this.effects.push(
			new Effect.Scale(this.currentAccordion, 100, options.toObject())
		);

        options = $H({
            sync: true,  
            scaleContent: false,
            transition: Effect.Transitions.sinoidal
        });
        options.update(this.scaling);

        
        for(var i=0;i<this.accordions.length;i++) {
            if(this.accordions[i].next(0) != this.currentAccordion && !this.accordions[i].hasClassName('locked')) {
                this.accordions[i].removeClassName(this.options.classNames.toggleActive);
				
				var currentHeight = this.accordions[i].next().getHeight();
				if(currentHeight > 0) this.startingHeights[i] = currentHeight;
				
                this.effects.push(new Effect.Scale(this.accordions[i].next(0), 0, options.toObject()));		
            }
        }
        
		/*if (this.showAccordion) {
			this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
			
 			options = $H({
				sync: true,
				scaleContent: false,
				transition: Effect.Transitions.sinoidal
			});
			options.update(this.scaling);
			
			this.effects.push(new Effect.Scale(this.showAccordion, 0, options.toObject()));		
		}*/
		
        new Effect.Parallel(this.effects, {
			duration: this.duration, 
			queue: {
				position: 'end', 
				scope: 'accordionAnimation'
			},
			beforeStart: function() {
				this.animating = true;
			}.bind(this),
			afterFinish: function(acc_index) {
				if (this.showAccordion && !this.showAccordion.previous(0).hasClassName('locked')) {
					this.showAccordion.setStyle({
                        height: '0px',
						display: 'none'
					});	
				}
				$(this.currentAccordion).setStyle({height: originalHeight,display:'block'});
 				this.showAccordion = this.currentAccordion;
				this.animating = false;
				
				if(this.scrollBars[acc_index].scrollBar) {
					this.scrollBars[acc_index].update();
				}
			}.bind(this, acc_index)
		});
	}
}
	