var CACHED_PAGES=Array();
var LAST_LOAD='';

$(document).ready(function() {


// Fade in hidden content to avoid flash of unstyled content
	$('div.content').fadeIn();
	

// Google Analytics - track AJAX content
	$('a[rel*=address]').click(function() {
		var trackUrl = $(this).attr('href');
		pageTracker._trackPageview(trackUrl);
	});


// Set up section/wrapper widths	
	var winWidth = $(window).width();
	var numSections = $('div.section').size();
	var wrapWidth = winWidth * numSections;
	
	$('div.section').width(winWidth);
	$('#wrapper').width(wrapWidth);
	
	
// Set hashtag to home if none are defined
	if ( window.location.hash == '' ) {
		window.location.hash = "#/home";
	}


// Scrolls to correct section if window is resized
	resetWindow(0,0);
	

// When URL changes, make appropriate AJAX calls 
	$.address.change(function(event) { resetWindow(1,500); });

	function resetWindow(doLoad,scrollSpeed) {
		var initialRawURL=$.address.value();
		var initialUrl = initialRawURL.split('/');
		var slugName = '';
		for (i=1;i<initialUrl.length;i++) slugName+=((slugName=='')?'':'/')+initialUrl[i];

		if (doLoad) {
			if (slugName=='') return false;
			if (initialRawURL==LAST_LOAD) return false;
			LAST_LOAD=initialRawURL;
		}

		var sectionName='';
		var As=$("ul#nav a").filter(function(idx) {
			if ($(this).attr('href')==("/pages/"+slugName)) {
				if (slugName.indexOf('/')>=0) sectionName=$(this).parent().parent().parent().attr("class");
				else sectionName=$(this).parent().attr("class");
				return 1;
			}
			return 0;
		});

		var performerInfo=0;
		if (sectionName=='') {
			if (slugName.match(/^home/)) sectionName="home";
			else if (slugName.match(/^performerInfo/)) {
				performerInfo=1;
				sectionName="performers";
			}
			else sectionName="general";
		}
		$.scrollTo( $('#'+sectionName), scrollSpeed );

		if (doLoad) {
			if (CACHED_PAGES[slugName]) $('#'+sectionName).html(CACHED_PAGES[slugName]);
			else {
				var url="/pages/"+slugName+"?ajax=1";
				if (performerInfo) url=slugName+"?ajax=1";

				$('#'+sectionName).load(url+' div.content',function(responseText,status,o) {
					CACHED_PAGES[slugName]=responseText;
				});
			}
		}

		$('ul#nav li a').removeClass('active');
		$('ul#nav li.'+sectionName+'').children('a').addClass('active');

		return false;
	}


// Set URL and make appropriate AJAX calls
	// Main Navigation 
	$('ul#nav > li > a').click(function() {
		resetWindow(1,500);
		return false;
	});
	
	// Submenu Navigation 
	$('ul.sub li a').click(function() {		
		resetWindow(1,500);
		return false;
	});

	// Performers Sidebar
	$('ul.actions li.bio a').click(function() {
		resetWindow(1,500);
		return false;		
	});

	
	// Footer Navigation 
	$('ul#misc li a').click(function() {
		resetWindow(1,500);
		return false;
	});


// Need to manually define what section to scrollTo
	$('#logo a').click(function() {					
		$.scrollTo( $('#home'), 500 );
		$('ul#nav li a').removeClass('active');
	});


// Swap form field values when focused
	$('input[type=text]').each(function() {
	    var default_value = this.value;
	    $(this).focus(function() {
	        if(this.value == default_value) {this.value = '';}
	    });
	    $(this).blur(function() {
	        if(this.value == '') {this.value = default_value;}
	    });
	});


// Count how many performers are currently showing
	function numOfPerformers() {
		var curPerformers = $('ul.performers > li:visible').size();
		var totalPerformers = $('ul.performers > li').size();
		
		$('p.showing').text('Showing '+curPerformers+' of '+totalPerformers+' performers');
	}
	numOfPerformers();
	

// Filter the list of performers
	$('#performances select').change(function() {
		var currentDay = $('select#day option:selected').attr('value');
		var currentStage = $('select#stage option:selected').attr('value');
			
		// Loop through all performers
		$('ul.performers > li').each(function() {
			var performer = $(this);
			var day = $(this).find('span.day').attr('title');
			var stage = $(this).find('span.stage').attr('title');
			var noDay = $('select#day option:selected').attr('value');
			var noStage = $('select#stage option:selected').attr('value');
			
			if ( day == currentDay && stage == currentStage ) { performer.show(); }
			else if ( day == currentDay && noStage == 'all' ) { performer.show();	}
			else if ( noDay == 'all' && stage == currentStage ) { performer.show();	}
			else if ( noDay == 'all' && noStage == 'all' ) { performer.show(); }
			else { performer.hide(); }
		});

		// Update number of performers
		numOfPerformers();
	});

	
// Fancybox configuration for email form	
	$('ul#social_network li.email a').fancybox({
		'type': 'iframe',
		'autoDimensions': true,
		'margin': 0,
		'padding': 0,
		'width' : 350,
		'height' : 400,
		'overlayColor': '#000',
		'overlayOpacity': '0.5',
		'hideOnOverlayClick': false
	});
	
	// Fancybox configuration for sponsors	
	$('#supporters a img.sponsors').live('click', function() {

		$.fancybox({
			'type': 'image',
			'href': 'http://hillsidefestival.ca/img/sponsors-large.jpg',
			'margin': 0,
			'padding': 0,
			'overlayColor': '#000',
			'overlayOpacity': '0.5',
			'hideOnOverlayClick': false
		});
		
		return false;
	});

// Fancybox configuration for map	
	$('#how a img.map').live('click', function() {
	
		$.fancybox({
			'type': 'image',
			'href': 'http://hillsidefestival.ca/img/Hillside2010-Map.gif',
			'margin': 0,
			'padding': 0,
			'overlayColor': '#000',
			'overlayOpacity': '0.5',
			'hideOnOverlayClick': false
		});
		
		return false;
	});


// Any links with rel="external" open in new window
	$('a[rel=external]').live('click', function() {
		$(this).attr('target','_blank');
	});

	
// Get the search terms and display via AJAX
	$('#search form').submit(function() {
		var searchTerms = $(this).children('input.search_box').val().replace(' ','+');				
		alert('You searched for: \"'+searchTerms+'\"');		
		return false;
	});
	
	
// Hide the dropdown menus on click
	$('ul.sub li a').click(function() {
		$(this).parent().parent().css('display','none');
	});
	
	$('ul#nav li').hover(function() {
		$(this).find('ul.sub').css('display','block');
	}, function() {
		$(this).find('ul.sub').css('display','none');
	});
	
	
// Fade in the performances section in sidebar
	$('#performances').delay(3000).fadeIn('slow');
	
	
// Detect if user agent is iPhone, iPod or iPad
	var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
	if (agentID) {
		$('link[href*=screen.css]').remove();
	}


}); // End of document ready