/**
 * commonspot.clientUI: methods and data for managing overall state of CommonSpot client UI
 */
commonspot.clientUI = {};

// Variable to indicate whether we have detected a bad URL. Used while displaying an error message. 
// Needed to ensure we don't re-display the error message for every iteration of uiWatcher.
commonspot.clientUI.isURLError = false; 

commonspot.clientUI.isComingFromEntrance = true; 
commonspot.clientUI.updateSource = false;

/**
 * initialize CommonSpot UI when it's first loaded
 */
commonspot.clientUI.uiOnLoad = function()
{
	// get data we need to set up initially
	// setup continues when this cmdCollection returns and runs the collection's onCompleteCallback
	commonspot.clientUI.getInitialData(commonspot.clientUI.handleInitialData);
};

commonspot.clientUI.showError = function(msg)
{
	setTimeout(commonspot.clientUI.uiWatcher, 1000);
	commonspot.dialog.client.alert(msg, {title: 'Error'});
}
/**
 * gets user and subsite root info from server, runs passed callback when done
 * @param function onCompleteCallback: function to run when cmd collection rtns w this data
 * @require: a valid commonspot.clientUI.state.location, to get a loader to use
 */
commonspot.clientUI.getInitialData = function(onCompleteCallback)
{
	// Detect and handle invalid URL.
	if (chkURLError())
		return;
	commonspot.clientUI.login.index = 0;
	var hashArgs = commonspot.util.getHashArgs();
	var mode = hashArgs.mode || commonspot.clientUI.state.mode.MYCS;
	var baseMode = commonspot.clientUI.state.mode.getBase(mode);
	var loader;
		
	// hide/show exitLview button
	if (mode == 'server_admin' || mode == 'customer_admin')
		$('closeLview').style.display = 'none';
		
	// Set loader appropriately (based on Server Admin mode or not).
	if (mode != 'server_admin')
	{
		var url = hashArgs.url;
		if (url.length > 0)
			loader = commonspot.clientUI.state.location.getPathFromUrlStr(url) + 'loader.cfm';
		else
			commonspot.clientUI.showError('No loader exists.');
	}
	else
		loader = '/commonspot/admin/loader.cfm';
	var cmdCollection = commonspot.ajax.commandEngine.commandCollectionFactory.getInstance(loader, onCompleteCallback);
	cmdCollection.add('Server', 'CheckValid');
	cmdCollection.add('Users', 'GetUserInfo');
	cmdCollection.add('Site', 'GetMenuContext');
	cmdCollection.add('SpellCheck', 'GetSettings');
	cmdCollection.add('Server', 'GetInfo');
	/*
	 * NEEDSWORK
		need pg ID to switch it to requested mode, and pg title to make a history entry for it
		can get those with his next cmd, but:
			- updating currentPage dataset makes an observer load real pg, before we've changed the mode
					can sleaze around that by using a different dataset; exists but not used right now
					could supressNotifications instead?
			- some thrash figuring out if we should
			- if we do this, it probably belongs in lview
	*/
	if (baseMode == 'lview')
	{
		var theURL = hashArgs.url;
		var theSubsiteURL =  commonspot.clientUI.state.location.get().subsiteurl;
		var filename = theURL.replace(theSubsiteURL, ''); 
		// check if the url is just the subsite, if so no need to call - let default page load
		if (filename != '' && theSubsiteURL)
			cmdCollection.add('Page', 'getVarsFromURL', {pageURL: theURL, fieldList: 'pageID,title,PageType'}, {datasetRoot: commonspot.data.uiState.lview, datasetName: 'dsCurrentPage'});
	}	
	cmdCollection.send();
}

/**
 * called once initial user and subsite root info comes back, to set up client ui
 * NEEDSWORK: ideally, things could sign themselves up to run now, rather than code them here
				  try Spry.Utils.Notifier.call(this);
 */
commonspot.clientUI.handleInitialData = function()
{
	// check if we're out of business; we really need all the info from the cmd collection that spawned this
	if (this.mustLogIn || this.hasAnyError)
		return;

	// hide initial loading msg, set it up for later use
	setTimeout(function(){commonspot.lightbox.loadingMsg.onDashboardLoaded();}, 2000);
	
	try
	{
		// call various objects to set themselves up
		commonspot.clientUI.menus.init();
		commonspot.lview.common.menus.init();
		commonspot.mycs.activityWorkflow.init();
	}
	catch (err)
	{
		commonspot.clientUI.showError(err.message);
	}
	
	// start periodic task to watch ui, call anybody who needs it
	commonspot.clientUI.uiWatcher();
};

/**
 * watches whole UI, calls whoever to adjust whatever they need
 * NEEDSWORK: ideally, things could sign themselves up to run now, rather than code them here
				  try Spry.Utils.Notifier.call(this);
 */
