function init()
{
	hookPopEvents();
    updateState();
}

function getForm()
{
    var form = null;
    if (document.LeadForm) {
        form = document.LeadForm;
    }else if (document.LeadFormTwoPage) {
        form = document.LeadFormTwoPage;
    }else if (document.LeadFormTwoPageCombo) {
        form = document.LeadFormTwoPageCombo;
    }else if (document.LeadFormThreePage) {
        form = document.LeadFormThreePage;
    }else if (document.LeadShortForm) {
        form = document.LeadShortForm;
    }else if (document.CallCenterLeadForm) {
        form = document.CallCenterLeadForm;
    }else if (document.LoanQuotesForm){
    	form = document.LoanQuotesForm;		
    }
    return form;
}

function updateState()
{
    var form = getForm();
    
    if (form != null){

    var state, license_state, job_employer_state;
    if (form.elements["state"]) 
    {
        state = form.elements["state"].value;
        
        if (form.elements["license_state"]) 
        {
            license_state = form.elements["license_state"].value;
            //if ( license_state == '' )
                form.elements["license_state"].value = state;
        }

        if (form.elements["job_employer_state"]) 
        {
            job_employer_state = form.elements["job_employer_state"].value;
            //if ( job_employer_state == '' )
                form.elements["job_employer_state"].value = state;
        }
    }
    }//if form
}

function getDayofWeek(y, m, d)
{
    var thedate2 = new Date();

    thedate2.setYear(y);
    thedate2.setDate(d);
    thedate2.setMonth(m-1);
    thedate2.setHours(0);
    thedate2.setMinutes(0);
    thedate2.setSeconds(0);

    var dayofweek = thedate2.getDay();

    return dayofweek;
}

function isWeekend(y, m, d)
{
    var dayofweek = getDayofWeek(y, m, d);

    if (dayofweek == 0 || dayofweek == 6)
        return true;
    else
        return false;
}

function isHoliday(y, m, d)
{
    switch(y) {
    case 2005:
        var holidays = {
          1 :  [1, 17],
          2 :  [21],
          5 :  [30],
          7 :  [4],
          9 :  [5],
          10 : [10],
          11 : [11,24],
          12 : [26]
        };
        break;
    case 2006:
        var holidays = {
          1 :  [2, 16],
          2 :  [20],
          5 :  [29],
          7 :  [4],
          9 :  [4],
          10 : [9],
          11 : [11, 23],
          12 : [25]
        };
        break;
    case 2007:
        var holidays = {
          1 :  [1, 15],
          2 :  [19],
          5 :  [28],
          7 :  [4],
          9 :  [3],
          10 : [8],
          11 : [12, 22],
          12 : [25]
        }
        break;
    case 2008:
        var holidays = {
          1 :  [1, 21],
          2 :  [18],
          5 :  [26],
          7 :  [4],
          9 :  [1],
          10 : [13],
          11 : [11, 27],
          12 : [25]
        }
        break;
    }

    // disable holidays
    holidaysthismonth = holidays[m];

    if (!holidaysthismonth)
        return false;

    for (var i in holidaysthismonth)
        if (holidaysthismonth[i] == d)
            return true;

    return false;
}

function dateAdd(intval, numb, base){
	/*intval is YYYY, M, D, H, N, S as in VBscript; numb is amount +/-; base is javascript date object*/
	switch(intval){
		case "M":
			base.setMonth(base.getMonth() + numb);
			break;
		case "YYYY":
			base.setFullYear(base.getFullYear() + numb);
			break;
		case "D":
			base.setDate(base.getDate() + numb);
			break;
		case "H":
			base.setHours(base.getHours() + numb);
			break;
		case "N":
			base.setMinutes(base.getMinutes() + numb);
			break;
		case "S":
			base.setSeconds(base.getSeconds() + numb);
			break;
		default:
	}
	return base
}

