var accordion = null
var currentIdx = -1;
var firstLoad = true;
var globalEvalMeta = true; 

window.onerror = function(e) {}

function getCurrentIdx() {
	var els = $$('.togglers');
	var idx = currentIdx;
	for(var i = 0; i < els.length; i++) {
		if( els[i].hasClass('active') ) { idx = i; break; }
	}
	return idx;
}

function getTogglerIdx(toggler){
	var els = $$('.togglers');
	var idx = 0;
	for(var i = 0; i < els.length; i++) {
		if( els[i].id == toggler.id ) { idx = i; break; }
	}
	return idx;
}

function getContentLoaded(idx) {
	if(idx < 0 || idx >= $$('.elements').length) return; 
	return $$('.elements')[idx].retrieve('loaded', false);
}

function setContentLoaded(idx, val) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	$$('.elements')[idx].store('loaded', val);
}

function getContentLoader(idx) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	return $$('.elements')[idx].retrieve('loader', null);
}

function setContentLoader(idx, val) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	$$('.elements')[idx].store('loader', val);
}

function getContentMeta(idx) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	return $$('.elements')[idx].retrieve('meta', '');
}

function setContentMeta(idx, val) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	$$('.elements')[idx].store('meta', val);
}

function getContentHashAction(idx) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	return $$('.elements')[idx].retrieve('hash-action', null);
}

function setContentHashAction(idx, val) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	$$('.elements')[idx].store('hash-action', val);
}

function getContentUrl(idx) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	return $$('.elements')[idx].retrieve('url', '');
}

function setContentUrl(idx, val) {
	if(idx < 0 || idx >= $$('.elements').length) return;
	$$('.elements')[idx].store('url', val);
}

function initAccordion(e) {
	
	if ( !checkLocation() ) return;
	
	currentIdx = getCurrentIdx();
	setContentLoaded(currentIdx, true);

	$('container').style.visibility = 'visible';
	
	// update the url hash
	$$('.togglers').addEvent('click', function() { updateHash( this.getElements('a')[0]); } );
	
	var initObj = {
		display: currentIdx,
		trigger: 'click',
		height: true,
		width: false,
		opacity: true,
		alwaysHide: false,
		initialDisplayFx: true,
		duration: 500
	}
	accordion = new Fx.Accordion($$('.togglers'), $$('.elements'), initObj);
	
	if( $$('#toggler-' + currentIdx + ' a')[0] != undefined ) {
		var hdl = $$('#toggler-' + currentIdx + ' a')[0].href.split('/');
		hdl = hdl[hdl.length - 2]; 
		contentScrollTo(hdl, 0, null, true);
	}
		
	accordion.addEvent('active', function(toggler, element) {

		// deactivate previous item and activate the new one
		if(currentIdx >= 0) $$('.togglers')[currentIdx].removeClass('active');
		toggler.addClass('active');
		
		// update the page title
		updateTitle(toggler.getElements('a')[0].innerHTML);
					
		// set the new index
		currentIdx = getTogglerIdx(toggler);		
		
		// start loading the content
		window.setTimeout( function () {
			try { 
				//stop pooling the url for location change
				pausePolling = true;

				// load the page and run the action stored in the hash action
				// this is done to enable hash nav				
				loadPage(currentIdx, function(idx) {
					if ( getContentHashAction(idx) != null ) {
						// this js MUST resume polling
						getContentHashAction(idx).run();
						setContentHashAction(idx, null);
					} else {
						//resume pooling the url for location change
						pausePolling = false;
					}
				} );
			} catch (e) {
				try {
					getContentLoader(idx).abort();
				} catch (e) { 
					//
				} finally {
					$$('#element-' + idx + ' .element-content')[0].innerHTML = '<div class="element-loading"></div>';
					setContentLoaded(idx, false);
					setContentLoader(idx, null);
				}
			}
		}, 600 );
	});
	
	accordion.addEvent('background', function(toggler, element) {
		// get the item's index
		idx = getTogglerIdx(toggler);
		
		// if the content is not yet loaded, clear the contents of the element content
		if( ! getContentLoaded(idx) ) { 
			$$('#element-' + idx + ' .element-content')[0].innerHTML = '<div class="element-loading"></div>';
		}
		
		// if there is an active loader abort the request and destroy the object then clear the contents
		if( getContentLoader(idx) != null ) {
			try {
				getContentLoader(idx).abort();
			} catch (e) { 
				//
			} finally {
				$$('#element-' + idx + ' .element-content')[0].innerHTML = '<div class="element-loading"></div>';
				setContentLoaded(idx, false);
				setContentLoader(idx, null);
			}
		}
	});
	
	// disable the nasty rectangle around links on ff and ie
	blurLinks();
	
	// update the behavior of links to modify the url hash
	updateLinks();
	
	// we're done loading
	firstLoad = false;
}