commonspot.clientUI.uiWatcher = function(){
	var hashArgs = commonspot.util.getHashArgs();
		
	if (!chkURLError())
	{	
		// check if url hash changed - returns true if the hash has changed
		// if the hash is detected to have changed, the page will have been reloaded		
		var skipWatcher = false;
		var hashUpdate = false;
		
		if (commonspot.lightbox) 
		{
			if (commonspot.lightbox.stack.length > 0)
			{
				var lbObj = commonspot.lightbox.getCurrent();
				var frmObj = document.getElementsByName(lbObj.getFrameName())[0];
				var src = frmObj.src.toLowerCase();
				if (src.indexOf('loader.cfm?csmodule=security/login&bnewwindow=1&ballowcancel=0') > 0) //ALL LOWER CASE!!  //waiting for login
					skipWatcher = true;
				else if (src == 'about:blank')  //error dump?
				{
					skipWatcher = true;
					commonspot.clientUI.isURLError = true;
				}
			}
		}	
		
		if (!skipWatcher)	
			hashUpdate = commonspot.clientUI.state.mode.urlHash.setModeAndPageFromHash() || commonspot.lview.bHandleOuterFrameSizing;
		if (hashUpdate)
		{			
			// set flag to indicate that we have handled
			commonspot.lview.bHandleOuterFrameSizing = 0;
			
			// call anyone else who needs to know
			if (commonspot.lview.common.uiWatcher)
			{
				commonspot.lview.common.uiWatcher();
				commonspot.lightbox.adjustLayout();
			}
			commonspot.admin.common.uiWatcher(commonspot.data.uiState.dsMode);
		}
	}
	var lview = $('lview');
	if (lview)
	{
		var winSize = commonspot.util.dom.getWinSize();
		var avlMaxHeight = winSize.height - (commonspot.admin.common.HEADER_HEIGHT+10);
		var lviewIframe = $(commonspot.lview.common.FRAME_CONTAINER);		
		lview.style.height = avlMaxHeight + 'px';
		if (lviewIframe)
		{
			var tabData = commonspot.data.uiState.lview.left.dsOpenFrame.getCurrentRow();
	   	var furnitureHt = 111 + (tabData.tabCount * 20);
		   var lviewht = winSize.height - furnitureHt;
			lviewIframe.style.height = lviewht + 'px';	
		}			
		var page = $(commonspot.lview.common.PAGE_IFRAME_ID);
		if (page)
			page.style.height = (avlMaxHeight-40) + 'px';
	}

	// rinse and repeat...
	setTimeout(commonspot.clientUI.uiWatcher, 1000);
};

function chkURLError()
{
	if (commonspot.clientUI.isURLError)  //someone set it to be true already....
		return true;
		
	var hashArgs = commonspot.util.getHashArgs();
	var mode = hashArgs.mode || commonspot.clientUI.state.mode.MYCS;
	var url = hashArgs.url;
	var chkCS = true;
		
	switch (mode)
	{
		case 'server_admin':
		case 'customer_admin':
		case 'user_admin':
		case 'group_admin':
			chkCS = false;
			break;		
	}

	if (!url || url == '' || (chkCS && url.indexOf('/commonspot/') == 0))
	{	
		if (!commonspot.clientUI.isURLError) 
		{
			commonspot.clientUI.showError('Invalid URL. Please specify a valid url.');
			commonspot.clientUI.isURLError = true;
			return true; 
		}
	}
	
	commonspot.clientUI.isURLError = false;
	return false;
}

/**
 * commonspot.clientUI.state: management of clientUI mode
 */
commonspot.clientUI.state = {};

commonspot.clientUI.state.location = {};

commonspot.clientUI.state.location.get = function()
{
	return commonspot.data.uiState.dsLocation.getCurrentRow(); // {server: , site: , subsite: }
}

commonspot.clientUI.state.location.getSitename = function()
{
	return commonspot.data.uiState.dsLocation.getCurrentRow().sitename;
}

commonspot.clientUI.state.location.getSubsitename = function()
{
	return commonspot.data.uiState.dsLocation.getCurrentRow().subsitename;
}

/**
 * @param string type: subsiteurl, siteurl, serveradminurl
 * @return string loaderURL: returns the loader for the current subsite, site, or server
 * gets it from saved dataset
 */
commonspot.clientUI.state.location.getLoaderURL = function(type)
{
	var strURL = '';

	switch(type)
	{
		case 'serveradminurl':
			strURL = '/commonspot/admin/';
			break;
		case 'siteurl':
		case 'subsiteurl':
			var location = commonspot.clientUI.state.location.get(); // {server, site, subsite}
			strURL = location[type];
			if (!strURL)
			{
				var hashArgs = commonspot.util.getHashArgs();
				var url = hashArgs.url;				
				if (!url || url == '' || url.indexOf('/commonspot/') == 0)
				{	
					if (!commonspot.clientUI.isURLError) 
					{
						commonspot.clientUI.showError('Invalid URL. Please specify a valid url.');
						commonspot.clientUI.isURLError = true; 
					}
				}
				else
				{
					// make sure only directory portion returned (not including filename)
					var pos = url.lastIndexOf("/");
					if( pos > 1 )
						strURL = url.substring( 0, pos+1 );
					else
						strURL = url;
				}
			}
			if (strURL == null)
				strURL = '/commonspot/admin/';
			break;
		default:
			commonspot.clientUI.showError('getLoaderURL was passed an unsupported type: ' + type);
	}

	return strURL + 'loader.cfm';
}

commonspot.clientUI.state.location.getPathFromUrlStr = function(urlStr)
{
	var pathStr = urlStr;
	
	if (urlStr.length > 1) // if urlStr is '/'
	{
		var aUrl = urlStr.split('/');
		if (urlStr.charAt(urlStr.length - 1) != '/')  // remove filename from urlStr, if there is one
		{
			var lastStr = aUrl[aUrl.length - 1];
			var bUrl = lastStr.split('.');  //we found a '.', assume URL conatins file name
			if (bUrl.length > 1)
				aUrl[aUrl.length - 1] = '';
			else
				aUrl[aUrl.length] = '';  //so the ending slash will be append...

			pathStr = aUrl.join('/');
		}
	}
	return pathStr;
};


