var currentLocation = '';
var hashInterval = null;
var pausePolling = true;
var pollingInterval = 100;

var ie = navigator.appVersion.split(';')[1].indexOf('MSIE 8') == -1 && navigator.appVersion.split(';')[1].indexOf('MSIE') >= 0;

if(ie) {
	window.addEvent('domready', function() { 
		var item = new Element('iframe', {
			'id': 'position',
			'src': '/location.php?path=' + escape(window.location.hash.replace('#','')),
			'styles': {
				'display': 'none',
				'position': 'absolute',
				'top': 0,
				'left': 0,
				'width': '400px',
				'height': '100px'
			}
		});
		$(document.body).grab(item);
	});
}

window.addEvent('domready', function() { window.setInterval( contentDispatch, pollingInterval ); });

function tracePollingStatus(text) {
	//$(window).status = "Poling: " + text;
}

function getIdxByHash(hash) {
	if(hash == '') return -1;
	var base = window.location.protocol + '//' + window.location.hostname + '/';
	var els = $$('.togglers');
	var idx = -1;
	for(var i = 0; i < els.length; i++) {
		if( els[i].getElements('a')[0] == undefined ) continue;
		if( els[i].getElements('a')[0].href.replace(base, '').indexOf(hash) == 0 ) { idx = i; break; }
	}
	return idx;
}

function updateLinks(container) {
	if(container == undefined) {
		elements = $$('a');
	} else {
		elements = $(container).getElements('a');
	}
	elements.addEvent('click', function() { updateHash(this); } );
}

function updateHashText(hash) {
	window.location.hash = hash;
	if(ie) $('position').src= '/location.php?path=' + escape(hash);
}

function updateCurrentLocation(hash) {
	currentLocation = hash;
}

function updateHash(sender){
	if(sender.href == undefined) return;
	pausePolling = true;
	var base = window.location.protocol + '//' + window.location.hostname + '/';
	if( sender.href.replace(base, '').indexOf('.') > 0 ) return;
	var hash = sender.href.replace(base, '').substr(0, sender.href.replace(base, '').length - 1);
	updateHashText(hash);
	updateCurrentLocation(hash);
	pausePolling = false;
	analyticsTrack( '/' + hash );
}

function checkLocation() {
	if(window.location.pathname == '/') return true;
	if(window.location.pathname == '/index.php') {
		//alert('asdasd');
		window.location.pathname = '/';
		return true;
	}
	var hash = window.location.pathname;
	hash = hash.substr(1, hash.length - 1);
	hash = hash.split('/');
	if(hash[hash.length - 1] == '') hash.pop();
	hash = hash.join('/');
	window.location.href = window.location.protocol + '//' + window.location.hostname + '/#' + hash;
	return false; 
}

function analyticsTrack(url) {
	if(_gaq) {
		//alert("trackPageView: " + url);
		_gaq.push(['_trackPageview', url]);
	}
}

