/*
 * oam.js
 * http://www.aha.org
 *
 * @projectDescription OAM JS Library 
 * @author Rey Echevarria rechevarria@aha.org
 * @copyright American Hospital Association
 * @version 1.0
 * @updated 2009-03-04
*/

/* ****************************** *
 * Initialization
 * ------------------------------ */
 
// Look for the SITE object and if oamLogin property is default, attach oamLogin function on page onload event. 
var loginType = (typeof SITE != 'undefined') ? SITE.oamLogin:'';
if (loginType == 'default') {
	ADS.addEvent(window, 'load', oamLogin);
} 

/* End Initialization 
 * ------------------------------ */
 
/* ****************************** *
 * Custom Objects 
 * ------------------------------ */

var OAMLINK = {
	register: 'http://www.hospitalconnect.com/hospitalconnect_app/registration/SingleSignOn/reg_id.jsp',
	updateProfile: 'http://www.hospitalconnect.com/hospitalconnect_app/preferences/edit_profile.jsp',
	forgotPassword: 'http://www.hospitalconnect.com/hospitalconnect_app/preferences/forgot_pword.jsp',
	updateProfessional: 'http://www.hospitalconnect.com/hospitalconnect_app/preferences/edit_professional.jsp',
	addMembership: 'http://www.hospitalconnect.com/hospitalconnect_app/preferences/edit_membership.jsp'
}

/* End Custom Objects 
 * ------------------------------ */

/* ****************************** *
 *	Global Variables 
 * ------------------------------ */

var DEBUG = 2;// 0=none, 1=alert, 2=log
var OAM_COOKIES = { };

/* End Global Variables 
 * ------------------------------ */

/* ****************************** *
 *	Utility Functions 
 * ------------------------------ */

function addEventByClass(elementClass, f) {
	/* Add event to elements of a particular class */
	
	var el = ADS.getElementsByClassName(elementClass, '*', document);
	if (el) {
		for (var i=0; i<el.length; ++i) {
			ADS.addEvent(el[i], 'click', f);
		}
	}
	return;
}
function removeEventByClass(elementClass, f) {
	/* Remove event to elements of a particular class */
	
	var el = ADS.getElementsByClassName(elementClass, '*', document);
	if (el) {
		for (var i=0; i<el.length; ++i) {
			ADS.removeEvent(el[i], 'click', f);
		}
	}
	return;
}

function checkAutoLogin() {
	/* The old login process utilized a call to checkAutoLogin. */
	/* This function was created to catch an instances of a call to the function. */
	/* This function may be removed once we go live. */	
	
	//alert('CLEAN: This site is trying to "checkAutoLogin"');	
}

function logMsg(msg) {
	/* Based on the DEBUG global var, this function logs or alerts messages. */
	
	switch(DEBUG) {
		case 1: alert('DEBUG: '+msg); break;
		case 2: if (window.console) { console.log(msg); } break; //FireBug
		default: break;
	}
	return;
}

function oamSetMsg(elementId, msg) {
	/* This function updates the login element (id value passed) with the message passed. */
	
	var el = ADS.$(elementId);
	if (el){ el.innerHTML = msg; }
	return;
}

function oamSetMsgByClass(elementClass, msg) {
	/* This function updates the login element (class value passed) with the message passed. */
	var el = ADS.getElementsByClassName(elementClass, '*', document);
	if (el) {
		for (var i=0; i<el.length; ++i) {
			el[i].innerHTML = msg; 
		}
	}
	return;
}

function ssoRedirect(page) {
	/* This function is called from the custom redirect pages. */

	location.replace(page);
}

function xssRequestCallback(r){
	logMsg('Hit Callback Func');
	return;
}

/* End Utility Functions
 * ------------------------------ */