function updateTitle(title, part) {
	var base = document.title.split(' // ');
	document.title = ( part != undefined ? part.split('amp;').join('') + ' // ' : '') + title.split('amp;').join('') + ' // ' + base[base.length - 1];
}

function loadPage(idx, action) {
	if(action == undefined) action = function() {}; 
	if ( ! getContentLoaded(idx) ) {
		
		$$('#element-' + idx + ' .element-content')[0].innerHTML = '<div class="element-loading"></div>';
		$$('#element-' + idx + ' .element-content')[0].set('morph', { duration: 50, transition: Fx.Transitions.linear });
		$$('#element-' + idx + ' .element-content')[0].morph( { opacity: [1, 1] } );
		
		var url = getContentUrl(idx) != '' ? getContentUrl(idx) : $$('#toggler-' + idx + ' a')[0].href;
		setContentUrl(idx, '');
		
		ajaxContent = getNewXMLHttp();
		setContentLoader(idx, ajaxContent);
		
		var str = "content-only=" + sessid + "&include-accordion=false";
		ajaxContent.open("POST", url, true);
		ajaxContent.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajaxContent.onreadystatechange = function() {
			if(ajaxContent.readyState != 4) return;
			$$('#element-' + idx + ' .element-content')[0].set('morph', { duration: 300, 
				onComplete: function() {
				
					var content = ajaxContent.responseText.split('[|]');
					var text = content.length >= 2 ? content[1] : content;
					var meta = content.length >= 2 ? content[0] : '';
					
					$$('#element-' + idx + ' .element-content')[0].innerHTML = text;
	
					if(meta != '') setContentMeta(idx, meta);
					if(meta != '' && getContentHashAction(idx) == null) eval(meta);
					
					$$('#element-' + idx + ' .element-content')[0].set('morph', { duration: 300, transition: Fx.Transitions.Quad.easeInOut,
						onComplete: function() {
							if(currentIdx == idx) $$('#element-' + idx + ' .element-content img.reflect').reflect();
						} 
					} );
					$('element-' + idx).set('morph', { duration: 300, transition: Fx.Transitions.Quad.easeInOut, 
						onComplete: function() {
							if(currentIdx == idx) postLoadUpdates(idx, false);
							setContentLoaded(idx, true);
							setContentLoader(idx, null);
							action.run(idx);
						}
					} );
					
					if(currentIdx == idx) $$('#element-' + idx + ' .element-content')[0].morph({ opacity: [0, 1] });
					if(currentIdx == idx) $('element-' + idx).morph ( { height: $$('#element-' + idx + ' .element-content')[0].getSize().y } );
					if ( $$('#element-' + idx + ' .element-content .scrolling-content').length > 0 ) {
						$$('#element-' + idx + ' .element-content .scrolling-content')[0].scrollLeft = 0;
					}
					
					blurLinks();
					updateLinks( $$('.elements')[idx] );
				}
			} );
			if(currentIdx == idx) {
				$$('#element-' + idx + ' .element-content')[0].morph({opacity: [1, 0]});
			} else {
				$$('#element-' + idx + ' .element-content')[0].innerHTML = '<div class="element-loading"></div>';
				setContentLoaded(idx, false);
				setContentLoader(idx, null);
			}
		};	
		ajaxContent.send(str);
	} else {
		postLoadUpdates(idx, true);
		action.run(idx);
	}
}