function contentDispatch() {

	if(pausePolling == true) {
		tracePollingStatus('paused');
		return;
	}
	
	var locationChanged = currentLocation == ( ie ? unescape($('position').src.replace('/location.php?path=','')) : window.location.hash.replace('#','') );
	if(locationChanged) {
		if(ie && window.location.hash.replace('#','') != currentLocation) window.location.hash = currentLocation;	
		tracePollingStatus('running (no change detected)');
		return;
	}

	tracePollingStatus('running ' + currentLocation + ' -> ' + window.location.hash.replace('#'));
	
	// stop polling while we processs so there's no overlapping
	pausePolling = true;

	// parse the hash	
	var params = window.location.hash.replace('#','').split('/');

	// determine current accordion section to load
	var idx = getIdxByHash(params[0]);
	
	// update the current location to the new hash
	updateCurrentLocation(params.join('/'));
	
	// track the page view
	analyticsTrack('/' + params.join('/'));
	
	var hashAction = function() { pausePolling = false; }
	
	switch(params[0]) {
		
		case '':
			hashAction = function() { 
				$$('.togglers')[currentIdx].removeClass('active');
				$$('.elements')[currentIdx].removeClass('active');
				currentIdx = -1;
				pausePolling = false; 
			}
			break;
			
		case 'artwork':
		case 'photography':
			hashAction = function() {
				var navSection = getSubmenuSectionIdx(idx, params[1]);
				
				switch(params.length) {
				
					case 4:							// an image in a series is opend in the popup
					case 3:							// either the content of a series or a single image in popup
						
						var action = function() { pausePolling = false; };
						
						// The gallery we have to display
						var galleryId = galleryGetIdFromHash( params.join('/') );
						if (galleryId != 0) {
							if ( galleryIsSeries(params.join('/')) ) {
								action = function() {
									var insideSeries = $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-contents>.thumbs').length == 1;
									if(insideSeries) {
										
										var galleryLoaded = $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-contents #thumbs-' + galleryId).length == 1;
										if(galleryLoaded) {
											if ( params.length == 4 ) {
												if ( overlay != null ) {
													var overlayIdx = overlayGetIdxByHash(params.join('/'));
													overlayScrollToIndex(overlayIdx, function () { pausePolling = false; } );
												} else {
													var overlayElements = $('thumbs-' + galleryId).getElements('.image a');
													var overlayIdx = parseInt(params[3]) - 1;
													if(overlayIdx >= overlayElements.length || overlayIdx <= 0) overlayIdx = 0; 
													overlaySlideShow( overlayElements[overlayIdx], function() { pausePolling = false; } );
												}
											} else {
												pausePolling = false;
											}
										} else {
											var sender = $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-description div a')[0];
											var currentGalleryId = parseInt( $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-contents>.thumbs')[0].id.split('-')[1] );
											var categoryId = parseInt( $$('.elements')[idx].getElements('.submenu a')[navSection.next - 1].getProperty('rel').split('-')[1]);
											galleryCategMain(sender, currentGalleryId, categoryId, function() { 
												galleryThumbs( $('gs-' + galleryId).getElements('a')[0], galleryId, 0, function() { 
													if ( params.length == 4 ) {
														if ( overlay != null ) {
															var overlayIdx = overlayGetIdxByHash(params.join('/'));
															overlayScrollToIndex(overlayIdx, function () { pausePolling = false; } );
														} else {
															var overlayElements = $('thumbs-' + galleryId).getElements('.image a');
															var overlayIdx = parseInt(params[3]) - 1;
															if(overlayIdx >= overlayElements.length || overlayIdx <= 0) overlayIdx = 0; 
															overlaySlideShow( overlayElements[overlayIdx], function() { pausePolling = false; } );
														}
													} else {
														pausePolling = false;
													}
												} );		 
											} );
										}
									} else {
										galleryThumbs( $('gs-' + galleryId).getElements('a')[0], galleryId, 0, function() {
											if ( params.length == 4 ) {
												if ( overlay != null ) {
													var overlayIdx = overlayGetIdxByHash(params.join('/'));
													overlayScrollToIndex(overlayIdx, function () { pausePolling = false; } );
												} else {
													var overlayElements = $('thumbs-' + galleryId).getElements('.image a');
													var overlayIdx = parseInt(params[3]) - 1;
													if(overlayIdx >= overlayElements.length || overlayIdx <= 0) overlayIdx = 0; 
													overlaySlideShow( overlayElements[overlayIdx], function() { pausePolling = false; } );
												}
											} else {
												pausePolling = false;
											}									
										} );
									}
								};
							} else {
								action = function() {
									var galleryId = galleryGetIdFromHash(params.join('/'));
									if ( overlay != null ) {
										var overlayIdx = overlayGetIdxByHash(params.join('/'));
										overlayScrollToIndex(overlayIdx, function () { pausePolling = false; } );
									} else {
										overlaySlideShow( $('thumbs-' + galleryId).getElements('.image a')[0], function() { pausePolling = false; } );
									}
								};
							}
						}
						if( navSection.next == navSection.current ) {
							action.run();
						} else {
							if(overlay != null) {
								overlayHide( function() { contentScrollTo(params[0], navSection.next, action); } );
							} else {
								contentScrollTo(params[0], navSection.next, action);
							}
						}
						
						break;
						
					default:
						if( navSection.next == navSection.current ) {
							var insideSeries = $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-contents>.thumbs').length == 1;
							if(insideSeries) {
								var sender = $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-description div a')[0];
								var galleryId = parseInt( $$('.elements')[idx].getElements('.scrolling-element')[navSection.next].getElements('.folder-contents>.thumbs')[0].id.split('-')[1] );
								var categoryId = parseInt( $$('.elements')[idx].getElements('.submenu a')[navSection.next - 1].getProperty('rel').split('-')[1]);
								galleryCategMain(sender, galleryId, categoryId, function() { pausePolling = false; } );
							} else {
								pausePolling = false;
							}
						} else {
							contentScrollTo(params[0], navSection.next, function() { pausePolling = false; } );
						}
						break;
				}
			}
			break;
		
		
		
		case 'books':
			break;
		
		
		case 'about':
			if (idx != currentIdx && ! getContentLoaded(idx) ) {
				setContentUrl(idx, '/' + params.join('/') + '/');
				hashAction = function() {
					if(params[1] != undefined) faqInit();
					pausePolling = false;
				}
			} else {
				hashAction = function() {
					var navSection = getSubmenuSectionIdx(idx, params[1]);
					
					navSection.next = Math.max(navSection.next, 1);
					navSection.next = Math.min(navSection.next, $$('.elements')[idx].getElements('.submenu a').length);
					
					if( navSection.next == navSection.current ) {
						pausePolling = false;
						return;
					}
					contentLoadPage( $$('.elements')[idx].getElements('.submenu a')[navSection.next - 1], params[0], navSection.next);
				}
			}
			break;
			
			
		case 'news':
			if (idx != currentIdx && ! getContentLoaded(idx) ) {
				setContentUrl(idx, '/' + params.join('/') + '/');
				hashAction = function() {
					eval(getContentMeta(idx));
					pausePolling = false;
				}
			} else {
				hashAction = function() {
					var newsId = 0;
					if ( params[1] != undefined) {
						newsId = newsGetIdByHandle(params[1]);
					} else {
						newsId = newsGetLatestId();
					}
					
					if(newsId == 0 || newsId == newsGetActiveId() ) {
						pausePolling = false;
						return;
					} else {
						newsShow( newsId, function() { pausePolling = false; } );
					}
				}
			}
			break;
		
		
		
		default:
			break;
	}

	var doAction = function() {
		if(currentIdx == idx) {
			hashAction.run();
		} else {
			// show the selected accordion section
			if( idx != -1 ) {
				setContentHashAction(idx, hashAction);
			} else {
				hashAction.run();
			}
			accordion.display(idx);
		}
	}
	
	// prevent execution of stored tasks (such as returning to the first section in scrolling pages)
	globalEvalMeta = false;
	
	// if there is an overlay present, and we are not in the series close it 
	if( overlay != null && ( params.length < 3 || ( params.length == 3 && galleryIsSeries( params.join('/') ) ) ) ) {
		overlayHide(doAction, false);
	} else {
		doAction.run();
	}
}


function getSubmenuSectionIdx(idx, param) {
	var sectionIdx = 0;
	var activeSectionIdx = 0;
	
	// the submenu items 
	var items = $$('.elements')[idx].getElements('.submenu a');
	
	// determine the active section
	for(var i = 0; i < items.length; i++) {
		var section =  $$('.elements')[idx].getElements('.submenu a')[i];
		if( section.hasClass('active') ) {
			activeSectionIdx = i + 1;
			break;
		}
	}
	
	// determine the section we have to navigate to
	if( param != undefined ) {
		for(var i = 0; i < items.length; i++) {
			var section =  $$('.elements')[idx].getElements('.submenu a')[i];
			if(section.href.indexOf(param) != section.href.length - param.length - 1) continue;
			sectionIdx = i + 1; 
		}
	}
	
	return { next: sectionIdx, current: activeSectionIdx };
}