﻿// JScript File
var bPopOffer = true;
var iSubmitCount = 0;

function SetCancelPops() 
{ 
    var anchors = document.getElementsByTagName("A");
    for(var i=0; i<anchors.length; i++)
    {  if (anchors[i].onclick == null){  anchors[i].onclick =  function() {CancelPop(true);} }  }
    anchors = document.getElementsByTagName("MAP"); //do the same for maps
    for(var i=0; i<anchors.length; i++)
    { if (anchors[i].onclick == null) { anchors[i].onclick = function() { CancelPop(true); } } }
    ResetPop();
} 

function popUp(theURL,Win_Height,Win_Width,Win_Name) 
{         
window.open(theURL,Win_Name,"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=452,height=350");
}

function popUpHelp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=350,left = 10,top = 10');");
}

function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
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];}}
}

function MM_findObj(n, d) { //v4.01
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;
}

function MM_swapImage() { //v3.0
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];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
window.open(theURL,winName,features);
}
function NeedHelp(i_type) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open('help/help.aspx?id=" + i_type + "', '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=350,left = 10,top = 10');");
}

function popUpExamp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=350,left = 10,top = 10');");
}

function AffiliateProgram(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=640,height=480,left = 0,top = 0');");
}

function popUpDoc(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=740,height=480,left = 0,top = 0');");
}

function popUpCalendar(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=290,left = 10,top = 10');");
}

function isGoodEmail(src) {
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.isGoodEmail(src);
}

function _ShowPopupCalendar( i_strFormName, i_strFieldName,i_blnHistory ) {
	var strURL = '/common/popcalendar.asp?FormName=' + i_strFormName + '&FieldName=' + i_strFieldName;
	if (i_blnHistory)
		strURL = strURL + '&History=on';
	else
		strURL = strURL + '&History=off';
	window.datefield = document.forms[i_strFormName][i_strFieldName]; 
	window.open( strURL + '&date=' + window.datefield.value, 'cal', 'WIDTH=295,HEIGHT=310' );
}      
	
var exit=false;	
function DontLeave(URL) {
	if (exit) {
		day = new Date();
		id = day.getTime();
		//eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=275,left = 376,top = 294.5');");
	}
}	

var winCal = null;
function NewWindow(mypage,myname,w,h,scroll) {
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left=';
	settings = settings + LeftPosition+',scrollbars='+scroll+',resizable';
	winCal = window.open(mypage,myname,settings)
	if (winCal.window.focus) { winCal.window.focus(); }
}
function trim( i_value ) {
	return i_value.replace( /^[ ]+|[ ]+$/g, '' );
}
function AgeAtToday(i_strDOB) {
	//RETURNS AGE (AS INTEGER), GIVEN THE DOB AND ANOTHER DATE
	//WILL RETURN -1 IF ENCOUNTERS AN ERROR
	var dtDOB = new Date(i_strDOB);
	var dtDate = new Date();
	if (isNaN(dtDOB) || isNaN(dtDate)) { return -1; }
	var intAge;
	intAge = dtDate.getFullYear() - dtDOB.getFullYear();
	dtDOB.setYear(dtDate.getFullYear())
	dtDOB.setHours(0, 0, 0, 0);
	dtDate.setHours(0, 0, 0, 0);
	if (dtDate < dtDOB) { intAge --; }
	return intAge;
}
function ValidateCheck(sender, args) {
    var Container = new String;
    Container = sender.id;
    Container = Container.replace('cstAgree', '');
	args.IsValid = document.forms[0][Container + 'chkTerms'].checked;
}

function IsValidDate(sender, args) {
      var Container2 = new String;
      Container2 = sender.id;
      Container2 = Container2.replace('cstDOB', '');    
	  var ThisMonth = trim(document.forms[0][Container2 + 'cmbDOBMonth'].options[document.forms[0][Container2 + 'cmbDOBMonth'].options.selectedIndex].value);
	  var ThisDay = trim(document.forms[0][Container2 + 'cmbDOBDay'].options[document.forms[0][Container2 + 'cmbDOBDay'].options.selectedIndex].value);
	  var ThisYear = trim(args.Value);
	  var i_date = ThisMonth + '/' + ThisDay + '/' + ThisYear;
	  
	  i_date = i_date.replace(/[ ]/g,''); //Remove whitespace
      var hit = i_date.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
      if (hit && hit.length == 4) {
            var arrMonths = new Array('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');
            var myDate = new Date(i_date);
            var myDate_string = myDate.toGMTString();
            var myDate_array = myDate_string.split(' ');
            args.IsValid = true;
            args.IsValid = myDate_array[2].toUpperCase() == arrMonths[Number(hit[1]) - 1];
            return;
      }
      args.IsValid = false;     //Invalid or No Date    
}


