﻿// Performs required client validation only if the control is enabled
function required_ClientValidate(source, args)
{
    if (document.getElementById(source.controltovalidate).disabled == true)
    {
        args.IsValid = true;
    }
    else
    {
        if (trim(args.Value) == '' || trim(args.Value) == '-1' || trim(args.Value) == 'Select')
        {
            args.IsValid = false;
        }
        else        
        {
            args.IsValid = true;
        }
    }
    
    // These next few lines are a fix to the .NET validator not focusing on a RadioButtonList if there is an error
    if (args.IsValid == false && document.getElementById(source.controltovalidate).nodeName == "SPAN")
    {
        document.getElementById(source.controltovalidate + "_0").focus();
    }
}

// Checks for empty space
function IsEmptySpace(source, args)
{
    if (document.getElementById(source.controltovalidate).disabled == true)
    {
        args.IsValid = true;
    }
    else
    {
        if (args.Value == '' || args.Value == ' ' || args.Value == '  ' || args.Value == '   ' || args.Value == '    ' || args.Value == '     ')
        {
            args.IsValid = false;
        }
        else        
        {
            args.IsValid = true;
        }
    }
    
    // These next few lines are a fix to the .NET validator not focusing on a RadioButtonList if there is an error
    if (args.IsValid == false && document.getElementById(source.controltovalidate).nodeName == "SPAN")
    {
        document.getElementById(source.controltovalidate + "_0").focus();
    }
}

// Return the control that generated the event
function getEventTarget(evt)
{ 
    evt = (evt) ? evt : (window.event) ? window.event : ""; 
    var elt; 
    if (evt.srcElement)
    { 
        elt = evt.srcElement; 
    }
    else if (evt.target)
    { 
        elt = evt.target; 
    } 
    return elt;
}

// function that makes an Ajax call into the server
var timerId;
var xmlHttp;
function postAjaxRequest(callbackFunction, url, xml, timeout, timeoutFunction)
{
    // Abort any previous in progress calls
    if (xmlHttp != null)
    {
        if (xmlHttp.readyState == 1 || xmlHttp.readyState == 2 || xmlHttp.readyState == 3)
        {
            xmlHttp.abort();		    
            clearTimeout(timerId);
        }
    }
    
    // Send the request
    if (window.ActiveXObject)
    {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        xmlHttp = new XMLHttpRequest();
    }
    xmlHttp.onreadystatechange = callbackFunction;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(xml);
    timerId = setTimeout(function(){_onTimeout(timeoutFunction);}, timeout);
}

// function called when the Ajax call is not coming back
function _onTimeout(timeoutFunction)
{
    if (xmlHttp.readyState == 1 || xmlHttp.readyState == 2 || xmlHttp.readyState == 3)
    {
        xmlHttp.abort();
        clearTimeout(timerId);
        if (timeoutFunction != null)
            timeoutFunction();
    }
}

//trims the white space from the beginning and end of the input string.
function trim(inStr)
{
	var start;
	var end;
	for (start = 0; start < inStr.length; start++)
	{
		if (inStr[start] != ' ')
		{
			break;
		}
	}
	for (end = inStr.length; end >= 0; end--)
	{
		if (inStr[end] != ' ')
		{
			break;
		}
	}
	
	if (start == end)
		return '';
	else
		return inStr.substring(start, end);
		
}

//removes all non-numeric characters from a string.  Decimals will be kept.
function removeNonNumerics(inStr)
{
	var validChars = "0123456789.";
	var outStr = "";
	for(var i = 0; i < inStr.length; i++){
		if(validChars.indexOf(inStr.charAt(i)) != -1)
			outStr += inStr.charAt(i);
	}
	return outStr;
}

//removes all non-numeric characters from a string.  Decimals will NOT be kept.
function removeNonNumericsInteger(inStr)
{
	var validChars = "0123456789";
	var outStr = "";
	for(var i = 0; i < inStr.length; i++){
		if(validChars.indexOf(inStr.charAt(i)) != -1)
			outStr += inStr.charAt(i);
		else if (inStr.charAt(i) == '.')
			break; //we've reached a decimal point, break out of the loop
	}
	return outStr;
}

