/*
 *------------------------------------------------------------------
 * framework.js
 *
 * Copyright (c) 2003-2006 by cisco Systems, Inc.
 * All rights reserved.
 *------------------------------------------------------------------
 */

// This script should only be included in the top frameset.

// Each page loaded in the mainFrame should 
// set the buttons it needs
// set the FAQ its list, if the page does not have any specific FAQ
// then it should pass an empty list, so that a generic set of FAQs
// will be populated.

// TBD: 
// Finalize whether each wizard step should set its buttons ?
// One way is to let the next step and previous step handlers in 
// each wizard to set the buttons needed.
// Other way is to have a centralized location top.nextStep() and top.previousStep()
// In this case the nextStep and previousStep handlers should return
// a value that can be used to find out whether

// The constants to identify the wizrd steps
var WIZARD_FIRST_STEP = 1;
var WIZARD_STEP		  = 2;
var WIZARD_LAST_STEP  = 3;

// different button constants
var APPLY_BTN	= 1;
var CANCEL_BTN	= 2;
var HELP_BTN	= 4;
var REFRESH_BTN	= 8;
var BACK_BTN	= 16;
var NEXT_BTN	= 32;
var FINISH_BTN	= 64;
var DONE_BTN	= 128;

//button sets for view only pages
var READONLY_BTNS = REFRESH_BTN | HELP_BTN;
// button sets for configurable pages
var CONFIG_BTNS	= APPLY_BTN | CANCEL_BTN | REFRESH_BTN | HELP_BTN;

// buttons set for wizards
var INITSTEP_BTNS = NEXT_BTN | CANCEL_BTN;
var LASTSTEP_BTNS = BACK_BTN | FINISH_BTN | CANCEL_BTN;
var WIZDSTEP_BTNS = BACK_BTN | NEXT_BTN | CANCEL_BTN;

// variable used to find polling status.
var pollBlocked = false;
var pollBlockReason = "";

// Will get invoked from the topFrame every one minute
// refresh the content in the mainFrame(content frame) and the FPV
function onAutoRefresh() {	// public
	if(pollBlocked) return;
	if(mainFrame.onRefresh) {
		var canRefresh = true;
		if(mainFrame.canAutoRefresh) {
			canRefresh = mainFrame.canAutoRefresh();
		}
		if(canRefresh == true)
			mainFrame.onRefresh()
	}
	if(topFrame.onRefresh) {
		topFrame.onRefresh();
		discoveryFrame.location.href = "discover.shtml";
	}
	if(top.healthFrame != null)
		healthFrame.location.href = "monitordata.shtml";
}

// Will refresh the content in the mainFrame(content frame) and the FPV
function refreshMainFrame() {	// private
	if(pollBlocked) return;
	if(mainFrame.onRefresh)
		mainFrame.onRefresh()
	else
		mainFrame.document.location.reload(true);
	if(topFrame.onRefresh) {
		topFrame.onRefresh();
		discoveryFrame.location.href = "discover.shtml";
	}
	if(top.healthFrame != null)
		healthFrame.location.href = "monitordata.shtml";
}

// Will refresh the FPV only.
function refreshFPV() {
	if(pollBlocked) return;
	if(top.topFrame && top.topFrame.onRefresh) {
		top.topFrame.onRefresh();
		top.discoveryFrame.location.href = "discover.shtml";
	}
}

// Will refresh the monitordata and discovery only.
function refreshHealthAndFPV() {
	if(pollBlocked) return;
	if(top.topFrame && top.topFrame.onRefresh) {
		top.topFrame.onRefresh();
		top.discoveryFrame.location.href = "discover.shtml";
	}
	if(top.healthFrame != null)
		healthFrame.location.href = "monitordata.shtml";
}

// will apply the changes made in the mainFrame to the device
// will call the onConfigure() method in the mainFrame page.
function applyMainFrame() {		// private
	if(mainFrame.onConfigure) {
		mainFrame.onConfigure();
	}
	else {
		alert(top.resourceFrame.re_frmWrk_ErrMsgNoApply); //('No handler available for Apply.');
	}
}

