var zch = zch || [];

zch.contact = {
	toggle:function(e) {
		if(e) {
				e.preventDefault();
		}
		if(this) {
			var $that = $(this).parent("li");
			if($that.hasClass("minimised")) {
				$that.removeClass("minimised");
				$(".contact-us").removeClass("minimised");
				$(".contact-us-container").slideDown("slow");
				$(".contact-us-nav").animate({
					"margin-top": 570 + "px",
					"z-index": 1
					}, "slow");
				window.location = "#contact-us";
			}
			else {
				$(".contact-us-container").slideUp("slow", function() {
					$that.addClass("minimised");
					window.location.hash=null;
				});
				$(".contact-us-nav").animate({
					"margin-top": 0 + "px"
				}, "slow");
			}
		}
	},
	ajax:function(e) {
		e.preventDefault();
		var qs = $(".contact-form").serialize();
		$.ajax({
			url:wptemplatedir + "/thanks/thanks-ajax.php",
			data:qs,                                                  
			type:'POST',
		   	success:function(data) {
      			if(data != "") {
      				$(".contact-form fieldset").html(data);
      			}
      			
      		}
		});
	},
	validate:function(e) {
		var submitForm = true;
		$(".error-message").remove();
		$(".contact-form *[required]").each(function(i, node) {
      var isEmpty = $(this).val();
      if(isEmpty == " " || isEmpty == "") {
        e.preventDefault();
        submitForm = false;
				$("<em class='error-message'>This field is required</em>").insertAfter($(this));
			}
			
		});
		if(submitForm == true) {
      zch.contact.ajax(e);
			return false;
		}
	
	}
};

$(document).ready(function(e) {
	//Convert the newsletter signup checkbox to be pretty.
	$("#iButton").iButton();
	
	// default state is minimised
	$(".contact-us-nav").addClass("minimised");
	
	// add ajax handle to contact form
	$(".contact-form").live("submit", zch.contact.validate);
	
	// add toggle 
	$(".contact-us-nav a").live("click", zch.contact.toggle);
	
	// add form validation
	$(".contact .email a, .case-study .contact-us a, li.contact a, .statement a, .contact-us .close-contact, .site-map-contact a, .ajax-contact").live("click", function(e) {
		zch.contact.toggle.call($(".contact-us-nav a"));
		e.preventDefault();	
	});
	var sHash = window.location.hash;
	if(sHash.match("contact-us")) {
		zch.contact.toggle.call($(".contact-us-nav a"));
	}
	// if escape key is pressed then contact form is closed (if open)
	$(document).keyup(function(e) {
		if (e.keyCode == 27) { 
	  		if(window.location.hash!="") {	
	  			$(".contact-us-container").slideUp("slow", function() {
	  				$(".contact-us-nav").addClass("minimised");
	  				window.location.hash="";
	  			});
	  		}
	  	}
	});
});



