var site = {
	defaultPage		: false,
	currentSection 	: 0,
	currentSectionName : false,
	lastSection		: false,
	nextSection		: false,
	currentPage		: false,
	lastPage		: false,
	nextPage		: false,
	pageToSection	: false,
	accordion		: false,
	otherStartPage	: false,
	pagecache		: {},
	cycles			: {},
	ignorePages		: {},
	
	// set up the accordion object
	setup 			: function()
	{
		var section = this.defaultPage ? this.getSectionIndexFromUrl( this.defaultPage ) : 0;
		
		$(".accordion").hrzAccordion({
			handlePosition 	: 'left'
			,closeSpeed     : 300
			,openSpeed      : 300
			,eventAction	: site.accordionStartHandler
			,completeAction	: site.accordionCompleteHandler
			,openOnLoad		: section+1
		});
		
		if( this.defaultPage ) window.location.hash = encodeURIComponent( this.defaultPage );
		
		$.history.init( site.historyHandler );
		
		$('#search_form').bind( 'submit', function(){
		
			var url = 'sitesearch?s='+$('#searchfield').attr('value');
			site.historyHandler( url );
			$('#searchfield').attr('value','+ search...');
			return false;
		
		});
		
		textfield_setDefaultValue( 'searchfield', '+ search...' );
	},
	
	addCycle : function( id )
	{
		this.cycles[id] = true;
		//$(id).show();
	},
	
	destroyCycles : function()
	{
		for( var i in site.cycles )
		{
			$(i).cycle('destroy');
			//$(i).hide();
		}
		
		site.cycles = {};
	},
	
	pageCleanup : function()
	{
		site.destroyCycles();
	},
	
	login : function( username, password )
	{
		site.submitForm( 'login', {
			user: username,
			pass: password
		});
		
		site.pagecache = {};
	},
	
	logout : function()
	{
		site.submitForm( 'logout' );
		
		site.pagecache = {};
	},
	
	getFormValues : function( formId, sendEmpties )
	{
		sendEmpties = sendEmpties === undefined ? true : sendEmpties;
		var values = {};
		$('input, textarea, select', $('#'+formId)).each( function(){
		
			if( $(this).attr('name') )
			{
				if( $(this).attr('value') == $(this).attr('defaulttext') || $(this).attr('value') == '' )
				{
					if( sendEmpties ) values[ $(this).attr('name') ] = '';
				}
				else if( $(this).attr('type') == 'checkbox' )
				{
					if( $(this).attr('checked') )
					{
						values[ $(this).attr('name') ] = $(this).attr('value');
					}
					else if( sendEmpties )
					{
						values[ $(this).attr('name') ] = '';
					}
				}
				else
				{
					values[ $(this).attr('name') ] = $(this).attr('value');
				}
			}
		
		});
		
		return values;
	},
	
	submitForm : function( url, data )
	{
		data = data || {};
		data.page = site.currentPage;
		
		site.ignorePages[url] = true;
		site.unCache( url );
		window.location.hash = encodeURIComponent( url );
		
		site.fetchPage( url, data );
	},
	
	getSectionIndexFromUrl : function( url )
	{
		if( url == 'login' ) return site.currentSection;
		if( url == 'logout' ) return site.currentSection;
		if( url == 'reminder' ) return site.currentSection;
		if( url == 'sign-up-process' ) return site.currentSection;
		
		if( url.indexOf( 'news-' ) == 0 ) return parseInt( site.pageToSection[ 'news' ] ) - 1;
		if( url.indexOf( 'events-' ) == 0 ) return parseInt( site.pageToSection[ 'events-and-entertainment' ] ) - 1;
		if( url.indexOf( 'gallery-' ) == 0 ) return parseInt( site.pageToSection[ 'galleries' ] ) - 1;
		if( url.indexOf( 'eat-and-drink-' ) == 0 ) return parseInt( site.pageToSection[ 'eat-and-drink' ] ) - 1;
		if( url.indexOf( 'careers-' ) == 0 ) return parseInt( site.pageToSection[ 'job-search' ] ) - 1;
		if( url.indexOf( 'job-search-' ) == 0 ) return parseInt( site.pageToSection[ 'job-search' ] ) - 1;
		if( url.indexOf( 'clubs-and-societies-' ) == 0 ) return parseInt( site.pageToSection[ 'clubs-and-societies' ] ) - 1;
		if( url.indexOf( 'clubs-' ) == 0 ) return parseInt( site.pageToSection[ 'clubs-and-societies' ] ) - 1;
		if( site.pageToSection[ url ] )
		{
			return parseInt( site.pageToSection[ url ] ) - 1;
		}
		
		return 0;
	},
	
	getSectionNameFromIndex : function( index )
	{
		return site.sectionIndexToName[ index ] || false;
	},
	
	accordionStartHandler : function( tabIndex )
	{
		$contentSection = $('.page-num-'+(site.currentSection+1)+' .content');
		$contentSection.html('');
		site.accordion = true;
		site.currentSection = tabIndex;
	},
	
	accordionCompleteHandler : function( tabIndex )
	{
		contentSection = $('.page-num-'+(site.currentSection+1)+' .content');
		
//		contentSection.show(); 
		site.accordion = false;
		site.currentSection = tabIndex;
	},
	
	historyHandler	: function( url )
	{
		if( url == '' ) url = 'home';
		
		if( url == 'logout' ) return site.logout();
		
		site.lastPage = site.currentPage;
		site.currentPage = url;
		
		var section = site.getSectionIndexFromUrl( url );
		
		site.pageCleanup();
		if( url == 'loginfailed' ) return false; 
		if( url == 'login' ) return false; 
		if( site.ignorePages[url] ) return false;
		
		$('#accordionHandle'+section).trigger('click');
		
		site.showPage( url );
	},
	
	showPage : function( url )
	{
		var cached = site.pageCached( url );
		
		if( cached )
		{
			site.displayPage( url, cached );
			FB.XFBML.parse();
			gapi.plusone.go(); 
			makeLight();
		}
		else
		{
			site.fetchPage( url );
		}
		
	},
	
	fetchPage : function( url, params )
	{
		site.showLoading();
		
		var data = {
			api		: 'true',
			l		: 'l_passthru'
		};
		
		if( params )
		{
			for( var i in params )
			{
				data[i] = params[i];
			}
		}
			
		$.ajax({
			url		: url,
			cache	: true,
			type	: 'GET',
			data	: data,
			dataType: 'html',
			success	: function(html)
			{
				site.pageCache( url, html );
				site.displayPage( url, html );
				FB.XFBML.parse();
				gapi.plusone.go(); 
				makeLight();
			},
			error : function( XHR, textStatus, errorThrown )
			{
				if( XHR.responseText )
				{
					site.pageCache( url, XHR.responseText ) ;
					site.injectContent( XHR.responseText, true );
					
				}
			}
		});
	},
	
	displayPage : function( pageid, content )
	{
		pageTracker._trackPageview(pageid);
		site.injectContent( content, true );
		
		if( pageid.indexOf( 'sitesearch' ) == 0 )
		{
			for(var i=0; i<searchtables.length; i++)
			{
				var old = window[searchtables[i]+"_onRequestComplete"];
				window[searchtables[i]+"_onRequestComplete"] = function( tableid, result )
				{
					old( tableid, result );
					site.resizeContent();
				};
			}

		}
	},
	
	showLoading : function()
	{
		var loadingImage = '<img src="templates/uqu/layout_images/ajax-loader.gif" alt="Loading..." />';
		
		site.injectContent( '<div style="color: #B3B2B2; text-align: center; margin-top: 100px;">Loading...<br/>'+loadingImage+'</div>', false );
	},
	
	pageCacheable : function( url )
	{
		return true;
	},
	
	pageCached : function( url )
	{
		return site.pagecache[ url ] || false;
	},
	
	pageCache : function( url, content )
	{
		site.pagecache[ url ] = content;
	},
	
	unCache : function( url )
	{
		if( site.pagecache[ url ] )
		{
			delete site.pagecache[ url ];
		}
	},
	
	injectContent : function( content, resize )
	{
		contentSection = $('.page-num-'+(site.currentSection+1)+' .content');
		contentSection.empty();
		contentSection
			.html( content );
			//.css({ 'opacity' : 0 })
			//.animate({'opacity':1});
		contentSection.find('.lightbox').lightBox();
		if( resize ) site.resizeContent();
	},
	
	resizeContent : function( delay )
	{
		if( delay == undefined ) delay = 500;
		setTimeout( function(){
			$contentSection = $('.page-num-'+(site.currentSection+1)+' .content');
			
			var height = $contentSection.attr('scrollHeight');
//			alert(height);
			$subnav = $('.page-num-'+(site.currentSection+1)+' .subnav' );
			if( $subnav.eq(0).length > 0 ) height += $subnav.eq(0).attr('scrollHeight');
			
//			height += 250;
			height += 220;
			if( height < 600 ) height = 600;
			
			$('.acc_container').animate({ height: height }); 
		}, delay );
	},
	
	ajaxAction : function( action, data, callbackSuccess, callbackError )
	{
		data.api = true;
		data.action = action;
		data.l = 'l_passthru';
		
		$.ajax({
			url		: 'uqun-ajax',
			cache	: false,
			type	: 'GET',
			data	: data,
			dataType: 'html',
			success	: function(html)
			{
				callbackSuccess( html );
			},
			error : function( XHR, textStatus, errorThrown )
			{
				if( callbackError == undefined ) return false;
				if( XHR.responseText )
				{
					callbackError( XHR.responseText );
				}
				else
				{
					callbackError();
				}
			}
		});
	},
	
	tagPhoto : function( imageId, imageDomId )
	{
		site.unCache( 'uq-you' );
		site.unCache( site.currentPage );
		$('#'+imageDomId).addClass('gallery_image_loading');
		
		site.ajaxAction( 'tag', {'img':imageId}, function( response ){
		
			$('#'+imageDomId).removeClass('gallery_image_loading');
			
			if( response == 'OK' )
			{
				$('#'+imageDomId).addClass('gallery_image_tagged');
			}
			else
			{
				$('#'+imageDomId).removeClass('gallery_image_tagged');
				alert( response );
			}
		
		});
	},
	
	unTagPhoto : function( imageId, imageDomId )
	{
		site.unCache( 'uq-you' );
		site.unCache( site.currentPage );
		$('#'+imageDomId).addClass('gallery_image_loading');
		
		site.ajaxAction( 'untag', {'img':imageId}, function( response ){
		
			$('#'+imageDomId).removeClass('gallery_image_loading');
			
			if( response == 'OK' )
			{
				$('#'+imageDomId).removeClass('gallery_image_tagged');
			}
			else
			{
				alert( response );
			}
		
		});
	}
}
function makeLight()
{
	$(".content img").each(function(){
		//get the URL of the image
		var the_url = $(this).attr('src');
		var parent=$(this).parent();
		if(parent[0].nodeName!='A')
		{
			//insert a href before image where rel=lightbox
			the_url=the_url.replace(/p=[0-9]{3}x[0-9]{3}/,'p=640x480');
			
			var a = $("<a></a>").attr({"href": the_url, "class": "lightbox"});
			$(this).wrap(a);
			/* $(this).load(function(){
				var the_width = $(this).width();
				var the_height = $(this).height();
				var max_dimension = 600;
				if (the_width && the_height){
					var ratio = the_width / the_height;
					if (ratio >= 1 && the_width > max_dimension){
						$(this).css('width', max_dimension);
						$(this).css('height', the_height * max_dimension / the_width);
					}
					else if (ratio > 1 && the_height > max_dimension){
						$(this).css('height', max_dimension);
						$(this).css('width', the_width * max_dimension / the_height);
					}
				}
			}); */
			$(this).parent().lightBox();
		}
    });
}
$(document).ready( function(){

 site.setup();
 
	
 
 } );

