/**
This file is used to create the javascript functiosn related to home page
@author  rpidikiti
@version 2.0
*/
var menuState = "closed";
var MENU_STATE_OPEN = "open";
var MENU_STATE_CLOSE = "closed";
var cometD = null;
var showcasePos = 1;
var showcaseMax = 4; //total number of slides before looping back to beginning
var isLowRes = false;
//on page load, check the user has 800x600 resolution- if so, load the css for a smaller console -- we might not need this for now
var widgetsDisabled = "no";
var consoleDisabled = "no";
var consoleInterval;
var sliderWidth =  -621;//if slider size changes, set appropriate value to show it how far to slide when closing
var currentMove = -(sliderWidth/2);
var ALERT_DIV_ID = "alerts_div";
var NEW_MESSAGE_ALERT_ID = "message_alert";
var NEW_EVENT_ALERT_ID = "event_alert";
var NEW_NETWORK_EVENT_ALERT_ID = "network_alert";
var MAX_CONNECTION_FAILURE_COUNT = 10;
var comet_connection_failure_count = 0;
var channels = new dojo.collections.ArrayList();
var cometConnected = false;
var debugMessages = new dojo.collections.ArrayList();

//declare name space for logging
passenger.home = function(){}
passenger.home.json = function(){}
passenger.home.handleHeaderLinks = function (){}
passenger.home.comet = function(){}

/**
 * Function is used to initialize comet and menus if it is already not. Currently this function is called from pages
 * which expect these methods to be initilized while loadng them. Example: If we directly load the session page on page
 * refresh we expect menus and cometd to be initialized before loading the session page. 
 */
function initializeCometAndMenus() {
	if(cometD == null) {
		//passenger.home.initialize();		
	}
	if(getPassengerMenuStatus() != "true") {	
		//load user headers and menu
		passenger.home.loadHeaderAndMenu();
		setPassengerMenuStatus(true);
	}
}

passenger.common.initialize = function () {
	if (typeof window.event != 'undefined') {
		dojo.event.connect(document.body, "onkeydown", passenger.common.trapKeyboardEvents());
	} else {
		dojo.event.connect(document.body, "onkeypress", passenger.common.trapKeyboardEvents());
	}
	passenger.home.initHomePage();
}

passenger.home.initialize = function() {
	//passenger.home.comet.initialize(getPassengerCometConnection(), document.getElementById("userIdDiv").innerHTML);
}

passenger.home.finalize = function() {
	//passenger.home.comet.finalize(getCurrentActivePassengerCometConnection(), document.getElementById("userIdDiv").innerHTML);
}

/**
 * Function used to load the content page
 */
