/* ***************************************************************
 *****************************************************************
 ***                                                            **
 ***    (C)Copyright 2007-2008, American Megatrends Inc.        **
 ***                                                            **
 ***                All Rights Reserved.                        **
 ***                                                            **
 ***        6145-F, Northbelt Parkway, Norcross,                **
 ***                                                            **
 ***        Georgia - 30071, USA. Phone-(770)-246-8600.         **
 ***                                                            **
 *****************************************************************
 *****************************************************************
 *****************************************************************
 *
 * Filename: home_imp.js
 *
 * File description: Implementation for home page
 *
 * Author:Manish Tomar <manisht@ami.com>
 *	   	  Rufina Mercelene. S <rufinamercelenes@amiindia.co.in> 
 *
 ************************************************************** */
 
/*
 *  Steps followed in beginning
	1. login page
	2. create session
	3. load wsdls
	4. check password
	5. session page
	6. main page
 */

gFrameTreeLoaded=false;
var gRefreshImageID;

var wsdlObj = null;
var wsmanURI = null;

var WSMAN_OP_SUCCESS = "0"; 	// taking it from pageinc.js as including that will unnecessarily include many files
var WSMAN_OP_TRUE = "1";
var WSMAN_OP_FALSE = "0";

function doInit() {

	debugOut("home-- doInit");
	
	loadFrames();

	wsmanURI = /^https?:\/\/[^\/]*\//.exec(document.URL)[0] + "wsman";
	
	// extract session id from window.location.hash if it is there
	// It'll be of "http://imm#sessionid:01a36e27-b840-44d8-8b37-e8fe3563c4aa"
	if (top.window.location.hash != "" && top.window.location.hash != "#") {
		var begin = "sessionid:".length + 1;
		top.gSessionID = window.location.hash.substring(begin);
	}
	
	// session_id cookie may be "none" which represents no session
	var sessionid = eExt.readCookie("session_id");
	sessionid = sessionid == "none" ? undefined : sessionid;
	
	// Load WSDSLs if session is already there i.e. during home page refresh
	if (top.gSessionID || sessionid) {
		debugOut("home-- session id: " + (top.gSessionID || sessionid));
		handleFreedCodeCase();
		
		// setup username from session or cookie
		if (!top.LoggedUserID) {
			getUsername();
		}
		
        loadWSDLs(["http://www.ibm.com/iBMC/sp/Monitors",
                   "http://www.ibm.com/iBMC/sp/Tasks",
                   "http://www.ibm.com/iBMC/sp/iBMCControl",
                   "http://www.ibm.com/iBMC/sp/iBMCNWProtocol",
                   "http://www.ibm.com/iBMC/sp/Scalability",
                   "http://www.ibm.com/iBMC/sp/ServiceAdvisor"
                   ], 
                   function() {loadInMainFrame("page/frameMain.html", true);}
        	);   
	}
	else {
		// session not there; show login page
		loadInMainFrame("page/login.html");
		debugOut("loading login page");
	}
	
	//On page refresh/load, hostname is retrieved from server
	refreshHostname();
}

function getUsername() {
	top.SendGETRequest("/username", function(resp) {
		if (!resp.exception) {
			top.LoggedUserID = resp;
		}
	});
}

function refreshHostname() {
	top.SendGETRequest("/hostname.txt?time=" + new Date().getTime(), recvHostname);
}

function recvHostname(data) {
	if(!data.exception) {
		//Display hostname in the titlebar
		document.title = data.trim();
	} else {
		document.title = eLang.getString('global_strings', "STR_PROJECT_NAME");
	}
}

