// pre-qualify-form.js
	var applicants = 1;
	var occupancy = '';
	var adults = 0;
	var children = 0;
	var pets = 0, dogs = 0, cats = 0;
	var vehicles = 0, cars = 0, boats = 0, trailers = 0, campers = 0, motorcycles = 0;
	var expenses =	{
						car: [0,0,0],
						appliance: [0,0,0],
						furniture: [0,0,0],
						childsupport: [0,0,0]
					};
	var addrs = new Object();
	var appid;
	
	var jqmPosition = function(hash) {
	// Somewhat of a hack - position the window to the top of the page, so jqModal dialog boxes are always within the visible area of the browser window.
	// A simple 'fixed' position of them doesn't work in IE6 or older browsers.  This seemed the best/simplest workaround
	// Copied from http://dev.iceburg.net/jquery/jqModal/
	 window.scrollTo(0,0);
	 hash.w.show(); // When using the callback, we have to explicitly show the dialog
	}
		
		$(function() {
			
			$('#submit-application-form').ajaxForm();
			
			$("textarea").each(
				function(i) {
					$(this).attr('id', $(this).attr('name')).addClass('dim');
				}
			);
			$("select").each(
				function(i) {
					$(this).attr('id', $(this).attr('name')).addClass('dim');
				}
			);
			
			$("input[type='button']").live('click',
				function(e) {
					switch ($(e.target).attr('name')) {
						case 'property-address': changeAddress(); break;
						case 'prior-application': requestApplication(); break;
						case 'save-application': doSubmit(e.target, false); break;
						case 'submit-application': doSubmit(e.target, true);
					}
				}
			);
/*			$("input", "form").keyup(
				function(e) {
					if (e.keyCode == 13) {
						$("input[name='submit-application']").click();
					}
				}
			);
*/
			$("select[name='total-applicants']").change(
				function(e) {
					var n = $(e.target).val();
					loadApplicants(n);
				}
			);
			$("select[name='type-of-occupancy']").change(
				function(e) {
					occupancy = $(e.target).val();
					showhide("div.occupant-information", (occupancy == 'Applicant') || (occupancy == 'Family'));
					showhide("div.investor-landlord", (occupancy == 'Family') || (occupancy == 'Tenant') || (occupancy == 'Investment'));
//					showhideapplicants();
					hideIfInvestor(occupancy == "Tenant" || occupancy == "Investment");
				}
			);
			$("select[name='total-adults']").change(
				function(e) {
					adults = $(e.target).val();
					$("#val-adults").text(adults);
					showmax('div' ,'adult-', adults);
					showhide('.occupants', (adults+children > 0));
				}
			);
			$("select[name='total-children']").change(
				function(e) {
					children = $(e.target).val();
					$("#val-children").text(children);
					showmax('div' ,'children-', children);
					showhide('.occupants', (adults+children > 0));
				}
			);
			$("select[name='total-dogs']").change(
				function(e) {
					dogs = $(e.target).val();
					$("#val-dogs").text(dogs);
					showmax('div' ,'dog-', dogs);
					showhide('.pets',(dogs+cats > 0));
					petcost();
				}
			);
			$("select[name='total-cats']").change(
				function(e) {
					cats = $(e.target).val();
					$("#val-cats").text(cats);
					showmax('div' ,'cat-', cats);
					showhide('.pets',(dogs+cats > 0));
					petcost();
				}
			);
			$("select[name='total-cars']").change(
				function(e) {
					cars = $(e.target).val();
					$("#val-cars").text(cars);
					showmax('div' ,'cars-', cars);
					showhide('.vehicles',(cars+boats+trailers+campers+motorcycles > 0));
				}
			);
			$("select[name='total-boats']").change(
				function(e) {
					boats = $(e.target).val();
					$("#val-boats").text(boats);
					showmax('div' ,'boats-', boats);
					showhide('.vehicles',(cars+boats+trailers+campers+motorcycles > 0));
				}
			);
			$("select[name='total-trailers']").change(
				function(e) {
					trailers = $(e.target).val();
					$("#val-trailers").text(trailers);
					showmax('div' ,'trailers-', trailers);
					showhide('div.vehicles',(cars+boats+trailers+campers+motorcycles > 0));
				}
			);
			$("select[name='total-campers']").change(
				function(e) {
					campers = $(e.target).val();
					$("#val-campers").text(campers);
					showmax('div' ,'campers-', campers);
					showhide('.vehicles',(cars+boats+trailers+campers+motorcycles > 0));
				}
			);
			$("select[name='total-motorcycles']").change(
				function(e) {
					motorcycles = $(e.target).val();
					$("#val-motorcycles").text(motorcycles);
					showmax('div' ,'motorcycles-', motorcycles);
					showhide('.vehicles',(cars+boats+trailers+campers+motorcycles > 0));
				}
			);
			$("input[name^='applicant-car-payment-']").live('click',
				function(e) {
					updateExpenses(e.target,'car','furniture','appliance','child-support');
				}
			);
			$("input[name^='applicant-furniture-payment-']").live('click',
				function(e) {
					updateExpenses(e.target,'furniture','appliance','child-support','car');
				}
			);
			$("input[name^='applicant-appliance-payment-']").live('click',
				function(e) {
					updateExpenses(e.target,'appliance','child-support','car','furniture');
				}
			);
			$("input[name^='applicant-child-support-payment-']").live('click',
				function(e) {
					updateExpenses(e.target,'child-support','car','furniture','appliance');
				}
			);
			$("input[name^='applicant-income-wages-']").live('click',
				function(e) {
					updateWages(e.target,'wages','other','none');
				}
			);
			$("input[name^='applicant-income-other-']").live('click',
				function(e) {
					updateWages(e.target,'other','wages','none');
				}
			);
			$("input[name^='applicant-income-none-']").live('click',
				function(e) {
					updateWages(e.target,'none','other','wages');
				}
			);
			$("input","div#applicant-info-1").live('keyup',
				function(e) {
					showHideGeneral(1);
				}
			);
			$("input","div#applicant-info-2").live('keyup',
				function(e) {
					showHideGeneral(2);
				}
			);
			$("input","div#applicant-info-3").live('keyup',
				function(e) {
					showHideGeneral(3);
				}
			);
		
// Changing the property associated with this application			
			$("#dialog-change-address").jqm({onShow: jqmPosition});
			
			$("#change-address-cancel-button").live('click',
				function(e) {
					$("#dialog-change-address").jqmHide();
				}
			);
			$("#ad_num, #ad_str").live('keyup',
					function(e) {
						if (e.keyCode == 13) {
							searchForAddress();
						}
					}
			);
			$("#change-address-button").live('click',
			// Process the form and append details from the query
				function(e) {
					searchForAddress();
				}
			);
			
// Reloading a saved prior application
			$("#dialog-open-prior").jqm({onShow: jqmPosition});
			
			
			$("#lastname-prior, #ssn-prior").live('keyup',
					function(e) {
						if (e.keyCode == 13) {
							resumeApplication();
							$("#dialog-prior-application").jqmHide();
						}
					}
			);
			$("#request-application-button").live('click',
				function(e) {
					resumeApplication();
					$("#dialog-prior-application").jqmHide();
				}
			);
			$("#request-application-cancel-button").live('click',
				function(e) {
					$("#dialog-open-prior").jqmHide();
				}
			);
			
			$("#dialog-save-submit").jqm({onShow: jqmPosition});
			$("#submit-save-close-button").live('click',
				function(e) {
					$("#dialog-save-submit").jqmHide();
				}
			);
//			$("#date-of-occupancy").datepick({changeMonth: false, changeYear: false});
			
			$("input[name='address-view']").live('click',
				function(e) {
					var target = e.target;
					getAddress('view', $(target).attr('id'));
				}
			);
			$("input[name='search-website']").live('click',
				function(e) {
					var target = e.target;
					window.open('/list.php','list');
				}
			);
			$("input[name='address-apply']").live('click',
				function(e) {
					var target = e.target;
					getAddress('apply', $(target).attr('id'));
				}
			);
			$("input.resume-app-button").live('click',
				function(e) {
					var target = e.target;
					reloadApplication(e.target);
				}
			);
		
			setTimeout('loadApplicants(1)',500);	// Add default Applicant #1
			
			if ($("input#id").val() == '') { 		// When page loads, request address for application if no ID provided
				changeAddress();
			}
		$("form#submit-application-form").validationEngine();
		$("input","form").live('focus',	// Requires jQuery 1.4
			function(e) {
			//	if ($(this)
				$.validationEngine.loadValidation(e.target,'load')
			}
		);

		});  // end ready function
		function searchForAddress() {
			if ($("input#ad_str").val() =='' && $("input#ad_num").val() == '') {
				$("#change-address-status").text("Please enter street address");
			}
			else {
				$.get(
					"change-application-address.php",
					{
						ad_str: $("input#ad_str").val(),
						ad_num: $("input#ad_num").val()
					},
					function(data, status) {
						
						$("#change-address-status").text(data.status);
						$("#change-address-html").html(data.html);
						
						addrs = data.matches;
				//		setTimeout('$("#dialog-change-address").jqmHide()', 2500);  // hidepopup
						
					},
					'json'
				);
			}
		}
		function hideIfInvestor(investor) {
			if (investor) {
				$(".investor").hide();
			}
			else {
				$(".investor").show();
			}
		};
		function loadApplicants(n) {

			var i = $("div[class^='applicant-']","span#applicant-section").length + 1;  // Existing count
				
			if ($("div.applicant-"+i,"span#applicant-section").length == 0) {  // If this section doesn't exist already
				$.get(	'applicant.php?n='+i,
						function(data, status) {
							$("span#applicant-section").append(data);
							$("div.applicant-"+i).show();
							// Can't use .live event feature in IE
							$("select[name='applicant-places-lived-"+n+"']").change(
								function(e) {
									var i = parseInt(tail($(e.target).attr('name'),'-')); // What applicant?
									var n = parseInt($(e.target).val());							  // How many places?
									$(".current-address", "#housing-"+i).toggle(n >= 1);
									$(".prior-address-1", "#housing-"+i).toggle(n >= 2);
									$(".prior-address-2", "#housing-"+i).toggle(n >= 3);
									$(".prior-address-3", "#housing-"+i).toggle(n >= 4);
									$("div#housing-"+i).toggle((n >= 1));
								}
							);
							if (i < n) {
								loadApplicants(n);
							}
							else {
//								initFormFields();
								showmax('div' ,'applicant-', n);
							}
						}
				);
			}
		}
		function initFormFields() {
		// Delay this until the form is loaded so responsiveness is maintained
			$("input.telephone").not('.masked').mask("(999) 999-9999").addClass('masked');  // Add masked class so it only gets applied once
			
			$("input.zipcode").not('.masked').mask("99999").addClass('masked');
			
			$("input.date").not('.masked').mask("99/99/9999").addClass('masked');
			
			$("input.ssn").not('.masked').mask("999-99-9999").addClass('masked');
			
			$("input, select, textarea").not("[type='button']").not('.modified').emptyonclick();
			$("input, textarea").not("[type='button']").each(
				function(i) {
					$(this).attr('id', $(this).attr('name')).not('.modified').addClass('dim');
				}
			);
		}
		function doSubmit(e, complete) {
		// Only allow submit if we have a property id, and firstname, lastname and ssn for applicant #1
		// If complete is true, submit the application
		// If complete is false, save the application for later retrieval byt the applicant
			var v0 = $("#id").val();
			var v2 = $("input[name='applicant1-last-name']").val();
			var v3 = $("input[name='applicant1-tax-id']").val();
			if ((v0 == '') ||
				(v2 == '' || v2 == 'Last Name') || 
				(v3 == '' || v3 == 'Social Security #')  ) {
				var msg = "Your application cannot be uploaded without: \n\nApplicant #1\n\n1. Last Name\n2. Social Security # and";
				if (v0 == '') { msg+= "\n3. a property selected."; }
				alert(msg);
				return false;
			}
			else {
				// Clear all the fields without any input (not '.modified').  The hidden 'id' (property id) is an exception, never clear this value.
				$("#submit-application-form").not(".modified").val("");
				var method  =  complete ? 'submit' : 'save' ;  // save or submit the application
				var id		=  $("#id").val();				   // Property id

				$("#submit-application-form").ajaxSubmit(
						{
							beforeSubmit: function(flds, frm, options) {
								var elem;
								for (idx in flds) {
									elem = $("#"+flds[idx].name)[0];
									if (elem != undefined && elem.id != 'id' && (elem.tagName == 'INPUT' || elem.tagName == 'TEXTAREA') && elem.defaultVal == flds[idx].value) {
										flds[idx].value = '';  // Clear the default 'prompt' text since the user typed nothing in this field
									}
								// Form valuues we must always pass, not reset or clear out above
								if (flds[idx].name == 'submit-save') flds[idx].value=method;
								if (flds[idx].name == 'id')			 flds[idx].value=id;
								}
								
								return;
							},
							success: 
								function(data, status) {
									$("#dialog-save-submit").html(data.response);
									$("#dialog-save-submit").jqmShow();
								},
							dataType: 'json'
						}
				); 
				return false;  // So the form's inherent submit action is suppressed
			}
		}
		function changeAddress() {
			// Fetch the form and load it
			$.get('change-application-address.php',
				{},
				function(data,status) {
					$("#dialog-change-address").html(data.html);
					$("#change-address-status").text(data.status);
					$("input#id").val(data.id);
					$("#dialog-change-address").jqmShow()
				},
				'json'
			);
		return false;  // Stop 'click' event propagation
		}
		function requestApplication() {
			// Fetch the form and load it
			$.get('get-prior-application.php',
				{},
				function(data,status) {
					$("#dialog-open-prior").html(data.data);
					$("input#ssn-prior","#dialog-open-prior").mask("999-99-9999");
					$("#dialog-open-prior").jqmShow()
				},
				'json'
			);
		return false;  // Stop 'click' event propagation
		}
		function reloadApplication(button) {
				appid = $(button).attr('name');		// Hang onto the application id
				$.post(
					"get-prior-application.php",
					{
						file:	$("input#lastname-prior").val(),
						id:		$(button).attr('name'),		// application id
						ssn:	$("input#ssn-prior").val()
					},
					function(data, status) {
						if (data.type == 'expired') { alert(data.status); }
						if (data.status == 'success' || data.type =='expired') {
							var key, values;
							values = data.data;
							$("#prior-application-status").html("<b style='background-color: #0f0'>Loading your saved application data...</b>");
							// Reload each data value into form field of same name
							var fld;
							for (key in values) {
								if (values[key] != "") {
									fld = $("[name='"+key+"']");
									fld.addClass('modified normal').removeClass('dim');
									if (fld.attr('type') == 'checkbox') {
										fld.attr('checked',false);
										fld.click();
									}
									else {
										fld.val(values[key]);
										fld.change();
									}
								}
							}
							for (fld=1;fld<=3;fld++) showHideGeneral(fld);
							$("#dialog-open-prior").jqmHide();
						}
						else {
							appid = null;  // Discard the id since we failed to load the application
						}
						$("#prior-application-status").html(data.status);  // Display error message
					},
					'json'
				);
		}
		function resumeApplication() {
			var v2 = $("input#lastname-prior").val();
			var v3 = $("input#ssn-prior").val();
			if (v2 == '' || v3 == '') {
				$("#prior-application-status").text("Please enter Last Name and SSN.\n are required to retrieve your application(s).");
			}
			else {
				$.post(
					"get-prior-application.php",
					{
						lastname:	v2,
						ssn:		v3
					},
					function(data, status) {
						$("#prior-application-list").html(data.data);
						$("#prior-application-status").text(data.status);
					},
					'json'
				);
			}
		}
		function showHideGeneral(i) {
			$("div.general-information-"+i).show();
		}
		function updateExpenses(ck,a,b,c,d) {
			var checked = $(ck).attr('checked');
			var i = parseInt(tail($(ck).attr('name'),'-'));
			$("div."+a+"-payment-"+i,"div.expenses-"+i).toggle(checked);  // Show/hide section for clicked checkbox
			
			// Show hide expenses section if any checkbox
					$("input[name^='applicant-"+a+"-payment-"+i+"']").attr('checked') ||
					$("input[name^='applicant-"+b+"-payment-"+i+"']").attr('checked') ||
					$("input[name^='applicant-"+c+"-payment-"+i+"']").attr('checked') ||
					$("input[name^='applicant-"+d+"-payment-"+i+"']").attr('checked');
			$("div.expenses-"+i).toggle(
					$("input[name^='applicant-"+a+"-payment-"+i+"']").attr('checked') ||
					$("input[name^='applicant-"+b+"-payment-"+i+"']").attr('checked') ||
					$("input[name^='applicant-"+c+"-payment-"+i+"']").attr('checked') ||
					$("input[name^='applicant-"+d+"-payment-"+i+"']").attr('checked')
				);

		}
		function updateWages(ck,a) {
			var checked = $(ck).attr('checked');
			var i = parseInt(tail($(ck).attr('name'),'-'));
			if (a != 'none') {
				$("input[name='applicant-income-none-"+i+"']").attr('checked', false);
				if (checked) {
		//			$("div.income-"+i).show();
					showHideIncome(a,i, checked);
				}
				else {
		//			$("div.income-"+i).hide();
					showHideIncome(a,i);
				}
			}
			else {
				$("input[name^='applicant-income-wages-"+i+"']").attr('checked', false);
				$("input[name^='applicant-income-other-"+i+"']").attr('checked', false);
				$("div.wages-"+i).hide();
				$("div.other-"+i).hide();
				$("div.income-"+i).hide();
			}
		}
		function showHideIncome(name,i, checked) {
			if ($("input[name='applicant-income-wages-"+i+"']").attr('checked') || $("input[name='applicant-income-other-"+i+"']").attr('checked')) {
				$("div.income-"+i).show();
			}
			else {
				$("div.income-"+i).hide();
			}
			if (checked) {
				$("div."+name+"-"+i).show();
			}
			else {
				$("div."+name+"-"+i).hide();
			}
		}
		function tail(string,delim) {
			var temp = string.split(delim);
			return temp[temp.length-1];
		}
		function petcost() {
			var cost = 20 * (parseInt(dogs) + parseInt(cats));
			$('span#pet-cost').text(cost);
		}
		function showhide(el, condition) {
		// Show or hide an element
			if (condition)
				$(el).show();
			else
				$(el).hide();
				
		}
		function showmax(el, classname, index) {
		// Show repeating elements <= index, hide the rest
			var maxIndex = index-1;
			$(el+"[class^='"+classname+"']").each(
				function(i) {
					if (i <= maxIndex) { 
						$(this).show();
						$('div.sp-'+$(this).attr('class')).show();
					}
					else {
						$(this).hide();
						$('div.sp-'+$(this).attr('class')).hide();
					}
				}
			);
		}
		function showhideapplicants() {
			if ((applicants != 0) && (occupancy != "")) {
				showmax('div' ,'applicant-', applicants);
			}
		}
		function getAddress(action, id) {
			id = id.split('_')[1];
			if (action=='view') {
				window.open('/detail.php?id='+id,'list');
			}
			else {
			// Paste values into the application form
				var addr = addrs[id];
				$("input#id").val(id);
				$("span#street").text(addr.fullstreet);
				$("span#city").text(addr.city);
				$("span#state").text(addr.state);
				$("span#zip").text(addr.zip);
				$("span#price").text(addr.price);
				$("span#down").text(addr.down);
				$("span#monthly").text(addr.month);
				$("#dialog-change-address").jqmHide();
			}
		}
