//<![CDATA[
$(function(){ 
	
	var forms = $("a[rel*='contact']");
	if (forms.length) {
		forms.each(function(){
			var thisform = $(this);
			thisform.click(function(e){
				var success = false;
				var urls = getUrlVars(thisform.attr('href'));
				var referral = (urls['ref']) ? "ref="+urls['ref'] : ""; 
				// get form from ajax, add to page
				$.ajax({
				   type: "POST",
				   url: "/scripts/ajax/contact_form.php.inc",
				   data: ""+referral,
				   async: false,
				   success: function(msg){
						if (msg!="") {
							var formcontainer = $("<div id=\"contact-form\">"+msg+"</div>");
							$("body").append(formcontainer);
							formcontainer.modal({close: false, onClose: closeModal, onOpen: openModal, persist: false, onShow: onShowContact, position: [1,]});
							
							success = true;
						}
				   },
				   error: function(obj,text,error) {   }
				 });
				return !success;
			});
		});
	}
});

function closeModal (dialog) {	dialog.data.fadeOut('slow', function () {dialog.container.fadeOut('slow', function () {dialog.overlay.slideUp('slow', function () {$.modal.close();$('#contact-form').remove();});});});}
function openModal (dialog) {	dialog.overlay.fadeIn('slow', function () {dialog.container.fadeIn('slow', function () {dialog.data.hide().slideDown('slow');});	});}
/*****************************************
 Take Care of Processing the Contact Form
*****************************************/
function onShowContact (dialog) {
	$(document).keypress(function(e){
	  var key  = (window.event) ?  event.keyCode : e.keyCode;
 	 if( key == 27 ) $.modal.close();
	});

	if($("#contact-form").length) {
		var phone = $("#contact-form input[name='phone']");
		var email = $("#contact-form input[name='email']");
		clearOptional(phone); 	setOptional(email);
		
		/* Bind field checking events */		
		$("#contact-form input[name='companyName'], #contact-form [name='contactTitle'], #contact-form [name='message'], #contact-form [name='address'], #contact-form [name='city'], #contact-form [name='state'], #contact-form [name='postCode'], #contact-form [name='estimateNeeded']")
			.blur(function(){checkField($(this),isCompleted,"Field Required.")});
		$("#contact-form input[name='contactName']")
			.blur(function(){checkField($(this),isValidName,"Full Name Required.")});
		$("#contact-form select[name='contact']").change(function(){
			var phone = $("#contact-form input[name='phone']");
			var email = $("#contact-form input[name='email']");
			if ($(this).val() == "email") {
				clearOptional(email);	setOptional(phone);
			} else {
				clearOptional(phone); 	setOptional(email);
			}
		});
		
		/* Do fancy stuff for contact methods */
		$("#contact-form input[name='email']").change(function(){
			var nullpasses = $("#contact-form select[name='contact']").val() == "email" ? false : true;
			checkField($(this),isValidEmail,"Invalid email format. Please correct.",nullpasses);
		});	
		$("#contact-form input[name='phone']").change(function(){
			var nullpasses = $("#contact-form select[name='contact']").val() == "phone" ? false : true;
			checkField($(this),isValidPhone,"Phone numbers cannot contain letters (with the exception of 'ext'). Please correct.",nullpasses);
		});	
			
		/* SUBMIT */
		$("#contact-form").submit(function(){
			/* Last shot at validation */
			$("#contact-form input[name='companyName'], #contact-form [name='contactTitle'], #contact-form [name='message'], #contact-form [name='address'], #contact-form [name='city'], #contact-form [name='state'], #contact-form [name='postCode'], #contact-form [name='estimateNeeded']")
				.each(function(){checkField($(this),isCompleted,"Field Required.")});
			checkField($("#contact-form input[name='contactName']"),isValidName,"Full Name Required.");
			var nullpasses = $("#contact-form select[name='contact']").val() == "email" ? false : true;
			checkField($("#contact-form input[name='email']"),isValidEmail,"Invalid email format. Please correct.",nullpasses);
			nullpasses = $("#contact-form select[name='contact']").val() == "phone" ? false : true;
			checkField($("#contact-form input[name='phone']"),isValidPhone,"Phone numbers cannot contain letters (with the exception of 'ext'). Please correct.",nullpasses);

			
			if ($('.form_error').length) {
				// Form fields empty!
				alert("Please complete all fields.");
			} else { 
				$(this).attr("disabled", "true");  // no submitting twice!
				data_string = $("#contact-form form").serialize();
				// user feedback:
					$("#contact-form form").append($('<p class="sending">Please wait while we send your message...</p>')); 
					name = $("#contact-form input[name='contactName']").val();			
					$("#contact-form").fadeTo(500,.5);
				$.ajax({
				   type: "POST",
				   url: "/scripts/ajax/contact_process.php",
				   data: data_string,
				   async: false,
				   success: function(msg){
					$("#contact-form form").append(
						$("<p class='success column span-4 last'>Hello, <strong>"
							+ name	+"</strong>:<br />" + 
							"Thank you for your interest. You'll hear back from a representative soon.</p>")); 
					$("#contact-form").fadeTo(500,1);
				   },
				   error: function(obj,text,error) {
					$("#contact-form form").append(
						$("<p class='error column span-4 last'>Hello, <strong>"
							+ name	+ "</strong>:<br />" + 
							"Something went wrong when we tried to send your message. You can try again later "
							+ "or contact us another way: by phone at XXXXXXXXXXXXXXXXXXXXXXX or by e-mail at "
							+ "<a href='mailto:"+"XXXXXXXXXXXXXX"+">XXXXXXXXXXXXXXXXXXXX</a>.</p>")); 
					$("#contact-form").fadeTo(500,1);
				   },
				   complete: function() { $(".sending").remove(); }
				 });

				$("#contact-form fieldset").remove();
			}
			return false; // We don't want to submit the form since AJAX handled it
		});
	}

}