function CheckAge(sender, args) {
    var Container = new String;
    Container = sender.id;
    Container = Container.replace('cstAge', '');
	var ThisMonth = trim(document.forms[0][Container + 'cmbDOBMonth'].options[document.forms[0][Container + 'cmbDOBMonth'].options.selectedIndex].value);
	var ThisDay = trim(document.forms[0][Container + 'cmbDOBDay'].options[document.forms[0][Container + 'cmbDOBDay'].options.selectedIndex].value);
	var ThisYear = trim(args.Value);
	var FullDate = ThisMonth + '/' + ThisDay + '/' + ThisYear;
	if (!isNaN( new Date(FullDate))) {
		if (AgeAtToday(FullDate) < 18) {
			args.IsValid = false;
			return;
		}
	}
	args.IsValid = true;
}
var win = null;
function NewWindow(mypage,myname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
win = window.open(mypage,myname,settings)
}
function ClientEmailMatch(source, arguments)
{
var txtEmail
var EmailValue
txtEmail = document.getElementById('ctl00_MainContent_ctl00_txtemail');
EmailValue = txtEmail.value
  if (arguments.Value.toUpperCase() == EmailValue.toUpperCase())
    arguments.IsValid = true;
  else
    arguments.IsValid = false;
}

// BEGIN: Pop-up calendar code
var calendar_window;
var pay_struct = '';
function Get_Pay_Structure() {
	return pay_struct;
}
function Set_Pay_Structure(obj)
{
    pay_struct = obj.value;
}
function SetPayDates(iDtBox1, iDtBox2, iFrequencyID)
{
    //Run the validation for the first text box again, to see if we have a correct value now
//    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_rngDateBox'), null, 'change');
//    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_rqvDateBox'), null, 'change');
//    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_cstDateBox'), null, 'change');
    
    var obj = document.getElementById(iDtBox1)
    var dDate = new Date(obj.value);
    var iFrequency = 0; //Frequency in secs
    var iSecs = 0;
    obj = document.getElementById(iFrequencyID)
    switch(obj.value) //Set Difference in Seconds
    {
        case '52': //weekly
            iFrequency =  604800000;    // 7 x 24 * 60 * 60 * 1000
            break;
        case '26': //biweekly
            iFrequency =  1209600000;   // 604800000 * 2
            break;
        // twice-a-month and monthly has too many scenerios
        // lets not do anything to confuse the customers
    }
    
    if (iFrequency > 0) //weekly or biweekly lets use the secs to calculate
    {
        iSecs = Number(dDate) + iFrequency + 10800000; //new date in seconds and 3 hours to avoid issues with timechanges (1000*60*60*3)
        var dDate = new Date(iSecs);
        obj = document.getElementById(iDtBox2);
        if (obj != null)
        {   obj.value = (dDate.getMonth() + 1) + '/' + dDate.getDate() + '/' + dDate.getFullYear();    } 
    }
}
function showCalendar(obj)
{

    if($('.PayCalNav > div:eq(0)').is(':visible') && $('.PayCalNav > div:eq(1)').is(':visible'))
    {
    $('.PayCalNav:eq(0) > div:eq(0)').hide();
    $('.PayCalNav:eq(1) > div:eq(0)').hide();
    }
    hideCalendars();
    var xy = findPos(obj);
    xy[1] += 20;
    addFrameie6bug(xy[0], xy[1], '422px', '202px');
    $(obj).nextAll('.PayCalendars').css('left', xy[0] + 'px').css('top', xy[1] + 'px').show();
}
function setCalDate(i_DtBox1, i_DtBox2, i_FrequencyID, i_Val)
{
    $("#" + i_DtBox1).val(i_Val);
    hideCalendars();
    if (i_DtBox2 != '')
    {   SetPayDates(i_DtBox1, i_DtBox2, i_FrequencyID);}
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_cstValidUKDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar2_cstValidUKDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_rngDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_rqvDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar1_cstDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar2_rngDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar2_rqvDateBox'), null, 'change');
    ValidatorValidate(document.getElementById('ctl00_MainContent_ctl00_MyCalendar2_cstDateBox'), null, 'change');
    
    HighlightPDLabel();
}
function validatePayDates(src, args)
{
    args.IsValid = false;
    var dt1,dt2;
    dt1 = new Date($('#ctl00_MainContent_ctl00_MyCalendar1_txtDateBox').val());
    dt2 = new Date($('#ctl00_MainContent_ctl00_MyCalendar2_txtDateBox').val());

    if (!(isNaN(dt1) || isNaN(dt2))) //two valid dates
    {  
        if (Number(dt1) >= Number(dt2))
        {   args.IsValid =  false;  }
        else
        {    args.IsValid = true;   }
    }//dt1 must be less than dt2
    else //not enought to validate, other validators should catch it.
    {   args.IsValid = true;}
}
function hideCalendars()
{
    removeFrameie6bug();
    $('.PayCalendars').hide();
}
function showPreviousMonth()
{
    $('.PayCalNav:eq(0) > div:eq(0)').hide();
    $('.PayCalNav:eq(1) > div:eq(0)').hide();
    $('.PayCalNav:eq(0) > div:eq(1)').show();
    $('.PayCalNav:eq(1) > div:eq(1)').show();
    $('.cal1').show();
    $('.cal2').css('float','right');
    $('.cal3').hide();
}
function showNextMonth()
{
    $('.PayCalNav:eq(0) > div:eq(0)').show();
    $('.PayCalNav:eq(1) > div:eq(0)').show();
    $('.PayCalNav:eq(0) > div:eq(1)').hide();
    $('.PayCalNav:eq(1) > div:eq(1)').hide();
    $('.cal1').hide();
    $('.cal2').css('float','left');
    $('.cal3').show();
}
// END: Pop-up calendar code

