var strSignalName = "";
var strSignalFilter = "";
var promoApplied = false;

function validateContactForm(frm) {
/* This function validates that we have all required values and that the are of the correct type/format
*/
	var val = "";
	var idx = 0;
	
	val = frm.txtFirstName.value;
	if(! checkRequiredField(val)) {
		frm.txtFirstName.focus();
		alert("First Name is required.");
		return false;
	}
	
	val = frm.txtLastName.value;
	if(! checkRequiredField(val)) {
		frm.txtLastName.focus();
		alert("Last Name is required.");
		return false;
	}
	
	val = frm.txtPhone.value;
	if(! checkInternationalPhone(val)) {
		frm.txtPhone.focus();
		alert("Phone is required.");
		return false;
	}
	
	val = frm.txtEmail.value;
	if(!echeck(val)) {
		frm.txtEmail.focus();
		alert("Email is required.");
		return false;
	}
	
	val = frm.txtTitle.value;
	if(! checkRequiredField(val)) {
		frm.txtTitle.focus();
		alert("Title is required.");
		return false;
	}
	
	val = frm.txtCoName.value;
	if(! checkRequiredField(val)) {
		frm.txtCoName.focus();
		alert("Company Name is required.");
		return false;
	}
	
	idx = frm.cboDepartment.selectedIndex;
	val = frm.cboDepartment.options[idx].text;
	if(! checkRequiredField(val)) {
		frm.cboDepartment.focus();
		alert("Department is required.");
		return false;
	}
	
	idx = frm.cboEmployees.selectedIndex;
	val = frm.cboEmployees.options[idx].text;
	if(! checkRequiredField(val)) {
		frm.cboEmployees.focus();
		alert("Company Size is required.");
		return false;
	}
	
	idx = frm.cboIndustry.selectedIndex;
	val = frm.cboIndustry.options[idx].text;
	if(! checkRequiredField(val)) {
		frm.cboIndustry.focus();
		alert("Industry is required.");
		return false;
	}
	
	idx = frm.cboQuestion.selectedIndex;
	val = frm.cboQuestion.options[idx].text;
	if(! checkRequiredField(val)) {
		frm.cboQuestion.focus();
		alert("Type of Question is required.");
		return false;
	}
	
	val = frm.taMessage.value;
	if(! checkRequiredField(val)) {
		frm.taMessage.focus();
		alert("Message is required.");
		return false;
	}
	
	
	return true;


}


function saveContactForm(frm) {
/*	This function will (using AJAX and JQuery) save the form data */
	var URL = "/ajax/save-contact.php?";
	var idx = 0;
	
	idx = frm.cboDepartment.selectedIndex;
	var dpt = frm.cboDepartment.options[idx].text;
	idx = frm.cboEmployees.selectedIndex;
	var emp = frm.cboEmployees.options[idx].text;
	idx = frm.cboIndustry.selectedIndex;
	var ind = frm.cboIndustry.options[idx].text;
	idx = frm.cboQuestion.selectedIndex;
	var quest = frm.cboQuestion.options[idx].text;
	
	URL += "fname=" + encodeURI(frm.txtFirstName.value) + "&lname=" + encodeURI(frm.txtLastName.value) + "&phone=" + encodeURI(frm.txtPhone.value);
	URL += "&email=" + encodeURI(frm.txtEmail.value) + "&title=" + encodeURI(frm.txtTitle.value) + "&coname=" + encodeURI(frm.txtCoName.value) + "&dept=" + encodeURI(dpt);
	URL += "&size=" + encodeURI(emp) + "&industry=" + encodeURI(ind) + "&question=" + encodeURI(quest);
	URL += "&message=" + encodeURI(frm.taMessage.value);
	
	
	getXMLData(URL, contactSaved, contactSaveFailed) 
	
	return true;

}

function contactSaved(xml) {
	var strHTML;
	if($("result", xml).text() == "200") {
		// Record was inserted.
		$("#contact_main").empty();
		strHTML = "<p class='head_text'>Thank You for your interest in justSignal. Someone will be in touch within 24 hours.</p>";
		$("#contact_main").append(strHTML);
	} else {
		alert("There was an error submiting your information.");
	}
	
}
function contactSaveFailed() {
	alert("We could not process your request, please try again.");	
}

function submitContactForm(frm) {
/* This is the function called by the form on submit. It will manage the validataion and save process */
	
	if(validateContactForm(frm)) {
		saveContactForm(frm);
	}
	return false;

}

