var loadFinishLater = true;
var opMode = '';
var local_rs = '';
var p = '';
var u = '';
var hid = '';
var browserName=navigator.appName; 
var browserVer=parseInt(navigator.appVersion); 


//check the url for https, and use the secure version of the _cfscriptFinishLaterLocation app
if (document.URL.substring(0,5) == 'https'){
	var _cfscriptFinishLaterLocation_localRef = _cfscriptFinishLaterLocation_secure;
}else{
	var _cfscriptFinishLaterLocation_localRef = _cfscriptFinishLaterLocation;
}


	///////////////////////////////////////////////////////////////////////////
	
	function getPausedFormData()
	{
		
		showLoading('Requesting Saved Data from the Server','We are searching for previously saved form data.');
		DWREngine._errorHandler =  errorHandler;
		
		p = document.lfprompt_form.lfprompt_field_password.value;
		u = document.lfprompt_form.lfprompt_field_username.value;
		hid = getFormName().Hid.getValue();
		DWREngine._execute(_cfscriptFinishLaterLocation_localRef, null, 'getPausedFormData',u,p,hid,null, getPausedFormData_result);
	}
	
	function getPausedFormDataWDDX(itemid)
	{
		/*
		This method is very smilar to the above getPausedFormData, except that it will return a single records WDDX for
		immediate population whereas the method above returns a list of form data that is incomplete and needs completion
		*/
		closeMultipleResults();
		showLoading('Populating Form Data','Loading Previously Saved Data');
		DWREngine._errorHandler =  errorHandler;
		//the username,password and hid are all used from when set previously
		DWREngine._execute(_cfscriptFinishLaterLocation_localRef, null, 'getPausedFormData', u, p, hid, itemid, getPausedFormData_result);
	}
	
	
	function getPausedFormData_result(result)
	{
		
		local_rs = result;
		//hide the prompt window
		closePrompt();
		hideLoading();
		
		//loop over the data and check for the WDDXFLAG which means that only
		//one record exists and the wddx has been deserialized and returned ready to populate the form
		var wddxflagfound = false;
		//alert(result.length);
		for (var e=0; e < result.length; e++){
			for (var i in result[e]){
				//alert(result[e]['KEY'] + ' = ' + result[e]['VALUE']);
				if (result[e]['KEY'] == 'WDDXFLAG'){
					wddxflagfound = true;
					break;
				}
			}
		}
		
		if (wddxflagfound){
			
			//create the object to be used in the setfields method
			var tempStruct = new Object();
			for (var e=0; e < result.length; e++){
				tempStruct[result[e]['KEY']] = result[e]['VALUE'];
			}
			
			//add the username/password fields to the tempStruct to 
			//populate the finishlater_password and finishlater_user fields
			tempStruct.finishlater_password =  document.lfprompt_form.lfprompt_field_password.value;
			tempStruct.finishlater_username =  document.lfprompt_form.lfprompt_field_username.value;
			
			//call populate form
			populateForm(tempStruct);
			
		}else{
			//if there is more than one record returned, show the prompt for the user to select the entry
			// they want to use, otherwise, update the message shown in the loading bar and proceed with the form 
			// population routine. Also, show an error message if no results were located
			if (result.length == 0){
				showErrorMessageHandler();
			}else if (result.length > 1){
				showMultipleResults();
			}
		}
		
		
	}
	
	///////////////////////////////////////////////////////////////////////////
	// HELPER FUNCTIONS
	
	//helper function to return form name (for single or multipage forms)
	function getFormName(){
		return logiform;
		
	}
	
	function hideAllSelects(){
		// looping through all forms on the page
		 if (getInternetExplorerVersion() != -1 && getInternetExplorerVersion() <=  6){
			for (f = 0; f < document.forms.length; f++)
			{
				var elements = document.forms[f].elements;
				// looping through all elements on certain form
				for (e = 0; e < elements.length; e++)
				{
					
					if ((elements[e].type == "select-one" ||  elements[e].type == "select-multiple") && elements[e].name != 'mydata')
					{
						elements[e].style.display = 'none';
					}
				}
			}	
		 }
	}
	
	function showAllSelects(){
		// hide all form elements for IE 6 and lower 
		 if (getInternetExplorerVersion() != -1 && getInternetExplorerVersion() <=  6){
			for (f = 0; f < document.forms.length; f++)
			{
				var elements = document.forms[f].elements;
				for (e = 0; e < elements.length; e++)
				{
					if ((elements[e].type == "select-one" ||  elements[e].type == "select-multiple"))
					{
						elements[e].style.display = 'inline';
					}
				}
			}
			
		 }
	}
	
	function getInternetExplorerVersion()
		// Returns the version of Internet Explorer or a -1
		// (indicating the use of another browser).
		{
		  var rv = -1; // Return value assumes failure
		  if (navigator.appName == 'Microsoft Internet Explorer')
		  {
			var ua = navigator.userAgent;
			var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
			if (re.exec(ua) != null)
			  rv = parseFloat( RegExp.$1 );
		  }
		  return rv;
		}
		
		
	

	///////////////////////////////////////////////////////////////////////////
	
	function SaveFormData2WddxAndServer(){

		//convert the current form data to wddx and send it to the server for later retrieval
		wd		 = getFormName().serialize('formtype,fID,Hid,Eid,Eid2,lfbuild,requestmode');
		p 		 = document.lfprompt_form.lfprompt_field_password.value;
		u		 = document.lfprompt_form.lfprompt_field_username.value;
		hid 	 = getFormName().Hid.getValue();
		err		 = '';
		
		if (u == ''){
			err = err + 'You must enter a username.<BR>';
			title = 'Invalid Username';
		}
		if (p == ''){
			title =  (err.length != 0)?'Invalid Username and Password':title = 'Invalid Password';
			err = err +  'You must enter a password.<BR>'
		}else if( !p.length >= 6 || !p.match(/[0-9]+/) || !p.match(/[A-Z]+/)){
	    	title =  (err.length != 0)?'Invalid Username and Password':title = 'Invalid Password';
	    	err  = err + 'The password entered is not strong enough. Your password must have at least 6 characters, one number and one uppercase character';
	    }
	    
	    if (err != ''){
			showCommonError('<b>'+title+'</b><BR>'+err+'<BR><BR><A href="javascript:hideCommonError();showLFPrompt(\'save\');">Click here to continue</a>');

	    }else{
			showLoading('Saving Partial Data','Your Data is being saved for retrieval at a later date');
			// check the form for a value in finishlater_id and send that to the server aswell. This will be a valid ID if the
			// record has already been edited/saved and then retreived. In this case, we update the paused record, and also do
			// and update on the submit as opposed to inserting a new record
			var itemid = getFormName().finishlater_id.getValue();
			
			DWREngine._execute(_cfscriptFinishLaterLocation_localRef, null, 'saveFormData', u, p, hid, itemid, wd, SaveFormData2WddxAndServer_result);
		}
	
	}
			
	function SaveFormData2WddxAndServer_result(result){
		/*
		The result returned is the new ID for the temp record. The id is then set on the form in a hidden field
		and used to ensure 
		*/
		//alert(result);
		hideAll();
		
		
	
		
		if (result == -1){
			// username already in use
			showCommonError('<b>Username already in Use</b><BR>The username you entered is already in use. If you have previously saved data for this form using this username and password, please verify that the password is correct and  <A href="javascript:hideCommonError();showLFPrompt(\'save\');">try again.</a> or <A href="javascript:hideCommonError();closePrompt();">cancel</a>');
		
		}else if (result == -2){
			// username already in use
			showCommonError('<b>Username and Password can not be blank</b><BR> Please enter both a username and password. <A href="javascript:hideCommonError();showLFPrompt(\'save\');">Click here to try again.</a>');
		
		
		}else if (result >= 1){
			/*success, update the finishlaterFlag field on the form and submit the form. The form
			data is not recorded when this flag is present, but autoresponders and notifications ARE sent.
			this provides the user with the ability to show a message to the customer AND send them the URL
			where they can return and pick up where they left off. 
			*/

			
			getFormName().finishlater_id.setValue(result);
			getFormName().finishlater_username.setValue(u);
			getFormName().finishlater_password.setValue(p);
			/*submit the form.
			When the form is submitted, the record will be be recorded to the users table if logiform.recordpartialdata is
			true. In this case the externalRequestHandler
			will check for the UserOptstoFinishLater, and if it exists, it will record the record and then update the
			temp table with the new record_id using the [finishlater_id] field as a reference to find the temp record
			*/
			
			if (getFormName().recordPartialData.getValue() == 'true'){
				showLoading('Processing Additional Data','Please Wait...');	
				//update the finishlater flag so the external request handler knows this is a partial save
				getFormName().finishlaterflag.setValue('UserOptstoFinishLater');
				//submit the form regardless of the alerts/validation errors
				getFormName()._skipValidation = true;
				submitform();
			}
			else{
				
				//tell the user their data has been saved and that they may close the window or navigate away from
				// the form 
					showMsg('<b>Your Information has been saved</b><BR>You can now close this window and navigate away from this form. Later, you can use your selected username and password to retrieve and complete your submission.<BR><BR><A href="javascript:hideMsg();">Close Window</a>');
			
			}
			
		}
		
	}
	
	// populate the form with the WDDX data
	function populateForm(tempStruct){				
		// and populate the form by calling a method in the parent template
		// that has a method named finishlaterPopulate();
		finishlaterPopulate(tempStruct);
		
		//and set the finish later flag to complete. this flag is reset if the user saves
		// again
		getFormName().finishlaterflag.setValue('completed');
		
		hideAll();
	}
	
	function hideAll(){
		closeMultipleResults();
		hideCommonError()
		closePrompt();
		hideLoading();
		showAllSelects();
	}
	
	// Show error message, no forms found
	function showErrorMessageHandler(){
		showCommonError('<b>No Data Found</b><BR>There are no incomplete submissions pending for that username/password combination. <BR> <A href="javascript:hideCommonError();showLFPrompt(\'retreive\');">Click here to try again.</a> or <A href="javascript:hideCommonError();closePrompt();">start a new entry</a>');
	}
	
	function showCommonError(msg){
		document.getElementById("lfErrorResult_text").innerHTML = msg
		document.getElementById("lfErrorResult").style.visibility = "visible";
		document.getElementById("lfErrorResult").style.display = "inline";
		hideAllSelects();
	}
	
	function hideCommonError(){
		document.getElementById("lfErrorResult").style.visibility = "hidden";
		document.getElementById("lfErrorResult").style.display = "none";
		showAllSelects();
	}
	
	function showMsg(msg){
		document.getElementById("lfmessageResult_text").innerHTML = msg
		document.getElementById("lfmessageResult").style.visibility = "visible";
		document.getElementById("lfmessageResult").style.display = "inline";
		hideAllSelects();
	}
	function hideMsg(msg){
		document.getElementById("lfmessageResult").style.visibility = "hidden";
		document.getElementById("lfmessageResult").style.display = "none";
		showAllSelects();
	}
	
	
	function showLoading(headtext,bodytext){
		
		hideAllSelects();
		
		//set default text
		if (headtext == undefined || headtext == ''){
			headtext = 'Loading Data, please Wait...';
		}
		
		if (bodytext == undefined || bodytext == ''){
			bodytext = 'Communicating with Remote Service';
		}
		
		//update text
		document.getElementById("lfloading_head").innerHTML = headtext
		document.getElementById("lfloading_text").innerHTML = bodytext
		
		//show the window
		document.getElementById("lfloading_win").style.visibility = "visible";
		document.getElementById("lfloading_win").style.display = "inline";
	}
	
	function hideLoading(){
		
		showAllSelects();
		
		document.getElementById("lfloading_win").style.visibility = "hidden";
		document.getElementById("lfloading_win").style.display = "none";
	}
	
	// show the selection window for multiple results
	function showMultipleResults(){
		
		hideAllSelects();
		
		//show and populate the window to select from multiplestored results
		if (document.getElementById('mydata').options.length > 0){
		 	DWRUtil.removeAllOptions('mydata');
		 }

		DWRUtil.addOptions('mydata',local_rs,'ID','FORMATTEDFIELD')
		//show the layer
		document.getElementById("multipleResults").style.visibility = "visible";
		document.getElementById("multipleResults").style.display = "inline";
	}
	
	function closeMultipleResults(){
		
		showAllSelects();
		
		 if (document.getElementById('mydata').options.length > 0){
		 	DWRUtil.removeAllOptions('mydata');
		 }
		 document.getElementById("multipleResults").style.visibility = "hidden";
		 document.getElementById("multipleResults").style.display = "none";
	}
	
	function lfPromptButtonHandler(){
		// This function is called when ever the save or retrieve button is clicked and
		// routes to the correct function based on the opMode var
		
		if (opMode == 'fetch'){
				//get data
				getPausedFormData()
			} else{
				SaveFormData2WddxAndServer();
		}
	}
	
	function getScroll(){
	    var yScroll;
	
	    if (self.pageYOffset) {
	        yScroll = self.pageYOffset;
	    } else if (document.documentElement && document.documentElement.scrollTop){ 
	        yScroll = document.documentElement.scrollTop; 
	    } else if (document.body) {
	        yScroll = document.body.scrollTop;
	    }
	        return yScroll;
	}

	function setScroll(x, y){
	    window.scrollTo(x, y); 
	}
	  
	  
	function showLFPrompt(mode){
		
	 	y = getScroll();	
	   	setScroll(0,0)
	  
	  
	
	 	
		
		if (mode == 'retreive'){
			//set the title a button label to the text for retreive
			var newmsg = '<B>Load Saved Data</b><BR>Returning Users: Enter your username and password to resume where you left off.';
			newmsg = newmsg + ' <b>For new submissions, <A href="javascript:closePrompt();">click here</a> to begin</b><BR><BR>';
				
			document.getElementById("lfprompt_head").innerHTML = newmsg
			document.getElementById("lfprompt_button").value = 'Get Partial Responses';
			
			//update the opMode var which controls if we are fetching data or if we are saving data
			opMode = 'fetch';
			
			//open the prompt window
			openPrompt();
			
		}else if (mode == 'save'){
			
			// custom code for Hank Stroll to enforce validation before save/finish later
			var hid = getFormName().Hid.getValue();
			if (hid=='78542' || hid=='78916'){
				 
				if (!logiform.email.isNotEmpty()){
					alert('To continue, please enter your email address into the registration form, then click on "Save and Continue" button again.');
					return;
				}else if (!logiform.email.isEmail()){
					alert('To continue, please enter a valid email address, then click on "Save and Continue" button again.');
					return;
				}
				
			}
			// end custom code;
			
			var newmsg = '<BR><B>Save & Finish Later</b><BR>Enter a username and password that you can then use later to return and complete this form submission.';
				
			document.getElementById("lfprompt_head").innerHTML = newmsg
			//set the prompt window text and button label for saving data
			document.getElementById("lfprompt_button").value = 'Save & Finish Later'; 
			
			//update the opMode var which controls if we are fetching data or if we are saving data
			opMode = 'save';
			
			//open the prompt window
			openPrompt();
		}
	
	}
	
	//open the prompt
	function openPrompt(){
	 // centerPrompt();
	 hideAllSelects();
	 document.getElementById("lfprompt").style.visibility = "visible";
	 document.getElementById("lfprompt").style.display = "inline";
	}
	
	//hide the prompt
	function closePrompt(){
	 showAllSelects();	 
	 document.getElementById("lfprompt").style.visibility = "hidden";
	 document.getElementById("lfprompt").style.display = "none";
	}
	
	function finishLater_loadInitialPrompt(){
		showLFPrompt('retreive');
	}
	
	
	function initFinishLater()
	{
		//check for the loadFinishLater flag and if it is true, show the UserPass Prompt
		//to retrieve date from the server
		if (loadFinishLater){
			showLFPrompt('retreive');
		}
		
	}
	

	
	