commonspot.clientUI.state.location.resetByGivenSubsiteURL = function(urlStr)
{
	var mode = 'subsite_admin';
	var modeTitle = commonspot.clientUI.state.mode.specs[mode].title;
	document.location.hash = commonspot.clientUI.state.mode.urlHash.modeQueryString(mode, urlStr);
	document.title = modeTitle + ' - ' + urlStr;
};

/*
 * Invoke commands to check hashURL
 */
commonspot.clientUI.state.location.hashURL = {};
commonspot.clientUI.state.location.hashURL.Subsite_GetContext = new commonspot.spry.Dataset({xpath: commonspot.data.STRUCT_XPATH});

commonspot.clientUI.state.location.hashURL.lastUrlChecked = {url: '', timestamp: new Date()};
commonspot.clientUI.state.location.hashURL.issueChkURLCmd = function(urlStr)
{
	// if we've done this same query recently, don't repeat it
	if(urlStr == this.lastUrlChecked.url && (this.lastUrlChecked.timestamp - new Date() < 120000))
		return;
	this.lastUrlChecked = {url: urlStr, timestamp: new Date()};
	
	var collectionOptions = {onCompleteCallback: this.issueChkURLCmdOnComplete, closeOnError: 1};
	var loaderURL = commonspot.clientUI.state.location.getPathFromUrlStr(urlStr) + 'loader.cfm';
	var cmds = commonspot.ajax.commandEngine.commandCollectionFactory.getInstance(loaderURL, collectionOptions);
	var cmdOptions_Subsite_GetContext = {datasetRoot: commonspot.clientUI.state.location.hashURL};

	cmds.add('Subsite', 'GetContext', null, cmdOptions_Subsite_GetContext);
	cmds.add('Site', 'GetMenuContext');
	cmds.add('Users', 'GetUserInfo');
	cmds.send();
};

/*
 * This callback function is called when issueChkURLCmd completes.
 */ 			
commonspot.clientUI.state.location.hashURL.issueChkURLCmdOnComplete = function()
{ 
	if (this.hasAnyError)
		return;
		
	commonspot.clientUI.state.location.set(commonspot.clientUI.state.location.hashURL.Subsite_GetContext.getCurrentRow()); 
	
	// update hash in admin mode
	
	var hashArgs = commonspot.util.getHashArgs();
	var mode = hashArgs.mode || commonspot.clientUI.state.mode.MYCS;
	var baseMode = commonspot.clientUI.state.mode.getBase(mode);
	
	if (baseMode == 'lview')
	{
		var url = hashArgs.url;  //url must be different when we call this...
		var qstring = '';
		
		if (hashArgs.qstring && hashArgs.qstring != '')
			qstring = hashArgs.qstring;
						
		commonspot.lview.currentPage.setURL(url, true, qstring);
		
		// Load the specified page in the main iframe & associated data.
		commonspot.lview.currentPage.loadPage();			
		commonspot.lview.currentPage.loadPageData();
	}
	
	commonspot.clientUI.state.mode.set(mode, false); //then call setHashFromModeAndPage() 
};
/**
 * sets site and subsite elements of location object, from passed site and subsite
 * @param {string} site
 * @param {string} subsite
 */
commonspot.clientUI.state.location.set = function(contextInfo)
{
	var siteURL = contextInfo.siteurl;
	var subsiteURL = contextInfo.subsiteurl;

	if (typeof siteURL != 'string' || typeof subsiteURL != 'string')
		commonspot.clientUI.showError("CommonSpot doesn't have a subsite context to work with. You need to navigate here using the tools provided on any CommonSpot page when you're logged in.");
	commonspot.data.uiState.dsLocation.update(contextInfo);
};

// mode package
commonspot.clientUI.state.mode = {};

// constants for all modes
// NOTE: new modes must also be added to commonspot.clientUI.state.mode.specs, and their baseMode to commonspot.clientUI.state.mode.baseMode.specs
commonspot.clientUI.state.mode.MYCS = 'mycs';
commonspot.clientUI.state.mode.READ = 'read';
commonspot.clientUI.state.mode.AUTHOR = 'author';
commonspot.clientUI.state.mode.EDIT = 'edit';
commonspot.clientUI.state.mode.APPROVE = 'approve';
commonspot.clientUI.state.mode.COMPARE = 'compare';
commonspot.clientUI.state.mode.SERVER_ADMIN = 'server_admin';
commonspot.clientUI.state.mode.CUSTOMER_ADMIN = 'customer_admin';
commonspot.clientUI.state.mode.SITE_ADMIN = 'site_admin';
commonspot.clientUI.state.mode.SUBSITE_ADMIN = 'subsite_admin';
commonspot.clientUI.state.mode.USER_ADMIN = 'user_admin';
commonspot.clientUI.state.mode.GROUP_ADMIN = 'group_admin';
commonspot.clientUI.state.mode.ADMIN_TOOLS = 'admin_tools';
commonspot.clientUI.state.mode.LOGIN = 'login';
commonspot.clientUI.state.mode.ERROR = 'error';
commonspot.clientUI.state.mode.NOPAGE = 'nopage';