/* ****************************** *
 *	Login/Logout Functions 
 * ------------------------------ */
 
 function setSessionUID(uidvar, uidval) {
	/* This function sets the session vavrialbe with the value of uidvar to the value defined by uidval. */
	
	ADS.ajaxRequest(SITE.docroot+'/oam/session.jsp?uidvar='+uidvar+'&uidval='+uidval+'&x='+Math.random(),{
		method:'GET',
		completeListener:function() {
			logMsg(this.responseText);
			
			// 03-04-09 added check for url to ensure 'www.ahrmm.org/' would not be refreshed - would be an endless loop
			logMsg(window.location.href.match(/[^\/]+$/));
			
			if (this.responseText.match(/Session var has been set\./) != null && window.location.href.match(/[^\/]+$/) != null) {
				logMsg('reloading page');
				window.location.reload();	
			}
			
		}
	});
	return;
}
 
 function oamLogin() {
	/* This function checks for the OAM related cookies locally. */
	/* If the cookies exist the welcome message is set. */
	/* If the cookies do not exist, they are obtained and set from HC. */

	logMsg('oamLogin begin');
	var cn = getCookie('AHA_CN');// getting the cookie value to check for Anonymous User
	
	if (getCookie('ObSSOCookie') == 'null' || getCookie('ObSSOCookie') == 'loggedout' || getCookie('ObSSOCookie') == 'loggedoutcontinue' || cn == 'Anonymous User') {
	// Any of these cookie values signify a LOGGED OUT user.
		logMsg('deleting cookies');
		delOblixCookie();// delete OAM specific cookies
		if (SITE.sessionSetUID) {// The SITE object is defined in a site's oam/siteinfo.js file.
			logMsg('clear session variable: '+SITE.sessionVarUID);
			setSessionUID(SITE.sessionVarUID, '');	
		}
	}
	cn = getCookie('AHA_CN');// need to get the value again becasue it may now be null
	logMsg('Initial Value: AHA_CN='+cn);
		
	if (cn != null && cn != 'Anonymous User') {
	// User has successfully LOGGED IN (determined locally)
	
		logMsg('setting welcome message');
		var uid = getCookie('AHA_UID');
		if (SITE.sessionSetUID) {// The SITE object is defined in a site's oam/siteinfo.js file.
			logMsg('set session variable: '+uid);
			setSessionUID(SITE.sessionVarUID, uid);	
		}
		// Setup appropriate LOGGED IN messages/links
		oamUpdateDynElements(1);

	}
	else {
	// Check HC to see if user has LOGGED IN 
		logMsg('getting HC cookies');
		getOAMcookies();
	}	
	return;
}

function oamLogoutInclude() {
	for (sitedomain in PORTAL) {// PORTAL object is defined in portalinfo.js
		document.writeln('<link rel="stylesheet" type="text/css" href="http://www.'+PORTAL[sitedomain]+'/oam/logout.css" />');
	}
}

function oamLogout() {
	/* This function initiates the logout process. It hits a HopsitalConnect page which does the bulk of the work. */
	
	ADS.xssRequest(
		'http://www.hospitalconnect.com/oam/logout.dhtml',{
			completeListener:function() { 
				logMsg('LOGOUT SUCCESS: '+this.responseJSON); 
				oamLogoutIStore();// redirects to iStore logout page
			},
			errorListener:function() { 
				logMsg('LOGOUT ERROR: '+this.statusText); 
			}		
		}
	);
	return;
}

function oamLogoutIStore() {
	/* This function initiates the logout process. */
	/* It hits a page on the OAM infrastructure (logout.jsp which includes header_js.jsp). */
	
	var homePage = 'http://www.'+SITE.domain;// This is the page that will be hit after logout.
	var currentPage = window.location;
	window.location = 'http://sso.hospitalconnect.com/sso/logout?p_done_url='+homePage;	
	return;
}

 /* End Login/Logout Functions
 * ------------------------------ */

/* ****************************** *
 *	OAM Element Functions 
 * ------------------------------ */