// will cancel the modification done in the config page
// will call the onCancel() method in the mainFrame page.
function cancelMainFrame() {	//private
	if(mainFrame.onCancel) {
		mainFrame.onCancel();
	}
	else {
		alert(top.resourceFrame.re_frmWrk_ErrMsgNoCancel); //('No handler available for Cancel.');
	}
}

// Function to invoke print from the Main Frame
function printMainFrame() {
	if(top.mainFrame.printPage) {
		top.mainFrame.printPage();
	} else {
		top.mainFrame.focus();
		window.print();
	}
}

// will launch the help window 
// Will launch the help for the active page in a new window
// The help tag will be obtained from the active page, if tag is not passed.
// The help tag will be the filename with or with out anchor eg. legend.htm#ports, legend.htm
var helpwindow = null;
function showHelp(tag, focusWindow) {	// private
	var helpTag = null;
	// The unique id for the help window, will be created using the mac address
	var windowId;
	if(focusWindow == null) focusWindow = true;

	if(tag != null) {
		helpTag = tag;
	} else if(mainFrame.getHelpTag) {
		helpTag = mainFrame.getHelpTag();
	} else {
		alert(top.resourceFrame.re_frmWrk_ErrMsgNoHelp); //('No Help Available');
		return;
	}
	// store the helptag in the dataCache
	dataCache.put("HELPTAG", helpTag);

	if(helpTag != null || helpTag != "") {
		var devices = getDeviceList();
		if((devices != null) && (devices.length > 0)) {
			windowId = devices[0].macAddress + "_help";
			windowId = windowId.replace(/:/g, "_");
		} else {
			windowId = "_blank";
		}

		var _width = 500, _height = 500;

		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			_width = window.innerWidth;
			_height = window.innerHeight;
		} else {
			if( document.documentElement &&
			( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
				//IE 6+ in 'standards compliant mode'
				_width = document.documentElement.clientWidth;
				_height = document.documentElement.clientHeight;
			} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
				//IE 4 compatible
				_width = document.body.clientWidth;
				_height = document.body.clientHeight;
			}
		}
		_width *= 0.7;
		_height *= 0.7;
		_width = Math.ceil(_width);
		_height = Math.ceil(_height);

                if(!dataCache.get("SETUPMODE") && !dataCache.get("RECOVERYMODE"))
                {
                        if(helpTag != "")
                        {
                                if(helpwindow == null || helpwindow.closed) {
        //                              helpwindow = window.open(helpTag, windowId, "toolbar=no,status=no,scrollbars=yes,resizable=yes,outerWidth=" + _width + ",outerHeight=" + _height + ",width=" + _width + ",height=" + _height);
                                        helpwindow = window.open("/help/help.htm", windowId, "toolbar=no,status=no,scrollbars=yes,resizable=yes,outerWidth=" + _width + ",outerHeight=" + _height + ",width=" + _width + ",height=" + _height);
                                } else {
                                        helpwindow.displayHelp(helpTag);
                                }
                                
                                try {
	                                	if(!focusWindow) {
		                                	helpwindow.blur();
		                                	window.focus();
		                                }
	                                	else if(focusWindow)
                                        	helpwindow.focus();
                                } catch(e){
                                }
                        }
                }
                else if(dataCache.get("SETUPMODE")) {
	                	if(helpwindow == null || helpwindow.closed) {
			                helpwindow = window.open("/help/xsetup_help.htm", windowId + "xsetup", "toolbar=no,status=no,scrollbars=yes,resizable=yes,outerWidth=" + _width + ",outerHeight=" + _height + ",width=" + _width + ",height=" + _height);
	                	}
	                	else {
		                	helpwindow.document.location.reload(true);
		                	//helpwindow.setHelpPage(top.dataCache.get("LANGUAGE_CODE"));
	                	}
	                	
	                	try {
		                		if(!focusWindow) {
			                		helpwindow.blur();
			                		window.focus();
			                	}
		                		else if(focusWindow)
		                			helpwindow.focus();
		                } catch(e){}
                        /*var helpwindow2 = window.open("/help/xsetup_help.htm", windowId + "xsetup", "toolbar=no,status=no,scrollbars=yes,resizable=yes,outerWidth=" + _width + ",outerHeight=" + _height + ",width=" + _width + ",height=" + _height);
                        if(helpwindow2)
                                        helpwindow2.focus();*/
                }
				else if(dataCache.get("RECOVERYMODE")) {
					helpwindow = window.open("/help/recover_help.htm", windowId + "recover", "toolbar=no,status=no,scrollbars=yes,resizable=yes,outerWidth=" + _width + ",outerHeight=" + _height + ",width=" + _width + ",height=" + _height);
					try {
						if(!focusWindow) {
							helpwindow.blur();
							window.focus();
						}
						else if(focusWindow)
							helpwindow.focus();
						} catch(e){
						}
				}
		
	}	
	
}

