var crapBrowser = false;		// flag for IE < 7

$(document).ready(function(){
	// flag to say if the browser is IE < 7, and hence has to have degraded animation (bounced images disappear for example)
	if ($.browser.msie && $.browser.version.substr(0,1)<7) crapBrowser = true;
	
	$('#mailingList_email').clickClear();							// on click behaviour to clear the text from the mailing list sign up box
	$('#mailingList_email').validateEmail('#mailingList_submit');	// mailing list email onchange behaviour to validate the email address
	
	// mailing list submission handler
	$('#mailingList').submit(function(){
		
		/* disabled due to emails not being validated when correct
		// check that the email address has the OK class
		if(!$('#mailingList_submit').hasClass("pending") && !$('#mailingList_submit').hasClass("disabled")) {
			$('#mailingList_error').hide();
			
			// submit the email address to the db
			$.post('/mailing-list/sign-up/',{ email: $('#mailingList_email').val(), sid: sid }, function(data){
				if(data) {
					$('#mailingListSignup').html(data);
				}
			});
		} else {
			$('#mailingList_error').fadeIn('fast');
		}
		*/
		$.post('/mailing-list/sign-up/',{ email: $('#mailingList_email').val(), sid: sid }, function(data){
			if(data) {
				$('#mailingListSignup').html(data);
			}
		});
		
		return false;
	});
	
	// open & close
	$('#mainMenu_btn').bind('click',function(){
		
		if ($('#mainMenu').hasClass('mainMenu_comingSoon')) {
			var trgt = "-125px"
		} else {
			var trgt = "-315px"
		}
		
		if($('#mainMenu').hasClass('open')) {
			$('#mainMenu').animate({ "top": trgt }, 1000, "swing");
			$('#mainMenu').removeClass('open');
		} else 
		{
			$('#mainMenu').animate({ "top": "0" }, 1000, "swing");
			$('#mainMenu').addClass('open');
			$('#mainMenu').bind('mouseleave',function(){
				$('#mainMenu').animate({ "top": trgt }, 1000, "swing");
				$('#mainMenu').removeClass('open');
			});
		}
		
		return false
	});
	
	// popin close function
	$('.popin-close, .popin-close-default').bind('click',function(){
		$('.popin').hide();
	});
});