function oamUpdateDynElements(status) {
		switch(status) {
			case 0:
				oamSetWelcomeMsg();
				
				oamSetLoginMsg();
				addEventByClass('oamLoginLink', setLoginLink);
				
				oamSetRegisterMsg(1);
				addEventByClass('oamRegisterLinkCurrent', setRegisterLinkCurrentPage);
				addEventByClass('oamRegisterLinkWelcome', setRegisterLinkWelcomePage);
				
				oamSetProfileMsg(0);	
				removeEventByClass('oamProfileLinkCurrent', setUpdateProfileLinkCurrentPage);
				
				addEventByClass('oamPasswordLinkWelcome', setForgotPasswordLinkWelcomePage);

				break;
			
			case 1:// 
				oamSetWelcomeMsg(getCookie('AHA_CN'));
		
				oamSetLogoutMsg();
				addEventByClass('oamLogoutLink', oamLogout);
				
				oamSetRegisterMsg(0);
				removeEventByClass('oamRegisterLinkCurrent', setRegisterLinkCurrentPage);
				removeEventByClass('oamRegisterLinkWelcome', setRegisterLinkWelcomePage);

				oamSetProfileMsg(1);
				addEventByClass('oamProfileLinkCurrent', setUpdateProfileLinkCurrentPage);
				
				addEventByClass('oamPasswordLinkWelcome', setForgotPasswordLinkWelcomePage);
				
				break;
			
			default:
				break;
		}
		return;
}

function oamSetLoginMsg() {
	/* Replace elements with id "ELEMENToamlink" with appropriate content. */
	
	oamSetMsg('ELEMENToamlink','<a href="#" class="oamLoginLink">Log in</a>');
	return;
}

function oamSetLogoutMsg() {
	/* Replace elements with id "ELEMENToamlink" with appropriate content. */
	
	oamSetMsg('ELEMENToamlink','<a href="#" class="oamLogoutLink">Log out</a>');
	return;
}

function oamSetWelcomeMsg() {
	/* Replace elements with id "ELEMENToamwelcome" with appropriate content. */
	/* If an arguemnt is passed a welome message will be displayed otherwise the messge is cleared. */
	
	var args = oamSetWelcomeMsg.arguments;
	var msg = (args.length == 0) ? '':'Welcome '+args[0];
	oamSetMsg('ELEMENToamwelcome', msg);
	return;
}

function oamSetRegisterMsg(status) {
	/* Replace elements with id "ELEMENToamregister" with appropriate content. */
	
	var msg = (status == 1) ? '<a href="#" class="oamRegisterLinkCurrent">Register</a>':'';
	oamSetMsg('ELEMENToamregister', msg);
	return;
}

function oamSetProfileMsg(status) {
	/* Replace elements with id "ELEMENToamprofile" with appropriate content. */
	
	var msg = (status == 1) ? '<a href="#" class="oamProfileLinkCurrent">Update profile</a>':'';
	oamSetMsg('ELEMENToamprofile', msg);
	return;
}

function oamSetPasswordMsg(status) {
	/* Replace elements with id "ELEMENToampassword" with appropriate content. */
	
	var msg = (status == 1) ? '<a href="#" class="oamPasswordLinkWelcome">Forgot password?</a>':'';
	oamSetMsg('ELEMENToampassword', msg);
	return;
}

/* The following functions are used to set the dynamic hyperlinks. */
function setLoginLink() {
	var current_page = window.location;
	window.location = SITE.docroot+'/oam/welcome.html';
	return;
}

function setUpdateProfileLinkCurrentPage() {
	var current_page = window.location;
	window.location = OAMLINK.updateProfile+'?redirectPage='+current_page;
	return;
}

function setRegisterLinkCurrentPage() {
	var current_page = window.location;
	window.location = OAMLINK.register+'?redirectPage='+current_page;
	return;
}

function setRegisterLinkWelcomePage() {
	var current_page = window.location;
	window.location = OAMLINK.register+'?redirectPage=http://www.'+SITE.domain+SITE.docroot+'/oam/welcome.html';
	return;
}

function setForgotPasswordLinkWelcomePage() {
	var current_page = window.location;
	window.location = OAMLINK.forgotPassword+'?redirectPage=http://www.'+SITE.domain+SITE.docroot+'/oam/welcome.html';
	return;
}

/* End OAM Element Functions
 * ------------------------------ */

