$(document).ready(function(){
	$("BODY").addClass("has-js");
	$("a[rel^='prettyPhoto']").prettyPhoto();
	tabbedContainers.init();
	blinkingButton("homepage");
	blinkingButton("apply-online");
	wireEvents();
	
	var validate = new Validation();
	validate.init();
	
	var submitForm = new SubmitForm();
	submitForm.init();
	
	$('.datepicker').datepicker({
		dateFormat: 'yy-mm-dd',
		changeMonth: true,
		changeYear: true,
		yearRange:'-40:+10'
	});
	
	$(".expand-visa-1, .expand-visa-2, .expand-visa-3, .expand-english-1, .expand-english-2, .expand-english-3, .expand-english-4, .expand-english-5, .expand-english-6, .expand-studies-1, .expand-studies-2").hide();
	
	$(".expand-visa-1-control input").bind("click", function(){
		if($(this).val() == "true") {$(".expand-visa-1").slideDown();}
		else {$(".expand-visa-1").slideUp();}
	});
	$(".expand-visa-2-control input").bind("click", function(){
		if($(this).val() == "true") {$(".expand-visa-2").slideDown();}
		else {$(".expand-visa-2").slideUp();}
	});
	$(".expand-visa-3-control input").bind("click", function(){
		if($(this).val() == "true") {$(".expand-visa-3").slideDown();}
		else {$(".expand-visa-3").slideUp();}
	});
	
	$(".expand-english-1-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-english-1").slideDown();}
		else {$(".expand-english-1").slideUp();}
	});
	$(".expand-english-2-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-english-2").slideDown();}
		else {$(".expand-english-2").slideUp();}
	});
	$(".expand-english-3-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-english-3").slideDown();}
		else {$(".expand-english-3").slideUp();}
	});
	$(".expand-english-4-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-english-4").slideDown();}
		else {$(".expand-english-4").slideUp();}
	});
	$(".expand-english-5-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-english-5").slideDown();}
		else {$(".expand-english-5").slideUp();}
	});
	$(".expand-english-6-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-english-6").slideDown();}
		else {$(".expand-english-6").slideUp();}
	});
	
	$(".expand-studies-1-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-studies-1").slideDown();}
		else {$(".expand-studies-1").slideUp();}
	});
	$(".expand-studies-2-control input").bind("click", function(){
		if($(this).val() == "yes") {$(".expand-studies-2").slideDown();}
		else {$(".expand-studies-2").slideUp();}
	});
	
});

var wireEvents = function() {
	$("#make-homepage").bind("click", function(){
		//Favorites 
		//		window.external.AddFavorite("http://www.gatesonline.com.au","Gates - Global Agency for Training, Education and Services");
		//Make Gates your homepage
		if(jQuery.browser.msie) {
			this.style.behavior='url(#default#homepage)';
			this.setHomePage('http://www.gatesonline.com.au');
		}
		return false;
	});
};

var blinkingButton = function(page) {
	if (page == "homepage") {
		if ($("P.apply-online-promo .button").length == 1) {
			setInterval(function(){
				$("P.apply-online-promo .button").toggleClass("button-red");
			}, 1000);
		}
	}
	else if(page == "apply-online") {
		if ($("DIV.body-text P.button A.start-app").length == 2) {
			setInterval(function(){
				$("DIV.body-text P.button A.start-app").toggleClass("link-red");
			}, 1000);
		}
	}
};

