/**
 * initialise the easySlider carousels
 */
function initCarousels(){
	$("#slider").easySlider({
		controlsBefore:	'<p id="controls">',
		controlsAfter:	'</p>',
		auto: false, 
		continuous: true
	});
	$("#slider2").easySlider({
		controlsBefore:	'<p id="controls2">',
		controlsAfter:	'</p>',		
		prevId: 'prevBtn2',
		nextId: 'nextBtn2',
		auto: false, 
		continuous: true,
		speed: 1200	
	});			
}


/**
 * basic slideshow for some of the gallery projects crafted from esaySlider & SimpleModal
 */
function initSlideShow(){
	$("#gallery_slideshow").easySlider({
		controlsShow: false,
		auto: true, 
		continuous: true
	});
	$("#gallery_slideshow a").click(function(e){
		e.preventDefault();
		img = $(this).attr('href');
		// create an image element, hide it & display it in a modal window
		$('<img>').attr('id', 'modal_image').attr('src', img).css('opacity', 0).modal({
			opacity: 80,
			overlayClose: true,
			containerId: 'simplemodal-container-slideshow',
			minWidth: null,
			minHeight: null
		});
		// centre & display the image when it has finished loading
		$('#modal_image').load(function(){
			// scale image if bigger than viewport
			var max_width = window.innerWidth - 60;	// 30px free either side
			var max_height = window.innerHeight - 60;
			var new_width = $(this).width();
			var new_height = $(this).height();
			if(new_width > max_width){
				new_height *= (max_width / new_width);
				new_width = max_width;
			}
			if(new_height > max_height){
				new_width *= (max_height / new_height);
				new_height = max_height;
			}
			$(this).css('width', new_width);
			$(this).css('height', new_height);
			// centre - use bitwise OR to cast x and y to ints so ie6 doesn't fallover when setting left and top
			x = ((window.innerWidth - $(this).width()) / 2) | 0;
			y = ((window.innerHeight - $(this).height()) / 2) | 0;
			$('#simplemodal-container-slideshow').css('left', x);
			$('#simplemodal-container-slideshow').css('top', y);
			// display
			$(this).hide().css('opacity', 1);
			$(this).fadeIn('slow');
		});
	});
}

/**
 * slide up captions on gallery carousel
 */
function initGalleryCaptions(){
	//To switch directions up/down and left/right just place a "-" in front of the top/left attribute
	//Vertical Sliding
	//Full Caption Sliding (Hidden to Visible)
	$('.boxgrid.captionfull').hover(function(){
		$(".cover", this).stop().animate({top:'0px'},{queue:false,duration:500});
	}, function() {
		$(".cover", this).stop().animate({top:'180px'},{queue:false,duration:500});
	});
}


/**
 * search box behaviour
 */
function initSearchBox(){
	// initial value in search box
	var search = 'Search';	
	$('#searchform-input').focus(function(){
		if(this.value == search)
			this.value = '';
	});
	$('#searchform-input').blur(function(){
		if($.trim(this.value) == '')
			this.value = search;
	});
	// hover state for submit button
	$('<img>').attr('src', '/img/input_btn_hover.png');	// pre-load image
	$('#searchsubmit').hover(
		// over
		function(){
			$(this).css('background-image', 'url(/img/input_btn_hover.png)');
		},
		// out
		function(){
			$(this).css('background-image', 'url(/img/input_btn.png)');
		}
	);
}


/**
 *	Carousel filter menu
 */
function initFilterBox(){
	$('#carousel_filter_button').click(function(){
		$('#filter_options').slideToggle('normal');
	});
}


function fadeNav(){
	$('#about_nav ul li, #nav ul li').hover(function(){
		$(this).css({opacity: 0.85},{duration:500});
	}, function() {
		$(this).css({opacity: 1.0},{duration:500});
	});
}


function attachNewsletterListener(){
	$('#newsletter_link').click(function(e){
		e.preventDefault();
		$('#signup').modal({
			opacity: 80,
			overlayClose: true,
			containerId: 'simplemodal-container-signup'
		});
	});
}


// This targets any link that has an attribute containing the word external. 	
function openExternalLinksInNewWindow(){	
	$('a[rel*=external]').click(function(event){
		window.open(this.href); 				
		event.preventDefault();
	});
}


/**
 * form validation for newsletter signup
 */
function validate_signup(frm) {
	var isError = false;
	var emailAddress = frm.Email.value;
	
	if (emailAddress == "" || emailAddress.indexOf("@") == -1) {
		alert("Please enter your email address");
		isError = true;
	}

	return !isError;
}


/**
 * display the splash screen if the user hasn't visited the site before
 */
function initSplashScreen(){
	if($.cookie('mediabox_intro'))
		return;
	// display modal window
	$('#splash').modal({
		opacity: 80
	});
	// set cookie when any of the buttons are clicked
	$('#splash area, #splash a').click(function(){
		$.cookie('mediabox_intro', true, { expires: parseFloat(30), path: '/'});
	});
}


/**
 * display all links to competition entry in a modal window
 */
function initCompetitions(){
	$("a[href^='/competitions/view/']").click(function(){
		$.get(this.href, function(data){
			$(data).modal({
				opacity: 80,
				overlayClose: true,
				containerId: 'simplemodal-competition-entry',
				minWidth: 422,
				minHeight: 690,
				onShow: initCompetitionForm
			})
		});
		return false;
	});
}


/**
 * update the remaining words counter on the competition entry form
 */
function updateRemainingWords(){
	var words = $('#CompetitionEntryEntry').val().match(/\b\S+\b/g);
	if(!words) {
		// wordLimit set as global var in competition form markup
		$('#CompetitionEntryAddForm > span').html(wordLimit);
		return;
	}
	var count = words.length;
	var remaining = wordLimit - words.length;
	$('#CompetitionEntryAddForm > span').html(remaining);
}


/**
 * process the response to the competition entry submission
 */
function processCompetitionResponse(response){
	if(response.error){
		var msg = '';
		for(e in response.error)
			msg += response.error[e] + "\n";
		alert(msg);
	} else {
		$('#CompetitionEntryAddForm').fadeOut(
			'slow',
			function(){
				$(this).html('<p>Thank you, your entry has been submitted</p>').fadeIn(
					'slow',
					function(){
						setTimeout('$.modal.close()', 3000)
					}
				);
			}
		);
	}
}

/**
 * initialise the competition entry form
 */
function initCompetitionForm(){
	$('#CompetitionEntryEntry').keyup(updateRemainingWords);
	$('#CompetitionEntryAddForm').submit(function(){
		$.post(
			$(this).attr('action'),
			$(this).serialize(),
			processCompetitionResponse,
			'json'
		);
		return false;
	});
}


/**
 * initialise Google Analytics without having to slow down page load with adding script tags in layout
 */
function initAnalytics(){
	var accountId = 'UA-1877929-1';
	jQuery.getScript('http://www.google-analytics.com/ga.js', function(){
		try {
			var pageTracker = _gat._getTracker(accountId);
			pageTracker._trackPageview();
		} catch(err) {}
	});
}


$(document).ready(function(){	
	initCarousels();
	initSearchBox();
	initGalleryCaptions();
	
	// jQuery rounded corners don't render properly in ie6, just disable them
	//if(!($.browser.msie && $.browser.version=="6.0"))
	//	$('.rounded').corners();
	
	initFilterBox();
	fadeNav();
	attachNewsletterListener();
	openExternalLinksInNewWindow();
	initSlideShow();
	//initSplashScreen();
	initCompetitions();
	initAnalytics();
});

