// Falls Festival 2009 [BETA] - Thats right, if it breaks then we fall back to the "but hey, it's a beta" excuse
// so it begins...
var defaultPage = 'home';
var allowedRegions = ['lorne', 'marionbay'];
var defaultRegion = allowedRegions[0];
var currentMain;
var currentSub;
var domdom = false;
var pageNotFound = false;
var showBoat = false;

// handle region switching
// called from flash
function regionSwitch(region, forceReload) {
	var oldRegion = $('#currentRegion').attr('value');
	$('#currentRegion').attr('value', region);
	
	// update region hash -
	$.each($("a[rel='history']"), function (i, n) {
		var oldRef = $(this).attr('href');
		oldRef = oldRef.split('-');
		$(this).attr('href', oldRef[0] + '-' + region);
	}); 
	
	// force reload when changing regions to updated content to other region
	if (forceReload && oldRegion != region) {
		var url = document.location.toString();
		var hash = url.split('#')[1];
		if ($.browser.msie) {
			// ie 6 hates special chars... just encase	
			hash = encodeURIComponent(hash);
		}
		hash = hash.replace('-' + oldRegion, '');
		$.historyLoad(hash);
	}
}

// handle menu selection
function menuSelect(obj, hash) {
	var currentRegion = $('#currentRegion').attr('value');
	
	
	// deselect previous and select current
	$("a[rel='history']").removeClass('selected');
	
	// selector can be passed name or the object
	if(typeof(obj) != 'object') {
		obj = $(obj);
	}
	
	/* NOTE: depreciated - it just didn't work scotty!
	// if the button is not visible then its a sub item
	// need to show the sub menu and select the parent
	if(!obj.is(':visible')) {
		var parentButton = '#' + $(obj).parent().attr('rel');
		$(obj).closest('.subnav-btn-wrapper').show();
		
		// set current button
		$(parentButton).addClass('selected');
	} else {
		// hide subnavs
		if($(obj).attr('class') != 'btn-subnav') {
			$('.subnav-btn-wrapper').hide();
		}
		
		if($(obj).attr('class') != 'btn-mainnav') {
			$('.subnav-btn-wrapper').hide();
		}
	}*/
	
	if($(obj).attr('class') == 'btn-mainnav') {
		var subSelector = '#sub-' + hash.replace('-' + currentRegion, '');
		$('.subnav-btn-wrapper').hide();
		
		// set current button
		currentMain =  hash.replace('-' + currentRegion, '');
		
		// select current
		obj.addClass('selected');
		
		// show teh submenu
		$(subSelector).show();
	}
	
	if($(obj).attr('class') == 'btn-subnav') {
		var parentButton = '#' + $(obj).parent().attr('rel');
		$(obj).closest('.subnav-btn-wrapper').show();
		$(parentButton).addClass('selected');
		obj.addClass('selected');
	}
	
}

// sets no selected items
function resetMenu() {
	$("a[rel='history']").removeClass('selected');
	$('.subnav-btn-wrapper').hide();
	pageNotFound = false;
	currentMain = null;
	currentSub = null;
	$.unblockUI();
}

// page loaded, hide loading and inject html
function showPage(html) {
	$('#content').html(html);
	
	if(pageNotFound === true) {
		resetMenu();
		return;
	}

	// append socal icons to page
	if(currentMain != 'history') {
		$('#content').append($('#social').clone().css('display', 'block'));
	}
	
	if(domdom) {
		// fix navigation after request
		var loc = document.location.toString();
		if (loc.match('#')) {
			var urihash = loc.split('#')[1];
			if ($.browser.msie) {
				 // ie 6 hates special chars... just encase
				urihash = encodeURIComponent(urihash);
			}
		} else {
			return;	
		}
		
		// select the sucker
		var obj = urihash.split('-')[0];
		currentMain =  obj;
		menuSelect('#' + obj, obj);
		
		if(currentMain == 'history') {
			$('#social').hide();
		}
		
		// conditional check for region to show boat for mb and shuttle bus for lorne
		if(showBoat) {
			$('#lorne_shuttle_bus').css('display', 'none');
			$('#boat').css('display', 'block');
			
			// if they switch region while on shuttle load boat page 
			if(obj == 'lorne_shuttle_bus') {
				$.historyLoad('boat');
				return;
			}
			
		} else {
			$('#lorne_shuttle_bus').css('display', 'block');
			$('#boat').css('display', 'none');
			
			// if they switch region while on boat load shuttle page 
			if(obj == 'boat') {
				$.historyLoad('lorne_shuttle_bus');
				return;
			}
		}
	}

	$.unblockUI();
}

// before we load a page, show laoding and stuff
function loadPage(hash) {
	var currentRegion = $('#currentRegion').attr('value');
	
	$.blockUI({ 
		message: $('div#pageload'),
		fadeIn: 0, 
		css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: 'transparent'
        },
		overlayCSS: {
			backgroundColor: '#f8f1e3',
			opacity: 0.95
		}
	});
	
	// conditional check for region to show boat for mb and shuttle bus for lorne
	// showBoat is acted up in the showPage();
	var parentButton = $('#' + hash).parent().attr('rel');
	if((hash == 'getting_there' || parentButton == 'getting_there') && currentRegion == 'lorne') {
		showBoat = false;
	} else {
		showBoat = true;
	}
}

// yar.. like the php thingy
function inArray(string, array) {
	var found = false;
	for (var i = 0; i < array.length; i++) {
		if (string == array[i]) {
			found = true;
			break;
		}
	}
	return found;
}

