/**
 * global javascript functions for ratetrack
 */

/**************************************************/
/* REQUIRED FIELD COLLECTIONS FOR DIFFERENT PAGES */
/**************************************************/
/* NOTE : these Arrays exist here to keep all JS  */
/* centralized. The individual pages should only  */
/* contain calls to methods declared in this file */
/**************************************************/


//lo_edit_mailer.php
var loeditmailerIds		= Array('full_name', 'email', 'state', 'month_start_reports', 'orig_loan_amount', 'interest_rate', 'loan_term', 'loan_type', 'first_payment_date', 'property_occupancy', 'interest_only' );
var loeditmailerNames	= Array('Name', 'Email', 'State', 'Month to Start Reports', 'Original Loan Amount', 'Interest Rate', 'Loan Term', 'Loan Type', 'First Payment Date', 'Property Occupancy', 'Payment P&I or Interest Only' );

//lo_referral_edit.php
var lorefeditIds	= Array('partner_name', 'promo_code' );
var lorefeditNames	= Array('Name', 'Promo Code' );

//lo_referrals.php
var loreferralsIds		= Array('partner_name', 'promo_code', 'banner_ad');
var loreferralsNames	= Array('Name', 'Promo Code', 'Banner Ad');

//lo_reports.php
var loreportsIds	= Array('region_id', 'intro_letter', 'arm_watch');
var loreportsNames	= Array('Region', 'Intro Letter', 'Arm Watch');

//lo_account.php
var loacctIds	= Array('company_name', 'company_phone', 'company_address', 'full_name', 'email', 'phone', 'address', 'city', 'state', 'zipcode', 'password', 'password2');
var loacctNames	= Array('Company Name', 'Company Phone', 'Company Address', 'Name', 'Email', 'Phone', 'Address', 'City', 'State', 'Zipcode', 'Password', 'Confirm Password');

/**************************************************/
/* LOAD REPORT POP-UP PAGE						  */
/**************************************************/

function openReportWin(url){
window.open('http://www.myratetrack.com/system/client/ms_loading_report.php?src='+url,'popup','width=750,height=580,scrollbars=1,resizable=1');
}