var SubmitForm = function() {
	this.init = function() {
		this.wireEvents();
	};
	
	this.wireEvents = function() {
		var me = this;
		$("#contact-form #send").bind("click", function(){
			me.submitContactForm(this);
			return false;
		});
		
		$("#inform-friend #send").bind("click", function(){
			me.submitInformFriend(this);
			return false;
		});
	};
	
	this.submitContactForm = function(eventSource){
		var form = $(eventSource).parents("FORM");
		if($(form).validate().form()) {
			$("#send").get(0).disabled = true;
			var name = $("#name",form).val();
			var email = $("#email",form).val();
			var message = $("#message",form).val();
			$("#send").next().remove();
			$("#send",form).after('<span class="loading-msg">'+sendingMessage+'</span>');
			var response = this.submit(
				pageURL,
				{
					name:name,
					email:email,
					message:message
				},
				{
					success: {message:messageSent,classname:"success"},
					fail: {message:messageFailed,classname:"fail"},
					error: {message:messageError,classname:"error"}
				}
			);
		}
	};
	
	this.submitInformFriend = function(eventSource){
		var form = $(eventSource).parents("FORM");
		if($(form).validate().form()) {
			$("#send").get(0).disabled = true;
			var senderName = $("#sender-name",form).val();
			var senderEmail = $("#sender-email",form).val();
			var recipientName = $("#recipient-name",form).val();
			var recipientEmail = $("#recipient-email",form).val();
			var message = $("#message",form).val();
			$("#send").next().remove();
			$("#send",form).after('<span class="loading-msg">Sending message...</span>');
			var response = this.submit(
				"process.php",
				{
					sender_name:senderName,
					sender_email:senderEmail,
					recipient_name:recipientName,
					recipient_email:recipientEmail
				},
				{
					success: {message:"Your friend has been invited!",classname:"success"},
					fail: {message:"Message failed!",classname:"fail"},
					error: {message:"There was an error!",classname:"error"}
				}
			);
		}
	};
	
	this.parseResponse = function(response,status) {
		var classname = "";
		var message = "";
		$("#send").next().remove();
		if(response == "1") {
			classname= status.success.classname;
			message = status.success.message;
		}
		else if(response == "0"){
			classname = status.fail.classname;
			message = status.fail.message;
		}
		else {
			classname = status.error.classname;
			message = status.error.message;
		}
		$("#send").after('<span class="server-msg '+classname+'">'+message+'</span>');
		$("#send").get(0).disabled = false;
	};
	
	this.submit = function(url,values,status) {
		var me = this;
		data = "";
		for(i in values) {
			data += i +"="+ values[i] +"&";
		}
		$.ajax({
			type: "POST",
			url: url,
			data: data,
			success: function(response){
				me.parseResponse(response,status);
			}
		});
	};
};

jQuery.validator.addMethod("GatesDate", function(value, element) { 
	var regex = /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/
	return this.optional(element) || regex.test(value);
}, "Please enter the date value in the following format: YYYY-MM-DD");