// sometimes callback stored in wsman lib is inconsistent as it is from a page that doesn't exist anymore
// following is an attempt to handle this situation
function handleFreedCodeCase() {

	wsman.beforesend = function(soaptext) {
		// a way do not handle right now
		if (top.NoFreedCodeCase) {
			return undefined;
		}
		// call from config summary page, instead of storing unique soapid, return a common id 
		// which will be used later to realize that the response is for conf summary page
		if (top.CallFromConfigSummary) {
			top.CallFromConfigSummary = undefined;
			return "cf";
		}
		// call from mainframe page, generate unique id and return
		else if (!frames.frameMain.document.soapid) {
			frames.frameMain.document.soapid = new Date().getTime().toString();
			debugOut("handleFreedCode--- req soapid: " + 
			 	 frames.frameMain.document.soapid); 
		}
		return frames.frameMain.document.soapid;
	}

	wsman.afterrecv = function(id, resp) {
		// call from config summary or id's match
		top.debugOut("handleFreedCode--- resp soapid: " + id + "; resp.status: " + resp.status);

		// session expired 
		if (resp.status == 404 || resp.status == 403) {
			top.debugOut("wsmanrecv--- loading sessionexp as no session");
			top.loadInMainFrame && top.loadInMainFrame("/page/sessionexp.html");
			return;
		}

		// do config summary / id matching
		if (top.NoFreedCodeCase || id == "cf" || id == frames.frameMain.document.soapid) {
			return true;
		}
		else {
			errorOut("Couldn't find associated main frame having the callback. not handling soap resp");
			return false;
		}
	}
}

// loads the WSDLs synchronously
function loadWSDLs(wsdls, recv) 
{
	var i = 0;
	
	// wsdls already loaded. 
	if (top.wsdlsLoaded) {
		debugOut("home-- wsdls already loaded");
		recv();
		return;		// Not having this was causing wsdl get to be sent again
	}
	
	debugOut("home-- loading " + wsdls[i]);
	wsman.getWSDLFromURI(wsdls[i] + "/wsdl", wsmanURI, function(resp) {
		try {
			debugOut("home-- got resp for " + wsdls[i]);
			wsdlRecv(wsdls[i], resp);
			debugOut("home-- loaded " + wsdls[i]);
		}
		catch (e) {
			alert("Error handling wsdl " + wsdls[i] + ": " + e.message);
			return;
		}
		if (++i < wsdls.length) {
			wsman.getWSDLFromURI(wsdls[i] + "/wsdl", wsmanURI, arguments.callee);
		}
		// loaded all the wsdls
		else {
			top.wsdlsLoaded = true;
			debugOut("home-- completed loading wsdls");
			recv();
		}
	});
}

// called after receving the wsdl node
function wsdlRecv(resURI, wsdlNode)
{
	if (wsdlNode.exception) {
		throw wsdlNode;
	}

	//debugOut("receved wsdl", wsdlText);
	wsdlObj = new wsman.WSDL(wsdlNode);
	wsdlObj.parse();

	wsdlObj.serviceEndpoint = wsmanURI;

	// creates functions for all operations
	for (var i = 0; i < wsdlObj.operations.length; i++) {
		var op = wsdlObj.operations[i];

		// assuming that all functions will have blank input 
		// and no selector set
		var createOp = function(oper, resourceURI) {
			if (window[oper.name]) {
				errorOut("\"" + op.name + "\" operation is already added. " +
							"Another operation with same name will overwrite previous one.");
			}
			window[oper.name] = function(ip, recv) {
				//var ip = oper.getSampleInputObject();
				oper.invoke(resourceURI, null, ip, recv);
			}
		}

		// creating function for "op" custom operation and adding to this window
		createOp(op, resURI);

		//console.debug("loaded op: " + op.name);
	}
}

// checks password status; whether it is expired or is required
gPWD_STATUS_EXPIRED = "1";
gPWD_STATUS_REQUIRED = "2";
function checkPasswd() 
{
	top.GetPasswordStatus({}, recv);
	debugOut("checkPasswd--- called getpwdstat");
	
	function recv(resp) {
		debugOut("checkPasswd--- got resp");
		if (resp.exception) {
			errorOut("ERROR: Could not find status of password: " + resp.message);
		}
		// password has expired
		if (resp.Status == gPWD_STATUS_EXPIRED || resp.Status == gPWD_STATUS_REQUIRED) {
			top.PasswordStatus = resp.Status;
			top.gBlankPasswordAllowed = (resp.BlankPasswordAllowed == WSMAN_OP_TRUE);
			top.loadInMainFrame("page/ibmccontrol_loginchangepwd.html");
			debugOut("checkPasswd--- passwd needed");
		}
		// password is all fine. login in cim
		else {
			var ports = {
				"http:": 80,
				"https:": 443
			};
			var port = location.port ? location.port : ports[location.protocol];
			top.UserLogOniBMC({DestIPAndPort:"[" + location.hostname + "]" + ":" + port,
					LogInForcefully:WSMAN_OP_FALSE}, recvLogon);
			//simulateLogin();
			debugOut("checkPasswd--- passwd fine; logging user");
		}
	}
}