//this is for the offers pop up

function CancelPop(bReset)
{
	bPopOffer = false;
	if (bReset == true) window.setTimeout('ResetPop()', 3000);
}
function ResetPop()
{
	bPopOffer = true;
}
function PopOffer(sOffer)
{
    if (!bPopOffer) return; //exit
    bPopOffer = false;
    var ctl = $("body");
    var oldColor = ctl.css('background-color');
    ctl.html('<center><iframe src="' + sOffer + '" scrolling="no" frameborder="0" allowtransparency="true" marginheight="0" marginwidth="0" id="iframe1" height="1150" width="974" style="margin:0 auto"></iframe></center>');
    ctl.css('background', oldColor);
    alert("Don't Leave! We have more options for you!\n\nJust click \'CANCEL\' on the next window!");
    return "\nPress 'CANCEL' to view options!\n";
}
function addFrameie6bug(x, y, w, h)
{
    $("<iframe id='blankie6frame' src='/blank.htm'></iframe>").css({left:x + 'px',top:y + 'px', width: w, height: h}).appendTo('body');
}
function removeFrameie6bug()
{
    $('#blankie6frame').remove();
}
//closes faq popup and goes to secure app
function gotoSecureApp(aID) {
	if (window.opener) {
	    window.opener.CancelPop(true);
		window.opener.location='https://applications.us.com/?aid=' + aID;
		self.close();
	}
	else {
	    CancelPop(true);
		window.location = 'https://applications.us.com/?aid=' + aID;
	}
}

//this closes popup window and goes to Contact page form
function gotoApply() {
	if (window.opener) {
	    window.opener.CancelPop(true);
		window.opener.location='/Default.aspx';
		self.close();
	}
	else {
	    CancelPop(true);
		window.location = '/Default.aspx';
	}
}

//this closes popup window and goes to the window passed in
function gotoPage(thePage) {
	if (window.opener) {
	    window.opener.CancelPop(true);
		window.opener.location=thePage;
		self.close();
	}
	else {
	    CancelPop(true);
		window.location = thePage;
	}
}

//this closes popup window and goes to Contact page form in AUTO site
function gotoApply2() {
	if (window.opener) {
	    window.opener.CancelPop(true);
		window.opener.location='/proc/auto-leads-for-dealers.aspx';
		self.close();
	}
	else {
	    CancelPop(true);
		window.location = '/proc/auto-leads-for-dealers.aspx';
	}
}

function GoReapply()
{
    if (window.opener)
    {
        window.opener.CancelPop(true);
        window.opener.location = '/Reapply.aspx';
        window.close();
    }
    else
    {
        CancelPop(true);
        window.location = '/Reapply.aspx';
    }
}

function ValidABA(sender, args) {
	var ctl = new String;
	ctl = sender.id;
	ctl = ctl.replace("cstABA", "txtABA");
	var s  = document.getElementById(ctl).value;
	// Run through each digit and calculate the total.
	var c = 0;
	var i = 0;
	var n = 0;
	var t = "";
	try {
		for (i = 0; i < s.length; i++) {
			c = parseInt(s.charAt(i), 10);
			t = t + c;
		}

		// Check the length, it should be nine digits.
		if (t.length != 9)
			args.IsValid = false;

		// Now run through each digit and calculate the total.
		n = 0;
		for (i = 0; i < t.length; i += 3) {
			n += (parseInt(t.charAt(i), 10) * 3) + (parseInt(t.charAt(i + 1), 10) * 7) + parseInt(t.charAt(i + 2), 10);
		}

   		// If the resulting sum is an even multiple of ten (but not zero),
		// the aba routing number is good.
		args.IsValid = (n != 0 && n % 10 == 0);
	}
	catch(err) {
		args.IsValid = false;
	}
}
/* hide button */
function DisableButton(obj)
{   obj.style.display = 'none'; }
function EnableButton(cid)
{    document.getElementById(cid).style.display = '';   }

