var browserwidth;
var browserheight;
var errorcheckRequests = new Object();
var getAjaxContent;
var preload_image_count = 0;
var preload_image_count_remaining = 0;

var api;
var scrolling = true;

var scrollerArea;
var copiedWidth;
var sliderPos;
var oldSliderPos;
var originalSize;

var paused = false;

var intval;

function resizeTextBox(){
	/*
	var newTextBoxWidth = 0.43 * $(window).width();
	if(newTextBoxWidth < 300) {
		newTextBoxWidth = 300;
	}
	$('.bodycopy').css('width',newTextBoxWidth+"px");
	*/
	var newTextBoxWidth
	if($(window).width()-225 < 780){
		newTextBoxWidth = $(window).width() - 225 - 15;	
	} else {
		newTextBoxWidth = 780;	
	}
	$('.bodycopy').css('width',newTextBoxWidth+"px");
}

//ENLARGE IMAGE - Set to fullscreen image
function supersizeImage(image) {
	var imagewidth = 1800;
	var imageheight = 1100;
	browserwidth = $(window).width();
	browserheight = $(window).height();

	var ratio = imageheight/imagewidth;

	if ((browserheight/browserwidth) > ratio){
		$(image).height(browserheight);
		$(image).width(browserheight / ratio);
	} else {
		$(image).width(browserwidth);
		$(image).height(browserwidth * ratio);
	}
	$(image).css('left', (browserwidth - $(image).width())/2);
	$(image).css('top', (browserheight - $(image).height())/2);
}

//Force resize all the fullscreen image
function forceSupersize(){
	$('img.supersize').each(function(){
		supersizeImage($(this));
	});
}

/*
$(document).ready(function(){
	forceSupersize();
});
*/

var startURL;

$(window).load(function() {
	forceSupersize();
	
	
	pageUrl = document.location.href.split("#")[1];
	if(!pageUrl){
		if(startURL){
			pageUrl = startURL;	
		}
		else {
			pageUrl = 'home';
		}
	}
	
	$('.loading .percent').html('0%');
	$('.loading').fadeIn(500,function(){	
		
		if(getAjaxContent){
			getAjaxContent.abort();	
		}
		
		getAjaxContent = $.ajax({
			type: "POST",
			url: pageUrl,
			data:({"json":true,"startup":true}),
			dataType:"json",
			error: function(){
				document.location.href = $('base').attr('href');
			},
			success: function(resp){
				preload_image_count = resp.preload_images.length;
				preload_image_count_remaining = preload_image_count;
				if(preload_image_count > 0){
					for(i in resp.preload_images){
						$(new Image()).attr("src",resp.preload_images[i]).load(function(){
							preload_image_count_remaining--;
							
							percentLoaded = ''+100 - ((preload_image_count_remaining / preload_image_count) * 100)+'';
							percentLoaded = percentLoaded.split(".")[0];

							$('.loading .percent').html(percentLoaded+'%');

							if(preload_image_count_remaining <= 0){
								loadpagedata(resp);

							}
						});
					}
				}
				else {
					loadpagedata(resp);
				}
			}
		});
	});
	
	//LISTENER - in window that will resize, reposition everything
	$(window).bind("resize", forceSupersize);
});

function loadpagedata(resp){
	document.title = resp.title;
	$('#nav1').fadeOut(250,function(){
		$('#nav1').html(resp.html_nav1);
		$('#nav1').fadeIn(250);
	});
	
	$('#nav2').fadeOut(250,function(){
		$('#nav2').html(resp.html_nav2);
		$('#nav2').fadeIn(250);
	});
	
	$('#content-main').fadeOut(250,function(){											
		$('#content-main').html(resp.html_content);
		$('#content-main').fadeIn(250,function(){
			setTimeout(function(){ startup(); $('.loading').fadeOut(500); },50);	
		});
	});
	
	$('#top-content').fadeOut(250,function(){										   
		$('#top-content').html(resp.html_top_content);
		$('.overlayblack').css('visibility','hidden');
		$('#top-content').fadeIn(250);
		$('.pauseInstruction').fadeIn(250);
	});
	
	if(resp.fancy_popup){
		$.fancybox(resp.fancy_popup,{
			'autoDimensions'	: false,
			'width' : 500,
			'overlayColor' : '#000',
			'overlayOpacity' : 0.5
		});	
	}
}