passenger.home.initHomePage = function() {
	try {
		passenger.home.loadContent();
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

function handleLoginStart() {
	try {
		if(getPassengerMenuStatus() != "true") {
			var myFormSubmitEvent = passenger.util.getHtmlSubmitEvent();
			document.AjaxFormSubmit_checkUserStatusForm_scriptSubmit([myFormSubmitEvent]);
			document.AjaxFormSubmit_loginUpdateForm_loginUpdateFormSubmit([myFormSubmitEvent]);
		} else if(getPassengerMenuStatus() == "true") {
			document.getElementById("menuHolderRow").style.visibility = "visible";
		}
		//passenger.home.initialize();//Init comet connection for home/menu refresh
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

function handleLoginFail() {}

/**
 * Function to handle the ajax response for checking if the user is allowed to 
 * access the application controls. This Ajax call is triggerd when the application
 * home page is accessed. Triggered again after logout or session invalidation.
 */
passenger.home.handleUserAccessToApplication = function () {};
passenger.home.handleUserAccessToApplication.beforeAjaxUpdate = function(responseElement)  {
	try {
		var isUserAllowedToAccessApplication = passenger.xml.getChildElementById(responseElement, "isUserAllowedToAccessApplication");
		if(isUserAllowedToAccessApplication != null) {
			//if status is true then stop the thread and load the menu and page header links
			if(passenger.xml.getChildElementById(isUserAllowedToAccessApplication, "status").firstChild.nodeValue == 'true') {
				//load user headers and menu
				passenger.home.loadHeaderAndMenu();
				//var myFormSubmitEvent = passenger.util.getHtmlSubmitEvent();
				//document.AjaxFormSubmit_pageRefreshForm_pageRefreshFormSubmit([myFormSubmitEvent]);
			}
		}
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Function to handle the ajax response for getting the user id. This Ajax call is 
 * triggerd when the application home page is accessed. 
 */
passenger.home.handleLoginUpdate = function() {}
passenger.home.handleLoginUpdate.responseComplete = function(responseElement) {
	try {
		passenger.home.initialize();
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * This ajax function is used to display the header links content. Currently tacos 
 * will take care of updating the ajax content to we might not do any specific action 
 * as part of these calls. In future, We can override these methods if requried. 
 */
passenger.home.handleHeaderLinks.ajaxUpdate = function(element, responseElement, elementId)  {
	try {
		//if(elementId == "headerActions") {
			//document.getElementById("headerActions").innerHTML = responseElement.innerHTML;
		//}
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}	

/**
 * Display header links and menu items
 */
passenger.home.loadHeaderAndMenu = function() {
	try {
		if(getPassengerMenuStatus() != "true") {
			var myFormSubmitEvent = passenger.util.getHtmlSubmitEvent();
			document.AjaxFormSubmit_headerLinksForm_headerLinksFormSubmit([myFormSubmitEvent]);
			//display menu
			setPassengerMenuStatus(true);
		}
		document.getElementById("menuHolderRow").style.visibility = "visible";
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
} 

/**
 * Hide the header and menu actions
 */
passenger.home.hideHeaderAndMenu = function() {
	try {
		document.getElementById("headerActions").innerHTML = "";//hide header
		document.getElementById("menuHolderRow").style.visibility = "hidden";//hide menu
		setPassengerMenuStatus(false);
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Displays the version relative to the position of the infomration icon
 */
passenger.home.displayVersion = function(tableCell) {
	try {
		var tipPosition = dojo.html.getAbsolutePosition(tableCell);
		var x = document.getElementById('versionDiv');
		x.style.left = (tipPosition.left)  + "px";
		//this is set to 0 so that scrollheight is calculated properly
		x.style.top = "0px";
		var scrollHeight = 0;
		if (document.all){//Internet Explorer 5 and above
				scrollHeight = document.body.scrollHeight;
		}else{
				scrollHeight=document.documentElement.scrollHeight;
		} 
		x.style.top = (scrollHeight - 65) + "px";		
		x.style.display = "block";	
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Hides the version information
 */
passenger.home.hideVersion = function() {
	try {
		var x = document.getElementById('versionDiv');
		x.style.display = "none";
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Get the menu status - true=open/false=closed
 */
getPassengerMenuStatus = function() {
	try {
		return document.getElementById("menuStatus").value;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Set the menu status - true=open/false=closed
 */
setPassengerMenuStatus = function(status) {
	try {
		document.getElementById("menuStatus").value = status;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Function to clear all alerts after closing the menu
 */
passenger.home.clearAlerts = function() {
	try {
		document.getElementById(ALERT_DIV_ID).style.display = "none";
		document.getElementById(NEW_MESSAGE_ALERT_ID).style.display = "none";
		document.getElementById(NEW_EVENT_ALERT_ID).style.display = "none";
		document.getElementById(NEW_NETWORK_EVENT_ALERT_ID).style.display = "none";
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Funtion to clear a single alert after closing the menu
 */
passenger.home.clearSingleAlert = function(id) {
	try {
		document.getElementById(id).style.display = "none";
		//Check to see if there are any more alerts before hiding the alert div.
		var event_alert = document.getElementById("event_alert").style.display;
		var network_alert = document.getElementById("network_alert").style.display;
		var message_alert = document.getElementById("message_alert").style.display;
		if(event_alert.toLowerCase() == "none" && network_alert.toLowerCase() == "none" && message_alert.toLowerCase() == "none") {
			document.getElementById(ALERT_DIV_ID).style.display = "none";		
		}
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Function used to load the conten to content frame. The control logic at the
 * presentation framework decides the page that needs to be lodaded into this 
 * frame based on the current system info and user status.
 * Example: If the user it no logged in then load login page, if the user is 
 * logging for the first time then show the edit user profile page etc.
 */
passenger.home.loadContent = function () {
	try {
		document.contentForm.target = "content";
		document.contentForm.submit();
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Function to update the product name.
 * @param productName - name of the product.
 */
function setProductName(productName) {
 	try {
 		PRODUCT_NAME = productName;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}
/**
 * Function to set the page title. This is called from the content pages
 * @param pageName - Name of the page
 */
function setPageTitle(pageName) {
	try {
		document.getElementById("pageTitle").innerHTML = pageName;
		window.document.title = PRODUCT_NAME + " - " + pageName;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * If the menu div is opened then list and audio, video elements re not 
 * hidden properly below the menu div hence we need to hide them on menu
 * open and display them back on menu close.
 * 
 * Since it is not very easy to identify list of elements that we need to hide, 
 * it is responsibility of every page to give that list.
 */
passenger.home.hideElementsForMenuOpen = function() {	
	//list of comma seperated elements 
	try{
		var listAsString = window.frames.content.getElementListForHide();
		var z; 
		var elementList = dojo.string.splitEscaped(listAsString, ",");
		for(var i=0; i < elementList.length; i++) {
			z = window.frames.content.document.getElementById(elementList[i]);	
			z.style.visibility = "hidden";
		}	
	}catch(ex){
		//exception means no elements to hide hence ignore
		//alert("hideElementsForMenuOpen: "+ex);
	}
}

passenger.home.displayElementsForMenuClose = function() {
	//list of comma seperated elements
	try{
		var listAsString = window.frames.content.getElementListForHide();
		var z; 
		var elementList = dojo.string.splitEscaped(listAsString, ",");
		for(var i=0; i < elementList.length; i++) {
			z = window.frames.content.document.getElementById(elementList[i]);	
			z.style.visibility = "visible";
		}	
	}catch(ex){
		//exception means no elements to hide hence ignore
		//alert("Exception: "+Exception);
	}
		
}

/*
Initializes the dojo specific logging
*/
try {// begin logic to initializing and applying the debugging
	if (djConfig["isDebug"])
	 {
	  dojo.event.connect(window, "onload", function(e) {
		 dojo.event.connect(dojo.byId("dclear"), "onclick", function(evt)
		 {
			 dojo.dom.removeChildren(dojo.byId("dojoDebug"));
		 });
		 dojo.event.connect(dojo.byId("dhide"), "onclick", function(evt)
		 {
			 dojo.byId("dojoDebug").style.display = "none";
			 dojo.byId("dhide").style.display = "none";
			 dojo.byId("dshow").style.display = "inline";
			 if (dojo.widget.byId("debugconsole")) {
			 dojo.widget.byId("debugconsole").resizeTo(
				  dojo.style.getOuterWidth(
				  dojo.byId("debugconsoleContentId")), 22);
			 dojo.widget.byId("debugconsole").onResized();
			 }
			 dojo.io.cookie.setCookie("dcdisplay", "none");
		 });
		 dojo.event.connect(dojo.byId("dshow"), "onclick", function(evt)
		 {
			 dojo.byId("dojoDebug").style.display = "";
			 dojo.byId("dshow").style.display = "none";
			 dojo.byId("dhide").style.display = "";
			 if (dojo.widget.byId("debugconsole")) {
			 dojo.widget.byId("debugconsole").resizeTo(
			 dojo.style.getOuterWidth(
				  dojo.byId("debugconsoleContentId")), 300);
			 dojo.widget.byId("debugconsole").onResized();
			 }
			 dojo.io.cookie.setCookie("dcdisplay", "");
		 });
			 var dd = dojo.io.cookie.getCookie("dcdisplay");
			 dojo.debug("dcdisplay cookie found with value:" + dd);
			 if (dd && dd == "none")
			 {
				 dojo.debug("Found dcdisplay cookie, sizing console to 22");
				 dojo.byId("dojoDebug").style.display = "none";
				 dojo.byId("dshow").style.display = "inline";
				 dojo.byId("dhide").style.display = "none";
				 if (dojo.widget.byId("debugconsole")) {
					 dojo.widget.byId("debugconsole").resizeTo(
					  dojo.style.getOuterWidth(
					  dojo.byId("debugconsoleContentId")), 22);
				 }
			 } else
				 dojo.byId("dojoDebug").style.display = "";

			 dconsole = dojo.byId("debugconsoleContentId");
			 if (dconsole) dconsole.style.zIndex = "2000";
			 if (djConfig["isDebug"])
			 {
				dojo.dom.moveChildren(dojo.byId("debugContainer"), dojo.byId("debugconsoleContentId"), false);
			 } else
			 {
				dojo.dom.removeNode(dojo.byId("debugContainer"));
			 }
			 if (dojo.widget.byId("debugconsole")) {
			  dojo.widget.byId("debugconsole").onResized();
			 }
			 dojo.debug("Completed window.onload setup...");
		 });
	 }
 } catch (e) {
  //alert("ERROR " + e);
 } // end logic to initializing and applying the debugging 

/**
 * Funtion to allow other pages to retrieve and share a single comet connection
 * Returns a newly created and initialized connection of one is not available. 
 */
getPassengerCometConnection = function(){
	try {
		if(cometD == null){
			
			cometD = cometd; 
			cometD.init("cometd");
		}
		return cometD;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Funtion to allow other pages to retrieve and share a single already initialized comet connection
 * Returns null if no connection is available
 */
getCurrentActivePassengerCometConnection = function(){
	try {
		return cometD;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Returns the current state of the cometD connection object.
 * Valid states are:
 * 		DISCONNECTED 	_initialized==false && _connected==false
 *		CONNECTING 		_initialized==true && _connected==false (handshake sent)
 *		CONNECTED		_initialized==true && _connected==true (first successful connect)
 *		DISCONNECTING	_initialized==false && _connected==true (disconnect sent)
 */
getPassengerCometConnectionState = function(){
	try {
		if(cometD != null) {
			return cometD.state();
		} else {
			return null;
		}
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Close the cometD connection and reset the object
 */
passenger.home.comet.endPassengerCometConnection = function() {
	try {
		if(cometD != null) {
			//Disconnect from the comet connection
			cometD.disconnect();
			cometD = null;
			cometConnected=false;
		}
	} catch(Exception) {
		//alert("endPassengerCometConnection: "+Exception);
	}
}

/**
 * gets the currently registered channels
 */
passenger.home.comet.getChannels = function() {
	try {
		return channels;
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * check if channel is already registered
 */
passenger.home.comet.isChannelRegistered = function(channelName) {
	try {
		for(var i=0; i < passenger.home.comet.getChannels().count; i++) {
			var aChannel = passenger.home.comet.getChannels().item(i);
			if(aChannel.getName() == channelName) {
				return true;
			}
		}
	} catch(Exception) {
		//alert("Exception: "+Exception);
	}
}

/**
 * Subscribe/Unsubscribe to comet channels based in boolean passed in.
 */
passenger.home.comet.manageCometSubscriptions =  function(isSubscribe) {
	try {
		var connection = getCurrentActivePassengerCometConnection();
		var currentChannels = passenger.home.comet.getChannels();
		for(var i=0; i < currentChannels.count; i++) {
			var aChannel = currentChannels.item(i);
			if(passenger.home.comet.isChannelRegistered(aChannel.getName())) {
				if(isSubscribe) {
					connection.subscribe(aChannel.getName(), aChannel.getHandler(), aChannel.getHandlerName());
				}else{
					connection.unsubscribe(aChannel.getName(), aChannel.getHandler(), aChannel.getHandlerName());
				}
			}
		}
	} catch(Exception) {
		//alert("error managing comet subscriptions: "+Exception);
	}	
}

/**
 * Initialize the cometD connections for this page (i.e. user notification updates)
 */
initialize = function(){
	//passenger.home.comet.initialize(getPassengerCometConnection(), document.getElementById("userIdDiv").innerHTML);
}

/**
 * Callback method for message on the cometD meta channel.
 * This method will provide error handling for various types of connection messages
 * as well as cleaning up cometD after a maximum number of consecutive errors.
 */
passenger.home.comet.handleConnectionMessage = function(event){
	try {
		var connection = getCurrentActivePassengerCometConnection();
		logDebugMessage("Handling connection message for connection  " + connection);
		
		var state = event.state;
		if(connection != null) {
			//Do not enter this block if we have disconnected.
			if(comet_connection_failure_count >= MAX_CONNECTION_FAILURE_COUNT &&
				(state != connection.DISCONNECTED && state != connection.DISCONNECTING)) {
				
				logDebugMessage("cometd connection is stopping after maximum number of failures");
				
				//We must unsubscribe from the event channel before we disconnect or we will get stuck in an event loop for the disconnect message.
				connection._meta=dojo.event.topic.unsubscribe("/cometd/meta",dojo.lang.hitch(passenger.home.comet, "handleConnectionMessage"));
				//Unsubscribe from all channels.
				passenger.home.comet.manageCometSubscriptions(false);
				//Destroy the connection.
				passenger.home.comet.endPassengerCometConnection();
				cometConnected=false;
				//Alert the user - also unloads page/cometD
				cometErrorPage(comet_connection_failure_count);
				logDebugMessage("cometD reached maximum error count - redirected to error page");
				//Reset the error count.
				comet_connection_failure_count = 0;
				return false;
			}
			if (event.action=="handshake"){
				logDebugMessage(event.action + (event.successful ? " successful" : " FAILED!"));
				if(event.reestablish) {
					logDebugMessage("cometd handshake started becuase of ERROR - reinitializing cache");
					passenger.home.comet.reinitializeCaches();
					passenger.home.comet.manageCometSubscriptions(true);
				}
			} else if (event.action=="connect") {
		        if (event.successful && !cometConnected) {
					logDebugMessage("cometd connection re-established successful");
		        	comet_connection_failure_count = 0;
		        }else if (event.successful && cometConnected) {
					logDebugMessage("cometd connection successful");		        			        	
		        	comet_connection_failure_count = 0;
		        }else if (!event.successful && cometConnected) {      	
		            comet_connection_failure_count++;
					logDebugMessage("cometd connection is failied for number of times: " + comet_connection_failure_count);		        			            
		        }else if (!event.successful && !cometConnected) {
		            comet_connection_failure_count++;
					logDebugMessage("cometd connection is failied for number of times: " + comet_connection_failure_count);		        		            
		        }		        
		        cometConnected=event.successful;
		    } else if (event.action=="publish") {
		    	if(!event.successful){
		    		logDebugMessage("cometd connection publish failed");
		    	}
		    }
		} else {
			logDebugMessage("connection is null");
		}
	}catch(Exception) {
		logDebugMessage("Failure in handle cometd connection message: " + Exception);
	}
}

/**
 * Attach to subscribe method to add subscribed channels to watch list.
 */
passenger.home.comet.mySubscribe = function(channel,objOrFunc,funcName,extra){
	dojo.debug("Subscribed: "+channel+" with "+extra+". Object: "+objOrFunc+" funcName: "+funcName);
	logDebugMessage("cometd subscription for channel: " + channel + " on connection :" + getPassengerCometConnection());	        	
	var newChannel = new passenger.home.comet.cometChannel(channel, objOrFunc, funcName, extra);
	if(!passenger.home.comet.isChannelRegistered(newChannel.getName()))
		channels.add(newChannel);
}

/**
 * Attach to unsubscribe method to remove unsubscribed channels from watch list.
 */
passenger.home.comet.myUnsubscribe = function(channel,objOrFunc,funcName,extra){
	try {
		dojo.debug("Unsubscribed: "+channel+" with "+extra+". Object: "+objOrFunc+" funcName: "+funcName);
		logDebugMessage("cometd un-subscription for channel: " + channel+ " on connection :" + getPassengerCometConnection());	        	
		passenger.home.comet.removeChannel(channel, channels);
	} catch(Exception) {
		//alert("Error: "+Exception);
	}
}

/**
* Method used to reestablish the caches when the user is switched from one web server to other web server
*/
passenger.home.comet.reinitializeCaches = function() {
	try {
		logDebugMessage("cometd connection is reinitializing caches");		        	
		
		var myFormSubmitEvent = passenger.util.getHtmlSubmitEvent();
		var currentChannels = passenger.home.comet.getChannels();
		for(var i=0; i < currentChannels.count; i++) {
			var aChannel = currentChannels.item(i);
			var params = aChannel.getCacheReInitializeParameters();
			for(var j=0; j < params.count; j++) {
				var param = params.item(j).split(":");			
				passenger.util.createHiddenElement(document.reinitializeCache, param[0], param[1]);
			}
		}
//		document.AjaxFormSubmit_reinitializeCache_reinitializeCacheSubmit([myFormSubmitEvent]);
	} catch(Exception) {
		//alert("reinitializeCaches: "+Exception);
	}
}

/**
 * commet channel that keeps the infomration of the registered channel
 */
passenger.home.comet.cometChannel = function (aName, aHandler, aHandlerName, cacheReInitParametersList) {
	try {
		var name = aName;
		var handler = aHandler;
		var handlerName = aHandlerName;
		var cacheReInitializeParameters = cacheReInitParametersList;
		this.getName = function() { return name; }
		this.getHandler = function() { return handler; }
		this.getHandlerName = function() { return handlerName; }
		this.getCacheReInitializeParameters = function() { return cacheReInitializeParameters; }
	} catch(Exception) {
		//alert("Error: "+Exception);
	}
}

/**
 * remove the channel from the list
 */
passenger.home.comet.removeChannel = function (aName, channelList) {
	try {
		for(var i=0; i < channelList.count; i++) {
			var aChannel = channelList.item(i);
			if(aChannel.getName() == aName) {
				channelList.remove(aChannel);
			}
		}
	} catch(Exception) {
		//alert("Error: "+Exception);
	}
}

/**
 * Subscribe to the channel(s)
 */
passenger.home.comet.initialize = function(connection, userId){
	try {
		logDebugMessage("Cometd connection is initializing");
		//General callback method for subscriptions/unsubscriptions
		dojo.event.connect(connection,"subscribe",passenger.home.comet.mySubscribe);
		dojo.event.connect(connection,"unsubscribe",passenger.home.comet.myUnsubscribe);
		// handle cometd failures by listening to the meta channel
		connection._meta=dojo.event.topic.subscribe("/cometd/meta",dojo.lang.hitch(passenger.home.comet, "handleConnectionMessage"));
		//Setup backoff algorithm
		connection._backoffInterval=0;//Initial value
		connection._backoffIncrement=5000;//Increment by this amount each time.
		connection._backoffMax=120000;//Stop incrementing when we hit this value.
		if(userId != null && userId != "" && userId != "-1") {
			connection.startBatch();
			var cacheReloadParams = new dojo.collections.ArrayList();
			cacheReloadParams.add("userId:"+userId);
			connection.subscribe("/userNotification/"+userId+"/user", passenger.home.json, "userRefresh", cacheReloadParams);
			connection.endBatch();
		}
	} catch(Exception) {
		//alert("comet initialize: "+Exception);
	}
}

/**
 * Unsubscribe from the channel(s)
 */
passenger.home.comet.finalize = function(connection, userId){
	try {
		if(userId != null && userId != "" && userId != "-1") {
			logDebugMessage("Cometd connection is finalyzing");
			passenger.home.comet.manageCometSubscriptions(false);		
			channels = new dojo.collections.ArrayList();
			dojo.event.disconnect(connection,"subscribe",passenger.home.comet.mySubscribe);
			dojo.event.disconnect(connection,"unsubscribe",passenger.home.comet.myUnsubscribe);			
			passenger.home.comet.endPassengerCometConnection();		
			dojo.event.topic.destroy("/cometd/meta");		
			
		}
	} catch(Exception) {
		//alert("comet finalize: "+Exception);
	}
}

/**
 * Process JSON messages sent from Comet subscription.
 */
passenger.home.json.userRefresh = function(msg) {
	try {
		logDebugMessage("Cometd user refresh" + msg);
		if(msg.data != null){
			if(msg.data.hasAccess == true){
				if(getPassengerMenuStatus() != "true") {
					passenger.home.loadHeaderAndMenu();
				}
			} else {
				passenger.home.hideHeaderAndMenu();
			}
			var hasMessages = false;
			var hasInvitation = false;
			var hasNetwork = false;
			for(var i=0; i < msg.data.events.length; i++) {
				if(msg.data.events[i] == "message") {
					hasMessages = true;
				} else if(msg.data.events[i] == "session") {
					hasInvitation = true;
				} else if(msg.data.events[i] == "network") {
					hasNetwork = true;
				}
			}
			if(hasMessages || hasInvitation || hasNetwork) {
				document.getElementById(ALERT_DIV_ID).style.display = "block";		
				if(hasMessages) {
					document.getElementById(NEW_MESSAGE_ALERT_ID).style.display = "block";
				}
				if(hasInvitation) {
					document.getElementById(NEW_EVENT_ALERT_ID).style.display = "block";
				}
				if(hasNetwork) {
					document.getElementById(NEW_NETWORK_EVENT_ALERT_ID).style.display = "block";
				}
			}
		}
	} catch ( Exception ) {
		//alert("userRefresh: "+Exception);
	}
}

getHomeViewPort = function(){
	return dojo.html.getViewport();
}

/**
 * Loggs the message in javascript array. 
 * Once the message size reaches a specific limit, the values are sent to server side for logging using an ajax call. 
 * The server call is only made if the debugging is enabled, the debugging can be enable dusing resource bundle
 * After reaching the maximum limit the list is cleared. 
 */
logDebugMessage = function(message) {
	if(enableDebug){	
		if(debugMessages.count == MAX_DEBUG_MESSAGES){
			document.debugMessagesForm.debugMessages.value = debugMessages;
			var myFormSubmitEvent = passenger.util.getHtmlSubmitEvent();
			document.AjaxFormSubmit_debugMessagesForm_debugMessagesFormSubmit([myFormSubmitEvent]);
			debugMessages = new dojo.collections.ArrayList();
		}
		var currentTime = new Date();
		debugMessages.add("Time:" + currentTime.getTime() + " , Message: " + message +"\n");
	}
}

/**
 * Navigates the user to an error page once the maximum number of cometD errors has been reached. 
 */
cometErrorPage = function(numErrs) {
	logDebugMessage("CometD maximum error count reached (current = "+numErrs+" - navigating to error page.");
	document.cometStaleSessionForm.submit();
}

/**
 * A click listener attached to the menu item links in the home page 
 */
passenger.home.handleMenuClick = function() {
	if(document.getElementById) {
		passengerMenuReset();
	}
	this.parentNode.className = 'menuPrimary';
};

/**
 * This method initializes all the links in the menu and attaches listeners to them
 */
passenger.home.attachMenuClickListeners = function() {
	if(document.getElementById) {
		var menuHolder = document.getElementById('menu');
		if(menuHolder) {
			var anchors = menuHolder.getElementsByTagName('a');
			if(anchors){
				for(anchorIndex in anchors) {
					if(anchors[anchorIndex].target && anchors[anchorIndex].target == 'content'){
						anchors[anchorIndex].onclick = passenger.home.handleMenuClick;
					}
				}				
			}
		}
	}
};

/**
 * Reset the menu and don't highlight any tabs
 */
var passengerMenuReset = function() {
	var menuHolder = document.getElementById('menu');
	if(menuHolder) {
		var anchors = menuHolder.getElementsByTagName('a');
		if(anchors){
			for(anchorIndex in anchors) {
			    if(anchors[anchorIndex].parentNode){
			        anchors[anchorIndex].parentNode.className = 'menu';
			    }
			}
		}
	}
};

/**
 * Highlight the menu tab identified by elementId
 */
var highlightPassengerMenuTabById = function(elementId) {
	if(document.getElementById) {
		if(elementId) {
			var element = document.getElementById(elementId);
			if(element && element.parentNode) {
				if(element.parentNode.className != 'menuPrimary') {
					passengerMenuReset();
					element.parentNode.className = 'menuPrimary';
				}
			}
		} else {
			passengerMenuReset();
		}
	}
};

var cleanLytebox = function() {
	try {
		//Whatever the page is, retrieve the LyteFrame and close it, and clear its contents
		if(window.parent && window.parent.document.getElementById) {
			var lyteOverLay = window.parent.document.getElementById('lbOverlay');
			if(lyteOverLay) {
				lyteOverLay.style.display = 'none';
			}
			var lyteBox = window.parent.document.getElementById('lbMain');
			if(lyteBox) {
				lyteBox.style.display = 'none';
				var childNodes = lyteBox.childNodes;
				if(childNodes) {
					var lyteFrame = (childNodes[1]).childNodes[0];
					if(lyteFrame) {
						var lbIframeObj = window.parent.frames['lbIframe'];
						if(lbIframeObj) {
					 		lbIframeObj.document.body.innerHTML = ''; //retrieve the content's body tag and clear it.
						 	var iframeContent = lbIframeObj.contentDocument; // retrieve the LyteFrame's contentDocument object
					 		if(iframeContent) {
					 			iframeContent.getElementsByTagName('body')[0].innerHTML = ''; //retrieve the content's body tag and clear it.
					 			lbIframeObj.document.body.innerHTML = '';
					 		}
					 	}
					}
				}
			}
		}
	} catch (exception) {
		//Do nothing
	}
};