// adds a star at a certain point that fades in and out
jQuery.fn.extend({
	addSparkle: function(x,y,delay,jitter) {
		
		// give this sparkle a unique id (so we can stagger the starts
		var id = 'sparkle'+(Math.round(Math.random()*10000));
		
		// attach it to the DOM
		$(this).append('<div id="'+id+'" class="sparkle" style="top: '+y+'px; left: '+x+'px;"></div>');
		
		// calculate the start time
		var timeOffset = delay + (Math.round(Math.random()*jitter));
		
		// when to start the sparkle
		setTimeout(function() { $('#'+id).fadeIn('slow').fadeOut('slow',function(){$(this).remove()}); },timeOffset );
	},
	
	// adds a bunch of sparkles at a certain point
	addSparkleGroup: function(x,y,count,xJitter,yJitter) {
		var delay = 0;		// base delay
		var jitter = 3000;		// up to how many ms to add to the delay
		
		for(var i = 0; i <= count; i++)
		{
			var nx = Math.round(x + ((Math.random()*xJitter)-(xJitter/2)));
			var ny = Math.round(y + ((Math.random()*yJitter)-(yJitter/2)));
			
			$(this).addSparkle(nx,ny,delay,jitter);
		}
	},
	
	// adds a bunch of sparkles over an image, using the size of the image as the x and y jitter
	addSparkleImage: function(count) {
		$(this).each(function(){
			
			var width = $(this).width();
			var height = $(this).height();
			var x = parseInt($(this).offset().left + (width/2) - $('#stage-front').offset().left);
			var y = parseInt($(this).offset().top + (height/2));
			
			$('#stage-front').addSparkleGroup(x,y,count,width,height);
		});
	},
	
	// clears a textfield when clicked
	clickClear: function(){
		$(this).bind('click',function(){
			if($(this).val() == 'ENTER YOUR EMAIL ADDRESS') {
				$(this).val('');
			}
		});
	},
	
	// live validation of an email address field
	validateEmail: function(submitButton) {
		
		var dst = this;							// reference to the email field for later manipulation
		var fieldTimeout = false;				// timeout var so that we don't validate at every keystroke, only when they pause
		
		$(this).bind('click',function(){
			if($(this).val() == 'ENTER YOUR EMAIL ADDRESS') {
				$(this).val('');
			}
		});
		
		$(this).bind('keyup',function() {
			$(this).removeClass();
			$(this).addClass('validating');
			
			// alter the submit button if applicable
			if (submitButton) {
				$(submitButton).addClass('pending');
			}
			clearTimeout(fieldTimeout);
			fieldTimeout = setTimeout(function(){
					$.post('/validation/email/',{ data: $(dst).val() },function(data){
						$(submitButton).removeClass();
						$(dst).removeClass();
						
						if(data == 1) {
							$(dst).addClass('ok');
						} else {
							$(submitButton).addClass('disabled');
							$(dst).addClass('error');
						}
					});
				}, 
				500
			);
		});
	},
	
	// validates a poll
	validatePoll: function() {
		$(this).submit(function(){
			$('#poll_emailError').hide();				// hide any previous email errors
			
			var passedValidation = true;				// flag for validation
			
			// check they have made a selection
			if($('[name=poll-answer]:checked').val() == undefined)
			{
				$('.pollItem img').addSparkleImage(10);
				$('#pollError').fadeIn('slow');
				passedValidation = false;
			}
			
			// check they have entered an email address if required
			if($('#poll-email').length == 1)
			{
				// an email is required, check it has passed validation
				if(!$('#poll-email').hasClass("ok"))
				{
					$('#poll_emailError').fadeIn('fast');
					passedValidation = false;
				}
			}
			
			if(passedValidation) return true;
			else return false;
		});
	},
	
	// horizontally scrollable sections 
	scrollSection: function() {
	    var dst = this;						    // save a reference to the target
	    var totalSections = parseInt($(this).width() / 1000);	    // how many sections are there (sections always being 1000 wide)
	    var currentSection = 1;					    // what section are we currently looking at
	    var spd = 1500;						    // how long we take to animate between sections (in ms)

	    // create the next handler

	    var handler_nxt = function() {
		if(!$('#scrollSection_nav_nxt').hasClass('disabled')) {
		    currentSection++;
		    $(dst).attr('currentSection',currentSection);

		    // enable the previous button
		    $('#scrollSection_nav_prv').removeClass('disabled');

		    // if we are on the last section, disable the next button
		    if(currentSection >= totalSections) {
			$('#scrollSection_nav_nxt').addClass('disabled');
		    }

		    // animate the scrolling section to the left
		    $(dst).animate({ "left": "-=1000px" }, spd, "swing");

		    return false;		// don't use the anchor as a link
		}
	    }

	    var handler_prv = function(){
		if(!$('#scrollSection_nav_prv').hasClass('disabled')) {
		    currentSection--;
		    $(dst).attr('currentSection',currentSection);

		    // enable the next button
		    $('#scrollSection_nav_nxt').removeClass('disabled');

		    // if we are on the last section, disable the next button
		    if(currentSection <= 1) {
			$('#scrollSection_nav_prv').addClass('disabled');
		    }

		    // animate the scrolling section to the left
		    $(dst).animate({ "left": "+=1000px" }, spd, "swing");

		    return false;		// don't use the anchor as a link
		}
	    }

	    $('#scrollSection_nav_nxt').bind('click',handler_nxt);
	    $('#scrollSection_nav_prv').bind('click',handler_prv);
	}
});