// specs for them
commonspot.clientUI.state.mode.specs = {};
with(commonspot.clientUI.state.mode)
{
	specs[MYCS] = {mode: MYCS, baseMode: 'mycs', title: 'My CommonSpot'};
	specs[READ] = {mode: READ, baseMode: 'lview', title: 'Viewing As Published'};
	specs[AUTHOR] = {mode: AUTHOR, baseMode: 'lview', title: 'Viewing My Changes'};
	specs[EDIT] = {mode: EDIT, baseMode: 'lview', title: 'Viewing All Changes'};
	specs[APPROVE] = {mode: APPROVE, baseMode: 'lview', title: 'Viewing Pending Approvals'};
	specs[COMPARE] = {mode: COMPARE, baseMode: 'lview', title: 'Compare Versions'};
	specs[SERVER_ADMIN] = {mode: SERVER_ADMIN, baseMode: 'admin', title: 'CommonSpot Server Administration'};
	specs[CUSTOMER_ADMIN] = {mode: CUSTOMER_ADMIN, baseMode: 'admin', title: 'CommonSpot Customer Administration'};
	specs[SITE_ADMIN] = {mode: SITE_ADMIN, baseMode: 'admin', title: 'CommonSpot Site Administration'};
	specs[SUBSITE_ADMIN] = {mode: SUBSITE_ADMIN, baseMode: 'admin', title: 'CommonSpot Subsite Administration'};
	specs[USER_ADMIN] = {mode: USER_ADMIN, baseMode: 'admin', title: 'CommonSpot User Administration'};
	specs[GROUP_ADMIN] = {mode: GROUP_ADMIN, baseMode: 'admin', title: 'CommonSpot Group Administration'};
	specs[ADMIN_TOOLS] = {mode: ADMIN_TOOLS, baseMode: 'admin', title: 'CommonSpot Tools'};
	specs[ERROR] = {mode: ERROR, baseMode: 'error', title: 'Error'};
	specs[NOPAGE] = {mode: NOPAGE, baseMode: 'nopage', title: 'CommonSpot Dashboard'};
}

// base mode package
commonspot.clientUI.state.mode.baseMode = {};

// specs for base modes
commonspot.clientUI.state.mode.baseMode.specs = {};
with(commonspot.clientUI.state.mode.baseMode)
{
	specs['mycs'] = {id: 'mycs', title: 'My Commonspot', showTop: 1};
	specs['lview'] = {id: 'lview', title: 'Contribute', showTop: 1};
	specs['admin'] = {id: 'admin', title: 'Commonspot Administrator', showTop: 1};
	specs['error'] = {id: 'error', title: 'Error', showTop: 0};
	specs['nopage'] = {id: 'nopage', title: 'Not A Commonspot Page', showTop: 0};
}


/**
 * sets the clientUI mode (mycs, read, author, server_admin etc) and corresponding baseMode
 */
commonspot.clientUI.state.mode.set = function(mode, dontUpdateHash, obj)
{
	if (typeof obj != 'undefined' && $(obj).hasClassName('disabled'))
	{
		return false;
	}
	else
	{
		var baseMode = commonspot.clientUI.state.mode.getBase(mode);
		var title = commonspot.clientUI.state.mode.specs[mode].title;
		var hashArgsURL = commonspot.util.getHashArgs().url;
		var closeLviewHide = false;
		// If Admin modes, hide top right corner cross mark used for hiding L-view.
		switch(mode)
		{
			case 'server_admin':
				hashArgsURL = '/commonspot/admin/';
				closeLviewHide = true;
				break;
			case 'customer_admin':
			case 'user_admin':
			case 'group_admin':
			case 'site_admin':
			case 'subsite_admin':
			case 'mycs':
				closeLviewHide = true;
				break;
		}
		var lviewPageTitle = null;
		if (baseMode == 'lview' && commonspot.csPage)
			lviewPageTitle = commonspot.csPage.title;
		commonspot.data.uiState.dsMode.update({mode: mode, baseMode: baseMode, title: title, currenturl: hashArgsURL, lviewPageTitle: lviewPageTitle});
		
		if ((!dontUpdateHash) || (hashArgsURL == ''))
			commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage();
			
		// If Admin modes, hide top right corner cross mark used for hiding L-view.
		if (closeLviewHide)
			$('closeLview').hide();
		else
			$('closeLview').show();	
	}
	commonspot.index.showHideSiteSpecificUI();
};

/**
 * returns base mode for passed mode, throws if invalid
 */
commonspot.clientUI.state.mode.getBase = function(mode)
{
	if (!(mode in commonspot.clientUI.state.mode.specs))
		commonspot.clientUI.showError('commonspot.clientUI.state.mode.getBase was passed an unknown mode: ' + mode);
	return commonspot.clientUI.state.mode.specs[mode].baseMode;
}

/**
 * base class for object that manages visual transition at mode changes
 */
commonspot.clientUI.state.mode.modeChangeVisualTransitionClass = function()
{
	var lastBaseModeElementID = '';
	
	this.dataset = commonspot.data.uiState.dsMode;
	this.dataset.addObserver(this);
	
	/**
	 * called when mode dataset changes, manages visual transition to new base mode when it changes
	 */
	this.onDataChanged = function(dataset)
	{
		var newMode = dataset.getCurrentRow().mode;
		var newBaseModeElementID = getBaseModeElementID(newMode);
		// do transition if base mode changes, or entering any admin mode
		if (newBaseModeElementID != lastBaseModeElementID || newBaseModeElementID == 'admin')
		{
			this.showBaseMode(newBaseModeElementID);
			lastBaseModeElementID = newBaseModeElementID;
		}
	};
	
	/**
	 * hides non-current base modes, fades current one in
	 */
	this.showBaseMode = function(baseModeElementID)
	{
		var baseMode;
		
		// hide top section initially
		$('top').hide();
		
		// and all base modes
		var baseModeSpecs = commonspot.clientUI.state.mode.baseMode.specs;
		for (baseMode in baseModeSpecs)
			$(baseMode).hide();
		
		// show top section, unless we're in a mode that doesn't
		if (baseModeSpecs[baseModeElementID].showTop)
			$('top').show();
		
		// show requested mode, with fx
		Effect.Appear(baseModeElementID, {duration: 1.5});
	};
	
	/**
	 * returns the element ID of container for passed base mode
	 */
	getBaseModeElementID = function(mode)
	{
		var id = commonspot.clientUI.state.mode.getBase(mode);
		return id;
	};

};