//removes all non-numeric characters from a string.
function removeNonNumericsPhone(inStr)
{
	var validChars = "0123456789";
	var outStr = "";
	for(var i = 0; i < inStr.length; i++){
		if(validChars.indexOf(inStr.charAt(i)) != -1)
			outStr += inStr.charAt(i);
	}
	return outStr;
}

//validates an amount and replaces the source with the parsed value
function validateAmount(source, args)
{
	var inStr = removeNonNumerics(args.Value);
	var parsedVal = parseFloat(inStr);
	
	if (!isNaN(parsedVal))
	{
		args.IsValid = true;
		document.getElementById(source.controltovalidate).value = parsedVal.toString();
	}
	else
		args.IsValid = false;
}

//format phone number
function formatPhone(src)
{ 
	var inStr = removeNonNumericsPhone(src);
	if (inStr.length >= 10)
	{
		var outStr = inStr.substr(0,3) + "-" + inStr.substr(3,3) + "-" + inStr.substr(6,4);
		// don't do extension anymore, it is a separate box
		//if (inStr.length > 10)
		//{
		//	outStr += "x" + inStr.substr(10); //assume everything else is the extension
		//	outStr = (outStr.length > 18) ? outStr.substr(0,18) : outStr; //trim this to 18 characters if need be
		//}
		return outStr;
	}
	else
		return inStr; //return the input string since we don't know what to do with it.
}

//Validate Phone Number Length
//Verfies 10 digits in phone number
function validatePhoneLength(source, args)
{
	var outStr = removeNonNumericsPhone(args.Value);
	
	if (outStr.length >= 10) {
		args.IsValid == true;
		document.getElementById(source.controltovalidate).value = formatPhone(outStr);
	}
	else
		args.IsValid = false;
}


// List of node types that have a "disabled" attribute.  
// Add elements here that have a "disabled" attribute associated with them
// You will need to verify that a control can really be disabled by using a 
// W3C DOM standards-compliant browser (meaning not Internet Explorer).
var disableableNodes = {
	input: 1,
	a: 1,
	select: 1,
	table: 1
};

// List of node types that don't have a "disabled" attribute, 
// we will style them to look like they are disabled.
var otherNodes = {
	label: 1,
	td: 1,
	th: 1,
	span: 1,
	div: 1
};

//disables an element and all children
//pass in "true" or "false" (yes you need quotes) for state.
//"true" means disable, "false" will re-enable.
function disableControl(control, state) {       // control is a Node 
    try
    {
        if (control.nodeType == 1)                  // Node.ELEMENT_NODE
        {
            if (control.nodeName.toLowerCase() in disableableNodes)
            {
                control.disabled = state;
            }
            else if (control.nodeName.toLowerCase() in otherNodes)
            {
                if (state)
                    control.className = "optionsOff";
                else
                    control.className = "optionsOn";
            }
        }
    
        var childs = control.childNodes;          // Now get all children of n
        for(var i=0; i < childs.length; i++) {    // Loop through the children
            disableControl(childs[i], state);	  // Do a recursive call to find all child controls
        }
     }                             
     catch (exception)
     {
     }   
}