// return the helpTag for which the help dialog is opened
// This method is the call back used by the Help farmework (helpframework.js) 
// to obtain the helpTag(filename).
function getActiveHelpTag() {
	return dataCache.get("HELPTAG");
}

// function that will take care of moving to the next step of wizard
// will call the onNextStep() in mainFrame
// onNextStep() method should set the necessary buttons for the next step.
function nextStep() {	// private
	if(mainFrame.onNextStep) {
		mainFrame.onNextStep();
	}
	else {
		alert(top.resourceFrame.re_frmWrk_ErrMsgNoNext); //('No handler available for Next.');
	}
	return;
}

// function that will take care of moving to the previous step of wizard
// will call the onPreviousStep() in mainFrame
// onPreviousStep() method should set the necessary buttons for the next step.
function previousStep() {	// private
	if(mainFrame.onPreviousStep) {
		mainFrame.onPreviousStep();
	}
	else {
		alert(top.resourceFrame.re_frmWrk_ErrMsgNoBack); //('No handler available for Back.' );
	}
	return;
}

// function that will take care of applying the configuration in wizard
// will call the onConfigure() in mainFrame
function wizardFinish() {	// private
	if(mainFrame.onFinish) {
		mainFrame.onFinish();
	}
	else {
		alert(top.resourceFrame.re_frmWrk_ErrMsgNoFinish); //('No handler available for Finish.');
	}
}

// Will update the faq links on the top right corner of top frame.
// faqList should be a list of FAQ objects.
function setFaq(faqList) {	// public

	if(faqList == null) {
		faqList = dataCache.get("CURRENTFAQS");
	}
	if(faqList == null || faqList.length < 0)
		return false;
	dataCache.put("CURRENTFAQS", faqList);
	if(topFrame.setFaq) {
		topFrame.setFaq(faqList);
	}
}

// Will update the faq combo box with the default set of FAQs
// As of now the FPV related FAQ is the only FAQ which is to
// be displayed everytime, and the default one. This will be
// added by the topbanner.htm. So pass an empty list.
function setDefaultFaq() { // public
	setFaq(new Array());
}

// Will take to the selected FAQ
// The value of the faq item should be the helpTag, which will be the
// help filename with anchor if needed. eg. index.htm#ports
function showFAQ(faq) {	// private
	if(faq.value && faq.value != "no_action"){}
}

// Will show/hide the bottomFrame according to the value of the parameter show
// Will show the frame if show is true, otherwise hide.
function showButtonFrame(show) {
	if(!top.contentFrameset || !top.contentFrameset.rows)
		return;
	if(show === true) {
		top.contentFrameset.rows = "*,40";
	} else {
		top.contentFrameset.rows = "*,0";
	}
}

// will set the buttons in the bottom panel.
// buttonSet will be an integer where each bit will stand for a button
// The following values can be passed as the value to setButtons
// READONLY_BTNS
// CONFIG_BTNS
// INITSTEP_BTNS
// LASTSTEP_BTNS
// WIZDSTEP_BTNS
function setButtons(buttonSet) {	// public
	if(buttonSet == null) {
		buttonSet = dataCache.get("CURRENTBUTTONS");
		if(buttonSet == null)
			buttonSet = READONLY_BTNS;
	}
	else {
		dataCache.remove("OK_BUTTON_NAME");
	}

	dataCache.put("CURRENTBUTTONS", buttonSet);

	if(bottomFrame.setButtons)
		bottomFrame.setButtons(buttonSet);
}