/* ****************************** *
 *	Cookie Manipulation Functions 
 * ------------------------------ */
 
 function getOAMcookies() {
	/* This function looks up OAM related HC cookies and sets them locally. */
	/* This function also updates the HC cookie "AHA_DOMAINS" */

	logMsg('getOAMcookies begin');
	// Call to create dynamic script elements
	ADS.xssRequest(
		'http://www.hospitalconnect.com/oam/oam.dhtml?task=cookie&x='+Math.random(),{
			completeListener:function() { 
				if (this.responseJSON.status == 1) {
					// User has successfully LOGGED IN (determined on HC)
					logMsg('HC cookies were found');
					
					// Set OAM cookies locally - based on object returned by oam.dhtml
					setLocalCookies(this.responseJSON);
					
					// Set session variable if necessary
					if (SITE.sessionSetUID) {// The SITE object is defined in a site's oam/siteinfo.js file.
						logMsg('set session variable: '+SITE.sessionVarUID);
						setSessionUID(SITE.sessionVarUID, this.responseJSON.AHA_UID);	
					}
					
					// Setup appropriate LOGGED IN messages/links
					oamUpdateDynElements(1);
					
				}
				else {
					// User is NOT LOGGED IN
					logMsg('no HC cookies found');
					logMsg('status = '+this.responseJSON.status);
					logMsg('status2 = '+this.status);
					logMsg('status2-txt = '+this.statusText);					

					// Setup appropriate LOGGED out messages/links
					oamUpdateDynElements(0);
				}
			},
			errorListener:function() { 
				logMsg('ERROR: '+this.statusText); 
				// Setup appropriate LOGGED IN messages/links
				oamUpdateDynElements(0);	
			}
		}
	);
	return;
}

function setLocalCookies(obj) {
	/* This function sets local cookies based on the object being passed. */
	/* If addtional cookies are to be "copied" from HC, you would need to update */
	/* the master "oam.dhtml" page to read the needed cookies and construct the */
	/* appropriate JSON response. 
	/* Object Property Name translates to the Cookie Name. */
	/* Object Property Value translates to the Cookie Value. */
	
	logMsg('setting local cookies');
	for (var prop in obj) {
		if (prop && prop != 'status') {// don't create a status cookie
			setCookie(prop, obj[prop]);
		}// end if
	}// end for	
	return;
}

function delOblixCookie() {
	/* This function cyles through the current domain (and subdomains) and deletes the named cookies. */
	/* This function utilizies the oam cookie.js library. */
	
	logMsg('deleting local cookies');
	
	// set focus to ok button
	var isNetscape = (document.layers);
	if (isNetscape == false || navigator.appVersion.charAt(0) >= 5) {
		for (var i=0; i<document.links.length; i++) {
			if (document.links[i].href == "javascript:top.close()") {
				document.links[i].focus();
				break;
			}
		}
	}
	delCookie('ObSSOCookie', '/');
	delCookie('AHA_RM', '/');
	delCookie('AHA_CN', '/');
	delCookie('AHA_UID', '/');
	delCookie('ASHHRA_ID', '/');
	delCookie('ASHRM_ID', '/');	

	// i don't think these are being set
	delCookie('JSESSIONID', '/');
	delCookie('ObTEMC', '/');
	delCookie('AHA_MAIL', '/');
	
	// in case cookieDomain is configured
	// delete same cookie to all of subdomain
	var subdomain;
	var domain = new String(document.domain);
	
	
	var index = domain.indexOf(".");
	
	while (index > 0) {
		subdomain = domain.substring(index, domain.length);
		if (subdomain.indexOf(".", 1) > 0) {
			delCookie('ObSSOCookie', '/', subdomain);
			delCookie('AHA_RM', '/', subdomain);
			delCookie('AHA_CN', '/', subdomain);			
			delCookie('AHA_UID', '/', subdomain);
			delCookie('ASHHRA_ID', '/', subdomain);
			delCookie('ASHRM_ID', '/', subdomain);
			
			// i don't think these are being set
			delCookie('JSESSIONID', '/', subdomain);
			delCookie('ObTEMC', '/', subdomain);
			delCookie('AHA_MAIL', '/', subdomain);
		}
		domain = subdomain;
		index = domain.indexOf(".", 1);
	}
	return;
}

/* End Cookie Manipulation Functions
 * ------------------------------ */