function postLoadUpdates(idx, evalMeta) {
	if(globalEvalMeta == true && evalMeta == true && getContentMeta(idx) != '') {
		eval(getContentMeta(idx));
	}
	globalEvalMeta = true;
	var contentHeight = $$('#element-' + idx + ' .element-content')[0].getSize().y + ( $$('.togglers').length * $$('.togglers')[0].getSize().y );
	centerContent(contentHeight, 500);
}

function contentScrollTo(handle, idx, action, noEffect) {

	pausePolling = true;
	
	if(action == '' || action == undefined || action == null) action = function() { pausePolling = false; };
	if(noEffect == undefined || noEffect == null) noEffect = false;

	if( ! $('sc-' + handle ) || ! $$('#sc-' + handle + ' .scrolling-element')[idx] ) { pausePolling = false; return; }
	if( idx == 0 && $('sc-' + handle).scrollLeft == 0 ) { pausePolling = false; return; }
	
	galleryRestoreContent($$('#sc-' + handle + ' .scrolling-element')[idx]);
	
	var newHeight = $$('#sc-' + handle + ' .scrolling-element')[idx].getSize().y;
	var currentHeight = $('sc-' + handle).getSize().y;

	if(firstLoad && noEffect == true && idx == 0) { 
		$('sc-' + handle).scrollTo(0, 0);
		pausePolling = false;
		return;
	}
	
	// calculate duration
	var distance = Math.abs ( currentHeight - newHeight );
	if(distance > 400) {
		var speed = 1; // pixels per milisecond
		var duration = Math.round ( distance/speed );
		var transition = Fx.Transitions.linear;
	} else {
		var duration = 500;
		var transition = Fx.Transitions.Sine.easeInOut;
	}

	if(newHeight >= currentHeight) $('sc-' + handle).style.height = newHeight + 'px';
	$('element-' + currentIdx).set('morph', { duration: duration, transition: transition,
		onComplete: function() {
			if(newHeight < currentHeight) $('sc-' + handle).style.height = newHeight + 'px';
			action.run();
		}
	} ); 
	$('element-' + currentIdx).morph( { height: newHeight } );
	
	var scroll = new Fx.Scroll( $('sc-' + handle), { duration: duration, transition: transition } );
	scroll.toElement( $$('#sc-' + handle + ' .scrolling-element')[idx] );
	
	// Update the link
	var links = $$('#sm-' + handle + ' a');
	for(var i = 1; i <= links.length; i++){
		links[i - 1].className = i == idx ? 'active' : '';
	}
	
	// update the page title
	updateTitle($$('.togglers a')[currentIdx].innerHTML, idx == 0 ? undefined : links[idx - 1].innerHTML);
	
	//pausePolling = false;
}

function centerContent(targetSize, duration) {
	var scroll = new Fx.Scroll( $(document.body), { duration: duration } );
	scroll.start( 0, 0 );
	return; 
	
	if ( duration == undefined ) duration = 300;
	if ( targetSize == undefined ) { 
		targetSize = $(document.body).getScrollSize().y;
	} else {
		if ( targetSize > $(document.body).getSize().y ) {
			var scroll = new Fx.Scroll( $(document.body), { duration: duration } );
			scroll.start( 0, 0 );
			return;
		} else {
			targetSize += 205;
		}  
	}
	
	var offset = targetSize - $(document.body).getSize().y;
	if(offset <= 0) return;
	
	var scroll = new Fx.Scroll( $(document.body), { duration: duration } );
	scroll.start(0, Math.round(offset / 2) + Math.round(55/2) ); 
}

function blurLinks() {
	$$('a').addEvent('click', function() { this.blur(); } );
}