/* Pop Offers */
function PopNewWindow(TemplateID)
{	
    if (bPopOffer == true)
    {
        var height = screen.availHeight;
        var width = screen.availWidth;
        window.open('/offers.aspx?F=1&TemplateID=' + TemplateID,'mywindow'+ TemplateID,'width=' + width + ',height=' + height + ', scrollbars=1, left=0, right=0, top=0'); 
        window.focus()
    }
}	

function PopNewWindowURL(URL)
{	
    
    if ((bPopOffer == true) && (URL != ""))
    {
        var height = screen.availHeight;
        var width = screen.availWidth;
        window.open(URL, 'mywindow' + Math.floor(Math.random()*50000), 'width=' + width + ',height=' + height + ', scrollbars=1, left=0, right=0, top=0'); 
        window.focus()
    }
}

/* removes extra spaces from text */
function removeSpaces(ctlID,value){
            
    var cleanValue = '';     
                                                                                        
    ctlID = document.getElementById(ctlID.toString());
                                        
    if (value.length > 0){
        //look for spaces in the text
        if (value.search(/\s/) != -1){
            //load into an array
          var myStringArray = new Array();
          myStringArray = value.split('');                                                               
          //loop through each letter and remove spaces
          for (var i=0; i <= myStringArray.length-1; i++){                                                                                                                                                                            
            //add the letter to the new string only if it is not a space
            if (myStringArray[i].search(/\s/) == -1 ){                                            
                cleanValue += myStringArray[i];    
            }                
          }            
        }                
    }
    
    if (cleanValue != ''){
        ctlID.value = cleanValue;
    }else{}                                               
}


/* Trim leading an trailing spaces */
function lTrim(ctlID,value){    
    
    if (value != '' && value != undefined){
                       
        ctlID = document.getElementById(ctlID.toString());

        //trim leading spaces    
        while (value.charAt(0) == ' '){        
            value = value.substr(1,value.length);        
        }        
    }
              
    ctlID.value = value;         
    return false;
}


/* Trims trailing spaces */
function rTrim(ctlID,value){
    if (value != '' && value != undefined){

        ctlID = document.getElementById(ctlID.toString());

        //trim trailing spaces
        while (value.charAt(value.length-1) == ' '){
            value = value.substr(0,value.length-1);
        }
    }
    ctlID.value = value;
    return false;
}


/* pop up general div */
function alertDiv(sender, divID, valueToCompare) //sender is the element that caused this to fire
{
    var xandy = findPos(sender);
    var x, y, showDiv;
    x = xandy[0];
    y = xandy[1] + 14 //sender.clientHeight; //we want right below the sender.
    obj = document.getElementById(divID);

    $(obj).children('.alertval').html($(sender).val());

    showDiv = 0;
    if (isNaN(valueToCompare))
    {   
         if ((sender.value != '') && (valueToCompare.indexOf(sender.value) >= 0))
                {showDiv=1;}
    }
    else
    {
        if (sender.value > valueToCompare)
            {showDiv=1;}
    }


    if (obj != null)
    {
        if (showDiv==1) //show div
        {
            var iHeight = 0;
            var iWidth = 0;
            var iScrollX = 0;
            var iScrollY = 0;
    
            if(document.all)
            {
                iHeight = document.documentElement.clientHeight;
                iWidth = document.documentElement.clientWidth;
                iScrollX = document.documentElement.scrollLeft;
                iScrollY = document.documentElement.scrollTop;
                y += 7;
            }
            else
            {
                iHeight = this.innerHeight;
                iWidth = this.innerWidth;
                iScrollX = this.scrollX;
                iScrollY = this.scrollY;
                
            }
            obj.style.display = '';
            
            if ((iWidth + iScrollX - obj.clientWidth) < x)
            {   x = iWidth + iScrollX - 10 - obj.clientWidth;  }
            if ((iHeight + iScrollY - obj.clientHeight) < y)
            {   y = y - obj.clientHeight - 10 - sender.clientHeight; } //put above sender
            addFrameie6bug(x, y, obj.clientWidth + 'px', obj.clientHeight + 'px');
            obj.style.left = x + 'px';
            obj.style.top = y  + 'px';
        }
        else
        {
            removeFrameie6bug();
            obj.style.display = 'none';
        }
    }
}

function resetDiv(objid, divID, valueToResetTo)
{
    removeFrameie6bug();
    document.getElementById(divID).style.display = 'none';
    document.getElementById(objid).value = valueToResetTo; 
    return false;
}

