function sendPartialData()
{
	if (formState == 1)
	{
		// send data if we have a partial form completion
		loadUTMValues();

		var company_name = document.forms[0].CompanyName.value;
		var firstname = document.forms[0].FirstName.value;
		var lastname = document.forms[0].LastName.value;
		var email = document.forms[0].Email.value;
		
		$.ajax({
			type: "POST", 
			url: "/vanillasoft/proxy.php", 
			async: true, 
			data: ({
			"signup": 1,
			"partial": 1,
			"ajax": 1,
			"SendWelcomeEmail": 0,
			"CreateContact": 1, 
			"CompanyName": company_name, 
			"Industry": "", 
			"NumUsers": "", 
			"FirstName": firstname, 
			"LastName": lastname, 
			"Title": "", 
			"Email": email, 
			"EmailConf": email, 
			"PhoneNumber": "",
			"Source": "",
			"Lite": $("#Lite").val(),
			"LeadSource": $("#LeadSource").val(),
			"AdWord": $("#AdWord").val(),
			"ClickTimestamp": $("#ClickTimestamp").val(),
			"Referrer": $("#Referrer").val(),
			"utmgclid": $("#utmgclid").val(),
			"utmccn": $("#utmccn").val(),
			"utmcmd": $("#utmcmd").val(),
			"utmctr": $("#utmctr").val(),
			"utmcsr": $("#utmcsr").val(),
			"NumVisits": $("#NumVisits").val(),
			"FirstVisit": $("#FirstVisit").val(),
			"AdWordsSource": $("#AdWordsSource").val(),		
			"USER_AGENT": navigator.userAgent
			}),
			dataType: "json",
			success: function(data) {
			}
		});
	}
}

var formState = 0;
function validate()
{
	if (formState == 0)
	{
		if (document.forms[0].FirstName.value == "")
		{
			alert('Please enter your First Name.');
			document.forms[0].FirstName.focus();
			return false;
		}	 
		if (document.forms[0].LastName.value == "")
		{
			alert('Please enter your Last Name.');
			document.forms[0].LastName.focus();
			return false;
		}
		if (document.forms[0].CompanyName.value == "")
		{
			alert('Please enter your Company Name.');
			document.forms[0].CompanyName.focus();
			return false;
		}
		if (document.forms[0].Email.value == "")
		{
			alert('Please enter your Email Address.');
			document.forms[0].Email.focus();
			return false;
		}
		if (!validateemail())
		{
			return false;
		}
		if (transmitting)
			return;
		formState = 1;
		displayForm();
		return;
	}
	else
	{

		if (formState == 2)
		{
			if (document.forms[0].FirstName.value == "")
			{
				alert('Please enter your First Name.');
				document.forms[0].FirstName.focus();
				return false;
			}	 
			if (document.forms[0].LastName.value == "")
			{
				alert('Please enter your Last Name.');
				document.forms[0].LastName.focus();
				return false;
			}
			if (document.forms[0].CompanyName.value == "")
			{
				alert('Please enter your Company Name.');
				document.forms[0].CompanyName.focus();
				return false;
			}
			if (document.forms[0].Email.value == "")
			{
				alert('Please enter your Email Address.');
				document.forms[0].Email.focus();
				return false;
			}
			if (!validateemail())
			{
				return false;
			}
		}
		
		formState = 2;
		
		if (document.forms[0].PhoneNumber.value == "")
		{
			alert('The Phone Number cannot be blank. Please insert your phone number.');
			document.forms[0].PhoneNumber.focus();
			return false;
		}	 
		if (typeof $('input[name=NumUsers]:checked').val() === "undefined")
		{
			alert('Please let us know your expected number of users.');
			return false;
		}

		if(checkCompanyName(document.forms[0].CompanyName.value) != "Company is valid.")
		{
			alert("This Company Name is already taken.  Please customize it.");
			return false;
		}
		if(checkEmail(document.forms[0].Email.value) != "Email entry is valid.")
		{
			alert("This Email Address is already taken.  Do you already have a Trial?  If so, please contact our Sales Department sales@vanillasoft.com");
			return false;
		}
		loadUTMValues();
		var spinner = document.getElementById('spinner');
		spinner.style.display = "inline";
		//document.forms[0].op.disabled = "disabled";
		document.forms[0].submit();
		return true;
	}
}
function displayForm() {

	if (formState == 0) {
	
		$('#TrialStep1').css("display", "inline");
		$('#TrialStep2').css("display", "none");
	} else if (formState == 1) {
		$('#TrialStep1').css("display", "none");
		$('#TrialStep2').css("display", "inline");
	}
}