function checkRequiredField(txt) {
/* This function will ensure a required field has a valid value */

	if(txt == "Please Select") return false;
	
	if(txt.length < 1) return false;
	
	return true;

}
function pwdCheck(Pwd, cPwd) {
/*	This funciton checks to ensure a valid password was entered */
	var minLen = 8;
	
	if(Pwd == cPwd) {
		if(Pwd.length >=8 ) {
			return true;
		} else {
			alert("Your password must be 8 characters or more. Please try again.");
		}
	} else {
		alert("Your passwords do not match. Please try again.");
	}
	
	return false;
	
	
}


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 ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		alert("Invalid E-mail ID")
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		alert("Invalid E-mail ID")
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		alert("Invalid E-mail ID")
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		alert("Invalid E-mail ID")
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){
		alert("Invalid E-mail ID")
		return false
	 }

	 return true					
}

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	
	// Declaring required variables
	var digits = "0123456789";
	// non-digit characters which are allowed in phone numbers
	var phoneNumberDelimiters = "()-. ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;
	
	var bracket=3
	strPhone=trim(strPhone)
	if(strPhone.indexOf("+")>1) return false
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
	var brchr=strPhone.indexOf("(")
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
function getXMLData(URL, SuccessFunc, ErrorFunc) {
	// accpets the URL (for GET) and the function to call on success

	
	$.ajax({
		url: URL,
		type: 'GET',
		dataType: 'xml',
		success: function(xml) {
			SuccessFunc(xml);
			//alert("Good getXML call: ");
		},
		error: function(a,b,c) {
			ErrorFunc();
			alert("Failed getXML call: " + a.statusText);
		}
		
	});

}
function postXMLDoc(URL, strXML, SuccessFunc, ErrorFunc) {
/*	This function handles posting an XML document to a URL
		This is useful when the server side expects the
		XML to be the post body.
		
*/

	$.ajax({
		url: URL,
		type: 'POST',
		dataType: 'xml',
		processData: false,
		data: strXML,
		contentType: "text/xml",
		success: function(xml) {
			SuccessFunc(xml);
			//alert("Good getXML call: ");
		},
		error: function(a,b,c) {
			ErrorFunc();
			alert("Failed getXML call: " + a.statusText);
		}
		
	});
	
}

function submitSignalForm(frm) {
	// validate the entry
	if(frm.txtSvcName.value.length < 1) {
		frm.txtSvcName.focus();
		alert("Signal Name is required.");
		return false;
	}
	
	if(frm.taFilter.value.length < 1) {
		frm.taFilter.focus();
		alert("A Signal (filter) is required.");
		return false;
	}
	
	strSignalFilter = frm.taFilter.value;
	strSignalName = frm.txtSvcName.value;
	
	displayPayment();
	
	return false;
	
	
}

function displayPayment() {
	
	$("#order-js").empty();
	
	// Load the HTML from the template
	
	$("#order-js").load("/templates/acct-signup.html");
	
	// Now we would change the initial price for promo code orders.
	
	
	
	return false;
}