// renameOkButton will change the label of the "Submit" button
// to the label specified.
function renameOkButton(label) {
	dataCache.put("OK_BUTTON_NAME", label);
	setButtons(null);
}

// will set the specified page in the mainFrame
// menuPage is the page needs to be displayed in the mainFrame
function setmainFramePage(menuPage) {	// public
	if(menuPage != null) {
		// window.open is safer than setting the location directly.
		window.open(menuPage, "mainFrame");
	}
}

// This will expand and make the menu items selected and
// sets the page in the meinFrame accordingly.
function selectMenu(menuItem, loadURLFlag) {		// public
	if(top.leftFrame && leftFrame.selectMenu) {
		leftFrame.selectMenu(menuItem, loadURLFlag);
	}
}

// This method will disable the menu system [Menu and Toolbar].
function freezeMenu(reason) {
	if(top.leftFrame && leftFrame.freezeMenu) {
		leftFrame.freezeMenu(reason);
	}
	if(top.toolbarFrame && toolbarFrame.freezeToolbar) {
		toolbarFrame.freezeToolbar(reason);
	}
}

//This method will enable the menu system [Menu and Toolbar]
function unFreezeMenu() {
	if(top.leftFrame && leftFrame.unFreezeMenu) {
		leftFrame.unFreezeMenu();
	}
	if(top.toolbarFrame && toolbarFrame.unFreezeToolbar) {
		toolbarFrame.unFreezeToolbar();
	}
}

// This is method is used to stop the FPV and feature refresing
// when software upgrade is in progress.
function blockPolling(reason) {
	pollBlocked = true;
	pollBlockReason = reason;
}

function unBlockPolling(reason) {
	pollBlocked = false;
}

function notifyBrowserClose() {
	if(top.mainFrame && top.mainFrame.getRedirectStatus && top.mainFrame.getRedirectStatus()){
		return;
	}
	if(top.mainFrame && top.mainFrame.getUpdateStatus && top.mainFrame.getUpdateStatus()) {
		var msg = top.resourceFrame.re_frmWrk_ConfMsgWindowClose; //"There are unsaved changes on the page.";
		return msg;
	}	
}

function notifyStackMemberSelection(member) {
	toolbarFrame.init();
	if(top.mainFrame && mainFrame.onStackMemberSelection) {
		if(mainFrame.getUpdateStatus && mainFrame.getUpdateStatus("onStackMemberSelect")) { //the param is a fix for foxhound xsetup
			var msg = top.resourceFrame.re_frmWrk_ConfMsg1; //"Warning:\n\nThere are unsaved changes on the page.\n\nClick OK to save the changes or Cancel to discard and continue.";
			if(confirm(msg)) {
				top.mainFrame.onConfigure();
				return;
			}
		}
		mainFrame.onStackMemberSelection(member);
	}
	if(top.leftFrame && top.leftFrame.onStackMemberSelection) {
		top.leftFrame.onStackMemberSelection();
	}
}

// Can be used to redirect the window to a new IP address
function redirectToNewIP(newIP, timeout) {
	if(newIP == null || newIP == "")
		newIP = dataCache.get("NEW_IP");
	else
		dataCache.put("NEW_IP", newIP);

	if(newIP != null && newIP != "") {
		if(timeout == null) {
			window.location = "http://" + newIP + "/";
		}
		else if(!isNaN(timeout)) {
			setTimeout('redirectToNewIP();', timeout);
		}
	}
}

// the object which holds the data.
// similar to a hash table.
var dataCache = new HashTable();

// create a hash table object
function HashTable() {		// public
	this._globalHash = new Array();
	// public methods			syntax
	this.put = _put;			// put(key, value), returns true if adds to hash table
	this.get = _get;			// get(key), returns the value if key is found, otherwise null
	this.remove = _remove;		// remove(key), returns true if removed, otherwise false.
	this.size = _size;			// size(), returns the number of not null items in the hast
	this.getKeys = _getKeys;	// getKeys(), returns the non null keys in the hash
	this.clear = _clear;		// clear(), will clear the key value pairs in hash
}

