function setCookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


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;
	  	}
}

function deleteCookie( name, path, domain ) {
	  if ( getCookie( name ) ) {
	  document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	  }
}

function logOut( name, path, domain, redir ) {
	  deleteCookie( name, path, domain );
	  deleteCookie( "GSA_SESSION_ID", path, domain )
	  location.href=redir;
}


// Our constants
var _SSO = "sso=un=";
var _NOSSO = "PS_NO_SSO=";
var _LOOP = "PS_SSO_LOOP="
var _REDIR = "&redir=";
var _USER = "&username=";
var _PASS = "&password=";
var _IIS_REDIR = "?ReturnUrl=";


// Global variables
var DEBUG = false;
var bAllowSubmit = false;
var prev_handler;
var gOrigURL = "";
var gDefaultURL = "https://www.qad.com/portal/site/erp/template.LOGIN/";


// These values can be overridden by the individual login forms as necessary as params to initVars()
var SSOURL = "";
var COOKIEURL = "";
var theform;
var _FLD_USER = "Username";
var _FLD_PASS = "Password";



function URLEncode(clearString) {
	var output = '';
 	var x = 0;
 	clearString = clearString.toString();
 	var regex = /(^[a-zA-Z0-9_.]*)/;
 	while (x < clearString.length) {
	 	var match = regex.exec(clearString.substr(x));
	 	if (match != null && match.length > 1 && match[1] != '') {
	 		output += match[1];
	 		x += match[1].length;
	 	} else {
	 		if (clearString[x] == ' ')
	 			output += '+';
	 		else {
	 			var charCode = clearString.charCodeAt(x);
	 			var hexVal = charCode.toString(16);
	  			output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}

function URLDecode(encodedString) {
	var binVal, thisString, ret = "", output = encodedString;
	var bNoMatches = true;
	var myregexp = /(%[0-9A-Fa-f]{2})/;
	while ((match = myregexp.exec(output)) != null && match.length > 1 && match[1] != '') {
		bNoMatches = false;		
		binVal = parseInt(match[1].substr(1), 16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);		
		ret = ret + output.substr(0, match.index) + thisString;
		output = output.substr(match.index + 1);
	}
	
	if (bNoMatches)
		return encodedString;
	else
		return ret + output;
}

function extractOrigURL(loc) {
	var ret = "/";
	var idx = loc.indexOf(_IIS_REDIR);
	if (DEBUG) alert("extractOrigURL() - URL marker at: " + idx);
	if (idx >= 0) {
		ret = URLDecode(loc.substring(idx + _IIS_REDIR.length));
	}
	if (DEBUG) alert("Original URL: '" + ret + "'");
	return ret;
}		

function doCookieCheck() {
	var idxSSO  = document.cookie.indexOf(_SSO);
	var idxNoSSO = document.cookie.indexOf(_NOSSO);

	if (idxNoSSO >= 0) {
		showLogin();
	} else if (idxSSO >= 0) {
		var mins = 0;
		var idxLoop = document.cookie.indexOf(_LOOP);
		if (idxLoop >= 0) {
			// There is a timestamp in our cookie - if it's less than a minute old, do NOT resubmit
			var valTime;
			var semi = document.cookie.indexOf(";", idxLoop);
			if (semi != -1)
				valTime = document.cookie.substring(idxLoop + _LOOP.length, semi);
			else
				valTime = document.cookie.substring(idxLoop + _LOOP.length);
			var svTime = new Date(parseInt(valTime));
			var curTime = new Date();
			mins = (curTime - svTime) / 1000 / 60;	// In minutes
		}

		/*if ((idxLoop >= 0 && mins <= 1)) {
			// Initial single sign-on failed - SSO disabled so display the logon form to allow manual authentication
			showLogin();
		} else {*/
			// Set a cookie so we prevent looping if there's a server-side authentication error 
			var tm = new Date();
			document.cookie = _LOOP + tm.getTime();

			// Call out to perl script to decrypt cookie
			doIframe();
		//}
	} else {
		// First time access from this machine - neither Pistolstar cookie present
		showLogin();
	}
}

function setGsaCookie(uname, pwd)
{
var t;
var frms = this;
var queryString = "http://cont506.qad.com:20080/GSALogin.aspx?username="+uname+"&pwd="+pwd;


if (DEBUG) {
	alert("GSA queryString: " + queryString); 	
} 

var ifrm = document.createElement('iframe');
         ifrm.src=queryString;
         ifrm.style.width = '0px';
         ifrm.style.height = '0px';
         ifrm.style.border = '0px';
         var gsaDiv = document.getElementById('gsa_div');
         gsaDiv.appendChild(ifrm);
  sleep(2000);
 
}
function setFormFocus() {
	theform.elements[_FLD_USER].focus(); 
	theform.elements[_FLD_USER].select();
}

function showLogin() {
	// Redirect to the IIS login form
	var theurl = COOKIEURL + URLEncode(window.location);
	if (DEBUG) alert("Redirecting to '" + theurl + "'");
	window.location = theurl;
}

function allowLogin() {
	try {
		document.getElementById("ps_sso_div").style.display = 'inline';
	} catch (e) {}
	setFormFocus();
}

function initVars(bDebug, frm, docdom, ssourl, cookieurl, requrl, fldUser, fldPass) {
	DEBUG = bDebug;
	document.domain = docdom;
	SSOURL = ssourl;
	COOKIEURL = cookieurl;
	if (DEBUG) alert("document.domain = '" + document.domain + "'\nSSOURL = '" + SSOURL + "'\nCOOKIEURL = '" + COOKIEURL + "'");
	prev_handler = frm.onsubmit;
	frm.onsubmit = doCallout;
	theform = frm;
	gOrigURL = requrl;
	
	if (fldUser) {
		if (DEBUG) alert("initVars() - Overidding user field to '" + fldUser + "'");
		_FLD_USER = fldUser;
	}
	if (fldPass) {
		if (DEBUG) alert("initVars() - Overidding password field to '" + fldPass + "'");
		_FLD_PASS = fldPass;
	}
	
}

function sleep(delay)
{
var start = new Date().getTime();
while(new Date().getTime() < start+delay);
}


function doIframe() {
	var ifrm = document.getElementById("ifrmDestFrame");
 	try {
		var theurl = SSOURL + _REDIR + URLEncode(window.location);
		if (DEBUG) alert("doIframe()\nURL: " + theurl);
 		ifrm.src = theurl;
 	} catch (e) {
 		var outp = "doIframe(): Error getting iframe handle\n==========\n";
		for (var i in e)
			outp = outp + i + ": " + e[i] + "\n";
		alert(outp);
			
		// Allow manual login
		showLogin();
 	}
}

function doCallout() {
	var frm = this;
	setGsaCookie(frm.elements[_FLD_USER].value, frm.elements[_FLD_PASS].value); // calls GSA function to set cookie

	if (DEBUG) {
		alert("In doCallout()");
		alert("setGsaCookie()"); 
	}

	setErrorText("");	// Clear any error

	if (bAllowSubmit) {
		prev_handler();
		if (DEBUG) alert("Allowing submit to continue");
		return true;	// Allows original POST to continue
	} else {
		try {
			var theurl = COOKIEURL + _USER + URLEncode(frm.elements[_FLD_USER].value) + _PASS + URLEncode(frm.elements[_FLD_PASS].value) + _REDIR + URLEncode(gOrigURL);
			var ifrm = document.getElementById("ifrmDestFrame");

			if (DEBUG) alert("doCallout()\nPreventing original post\nNew URL: " + theurl);
			//window.frames["ifrmDestFrame"].location = theurl;
			ifrm.src = theurl;
		} catch (e) {
			var outp = "doCallout(): Error setting iframe src\n==========\n";
			for (var i in e)
				outp = outp + i + ": " + e[i] + "\n";
			alert(outp);
			//showLogin();	// Should already be visible...
		}
		
		return false;	// Stops original POST...
	}
}

function doSubmit() {
	bAllowSubmit = true;
	theform.submit();
}

function checkStatus() {
	if (DEBUG) alert("In checkStatus()");
	// If our SSO cookie is present, then the login succeeded
	var idxSSO  = document.cookie.indexOf(_SSO);
	if (idxSSO >= 0) {
		if (DEBUG) alert("Redirecting back to the original URL: '" + gOrigURL + "'");
		if ((gOrigURL.indexOf("http://") >= 0) || (gOrigURL.indexOf("https://") >= 0))
			window.location = gOrigURL;
		else {
			//alert("You have successfully authenticated, please go back to your originally requested URL");
			window.location = gDefaultURL;
		}
	} else {
		//setErrorText("Invalid username or password - please try to login again");
		setErrorText("Invalid credentials or locked account");

	}
}

function populateFields(user, pass) {
	//document.all.ps_sso_div.style.display = 'inline';
	if (DEBUG) alert("In populateFields()");
	try {
		theform.elements[_FLD_USER].value = URLDecode(user);
		theform.elements[_FLD_PASS].value = URLDecode(pass);
		if (DEBUG) alert("Submitting form automatically here!");
		doSubmit();
	} catch (e) {
 		var outp = "populateFields(): Error filling destination form\n==========\n";
		for (var i in e)
			outp = outp + i + ": " + e[i] + "\n";
		alert(outp);
		showLogin();
	}
}
