//Gloval vars
var subNavLinks, triggers, elements, accordLinks, accordTriggers, accordElements, accordLhrefs, modalTrigs;
var firstPageLoad = true;

// Start getPage class to fetch ajax of iframe page 
var getPage = new Class({
	options: {
		element: null,
		updateArea: 'contentArea', // id of container that will hold new content
		triggers:[],
		iframe: false
	},
	
	initialize: function(options){
		this.setOptions(options),
		this.el = $(this.options.element),
		this.updateArea = $(this.options.updateArea) || null,
		this.iframe = this.options.iframe,
		this.triggers = this.options.triggers,
		this.buildPath(this.el)
	},
	
	buildPath: function(el){
		var url = (el.tagName.toLowerCase() == 'a')? el.href : null;
		if ($defined(url)==false) return;
		var classNameRel = el.className.split('-')[0] + " " + el.className.split('-')[1] + " " + el.className.split('-')[2] + " " + el.className.split('-')[3];
		var rel =  ($defined(el.rel))?el.rel:classNameRel;
		if (($defined(rel) && rel.indexOf("iframe") >-1) || this.iframe==true) { 
			this.getIframe(url);
			this.setFrameSize(rel);
		} else {
			this.getAjax(url);
		}
	},
	
	getIframe: function(url){
		this.updateArea.innerHTML='<iframe frameborder="0" id="contentFrame" allowtransparency="true" src=""></iframe>';
		$('contentFrame').src=url;
	},
	
	setFrameSize: function(rel){
		var contentFrame = $('contentFrame');
		if (!contentFrame || this.getFrameSize(rel).length < 1) return;
		var h = (this.getFrameSize(rel)[1] * 1)  + 15;
		var w = (this.getFrameSize(rel)[2] * 1);
		contentFrame.style.height=h +"px";
		contentFrame.style.width=w +"px";
		 return false;
	},
	
	getFrameSize: function(x){
		if(x.substring(0,4) == "size"){
			el = x.split(" ");
			return el;
		} return;
	},
	 
	getAjax: function(url){ 
		new Ajax(url, {	
				method: 'get', 
				update: this.updateArea,
				evalScripts: false,
				onComplete: (function(){
						sendContactForm();
					}).bind(this)
			}).request();
	 } 
	
})
getPage.implement(new Options, new Events); 


Element.extend({
	getPageNow: function(options){
		var el = $(this);
		return new getPage((options, {element:el}));
	}

});
// ###### end getPage Class  #######


/* ################################
 * HistoryManager
 * @version		1.0rc2
 * 
 * @see			Events, Options
 * 
 * @license		MIT License
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	2007 Author
 */