// the function will add a key value pair to the global hash.
// the key should be a string object 
// the dataObj can be of any type
function _put(key, dataObj) {		// private
	if(key != null) {
		if(typeof(key) == 'string') {
			this._globalHash[key] = dataObj;
			return true;
		}
	}
	return false;
}

// return the value stored in the hash
// key should be a String type
function _get(key) {		// private
	if(key != null) {
		if(typeof(key) == 'string') {
			if(this._globalHash[key] != null) {
				return this._globalHash[key];
			}
		}
	}
	return null;
}

// removes the data stord in the hash with the key
// key should be of type String
function _remove(key) {		// private
	if(key != null) {
		if(typeof(key) == 'string') {
			if(this._globalHash[key]) {
				this._globalHash[key] = null;
				return true;
			}
		}
	}
	return false;
}

// returns the number of non null items in the hash
function _size() {		// private
	var no_of_items = 0;
	for (key in this._globalHash) {
		if(this._globalHash[key]) {
			no_of_items += 1;
		}
	}
	return no_of_items;
}

// returns the non null keys
function _getKeys() {		// private
	var keys = new Array();
	for (key in this._globalHash) {
		if(this._globalHash[key]) {
			keys[keys.length] = key;
		}
	}
	return keys;
}

// clear the hash
function _clear() {
	for (key in this._globalHash) {
		this._globalHash[key] = null;
	}
}

// can be used to restrict the window resizing,
// can restrict the user from minimizing the window below a specified size
function _onResize() {
	var _width = 0, _height = 0;

	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		_width = window.innerWidth;
		_height = window.innerHeight;
	  } else {
		if( document.documentElement &&
			( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		  //IE 6+ in 'standards compliant mode'
		  _width = document.documentElement.clientWidth;
		  _height = document.documentElement.clientHeight;
		} else {
		  if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			_width = document.body.clientWidth;
			_height = document.body.clientHeight;
		  }
		}
	  }

	if( _height < 768) {
		if(top.window.screen.availHeight < 768)
			_height = top.window.screen.availHeight;
		else
			_height = 768;
	}
	if(_width < 1024) {
		if(top.window.screen.availWidth < 1024)
			_width = top.window.screen.availWidth;
		else
			_width = 1024;
	}

	//if(_width != top.window.outerWidth || _height != top.window.outerHeight)
		//top.window.resizeTo(_width, _height);
}

//top.window.onResize="_onResize();";

// _deviceList will hold the list of devices discovered.
var _deviceList = new Array();
// _selectedDeviceIndex contains the index of the currently selected devcie
// in the FPV
var _selectedDeviceIndex = 0;

// setDeviceList will set the device list to the list of devices passed as devices
function setDeviceList(devices) {
	_deviceList = devices;
}

// returns the list of devices.
function getDeviceList() {
	return _deviceList;
}

// getSelectedDevice returns the selected devcie
function getSelectedDevice() {
	if(!_deviceList[_selectedDeviceIndex]) {
		_selectedDeviceIndex = 0;		
	}
	return _deviceList[_selectedDeviceIndex];
}

// setSelectedDeviceIndex sets the selected device index
function setSelectedDeviceIndex(deviceIndex) { // deviceIndex is the position in the combobox
	_selectedDeviceIndex = deviceIndex;
}

// getSelectedDeviceIndex returns the selected device index
function getSelectedDeviceIndex() { // deviceIndex is the position in the combobox
	return _selectedDeviceIndex;
}

// create a device object, if device type is not known to the current code, 
// an UnknownDevice will be created
function mainCreateDevice(int_status, media_type, deviceType) {
	var dev = null;
	dev = createDevice(int_status, media_type, deviceType);
	if(!dev) dev = new unknownDevice();
	return dev;
}

//functions to avoid dragging of images
//addImageEvents can be called in the onload event of a document with the document itself as the parameter
//the function needs to be called each time a new IMG element is created in the document
var netscape = !document.all && document.getElementById;
var x, y, x1, y1;

