// _deltains_functions.js

var req = null;
//var console = null;
var READY_STATE_UNINITIALIZED = 0;
var READY_STATE_LOADING = 1;
var READY_STATE_LOADED = 2;
var READY_STATE_INTERACTIVE = 3;
var READY_STATE_COMPLETE = 4;

// Returns reference to form according to user agent's convention
function getFormElement()
{
	if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1)
		f = document.form1;
	else
		f = document.forms["form1"];
	return(f);
}

// Returns true if string is completely whitespace
function isBlank(s)
{	
	s = s.replace(/(^\s*)|(\s*$)/g, "");
	return (s == '');
}

// Returns string devoid of leading and trailing spaces
function trimString(s)
{
    return s.replace(/(^\s*)|(\s*$)/g, "");
}

// Sets monitor's pixel width/height
function getWH()
{
	f = getFormElement();
	f.formW.value = screen.width;
	f.formH.value = screen.height;
}


// Validates DELTADIRECT Log On form
function verifyLogOnFields()
{
	var authUser = document.getElementById('authUser');	
	if (true || authUser.value == 'true')		// Temporary
	{
		var f = getFormElement();
		var s = '';
		var BlankUsername = false;
		var BlankPassword = false;
		f.formUsername.value = trimString(f.formUsername.value);
		f.formPassword.value = trimString(f.formPassword.value);
		if ((f.formUsername.value == '911') || (f.formUsername.value == '9-1-1'))
		{
			document.location = 'http://www.deltains.com/911';
			return false;
		}
		else if (f.formUsername.value.toLowerCase() == 'citrix')
		{
			document.location = 'https://citrix.deltains.com';
			return false;
		}
		else
		{	
			if (isBlank(f.formUsername.value)) { s += '\n- Login'; BlankUsername = true; }
			if (isBlank(f.formPassword.value)) { s += '\n- Password'; BlankPassword = true; }
			if (s.length)
			{
				alert('Please enter the following fields in the\nDELTADIRECT Agent Log On form:\n'+s);
				if (BlankUsername) f.formUsername.focus();
				else if (BlankPassword)	f.formPassword.focus();
				return false;
			}
			else return true;
		}
	}
	else
	{
		toConsole(true);
		return false;
	}
}

// Returns 'inline' (visible) or 'none' (not visible)
function getVisibleStatus(targetName) {
    if (document.getElementById) { // NS6+
        target = document.getElementById(targetName);
    } else if (document.all) { // IE4+
        target = document.all[targetName];
    }    
    if (target) return (target.style.display);
} 

// Set status of 'inline' (visible) or 'none' (not visible)
function setVisibleStatus(targetName, status) {
    if (document.getElementById) { // NS6+
        target = document.getElementById(targetName);
    } else if (document.all) { // IE4+
        target = document.all[targetName];
    }    
    if (target) target.style.display = status;
}

// Show/Hide element; accepts name of element
function toggleDisplay(e)
{
	if (getVisibleStatus(e) == 'inline')
		setVisibleStatus(e, 'none');
	else
		setVisibleStatus(e, 'inline');
}

// Handles CSS font size changes
function selectCSS(s)
{
	u = document.location.href;
	h = u.indexOf('#');
	if (h > -1)
	{
		anch = u.substring(h, u.length);
		u = u.substring(0, h);
		q = u.indexOf('?');
		if (q > -1) u = u.substring(0, q);				
		u = u + '?css='+s+anch;
	}
	else
	{
		q = u.indexOf('?');
		if (q > -1) u = u.substring(0, q);
		u = u + '?css='+s;
	}
	document.location = u;
}


// Returns true if address follows SMTP syntax
function followsSMTPSyntax(a)
{
	var FlagEmail = false;
	var regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	if (a.match(regex))
	{
		LastPeriod = a.lastIndexOf('.');
		if (LastPeriod < a.length-1)
		{
			arrayTLD = new Array('co', 'com', 'net', 'cc', 'org', 'us', 'info', 'biz', 'bz', 'mobi');			
			TLD = a.substr(LastPeriod+1);
			for (i=0; i<arrayTLD.length; i++)
				if (TLD == arrayTLD[i])
				{
					FlagEmail = true;
					break;
				}
		}
		return FlagEmail;
	}
	else return false;
}