var Validation = function(){
	this.init = function() {
		this.contactForm();
		this.informFriend();
		this.applyForm();
		this.immiForm();
	};
	
	this.immiForm = function(){
		if ($("#immi-form").length > 0) {
			$("#immi-form").validate({
				rules: {
					name: "required",
					dateOfBirth: {
						required: true,
						GatesDate: true
					},
					nationality: "required",
					residentialAddress: "required",
					mailingAddress: "required",
					phone: "required",
					mobile: "required",
					email: {
						required: true,
						email: true
					},
					countryApplyingFor: "required",
					additionalInformation: "required",
					attachResume: "required"
				},
				messages: {
					name: "Please enter your name",
					email: {
						required: "Please enter an email address",
						email: "Please enter a valid email address"
					}
				}
			});
		}
	};
	
	this.applyForm = function() {
		if ($("#apply-form").length > 0) {
			$("#apply-form").validate({
				invalidHandler: function() {
					
					setTimeout(function(){
						var link;
						if($("#personal-container LABEL.error").size() > 0) {
							link = $("A[href*='personal-container']").get(0);
						}
						else if($("#contact-container LABEL.error").size() > 0) {
							link = $("A[href*='contact-container']").get(0);
						}
						tabbedContainers.flipTabs(link,"tab");
					},200)
					
				},
				rules: {
					"applicant[prefix]": {
						required: true
					},
					"applicant[firstnames]": {
						required: true
					},
					"applicant[surname]": {
						required: true
					},
					"applicant[dob]": {
						required: true,
						GatesDate: true
					},
					"applicant[country_birth]": {
						required: true
					},
					"applicant[country_residence]": {
						required: true
					},
					"applicant[country_citizenship]": {
						required: true
					},
					"applicant[passport]": {
						required: true
					},
					"applicant[passport_expiry]": {
						required: true,
						GatesDate: true
					},
					"applicant[street]": {
						required: true
					},
					"applicant[suburb]": {
						required: true
					},
					/*
					"applicant[state]": {
						required: true
					},
					*/
					"applicant[country]": {
						required: true
					},
					/*
					"applicant[postcode]": {
						required: true
					},
					*/
					"applicant[phone]": {
						required: true
					},
					"applicant[email]": {
						required: true,
						email: true
					},
					"applicant[mobile]": {
						required: true
					},
					"applicant[visa_issued]": {
						GatesDate: true
					},
					"applicant[visa_expiry]": {
						GatesDate: true
					},
					"applicant[oshc_expiry]": {
						GatesDate: true
					},
					"applicant[english_certificate_date]": {
						GatesDate: true
					},
					"applicant[english_test_date]": {
						GatesDate: true
					},
					"applicant[english_tertiary_start]": {
						GatesDate: true
					},
					"applicant[english_tertiary_finish]": {
						GatesDate: true
					},
					"applicant[english_enrolled_start]": {
						GatesDate: true
					},
					"applicant[english_enrolled_finish]": {
						GatesDate: true
					},
					"applicant[studies_australia_start]": {
						GatesDate: true
					},
					"applicant[studies_australia_finish]": {
						GatesDate: true
					},
					"applicant[studies_outside_start]": {
						GatesDate: true
					},
					"applicant[studies_outside_finish]": {
						GatesDate: true
					},
					"applicant[education_1_start]": {
						GatesDate: true
					},
					"applicant[education_1_finish]": {
						GatesDate: true
					},
					"applicant[education_2_start]": {
						GatesDate: true
					},
					"applicant[education_2_finish]": {
						GatesDate: true
					},
					"applicant[education_school_start]": {
						GatesDate: true
					},
					"applicant[education_school_finish]": {
						GatesDate: true
					},
					"applicant[employment_1_start]": {
						GatesDate: true
					},
					"applicant[employment_1_finish]": {
						GatesDate: true
					},
					"applicant[employment_2_start]": {
						GatesDate: true
					},
					"applicant[employment_2_finish]": {
						GatesDate: true
					},
					"applicant[employment_3_start]": {
						GatesDate: true
					},
					"applicant[employment_3_finish]": {
						GatesDate: true
					}
				},
				messages: {
					"applicant[prefix]": {
						required: "Please select a prefix"
					},
					"applicant[firstnames]": {
						required: "Please enter a first name"
					},
					"applicant[surname]": {
						required: "Please enter a last name"
					},
					"applicant[dob]": {
						required: "Please enter a date of birth"
					},
					"applicant[country_birth]": {
						required: "Please enter a country of birth"
					},
					"applicant[country_residence]": {
						required: "Please enter a country of residence"
					},
					"applicant[country_citizenship]": {
						required: "Please enter a country of citizenship"
					},
					"applicant[passport]": {
						required: "Please enter a passport number"
					},
					"applicant[passport_expiry]": {
						required: "Please enter a passport expiry date"
					},
					"applicant[street]": {
						required: "Please enter a street number and name"
					},
					"applicant[suburb]": {
						required: "Please enter a suburn/town/city"
					},
					"applicant[state]": {
						required: "Please enter a state"
					},
					"applicant[country]": {
						required: "Please enter a country"
					},
					"applicant[postcode]": {
						required: "Please enter a postcode"
					},
					"applicant[phone]": {
						required: "Please enter a phone number"
					},
					"applicant[email]": {
						required: "Please enter an email address",
						email: "Please enter a valid email address"
					},
					"applicant[mobile]": {
						required: "Please enter a mobile number"
					}
				}
			});
		}
	};
	
	this.contactForm = function(){
		if ($("#contact-form").length > 0) {
			$("#contact-form").validate({
				rules: {
					name: "required",
					email: {
						required: true,
						email: true
					},
					message: {
						required: true,
						minlength: 5
					}
				},
				messages: {
					name: "Please enter your name",
					email: {
						required: "Please enter an email address",
						email: "Please enter a valid email address"
					},
					message: {
						required: "Please write a message",
						minlength: "Your message must be at least 5 characters long"
					}
				}
			});
		}
	};
	
	this.informFriend = function(){
		if ($("#inform-friend").length > 0) {
			$("#inform-friend").validate({
				rules: {
					sender_name: "required",
					sender_email: {
						required: true,
						email: true
					},
					recipient_name: "required",
					recipient_email: {
						required: true,
						email: true
					}
				
				},
				messages: {
					sender_name: "Please enter your name",
					sender_email: {
						required: "Please enter your email address",
						email: "Please enter a valid email address"
					},
					recipient_name: "Please enter the recipient name",
					recipient_email: {
						required: "Please enter the recipient email address",
						email: "Please enter a valid email address"
					}
				}
			});
		}
	};
};