var HistoryManager = {
	options: {
		observeDelay: 100,
		stateSeparator: ';',
		iframeSrc: '/blank.html',
		onStart: Class.empty,
		onRegister: Class.empty,
		onUnregister: Class.empty,
		onStart: Class.empty,
		onUpdate: Class.empty,
		onStateChange: Class.empty,
		onObserverChange: Class.empty
	},

	dataOptions: {
		skipDefaultMatch: true,
		defaults: [],
		regexpParams: ''
	},

	initialize: function(options) {
		if (this.modules) return this;
		this.setOptions(options);
		this.modules = $H({});
		this.count = history.length;
		this.states = [];
		this.states[this.count] = this.getHash();
		this.state = null;
		return this;
	},

	start: function() {
		this.observe.periodical(this.options.observeDelay, this);
		this.started = true;
		this.observe();
		this.update();
		this.fireEvent('onStart', [this.state]);
		return this;
	},

	register: function(key, defaults, onMatch, onGenerate, regexp, options) {

		if (!this.modules) this.initialize();
		var data = $merge(this.dataOptions, options || {}, {
			defaults: defaults,
			onMatch: onMatch,
			onGenerate: onGenerate,
			regexp: regexp
		});
		data.regexp = data.regexp || key + '-([\\w_-]*)';
		if (typeof data.regexp == 'string') data.regexp = new RegExp(data.regexp, data.regexpParams);
		data.onGenerate = data.onGenerate || function(values) { return key + '-' + values[0]; };

		data.values = data.defaults.copy();
		this.modules.set(key, data);
		this.fireEvent('onUnregister', [key, data]);
		return {
			setValues: function(values) {
				return this.setValues(key, values);
			}.bind(this),
			setValue: function(index, value) {
				return this.setValue(key, index, value);
			}.bind(this),
			generate: function(values) {
				return this.generate(key, values);
			}.bind(this),
			unregister: function() {
				return this.unregister(key);
			}.bind(this)
		};
	},

	unregister: function(key) {
		this.fireEvent('onRegister', [key]);
		this.modules.remove(key);
	},

	setValues: function(key, values) {
		var data = this.modules.get(key);
		if (!data || data.values.isSimilar(values)) return this;
		data.values = values;
		this.update();
		return this;
	},

	setValue: function(key, index, value) {
		var data = this.modules.get(key);
		if (!data || data.values[index] == value) return this;
		data.values[index] = value;
		this.update();
		return this;
	},

	generate: function(key, values) {
		var data = this.modules.get(key);
		var current = data.values.copy();
		data.values = values;
		var state = this.generateState();
		data.values = current;
		return '#' + state;
	},

	observe: function() {
		if (this.timeout) return;
		var state = this.getState();
		if (this.state == state) return;
		if ((window.ie || window.webkit419) && (this.state !== null)) this.setState(state, true);
		else this.state = state;
		this.modules.each(function(data, key) {
			var bits = state.match(data.regexp);
			if (bits) {
				bits.splice(0, 1);
				bits.complement(data.defaults);
				if (!bits.isSimilar(data.defaults)) data.values = bits;
			} else data.values = data.defaults.copy();
			data.onMatch(data.values, data.defaults);
		});
		this.fireEvent('onStateChange', [state]).fireEvent('onObserverChange', [state]);
	},

	generateState: function() {
		var state = [];
		this.modules.each(function(data, key) {
			if (data.skipDefaultMatch && data.values.isSimilar(data.defaults)) return;
			state.push(data.onGenerate(data.values));
		});
		return state.join(this.options.stateSeparator);
	},

	update: function() {
		if (!this.started) return this;
		var state = this.generateState();
		if ((!this.state && !state) || (this.state == state)) return this;
		this.setState(state);
		this.fireEvent('onStateChange', [state]).fireEvent('onUpdate', [state]);
		return this;
	},

	observeTimeout: function() {
		if (this.timeout) this.timeout = $clear(this.timeout);
		else this.timeout = this.observeTimeout.delay(200, this);
	},

	getHash: function() {
		var href = top.location.href;
		var pos = href.indexOf('#') + 1;
		return (pos) ? href.substr(pos) : '';
	},

	getState: function() {
		var state = this.getHash();
		if (this.iframe) {
			var doc = this.iframe.contentWindow.document;
			if (doc && doc.body.id == 'state') {
				var istate = doc.body.innerText;
				if (this.state == state) return istate;
				this.istateOld = true;
			} else return this.istate;
		}
		if (window.webkit419 && history.length != this.count) {
			this.count = history.length;
			return $pick(this.states[this.count - 1], state);
		}
		return state;
	},

	setState: function(state, fix) {
		state = $pick(state, '');
		if (window.webkit419) {
			if (!this.form) this.form = new Element('form', {method: 'get'}).injectInside(document.body);
			this.count = history.length;
			this.states[this.count] = state;
			this.observeTimeout();
			this.form.setProperty('action', '#' + state).submit();
		} else top.location.hash = state || '#';
		if (window.ie && (!fix || this.istateOld)) {
			if (!this.iframe) {
				this.iframe = new Element('iframe', {
					src: this.options.iframeSrc,
					styles: 'visibility: hidden;'
				}).injectInside(document.body);
				this.istate = this.state;
			}
			try {
				var doc = this.iframe.contentWindow.document;
				doc.open();
				doc.write('<html><body id="state">' + state + '</body></html>');
				doc.close();
				this.istateOld = false;
			} catch(e) {};
		}
		this.state = state;
	},

	extend: $extend
};