/**************************************************/
/* FUNCTIONS USED THROUGHOUT APP				  */
/**************************************************/


	/*
		Required field and password checker for signup with promo code
	*/
	function checkSignupPromo()
	{
		//login.php : signup with promo
		var signupIds	= Array('pc1_full_name', 'pc1_email', 'pc1_password', 'pc1_password2');
		var signupNames	= Array('Full Name', 'Email', 'Password', 'Confirm Password');

		//required fields good?
		if( checkRequiredFields( signupIds, signupNames ) )
		{
			//do passwords match?
			return comparePasswords('pc1_password', 'pc1_password2');
		}
		else
		{
			return false;
		}
	}

	/*
		Required field and password checker for signup with promo code
	*/
	function validateRegister()
	{
		//register.php : register without promo
		var signupIds	= Array('pc_full_name', 'pc_email', 'pc_password', 'pc_password2');
		var signupNames	= Array('Full Name', 'Email', 'Password', 'Confirm Password');

		//required fields good?
		if( checkRequiredFields( signupIds, signupNames ) )
		{
			//do passwords match?
			return comparePasswords('pc_password', 'pc_password2');
		}
		else
		{
			return false;
		}
	}

	/*
		Calculate ARM first adj.date = closing date + the ARM fixed term in months
		This just returns an adjusted date string, and not an true date object

		ASSUMPTIONS MADE BY THIS FUNCTION :
		- the field ids hard coded here exist in the calling form

		- the values coming in from arm_fixed_term are 1,6, { factors of 12 }
		That is, this function adds values < 12 to the month. Values > 12 get
		divided by 12 then added to the year.  If a value > 12 isn't a factor of multiple
		of 12, this function will return unexpected results
	*/
	function calculateArmAdjDate()
	{
		//get fields
		var closing_date	= document.getElementById('closing_date').value;
		var term_months		= document.getElementById('arm_fixed_term').value;
		//target field
		var f_arm_adj_date	= document.getElementById('arm_first_adjustment_date');

		//make sure we have values to work with
		if( ( closing_date != "" ) && ( term_months != "" ) )
		{
			//cast to number
			term_months			= parseInt( term_months );

			//split text date into array for date manipulation below ( month/day/year )
			var aDate	= closing_date.split('/');
			var mo		= parseInt( aDate[0] );
			var day		= parseInt( aDate[1] );
			var yr		= parseInt( aDate[2] );

			//holder for the adjusted date
			var s_new_date = "";

			//determine if we're adjusting month or year
			if( term_months < 12 )
			{
				//adjust existing month
				var new_mo = parseInt( mo + term_months );
				s_new_date = new_mo + "/" + day + "/" + yr;
			}
			else
			{
				//adjust years
				var add_years	= parseInt( term_months / 12 ); //convert to years
				var new_yr		= parseInt( yr + add_years );
				s_new_date		= mo + "/" + day + "/" + new_yr;
			}

			//set value
			f_arm_adj_date.value = s_new_date;
		}
		else
		{
			f_arm_adj_date.value = "";
		}
	}

	/*
	When ARM loan is set to yes, this function will set all of the appropiate
	default settings.

	When set to no, this should erase the values

	ARM Index: *	required if ARM loan is “yes” (default will be 12 month LIBOR)
	ARM Margin: *	required if ARM loan is “yes” (default will be 2.5%)
	ARM first cap: * required if ARM loan is “yes” (default will be 5%)
	*/
	function setArmDefaults()
	{
		//get fields
		var f_arm		= document.getElementById('arm_loan');
		var f_arm_idx	= document.getElementById('arm_index');
		var f_arm_mrg	= document.getElementById('arm_margin');
		var f_arm_cap	= document.getElementById('arm_first_cap');

		if( f_arm.value == 1)
		{
			//set defaults

			//NOTE : these fields may be converted to SELECTs, to be aware of that
			f_arm_idx.value = "12 month LIBOR";
			f_arm_mrg.value	= "2.5";
			f_arm_cap.value	= 5;
		}
		else
		{
			//erase values
			f_arm_idx.value = "";
			f_arm_mrg.value	= "";
			f_arm_cap.value	= "";
		}
	}


	/*
		Custom required field validator for lo_client_search Add a Client

		ARM loan?: *  yes or no
		ARM Index: *	required if ARM loan is “yes” (default will be 12 month LIBOR)
		ARM Margin: *	required if ARM loan is “yes” (default will be 2.5%)
		ARM fixed term: *	required if ARM loan is “yes”
		ARM first adjustment date: * required if ARM loan is “yes”
		ARM first cap: * required if ARM loan is “yes” (default will be 5%)
	*/
	function checkAddClientForm()
	{
		//always required
		var loclisIds	= Array('full_name', 'email', 'region_id', 'month_start_reports', 'orig_loan_amount', 'interest_rate', 'loan_term', 'loan_type', 'first_payment_date', 'property_occupancy', 'interest_only' );
		var loclisNames	= Array('Name', 'Email', 'State / Region', 'Month to Start Reports', 'Original Loan Amount', 'Interest Rate', 'Loan Term', 'Loan Type', 'First Payment Date', 'Property Occupancy', 'Interest Only' );

		var good		= checkRequiredFields(loclisIds, loclisNames);

		//did the first group of required fields pass the test?
		if(good)
		{
			var bArmLoan = document.getElementById('arm_loan').value;

			//is this an arm loan?
			if(bArmLoan == 1)
			{
				//required if ARM loan = yes
				var armIds		= Array( 'closing_date', 'arm_margin', 'arm_fixed_term', 'arm_first_adjustment_date', 'arm_first_cap' );
				var armNames	= Array( 'Closing Date', 'ARM Margin', 'ARM Fixed Term', 'ARM First Adjustment Date', 'ARM First Cap' );

				//check required ARM loan fields
				good = checkRequiredFields( armIds, armNames );
			}
		}

		return good;
	}



	//verify passwords, then required
	function checkEditMailerForm()
	{
		if( comparePasswords('password', 'password2') )
		{
			return checkRequiredFields( loeditmailerIds, loeditmailerNames );
		}
		else
		{
			return false;
		}
	}

	function verifyAdminLoSearchForm()
	{
		//verify password fields
		if( comparePasswords( 'password', 'password2') )
		{
			//check required fields
			return checkRequiredFields(
									Array('company_name', 'company_phone', 'company_address', 'full_name', 'email'),
								 	Array('Company Name', 'Company Phone', 'Company Address', 'Name', 'Email')
								 	);
		}
		else
		{
			return false;
		}
	}


	function verifyLoAccountForm()
	{
		//verify password fields
		if( comparePasswords( 'password', 'password2') )
		{
			//check required fields
			return checkRequiredFields( loacctIds, loacctNames );
		}
		else
		{
			return false;
		}
	}


	//form submitter function used to set appropriate command
	//prior to submitting a multi-purpose form
	function setCmd( cmd )
	{
		var f_cmd = document.getElementById('cmd');
		f_cmd.value = cmd
		return true;
	}



	/* This routine changes the CMD of this form so the handler knows which
	 * button was pushed
	 */
	function checkForm( act )
	{
		var f_act = document.getElementById('cmd');
		f_act.value = act;

		switch( act )
		{
			//field checks
			case "update":

				var pswd = document.getElementById('password');
				var pswd2 = document.getElementById('password2');
				var email = document.getElementById('email');

				//mis-matched password?
				if( pswd.value != pswd2.value )
				{
					alert("The password fields do not match.  Please retype your password before submitting this form.");
					return false;
				}
				//required fields
				else if ( (email.value == "") || (pswd.value == "") )
				{
					alert("Email and Password are required.  Please fill these fields out before submitting this form.");
					return false;
				}
				else
				{
					return true;
				}
			break;

			case "renew" :
				var cc = document.getElementById('card_number');

				if( cc.value == "")
				{
					alert("Please enter a credit card number.")
					return false;
				}
				else
				{
					return true;
				}
			break;
		}
	}


	//validate required fields on ms_formchange
	function validateFormChange()
	{
		var name		= document.getElementById("name");
		var email		= document.getElementById("email");
		var comments	= document.getElementById("comments");

		if( ( name.value == "" ) || ( email.value == "" ) || ( comments.value == "" ) )
		{
			alert("Please fill out all fields before submitting this form.");
			return false;
		}
		else
		{
			return true;
		}
	}


	/**
	* Pass in an array of field ids, and this
	* will loop through and verify each required field
	* contains a value.
	* If any of your fields do not get checked, verify
	* that field has id="" set to the value in fld_ids
	*/
	function checkRequiredFields( fld_ids, fld_names )
	{
		var msg		= "The following required fields are empty : \n";
		var good	= true; //is form good to submit?

		for( xx = 0; xx <= fld_ids.length-1; xx++ )
		{
			var fld = document.getElementById( fld_ids[xx] );

			//check for bad fields
			if(fld == null)
			{
				alert("The field '" + fld_names[xx] + "' doesn't have it's ID ("+ fld_ids[xx] +") set properly");
				good = false;
				xx = fld_ids.length-1;	//force loop break
				break;
			}

			//remove spaces ( not trim )
			field_value = fld.value.split(" ").join("");

			if(field_value == "")
			{
				msg		+= " - " + fld_names[xx] + "\n";
				good	= false;
				fld.style.border = "1px solid red";
			}
			else
			{
				fld.style.border = "";
			}
		}

		msg += "Please fill out these fields before submitting the form.";

		if(!good)
		{
			//show required field msg
			alert( msg );
		}

		//if the code makes it here, the form is good
		return good;
	}

	/**
	* Pass in the id of two password fields, and this will tell
	* you if their values match or not
	*/
	function comparePasswords( fld1, fld2 )
	{
		var f1 = document.getElementById( fld1 );
		var f2 = document.getElementById( fld2 );

		//remove spaces
		pswd1 = f1.value.split(" ").join("");
		pswd2 = f2.value.split(" ").join("");

		if( pswd1 != pswd2 )
		{
			alert("Password fields do not match.  Please re-type your password in both fields.");
			return false;
		}
		else
		{
			return true;
		}
	}


	function verifyNewRegionForm()
	{
		setCmd('add');

		//required field ids
		var aIds	= Array('region_name', 'origination_fee', 'appraisal_fee', 'credit_report_fee',
							'uw_admin_fee', 'attorney_fee', 'title_search_fee', 'title_insurance_factor',
							'property_tax_factor', 'hazard_insurance_factor', 'license_state_number' );
		//required field names
		var aNames	= Array('Region Name', 'Origination Fee', 'Appraisal Fee', 'Credit Report Fee',
							'UW/Admin Fee', 'Attorney Fee', 'Title Search Fee', 'Title Insurance Factor',
							'Property Tax Factor', 'Hazard Insurance Factor', 'License State Number' );

		return checkRequiredFields( aIds, aNames );
	}

	/**
	* Choose region postback handler.  Does not postback if no region was
	* selected
	*/
	function doPostback()
	{
		//first verify cmd == step1
		setCmd('step1');

		var f_region = document.getElementById('region_id');

		//blank or 0 == bogus
		if(f_region.value == "" || f_region.value == 0 )
		{
			alert("Please choose a region");
			return false;
		}
		else
		{
			//a single form is assumed here
			document.forms[0].submit();
		}
	}