$(document).ready(function() {
	$(".chat").fancybox({
		'width'				: 590,
		'height'			: 560,
		'autoScale'			: false,
		'titleShow'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'padding'			: 0,
		'scrolling'			: 'auto'
	});
});

$(document).ready(function() {
	$(".loanpost_popup").fancybox({
		'width'				: 850,
		'height'			: 650,
		'autoScale'			: false,
		'titleShow'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'padding'			: 0,
		'scrolling'			: 'auto'
	});
});


$(document).ready(function() {
	$(".faq_list .h4").click(function() {
		$(this).next().toggle("fast");
	});
});

$(document).ready(function() {
	$("#mainmenu > li").hover(
		function () {
			$(".positioner").each(function() {
				$(this).hide();
			  });
			$(this).find(".positioner").show();
		}, 
		function () {
			//$(this).find(".positioner").hide();
			//$("#default_submenu").show();
		}
	);
});

$(document).ready(function() {
	$("#mainmenu").hover(
		function () {
			//$("#default_submenu").hide();
			//$(this).find(".positioner").show();
		}, 
		function () {
			$(".positioner").each(function() {
				$(this).hide();
			  });
			$("#default_submenu").fadeIn("fast");
			//$(this).find(".positioner").hide();
		}
	);
});

/* ////////////////////////////////////////////////////////////////////////////////////////////////// */


function fillSelectBoxes() {

	count = 0;
	numFormEls = document.webform.elements.length;
	formEls = document.webform.elements;

	while (count < numFormEls) {

		regxState 		= /state/;
		regxPhoneType	= /phone-type/;
		regxBestTime	= /best-time/;
		regxEmployType	= /employment-type/;

		if (regxState.test(formEls[count].name)) {			
			regNum = parseInt(RegExp.$1) + 1;		
			inputStates();		
		}

		if (regxPhoneType.test(formEls[count].name)) {			
			regNum = parseInt(RegExp.$1) + 1;		
			inputPhoneTypes();		
		}

		if (regxBestTime.test(formEls[count].name)) {			
			regNum = parseInt(RegExp.$1) + 1;		
			inputBestTime();		
		}

		count++;
	}	
}

function inputStates() {
	formEls[count].length = 51;
	formEls[count].options[0].value = "none selected";
	formEls[count].options[0].text = "Please Select";
	var stateVals = new Array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Colombia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming")
	var stateTexts = new Array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Colombia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming")
	for(sCount=1;sCount<51;sCount++) {
		formEls[count].options[sCount].value = stateVals[sCount]
		formEls[count].options[sCount].text = stateTexts[sCount]
	}
}

function inputPhoneTypes() {
	formEls[count].length = 4;
	var phoneTypeVals = new Array("None", "Home", "Work", "Cell")
	var phoneTypeTexts = new Array("Please Select", "Home", "Work","Cell")
	for(sCount=0;sCount<4;sCount++) {
		formEls[count].options[sCount].value = phoneTypeVals[sCount]
		formEls[count].options[sCount].text = phoneTypeTexts[sCount]
	}
}

function inputBestTime() {
	formEls[count].length = 4;
	var bestTimeVals = new Array("None", "Morning", "Afternoon", "Evening")
	var bestTimeTexts = new Array("Please Select", "Morning", "Afternoon","Evening (after 5 p.m.)")
	for(sCount=0;sCount<4;sCount++) {
		formEls[count].options[sCount].value = bestTimeVals[sCount]
		formEls[count].options[sCount].text = bestTimeTexts[sCount]
	}
}


/* ////////////////////////////////////////////////////////////////////////////////////////////////// */