// Allows user to confirm logoff
function confirmClear()
{
	if (confirm('Do you want your DELTADIRECT login credentials to be removed from this computer?\n\nIf so, click on \'OK\'; otherwise, click on \'Cancel\'.'))
		document.location = 'clear.cfm';
	else return;
}

// Handles Quick List
function handleQuickList()
{
	f = document.form2;
	document.location = f.formQuickList.options[f.formQuickList.selectedIndex].value;
}

// Shows printer-friendly carriers page
function handlePrinterFriendlyCarriers()
{
	window.open('carriers_pf.html', 'pfdeltainsgencies', 'scrollbars=yes,status=no,location=no,toolbar=no,menubar=no,resizable=yes,width=785,height=558,left=10,top=10');
}


// Manipulates images
function MM_swapImgRestore()
{
	var i,x,a=document.MM_sr;
	for (i=0; a && i<a.length && (x=a[i]) && x.oSrc; i++)
		x.src = x.oSrc;
}

// Manipulates images
function MM_preloadImages()
{
	var d=document;
	if (d.images)
	{
		if(!d.MM_p) d.MM_p=new Array();
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
		for(i=0; i<a.length; i++)
			if (a[i].indexOf("#")!=0)
			{
				d.MM_p[j]=new Image;
				d.MM_p[j++].src=a[i];
			}
	}
}

