﻿
// state variables
var _sd = new SiteDictionary("../../Shared/ClientScripts/ContactUs/validation.dictionary.xml");		
var _validating = false;	// do not validate another field until current is valid
var _validatingObject = null;	// hold the field being validated
var _reqFields = ["first_name","last_name","main_phone","email","doc_file","ContactUsTemplate_Phone1PrefixList","ContactUsNSTemplate_Phone1PrefixList","ContactUsNSTemplate_HearAboutList"]; 
var _allowedImgFileTypes = ["jpg","gif","jpeg"]; 
var _allowedDocFileTypes = ["doc","pdf"]; 
var _formName = "";
var _templateId = "";
var _posting = false;
var _SendSuccess, _SendFail;
var isProcessSuccess = false;

// 1. called onBlur by each field
// 2. called for each field during saving form as XML
function validateField(o, testReqFields)
{
	if (testReqFields == null) testReqFields = false;
	
	
	
	
	if (!_validating || (_validating && _validatingObject == o))
	{
		// required field - validate non null
		if (testReqFields && a_in_array(o.id, _reqFields))
		{
			if (o.value == null || o.value == '')
			{
				alert(_sd.get("emptyField"));
				o.focus();
				_validatingObject = o;
				_validating = true;
				o.style.backgroundColor="yellow";
				return false;
			}
		}
		
		// any field - content validation by type and id		
		switch(o.type)
		{
			
			case "radio":
			case "checkbox":
			break;
			
			case "text":
				o.value = removeInvalidChars(o.value);
				if (testReqFields && o.value != null && o.value != '')
				{
					if (o.id.indexOf("main_phone")>-1 ||
						o.id.indexOf("secondary_phone")>-1 ||
						o.id.indexOf("fax")>-1)
					{
						// validate phone numbers
						if (!isPhoneNumber(o.value))
						{
							alert(_sd.get("noNumberField"));
							o.focus();
							// set this field as _validating
							_validatingObject = o;
							_validating = true;
							o.style.backgroundColor="yellow";	
							return false;	
						}
					}
					else if(o.id.indexOf("email")>-1)
					{
						// validate email address
						if (!isEmail(o.value))
						{
							alert(_sd.get("noEmailField"));
							o.focus();
							// set this field as _validating
							_validatingObject = o;
							_validating = true;
							o.style.backgroundColor="yellow";
							return false;	
						}
					}
				}
				
			break;
			
			case "textarea":
				o.value = removeInvalidChars(o.value);
				break;
			case "file":
				
				o.value = removeInvalidChars(o.value);
				if (testReqFields && o.value != null && o.value != '') 
				{	
					var valid_type = (o.id.indexOf("image")>-1)?filterFileTypes(o.value):filterFileTypes(o.value,"doc");
					if (!valid_type)
					{
						alert(_sd.get("invalidFileType"));
						o.focus();
						_validatingObject = o;
						_validating = true;
						o.style.backgroundColor="yellow";
						return false;
					}
				}
			break;
		}
		
		// reset on each call
		_validatingObject = null;
		_validating = false;
		o.style.backgroundColor="white";
		
	}
	return true;
}
function isPhoneNumber(str)
{
    return(str.match(/^[ ]*[0-9]{7}[ ]*$/)!=null); // number||null
}
function isEmail(str)
{
	return (str.match(/^([a-zA-Z0-9_\-\.]+)@[\w-]+\.([a-zA-Z]+|[a-zA-Z]+\.[a-zA-Z]+)$/)!=null);
}
function removeInvalidChars(str)
{
	str = str.replace(/[#\$%\^<>;&\*\+=\'\"]*/g,"");
	return str
}
function filterFileTypes(str, testtype)
{
	var ext = str.substring(str.lastIndexOf(".")+1, str.length).toLowerCase();
	if (testtype == "doc")
	{
		return (a_in_array(ext,_allowedImgFileTypes) || a_in_array(ext,_allowedDocFileTypes));	
	}
	return (a_in_array(ext,_allowedImgFileTypes));
}

function a_in_array(a,arr)
{
	for (i=0;i<arr.length;i++)
	{
		if (a.indexOf(arr[i])>-1)
		{
			return true;
		}
	}
	return false;
}



function Submit(imgSubmit, formName, templateId)
{
	
	if (templateId==null) templateId = "";
	_formName = formName;
	_templateId = templateId;
	if (_posting)
	{
		alert(_sd.get("AlreadyPosted"));
	}
	else
	{
		SaveXMLForm();
	}
}


function SubmitHP_NS(imgSubmit, formName)
{
	_templateId = '';
	_formName = formName;
	var form = document.getElementById(_formName);
	var _EmptyField = form["EmptyField"].value;
	var _InvalidPhone = form["InvalidPhone"].value;
	_SendSuccess = form["SendSuccess"].value;
	_SendFail = form["SendFail"].value;
	_MailSubject = form["MailSubject"].value;
		
	var msgTd = document.getElementById("tdServerMessage");
	msgTd.style.display = 'inline';
	
	if (_posting)
	{
		if (isProcessSuccess)
		{
			msgTd.innerText = _SendSuccess;
		}
		else
		{
			msgTd.innerText = _SendFail;
		}
	}
	else
	{
		var o = form["first_name"];
		if (o.value == null || o.value == '')
		{
			o.focus();
			msgTd.innerText = _EmptyField;
			o.style.backgroundColor="yellow";
			return false;
		}
		
		var o = form["main_phone"];
		if (o.value == null || o.value == '')
		{
			o.focus();
			msgTd.innerText = _EmptyField;
			o.style.backgroundColor="yellow";
			return false;
		}
		
		if (!isPhoneNumber(o.value))
		{
			o.focus();
			msgTd.innerText = _InvalidPhone;
			o.style.backgroundColor="yellow";
			return false;
		}			
		_posting = true;
		
		var f = form["Phone1PrefixList"];
		var prefix = f.options[f.selectedIndex].value;
		
		var strXML = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
			strXML += "<FORM CSDocID=\""+form["CSDocID"].value+"\">";
			strXML += "<FIELD ID=\"first_name\" VALUE=\""+form["first_name"].value+"\"/>";
			strXML += "<FIELD ID=\"main_phone\" VALUE=\""+form["main_phone"].value+"\"/>";
			strXML += "<FIELD ID=\"Phone1PrefixList\" VALUE=\""+prefix+"\"/>";
			strXML += "<FIELD ID=\"ApplicationSubjectList\" VALUE=\""+_MailSubject+"\"/>";
			
			strXML += "</FORM>";
		var xmlDoc   = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = false;
		try
		{
			xmlDoc.loadXML(strXML);
		}
		catch(e)
		{
		}
		PostXMLData(xmlDoc);
	}
}
function SaveXMLForm()
{
	
	_posting = true;
	
	var _validForm = true;
	var form = document.getElementById(_formName);
	
	var baseXml = new BaseXML("../../Shared/ClientScripts/ContactUs/BaseForm.xml");
	var root = baseXml.selectSingleNode("FORM");
	var fieldNodes = root.selectNodes("FIELD");
	
	_SendSuccess = form[_templateId + "SendSuccess"].value;
	_SendFail = form[_templateId + "SendFail"].value;

	// copy field values into the base form XML
	/// only fields found in the base XML are copied into it. 
	for (var i=0;i<fieldNodes.length && _validForm;i++)
	{
		try
		{
			var fieldNode = fieldNodes.nextNode();
			var fieldName = fieldNode.getAttribute("ID");
			var formField = null;
			var formFieldValue = "";
			try
			{
				formField = form[_templateId + fieldName];
				//alert(fieldName + " - " + formField);
				if (formField != null)
				{
					if (!validateField(formField, true))
					{
						_validForm = false;
						_posting = false;
					}
					else
					{
						switch(formField.type)
						{
							case "text":
							case "file":
								formFieldValue = formField.value;
							break;
							
							case "radio":
							case "checkbox":
								formFieldValue = formField.checked?1:0;
							break;
							
							case "select":
							case "select-one":
								formFieldValue = formField[formField.selectedIndex].text;
							break;
							
							case "textarea":
								formFieldValue = formField.innerText;
							break;
						}
					}
				}
			}catch(e){}
			
			// if this field exist in the XML but not in the HTML form, remove it from the XML
			if (formField == null)
			{
				baseXml.documentElement.removeChild(fieldNode);
			}
			else
			{
				fieldNode.setAttribute("VALUE",formFieldValue);
			}
		}
		catch(e)
		{
			continue;
		}
	}
	
	
		
	if (_validForm)
	{
		root.setAttribute("CSDocID",form[_templateId + "CSDocID"].value); // NS/IS/HR/SP
		root.setAttribute("TemplateID",form[_templateId + "currentCss"].value); // NS/IS/HR/SP
		//alert(baseXml.xml);
		PostXMLData(baseXml);
	}
}
function BaseXML(path)
{
	try
	{
		this.xmlDoc       = new ActiveXObject("Microsoft.XMLDOM");
		this.xmlDoc.async = false;
		
		if(!this.xmlDoc.load(path))
		{
			var err		= this.xmlDoc.parseError;
		}
	}
	catch(e)
	{ 
		//alert("BaseXML() error="+e.description);
	}
	return this.xmlDoc;
}

function PostXMLData(xmldoc)
{
	//alert("PostXMLData");
	var url	= getHostAddress() + "/TemplateControls/ContactUs/SendMessage.aspx";
	
	isProcessSuccess = true;
	try
	{
		xmlhttp	= new ActiveXObject("Microsoft.XMLHTTP");
		//xmlhttp	= new ActiveXObject("Msxml2.XMLHTTP");
		
		xmlhttp.onreadystatechange	= HandleStateChange;		
		xmlhttp.Open("POST", url, false);
		xmlhttp.setRequestHeader("Content-Type", "text/xml; charset='utf-8' ");
		xmlhttp.Send(xmldoc);
	}
	catch (e)
	{
		//"postXMLData() "+ws("postXMLData() "+e.description);
		isProcessSuccess = false;
	}
	
	// display message according to submission results
	var msgTd = document.getElementById(_templateId + "tdServerMessage");
	msgTd.style.display = 'inline';
	
	
	if (isProcessSuccess)
	{
		//msgTd.innerText = _SendSuccess;
		window.location.href= contactUsUrl + "?SuccessSend=1";
	}
	else
	{
		msgTd.innerText = _SendFail;
		_posting = false;
	}
	xmlhttp = null;
	
	return;

//'''''''''''''''''''''''''
	function HandleStateChange()
	{
		if(xmlhttp.readyState==4)
		{
			try
			{
				if(xmlhttp.responseText)
				{
					var xmlRes = new ActiveXObject("Microsoft.XMLDOM");
					xmlRes.async = false;
					xmlRes.loadXML(xmlhttp.responseText);

					var nodes = xmlRes.selectNodes("//ROWSET/ROW");
					if (node = nodes.nextNode()) 
					{
						isProcessSuccess = node.getAttribute("id");
					}
					else
					{
						isProcessSuccess = false; 
					}	
				}
			}
			catch(e){
				//alert("err ; " + e.description)
			}
			window.status	= "Done";
		}
	}
}
function showSuccessMsg()
{
	var _SendSuccess = document.getElementById("ContactUsTemplate_SendSuccess").value;
	var msgTd = document.getElementById("ContactUsTemplate_tdServerMessage");
	msgTd.style.display = 'inline';
	msgTd.innerText = _SendSuccess;
	
}

function SiteDictionary(path)
{
	try
	{
		this.dom       = new ActiveXObject("Microsoft.XMLDOM");
		this.dom.async = false;
		
		if(!this.dom.load(path))
		{
			var err		= this.dom.parseError;
		}
	}
	catch(e)
	{ 
		//alert("SiteDictionary() error="+e.description);
	}
}
function SiteDictionary.prototype.get(word)
{
	var xpath	= "/SITE/KEY[@ID='"+word+"']";
	
	try
	{
		return this.dom.selectSingleNode(xpath).text;
	}
	catch(e)
	{
		//alert("SiteDictionary.get("+xpath+") \n error="+e.description);
	}
	return word;
}


function displayAge(o, current_year)
{
	var age = "";
	var display_year = document.getElementById("display_year");
	try
	{
		if (current_year >= 2007)
		{
			age = current_year - o.options[o.selectedIndex].value;
		}
	}catch(e){}
	display_year.value = age;
}

function ContactImmediately()
{
	_templateId = '';
	var form = document.getElementById(_formName);
	var _EmptyField = document.getElementById("ucContactImmediately_EmptyField").value;
	var _InvalidPhone = document.getElementById("ucContactImmediately_InvalidPhone").value;
	_SendSuccess = document.getElementById("ucContactImmediately_SendSuccess").value;
	_SendFail = document.getElementById("ucContactImmediately_SendFail").value;
	_MailSubject = document.getElementById("ucContactImmediately_MailSubject").value;
		
	var msgTd = document.getElementById("tdServerMessage");
	msgTd.style.display = 'inline';
	
	if (_posting)
	{
		if (isProcessSuccess)
		{
			msgTd.innerText = _SendSuccess;
		}
		else
		{
			msgTd.innerText = _SendFail;
		}
	}
	else
	{
		var o = document.getElementById("ucContactImmediately_first_name");
		if (o.value == null || o.value == '')
		{
			o.focus();
			msgTd.innerText = _EmptyField;
			o.style.backgroundColor="yellow";
			return false;
		}
		
		var o = document.getElementById("ucContactImmediately_main_phone");
		if (o.value == null || o.value == '')
		{
			o.focus();
			msgTd.innerText = _EmptyField;
			o.style.backgroundColor="yellow";
			return false;
		}
		
		if (!isPhoneNumber(o.value))
		{
			o.focus();
			msgTd.innerText = _InvalidPhone;
			o.style.backgroundColor="yellow";
			return false;
		}			
		_posting = true;
		
		var f = document.getElementById("ucContactImmediately_Phone1PrefixList");
		var prefix = f.options[f.selectedIndex].value;
		
		var strXML = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
			strXML += "<FORM CSDocID=\""+document.getElementById("ucContactImmediately_CSDocID").value+"\">";
			strXML += "<FIELD ID=\"first_name\" VALUE=\""+document.getElementById("ucContactImmediately_first_name").value+"\"/>";
			strXML += "<FIELD ID=\"main_phone\" VALUE=\""+document.getElementById("ucContactImmediately_main_phone").value+"\"/>";
			strXML += "<FIELD ID=\"Phone1PrefixList\" VALUE=\""+prefix+"\"/>";
			strXML += "<FIELD ID=\"ApplicationSubjectList\" VALUE=\""+_MailSubject+"\"/>";
			
			strXML += "</FORM>";
		var xmlDoc   = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = false;
		try
		{
			xmlDoc.loadXML(strXML);
		}
		catch(e)
		{
		}
		PostXMLData(xmlDoc);
	}
}