String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } //trim func
var currentField = "";
var listen = null;
var o_or_n = "";
function unrecognizedUseAsIs(oForm){	
	if($('addr_useAsIs') && $('addr_useAsIs').value=="1"){
		if(o_or_n!=""&&o_or_n.toLowerCase()=="old"){			
			showUserTyped('cyaForm:oldCustomerUseAsTyped', 'cyaForm:oldCustomerUnRecognized');
		}else if(o_or_n.toLowerCase()=="new"){	
			showUserTyped('cyaForm:newCustomerUseAsTyped', 'cyaForm:newCustomerUnrecognized');
		}
	}
	Richfaces.hideModalPanel('unRecognizedAddressModal:panel');	
}

function initFields(){	
	var x=0;
	var addressInputs = document.getElementsByClassName('addressInput');	
	for(x=0 ; x < addressInputs.length; x++){		
		addressInputs[x].onfocus = function(){			
			currentField = this.id;			
		}
	}	
}

function checkAddress(){	
	var AddressObj = {
			Old:{Street:document.getElementById("cyaForm:oldStreet"),
				Apt:document.getElementById("cyaForm:oldAptNo"),
					City:document.getElementById("cyaForm:oldCity"),
						State:document.getElementById("cyaForm:oldState"),
							Zip:document.getElementById("cyaForm:oldZip")},
			New:{Street:document.getElementById("cyaForm:newStreet"),
				Apt:document.getElementById("cyaForm:newAptNo"),
					City:document.getElementById("cyaForm:newCity"),
						State:document.getElementById("cyaForm:newState"),
							Zip:document.getElementById("cyaForm:newZip")}}	
	
	if(IsIdenticalAddress(AddressObj)){		
		var oldNewTest = new RegExp("old");
		var oldNew = (oldNewTest.test(currentField))?"Old":"New";
		var input = AddressObj[oldNew];
		Richfaces.showModalPanel('sameAddressModal:panel', {height:'400', width:'550'});
  		document.getElementById("newOrOld").innerHTML = "The Old and New Mailing address cannot be the same address. Please update your "+oldNew+" address.";
  		input.Street.value="";
  		input.Apt.value="";
  		input.City.value="";
  		input.State.value="";
  		input.Zip.value="";
  		clearInterval(listen);
		listen = null;		
	}
	
}

function IsIdenticalAddress(AddressObj){	
	if(null!=AddressObj && AddressObj.Old.Street.value.trim()!=""&& AddressObj.New.Street.value.trim()!="" &&
			(AddressObj.Old.Street.value.trim().toUpperCase()== AddressObj.New.Street.value.trim().toUpperCase()) &&
			(AddressObj.Old.Apt.value.trim() == AddressObj.New.Apt.value.trim()) &&
			(AddressObj.Old.City.value.trim()!="" && AddressObj.Old.City.value.trim().toUpperCase() == AddressObj.New.City.value.trim().toUpperCase())&&
				(AddressObj.Old.State.value.trim()!="" && AddressObj.Old.State.value == AddressObj.New.State.value) && 
					(AddressObj.Old.Zip.value.trim()!="" && AddressObj.Old.Zip.value.substring(0,5).trim().toUpperCase()== AddressObj.New.Zip.value.substring(0,5).trim().toUpperCase())){
		return true;
	}
	return false;	
}