HistoryManager.extend(Events.prototype);
HistoryManager.extend(Options.prototype);


/**
 * Extends Array with 2 helpers: isSimilar(array) and complement(array)
 * 
 */
Array.extend({
	isSimilar: function(array) {
		return (this.toString() == array.toString());
	},

	complement: function(array) {
		for (var i = 0, j = this.length; i < j; i++) this[i] = $pick(this[i], array[i] || null);
		return this;
	}
});
//############ END History Manager ##################

// ajax history function
function ajaxHistory(updateDiv , b, ind){
	var b = (!b)? false : true;
	var updateDiv = (updateDiv) ? $(updateDiv) : $('contentArea');
	if (updateDiv==null) return
	
	var ajax = true;
	var baseLocation = (window.location.href + "").split("#")[0];
	//var baseContent = updateDiv.innerHTML;
	var hrefs = accordLinks.getProperty('href') || null;
	var currentIndex = -1;
	
	var reqHistory = HistoryManager.register(
		'page-index',
		[-1], // default, page -1
		function(values) {
			ajaxUpdate(values[0]);
		},
		function(values) {
			return 'page-index(' + values[0] + ')';
		},
		/page-index\((\d+)\)/ // the regexp to match "page-index(0)"
	);
	
	if (b) ajaxUpdate(ind);
	
	function ajaxUpdate(index) { 
		var url = hrefs[index] || null;
		var el =  accordLinks[index] || null;
		var trig = accordTriggers.indexOf(el);
		currentIndex = index;
		// updating the history
		reqHistory.setValue(0, index);
		if (index < 0){ 
			if (firstPageLoad){ 
				firstPageLoad = false;
				 return;
			}
			window.location=baseLocation;
			return;
		} else {
			if (!el) return;
			start = false;
			if (ajax && accordLinks[index].className.indexOf('openWindow')<0  &&  accordLinks[index].className.indexOf('ajaxOff')<0){ 
				el.getPageNow();
			}
		}
	};
	
	accordLinks.each(function(el, i) {
		el.addEvent('click', function(e) {
			if (e) new Event(e).stop();
			
			ajaxUpdate(i);
		});
	});
	HistoryManager.start();
}
//end ajax history