function changePwd(newPwd) {
	top.ChangePassword({Using: "1",		// changing via PAM
				NewPassword:newPwd}, 
				recvChgPwd);
	top.frames.frameMain.displayChangePasswordProgress("Changing password...");
	top.debugOut("called changepwd");
	
	function recvChgPwd(resp) {
		top.frames.frameMain.hideChangePasswordProgress();
		top.debugOut("recvChgPwd-- hid progress");
		if (resp.exception) {
			alert("Could not change password. Possible reasons are:\n" + 
				  " 1. Password did not contain both alphabetic and numeric characters\n" +
				  " 2. Password length was too short\n" +
				  " 3. Password entered has been used before\n" +
				  " Please try again"
				 );
		}
		// password changed successfully; now login in cim
		else {
			top.debugOut("recvChgPwd-- password changed successfully; now login in cim");
			top.UserLogOniBMC({DestIPAndPort:"[" + location.hostname + "]" + ":" + (location.port || "80"),
						  		LogInForcefully:WSMAN_OP_FALSE}, recvLogon);
			top.frames.frameMain.displayChangePasswordProgress("Password changed. Logging in...");
		}
	}
}

// called after receiving logon response
function recvLogon(data) {

	hideLoginWait();

	// login custom op not successful
	if (data.exception || data.UserLogOniBMCResponse != WSMAN_OP_SUCCESS) {
		alert("Error logging user: " + data.message || "Reasons unknown");
		return;
	}
	debugOut("recvLogon--- successfully logged; going to load session page");

	// store session timeout in top wnd which will be used by session pages
	top.SessionTimeout = data.SessionTimeout;

	// logged in successfully, load session page
	top.LoggedUserID = data.UserIDAndIP;	// when login successful, only username will come
	
	// Store the username in cookie as it is needed during home page refresh
	if (!top.gSessionID) {
		eExt.createCookie("username", top.LoggedUserID);
	}
	
	
	top.iBMCSystemName = data.SystemName;
	top.iBMCDisplayName = data.DisplayName;

	setTreeSerialNum(top.iBMCSystemName);

	// load session page
	loadInMainFrame("page/session.html");
	top.debugOut("loaded session page");
}

// Simulates calling UserLogoniBMC. useful when this custom op is not working
//#TestFunction
function simulateLogin() {
	var resp = {
		UserLogOniBMCResponse: WSMAN_OP_SUCCESS,
		SessionTimeout: "0",
		UserIDAndIP: "manish"
	};
	window.setTimeout(function () {
		recvLogon(resp);
	}, 1000);
}

// will invoke login custom op to inform that user has logged in
//#InterfaceFunction
function login(username, password)
{
	// first create session
	SendPOSTRequest("/session/create", username + "," + password,
					[], recvSession);
	debugOut("create session req sent");
	showLoginWait();
	
	function recvSession(resp) {
		debugOut("received create session response");
		if (resp.exception) {
			alert("Could not create session: " + resp.message);
			return;
		}
		// user is authenticated; valid session created
		if (resp.substr(0,2) == "ok") {
			
			// Is valid session_id (non-none) cookie received?
			if (!eExt.readCookie("session_id") || eExt.readCookie("session_id") == "none") {
				// Session cookie not there, use custom http header based session 
				// extract session id and store it in top window
				top.gSessionID = resp.substr(3);
				top.window.location.hash = "#sessionid:" + top.gSessionID;
				debugOut("home-- user authenticated; session id: " + top.gSessionID);
			}
			
			// loads wsdls and then call check password
			debugOut("home-- loading wsdls and checking password");
			loadWSDLs(["http://www.ibm.com/iBMC/sp/Monitors", 
					   "http://www.ibm.com/iBMC/sp/Tasks",
					   "http://www.ibm.com/iBMC/sp/iBMCControl",
					   "http://www.ibm.com/iBMC/sp/iBMCNWProtocol",
					   "http://www.ibm.com/iBMC/sp/Scalability",
					   "http://www.ibm.com/iBMC/sp/ServiceAdvisor"
					  ], checkPasswd);	// check the password status	
		}
		// unauthorized user; could not create session
		else if (resp == "unauthorized") {
			// display user about invalid username/password
			hideLoginWait();
			alert("Invalid username/password. Please try again");
			//top.location.reload();
			top.frames['frameMain'].location.reload();
			top.frames['frameMain'].clearCredentials();
		}
		// user is locked; display locked page
		else if (resp == "locked") {
			debugOut("home-- user locked");
			loadInMainFrame("page/locked.html");
		}
		else if (resp == "existing") {
			debugOut("home-- existing session. reloading home");
			top.location.reload();
		}
	}
}