function validateForm() {

	var count = 0;
	var numFormEls = "";
	var formEls = "";
	var formElId = "";
	var name = "";
	var valMsg = false;
	var errExist = false;
	var reqOmni = "";

	numFormEls = document.webform.elements.length;
	formEls = document.webform.elements;

	jQuery(function(){

		for(count=0; count < numFormEls; count++) {

			regx = /^(\w+)\-?\-?\w*\-\-req\-?\-?\w*$/;

			if (regx.test(formEls[count].id)) {

				//removing --req 
				name = RegExp.$1;
				formElId = formEls[count].id;	

				var errMsg = "";
				var expression = "";

				//If the control is E-mail address
				if (formEls[count].id == "email--req"){	
				
					expression = "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;";
					errMsg = "Please enter a valid e-mail address";
					setBlurEvent(formElId, expression, errMsg);
					valMsg =  validate_field({
						tid: formElId,	
						expression: expression,
						message: errMsg
                	});

				}

				//If the control is Phone
				else if (numFormEls[count].id == "phone--req"){
					
					expression = "if (isValidPhone(VAL)) return true; else return false;";
					errMsg = "Please enter a valid Phone";
					setBlurEvent(formElId, expression, errMsg);
					valMsg =  validate_field({
						tid: formElId,
						expression: expression,
						message: errMsg

					});
				}
				
				else {	

					expression = "if (VAL) return true; else return false;";										

					//If title attr contains the custom error msg
					if ($("#"+formElId).attr("title") != ""){ 
						errMsg = $("#" + formElId).attr("title");
					}

					else {
						errMsg = "Please enter " + properCap(name);
					}									

					setBlurEvent(formElId, expression, errMsg);
					valMsg =  validate_field({
						tid: formElId,
						expression: expression,
						message: errMsg
					});
				}

				

				//If error
				if (valMsg == false){
					reqOmni+= properCap(formElId) + ", ";
				}

				//setting error flag
				if (errExist == false && valMsg == false){
					errExist = true;
				}

			}			
			// END: if (regx.test(formEls[count].id)
		}			
		// END: for(count=0; count < numFormEls; count++)

		

		//If error flag true
		if (errExist) {

			//Omniture Code for Form Analysis Report
			var reqOmniArray = new Array();
			reqOmniArray = reqOmni.split(",");
			
			for(m=0; m<reqOmniArray.length-1; m++){
				s.sendFormEvent('e', thisPageName, document.form_val.name, reqOmniArray[m]);
			}

			var formID = document.form_val.title;
			if(formID == ''){ formID = thisPageName; }
			s.eVar8 = formID;
			//End of Omniture Code for Form Analysis Report
		}

		else {
			s.sendFormEvent('s', thisPageName, document.form_val.name);
			document.form_val.submit();
		}
	});	

}



//Validating the field on blur
function setBlurEvent(sId, sExp, sMsg) {

	jQuery("#" + sId).bind('blur', function(){						

		validate_field({
			tid: sId,	
			expression: sExp,
			message: sMsg
		});
	});

}



//Validating the field and setting the error styles
function validate_field(options){

	options = jQuery.extend({

			tid: "",				 
            expression: "return true;",
            message: "",
            error_class: "ValidationErrors",
            error_field_class: "ErrorField",
            live: true

        }, options);			

	var self ="#"+ options['tid'];
	var SelfID = jQuery(self).attr("id");	
	var expression = 'function Validate(){' + options['expression'].replace(/VAL/g, '$(\'#' + SelfID + '\').val()') + '} Validate()';
	var validation_state = eval(expression);		

	if (!validation_state) {
		if (jQuery(self).parent().next('.' + options['error_class']).length == 0) {

			//Adding error style to the container containing the control
			jQuery(self).parent().addClass(options['error_field_class']);

			//Adding error style to the container containing the label
			jQuery(self).parent().prev().addClass(options['error_field_class']);

			//Adding error message
			jQuery(self).parent().after('<div class="' + options['error_class'] + '">' + options['message'] + '</div>');

		}	 
	}

	

	//On focus remove error message
	jQuery(self).bind('focus keypress', function(){

		jQuery(self).next('.' + options['error_class']).fadeOut("fast", function(){
                        jQuery(self).remove();
                    });

		//Removing error style to the container containing the control
		jQuery(self).parent().removeClass(options['error_field_class']);

		//Removing error style to the container containing the label
		jQuery(self).parent().prev().removeClass(options['error_field_class']);

		//Removing error message
		jQuery(self).parent().next('.' + options['error_class']).remove();

	});		

	return validation_state;	

}



 /* This functions checks where an entered date is valid or not.
 * It also works for leap year feb 29ths.
 * @year: The Year entered in a date
 * @month: The Month entered in a date
 * @day: The Day entered in a date
 */

function isValidDate(year, month, day){

    var date = new Date(year, (month - 1), day);
    var DateYear = date.getFullYear();
    var DateMonth = date.getMonth();
    var DateDay = date.getDate();

    if (DateYear == year && DateMonth == (month - 1) && DateDay == day) 
        return true;
    else 
        return false;
}



/*
 * This function checks if there is at-least one element checked in a group of check-boxes or radio buttons.
 * @id: The ID of the check-box or radio-button group
 */

function isChecked(id){

    var ReturnVal = false;

    $("#" + id).find('input[type="radio"]').each(function(){

        if ($(this).is(":checked")) 
            ReturnVal = true;

    });

    $("#" + id).find('input[type="checkbox"]').each(function(){

        if ($(this).is(":checked")) 
            ReturnVal = true;

    });

    return ReturnVal;
}



/* Phone number validation.
	Minimum 7 digits
	Allows only Numbers after striping out '.','-','(', ')' and empty spaces */

function isValidPhone(phone){

	var cl_phone = phone.replace(/[-.\(\)]/g,'')
	cl_phone = cl_phone.replace(/ /g,'')

	if ((Number(cl_phone)) && (cl_phone.length > 6)){       
	   return true;
	}
    else return false;
	
}