// Makes sure we have a date with the day specified within the
// range specified for the month.  Takes into account leap years as well.
function validateDate(source, args)
{
    try
    {
        var dateparse;
        
        if (args.Value.indexOf("/") >= 0)
			dateparse = args.Value.split("/");
		else if (args.Value.indexOf("-") >= 0) 
			dateparse = args.Value.split("-");
		else
			throw new Error("Invalid input string");
			
		if (dateparse.length < 2 || dateparse.length > 3) //make sure this is a valid date, even tho there probably is a regular expression validator
			throw new Error("Invalid input string");

        //make sure we have a 4 digit year
        dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
        
        if (dateparse.length == 2)
			dateparse = [dateparse[0], "01", dateparse[1]];
		
		var year = dateparse[dateparse.length-1];
		var dayofmonth = [31,28,31,30,31,30,31,31,30,31,30,31];

		// check to see if this is a leap year and change days in Feb accordingly
		dayofmonth[1] = (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

		if (dateparse[1] > 0 && dateparse[1] <= dayofmonth[dateparse[0]-1])
		    args.IsValid = true;
		else
		    args.IsValid = false;
		    
	}  
	catch (exception)
    {
        args.IsValid = false;
    }		            

}

// Makes sure we have a valid birthdate (which must be in M[M]/D[D]/YY[YY]).
// Takes into account leap years as well.
function validateBirthdate(source, args)
{
    try
    {
        var dateparse;
        
        if (args.Value.indexOf("/") >= 0)
			dateparse = args.Value.split("/");
		else if (args.Value.indexOf("-") >= 0) 
			dateparse = args.Value.split("-");
		else
			throw new Error("Birthdate is incorrect, please enter in the form of MM/DD/YYYY.");
			
		if (dateparse.length != 3) //make sure there are 3 date parts
			throw new Error("Birthdate is incorrect, please enter in the form of MM/DD/YYYY.");
			
		//make sure all date parts are numbers
		if (isNaN(dateparse[0]) || isNaN(dateparse[1]) || isNaN(dateparse[2]))
			throw new Error("Birthdate is incorrect, please enter in the form of MM/DD/YYYY.");
			
		//make sure the month is okay
		if (dateparse[0] < 1 || dateparse[0] > 12)
			throw new Error("Birthdate is incorrect, please check the month.");

        //make sure we have a 4 digit year
        dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
		
		var year = dateparse[dateparse.length-1];
		var dayofmonth = [31,28,31,30,31,30,31,31,30,31,30,31];

		// check to see if this is a leap year and change days in Feb accordingly
		dayofmonth[1] = (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

		if (dateparse[1] > 0 && dateparse[1] <= dayofmonth[dateparse[0]-1])
		    args.IsValid = true;
		else
		    throw new Error("Birthdate is incorrect, please check the day of month.");
		    
	}  
	catch (ex)
    {
		source.innerHTML = "<br />" + ex.message; //Change the error message to the appropriate message above
        args.IsValid = false;
    }		            

}

//return true if the date is within the time span specified
//false if there is an exception or not within the time span.
// spanStart and spanEnd expect a negative value for the past, positive value for the future specified in days
// ex. validateDate("11/1/2005", -365, 0) would be true if the date specified is within 12 months of the current date.
function validateDateInRange(tmpDate, spanStart, spanEnd)
{
    try
    {
        var testDate = new Date();
        var dateparse;
        
        if (tmpDate.indexOf("/") >= 0)
			dateparse = tmpDate.split("/");
		else if (tmpDate.indexOf("-") >= 0) 
			dateparse = tmpDate.split("-");
		else
			return false;

		if (dateparse.length < 2 || dateparse.length > 3) //make sure this is a valid date, even tho there probably is a regular expression validator
			return false;

        //make sure we have a 4 digit year
        dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
        
        if (dateparse.length == 2)
			dateparse = [dateparse[0], "01", dateparse[1]];              

        // create a properly formatted date 
        testDate = new Date();
        testDate.setFullYear(dateparse[2], dateparse[0] - 1, dateparse[1]); // setFullYear(year, month, day);
        //alert("testDate: " + testDate.toString());
        var startDate = new Date(SystemTime.toDateString()); 
        var endDate = new Date(SystemTime.toDateString());
        
        startDate.setHours(0,0,0,0);
        endDate.setHours(23, 59, 59, 999);
        
        //check our timespan values, make sure the past date is the older date
        if (spanEnd < spanStart)
        {
			startDate.setTime(startDate.getTime() + (86400000 * spanEnd)); //number of milliseconds in a day * the number of days)
			endDate.setTime(endDate.getTime() + (86400000 * spanStart));
        }
        else
        {
			startDate.setTime(startDate.getTime() + (86400000 * spanStart)); //number of milliseconds in a day * the number of days)
			endDate.setTime(endDate.getTime() + (86400000 * spanEnd));
        }
		
        // check the date range with current date and the past date or span
        if (testDate >= startDate && testDate <= endDate)
            return true;
        else
            return false;
    }
    catch (exception)
    {
        return false;
    }
}

//returns a 4 digit year.  If a 2 digit year is supplied, the century will be added.
function getCentury(inStr)
{
	if (inStr.length == 2)
	{
		var tmpDate = SystemTime;

		var century = parseInt(tmpDate.getFullYear().toString().substring(0,2));
		var year = parseInt(tmpDate.getFullYear().toString().substring(2));
		
		if (inStr <= (year + 10)) //add 10 to the current year to handle dates up to 10 year in the future
			return century + inStr;
		else
			return (century - 1) + inStr;
    }
    else
		return inStr;
}

//returns a date in mm/dd/yyyy
function formatDateString(inStr)
{
    try 
    {
		var dateparse;
        if (inStr.indexOf("/") >= 0)
			dateparse = inStr.split("/");
		else if (inStr.indexOf("-") >= 0) 
			dateparse = inStr.split("-");
		else
			return dateparse;

        //make sure we have a 4 digit year
        dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
        
        if (dateparse.length == 2)
			dateparse = [dateparse[0], "01", dateparse[1]];              

        // create a properly formatted date 
        return dateparse.join("/");
	}
	catch (exception)
	{
		return inStr;
	}
}

function clearPageValidators()
{
    for (var i = 0; i < Page_Validators.length; i++)
        clearValidator(Page_Validators[i]);
}

function clearValidator(val)
{
    if (typeof(val.display) == "string") {
        if (val.display == "Dynamic") {
            val.style.display = "none";
        }
    }
    else
    {
        if ((navigator.userAgent.indexOf("Mac") > -1) &&
            (navigator.userAgent.indexOf("MSIE") > -1)) {
            val.style.display = "inline";
        }
        val.style.visibility = "hidden";
    }
}

//Modified .Net Supplied function to allow repeated clicks of the default button when the Enter key is pressed.
function fireDefaultButton(event, target) {
	var evtTarget = getEventTarget(event);
    if (event.keyCode == 13 && !(evtTarget && evtTarget.tagName.toLowerCase() == "textarea"))
    {
        var defaultButton = document.getElementById(target);

        if (defaultButton && typeof(defaultButton.click) != "undefined") {
            defaultButton.click();
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            return false;
        }
    }
    return true;
}

//Limits the length of a text area.
//field - the text area you want to limit the length of
//countfield - characters remaining value field
//maxlimit - max length of the text area
function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit)
		field.value = field.value.substring(0, maxlimit);					
	else if (countfield != null)
		countfield.innerHTML = maxlimit - field.value.length;
}