function closeDiv(divID)
{
    removeFrameie6bug();
    document.getElementById(divID).style.display = 'none';
    return false;
}




/* hides div alert and calender popups*/
function hideDivAndCal(){           
    hideCalendars();      
}







/* pop up benefits div */
function alertBenefits(sender) //sender is the element cause this to fire
{

    var xandy = findPos(sender);
    var x, y;
    x = xandy[0];
    y = xandy[1] + sender.clientHeight; //we want right below the sender.
    obj = document.getElementById('benefitsAlert')
    if (obj != null)
    {
        if (sender.value == 'BENEFITS') //show benefits
        {
            var iHeight = 0;
            var iWidth = 0;
            var iScrollX = 0;
            var iScrollY = 0;
    
            if(document.all)
            {
                iHeight = document.documentElement.clientHeight;
                iWidth = document.documentElement.clientWidth;
                iScrollX = document.documentElement.scrollLeft;
                iScrollY = document.documentElement.scrollTop;
                y += 7;
            }
            else
            {
                iHeight = this.innerHeight;
                iWidth = this.innerWidth;
                iScrollX = this.scrollX;
                iScrollY = this.scrollY;
            }
            obj.style.display = '';

            if ((iWidth + iScrollX - obj.clientWidth) < x)
            {   x = iWidth + iScrollX - 10 - obj.clientWidth;  }
            if ((iHeight + iScrollY - obj.clientHeight) < y)
            {   y = y - obj.clientHeight - 10 - sender.clientHeight; } //put above sender
            addFrameie6bug(x, y, obj.clientWidth + 'px', obj.clientHeight + 'px');
            obj.style.left = x + 'px';
            obj.style.top = y + 'px';
        }
        else
        {
            removeFrameie6bug();
            obj.style.display = 'none';
        }
    }
}

function resetBenefits(objid)
{
    removeFrameie6bug();
    document.getElementById('BenefitsAlert').style.display = 'none';
    document.getElementById(objid).value = 'EMPLOYMENT';
    return false;
}

function closeBenefits(objid)
{
    removeFrameie6bug();
    document.getElementById('BenefitsAlert').style.display = 'none';
    return false;
}


/* pop up military disclaimer div */
function alertMilitary(sender) //sender is the element cause this to fire
{

    var xandy = findPos(sender);
    var x, y;
    x = xandy[0];
    y = xandy[1] + sender.clientHeight; //we want right below the sender.

    obj = document.getElementById('militaryalert')

    if (obj != null)
    {
        if (sender.value == 1) //show military
        {
            var iHeight = 0;
            var iWidth = 0;
            var iScrollX = 0;
            var iScrollY = 0;
    
            if(document.all)
            {
                iHeight = document.documentElement.clientHeight;
                iWidth = document.documentElement.clientWidth;
                iScrollX = document.documentElement.scrollLeft;
                iScrollY = document.documentElement.scrollTop;
                y += 7;
            }
            else
            {
                iHeight = this.innerHeight;
                iWidth = this.innerWidth;
                iScrollX = this.scrollX;
                iScrollY = this.scrollY;
            }
            obj.style.display = '';

            if ((iWidth + iScrollX - obj.clientWidth) < x)
            {   x = iWidth + iScrollX - 10 - obj.clientWidth;  }
            if ((iHeight + iScrollY - obj.clientHeight) < y)
            {   y = y - obj.clientHeight - 10 - sender.clientHeight; } //put above sender
            addFrameie6bug(x, y, obj.clientWidth + 'px', obj.clientHeight + 'px');
            obj.style.left = x + 'px';
            obj.style.top = y + 'px';
        }
        else
        {
            removeFrameie6bug();
            obj.style.display = 'none';
        }
    }
}
function resetMilitary(objid)
{

    removeFrameie6bug();
    document.getElementById('militaryalert').style.display = 'none';
    document.getElementById(objid).value = 0;
    
    return false;
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
function isValidUKDate(source, clientside_arguments)
{   
          
    if (isDate(clientside_arguments.Value))
    { clientside_arguments.IsValid=true; }
    else
    { clientside_arguments.IsValid=false; }
}

function isDate(dateStr) 
{
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) 
    { return false; }

    day = matchArray[1]; // parse date into variables
    month = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) 
    { // check month range
    return false;
    }

    if (day < 1 || day > 31) 
    { return false; }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) 
    { return false; }

    if (month == 2) 
    { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) 
        { return false; }
    }
    
    //check to see if it is more than 2 months or less than a day away
    today=new Date();
    //Set 1 day in milliseconds
    var one_day=1000*60*60*24;

    usDate = new Date(year, month-1, day);
    diffInDays = Math.ceil(usDate.getTime()-today.getTime())/one_day;
    if ((diffInDays<0) || (diffInDays>62))
    {return false;}
            
    return true; // date is valid
}