tabbedContainers = {
	init: function() {
		this.tabs();
		this.previous();
		this.next();
	},
	tabs: function() {
		var me = this;
		$(".tabbed-containers").find(".tabs a[href]").click(function(){
			me.flipTabs(this, "tab");
			return false;
		});
	},
	previous: function() {
		var me = this;
		$(".tabbed-containers .containers .container DIV.button A").click(function(){
			me.flipTabs(this, "prev");
			return false;
		});
	},
	next: function() {
		var me = this;
		$(".tabbed-containers .containers .container DIV.button:not(.submit) INPUT").click(function(){
			me.flipTabs(this, "next");
			return false;
		});
	},
	flipTabs: function(link, source) {
		var tabbedContainers = $(".tabbed-containers");
		// Hide currently visible container
		var prevContainer = $(tabbedContainers).find(".container:not(.inactive)").addClass("inactive");
		
		if(source == "tab") {
			// Set tab status
			var parentLi = $(link).parents("li");
			$(parentLi).siblings(".current").removeClass("current");
			$(parentLi).addClass("current");
			var containerId = $(link).attr("href");
		}
		else if(source == "prev") {
			var previousTab = $(".tabs",tabbedContainers).find(".current");
			var newTab = $(previousTab).prev().addClass("current");
			$(previousTab).removeClass("current");
			var containerId = $(prevContainer).prev();
			$('html, body').animate({scrollTop:100}, 'slow');
		}
		else if(source == "next") {
			var previousTab = $(".tabs",tabbedContainers).find(".current");
			var newTab = $(previousTab).next().addClass("current");
			$(previousTab).removeClass("current");
			var containerId = $(prevContainer).next();
			$('html, body').animate({scrollTop:100}, 'slow');
		}
		// Show selected container
		$(containerId).removeClass("inactive");
	}
};

function SlideShow(container,images,time) {
	this.interval = null;
	this.container = container;
	this.images = images;
	this.time = time;
	this.current = 0;
	this.count = 1;
	this.init();
}

SlideShow.prototype = {
	init: function(){
		if (this.images.length > 1) {
			$('img',this.container).attr("src",this.images[0]);
			this.preload();
			this.play();
		}
	},
	preload: function() {
		if (document.images) {
			for (var i = 0; i < this.images.length; i++) {
				pic = new Image();
				pic.src = this.images[i];
			}
		}
	},
	play: function() {
		me = this;
		this.interval = setInterval(function(){
			me.current = (me.isOverLength(me.current+1)) ? 0 : (me.current + 1);
			me.count = me.count + 1;
			me.animate(me.current);
		}, this.time);
	},
	animate: function(current) {
		$(this.container).css("background-image","url("+this.images[this.previousIndex(current)]+")");
		$('img',this.container).attr("src",this.images[current]).hide().fadeIn(1000);
	},
	isOverLength: function(number) {
		return(number > this.images.length-1);
	},
	previousIndex: function(index) {
		if(this.count != 1) {
			index = ((index == 0) ? this.images.length-1 : index-1);
		}
		return index;
	}
}

$(document).ready(function() {
	var container = $("#slideshow");
	if($(container).length > 0) {
		var slideshow = new SlideShow(container,slideshow_images,4000);
	}
});