// create instance
commonspot.clientUI.state.mode.modeChangeVisualTransition = new commonspot.clientUI.state.mode.modeChangeVisualTransitionClass();


/**
 * stuff for working with url hash
 */
commonspot.clientUI.state.mode.urlHash = {};

/**
 * if mode isn't there, or we have an invalid combo of mode and page info, use mycs
 */

commonspot.clientUI.state.mode.urlHash.setModeAndPageFromHash = function()
{
	var mode, baseMode, url='', modeDS, urlDS, qstring='', qstringDS;
	var hashArgs = commonspot.util.getHashArgs();
	var servertype = commonspot.data.Server_GetInfo.getData()[0]["servertype"];
	mode = hashArgs.mode || commonspot.clientUI.state.mode.MYCS;
	if ((servertype == 'SharedDatabaseReadOnly') && (mode != 'server_admin'))
	{
		commonspot.clientUI.state.mode.urlHash.invalidROPSpageAlert(mode);
		return false;
	}
		
	baseMode = commonspot.clientUI.state.mode.getBase(mode);  //NOT from dataset
	
	if (hashArgs.url)
		url = hashArgs.url;

	if (baseMode == 'lview') 
	{
		var curPageRow = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow();
		urlDS = curPageRow.url;
		qstringDS = curPageRow.qstring;
	}
	else
	{
		urlDS = commonspot.clientUI.state.location.get().subsiteurl;
		qstringDS = '';
	}
	
	var updateStatus = 0;
	var adminLocation = {menucontexttimestamp:1, subsiteid: 0, siteid: 0, subsiteurl: url, siteurl: url, sitetype: 2, sitename: 'CommonSpot Administrator', subsitename: ''};
	if ((!urlDS) && (url.length > 0))  //set dsLocation dataset by hash
	{
		var issueCMD = true;
		
		if (url == '/commonspot/admin/')
		{
			switch(mode)
			{
				case 'server_admin':
				case 'customer_admin':				
				case 'user_admin':
				case 'group_admin':					
					commonspot.clientUI.state.location.set(adminLocation);
					issueCMD = false;
					break;
				default:
					commonspot.clientUI.showError('ERROR - Not a valid loader URL');
					return false;				
			}			
		}
		else if (mode == 'server_admin')
		{
			commonspot.clientUI.showError('ERROR - Not a valid loader URL');
			return false;
		}
		
		if (issueCMD)
			commonspot.clientUI.state.location.hashURL.issueChkURLCmd(url);

		return true; //let's wait 1 sec
	}
				
	modeDS = commonspot.data.uiState.dsMode.getCurrentRow().mode;

	if ((!modeDS) && (mode.length > 0))  //set dsMode dataset by hash
	{	
		commonspot.clientUI.state.mode.set(mode, true);
		return true; //let's wait 1 sec
	}

	if (hashArgs.qstring)
		qstring = hashArgs.qstring;

	// Load page if appropriate.
   commonspot.lview.isNonCSNavigationSmallScope = false;
	
	if (url != urlDS)
	{
		if (mode != 'server_admin')
			commonspot.clientUI.state.location.hashURL.issueChkURLCmd(url); //create a new dsLoaction if it is valid and it is in subsite_admin... also call then call setHashFromModeAndPage()
		else
		{
			commonspot.clientUI.state.location.hashURL.lastUrlChecked.url = '';
			commonspot.clientUI.state.location.set(adminLocation);
			commonspot.clientUI.state.mode.set(mode, false);  //then call setHashFromModeAndPage()
	
			var loaderURL = commonspot.clientUI.state.location.getLoaderURL('serveradminurl');
			var cmds = commonspot.ajax.commandEngine.commandCollectionFactory.getInstance(loaderURL);
			cmds.add('Users', 'GetUserInfo');
			cmds.send();
		}

		commonspot.lview.isComingFromNonCSPage = false;
		return true; //let's wait 1 sec
	}
	
	if (mode != modeDS)  // and url is the same
	{
		if (urlDS == '/commonspot/admin/')
		{
			switch(mode)
			{
				case 'server_admin':
				case 'customer_admin':
				case 'user_admin':
				case 'group_admin':
					break;
				default:
					//the url is still the '/commonspot/admin' alert message from chkURLError()
					commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage();
					commonspot.lview.isComingFromNonCSPage = false;
					return false; //treat as nothing changed....				
			}				
		}
		
		if ((baseMode == 'lview') && (qstring == qstringDS))
		{
			if ( eval('commonspot.csPage.userRights.' + mode) )
			{
				switch (mode) 
				{
					case 'read':
						commonspot.index.changeMode('view_page_as_published_menu_item', 0);
						break;
					case 'author':
						commonspot.index.changeMode('work_on_this_page_my_changes_menu_item', 1);
						break;
					case 'edit':
						commonspot.index.changeMode('work_on_this_page_edit_menu_item', 3);
						break;
					case 'approve':
						commonspot.index.changeMode('work_on_this_page_approval_menu_item', 2);
						break;
				}
				commonspot.clientUI.updateSource = 'fromHash';	
			}
			else
				commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage(); // user do not right permissions to go to desired mode
		}
			
		commonspot.clientUI.state.mode.set(mode, false);  //then call setHashFromModeAndPage()
		commonspot.lview.isComingFromNonCSPage = false;
		return true;  //mode changed
	}
		
	return false; //nothing should happen here; same mode, same url... (??? how about qstring??)
};