function ChangeLabelColor(val){
myInput = document.getElementById(val.controltovalidate);
myLabelName = 'lbl' + val.controltovalidate.substring(val.controltovalidate.lastIndexOf("_"), val.controltovalidate.length);
rightValue = myLabelName.substring(myLabelName.length-1, myLabelName.length)
if (!isNaN(rightValue))
{
myLabelName = myLabelName.substring(0, myLabelName.length-1)
}

myLabel = document.getElementById(myLabelName);
mySpan = document.getElementById('span' + val.controltovalidate.substring(val.controltovalidate.lastIndexOf("_"), val.controltovalidate.length));

    //if(val.controltovalidate != null ){
         var k, value;
        // Find out all validators associated
        var vals = new Array();
        for(k=0; k < Page_Validators.length; k++){
            if(Page_Validators[k].controltovalidate == val.controltovalidate)
                vals.push(Page_Validators[k]);
        }

        //Determine if some validator fails
        value = true;
        for(k=0; k < vals.length;k++)
                       value = (value && vals[k].isvalid);
          
        // Change label text color
        if(value){
            if (myInput != null)
            {myInput.className = 'inputitems';}
            if (myLabel != null)
            {myLabel.className = 'AppLabel2';}
            if (mySpan != null)
            {mySpan.className = '';}
        }else{
            if (myInput != null)
            {myInput.className= 'inputerror';}
            if (myLabel != null)
            {myLabel.className = 'AppLabelError';}
            if (mySpan != null)
            {
                mySpan.className = 'inputerror';
            }
        }
    //}
}

function ShowHideSummaryImage()
{ 

    HighlightPDLabel();
    CancelPop(true);
    var mySummaryImageDiv = document.getElementById('divValSummaryImage');
    var myValSummaryDiv = document.getElementById('divValSummary');
    
    var uCaseinnerHTML
       uCaseinnerHTML = myValSummaryDiv.innerHTML.toUpperCase();
    if(uCaseinnerHTML.indexOf('<UL>') >= 0)
    {
        mySummaryImageDiv.style.display = 'block';
        //show hidden fields, hide calendars 
        $("[hideWhenFilled]").show();
        hideCalendars();
    }
    else
    {
        mySummaryImageDiv.style.display = 'none';          
    }
  
}


function slideToggleDiv(divID)
{
    $('#' + divID).slideToggle(400);
}

function updateInvisibleTerms()
{
var mychkTerms;
mychkTerms =document.getElementById('ctl00_MainContent_ctl00_chkTerms');
if (mychkTerms.checked)
    {
        document.getElementById('ctl00_MainContent_ctl00_txtInvisbleTerms').value = "1"
    }
    else
    {
        document.getElementById('ctl00_MainContent_ctl00_txtInvisbleTerms').value = ""
    }
}


/* jqmodal helper functions */
function openJqModal(i_height, i_width, i_url)
{
    var winLeft = ($(window).width()  - i_width)/2;
    $('#dialog > #ciLoading').show();
    $('#dialog').css({height:i_height, width:i_width});
    $('#dialog').jqm({onHide:closeJqModal}).jqmShow();
    $('#jqmFrame').bind('load', function(){
    $('#dialog > #ciLoading').fadeOut(1000, function(){
    $('#jqmFrame').fadeIn('slow');});
        });
    $('#jqmFrame').attr('src', i_url);
    $('#dialog').animate({left: winLeft}, 1500);
    //close modal when buttons in jqmCloseWin are clicked
    $('#jqmCloseWin').unbind().click(function(){
        $('#dialog').jqmHide();
    });
    
}


function openJqModal2(i_height, i_width, i_divToShow, i_alertVal)
{
    var winLeft = ($(window).width()  - i_width)/2;
   //$('#AccountTypeAlert').hide();
   //$('#benefitsAlert').hide();
   //$('#StateAlert').hide();
   //$('#militaryalert').hide();
   //$('#RequestAmtAlert').hide();
   //$('#InvalidZipAlert').hide();
   
   $('#AlertMessage').remove();
   
    var divAlertHTML = $('#' + i_divToShow).clone().html();
    divAlertHTML = '<div id="AlertMessage">' + divAlertHTML + '</div>'; 
    
    divAlertHTML = divAlertHTML.replace("@@alertval@@", i_alertVal);
   
    $(divAlertHTML).appendTo('#AlertDiv');
   
    //$('#' + i_divToShow).show();
    $('#dialog').css({height:i_height, width:i_width});
    $('#dialog').jqm({onHide:closeJqModal}).jqmShow();
    $('#dialog').animate({left: winLeft}, 1500);
    //close modal when buttons in jqmCloseWin are clicked
    $('#jqmCloseWin').unbind().click(function(){
        $('#dialog').jqmHide();
    });
    
}