function showLoginWait(text) {
	debugOut("showlogin wait called");
	top.document.getElementById("frmSet").cols = "0,*";
	//top.frames['frameMain'].showWait(true, "Please wait while you are logged in...");
	top.frames['frameMain'].document.getElementById("_btnLogin").disabled = true;
	top.frames['frameMain'].document.getElementById("_btnLogin").value = "Logging in..";

}

function setTreeStatusImage(image)
{
	top.debugOut("setTreeStatusImage inside; src: " + image);
	top.frames.frameTree.g_imgStatusSrc = image;
	top.frames.frameTree.updateStatusIcon();
}

function showLoading() {
	debugOut("showloading wait called");
	top.document.getElementById("frmSet").cols = "0,*";
	top.frames['frameMain'].document.writeln(
	'<div id="WaitDiv" style="visibility:visible; position:absolute; \
			 left:90px; top:100px; width:600px; height:69px; \
			 z-index:2; background-color: #FFFFFF; layer-background-color: \
			 #FFFFFF; border: 1px none #000000;">	\
		<table width="100%" height="68"  border="2" cellpadding="0" cellspacing="0" bordercolor="#666666">	\
		<tr>	\
			<td><div align="center"><img src="res/loader.gif" align="absmiddle">	\
				<span id="WaitMsg">Loading...</span></div></td>	\
		</tr>	\
		</table>	\
	</div>');
}

function hideLoginWait() {
	// remove "please wait.." 
	top.frames['frameMain'].showWait(false);
	try {
		top.frames['frameMain'].document.getElementById("_btnLogin").disabled = false;
		top.frames['frameMain'].document.getElementById("_btnLogin").value = "Login";
	} catch (e) {
	// The login may not be there; Do nothing. just continue 
	}
}

// starts a new session by setting the cookie with given timeout and going to main page
// called after click on "continue" or "start new session" in session pages
function startSession()
{
	// get the timeout from combo box if user selected timeout
	var timeoutStr = "0";
	if (top.SessionTimeout == "-1") {
		var cmb = top.frames.frameMain.document.getElementById("cmbSession");
		timeoutStr = cmb.options[cmb.selectedIndex].value;
	}
	else {
		timeoutStr = parseInt(top.SessionTimeout, 10) * 60;
	}

	// if user selected "no timeout" then internally create a timeout of 2 mins 
	// and start pinging every 45 seconds to avoid zombie sessions.
	if (timeoutStr == "0") {
		timeoutStr = new Number(2 * 60).toString();
		startPinging(45);
	}
	
	// post /session/activate to set the inactive timeout
	top.SendPOSTRequest("/session/activate", "session_expiry=" + timeoutStr, [], recvLightyLogin);
	top.frames.frameMain.showWait(true, "Please wait while session is established...");

	// called on response of /session/activate
	function recvLightyLogin(resp) {
		top.frames.frameMain.showWait(false);
		
		// coming from welcome page; just goto mainframe
		debugOut("from welcom page after resp of /session/activate, loading main page");

		loadInMainFrame("page/frameMain.html", true);
	

	}
}

// starts pinging on given interval in seconds
function startPinging(interval)
{
	function recv() { }

	function ping() {
		top.SendGETRequest("/page/blank.html?" + new Date().getTime(), recv);
		top.debugOut("sent ping to /blank.html");
	}

	top.gPingId = top.setInterval(ping, interval * 1000);
	top.debugOut("started ping interval");
}

