/* Simple Accordion Script 
 * Requires Prototype and Script.aculo.us Libraries
 * By: Brian Crescimanno <brian.crescimanno@gmail.com>
 * http://briancrescimanno.com
 * This work is licensed under the Creative Commons Attribution-Share Alike 3.0
 * http://creativecommons.org/licenses/by-sa/3.0/us/
 */

if (typeof Effect == 'undefined')
  throw("You must have the script.aculo.us library to use this accordion");

var Accordion = Class.create({

    initialize: function(id, defaultExpandedCount) {
        if(!$(id)) throw("Attempted to initialize accordion with id: "+ id + " which was not found.");
        this.accordion = $(id);
        this.options = {
            toggleClass: "accordion-toggle",
            toggleActive: "accordion-toggle-active",
            contentClass: "accordion-content"
        }
        this.contents = this.accordion.select('div.'+this.options.contentClass);
        this.isAnimating = false;
        this.maxHeight = 0;
        
        // there is a 'hidden element' (no content) which is the default current element so we can contract all elements at start
        this.hiddenElement = this.contents[this.contents.length - 1];
        this.current = defaultExpandedCount ? this.contents[defaultExpandedCount] : this.hiddenElement;
        this.targetElement = null;

        this.checkMaxHeight();
        this.initialHide();
        this.attachInitialMaxHeight();

        var clickHandler =  this.clickHandler.bindAsEventListener(this);
        this.accordion.observe('click', clickHandler);

		// preload images
        var images = [];
		for (i = 1; i < 10; i++) {
		//http://www.beyondrecruitment.co.nz
			images[images.length] = '/themes/beyondrecruitment/images/head_bg_' + i + '.gif';
			images[images.length] = '/themes/beyondrecruitment/images/head_bg_' + i + 'b.gif';
			images[images.length] = '/themes/beyondrecruitment/images/head_bg_' + i + 'c.gif';
			images[images.length] = '/themes/beyondrecruitment/images/head_bg_' + i + 'd.gif';
		}
		var img = new Image();
		for (i = 0; i < images.length; i++) {
//			console.log('preloading ' + images[i]);
			img.src = images[i];
		}
    },

    expand: function(el) {
        this.targetElement = el.next('div.'+this.options.contentClass);
        
       	if (this.current != this.targetElement)
			this.targetElement.show();
			
		this.animate();
    },

    checkMaxHeight: function() {
        for(var i=0; i<this.contents.length; i++) {
            if(this.contents[i].getHeight() > this.maxHeight) {
                this.maxHeight = this.contents[i].getHeight();
            }
        }
    },

    attachInitialMaxHeight: function() {
    
		this.current.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
        if(this.current.getHeight() != this.maxHeight) this.current.setStyle({height: this.maxHeight+"px"});
    },

	clickHandler: function(e) {
		if (!this.isAnimating)	{
			var el = e.element();
			while (el && el.hasClassName && !el.hasClassName(this.options.toggleClass)) {
				el=el.parentNode;
			}
			if(el && el.hasClassName && el.hasClassName(this.options.toggleClass)) {
				this.expand(el);
			}
		}
	},
		
    initialHide: function(){
        $('aftersectors').setStyle({ top: '0px' });
        for(var i=0; i<this.contents.length; i++){
            if(this.contents[i] != this.current) {
                this.contents[i].hide();
                this.contents[i].setStyle({height: 0});
            }
        }
    },

    animate: function() {
        var effects = new Array();
        var options = {
            sync: true,
            scaleFrom: 0,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleMode: {
                originalHeight: this.maxHeight,
                originalWidth: this.accordion.getWidth()
            },
            scaleX: false,
            scaleY: true
        };
        // only grow targetElement if it's not already shown
		if (this.current != this.targetElement) 
        	effects.push(new Effect.Scale(this.targetElement, 100, options));
        
        options = {
            sync: true,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleX: false,
            scaleY: true
        };
		// always shrink the current element
        effects.push(new Effect.Scale(this.current, 0, options));

        var myDuration = 0.75;
        this.ie_class_prev = this.ie_class;
       	this.ie_class = this.options.toggleActive + this.targetElement.id.substr(this.targetElement.id.length - 2, 2);
       	
//		try { console.log(this.ie_class + ' ' + this.ie_class_prev) } catch(e) {};

        new Effect.Parallel(effects, {
            duration: myDuration,
            fps: 35,
            queue: {
                position: 'end',
                scope: 'accordion'
            },
            beforeStart: function() {
            
                this.isAnimating = true;
                this.current.previous('div.'+this.options.toggleClass).removeClassName(this.options.toggleActive);
                this.current.previous('div.'+this.options.toggleClass).down('div').removeClassName(this.options.toggleActive);
                
                this.current.previous('div.'+this.options.toggleClass).removeClassName(this.ie_class_prev);
                this.current.previous('div.'+this.options.toggleClass).down('div').removeClassName(this.ie_class_prev);
                
//				try { console.log('removed class: ' + this.ie_class_prev + ' from: ' + this.current.id) } catch(e) {};
                
            }.bind(this),
            
            afterFinish: function() {
                if (this.current != this.targetElement) {
                	// we've opened another element
	                this.targetElement.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
	                this.targetElement.previous('div.'+this.options.toggleClass).down('div').addClassName(this.options.toggleActive);

	                this.targetElement.previous('div.'+this.options.toggleClass).addClassName(this.ie_class);
	                this.targetElement.previous('div.'+this.options.toggleClass).down('div').addClassName(this.ie_class);
	                
//					try { console.log('added class: ' + this.ie_class + ' to: ' + this.targetElement.id) } catch(e) {};

	                this.current = this.targetElement;
	            } else {
	            	// we've closed the current element
                	this.current.hide();
	            	this.current = this.hiddenElement;
	            }
                
                $('aftersectors').setStyle({top: '0px'});

                this.isAnimating = false;
                
            }.bind(this)
        });
    }

});

document.observe("dom:loaded", function(){
    accordion = new Accordion("nav-accordion");
})