function correctPayday(y, m, d)
{
    var thedate = new Date();
    thedate.setYear(y);
    thedate.setDate(d);
    thedate.setMonth(m-1);
    thedate.setHours(0);
    thedate.setMinutes(0);
    thedate.setSeconds(0);

    // Step 1 - if weekend, then move back 1 or 2 days
    if (isWeekend(y,m,d))
    {
        var dayofweek = getDayofWeek(y, m, d);
        if (dayofweek==0)
            dateAdd("D", -2, thedate);
        if (dayofweek==6)
            dateAdd("D", -1, thedate);

        correctPayday((thedate.getYear()<1000)?1900+thedate.getYear():thedate.getYear(), thedate.getMonth()+1, thedate.getDate());
    }

    // Step 2 - if holiday, then move back 1 day, unless the holiday is a Monday, then go to Tuesday
    if (isHoliday(y,m,d))
    {
        var dayofweek = getDayofWeek(y, m, d);

        if (dayofweek==1)
            dateAdd("D", +1, thedate);
        else
            dateAdd("D", -1, thedate);
    }

    return thedate;
}

function validateSSN(ssn)
{
	var value = ssn;
	var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/; 
	if (!re.test(value)) { return false; } 
	var temp = value; 
	if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); } 
	if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); } 
	if (temp.substring(0, 3) == "000") { return false; } 
	if (temp.substring(3, 5) == "00") { return false; } 
	if (temp.substring(5, 9) == "0000") { return false; } 
	return true;
}

function showHelp(id) {
    document.getElementById(id).style.display = 'block';
}
function hideHelp(id) {
    document.getElementById(id).style.display = 'none';
}

function checkRadio(fieldset,alertText) {
    var selected = 0;
    if (document.getElementsByName(fieldset).length == 0) {
        return;
    }
    for (var i = 0; i < document.getElementsByName(fieldset).length; i++) {
        if (document.getElementsByName(fieldset)[i].checked) {
            selected++;
        }
    }
    if (selected == 0) {
        if (alertText) {
            alert (alertText);
        }
        else {
            alert ('Please make sure you have completed the form.');
        }
        return false;
    }
}

function hookPopEvents()
{
	// put an onchange call to the handlePopEvents on all the interesting form elements
	
	var formNode = document.getElementsByTagName("form");
	
	if (formNode[0]!= undefined){
		
	var nodes = [];
	for (i=0; i<formNode[0].getElementsByTagName("select").length; ++i) nodes.push(formNode[0].getElementsByTagName("select")[i]);
	for (i=0; i<formNode[0].getElementsByTagName("input").length; ++i) nodes.push(formNode[0].getElementsByTagName("input")[i]);
	for (var i=0; i<nodes.length; ++i)
	{
		if (nodes[i].getAttribute("name") == "state" ||
			nodes[i].getAttribute("name") == "income_monthly_net" ||
			nodes[i].getAttribute("name") == "isMilitary" ||
			nodes[i].getAttribute("name") == "income_directdeposit")
		{
			if (nodes[i].addEventListener != null)
				nodes[i].addEventListener("change", processPopWidgetEvent, false);
			else if (nodes[i].attachEvent != null)
				nodes[i].attachEvent("onchange", processPopWidgetEvent);
		}
	}
	}
	return;
}

function processPopWidgetEvent(event)
{
	var e = event || window.event;
	var name, value;
	if (e.srcElement)
	{
		name = e.srcElement.name;
		value = e.srcElement.value;
	}
	else if (e.target)
	{
		name = e.target.name;
		value = e.target.value;
	}
		
	//alert(name + " " + value);
	
	var submitURL = "/leads/get_form_value_pops.jsp";
	var params =  "fieldname=" + name + "&value=" + value;

	var req;
	try {
		// Firefox, Opera 8.0+, Safari
		req = new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				// fall through
			}
		}
	}
	if (req != undefined) {
		req.onreadystatechange=function()
		{
			if(req.readyState==4)
			{
				// only if "OK"
				if (req.status == 200 && req.responseText.length > 0)
				{
					var cleanResponse = req.responseText.replace(/^\s+/, '');
					cleanResponse = cleanResponse.replace(/\s+$/, '');
					var pops = cleanResponse.split("&dummyendofurl=true&");
					for (var i=0; i<pops.length; ++i)
					{
						pop = pops[i];
						if (pop.length == 0)
							continue;
						var type = pop.substring(0, pop.indexOf("="));
						var url = pop.substring(pop.indexOf("=")+1, pop.length);
						
						if (url.length > 0)
						{
							popit(url, type.indexOf("under") > 0 ? 1 : 0);
						}
					}
				}
			}
		}
		
		req.open("POST",submitURL,true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", params.length);
		req.setRequestHeader("Connection", "close");
		req.send(params);
	}
}
