// requestDemo functions

$(document).ready(init);
	
function init() {
	$("#demoForm").submit(validateForm);
	$(".emailLink").each(replaceEmailText);
}

function replaceEmailText (){ 
	var 	href = $(this).attr("href"),
			hrefSplit,
			email;
	hrefSplit = href.split(": ");
	hrefSplit = hrefSplit[1].split("?");
	email = hrefSplit[0];
	
	$(this).html(email);
}	

function validateForm() {
	var errors = [];
	var formData;
	
	$("label").css({'font-weight':'normal', 'color': '#ffffff'});
	
	$("input", this).each(function (){
		var 	type = $(this).attr("rel");
				value = $(this).val();
					
		if (type === "required" && value === ""){
			errors.push($(this).siblings("label"));
		} else if (type === "email" && value === "" && !validateEmail(value)) {
			errors.push($(this).siblings("label"));
		} else if (type === "telephone" && !validateTelephone(value) && value !== "") {
			errors.push($(this).siblings("label"));
		}
	});
	
	
	if (errors.length){
		for (var i = 0, count = errors.length; i < count; i++){
			$(errors[i]).css({'font-weight':'bold', 'color': "#d7b18e"});
		}
		$("#form-message").hide();
		$("#form-message")
			.html("<p>You have errors in your submission.  Please double check and try again.</p>")
			.fadeIn("fast");
		return false;
	}
	
	
	formData = {
		firstName : $("input[name='fname']", this).val(),
		lastName : $("input[name='lname']", this).val(),
		company : $("input[name='company']", this).val(),
		title : $("input[name='title']", this).val(),
		email : $("input[name='email']", this).val(),
		phone : $("input[name='phone']", this).val()
	}
	
	
	$.ajax({
	   type: "POST",
	   url: "processForm.cfm",
	   dataType: "XML",
	   data: formData,
	   success: formSuccess
	 });
		
	return false;
}

function formSuccess (){
	$("#form-message").hide();
	$("#form-message")
		.html("<p>Thank you for requesting a demo of Prexis&reg;.  A representative will contact you shortly to set up a date and time.</p>")
		.fadeIn("fast");
		
	$("input").val("");
}

function validateEmail (str){		
	var regEx = new RegExp(/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/);
	if (regEx.test(str)) return true;
	return false;
}

function validateTelephone (str){
	var regEx = new RegExp(/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/);
	if (regEx.test(str)) return true;
	return false;
}