function echeck(str)
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	if (str.indexOf(" ")!=-1){
		alert("Invalid E-Mail address. Please enter your E-Mail address.");
		return false;
	}
	return true;
}

function validateemail()
{
	var emailID=document.forms[0].Email;
	if ((emailID.value==null)||(emailID.value=="")){
		alert("Please enter a valid E-Mail address.");
		emailID.focus();
		return false;
	}
	if (echeck(emailID.value)==false){
		emailID.focus();
		return false;
	}
	return true;
}
 
function Get_Cookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
 
function saveValueToField(key, value)
{
	if (value != null)
	{
		var hdnField = document.getElementById(key);
		if (hdnField)
		{
			hdnField.value = value;
		}
	}
}
 
function loadUTMValues()
{
	var adWordsSource;
	 
	// load the the ad word from the cookie if it is there
	if (Get_Cookie("OriginalAdWord") == null)
	  saveValueToField("AdWord", Get_Cookie("AdWord"));
	else
	  saveValueToField("AdWord", Get_Cookie("OriginalAdWord"));

	var hdnLeadSource = document.getElementById("LeadSource");
	if (hdnLeadSource && hdnLeadSource.value.length == 0)
	{
		if (Get_Cookie("OriginalLeadSource") == null)
		  saveValueToField("LeadSource", Get_Cookie("LeadSource"));
		else
		  saveValueToField("LeadSource", Get_Cookie("OriginalLeadSource"));
	}

	if (Get_Cookie("OriginalReferrer") == null)
	  saveValueToField("Referrer", Get_Cookie("Referrer"));
	else
	  saveValueToField("Referrer", Get_Cookie("OriginalReferrer"));
	 
	saveValueToField("NumVisits", Get_Cookie("NumVisits"));
	saveValueToField("FirstVisit", Get_Cookie("FirstVisit"));
	saveValueToField("LandingPage", Get_Cookie("LandingPage"));
	 
	var UTMValue = Get_Cookie("Original__utmz");
	if (UTMValue  == null)
	{
		UTMValue = Get_Cookie("__utmz");
	  adWordsSource = "google";
	}
	else
	{
	  adWordsSource = "vanillasoft";
	}
	 
	saveValueToField("AdWordsSource", adWordsSource);
 
	if (!UTMValue || UTMValue == null || UTMValue.length == 0)
		return;
	var pieces = UTMValue.split("|");
	if (pieces != null && pieces.length > 0)
	{
		for (var i=0; i< pieces.length; ++i)
		{
			if (pieces[i] == null || pieces[i].length == 0)
				continue;
			  //alert(pieces[i]);
			var keyVal = pieces[i].split("=");
			if (keyVal.length != 2)
				continue;
			var key;
			if (keyVal[0].lastIndexOf(".") > 0)
			{
				if (keyVal[0].lastIndexOf(".") + 1 > keyVal[0].length - 1)
					continue;
				key = keyVal[0].substring(keyVal[0].lastIndexOf(".")+1);
			}
			else
				key = keyVal[0];
			//alert(key);
			saveValueToField(key, keyVal[1]);
		}
	}
}

/* Called from flash */

function checkCompanyName(company_name)
{
	if (company_name.length > 0)
	{
		var message = '';
		$.ajax({
			type: "GET", 
			url: "/vanillasoft/proxy.php", 
			async: false, 
			data: ({"check": "company", "value": company_name }),
			dataType: "json",
			success: function(data) {
				if (data.error)
				{
					sendProblem("company", company_name,"industry","number_users","firstname","lastname","user_title","email","phone","media_source");
						
					message = "This Company Name is already taken.  Please customize it.";
				}
				else
				{
					message = "Company is valid.";
				}
			}
		});
		return message;
	}
	else
	{
		return "Company is valid.";
	}
}

