
document.observe("dom:loaded", function() {
					
	if (currentURL) {

		if (currentURL.length > 0) {
			var launchString = location.search.substring(1, location.search.length);
			var launchStringArray = launchString.split("&");
			for (var i = 0; i <= launchStringArray.length - 1; i++) {
				var left = launchStringArray[i].substring(0, launchStringArray[i].indexOf("="));
				var right = launchStringArray[i].substring(launchStringArray[i].indexOf("=") + 1, launchString.length);
				if (left == "login") {
					login = right ;
				}
			}
		} 				
		
    if (login == "start") {
			// Make ajax call to read the user/pass from session
			currentURL = document.location.href ;
			getCredentials() ;
		}
	}			
	
	// Capture enter key
	if ($('login_password')) {
		$('login_password').observe('keypress', function (event) {
			if (event.keyCode == Event.KEY_RETURN) {
				handleLogin() ;	
				Event.stop(event) ;
			}
			
			//Event.stop(event) ;
		
		}) ;
	}		

});


function getCredentials() {
	if ($('redirect')) {
		$('redirect').setValue('true') ;
	}
	$('currentURL').setValue(currentURL) ;
	new Ajax.Request(pollURL, {
	  parameters: $('loginForm').serialize(true),
	  method: 'post',
	  onSuccess: function(transport) {
		// Cookie should be set by now
		var user = "" ;
		var pass = "" ;
		try {
			user = transport.responseXML.getElementsByTagName("username")[0].childNodes[0].nodeValue ;
  			pass = transport.responseXML.getElementsByTagName("password")[0].childNodes[0].nodeValue ;
		} catch(err) {
			user = "" ;
			pass = "" ;
		}

		
		$('login_name').setValue(user) ;
		$('login_password').setValue(pass) ;
		$('redirect').setValue('') ;
		$('currentURL').setValue(currentURL) ;
					
		handleLogin() ;			  
	  },
	  onFailure: function(transport) {
	  	//alert("Failed to get credentials") ;
		cleanup() ;
	  },
	  onException: function(request, exception) {
	  	//alert("Exception to get credentials") ;
		cleanup() ;
	  }
	});
}
/**
* Check if the current URL is HTTP or HTTPS
* If HTTP - Send redirect to HTTPS version
* If HTTPS - Handle login
*/

function handleLogin() {

	if (isSecure(currentURL)) {
		$('currentURL').setValue(currentURL) ;
		performLogin() ;
	} else {
		makeURLSecure() ;
		$('currentURL').setValue(currentURL) ;
		$('redirect').setValue('false') ;
		$('loginForm').action = pollURL ;
		$('loginForm').submit() ;
	}
}

function isSecure(url) {

	if (env == "local") {
		return true ;
	}
	url = url.toLowerCase() ;
	if (url.indexOf("https:") != -1) {
		return true ;
	} else {
		return false;
	} 
}

function makeURLSecure() {
		if (env == "local") {
			return ;
		} else {
			// Change from http to https
			if (currentURL.indexOf(httpHost) != -1) {
				currentURL = currentURL.replace(httpHost,httpsHost) ;
			} else if (currentURL.indexOf(httpHostVar1) != -1) {
				currentURL = currentURL.replace(httpHostVar1,httpsHost) ;
			} else {
				// Attempt to just change protocol
				currentURL = currentURL.replace("http:","https:") ;
			}
		}
}

/** 
 *	Handles the asynchronous login request.
*/
function performLogin() {

	// Check if loginMethod has been set
	// If method is "sync" - submit form
	// If method is "async" - Send Ajax requests to siteminder, posting request and response polling
	if (loginMethod) {
		if (loginMethod == "sync") {
			$('loginForm').submit();
		} else if (loginMethod == "async") {

		
			// If production call siteminder
			if (env == "local") {
				loginPrecheck() ;
				//return ;
			} else {
				callSiteminder() ;
			}
		}
	}

}

function loginPrecheck() {

	//var precheckUrl = '/Owners/mytoyota/login_check_async.do' ;
	// Reset loginRequestID if requestID is empty
	if (requestID == "") {
		$('loginRequestID').setValue('') ;
	}
	$('currentURL').setValue(currentURL) ;
	//alert('Posting request') ;
	
	new Ajax.Request(actionURL, {
	  parameters: $('loginForm').serialize(true),
	  method: 'post',
	  onSuccess: function(transport) {
	  
	  	// Fetch response from transport object
		// This method fetches requestID, status, error and forward URL.
		getResponse(transport) ;
	  	// Get request status & request id
	  	if (status == "REQUEST_SENT") {
	  		// Request sent successfully - You can start polling
		  	//Set requestID received in loginRequestID
		  	$('loginRequestID').setValue(requestID);
			modal = "shown" ;
			Modalbox.show('<div id=\'loading\' style=\'display:visible\'></div>',
								{title:"", width: 300, height:600, border:0, transitions:false});
		  	startPoll();
		  	// Timeout after speicified no. of secs
		  	timeOutID = window.setTimeout("timeoutPoll()", loginTimeout) ;

	  	} else if (status == "REQUEST_ERROR"){
	  		// Check error message and forward URL. Errors to be shown
	  		// on target page have to be saved in session so that the html:errors tag picks it up.
	  		// Process error if no forward required.
	  		if (isForward()) {
		  		forward() ;
		  	} else {
		  		processErrors() ;
			}
	  	}
	  },
	  onFailure: function(transport) {
	  	//alert("Failed precheck") ;
	  	cleanup() ;
	  },
	  onException: function(request, exception) {
	  	//alert("Exception during precheck call:"+exception) ;
	  	cleanup() ;
	  }
	});
	
}