commonspot.clientUI.state.mode.urlHash.invalidROPSpageAlert = function(mode)
{
	var pname = '';
	switch(mode)
	{
		case 'site_admin':
			pname = 'The Site Administration page';
			break;
		case 'subsite_admin':
			pname = 'The Subsite Administration page';
			break;
		case 'customer_admin':
			pname = 'The Customer Administration page';
			break;
		case 'user_admin':
			pname = 'The User Administration page';
			break;
		case 'group_admin':
			pname = 'The Group Administration page';
			break;
		case 'mycs':
			pname = 'My CommonSpot dashboard';
			break;
		default:
			pname = 'Specifying any mode';
			break;
	}
	commonspot.clientUI.showError(pname+' is not available on this shared database read-only production server.  Please make changes on the authoring server.');
};

/**
 * sets url hash and window title from mode and currentPage datasets
 * assumes we've already checked that it's changed, so just do it
 */
commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage = function()
{
	var dashName, currMode, mode, baseMode, modeTitle, url, title;
	
	dashName = 'CommonSpot Dashboard';
	currMode = commonspot.data.uiState.dsMode.getCurrentRow();

	if (!currMode.mode)
		return; //do nothing. nothing in dsMode dataset, probably dataset is cleared and CF is restarted

	mode = currMode.mode;
	baseMode = currMode.baseMode;
	modeTitle = currMode.title;
	
	if (baseMode == 'lview')
	{
		var currentPage = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow();
		url = currentPage.url;
		title = currentPage.title + ' - ' + modeTitle + ' - ' + dashName;
	}
	else
	{
		switch (mode)
		{
			case 'server_admin':
				url = '/commonspot/admin/';
				title = modeTitle;					
				break;
			case 'site_admin':
				url = commonspot.clientUI.state.location.get().siteurl;
				title = modeTitle + ' - ' + url;						
				break;	
			case 'subsite_admin':
				url = commonspot.clientUI.state.location.get().subsiteurl;
				title = modeTitle + ' - ' + url;						
				break;		
			default:
				url = commonspot.clientUI.state.location.get().subsiteurl;
				title = modeTitle;	
		}	
	}
		
	if (!url)
		return; //do nothing. nothing in dataset, probably dataset is cleared and CF is restarted
	
	var _mode, _url;
	var _hashArgs = commonspot.util.getHashArgs();
	
	_mode = _hashArgs.mode || commonspot.clientUI.state.mode.MYCS;
	_url = _hashArgs.url;

	if (_mode != mode || _url != url || commonspot.lview.isNonCSNavigation)
	{	
		document.location.hash = commonspot.clientUI.state.mode.urlHash.modeQueryString(mode, url);
		document.title = commonspot.util.xml.decodeEntities(title).replace(/&#39;/g, "'");
	}
};

/**
 * returns passed args in query string format (url=?&mode=?)
 * @param string mode: clientUI mode (read/author/cs_ui etc) 
 * @param string url:
 * 	so far, expected uses are:
 * 		url, of page, when in an lview mode
 * 		url, of subsite root, in any other mode
 */
commonspot.clientUI.state.mode.urlHash.modeQueryString = function(mode, url)
{
	return 'mode=' + mode + '&url=' + url;
};


/**
 * login package
 */
commonspot.clientUI.login = {};
commonspot.clientUI.login.index = 0;
/**
 * login menu item; note that this changes the mode to 'login', losing any other mode
 */
commonspot.clientUI.login.goToLogin = function()
{
	var hashArgs = commonspot.util.getHashArgs();
	if (hashArgs.url && (hashArgs.url.length > 0))
	{
		var urlStr = commonspot.clientUI.state.location.getPathFromUrlStr(hashArgs.url);
		var loaderURL = urlStr + 'loader.cfm?csModule=security/logout&bNewWindow=1';
		skipWatcher = true;
		$('body').hide();
		window.open(loaderURL, 'logout', 'width=1,height=1,left=5000,top=5000');
	}	
	else
		commonspot.clientUI.showError('ERROR - Must specify URL');			
}

/**
 * mode dataset observer, shows login dlg if mode is login
 */
commonspot.clientUI.login.onDataChanged = function(dataset)
{
	if (dataset.getCurrentRow().mode != commonspot.clientUI.state.mode.LOGIN) // not our mode
		return;
	commonspot.clientUI.login.show();
}
commonspot.data.uiState.dsMode.addObserver(commonspot.clientUI.login);

/**
 * low-level function to display login dlg; doesn't change current ui mode, or session state on server
 * NEEDSWORK: this is a temporary partial hack
 * 	- closing login dlg currently relies on patch to ForceParentReload() in security/login-finish.cfm
 * 	- cancel btn in dlg doesn't work right
 * 	- change password doesn't work right, concerned about other dlg chains (nt profile, etc)
 * 	maybe use generic legacy dlg overrides instead
 */
commonspot.clientUI.login.show = function()
{
	// zero out user info
	commonspot.data.Users_GetUserInfo.update({name: '', canAdminSite: 0, canAdminUsersGroups: 0});
	var hashArgs = commonspot.util.getHashArgs();
	if (hashArgs.url && (hashArgs.url.length > 0))
	{
		var urlStr = commonspot.clientUI.state.location.getPathFromUrlStr(hashArgs.url);
		var loginURL = urlStr + 'loader.cfm?csmodule=security/login&bNewWindow=1&bAllowCancel=0';
		commonspot.clientUI.login.index++; // reset in getInitialData
		if (commonspot.clientUI.login.index == 1)
			commonspot.lightbox.openDialog(loginURL, true, 'userlogindlg', null, null, null, true); // open in lightbox
	}	
	else
		commonspot.clientUI.showError('ERROR - Must specify URL');
};

/**
 * clientUI menu handling
 */
commonspot.clientUI.menus = {};
commonspot.clientUI.menus.allEnabledMenuClassesToCheck = '';	// hold ALL menu classes that have ever been enabled/disabled from GetMenuContext
commonspot.clientUI.menus.allVisibleMenuClassesToCheck = '';	// hold ALL menu classes that have ever been shown/hidden from GetMenuContext

commonspot.clientUI.menus.init = function()
{
	var menuOptions =
	{
		menuBarID: 'clientUICommonMenu',
		doMenuPositioning: false
	};
	var menuDefs =
	{
		my_content_btn: 'my_content_menu',
		new_btn: 'new_menu',
		tools_btn: 'tools_menu',
		reports_btn: 'reports_menu',
		admin_btn: 'admin_menu',
		helpMenu: 'helpMenuMenu'
	};
	var topMenuBar = new cs_MenuBar(menuOptions, menuDefs);
};

/**
 * base class to manage security-related updates to top-level menus; observes getMenuContext dataset
 */
commonspot.clientUI.menus.securityClass = function()
{
	this.dataset = commonspot.data.Site_GetMenuContext;
	this.dataset.addObserver(this);
};

/**
 * onDataChanged observer for Site_GetMenuContext
 * show/hide and enable/disable menu items based on user's permissions passed in Site.GetMenuContext()
 */
commonspot.clientUI.menus.securityClass.prototype.onDataChanged = function(dataset)
{
	var enabledList = this.dataset.getData()[0]["enabledmenuclasslist"];
	var visibleList = this.dataset.getData()[0]["visiblemenuclasslist"];
	var temp = '';

	// enable/disable or show/hide menu items
	// We loop over passed-in enabledMenuClasses, check if each item is already present 
	// in the master list of permissions (commonspot.clientUI.menus.allEnabledMenuClassesToCheck) and 
	// if not, add it to the list.
	var allEnabledToCheck = '';
	var arrEnabledMenuClasses = enabledList.split(',');	
	for (var i = 0; i < arrEnabledMenuClasses.length; i++)
	{
		temp = "," + arrEnabledMenuClasses[i] + ",";
		allEnabledToCheck = "," + commonspot.clientUI.menus.allEnabledMenuClassesToCheck + ","; 	// make sure list starts and ends with commas so we can find the class name exactly
		if( allEnabledToCheck.indexOf(temp) == -1)
			commonspot.clientUI.menus.allEnabledMenuClassesToCheck += ',' + arrEnabledMenuClasses[i];
	}	
	if( commonspot.clientUI.menus.allEnabledMenuClassesToCheck.length > 0 )
	{
		if( commonspot.clientUI.menus.allEnabledMenuClassesToCheck.charAt(0) == ',' )
			commonspot.clientUI.menus.allEnabledMenuClassesToCheck = commonspot.clientUI.menus.allEnabledMenuClassesToCheck.substring(1);
	}
	
	var allVisibleToCheck = '';
	var arrVisibleMenuClasses = visibleList.split(',');	
	for (var i = 0; i < arrVisibleMenuClasses.length; i++)
	{
		temp = "," + arrVisibleMenuClasses[i] + ",";
		allVisibleToCheck = "," + commonspot.clientUI.menus.allVisibleMenuClassesToCheck + ","; 	// make sure list starts and ends with commas so we can find the class name exactly
		if( allVisibleToCheck.indexOf(temp) == -1)
			commonspot.clientUI.menus.allVisibleMenuClassesToCheck += ',' + arrVisibleMenuClasses[i];
	}	
	if( commonspot.clientUI.menus.allVisibleMenuClassesToCheck.length > 0 )
	{
		if( commonspot.clientUI.menus.allVisibleMenuClassesToCheck.charAt(0) == ',' )
			commonspot.clientUI.menus.allVisibleMenuClassesToCheck = commonspot.clientUI.menus.allVisibleMenuClassesToCheck.substring(1);
	}

	// Enable/Disable or Show/Hide menu classes for top user menu items
	//var fieldsList = 'Contrib,UpdateCredentials,EnableLogout';
	//commonspot.util.enableFromMenuFields(enabledList, fieldsList, 'inline');
	commonspot.util.showFromMenuFields(enabledList, 'Contrib,UpdateCredentials,EnableLogout', 'inline');
	
	// Enable/Disable or Show/Hide menu classes for main menu
	commonspot.util.enableFromMenuFields(enabledList, commonspot.clientUI.menus.allEnabledMenuClassesToCheck );
		
	// Enable/Disable or Show/Hide menu classes for main menu
	commonspot.util.showFromMenuFields(visibleList, commonspot.clientUI.menus.allVisibleMenuClassesToCheck );
};

// create instance
commonspot.clientUI.menus.security = new commonspot.clientUI.menus.securityClass();


/**
 * integrated support
 */
commonspot.clientUI.integratedSupport = {};
commonspot.clientUI.integratedSupport.winRef = null;
commonspot.clientUI.integratedSupport.open = function(obj)
{
	if (typeof obj != 'undefined' && $(obj).hasClassName('disabled'))
	{
		return false;
	}
	else
	{
		if(!commonspot.clientUI.integratedSupport.winRef || commonspot.clientUI.integratedSupport.winRef.closed)
		{
			var width = Math.min(screen.availWidth - 100, 1000);
			var height = Math.min(screen.availHeight - 120, 750);
			var winFeatures = 'top=' + 10 + ',left=' + 10 + ',width=' + width + ',height=' + height + ',resizable,scrollbars=auto';
			commonspot.clientUI.integratedSupport.winRef = window.open('/commonspot/bug-report/index.cfm', 'integratedSupportWin', winFeatures)
		}
		commonspot.clientUI.integratedSupport.winRef.focus();		
	}
}

/**
 * Function to open appropriate legacy dialog for copy/move/rename etc. purpose
 */
function openLegacyCallback(destinationSubsiteURL, destinationSubsiteID, dialogType, strSelectedPageIDs) // dialogType, subsiteurl, subsiteid
{
	if (typeof strSelectedPageIDs != 'undefined')
	{
		var arrSelectedPageIDs = strSelectedPageIDs.split(',');
		var pageID = arrSelectedPageIDs[0]; // Legacy copy, move, delete page dialog does not take multiple pageIDs.
	}
	else
		var pageID = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().pageid;
	
	var urlToOpen;
	switch (dialogType)
	{
		case 'copy':
			urlToOpen = 'csModule=templates/copy-page&pageid=' + pageID + '&actionType=1&ssid=' + destinationSubsiteURL +'&isTemplate=0';
			break;
		case 'move':
			urlToOpen = 'csModule=templates/copy-page&pageid=' + pageID + '&actionType=2&ssid=' + destinationSubsiteURL + '&isTemplate=0';
			break;
		case 'page':
			urlToOpen = 'csModule=legacy/new-page';
			break;
		case 'pagewithtemplate':
			urlToOpen = 'csModule=legacy/new-page&useTemplateID=' + pageID;
			break;
		case 'pageset':
			urlToOpen = 'csModule=legacy/new-pageset&pageid=' + pageID + '&from=Admin&pageset=1';
			break;
		case 'uploadimage':
			urlToOpen = 'csModule=legacy/new-image&requiredPermission=UploadImages';
			break;
		case 'registeredurl':
			urlToOpen = 'csModule=legacy/new-registered-url';
			break;
		case 'uploadeddoc':
			urlToOpen = 'csModule=legacy/new-uploaded-doc';
			break;
	}	
	
	// Open the legacy dialog
	var FullURL = destinationSubsiteURL + 'loader.cfm?' + urlToOpen;
	
	top.commonspot.lightbox.loadLegacyFullURL( FullURL );
}

function uploadFileCallback(destinationSubsiteURL, destinationSubsiteID, dialogType)
{
	commonspot.lightbox.loadSpryURL('/commonspot/dashboard/dialogs/tools/upload-file.html?subsiteURL=' + destinationSubsiteURL + '&subsiteID=' + destinationSubsiteID);
}
 
/**
 * Function to reload Subsite Administration for the passed-in Subsite.
 */
function subsiteAdminCallback(destinationSubsiteURL, destinationSubsiteID, dialogType)
{
	commonspot.clientUI.state.location.resetByGivenSubsiteURL(destinationSubsiteURL);	
	top.commonspot.lightbox.closeCurrent();
}

/**
 * Function to open "Select Subsite" dialog.
 */
commonspot.clientUI.selectSubsite = function(obj)
{
	if (typeof obj !== 'undefined' && $(obj).hasClassName('disabled'))
	{
		return false;
	}
	else
	{
		var currentSubsitePath = commonspot.clientUI.state.location.get().subsiteurl;
		commonspot.lightbox.openDialog(
			'/commonspot/dashboard/dialogs/common/destination-subsite.html' + 
			'?mode=subsite' + 
			'&title=Select Subsite' + 
			'&callback=subsiteAdminCallback' +
			'&requiredPermission=ShowSubsiteAdmin' + 
			'&ismultiselect=0' +
			'&currentSubsitePath=' + currentSubsitePath
		);		
	}
};

/*
* Function to open Current Page Set dialog depending upon a
* valid PageSetID
*/
commonspot.clientUI.currentPageSet = function (obj)
{
	if (typeof obj != 'undefined' && $(obj).hasClassName('disabled'))
	{
		return false;
	}
	else
	{ 
		var pageSetID = commonspot.lview.common.getPageWin().jsPageSetID;	
		if (pageSetID == 0)
		{	
			commonspot.clientUI.showError('The current page you are viewing is not a pageset.');		
			return;
		}	
		commonspot.lightbox.openDialog('/commonspot/dashboard/dialogs/tools/pageset-members.html?pageSetID='+ pageSetID);		
	}
}

// Display Site name onPostLoad of "location" dataset.
commonspot.clientUI.state.dataLoader = {};
commonspot.clientUI.state.dataLoader.onPostLoad = function()
{
	var siteName = commonspot.clientUI.state.location.getSitename();
	$('siteName').innerHTML = '<a href="javascript:;" onclick="navSite()">' + siteName + '</a>';
};
commonspot.data.uiState.dsLocation.addObserver(commonspot.clientUI.state.dataLoader);

/*
* Function to navigate to the site in Dashboard
*/
function navSite()
{
	top.$('page_frame').src = commonspot.data.uiState.dsLocation.getCurrentRow().siteurl;
}