function checkEmail(email)
{
	if (email.length > 0)
	{
		var message = '';
		$.ajax({
			type: "GET", 
			url: "/vanillasoft/proxy.php", 
			async: false, 
			data: ({"check": "email", "value": email }),
			dataType: "json",
			success: function(data) {
				if (data.error)
				{
					sendProblem("email", "company_name","industry","number_users","firstname","lastname","user_title",email,"phone","media_source");
		
					message = "This Email Address is already taken.  Do you already have a Trial?  If so, please contact our Sales Department sales@vanillasoft.com";
				}
				else
				{
					message = "Email entry is valid.";
				}
			}
		});
		return message;
	}
	else
	{
		return "Email entry is valid.";
	}
}

function signUpWhitePaper(firstname,lastname,email,media_source)
{
	return simpleForm(firstname,lastname,email, "", media_source, 'whitepaper');
}

function signUpBrochure(firstname,lastname,email,media_source)
{
	return simpleForm(firstname,lastname,email, "", media_source, 'brochure');
}


function signUpContactUs(firstname,lastname,email,phone,media_source)
{
	return simpleForm(firstname,lastname,email, phone, media_source, 'contactus');
}


function simpleForm(firstname,lastname,email, phone, media_source, request_type)
{
	// validate fields
	// return string with any field errors

	// send values to server
	// return string with any errors

	// reutrn ""; on success
	loadUTMValues();
	
	var whitepaper = 0;
	var brochure = 0;
	var contactus = 0;
	if (request_type == "whitepaper")
	{
		whitepaper = 1;
	}
	else if (request_type == "brochure")
	{
		brochure = 1;
	}
	else if (request_type == "contactus")
	{
		contactus = 1;
	}	
	var returnMessage = "";
	$.ajax({
		type: "POST", 
		url: "/vanillasoft/proxy.php", 
		async: false, 
		data: ({

		"whitepaper": whitepaper,
		"brochure": brochure,
		"contactus": contactus,
		"ajax": 1,
		"CreateContact": 1, 
		"CompanyName": "", 
		"FirstName": firstname, 
		"LastName": lastname, 
		"Email": email, 
		"PhoneNumber": phone,
		"Source": media_source,
		"LeadSource": $("#LeadSource").val(),
		"AdWord": $("#AdWord").val(),
		"ClickTimestamp": $("#ClickTimestamp").val(),
		"Referrer": $("#Referrer").val(),
		"utmgclid": $("#utmgclid").val(),
		"utmccn": $("#utmccn").val(),
		"utmcmd": $("#utmcmd").val(),
		"utmctr": $("#utmctr").val(),
		"utmcsr": $("#utmcsr").val(),
		"NumVisits": $("#NumVisits").val(),
		"FirstVisit": $("#FirstVisit").val(),
		"AdWordsSource": $("#AdWordsSource").val(),
		"WatchedVideo": "1",
		"USER_AGENT": navigator.userAgent

	 	}),
		dataType: "json",
		success: function(data) {
			if (data.error)
			{
				returnMessage = data.message;
			}
			returnMessage = "New record created successfully.";
		}
	});
	
	return returnMessage;
}

function signUp(company_name,industry,number_users,firstname,lastname,user_title,email,phone,media_source)
{

	// validate fields
	// return string with any field errors

	// send values to server
	// return string with any errors

	// reutrn ""; on success
	loadUTMValues();
	var watchedVideo = readCookie("WatchedVideo");
	if (watchedVideo != null)
	{
		$("#WatchedVideo").val(watchedVideo);
	}
	$.ajax({
		type: "POST", 
		url: "/vanillasoft/proxy.php", 
		async: false, 
		data: ({
		"signup": 1,
		"ajax": 1,
		"SendWelcomeEmail": 1,
		"CreateContact": 1, 
		"CompanyName": company_name, 
		"Industry": industry, 
		"NumUsers": number_users, 
		"FirstName": firstname, 
		"LastName": lastname, 
		"Title": user_title, 
		"Email": email, 
		"EmailConf": email, 
		"PhoneNumber": phone,
		"Source": media_source,
		"Video": $("#Video").val(),
		"Lite": $("#Lite").val(),
		"LeadSource": $("#LeadSource").val(),
		"AdWord": $("#AdWord").val(),
		"ClickTimestamp": $("#ClickTimestamp").val(),
		"Referrer": $("#Referrer").val(),
		"utmgclid": $("#utmgclid").val(),
		"utmccn": $("#utmccn").val(),
		"utmcmd": $("#utmcmd").val(),
		"utmctr": $("#utmctr").val(),
		"utmcsr": $("#utmcsr").val(),
		"NumVisits": $("#NumVisits").val(),
		"FirstVisit": $("#FirstVisit").val(),
		"AdWordsSource": $("#AdWordsSource").val(),
		"WatchedVideo": $("#WatchedVideo").val(),
		"LandingPage": $("#LandingPage").val(),
		"USER_AGENT": navigator.userAgent
	 	}),
		dataType: "json",
		success: function(data) {
			if (data.error)
			{
				return data.message;
			}
			return "New record created successfully.";
		}
	});
}

