var isMinIE4 = (document.all) ? 1 : 0;
var isDOM = (document.getElementById) ? 1 : 0;
var usernameHintText = "User Name";
var passwordHintText = "Password";
var useAlternateSignIn = false;

/** Get elements from the document by ID **/
function get(elementName) {
	if (isDOM == 1) {
		if(document.getElementById(elementName)) {
			return document.getElementById(elementName);
		} else {
			return null;
		}
	} else if (isMinIE4 == 1) {
		if(document.all(elementName)[0]) {
			return document.all(elementName)[0];
		} else {
			return document.all(elementName);
		}
	}
}

/** Submit the Signon form
 **/
function doSubmitSignon(form) {
	form.submit();
}

/** Make sure that the External Portal signon credentials are provided
 *  	username and password have non empty values
 * 		username and password doesn't contains script characters that could be a security risk
 * If the credentials are invalid display an error by changeing the sytle of the signonCredentialError
 *
 **/
function validateSignonCredentials() {
	var errorContainer = get('signonCredentialError');
	var username = get('signin-user');
	var password = get('signin-pass');
	var validationError = false;

	// Reset the styles for the backgournd and border of username and password inputs
	username.style.backgroundColor = "";
	username.style.borderColor = "";
	password.style.backgroundColor = "";
	password.style.borderColor = "";

	if(username.value == "" || username.value == usernameHintText || (!stripScripts(username))) {
		if(errorContainer.style.display!='block')
			errorContainer.style.display = 'block';
		errorContainer.innerHTML = "Username is required";
		username.style.backgroundColor = "#FFFFCC";
		username.style.borderColor = "#FF0000";
		validationError = true;
	}
	if (password.value == "" || password.value == passwordHintText) {
		if(errorContainer.style.display!='block')
			errorContainer.style.display = 'block';
		errorContainer.innerHTML = "Password is required";
		password.style.backgroundColor = "#FFFFCC";
		password.style.borderColor = "#FF0000";
		validationError = true;
	}
	if ((username.value == "" || username.value == usernameHintText) && (password.value == "" || password.value == passwordHintText)) {
		errorContainer.innerHTML = "Username and Password required";
	}
	if (validationError)
		return;
	doSubmitSignon(get('SignIn'));
}

/* Check if we have a enter key; if so submit the External Portal signon form
 * after validating the signon credentials
 */
function handleDefaultEnter(e) {
	if(e.keyCode == 13) {
		validateSignonCredentials();
	}
}

/* Signoff the Session to External Portal and show the single sign in form */
function doSubmitSignoff() {

	$('#sign-out').hide();
	$('#single-sign-in').show();
	get('SignOut').submit();
	//window.open('./index.asp','_top');

}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) {
		return null;
	}
}

/* Signoff for External Portal. Make a HTTPRequest either for IE of Mozilla */
function makeRequest() {
	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
	return http_request;
}

/* Signoff for External Portal. POST the signoff request and show the single-sign-in panel*/
function sendRequest(url) {
	var request = makeRequest();
	request.open('POST',url,false);
	// Mozilla, Safari Firefox etc needs the withCredentials to send the session cookie. IE does not need it or support it.
	if (window.XMLHttpRequest) {
		request.withCredentials = 'true';
	}
	try {
		request.send();
	} catch(e) {
	}
	$('#sign-out').hide();
	$('#single-sign-in').show();
}

/* Handles showing the Portal sign-in. There are multiple views that will be either hidden or shown.
 * 1. If we want to use the alternate sign-in to Portal that doesn't send credentials and just redirects to the
 * Portal sign-in page there is a global boolean variable useAlternateSignIn that if set to true that will use the alternate
 * sign-in.
 * 2. The standard handling will show the sign-in to Portal that requires credentials. In addition if you are already
 * signed in you will be presented with a form to sign-out or to redirect to the Portal launch page.
 */
function showSignIn() {

	/* Use the Alternate Portal sign-in that just has a link to the Portal sign-in. This is
	 * to be used if the integrated sign-in is putting too much of a load on the website
	 */
	if (useAlternateSignIn) {
		$('#sign-out').hide();
		$('#single-sign-in').hide();
		$('#alternate-sign-in').show();
	} else {
		/* If a Portal user is not logged in the username-portal cookie will be null.
		 * Once the user is logged out the username-portal cookie value is set to '-'.
		 * Show the single-sign-in panel if they are not logged into Portal
		 * Once they are logged into Portal show the sign-out panel that will allow
		 * them to logout or redirect to the Portal landing page
		 */
		$('#alternate-sign-in').hide();
		var portalCookieValue = getCookie('username-portal');

		if ((portalCookieValue == null) || (portalCookieValue == '-')) {
			$('#sign-out').hide();
			$('#single-sign-in').show();
		} else {
			$('#sign-out').show();
			$('#single-sign-in').hide();
		}
	}

}