// ajax page load
function loadAjaxPage(pageURL, currentRegion, hash) {
	// current region may only equal lorne or marionbay at this point
	if (inArray(currentRegion, allowedRegions) === false) {
		pageURL = 'pages/404.php';
		pageNotFound = true;
	}
	
	// last min hardcoded auto redirects for pages with no landing
	// also see menuSelect for manual setting of currentMain
	switch(hash) {
		case 'music':
			$("a[rel='history']").removeClass('selected');
			$('.subnav-btn-wrapper').hide();
			$.historyLoad('performers');
			return;
		break;
		case 'art':
			$("a[rel='history']").removeClass('selected');
			$('.subnav-btn-wrapper').hide();
			$.historyLoad('comedy');
			return;	
		break;
		case 'getting_there':
			$("a[rel='history']").removeClass('selected');
			$('.subnav-btn-wrapper').hide();
			$.historyLoad('plane');
			return;
		break;
		case 'heart_and_soul':
			$("a[rel='history']").removeClass('selected');
			$('.subnav-btn-wrapper').hide();
			$.historyLoad('the_team');
			return;
		break;
		case 'information':
			$("a[rel='history']").removeClass('selected');
			$('.subnav-btn-wrapper').hide();
			$.historyLoad('the_venue');
			return;
		break;
	}
		
	$.ajax({
		type: 'get',
		url: pageURL,
		data: 'region=' + currentRegion + '&hash=' + hash,
		dataType: 'html',
		beforeSend: function () {
			loadPage(hash);
		},
		success: function (html) {
			showPage(html);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			loadAjaxPage(null, null, null); // 404
		}
	});
}

// handle page load calls for the history plugin
function pageLoad(hash) {
	if (hash) {
		// ie 6 hates special chars... just encase
		if($.browser.msie) {
			hash = encodeURIComponent(hash);
		}
		var currentRegion = $('#currentRegion').attr('value'); // update region value if changed
		var regionSeg = hash.split('-');
		if (regionSeg[1] === undefined) {
			hash += '-' + currentRegion;
			$.historyLoad(hash); // rehash with defaut region
			return; // avoid double load
		} else {
			if (regionSeg[1] != currentRegion) {
				$('#currentRegion').attr('value', regionSeg[1]);
				regionSwitch(regionSeg[1], false);
			}
		}
		currentRegion = $('#currentRegion').attr('value');
		hash = hash.replace('-' + currentRegion, '');
		
		
		
		var pageURL = 'pages/' + hash + '.php';
		loadAjaxPage(pageURL, currentRegion, hash);
	} else { 
		// hash fail, we should always have one
		pageNotFound = true;
		loadAjaxPage('pages/404.php', currentRegion, hash);
	}
}

// call flash function to updated selected region
function updateFlashHeader(region) {
	var flashName = "header";
	var flashMovie = (window[flashName]) ? window[flashName] : document[flashName];
	if (flashMovie) {
		flashMovie.toActionScript(region);
	}
}

/* NOTE: depreciated - menuSelect will handle actions for both
// handle submenu selection
function submenuSelect(obj, hash) {
	var currentRegion = $('#currentRegion').attr('value');
	
	// set current sub button
	currentSub =  hash.replace('-' + currentRegion, '');
	
	// hide subnavs
	//$('.subnav-btn-wrapper').hide();
	
	// deselect previous and select current
	$('.subnav-btn-align a').removeClass('selected');
	obj.addClass('selected');
}*/



// dom ready ... set us up the bomb DOOF DOOF DOOF
$(document).ready(function () { 
	// init history plugin
	$.historyInit(pageLoad);
	domdom = true;
	
	// inital dom page laod
	var initURL = document.location.toString();
	if (initURL.match('#')) {
		initURL = document.location.toString();
		if (initURL.match('#')) { 
			// 2. check the hash for a region, if none then we set lorne to default
			var initHash = initURL.split('#')[1];
			if ($.browser.msie) {
				 // ie 6 hates special chars... just encase
				initHash = encodeURIComponent(initHash);
			}
			var initRegion = initHash.split('-');
			if (initRegion[1] === undefined) {
				initHash += '-lorne';
				regionSwitch('lorne', false);
				$.historyLoad(initHash);
			} else {
				// set current main nav on init
				currentMain = initRegion[0];
				regionSwitch(initRegion[1], false);
			}
		} else {
			regionSwitch('lorne', false);
			$.historyLoad(defaultPage + '-' + defaultRegion);
		}
	} else {
		regionSwitch('lorne', false);
		$.historyLoad(defaultPage + '-' + defaultRegion);
	}						  
	
	// set click event for navigation
	$("a[rel='history']").click(function () { 
		// no reloading current page
		if(currentMain == this.id || currentSub == this.id) {
			return false;
		}
		
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
	
		// avoid re-click on hardcoded no land pages pages pages...
		var geturl = document.location.toString();
		var currhash = geturl.split('#')[1];
		var hashkill = currhash.replace('-' + $('#currentRegion').attr('value'), '');
		if(hashkill == 'performers' && this.id == 'music')
			return false;
		if(hashkill == 'comedy' && this.id == 'art')
			return false;
		if(hashkill == 'road_trip' && this.id == 'getting_there')
			return false;
		if(hashkill == 'the_team' && this.id == 'heart_and_soul')
			return false;
		if(hashkill == 'the_venue' && this.id == 'information')
			return false;
		
		/* NOTE: depreciated - moved after page load to ensure correct selection on inital load and returning visitors
		// menu actions
		var objClass = $(this).attr('class');
		if(objClass == 'btn-mainnav') {
			menuSelect($(this), hash);
		}
		// submenu actions
		if(objClass == 'btn-subnav') {
			submenuSelect($(this), hash);
		}*/
			
		$.historyLoad(hash);
		return false;
	});
		
});