function sendProblem(problemType, company_name,industry,number_users,firstname,lastname,user_title,email,phone,media_source)
{
	loadUTMValues();
	var watchedVideo = readCookie("WatchedVideo");
	if (watchedVideo != null)
	{
		$("#WatchedVideo").val(watchedVideo);
	}
	$.ajax({
		type: "POST", 
		url: "/vanillasoft/proxy.php", 
		async: true, 
		data: ({
		"signup": 0,
		"problem": problemType,
		"ajax": 1,
		"SendWelcomeEmail": 0,
		"CreateContact": 0, 
		"CompanyName": company_name, 
		"Industry": industry, 
		"NumUsers": number_users, 
		"FirstName": firstname, 
		"LastName": lastname, 
		"Title": user_title, 
		"Email": email, 
		"EmailConf": email, 
		"PhoneNumber": phone,
		"Source": media_source,
		"Video": $("#Video").val(),
		"Lite": $("#Lite").val(),
		"LeadSource": $("#LeadSource").val(),
		"AdWord": $("#AdWord").val(),
		"ClickTimestamp": $("#ClickTimestamp").val(),
		"Referrer": $("#Referrer").val(),
		"utmgclid": $("#utmgclid").val(),
		"utmccn": $("#utmccn").val(),
		"utmcmd": $("#utmcmd").val(),
		"utmctr": $("#utmctr").val(),
		"utmcsr": $("#utmcsr").val(),
		"NumVisits": $("#NumVisits").val(),
		"FirstVisit": $("#FirstVisit").val(),
		"AdWordsSource": $("#AdWordsSource").val(),
		"WatchedVideo": $("#WatchedVideo").val(),
		"USER_AGENT": navigator.userAgent
	 	}),
		dataType: "json",
		success: function(data) {
			if (data.error)
			{
				return data.message;
			}
			return "";
		}
	});
	
}

var transmitting = false;

$(document).ready(function(){

	$("body.landing").each(function(){
		window.onunload=sendPartialData;
	});
	$("body.landing #CompanyName, body.litelanding #CompanyName").blur(function(){

		if(checkCompanyName(this.value) != "Company is valid.")
		{
			alert("This Company Name is already taken.  Please customize it.");
			this.focus();
		}

	});
	$("body.landing #Email, body.litelanding #Email").blur(function(){

		if(checkEmail(this.value) != "Email entry is valid.")
		{
			alert("This Email Address is already taken.  Do you already have a Trial?  If so, please contact our Sales Department sales@vanillasoft.com");
			this.focus();
		}
	});

	$("#testsubmit").click(function(){
		//company_name,industry,number_users,firstname,lastname,title,email,phone
		//alert(signUpWhitePaper('Colin Video Signup Test3', 'Colin','McDonald', 'colin3@videotest.com', '1234567890', 'whitepaper'));
		testSubmitClick();
	});

	$(".litelanding").each(function() {
		formState = 2;
	})
	
	var watchedVideo = readCookie("WatchedVideo");
	if (watchedVideo != null)
	{
		$("#WatchedVideo").val(watchedVideo);
	}
	$("body.video").each(function(){
		$("#WatchedVideo").val("1");
	});
	loadUTMValues();
});