function contentLoadPage(sender, handle, item, action) {
	
	if(action == undefined) action = function() { }; 
	
	if(sender.hasClass('active') ) return false;
	
	pausePolling = true; 
	
	var url = sender.href;
	var idx = currentIdx;

	$$('#element-' + idx + ' .element-content .submenu a.active')[0].className = '';
	$$('#element-' + idx + ' .element-content .submenu a')[item - 1].className = 'active';
	
	$$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].set('morph', { duration: 500, transition: Fx.Transitions.linear,  
		onComplete: function() {
			var workingDiv = new Element( 'div', { 'class': 'element-loading', 
				'styles': { 
					'height': '200px', 'display': 'none',
					'opacity': 0, '-khtml-opacity': 0,
					'-webkit-opacity': 0, '-moz-opacity': 0,
					'filter': 'alpha(opacity=0)'
				} 
			} );
			workingDiv.set('morph', { duration: 500, transition: Fx.Transitions.linear, 
				onComplete: function() {
					ajaxContent = getNewXMLHttp();
					var str = "content-only=" + sessid + "&include-accordion=false";
					str += '&inner=true';
					ajaxContent.open("POST", url, true);
					ajaxContent.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");	    
					ajaxContent.onreadystatechange = function() {
						if(ajaxContent.readyState != 4) return; 
						
						workingDiv.set('morph', { duration: 500, transition: Fx.Transitions.linear, 
							onComplete: function () {
								workingDiv.dispose();
		
								var content = ajaxContent.responseText.split('[|]');
								var text = content.length >= 2 ? content[1] : content;
								var meta = content.length >= 2 ? content[0] : '';
								
								$$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].innerHTML = text;
								
								if(meta != '') {
									eval(meta);
								}
								
								if( idx == currentIdx ) $$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].style.display = 'block';
								$$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].set('morph', { duration: 300, 
									onComplete: function() {
										action.run();
										pausePolling = false; 
									}
								} );
								if( idx == currentIdx ) $$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].morph({opacity: [0, 1] });
									
								$('element-' + idx).set('morph', { duration: 300, transition: Fx.Transitions.Quad.easeOut } );
								if( idx == currentIdx ) $('element-' + idx).morph ( { height: $$('#element-' + idx + ' .element-content')[0].getSize().y } );
					
								var contentHeight = $$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].getSize().y + ( $$('.togglers').length * $$('.togglers')[0].getSize().y );
								if( idx == currentIdx ) centerContent(contentHeight, 500);
								
								blurLinks();
								if( idx == currentIdx ) updateLinks();
										
							} 
						} );
						workingDiv.morph( { opacity: [1, 0] } );
					};	
					ajaxContent.send(str);	
				}
			} );
			
			$$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].style.display = 'none';
			$$('#element-' + idx + ' .element-content')[0].grab(workingDiv);
			workingDiv.style.display = '';
			if( idx == currentIdx ) workingDiv.morph( { opacity: [0, 1] } );
		}
	} );
	if( idx == currentIdx ) $$('#element-' + idx + ' .element-content .ab-content-wrapper')[0].morph({opacity: [1, 0]});
}

function hoverImg(sender, hover) {
	var reflect = false;
	var parent = $(sender).getParent();
	
	if( parent.hasClass('reflect') ) {
		parent = parent.getParent();
		reflect = true;
	}
	
	var img = parent.getElements(reflect ? '.reflect img' : 'img')[0];
	if(img == undefined) return;
	if(reflect) img.unreflect();
	img.src = img.src == img.getProperty('data-bw') ? img.getProperty('data-color') : img.getProperty('data-bw');
	if(reflect) img.reflect(); 
}

function aboutReset() {
	pausePolling = true;
	
	var e = $('sm-about').getElements('a');
	var idx = 0;
	for(i = 0; i< e.length; i++) {
		if( ! e[i].hasClass('active') ) continue;
		idx = i;
	}
	if(idx != 0) contentLoadPage(e[0], 'about', 1 );
}