function submitAccountForm(frm) {
	
	var strURL = "/ajax/js_order_proc.php";
	var strXML = "";
	
	// Hide the button
	
	$("#js-order-submit").hide();
	$("#order-js").append("<p id='processing-status'>Processing your order... please be patient.</p>");
	
	// validate the form entry

	var val = "";
	
	val = frm.txtFName.value;
	if(! checkRequiredField(val)) {
		frm.txtFName.focus();
		alert("First Name is required.");
		$("#processing-status").remove();
		$("#js-order-submit").show();
		return false;
	}
	
	val = frm.txtLName.value;
	if(! checkRequiredField(val)) {
		frm.txtLName.focus();
		alert("Last Name is required.");
		$("#processing-status").remove();
		$("#js-order-submit").show();
		return false;
	}
	
	val = frm.txtPhone.value;
	if(! checkInternationalPhone(val)) {
		frm.txtPhone.focus();
		alert("Phone is required.");
		$("#processing-status").remove();
		$("#js-order-submit").show();
		return false;
	}
	
	val = frm.txtEmail.value;
	if(!echeck(val)) {
		frm.txtEmail.focus();
		alert("Email is required.");
		$("#processing-status").remove();
		$("#js-order-submit").show();
		return false;
	}
	
	if(!pwdCheck(frm.txtPword.value, frm.txtCPword.value)) {
		frm.txtPword.focus();
		$("#processing-status").remove();
		$("#js-order-submit").show();
		return false;
	}
	
	// Now Check the Billing Info
	
	if(frm.txtCardNum.value.length < 15 || !(isInteger(frm.txtCardNum.value))) {
		frm.txtCardNum.focus();
		alert("The card number appears to be invalid.");
		$("#processing-status").remove();
		$("#js-order-submit").show();
		return false;
	}
	
	// Check for Promo Code
	
	if(frm.txtPromoCode.value.length > 1) {
		// Apply the Promo Code
		applyPromo(frm.txtPromoCode.value);
	}
	
	// New fields, billing address and CCV code
	if(frm.txtCCV.value.length < 3 || !(isInteger(frm.txtCCV.value))) {
		frm.txtCCV.focus();
		alert("The CCV code appears to be invalid.");
		$("#processing-status").remove();
		$("js-order-submit").show();
		return false;
	}
	
	if(frm.txtAddress.value.length < 4) {
		frm.txtAddress.focus();
		alert("The billing address appears to be invalid.");
		$("#processing-status").remove();
		$("js-order-submit").show();
		return false;
	}
	
	if(frm.txtCity.value.length < 2) {
		frm.txtCity.focus();
		alert("The billing City appears to be invalid.");
		$("#processing-status").remove();
		$("js-order-submit").show();
		return false;
	}
	
	if(frm.txtState.value.length < 2) {
		frm.txtState.focus();
		alert("The billing state appears to be invalid.");
		$("#processing-status").remove();
		$("js-order-submit").show();
		return false;
	}
	if(frm.txtZip.value.length != 5 || !(isInteger(frm.txtZip.value))) {
		frm.txtZip.focus();
		alert("The billing zip code appears to be invalid.");
		$("#processing-status").remove();
		$("js-order-submit").show();
		return false;
	}
	
	
	// Make the order XML Doc
	
	
	
	strXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
	strXML += "<xml><order>";
	
	strXML += "<svc_name>" + escape(strSignalName) + "</svc_name>";
	strXML += "<signal_filter>" + escape(strSignalFilter) + "</signal_filter>";
	strXML += "<first_name>" + escape(frm.txtFName.value) + "</first_name>";
	strXML += "<last_name>" + escape(frm.txtLName.value) + "</last_name>";
	strXML += "<bill_address>" + escape(frm.txtAddress.value) + "</bill_address>";
	strXML += "<bill_city>" + escape(frm.txtCity.value) + "</bill_city>";
	strXML += "<bill_state>" + escape(frm.txtState.value) + "</bill_state>";
	strXML += "<bill_zip>" + escape(frm.txtZip.value) + "</bill_zip>";
	strXML += "<email>" + escape(frm.txtEmail.value) + "</email>";
	strXML += "<phone>" + escape(frm.txtPhone.value) + "</phone>";
	strXML += "<pwd>" + escape(hex_md5(frm.txtPword.value)) + "</pwd>";
	var idx = frm.cboCardType.selectedIndex;
	var cardtype = frm.cboCardType.options[idx].text;
	strXML += "<card_type>" + escape(cardtype) + "</card_type>";
	strXML += "<card_num>" + escape(frm.txtCardNum.value) + "</card_num>";
	strXML += "<card_ccv>" + escape(frm.txtCCV.value) + "</card_ccv>";
	var idx = frm.cboExpMonth.selectedIndex;
	var expmonth = frm.cboExpMonth.options[idx].text;
	strXML += "<exp_month>" + escape(expmonth) + "</exp_month>";
	var idx = frm.cboExpYear.selectedIndex;
	var expyear = frm.cboExpYear.options[idx].text;
	strXML += "<exp_year>" + escape(expyear) + "</exp_year>";
	strXML += "<promo_code>" + escape(frm.txtPromoCode.value) + "</promo_code>";
	strXML += "<sku>jsbase</sku>";
	
	strXML += "</order></xml>";
	
	
	
	
	// POST it and wait for a response
	postXMLDoc(strURL, strXML, processOrderResult, orderSubmitError);
	
	
	
	return false;
}