function initiateScroll(resume){
	if(resume) {
		sliderPos = oldSliderPos;
	} else {
		if(intval){
			intval = '';
			$('.scrollableArea').stop(true, true);
		} else {
			scrollerArea = $('.scrollWrapper').width()-$('#scroller').offset().left;
			copiedWidth = 0;
		}
		sliderPos = 0;
		$('.scrollableArea').css("left",0);
		originalSize = $('.scrollableArea img').length;
		for(var i=0; i<$('.scrollableArea img').length; i++){
			copiedWidth += $('.scrollableArea img').eq(i).width();
			$('.scrollableArea img').eq(i).clone().appendTo('.scrollableArea');
			if(copiedWidth > scrollerArea) {
				break;
			}
		}
	}
	$('.pauseInstruction').html("Click image to pause");
	intval = setInterval(slideStart, 3300);
}
function slideStart() { 
	if($('.noFiller').length > 0){
		var slideAmount = $('.scrollableArea img').eq(sliderPos).width();
	} else {
		var slideAmount = $('.scrollableArea img').eq(sliderPos).width()+2;
	}
	$('.scrollableArea').animate({
		left: '-=' + slideAmount
	}, 1800, function() {
		if(sliderPos+1 == originalSize){
			$('.scrollableArea').css("left",0);
			sliderPos = 0;
		} else {
			sliderPos++;
		}
	});
}
	