function validateAddress(id){
	var button = new RegExp("cyaForm+[:new||:old]+CheckAddressImg");
	var oldNewTest = new RegExp("old");
	var oldNew = (oldNewTest.test(id))?"Old":"New";	
	o_or_n = oldNew;
	var AddressObj = {Old:{Street:document.getElementById("cyaForm:oldStreet"),
							Apt:document.getElementById("cyaForm:oldAptNo"),
								City:document.getElementById("cyaForm:oldCity"),
									State:document.getElementById("cyaForm:oldState"),
										Zip:document.getElementById("cyaForm:oldZip")},
					  New:{Street:document.getElementById("cyaForm:newStreet"),
							Apt:document.getElementById("cyaForm:newAptNo"),
								City:document.getElementById("cyaForm:newCity"),
									State:document.getElementById("cyaForm:newState"),
										Zip:document.getElementById("cyaForm:newZip")}}	
	var input = AddressObj[oldNew];	
  	addressButton = document.getElementById(((oldNew=="Old")?"old":"new")+"CheckAddressButton");  		
  	
  	if(listen==null){
  		listen = setInterval("checkAddress()",1);	
  	}
  	
  	if(!IsIdenticalAddress(AddressObj) && input.Street.value.trim() != '' && input.City.value.trim() != '' &&
  			input.State.value != '' && input.State.value != '0' && input.Zip.value.trim() != '' && (addressButton.style.display=='none' || (addressButton.style.display=='' && button.test(id)))){  		
  		
  		if(oldNew=="Old"){
  			// hide all the other divs if they are shown
  			hideOldRecognized();hideOldUnRecognized();hideOldUseAsTyped();
  			// reset the old original div and show spinnner
  			showOldOriginalDiv();showOldSpinner();
  			// show Check Address Button
  			showOldUpdateAddressButton();
  			
  		// run validate on the backing bean  		
  	  		Seam.Component.getInstance("coaValidate").validateOldAddress(input.Street.value.trim(), input.Apt.value.trim(), 
  	  			input.City.value.trim(), input.State.value, input.Zip.value.trim(), validateOldAddressCallBack);
  		}else{
  			// hide all the other divs if they are shown
  			hideNewRecognized();hideNewUnRecognized();hideNewUseAsTyped();
  			// reset the old original div and show spinnner
  			showNewOriginalDiv();showNewSpinner();
  			// show Check Address Button
  			showNewUpdateAddressButton();  		
  			
  		// run validate on the backing bean  		
  	  		Seam.Component.getInstance("coaValidate").validateNewAddress(input.Street.value.trim(), input.Apt.value.trim(), 
  	  			input.City.value.trim(), input.State.value, input.Zip.value.trim(), validateNewAddressCallBack);  		
  		}
  		
  	}
}   
  
  function checkIfYourAddressIsCompletelyFilledIn(){
  	newOriginal = document.getElementById('cyaForm:newOriginal');
  	newUnRecognized = document.getElementById('cyaForm:newCustomerUnrecognized');
  	
  	oldOriginal = document.getElementById('cyaForm:oldOriginal');
  	oldUnRecognized = document.getElementById('cyaForm:oldCustomerUnRecognized');
  	
  	var complete = false;
  	
  	if(newOriginal.style.display=='none' && newUnRecognized.style.display=='none' 
  		&& oldOriginal.style.display=='none' && oldUnRecognized.style.display=='none'){
  		complete = true;
  	}
  	
  	return complete;
  	
  }
  
  /**
   * 
   * RECOGNIZED ADDRESS section
   * 
   */
   
   function setRecognizedOldAddressOnForm(){
   		Seam.Component.getInstance("coaValidate").getNormalizedOldAddress(addressOldSetCallBack);
   		showOldRecognized();
   }
   
   function setRecognizedNewAddressOnForm(){
   		Seam.Component.getInstance("coaValidate").getNormalizedNewAddress(addressNewSetCallBack);
   		showNewRecognized();
   }
   
   
   /**
    * 
    * END RECOGNIZED ADRESS
    * 
    */
 
  /**
   * MODAL java script section
   */
  
  function selectOldAddressModal(element){
  	if(element.value == '0'){
  		showUserTyped('cyaForm:oldCustomerUseAsTyped', 'cyaForm:oldCustomerUnRecognized');
  	}else{
  		// save the address into the customer old physical address
  		// set the value of the old address on the page to the recognized address
  		Seam.Component.getInstance("coaValidate").setAddressSelectedOnModal(element.value, true, addressOldSetCallBack);
  		
  	}
  	
  	// reset clicked state of element
  	element.checked=false;
  }
 
  /**
   * called from new Address Normalization model
   * gets the selected value from the radio button and sends to the backing bean
   */
  function selectNewAddressModal(element){
  	if(element.value == '0'){
  		showUserTyped('cyaForm:newCustomerUseAsTyped', 'cyaForm:newCustomerUnrecognized');
  	}else{
  		// set the value on the backing bean to match the value selected from the modal
  		Seam.Component.getInstance("coaValidate").setAddressSelectedOnModal(element.value, false, addressNewSetCallBack);
  		
  	}
  	
  	// reset clicked state of element
  	element.checked=false;
  }
  
  /**
   * callback function for selectOldAddress modal
   * 
   * sets the address on the front page to the same address
   * string which is passed into this function
   */
    function addressOldSetCallBack(result){
  	
  	var streetAddr1 = getElement(result);
  	result = nextElementInAddressString(result);
  	var aptNo = getElement(result)
  	result = nextElementInAddressString(result);  	
  	var city = getElement(result);
  	result = nextElementInAddressString(result);
  	var state = getElement(result);
  	result = nextElementInAddressString(result);
  	var zip = getElement(result);
  	
  	
  		oldStreet = document.getElementById("cyaForm:oldStreet");
 	  	oldStreet.value=streetAddr1;
 	  	// set old apt no on the page
 	  	oldAptNo = document.getElementById("cyaForm:oldAptNo");
 	  	oldAptNo.value=aptNo;
 
 	  	oldCity = document.getElementById("cyaForm:oldCity");
 	  	oldCity.value=city;
 	  	document.getElementById("cyaForm:oldState").disabled=false;
 	  	
 	  	oldZip = document.getElementById("cyaForm:oldZip");
 	  	oldZip.value=zip;
  	showOldRecognized();
  	
  }
  
   /**
   * callback function for selectNewAddress modal
   * 
   * sets the New address on the page to the same address
   * string which is passed into this function
   */
  function addressNewSetCallBack(result){
  	
  	var streetAddr1 = getElement(result);
  	result = nextElementInAddressString(result);
  	var aptNo = getElement(result)
  	result = nextElementInAddressString(result);  	
  	var city = getElement(result);
  	result = nextElementInAddressString(result);
  	var state = getElement(result);
  	result = nextElementInAddressString(result);
  	var zip = getElement(result);
  	
  		newstreet = document.getElementById("cyaForm:newStreet");
 	  	newstreet.value=streetAddr1;
 
 	  	newaptNo = document.getElementById("cyaForm:newAptNo");
 	  	newaptNo.value=aptNo;
 
	  	newcity = document.getElementById("cyaForm:newCity");
 	  	newcity.value=city;
 	  	document.getElementById("cyaForm:newState").disabled=false;
 	  	
 	  	newzip = document.getElementById("cyaForm:newZip");
 	  	newzip.value=zip;
 	  	
 	// after setting value show the div for recognized
  	showNewRecognized();
  	
  }
  
  /**
   * helper functions
   */
  function getElement(address){
  	return address.substring(0, address.indexOf(':'));
  }
  
  function nextElementInAddressString(address){
  	return address.substring(address.indexOf(':')+1, address.length);
  } 
  
  /*
   * END MODAL javascript section
   */
  
  /** YOUR INFO VALIDITY **/
  
  var emailverify = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
  
  var textverify = /^[a-zA-Z]/g;
  
  var middleInitialVerify = /[a-zA-Z]/g;
  
  var phone1verify = /[0-9]{3}/;
  var phone2verify = /[0-9]{3}/;
  var phone3verify = /[0-9]{4}/;
  
  	  
  	  
  	  /**
  	   * changes the your info div
  	   * to the checked state
  	   */
  	  function changeYourInfoToChecked(){
  	  	document.getElementById("cyaForm:yourInfoUnChecked").className="your_info_checked div_inside";
  	  }
  	  
  	  /**
  	   * change the your info
  	   * to unchecked state
  	   */
  	  function changeYourInfoToUnChecked(){
  	  	document.getElementById("cyaForm:yourInfoUnChecked").className="your_info_number div_inside";
  	  }
 	  
 	  /**
 	   * change the your address div
 	   * to have a checkmark at the top
 	   */
 	  function changeYourAddressToCheck(){
 	  	document.getElementById("cyaForm:yourAddressInactive").className="your_address_checked div_inside";
 	  }
 	  
 	  function changeYourAddressToUnCheck(){
 	  	document.getElementById("cyaForm:yourAddressInactive").className="your_address_number div_inside";
 	  }
 	  
 	  
	 function changeYourMoveToChecked(){
	 	var yourMoveDiv = document.getElementById("cyaForm:yourMoveDiv");
	 	yourMoveDiv.className = "your_move_checked div_inside";
	 }
	 
	 function changeYourMoveToUnChecked(){
	 	var yourMoveDiv = document.getElementById("cyaForm:yourMoveDiv");
	 	yourMoveDiv.className = "your_move_number div_inside";
	 }
	 
	 function changeYourApprovalToChecked(){
	 	document.getElementById("cyaForm:yourApproval").className="your_approval_checked div_inside";
	 }
	 
	 function changeYourApprovalToUnChecked(){
	 	document.getElementById("cyaForm:yourApproval").className="your_approval_number div_inside";
	 }
 
 
  	  /** 
  	   * takes in the name of the element it should show when there is an error
  	   * the actual element input it is checking
  	   * the regular expression it should check against
  	  **/
  	  function checkValidity(elementName, element, regexpression){
  	  	var valid = checkRegEx(element, regexpression); 
  	  	if(element.value==''){
	  	  	Effect.Fade(elementName);
  	  	}else{
  	  		if(valid){
	  	  		Effect.Fade(elementName);
	  	  	}else{
		  		Effect.Appear(elementName);
		  	}
  	  	}
	  }
	  
	  /**
	   * checked if the passed in element passes regex check
	  **/
	  function checkRegEx(element, regexpression){
	  	//var nameregex = new RegExp(regexpression);
	  	var regex;
	  	if(regexpression == 'email'){
	  		regex = emailverify;
	  	}else if(regexpression == 'text'){
	  		regex = textverify;
	  	}else if(regexpression == 'middleInitialVerify'){
	  		regex = middleInitialVerify;
	  	}else if(regexpression == 'phone1'){
	  		regex = phone1verify;
	  	}else if(regexpression == 'phone2'){
	  		regex = phone2verify;
	  	}else if(regexpression == 'phone3'){
	  		regex = phone3verify;
	  	}
  	  	var valid = regex.test(element.value);  	
	  	return valid;
	  }
  
  
    
  // hide Modal for address selection
  function showUserTyped(usedAsTypedId, unrecognizedId) {
  	unRec = document.getElementById(unrecognizedId);
  	unRec.style.display = "none";
  	Effect.Appear(usedAsTypedId);
  	saveUseAsTypedAddressIntoBean(usedAsTypedId);
  	// check page Completeness after use as typed has been set
  	setTimeout("checkPageCompleteness()", 1000);
  }
  
  function usedTypedCallBack(result){
	// do nothing
  }
  
  function saveUseAsTypedAddressIntoBean(useAsTypedId){
  	
  	if(useAsTypedId == 'cyaForm:oldCustomerUseAsTyped'){
  		streetInput = document.getElementById("cyaForm:"+"old"+"Street");
  		aptInput = document.getElementById("cyaForm:"+"old"+"AptNo");
  		cityInput = document.getElementById("cyaForm:"+"old"+"City");
  		stateInput = document.getElementById("cyaForm:"+"old"+"State");
  		zipInput = document.getElementById("cyaForm:"+"old"+"Zip");
  		
  		Seam.Component.getInstance("coaValidate").saveUseAsTypeAddressOld(streetInput.value, aptInput.value, 
  				cityInput.value, stateInput.value, zipInput.value, usedTypedCallBack);
  		
  	}else{
  		streetInput = document.getElementById("cyaForm:"+"new"+"Street");
  		aptInput = document.getElementById("cyaForm:"+"new"+"AptNo");
  		cityInput = document.getElementById("cyaForm:"+"new"+"City");
  		stateInput = document.getElementById("cyaForm:"+"new"+"State");
  		zipInput = document.getElementById("cyaForm:"+"new"+"Zip");
  		
  		Seam.Component.getInstance("coaValidate").saveUseAsTypeAddressNew(streetInput.value, aptInput.value, 
  				cityInput.value, stateInput.value, zipInput.value, usedTypedCallBack);
  	}
  	
  }
  
  
  
    //===========  Old Unchecked/Original =============
  
  
  function validateOldAddressCallBack(result){    
	o_or_n = 'old';
  	hideOldSpinner();
  	if(result == 'invalid'){
  		showOldUnRecognized();
  		Richfaces.showModalPanel('oldAddressNormalizationModal:panel', {height:'450', width:'550',oldNew:'old'});
  		Seam.Component.getInstance("coaValidate").getAddressesForDisplay(true, getOldAddressDisplayCallback);
  	}else if(result == 'valid'){
  	    setRecognizedOldAddressOnForm();	
  	}else if(result == 'none'){
  	  	showOldUnRecognized();
  	  	Richfaces.showModalPanel('unRecognizedAddressModal:panel', {height:'450', width:'550',oldNew:'old'},{oldNew:'old'});
  	  	
  	}
  	checkPageCompleteness();
  }
  
  function getOldAddressDisplayCallback(result) {
  	var htmlString = "<table>";
  	var addressv = null,addressv=null,addressValue=null;
 	for (i=0;i<result.length;i++) {
  		addressv = result[i];
  		addressKey = addressv.substring(0, addressv.indexOf('$'));
  		addressValue = addressv.substring(addressv.indexOf('$')+1, addressv.length);
  		htmlString += "<tr><td><input type='radio' onclick=\"selectOldAddressModal(this);javascript:Richfaces.hideModalPanel('oldAddressNormalizationModal:panel');\" value='"+addressKey+"'></input>"+addressValue+"</td></tr>";
  	}
  	htmlString += "</table>";
  	
  	var oldAddressDiv = document.getElementById("oldAddressNormalizationModal:oldAddressList");
  	oldAddressDiv.innerHTML = htmlString;
  	
  	result = null;
  	htmlString = null;
  }
  
  function showOldUpdateAddressButton() {
  	button = document.getElementById("oldCheckAddressButton");
  	button.style.display="";  
  }
  
  function showOldSpinner(){
  	Effect.Appear("cyaForm:oldSpinner");
  }
  
  function hideOldSpinner(){
  	spin = document.getElementById("cyaForm:oldSpinner");
  	spin.style.display="none";
  }
  
  // show the old recognized div
  // hides all other competing divs
  function showOldRecognized(){
  	hideOldOriginalDiv();
  	hideOldUnRecognized();
  	Effect.Appear("cyaForm:oldCustomerRecognized");
  	setTimeout("checkPageCompleteness()", 1000);
  }
  
  // show the old un recognized div
  // hides all other competing divs
  function showOldUnRecognized(){
  	hideOldOriginalDiv();
  	hideOldRecognized();
  	Effect.Appear("cyaForm:oldCustomerUnRecognized");
  }
  
  // hide oldOriginalDiv
  function hideOldOriginalDiv(){
  	oldDiv = document.getElementById("cyaForm:oldOriginal");
  	if(oldDiv){
  		oldDiv.style.display="none";
  	}
  }
  
  // show oldOriginalDiv
  function showOldOriginalDiv(){
  	oldDiv = document.getElementById("cyaForm:oldOriginal");
  	if(oldDiv){
  		oldDiv.style.display="";
  	}
  }
  
  
  // hide the old recognized div
  function hideOldRecognized(){
  	oldRec = document.getElementById("cyaForm:oldCustomerRecognized");
  	if(oldRec){
  		oldRec.style.display = "none";	
  	}
  	
  }
  
  
  // hide old Un recognized
   function hideOldUnRecognized(){
  	oldUnRec = document.getElementById("cyaForm:oldCustomerUnRecognized");
  	if(oldUnRec){
  		oldUnRec.style.display = "none";
  	}
  }
  
  // hide old Used as typed
   function hideOldUseAsTyped(){
  	oldUnRec = document.getElementById("cyaForm:oldCustomerUseAsTyped");
  	if(oldUnRec){
  		oldUnRec.style.display = "none";
  	}
  }
  
  //===========  New Unchecked/Original =============
 
 function validateNewAddressCallBack(result){
	o_or_n = 'new';
  	hideNewSpinner();
  	if(result == 'invalid'){
  		showNewUnRecognized();
   		Richfaces.showModalPanel('newAddressNormalizationModal:panel', {height:'450', width:'550',oldNew:'new'});
  		Seam.Component.getInstance("coaValidate").getAddressesForDisplay(false, getNewAddressDisplayCallback);
  	}else if(result == 'valid'){
  		setRecognizedNewAddressOnForm()
  	}else if(result == 'none') {
  	  	showNewUnRecognized();
  	  	Richfaces.showModalPanel('unRecognizedAddressModal:panel', {height:'450', width:'550',oldNew:'new'});  	
  	}  	
  	
  }
  
  function getNewAddressDisplayCallback(result) {
  	var htmlString = "<table>";
	var addressv = null,addressv=null,addressValue=null;
 	for (i=0;i<result.length;i++) {
  		addressv = result[i];
  		addressKey = addressv.substring(0, addressv.indexOf('$'));
  		addressValue = addressv.substring(addressv.indexOf('$')+1, addressv.length);
  		htmlString += "<tr><td><input type='radio' onclick=\"selectNewAddressModal(this);javascript:Richfaces.hideModalPanel('newAddressNormalizationModal:panel');\" value='"+addressKey+"'></input>"+addressValue+"</td></tr>";
  	}
  	htmlString += "</table>";
  	
  	var newAddressDiv = document.getElementById("newAddressNormalizationModal:newAddressList");
  	newAddressDiv.innerHTML = htmlString;
  	
  	result = null;
  	htmlString = null;
  }
  
  function showNewUpdateAddressButton() {
  	button = document.getElementById("newCheckAddressButton");
  	button.style.display="";  
  }
  
 function showNewSpinner(){
  	Effect.Appear("cyaForm:newSpinner");
  }
  
  function hideNewSpinner(){
  	spin = document.getElementById("cyaForm:newSpinner");
  	spin.style.display="none";
  }
  
  // show the new recognized div
  // hides all other competing divs
  function showNewRecognized(){
  	hideNewOriginalDiv();
  	hideNewUnRecognized();
  	Effect.Appear("cyaForm:newCustomerRecognized");
  	// show check if recognized and other div has use as typed
  	// or recognized
  	
  	// check page completeness - by now the recognized modal should
  	// be set
  	setTimeout("checkPageCompleteness()", 1000);
  }
  
  // show the new un recognized div
  // hides all other competing divs
  function showNewUnRecognized(){
  	hideNewOriginalDiv();
  	hideNewRecognized();
  	Effect.Appear("cyaForm:newCustomerUnrecognized");
  }
  
  
    // hide newOriginalDiv
  function hideNewOriginalDiv(){
  	oldDiv = document.getElementById("cyaForm:newOriginal");
  	if(oldDiv){
  		oldDiv.style.display="none";
  	}
  }
  
   // hide newOriginalDiv
  function showNewOriginalDiv(){
  	oldDiv = document.getElementById("cyaForm:newOriginal");
  	if(oldDiv){
  		oldDiv.style.display="";
  	}
  }
  
  
  // hide the new recognized div
  function hideNewRecognized(){
  	oldRec = document.getElementById("cyaForm:newCustomerRecognized");
  	if(oldRec){
  		oldRec.style.display = "none";	
  	}
  	
  }
  
   // hide New Used as typed
   function hideNewUseAsTyped(){
  	oldUnRec = document.getElementById("cyaForm:newCustomerUseAsTyped");
  	if(oldUnRec){
  		oldUnRec.style.display = "none";
  	}
  }
  
  // hide new Un recognized
   function hideNewUnRecognized(){
  	oldUnRec = document.getElementById("cyaForm:newCustomerUnrecognized");
  	if(oldUnRec){
  		oldUnRec.style.display = "none";
  	}
  }
  
  function showMoveEndDate(element){
  	if(element.value=='1'){
  		document.getElementById('moveEndDate').style.display='';
  	}else{
  		document.getElementById('moveEndDate').style.display='none';
  	}
  }
  
  function openMoveType(element){
  	if(element.checked){
  		document.getElementById("moveType").style.display='';
  	}else{
  		document.getElementById("moveType").style.display='none';	
  	}
  }
  
  /**
   * submits the form
   */
  function submitForm(){
  	document.forms["cyaForm"].submit();
  }
  
  /**
 * change continue button
 * on your approval column
 * from gray button to active
 * blue button
 */
 function changeContinueFromGrayToBlue(){
	document.getElementById("greyContinueButton").style.display="none";
	document.getElementById("blueContinueButton").style.display="";
 }
 
 function redirectToConfirmationPage(result){
 	window.location='confirmation.seam';
 }
 
 function submitConsumer(){
 	Seam.Component.getInstance("coaValidate").saveConsumer(redirectToConfirmationPage);
 }  