// This method calls siteminder URL asynchronously

function callSiteminder() {

	//$('login_name').setValue($F('userName'));
	$('currentURL').setValue(currentURL) ;
	new Ajax.Request(actionURL, {
	  parameters: $('loginForm').serialize(true),
	  method: 'post',
	  onSuccess: function(transport) {
		
		if (transport.responseXML != null) {
			// Check if it has status
			try {
				// Get response
				getResponse(transport) ;
			} catch(err) {
				//alert('Siteminder Login failed. XML Parsing Error: ' + errorCount);

				errorCount++;
				if (errorCount < 4) {
					error = "You have entered an invalid username and/or password." ;
				} else {
					error = "Sorry, we could not validate your login information. If you wish to contact Lexus, please call 1-800-25-LEXUS.";
				}
				status = "REQUEST_ERROR" ;
				forwardURL = "DO_NOT_FORWARD" ;
			}
		} else if (transport.responseXML == null) {
			//alert('Siteminder Login failed. No XML Response: ' + errorCount);

			// Siteminder has redirected
			status = "REQUEST_ERROR" ;
			errorCount++;
			if (errorCount < 4) {
				error = "You have entered an invalid username and/or password." ;
			} else {
				error = "Sorry, we could not validate your login information. If you wish to contact Lexus, please call 1-800-25-LEXUS.";
			}
			forwardURL = "DO_NOT_FORWARD" ;
		} 

		// Get request status & request id
		if (status == "REQUEST_SENT") {
			// Request sent successfully - You can start polling
			//Set requestID received in loginRequestID
			$('loginRequestID').setValue(requestID);
			modal = "shown" ;
			Modalbox.show('<div id=\'loading\' style=\'display:visible\'></div>',
								{title:"", width: 300, height:600, border:0, transitions:false});

			startPoll();
			// Timeout after speicified no. of secs
			timeOutID = window.setTimeout("timeoutPoll()", loginTimeout) ;

		} else if (status == "REQUEST_ERROR"){
			// Check error message and forward URL. Errors to be shown
			// on target page have to be saved in session so that the html:errors tag picks it up.
			// Process error if no forward required.
			if (isForward()) {
				forward() ;
			} else {
				processErrors() ;
				return ;
			}
		}
	  },
	  onFailure: function(transport) {
		forwardURL = "/lexusdrivers/registration/processLogin.do?error=true" ;
		
		//alert('Ajax.Request onFailure()');

		if (isForward()) {
			forward() ;
			cleanup() ;
		} else {
			processErrors() ;
			cleanup() ;
			return ;
		}
	  	
	  },
	  onException: function(request, exception) {
		//alert(exception) ;
		//forwardURL = "/lexusdrivers/registration/processLogin.do?error=true" ;
		if (isForward()) {
			forward() ;
			cleanup() ;
		} else {
			processErrors() ;
			cleanup() ;
			return ;
		}
	  	cleanup() ;
	  }
	});

}

// Fetch the response from the transport
function getResponse(transport) {
  	status = transport.responseXML.getElementsByTagName("status")[0].childNodes[0].nodeValue ;
  	requestID = transport.responseXML.getElementsByTagName("request-id")[0].childNodes[0].nodeValue ;
 	error = transport.responseXML.getElementsByTagName("error-message")[0].childNodes[0].nodeValue ;
 	forwardURL = transport.responseXML.getElementsByTagName("forward-url")[0].childNodes[0].nodeValue ;
}

function processErrors() {
	//alert("Adding error: " + error);

	// Stop polling
	if (pollHandle) {
		pollHandle.stop() ;
	}

	// clear existing errors
	$('errors').update('').hide();
	var errors = [];

	errors.push(error);

	if (errors.length > 0) {
		$A(errors).each(function(error) {
			$('errors').insert('<li>' + error + '</li>').show();
			
			// Calling Omniture to capture login errors
			omnitureLoginErrorEvent(error);
		});
	}
	
	// Show login box
	showLoginBox() ;
	// Cleanup variables
	cleanup() ;

}

// Decide whether to forward or not based on forwardURL
function isForward() {

	if (forwardURL != "" && forwardURL != "DO_NOT_FORWARD") {
		return true ;
	} else {
		return false ;
	}
}