//start ajax overlay class
var modalContent = new Class({
	options: {
		triggers: '.openWindow',
		container: 'container',
		waitText: 'Loading. Please wait...',
		qvOffestLeft: -150,
		qvOffestTop: -150
	},
	
	initialize: function(options){
		this.setOptions(options),
		this.triggers = $$(this.options.triggers),
		this.container = $(this.options.container) || null,
		this.waitText = this.options.waitText || "",
		this.qvOffestLeft = this.options.qvOffestLeft || 0,
		this.qvOffestTop = this.options.qvOffestTop || 0,
		this.mwin = null,
		this.ajax = null,
		this.qvOverlay = null,
		this.waiting = null,
		this.cLeft = 0,
		this.cTop = 0,
		this.pageHeight = 0;
		this.body = $(document.getElementsByTagName('body')[0]),
		this.initMwin(this.triggers)
	},
	
	initMwin: function(trigs){   
		trigs.each(function(im){
			im.addEvent('click',this.prepQvWin.bind(this));
		}, this);
	},
	
	prepQvWin: function(e){
		if (!e) var e = window.event; 
		new Event(e).stop();  
		var el1 = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null); 
		if ($type(el1).toUpperCase()=="TEXTNODE"){
			el1=e.srcElement.parentNode;
		}
 
		var el = (el1.tagName.toUpperCase()!="IMG") ? el1 : el1.parentNode;
		if (this.qvShell) this.qvShell.remove();
		this.qvShell = $(document.createElement('div'));
		this.qvShell.setAttribute('id','qvShell');
	  	this.qvShell.injectInside(this.body);
		this.winTop = $(document.createElement('div'));
		this.winTop.setAttribute('id','winTop');
	  	this.winTop.injectInside(this.qvShell);
		this.winTop.innerHTML="Close";
		this.winTop.addEvent('click',this.closeWin.bind(this));
		
		this.mwin = $(document.createElement('div'));
		this.mwin.setAttribute('id','mwin');
	  	this.mwin.injectInside(this.qvShell);
		if (el.rel){
			var rel = el.rel;
			rel = rel.split(',');
			var w = rel[0];
			if(w>0)this.qvShell.style.width="100%";
			if(w>0)this.winTop.style.width=w + "px";
			if(w>0)this.mwin.style.width=w + "px";
		}
	  	this.getAjax(el.href);
		this.buildOverlay();
	},
	
	getWinHeight: function(){
		var a = this.container.offsetHeight;
		var b = window.getHeight()+ window.getScrollTop();
		return Math.max(a, b);
	},
	
	buildOverlay: function(){
		if (this.qvOverlay) this.qvOverlay.remove();
		if (this.waiting) this.waiting.remove();
		this.qvOverlay = $(document.createElement("div")); 
		this.qvOverlay.setAttribute('id','qvOverlay'); 
	  	this.qvOverlay.injectTop(this.body);
		this.qvOverlay.style.height=this.getWinHeight() + "px";		
		var fadeInOverlayFx = new Fx.Style('qvOverlay', 'opacity', {duration: 200}).start(0,.3);
	},
	
	getAjax: function(url){ 
		if(this.ajax){if (this.ajax.url==url)return;}
		this.ajax = new Ajax(url, {	
				method: 'get', 
				update: this.mwin,
				evalScripts: true,
				autoCancel: true,
				onSuccess: this.showWin.bind(this) 
			}).request();
	 },
	 
	 showWin: function(ResponseText){	
		var fadeInFx = new Fx.Style('qvShell', 'opacity', {duration: 300}).start(0,1);
		this.ajax = null;
		this.mwin.style.background="#fff";
		sendContactForm();
	},
	
	closeWin: function(){
		var fadeOutFx = new Fx.Style('qvShell', 'opacity', {duration: 300}).start(1,0);
		var fadeOutOverlayFx = new Fx.Style('qvOverlay', 'opacity', {duration: 200}).start(.3,0);
	}
});
modalContent.implement(new Options, new Events); 
//end ajax overlay class

function sendContactForm(){ 
	if(!$('contactForm')) return;
 	var form = $('contactForm');
	form.addEvent('submit', function(e) {
		new Event(e).stop();
 
		form.send({
			onSuccess: function(){
				form.innerHTML="Thank you. Your comments have been sent.";
				form.addClass('thankyou');
			}
		});
	});
}


// sidenav accordion function
function sideNavAccordion(){
	if (iphone)return;
	//var show = ((window.location + "").indexOf('menu.php')>-1)?0:-1;
	accordNav = new Accordion(accordTriggers, accordElements, {
		alwaysHide: true,
		opacity: false,
		show: -1,
		onActive: function(toggler, element){
			element.addClass('block');
		},
		
		onBackground: function(toggler, element){
			element.removeClass('block')
		}
	}, $('sideNav'));
}

function initFunctions(){
	new modalContent({});
	HistoryManager.initialize();
	sideNavAccordion();
	ajaxHistory();
}

//############# start load on domready #####
window.addEvent('domready', function(){

	$$('a').each(function(a){a.onfocus=function(){this.blur()}}) 
	if($('contactForm')) sendContactForm();
	// create arrays for nav
	accordLinks = $$('#sideNav a');
	accordTriggers = $$('#sideNav .accordion');
	accordOffs = $$('#sideNav .accordionOff');
	accordElements = $$('#sideNav .aElements');
	accordLhrefs = accordLinks.getProperty('href');
	// close accordion when non-accord link is clicked
	accordOffs.each(function(nav){
		nav.addEvent('click', function(){
			accordNav.display(-1)
		})
	})
	// add 'highlight' class to selected nav
	accordLinks.each(function(l){
		l.addEvent('click', function(){
			accordLinks.each(function(x){x.removeClass('highlight');})
			l.addClass('highlight');
		})
	})
	
	//init functions
	if ($('footer') && accordTriggers.length>0){
		initFunctions()
	}
	else {window.onload=initFunctions}
});
//############# end load on domready #####