// Manipulates images
function MM_findObj(n, d)
{
	var p,i,x;
	if (!d) d=document;
	if ( (p=n.indexOf("?") ) > 0 && parent.frames.length)
	{
		d=parent.frames[n.substring(p+1)].document;
		n=n.substring(0,p);
	}
	if (!(x=d[n])&&d.all) x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for (i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if (!x && d.getElementById) x=d.getElementById(n);
	return x;
}

// Manipulates images
function MM_swapImage()
{
	var i,j=0,x,a=MM_swapImage.arguments;
	document.MM_sr=new Array;
	for (i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null)
		{
			document.MM_sr[j++]=x;
			if (!x.oSrc) x.oSrc=x.src;
			x.src=a[i+2];
		}
}

// Sets target of rollover image link
function setRolloverLink(u, s)
{
	document.getElementById('rolloverLinkImg').href = u;
	document.getElementById('rolloverInfo').innerHTML = s;
	if (u.indexOf('http') > -1) aTarget = "_blank"; else aTarget = "_self";
	document.getElementById('rolloverLinkImg').target = aTarget;
}

// Verify string of n digits
function validateDigits(e, n)
{
	regex = eval("/^\\d{"+n+"}/");
	return (e.value.match(regex));
}

// Display DD logon unavailable 
function showDDLogonUnavailable()
{
	window.open('logonUnavailable.cfm','logonunavailable','scrollbars=yes,status=yes,toolbar=no,directories=no,menubar=no,resizable=yes,width=562,height=275,left=100,top=100');
}

// DFOT Login
function verifyLogOnFieldsDFOT(ShowEspanol)
{
	f = getFormElement();
	f.formAcctNo.value = trimString(f.formAcctNo.value);
	f.formZIP.value = trimString(f.formZIP.value);
	
	if (isBlank(f.formAcctNo.value) || isBlank(f.formZIP.value))
	{
		if (ShowEspanol == 'YES')
			alert('Proporcione por favor un n\xFAmero de cuenta y el c\xF3digo postal asociado.');
		else
			alert('Please provide an Account # and the associated ZIP code.');
		if (isBlank(f.formAcctNo.value))
			f.formAcctNo.focus();
		else if (isBlank(f.formZIP.value))
			f.formZIP.focus();
		return false;
	}
	else
	{		
		return true;
	}
}

// Show all DFOT FAQ answers
function showAllDFOTFAQAnswers()
{
	f = getFormElement();
	
	for (i=1; i <= 6; i++)
	{
		eval("setVisibleStatus('FAQId_"+i+"', 'inline')");
		eval("setVisibleStatus('FAQShow_"+i+"', 'none')");
		eval("setVisibleStatus('FAQHide_"+i+"', 'inline')");
	}
}

// Hide all DFOT FAQ answers
function hideAllDFOTFAQAnswers()
{
	f = getFormElement();

	for (i=1; i <= 6; i++)
	{
		eval("setVisibleStatus('FAQId_"+i+"', 'none')");
		eval("setVisibleStatus('FAQShow_"+i+"', 'inline')");
		eval("setVisibleStatus('FAQHide_"+i+"', 'none')");
	}	
}

// Show all Catastrophe FAQ answers
function showAllCatFAQAnswers()
{
	f = getFormElement();
	
	for (i=1; i <= 7; i++)
	{
		eval("setVisibleStatus('FAQId_"+i+"', 'inline')");
		eval("setVisibleStatus('FAQShow_"+i+"', 'none')");
		eval("setVisibleStatus('FAQHide_"+i+"', 'inline')");
	}
}

// Hide all Claims FAQ answers
function hideAllCatFAQAnswers()
{
	f = getFormElement();

	for (i=1; i <= 7; i++)
	{
		eval("setVisibleStatus('FAQId_"+i+"', 'none')");
		eval("setVisibleStatus('FAQShow_"+i+"', 'inline')");
		eval("setVisibleStatus('FAQHide_"+i+"', 'none')");
	}	
}

// Displays reminder for payment authorization form
function showPmtFormReminder()
{
	alert('Please note:\n\nFaxes received after 1:00pm central time will be processed the following business day.');
}

// Return XMLHTTPrequest object
function initXMLHTTPRequest()
{
	var xRequest = null;
	if (window.XMLHttpRequest)
		xRequest = new XMLHttpRequest();
	else if (typeof ActiveXObject != 'undefined')
		xRequest = new ActiveXObject("Microsoft.XMLHTTP");
	return(xRequest);
}

function sendRequest(url, params, HttpMethod)
{
	if (!HttpMethod) HttpMethod = "GET";
	req = initXMLHTTPRequest();
	if (req)
	{
		req.onreadystatechange = onReadyState;
		req.open(HttpMethod, url, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(params);
	}
}

function onReadyState()
{
	var ready = req.readyState;
	var data = null;
	if (ready == READY_STATE_COMPLETE)
	{
		data = req.responseText;
		var authUser = document.getElementById('authUser');		// ISSUE: authUser == null in FireFox
		var authISO = document.getElementById('authISO');
		var arrayData = data.split('|');
		authUser.value = arrayData[0];
		authISO.value = arrayData[1];
	}
	else
	{
		//data = "loading ... "+ready+"]";
	}
}

function toConsole(data)
{
	if (data != null)
	{
		var authError = document.getElementById('authError');
		authError.innerHTML = '<span style="color:red;font-family:Arial;font-size:.8em"><strong>Invalid login request.<strong> <a href="javascript:authorizationRequest()">Learn more</a>.</span>';
		authError.style.borderStyle = "solid";
		authError.style.borderWidth = "1px";
		authError.style.borderColor = "red";
		authError.style.padding = "2px";
		authError.style.margin = "2px";
	}
}

// Called when 'Go >' clicked
function verifyGeo()
{
	sendRequest("geo.cfm", "id=PresharedKey", "POST");		// &test=TRUE
}


function authorizationRequest()
{
	// see https://devwww.deltains.com/registrationhelp.cfm
	var objWin = window.open('authorizationRequest.cfm', 'authrequest', 'scrollbars=yes,status=no,location=no,toolbar=no,menubar=no,resizable=yes,width=650,height=600,left=10,top=10');
}