// Forward to the url specified
function forward() {
	// If login status is RESPONSE_RECEIVED
	// MAKE THE URL SECURE IF ITS NOT ALREADY SECURE
	if (status == "RESPONSE_RECEIVED") {
		//alert("ForwardURL before secure: "+forwardURL) ;
		// For local dont do anything
		if (env != "local") {
			// Change from http to https
			if (forwardURL.indexOf(httpHost) != -1) {
				forwardURL = forwardURL.replace(httpHost,httpsHost) ;
			} else if (forwardURL.indexOf(httpHostVar1) != -1) {
				forwardURL = forwardURL.replace(httpHostVar1,httpsHost) ;
			} else {
				// Attempt to just change protocol
				forwardURL = forwardURL.replace("http:","https:") ;
			}
		}	
		//alert("ForwardURL after secure: "+forwardURL) ;
	}
	
	if (forwardURL.indexOf("/lexusdrivers/magazine/content.do") != -1) {
		document.location.reload(true);
	} else {
		window.location.href = forwardURL ;
		cleanup() ;
	}
}

/** Start Polling for response
*	Poll for response every 3 seconds
*   Once the response is success, forward the URl to new location
*	Else keep polling till timeout is invoked
**/
function startPoll() {
	// Setup Periodical poll
		//alert("Polling URL: "+pollURL) ;
	$('currentURL').setValue(currentURL) ;
       pollHandle = new Ajax.PeriodicalUpdater('loginResponse', pollURL, {
            parameters: $('loginForm').serialize(true),
            method: 'post',
            frequency: 2,
            decay: 1,
			onSuccess: function(transport) {
				// Hide the div contents
				$('loginResponse').update('').hide();
				getResponse(transport) ;
				//alert(status) ;
			  	// Get request status & request id
			  	if (status == "RESPONSE_RECEIVED") {
					// Login Successful - Calling Omniture
					omnitureLoginSuccessEvent();
					
					// Stop polling and forward
					pollHandle.stop() ;
			  		if (isForward()) {
						forward() ;
					}
					return ;
			  	} else if (status == "RESPONSE_NOT_AVAILABLE"){
			  		// Still need to poll
			  		return ;
			  	} else if (status == "RESPONSE_ERROR") {
			  		// Process errors
			  		if (isForward()) {
				  		forward();
				  	} else {
              logoutOfSiteMinder();
					  	Modalbox.hide() ;
				  		processErrors() ;
						cleanup() ;
				  	}
			  		return ;
			  	}

			},
		  onFailure: function(transport) {
		  	//alert("Failed polling") ;
		  	cleanup() ;
		  },
		  onException: function(request, exception) {
		  	//alert("Exception during poll call:"+exception) ;
		  	cleanup() ;
		  }
	});
       
}

// This method is called when the timeout occurs.
// Stop polling and process any error messages along with cleanup
function timeoutPoll() {


	// Stop polling
	if (pollHandle) {
		pollHandle.stop() ;
	}

	forwardURL = pollURL+"?timeout=true" ;
	if (isForward()) {
		forward() ;
		cleanup() ;
	} else {
		processErrors() ;
		cleanup() ;
		return ;
	}

}

// Checks if the Login button has been clicked more than once
function isDoubleSubmission() {
	//alert("Login Clicked") ;
	if (requestID != "") {
		//alert("Login already in process. Please wait") ;
		return true ;
	} else {
		return false ;
	}

}

// Cleanup variables
function cleanup() {
	//Reset variables
	// To reset request id, the session needs to be recreated in the next call
	requestID = "" ;
	$('loginRequestID').setValue('') ;
	error = "" ;
	status = "" ;
	forwardURL = "" ;
	$('redirect').setValue('') ;
	/* Commented out hide model box so that page does not jump when redirecting.
	if (modal == "shown") {								
		Modalbox.hide();
	}
	*/
	window.clearTimeout(timeOutID) ;

}



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function showLoginBox() {
	if (currentURL) {
		if ((currentURL.indexOf("/my-lexus/") != -1)  ||
			(currentURL.indexOf("benefits") != -1) ||
			(currentURL.indexOf("registration") != -1)) {
				if ($('loginnav_drop').visible()) {
					return ; 
				} else {
					Effect.toggle('loginnav_drop', 'slide');
				}
			}
	}
}

function omnitureLoginErrorEvent(errorString) {
	s.events = 'event15';
	s.prop40 = s.eVar6 = s.pageName;
	s.prop41 = errorString;
	s.t();
}

function omnitureLoginSuccessEvent() {
	s.events = 'event55';
	s.linkTrackEvents = 'event55';
	s.linkTrackVars = 'events';
	s.tl(this, 'o', 'Login - Success');
}

function logoutOfSiteMinder() {
	new Ajax.Request('/lexusdrivers/info/logout.do', {
		onSuccess: function() {
			// let SiteMinder invalidate cookie and do nothing else
		}
	});
}