function loadInMainFrame(path, showtree) {
	if (path == "page/frameMain.html") {
		handleFreedCodeCase();
	}
	// already logged in, load main page
	top.document.getElementById("FRAMEMAIN").src = top.path + path;
	 //show the tree
	top.document.getElementById("frmSet").cols = showtree ? "200,*" : "0,*";
}


// Go and get all summary data and display in a popup
function displayCfgSummary(link)
{
	var w = window.open("ibmccontrol_configsummary.html"+link, 
						"forcedOpener",
						"resizable=yes, location=no, menubar=no, scrollbars=yes, titlebar=no, width=450, height=600");
	w.focus();
}


// log off implementation
// delete the cookie, call logoff custom op & and goto logoff.html
function logoff()
{
	// display logoff wait msg on main frame
	top.frames['frameMain'].document.open();
	top.frames['frameMain'].document.writeln(
			'<div id="WaitDiv" style="visibility:visible; position:absolute; \
					 left:90px; top:100px; width:600px; height:69px; \
					 z-index:2; background-color: #FFFFFF; layer-background-color: \
					 #FFFFFF; border: 1px none #000000;">	\
		  		<table width="100%" height="68"  border="2" cellpadding="0" cellspacing="0" bordercolor="#666666">	\
				<tr>	\
			  		<td><div align="center"><img src="../res/loader.gif" align="absmiddle">	\
			  			<span id="WaitMsg">Please wait while you are logged off...</span></div></td>	\
				</tr>	\
		  		</table>	\
		</div>');
	top.frames['frameMain'].document.close();
	
	// this will work only if logoff is called onclick of Logoff link. it will
	// not work if we try to logoff while the page is loading during session timeout
	//top.frames['frameMain'].showWait(true, "Please wait while you are logged off...");
	
	// for testing
//	setTimeout(function(resp) {
//		top.frames['frameMain'].showWait(false);
//		eExt.eraseCookie("session");
//		top.location.href = top.path + "page/logoff.html";
//	}, 500);	

//------- Not calling logoffibmc as it is called during deactivate
//	// call logoffibmc
//	debugOut("before calling logoffibmc");
//	top.UserLogOffiBMC({}, recvLogoffiBMC);
//	function recvLogoffiBMC(resp) {
//		debugOut("before calling /session/deactivate");
//		SendPOSTRequest("/session/deactivate", "", [], recv); 
//	}

	debugOut("before calling /session/deactivate");
	SendPOSTRequest("/session/deactivate", "", [], recv); 

	function recv(resp) {
		debugOut("inside resp of deactivate. going to logoff html: " + resp);
		// erase all cookies
		loadInMainFrame("page/login.html");
	}
}

// cleans up stuff when loading login page
function cleanup()
{
	// hide login progress 
	hideLoginWait();

	// clear stored sessionid
	top.gSessionID = undefined;
	
	// set Default radio Selection as Java Client in remote control page
	top.remoteSelection = "radioJava";
	
	// This is required as there could be other sessions in another tab using
	// session_id cookie. If they don't see any cookie at all, they'll display
	// popup for username/password because server would respond with 401 unauthorized
	// for WSMAN requests
	eExt.createCookie("session_id", "none");
	
	top.window.location.hash = "#";
	eExt.eraseCookie("username");

	// remove refresh image timer
	window.clearInterval(gRefreshImageID);

	// stop pinging
	if (top.gPingId) {
		top.clearInterval(top.gPingId);	
	}
	top.debugOut("stopped pinging");
}

function setTreeSerialNum(text)
{
	function set() {
		if (top.frames.frameTree && top.frames.frameTree.document.getElementById("txtLocalSer")) {
			top.frames.frameTree.document.getElementById("txtLocalSer").innerHTML = text;
		}
		else {
			setTimeout(set, 500);
		}
	}
	set();
}

//Start Pinging when firmware upgrade process called
function firmwareStartPing() {

	top.gFmPingId = setInterval(recvFirmwareUpdate, 300);
	
}

function recvFirmwareUpdate() {
	try{
		top.frames.frameMain.document;
	} catch(e) {
		// clear interval 
		top.clearInterval(top.gFmPingId);
		loadInMainFrame("/page/uploadfail.html", true);
	}	
}

String.prototype.trim = function() 
{
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