//function hideJqModal()
//{

// $('#dialog').hide();
//   $('#dialog').jqmHide(); 

//}


function closeJqModal(hash)
{
    $('#jqmFrame').hide();
    hash.w.fadeOut('2000', function(){hash.o.remove();});
}
//function getUniqCall()
//{
    //return '&wtsmni=' + Number(new Date());//used to sold ie's cachin issue.
//}

function ShowHideTradeInInfo(sender)
{
    if (sender.value == 1) {
        //show TradeInInfo
        $('.TradeInInfo').show()
    }
    else {
        //hide TradeInInfo
        $('.TradeInInfo').hide()
    }
    
    
}

/* pop up general jqModal */
function alertModal(sender, URL, valueToCompare, height, width) //sender is the element that caused this to fire
{
    var showModal;
    showModal = 0;
    
    $('#AlertDiv').hide();

    //alert('sender.value = ' + sender.value);
    //alert('valueToCompare = ' + valueToCompare);

    if (isNaN(valueToCompare))
    {
        if ((sender.value != '') && (valueToCompare.indexOf(sender.value) >= 0)) 
                {showModal=1;}
    }
    else
    {
        if ((sender.value > valueToCompare) || ((sender.value == '') && (valueToCompare == '')))
            {showModal=1;}
    }

    if (showModal==1) //show div
    {
        if (URL.indexOf("?") == -1) //add sender value
        {   URL = URL + "?alertval=" + sender.value;  }
        else{   URL = URL + "&alerval=" + sender.value; }
        openJqModal(height, width, URL);
        return true;
    }
    else {
    return false;
    }
}

function alertModal2(sender, divToShow, valueToCompare, height, width, alertVal) //sender is the element that caused this to fire
{
    var showModal;
    showModal = 0;
    
    //alert('sender.value = ' + sender.value);
    //alert('valueToCompare = ' + valueToCompare);

    if (isNaN(valueToCompare))
    {
        if ((sender.value != '') && (valueToCompare.indexOf(sender.value) >= 0)) 
                {showModal=1;}
    }
    else
    {
        if ((sender.value > valueToCompare) || ((sender.value == '') && (valueToCompare == '')))
            {showModal=1;}
    }

    if (showModal==1) //show div
    {
        openJqModal2(height, width, divToShow, alertVal);
        return true;
    }
    else {
    return false;
    }
}


function resetModal(objid, valueToResetTo)
{
    top.$('#dialog').jqmHide();
    top.document.getElementById(objid).value = valueToResetTo; 
    return false;
}

function resetModal2(objid, valueToResetTo)
{
    //top.$('#dialog').jqmHide();
    top.document.getElementById(objid).value = valueToResetTo; 
    return false;
}

function closeModal()
{
    top.$('#dialog').jqmHide();
    return false;
}

function preSubmitProcess()
{   //use this function to call any function to be executed on submit.
    iSubmitCount = iSubmitCount + 1;
    setTimeout('ShowHideSummaryImage();', 500);
    hideDivAndCal();
    //swap visible images source for error tracking
    setTimeout('swValImageUrl();', 500);
    ResetPop();
}
function swValImageUrl()
{
    $('span:visible > .error_img').each(function()
    {
        var sSrc = $(this).attr('src');
        if (this.id != '')//change has been implemented
        {   
            var ipos = sSrc.indexOf('?');
            if(ipos > -1)//source has already changed
            {   sSrc = sSrc.substring(0, ipos);    }
            $(this).attr('src', trim(sSrc) + '?id=' + this.id + '&sc=' + iSubmitCount);
        }
//        else //for debugging only 
//            alert(this.id);
    });
}

function HighlightPDLabel() {
    if ($("#ctl00_MainContent_ctl00_MyCalendar1_txtDateBox").hasClass("inputerror") || $("#ctl00_MainContent_ctl00_MyCalendar2_txtDateBox").hasClass("inputerror")) {
        $("#lbl_txtDateBox").addClass("AppLabelError") 
        $("#lbl_txtDateBox").removeClass("AppLabel2")
        }
    else {
        $("#lbl_txtDateBox").removeClass("AppLabelError")
    }
}

//JSON For Zip Code