function addImageEvents(frameDocument)
{
	if (!(document.getElementById || document.all || document.layers)) return;

	for (i=0;i<frameDocument.images.length;i++)
	{
		if(netscape) //netscape
		{
			frameDocument.images[i].onmousedown = imgMouseDown;
			frameDocument.images[i].onmouseup = function() {return false};
			frameDocument.images[i].onmousemove = imgMouseMove;
			//if image does not have a pre-defined onclick event or does not have a link cancel the click event
			if(!frameDocument.images[i].onclick && frameDocument.images[i].parentNode.tagName.toLowerCase() != "a") frameDocument.images[i].onclick = function() {return false};
		}
		else //IE
		{
			//when the drag event is cancelled the mouseout event needs to be called
			//to ensure that if there is a rollover image, it is restored to its original src
			frameDocument.images[i].ondrag = function() {this.fireEvent("onmouseout");return false};
		}
	}
}

//record the x and y co-ordinates of the mousedown event
function imgMouseDown(e)
{
	x = e.screenX;
	y = e.screenY;
	return false;
}

//check if the parent tag is an anchor tag or 
//if the new difference betn (x, y) and (x1, y1) is more than 10px
//assume it as an attempt to drag the image
function imgMouseMove(e)
{
	var tagname = '';
	x1 = e.screenX;
	y1 = e.screenY;
	if (e.target.parentNode)
		tagname = e.target.parentNode.tagName;
		
	if ((!(tagname.toLowerCase() == "a") || ((Math.abs(x-x1) > 10) || (Math.abs(y-y1) > 10))))
	{
		return false;
	}
}

function onChangeLanguage() {
	var helpTag = null;
	
	if(helpwindow && !helpwindow.closed) {
		helpTag = mainFrame.getHelpTag();
	}
	var date = new Date();
	var expiryDate = (new Date(date.setDate(date.getYear()+10))).toGMTString();
	document.cookie = "LanguagePreference=" + top.dataCache.get("LANGUAGE_CODE") + ";expires=" + expiryDate;
	
	top.statusUpdated = false; //to reload the status frame from monitordata
	if(top.healthFrame) top.reloadMainFrame = true; //to reload main frame
	if(top.healthFrame) top.healthFrame.location.href = "monitordata.shtml";
	if(top.discoveryFrame) top.discoveryFrame.location.href = "discover.shtml";
	
	var tmpCharset = top.dataCache.get("CHARSET");
	if(top.mainFrame) top.mainFrame.document.charset = tmpCharset;
	if(top.leftFrame) top.leftFrame.document.charset = tmpCharset;
	if(top.bottomFrame) top.bottomFrame.document.charset = tmpCharset;
	if(top.statusFrame) top.statusFrame.document.charset = tmpCharset;
	if(top.resourceFrame) top.resourceFrame.document.charset = tmpCharset;
	if(top.topFrame) top.topFrame.document.charset = tmpCharset;
	if(top.sslFrame) top.sslFrame.document.charset = tmpCharset;
	if(top.toolbarFrame) top.toolbarFrame.document.charset = tmpCharset;
	
	//top.resourceFrame.document.location.href = "frmwrkResource.htm";
	if(top.resourceFrame) top.resourceFrame.document.location.reload(true);
	if(top.topFrame) top.topFrame.document.location.reload(true);
	if(top.healthFrame == null && top.mainFrame)
	{
		var url = top.mainFrame.location+"";
		if ( url.indexOf("troubleshooting_") != -1 )
		{
			var tempStringArray = url.split("/");
			tempStringArray[3] = top.dataCache.get("LANGUAGE_CODE");
			var newurl = tempStringArray.join("/");
			top.mainFrame.document.location = newurl;
		}
		else
		{
			top.mainFrame.document.location.reload(true);
		}

	}
	if(top.leftFrame) top.leftFrame.document.location.reload(true);
	if(top.bottomFrame) top.bottomFrame.document.location.reload(true);
	if(top.sslFrame) top.sslFrame.document.location.reload(true);
	if(top.toolbarFrame) top.toolbarFrame.document.location.reload(true);
	if(helpwindow && !helpwindow.closed && !dataCache.get("RECOVERYMODE")) {
		helpwindow.close();
		showHelp(helpTag, false);
	}
	//if(top.statusFrame && top.statusFrame.document)
	//	top.statusFrame.document.location.reload(true);
	
	//top.topFrame.onRefresh();
}