function processOrderResult(xml) {
/*
	This funciton handles an order sumission that returns a valid
	xml document.
	
	This does not mean the order processed... just that the HTTP
	transaction worked.	
*/
	var strHTML;

	if($("result", xml).text() == "200") {
		// Record was inserted.
		var orderDate = new Date();
		
		$("#order-js").empty();
		
		strHTML = "<span class='order-complete'><p class='section_heading'>Your justSignal Subscription is now active.</p><p>Your order number: <b>";
		strHTML += $("order_number", xml).text() + " was processed on: " + orderDate.toString() + "</b> Please save this for your records.</p>";
		strHTML += "<p class='section_heading'>Order Summary:</p><div class='clear'></div>";
		strHTML += "<table class='order-summary'><tr class='due-now'><td>Charged Today:</td><td class='first-month'>$";
		strHTML += $("first_month", xml).text() + "</td></tr><tr><td>Each Subsequent Month:</td><td>$";
		strHTML += $("every_month", xml).text() + "</td></tr></table>";
		strHTML += "<p class='section_heading'>You can head on over to the <a href='https://justsignal.com/portal'>Portal</a> ";
		strHTML += "and log in to your account.</p>";
		strHTML += "<p>The last thing you need is another email, so we don't send order confirmation emails. Please print this page if you need a reciept.</p>";
		strHTML += "<p>NOTE: It may take up to 15 mintues for your widgets to be activated.</p></span>";
		
		$("#order-js").append(strHTML);
		
		window.location = "#top";
		
		$("#order-wrap").animate( {height:380}, 200);
		
	} else {
		// Append the new HTML to the #order-js div
		$("#processing-status").remove();
		$("#js-order-submit").show();
		strHTML = "<p id='processing-status'>Uh oh... something went terribly wrong...<br/>";
		if($("result", xml).text() == "300") {
			// Credit Card Error
			strHTML += $("message", xml).text() + "<br/>";
		} else {
			strHTML += $("error", xml).text() + "<br/>";
		}
		strHTML += "</p>";
		
		$("#order-js").append(strHTML);
	}

	
}

function orderSubmitError() {
/* 
	This function handles an error in the AJAX transaction
	to submit an order.
	
	
*/


}


function applyPromo(strCode) {
/*	This function looks up the promo code (using ajax)
	and applies it to the listed pricing 				*/
	
	var strURL = "/ajax/get-promo-code.php?pc=" + strCode;
	
	getXMLData(strURL, updatePromoTotals, promoLookupFail);
	
}

function updatePromoTotals(xml) {
/* This function will validate the XML returned and
	(if the xml does not contain an error) update
	the prices with the promo prices.
*/

	if($("result", xml).text() == "200") {
		// Record was inserted.
		$("#promo-result").empty();
		strHTML = "<p class='head_text'>Your Promo Code has been applied.</p>";
		$("#promo-result").append(strHTML);
		// now we update the pricing table
		$("#first-month").empty();
		$("#first-month").append("$"+$("first_month", xml).text());
		$("#due-now").empty();
		$("#due-now").append("$"+$("std_month", xml).text());
		$("#each-month").empty();
		$("#each-month").append("$"+$("std_month", xml).text());
		
	} else {
		$("#promo-result").empty();
		strHTML = "<p class='head_text'>" + $("error", xml).text() + "</p>";
		$("#promo-result").append(strHTML);
		// now we update the pricing table
		$("#first-month").empty();
		$("#first-month").append("$59.00");
		$("#due-now").empty();
		$("#due-now").append("$59.00");
		$("#each-month").empty();
		$("#each-month").append("$59.00");
		$("#txtPromoCode").val(""); 
	}	
	
	
}

function promoLookupFail() {
	$("#promo-result").empty();
	strHTML = "<p class='head_text>There was an error processing your Promo Code.</p>";
	$("#promo-result").append(strHTML);
}

function setPromoCode() {
	applyPromo($("#txtPromoCode").val());
}

function tryFilterOnTwitter() {
	var strTwitUrl = "http://search.twitter.com/search?q=";
	var strFilterTAName;
	var strNewFilter;
	var aryFilterParts;
	var strModFilter;
	 
	
	strNewFilter = $("#taFilter").val();
	aryFilterParts = strNewFilter.split(",");
	
	for(var i in aryFilterParts) {
		if(i == 0) {
			strModFilter = trim(aryFilterParts[i]) + " OR ";
		} else if(i == (aryFilterParts.length - 1)) {
			// last one.. nor or
			strModFilter += trim(aryFilterParts[i]);
		} else {
			strModFilter += trim(aryFilterParts[i]) + " OR ";
		}
	}
	
	window.open(strTwitUrl + escape(strModFilter), '_blank');
	return false;	
}