function startup(){
	
	if($('p.register-interest')){
		$('p.register-interest').each(function(){
			$(this).parents('div#content-main').find('h2:first').append(' - '+$(this).html());
			$(this).remove();
		});
	}
	
	$('.logo').fadeIn(250);

	resizeTextBox();
	$('.scroll-pane').jScrollPane();
	$('.overlayblack').css('visibility','hidden');
	if($('.awardsscroll').length > 0) {
		$('.overlayblack').css('visibility','hidden');
		$('.awardsscroll').jScrollPane({
			verticalGutter: 10
		});
	} else {
		$('.overlayblack').css('visibility','hidden');
		$('.blackscroll').jScrollPane({
			verticalGutter: 10
		});
	}
	$('.overlayblack').css('visibility','visible');
	$('.btnExpand').click(function(){
		var leftPos = $(this).parent().css("left").replace("px", "");
		if(leftPos >= 0) {
			$(this).parent().animate({				
				left: -1*$(".overlayblack").width()-19
			}, 800);
		} else {
			$(this).parent().animate({				
				left: 0
			}, 800);
		}
		return false;
	});						 

	$("a[rel=awardlink]").fancybox({
		overlayOpacity: 0.6,
		overlayColor: '#000',
		speedIn: 400,
		autoDimensions: true,
		padding: 15
	});

	$('.scroll-pane').each(function(){
		var api = $(this).data('jsp');
		var throttleTimeout;
				
		$(window).bind('resize', function() {
			resizeTextBox();
			if ($.browser.msie) {
				if (!throttleTimeout) {
					throttleTimeout = setTimeout(function(){
						api.reinitialise();
						throttleTimeout = null;
					},50);
				}
			}
			else {
				api.reinitialise();
			}
		});
	});
	
	if($('#scroller').length > 0){
		clearInterval(intval);
		
		if($('#scroller').hasClass('normalslide')){
			$("#scroller").smoothDivScroll({
				autoScroll: "onstart",
				autoScrollDirection: "endlessloopright",
				autoScrollStep: 1,
				autoScrollInterval: 15
			});	
			$("#scroller").click(function(){
				if(scrolling){
					$("#scroller").smoothDivScroll("stopAutoScroll");
					$('.pauseInstruction').html("Gallery is paused");
					scrolling = false;
				} else {
					$("#scroller").smoothDivScroll("startAutoScroll");
					$('.pauseInstruction').html("Click image to pause");
					scrolling = true;
				}
			});
		}
		else {
			initiateScroll();
			$("#scroller").click(function(){
				if(paused == false){
					window.clearInterval(intval);
					$('.pauseInstruction').html("Gallery is paused");
					oldSliderPos = sliderPos;
					paused = true;
				} else {
					initiateScroll(true);
					paused = false;
				}
			});
		}
	}
	
	$('a.ajax').click(function(){
		$.fancybox.close();
		window.clearInterval(intval);
		
		pageUrl = $(this).attr('href');
		$('.loading .percent').html('0%');
		$('.loading').fadeIn(500,function(){	
			window.location.href = document.location.href.split("#")[0] + '#' + pageUrl;
			
			if(getAjaxContent){
				getAjaxContent.abort();	
			}
			
			getAjaxContent = $.ajax({
				type: "POST",
				url: pageUrl,
				data:({"json":true}),
				dataType:"json",
				error: function(){
					alert('An unexpected error occurred. Please try again');
					location.reload(true);
				},
				success: function(resp){
					preload_image_count = resp.preload_images.length;
					preload_image_count_remaining = preload_image_count;
					_gaq.push(['_trackPageview', window.location.href]);
					
					if(preload_image_count > 0){
						for(i in resp.preload_images){
							$(new Image()).attr("src",resp.preload_images[i]).load(function(){
								preload_image_count_remaining--;
								
								percentLoaded = ''+100 - ((preload_image_count_remaining / preload_image_count) * 100)+'';
								percentLoaded = percentLoaded.split(".")[0];

								$('.loading .percent').html(percentLoaded+'%');
								
								if(preload_image_count_remaining <= 0){
									loadpagedata(resp);
									
								}
							});
						}
					}
					else {
						loadpagedata(resp);
					}
				}
			});
		});
		return false;
	});
	
	$('form.errorcheck').bind('submit',function(){
		formId=$(this).attr('id');
		url=$(this).attr('action');
	
		submitBtn=$('#'+$(this).attr('id')+' input.submit');	
		submitBtn.attr('disabled','disabled');
		submitTxt=submitBtn.val();
		submitBtn.val('Saving form..');

		submitData=new Object();
		submitData['json'] = true;
		$('#'+$(this).attr('id')+' input,'+' #'+$(this).attr('id')+' textarea,'+' #'+$(this).attr('id')+' select').each(function(){
			type=$(this).attr('type');
			if(type=='radio' || type=='checkbox'){
				if($(this).is(":checked")){
					submitData[$(this).attr('name')]=$(this).val();
				}
			}
			else {
				submitData[$(this).attr('name')]=$(this).val();
			}
		});
		
		if(errorcheckRequests[formId]){
			errorcheckRequests[formId].abort();	
		}
		
		if(url.indexOf("?") >= 0){
			url+="&";
		}
		else {
			url+="?";	
		}

		errorcheckRequests[formId]=$.ajax({
			type: "POST",
			url: url+'errorcheck='+formId+"&submitTxt="+submitTxt,
			data:submitData,
			dataType:"json",
			error: function(){
				alert('An unexpected error occurred. Please try again');
				$('form#'+response.formId+' input.submit').val(response.submitTxt);
				$('form#'+response.formId+' input.submit').removeAttr('disabled');
			},
			success: function(response){
				errMsg='';
				for(i in response.errors){
					errMsg+=' - '+response.errors[i]+'\n';
				}
				if(errMsg){
					alert(errMsg);
					$('form#'+response.formId+' input.submit').val(response.submitTxt);
					$('form#'+response.formId+' input.submit').removeAttr('disabled');
				}
				else {
					if(response.eval){
						eval(response.eval);
					}
					else {
						$('form#'+response.formId).unbind('submit');
						$('form#'+response.formId).submit();
					}
				}
			}
		});

		return false;
	});	
}