//Sets a default string if the field is left blank.  Updates the counter field.
function setText(defaultString, field, countfield, maxlimit)
{   
    if (field.value == '')
	    field.value = defaultString;					
	textCounter(field,countfield,maxlimit);
}

//Clears the default string from the comment area when the user selects 
function clearText(defaultString, field, countfield, maxlimit)
{
    if (field.value == defaultString) 
	    field.value = '';
	textCounter(field,countfield,maxlimit);    
}

//Will set the focus to the first control in the page that
//is not disabled or hidden
function focusOnFirstControl()
{		
    var bFound = false;

    // for each form
    for (f=0; f < document.forms.length; f++)
    {
        // for each element in each form
        for(i=0; i < document.forms[f].length; i++)
        {
            // if it's not a hidden element
            if (document.forms[f][i].type != "hidden")
            {
                // and it's not disabled
                if (document.forms[f][i].disabled != true)
                {
                    try
                    {
                        // set the focus to it
                        document.forms[f][i].focus();
                        bFound = true;
                    }
                    catch (err)
                    {
                        // ignore
                    }
                }
            }
            // if found in this element, stop looking
            if (bFound == true)
                break;
        }
        // if found in this form, stop looking
        if (bFound == true)
            break;
    }		
}

//Used to display the verisign splash site.  This will display in a popup window.
function showVerisignPopup(site)
{
     //The url of the splash site.  The domain on which InsureMe has a ssl certificate goes between url1 and url2
     var url1 = 'https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn=';
     var url2 = '&lang=en';
     //The width and height are set to give enough room for languages like spanish that take up more room.
     //Set the menubar to yes to display the menu bar.
     var completeUrl = url1 + site + url2;  
     //window.open(url1 + site + url2, 'VerisignPopUp', 'width=550, height=450, menubar=no, resizable=no');
     sw = window.open(completeUrl,'VRSN_Splash','location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500');
     sw.focus();
}