function getCitiesAndStateJS(zipCode) {
//could add more error checking so we don't go to the server if it is not 5 digits

    if (zipCode != "")
    {
        var url = "DataHandler.ashx?" + addQueryStr("action", "1") + addQueryStr("zip", zipCode);

        $.getJSON(url + getUniqCall(),
            function(ret) {
                if (ret.responseObject == null) {
                    //$("#ctl00_MainContent_ctl00_InvalidZip").show();
                    document.getElementById('ctl00_MainContent_ctl00_txtState').value = '';
                    document.getElementById('ctl00_MainContent_ctl00_txtZipCodeTwo').value = '';
                    document.getElementById('cmbCity').length = 0
                    document.getElementById('ctl00_MainContent_ctl00_txtZipCodeTwo').className = 'inputerror';
                    document.getElementById('lbl_txtZipCodeTwo').className = 'AppLabelError';
                    //Zip code has been set to empty so not alert them that it is invalid
                    alertModal2(document.getElementById('ctl00_MainContent_ctl00_txtZipCodeTwo'), 'InvalidZipAlert', '', 100, 350);
                }
                else {
                    //clear out city drop down here
                    document.getElementById('cmbCity').length = 0
                    //$("#ctl00_MainContent_ctl00_cmbCity").append('<option value="">-- Select --</option>');
                    $.each(ret.responseObject, function(i,item)
                    {   
                        FillCitiesAndZip(i, item)
                    });
                    
                    //select the first choice
                    document.getElementById('cmbCity').selectedIndex = 0
                    document.getElementById('ctl00_MainContent_ctl00_txtCity').value = document.getElementById('cmbCity').options[0].value
                    
                    //if state is in filtered states display message
                    if (alertModal2(document.getElementById('ctl00_MainContent_ctl00_txtState'), 'InvalidZipAlert', $('#ctl00_MainContent_ctl00_txtState').attr('FilteredStates'), 100, 350)) {
                        document.getElementById('ctl00_MainContent_ctl00_txtState').value = '';
                        document.getElementById('ctl00_MainContent_ctl00_txtZipCodeTwo').value = '';
                        document.getElementById('ctl00_MainContent_ctl00_txtZipCodeTwo').className = 'inputerror';
                        document.getElementById('lbl_txtZipCodeTwo').className = 'AppLabelError';
                        document.getElementById('cmbCity').length = 0
                    }
               }      
        });
    }
}

function UpdatePayDatesJS(PayFrequency) {
    if (PayFrequency != "")
    {
        var url = "DataHandler.ashx?" + addQueryStr("action", "2") + addQueryStr("PayFrequency", PayFrequency);

        $.getJSON(url + getUniqCall(),
        {},
            function(ret) {
                if (ret.responseObject != null) {
                //clear out paydate drop down here
                    document.getElementById('cmbPayDate').length = 0
                    $.each(ret.responseObject, function(i,item)
                    {   
                        if (item == null) {
                        }
                        else {
                            $("#cmbPayDate").append('<option value="' + item.toString()+ '">' + item.toString() + '</option>');
                        }
                        
                    });
                    
                    //select the first choice
                    document.getElementById('cmbPayDate').selectedIndex = 0
                    document.getElementById('ctl00_MainContent_ctl00_txtPayDate').value = document.getElementById('cmbPayDate').options[0].value.substr(0, 10)    
                }
        });
    }
}



function FillCitiesAndZip(i, item) {
    if ((i % 2) == 0) {
    //even so fill the cities
        if (item.toString() != '') {
            $("#cmbCity").append('<option value="' + item.toString()+ '">' + item.toString() + '</option>');
        }
    }
    else {
        //odd
        if (i==1) {
            //prefill the state and drivers's license state if the value isn't empty string
            document.getElementById("ctl00_MainContent_ctl00_txtState").value= item.toString();
            //document.getElementById("ctl00_MainContent_ctl00_cmbDLState").selectedValue = item.toString();
        
            $('#ctl00_MainContent_ctl00_cmbDLState').val(item.toString());
        
//            for (i=0;i<document.getElementById('ctl00_MainContent_ctl00_cmbDLState').options.length;i=i+1) {
//            
//                if (document.getElementById('ctl00_MainContent_ctl00_cmbDLState').options[i].value == item.toString()) {
//                document.getElementById('ctl00_MainContent_ctl00_cmbDLState').selectedIndex = i;
//                }
//            }          
        }
        //if it isn't 1 ignore the odd numbers
    } 
}

function setCityTxt() {
//set the city textbox to whatever was chosen in the city drop down

    document.getElementById("ctl00_MainContent_ctl00_txtCity").value = document.getElementById("cmbCity").value
}

function setPayDateTxt() {
//set the city textbox to whatever was chosen in the city drop down

    document.getElementById("ctl00_MainContent_ctl00_txtPayDate").value = document.getElementById("cmbPayDate").value.substr(0, 10)
}


function addQueryStr(name, val) {
    return "&" + name + "=" + val;
}

function getUniqCall() {
    return '&wtsmni=' + Number(new Date());//used to sold ie's cachin issue.
}
//End JSON For Zip Code