/*****************************************
 Helper Fcns
*****************************************/
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars(u)
{
	var url = u=="" ? window.location.href : u;
	var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
jQuery.fn.addNotice = function(element, time) {
	jQuery(this).prepend(element);
	element.animate({opacity:1},time, function(){
		jQuery(this).animate( {opacity: 0.0, height:0}, 1000, function() {jQuery(this).remove();})
	});
	return this;
}
function isCompleted(str) { str = trim(str); return str != ""; }
function isValidName(str) {
  var format = new RegExp("^.* .*$"); 
  var matches = format.exec(str);
  return matches;
}
function isValidEmail(str) {
  if (str == "optional") return true;
  var format = new RegExp("^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+[.])+[A-Za-z]{2,4}$"); 
  var matches = format.exec(str);
  return matches;
}
function isValidPhone(str) {
  if (str == "optional") return true;
  var format = new RegExp("^[-0-9ext,.\s ()+]+$"); 
  var matches = format.exec(str);
  return matches;
}
function checkField(element,check,error,nullpasses) {
	nullpasses = nullpasses ? (trim(element.val())=="" ? true : false) : false;
	element.removeClass('form_error');
	if (element.parent('div,p,li').children("span.error").length) 
			element.parent('div,p,li').children("span.error").remove();
	
	if (nullpasses || check(element.val())) return true; 
	
	element.addClass('form_error');
	$('<span class="error">'+error+'</span>').appendTo(element.parent('div,p,li'));
	return false;
									
}
function trim(str) {
	var	str = str.replace(/^\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function setOptional(el) {
	if (el.val() == "") el.val('optional').addClass('js_option');
	el.focus(function(){ if (el.val() == 'optional') el.val("").removeClass('js_option'); })
			 .blur(function(){ if (el.val() == "") el.val('optional').addClass('js_option'); }).change();	
}
function clearOptional(el) {
	if (el.val() == "optional") el.val("");
	el.removeClass('js_option').unbind('focus').unbind('blur');
}
jQuery.fn.pulse = function(time) {this.animate({opacity:.2},time).animate({opacity:1},time);return this;}

// ]]>

