commonspot.index = {};
commonspot.index.switchMode_index = 0;
commonspot.index.switchMode_pageID = 0;
commonspot.index.switchMode_mode = '';
commonspot.index.previewstate = {
		pageID: null,
		submitState: null,
		activateState: null,
		previewState: null
	};

var lviewToggleInitDone = 0;
var modeTarget = {
	pageID: null,
	pageURL: null
};
// Define datasets.
var commonspotLocalData = {};

// Dataset for switching pageMode.
commonspotLocalData.Page_switchMode = new commonspot.spry.Dataset({ xpath: commonspot.data.STRUCT_XPATH });

commonspot.index.openPage = function(contributeMode)
{
	// Update hash (with new mode).
	var hashArgs = commonspot.util.getHashArgs();
	document.location.hash = '#mode=' + contributeMode + '&url=' + hashArgs.url;
};

/**
 * Function to handle click of mode-related View menu options.
 * 	Checks & un-checks appropriate menu options.
 * 	Changes mode.
 */
commonspot.index.changeMode = function(menuItemID, modeState, objID, targetPageID, targetPageURL)
{
	var obj = objID ? $(objID) : null;
	
	if (obj && $(obj).hasClassName('disabled'))
		return false;
	var curPageID, curPageURL, pageID, pageURL;

	if (commonspot.csPage)
	{
		curPageID = commonspot.csPage.id;
		curPageURL = commonspot.csPage.url;
	}
	/*
		if the targetPageID and targetPageURL are passed (Ex: select mode from myPages report results), use it.
		otherwise, get the values from the current page.(changing mode of current page from view menu)
	*/
	pageID = targetPageID ? targetPageID : curPageID;
	pageURL = targetPageURL ? targetPageURL : curPageURL;
	
	/* we need to do this fuzzy math cause sometimes the modestate is number (0-3) 
		and in some cases its string (read,author,edit,approve) */ 
	var mode = (modeState && modeState.length > 1) ? modeState : stateToStr(modeState);

	if (menuItemID)
	{
		var requestedMenuItem = $(menuItemID);
		if (!requestedMenuItem.hasClassName('checkedMenuItem'))	// If already selected, do nothing.
			commonspot.index.selectViewMenuOption(menuItemID);
	}
	if (pageURL && !pageID && mode != 99999) // coming from "my pagesets" while in "my commonspot"
		parent.window.location.hash = '#mode=' + mode + '&url=' + pageURL;
	else if (pageID && mode != 99999)
	{
		// should we always call the command even if we are just loading a page in read mode ? 
		commonspot.index.switchPageMode(pageID, mode);
		modeTarget = { pageID: pageID, pageURL: pageURL };			
	}	
};

/*
* Function to toggle page preview/leave preview
*/
commonspot.index.togglePagePreview = function()
{	
	var setPreview = true;
	var previewText = $('pagePreviewText');
	var previewBtn = $('preview');
	var activateBtn = $('activate');
	var submitBtn = $('submit');
	if(previewText.innerHTML == "Preview")
	{
		previewText.innerHTML = "Leave Preview";
		commonspot.index.previewstate = {
				pageID: commonspot.csPage.pageID,
				submitState: submitBtn.style.display,
				activateState: activateBtn.style.display,
				previewState: previewBtn.style.display
			};		
		previewBtn.title = "Leave preview from current page";
		setPreview = true;
		activateBtn.style.display = 'none';
		submitBtn.style.display = 'none';
	}
	else
	{
		previewText.innerHTML = "Preview";
		previewBtn.title = "Preview the current page";
		setPreview = false;
		activateBtn.style.display = commonspot.index.previewstate.activateState;
		submitBtn.style.display = commonspot.index.previewstate.submitState;
		commonspot.index.previewstate = {
				pageID: null,
				submitState: null,
				activateState: null,
				previewState: null
			};		
	}
	top.$(commonspot.lview.common.PAGE_IFRAME_ID).contentWindow.CS_UI.status.setPreviewMode(setPreview,true);
}

/**
 * Function to select the appropariate View menu mode option (given the menu option ID).
 * 	Unchecks all other mode-related View menu options if found checked.
 */
commonspot.index.selectViewMenuOption = function(menuItemID)
{
	var requestedMenuItem = $(menuItemID);
	if (!requestedMenuItem.hasClassName('checkedMenuItem'))	// If already selected, do nothing.
	{
		// IDs of all mode menu options.
		var arrViewMaenuItemIDs = new Array('view_page_as_published_menu_item', 
														'work_on_this_page_my_changes_menu_item', 
														'work_on_this_page_edit_menu_item', 
														'work_on_this_page_approval_menu_item');
	
		// Loop over. Select requested. Deselect others if found selected.
		for (var i = 0; i < arrViewMaenuItemIDs.length; i++)
		{
			if (arrViewMaenuItemIDs[i] != menuItemID)
				commonspot.util.menus.checkItem(false, arrViewMaenuItemIDs[i]);	
			else
				commonspot.util.menus.checkItem(true, menuItemID);
		}
	}
};

/**
 * Function to select the appropriate View menu mode option (given the mode).
 */
commonspot.index.selectViewMenuMode = function(mode)
{
	switch (mode)
	{
		case 'read':
			commonspot.index.selectViewMenuOption('view_page_as_published_menu_item');
			break;
		case 'author':
			commonspot.index.selectViewMenuOption('work_on_this_page_my_changes_menu_item');
			break;
		case 'edit':
			commonspot.index.selectViewMenuOption('work_on_this_page_edit_menu_item');
			break;
		case 'approve':
			commonspot.index.selectViewMenuOption('work_on_this_page_approval_menu_item');
			break;			
	}
};

commonspot.index.isActiveSwitchModeRequest = function(pageID, mode)
{
	var result = false;
	if (commonspot.index.switchMode_pageID == pageID && commonspot.index.switchMode_mode == mode)
		result = true;
	commonspot.index.switchMode_index = 1;
	commonspot.index.switchMode_pageID = pageID;
	commonspot.index.switchMode_mode = mode;
	return result;
};

/*
 * This function is called from dashboard links 
 * Function changes the mode before the page url called  
 */
commonspot.index.switchPageMode = function(pageID, mode)
{ 
	var LOADER_URL = commonspot.clientUI.state.location.getLoaderURL('siteurl');
	var isActiveSwitchModeRequest = false;
	commonspot.index.switchMode_index++;
	// debugger;
	if (commonspot.index.switchMode_index > 1)
		isActiveSwitchModeRequest = commonspot.index.isActiveSwitchModeRequest(pageID, mode);
	else
	{
		commonspot.index.switchMode_mode = mode;
		commonspot.index.switchMode_pageID = pageID;
	}	
	if (!isActiveSwitchModeRequest)
	{
		var collectionOptions = {onCompleteCallback: onCompleteCallback_switchPageModeCmd};
		var cmds = commonspot.ajax.commandEngine.commandCollectionFactory.getInstance(LOADER_URL, collectionOptions);
		var args = { pageID : pageID, requestedMode: mode };	 	
		var cmdOptions = {datasetRoot: commonspotLocalData, datasetName: 'Page_switchMode' };
		cmds.add('Page', 'switchMode', args, cmdOptions);  	
		cmds.send();	
	}
};

/*
 * This callback function is called when the switchPageMode command returns
 */ 			
function onCompleteCallback_switchPageModeCmd()
{
	if (this.hasAnyError)
		return;  
	var data = commonspotLocalData.Page_switchMode.getData()[0];		
	var requestedMode = this.commands[0].commandArgs.requestedMode;
	var pageID = this.commands[0].commandArgs.pageID;
	var win = commonspot.lview.common.getPageWin();
	
	if (data.code != commonspot.constants.SWITCH_MODE_RESULT_SUCCESS)
		commonspot.dialog.server.show('csModule=security/page-switchmode-finish&modeAttempted=' + requestedMode + '&pageID=' + pageID + '&state=' + data.code);

	if (modeTarget.pageID && requestedMode)
	{
		if (win)
			win.location.href = commonspot.lview.currentPage.getPageFrameUrl(modeTarget.pageURL);
		else if (data.pagemode == requestedMode) // when do we skip first and come to this second condition ???
			parent.window.location.hash = '#mode=' + requestedMode + '&url=' + modeTarget.pageURL;
		else
		{
			/*
				mode switch failed. update the hash to the page mode.
				we should show error based on the data.code which contains the code of error.(see page-lock.cfc)
			*/
			parent.window.location.hash = '#mode=' + data.pagemode + '&url=' + modeTarget.pageURL;
		}
		
		if (data.pagemode == requestedMode)
		{
			commonspot.index.switchMode_index = 0;
			commonspot.index.switchMode_pageID = 0;
			commonspot.index.switchMode_mode = '';
		}
		modeTarget = { pageID: null, pageURL: null };			
	}	
}

/**
 * Function to show or hide site-specific things in Admin UI (Called from onLoad functions of various Admin modules).
 * Hide site-specific UI if (a) mode=server_admin, or (b) url is not specified or /commonspot/admin (or /commonspot/*)
 */
commonspot.index.showHideSiteSpecificUI = function(fromROPS)
{
	if (!fromROPS)
		var fromROPS = 0;
	// Get hash mode and url.
	var hashArgs = commonspot.util.getHashArgs();	
	var mode = hashArgs.mode || commonspot.clientUI.state.mode.MYCS;	
	var url = hashArgs.url;
	var helpWindow = '/commonspot/help/contributors_reference/contributor_reference/commonspot_menu_bar.htm';
	
	switch (mode)
	{
		case 'server_admin':
			helpWindow = '/commonspot/help/administrators_reference/index_CSH.htm#admin_reference/server_administration_dashboard.htm'; 
			break;
		case 'customer_admin':
			helpWindow = '/commonspot/help/administrators_reference/index_CSH.htm#admin_reference/customer_administration.htm'; 
			break; 
		case 'site_admin':
			helpWindow = '/commonspot/help/administrators_reference/index_CSH.htm#admin_reference/site_administration.htm'; 
			break;
		case 'subsite_admin':
			helpWindow = '/commonspot/help/administrators_reference/index_CSH.htm#admin_reference/subsite_administration.htm'; 
			break; 
		case 'user_admin':
			helpWindow = '/commonspot/help/administrators_reference/index_CSH.htm#admin_reference/user_administration.htm'; 
			break;
		case 'group_admin':
			helpWindow = '/commonspot/help/administrators_reference/index_CSH.htm#admin_reference/group_administration.htm'; 
			break;
		case 'mycs':
			helpWindow = '/commonspot/help/contributors_reference/index_CSH.htm#contributor_reference/my_commonspot1.htm'; 
			break;
			
		default:
			helpWindow = '/commonspot/help/contributors_reference/index_CSH.htm#contributor_reference/commonspot_menu_bar.htm';   
			break;
	}
	$('thispagehelp').href =  helpWindow;
	// Hide site-specific UI if (a) mode=server_admin, or (b) url is not specified or /commonspot/admin (or /commonspot/*)
	if (url.indexOf('/commonspot/') == 0)
		showHideMenus('hide');
	else // Display otherwise.
		showHideMenus('show');

	switch (mode)
	{ 
		case 'server_admin':			
		case 'customer_admin': 
		case 'user_admin': 
		case 'group_admin':
			$('quickFindContainer').style.display = 'none';
			break;
		default:
			$('quickFindContainer').style.display = 'inline';
			break;
	}

	if (fromROPS > 0)
		showHideROPSMenus(fromROPS);
	/*
		commonspot.index.showHideSiteSpecificUI gets called multiple times page onload of index.html
		so to handle Lview one lviewToggleInitDone variable is used for now to execute 
		commonspot.lview.left.displayManagerClass.prototype.showHide() once.
	*/
	if (lviewToggleInitDone == 0)
	{
		lviewToggleInitDone = 1;
		switch (mode)
		{
			case 'read':
			case 'author':
			case 'edit':
			case 'approve':
				if(commonspot.util.cookie.readCookie('CSLVIEWOPENCLOSE') == 1)
					commonspot.lview.left.displayManagerClass.prototype.showHide('');
		}
	}
};

window.onresize = function()
{
	var basemode = commonspot.data.uiState.dsMode.getCurrentRow().baseMode;
	if (basemode)
	{
		var thisResize = eval('commonspot.'+basemode+'.common.uiWatcher');
		if (typeof thisResize == 'function')
			thisResize();
	}
};
/**
 * Function to show or hide site-specific things in Admin UI (Called from inside commonspot.index.showHideSiteSpecificUI above).
 */
function showHideMenus(showOrHide)
{
	var blockOrNone = (showOrHide == 'show') ? 'block' : 'none';

	// 1. Remove menus: My CommonSpot, My Content, New, Tools, Reports.
	$('homeMenu').setStyle({ display: blockOrNone });
	$('my_content_btn').setStyle({ display: blockOrNone });
	$('new_btn').setStyle({ display: blockOrNone });
	$('tools_btn').setStyle({ display: blockOrNone });
	$('reports_btn').setStyle({ display: blockOrNone });
	
	// 2. Remove 'Site:' label and text from menu bar in upper right corner.
	// Note: "inline" (not "block") used for this to preserve its alignment.
	var inlineOrNone = (showOrHide == 'show') ? 'inline' : 'none';
	$('siteNameContainer').setStyle({ display: inlineOrNone });
	if (inlineOrNone == 'inline')
		commonspot.clientUI.state.dataLoader.onPostLoad();
	// 3. In the Admin menu, hide Site Administration, Subsite Administration.
	$('siteAdminMenuOption').setStyle({ display: blockOrNone });
	$('subsiteAdminMenuOption').setStyle({ display: blockOrNone });

	//4. make sure those are on... since it might be set by showHideROPSMenus()
	$('customerAdminMenuOption').style.display = 'block';
	$('userAdminMenuOption').style.display = 'block';
	$('groupAdminMenuOption').style.display = 'block';
	$('user_profile_span').style.display = 'inline';
	$('admin_menu_separator').style.display = 'block';
}

function showHideROPSMenus(type)
{
	if (type == 1) //cluster ROPS
	{
		$('siteNameContainer').style.display = 'none';
      $('siteAdminMenuOption').style.display = 'none';
      $('subsiteAdminMenuOption').style.display = 'none';
		$('customerAdminMenuOption').style.display = 'none';
	}

	$('userAdminMenuOption').style.display = 'none';
	$('groupAdminMenuOption').style.display = 'none';
	$('user_profile_span').style.display = 'none';
	$('admin_menu_separator').style.display = 'none';

	$('homeMenu').style.display = 'none';
	$('my_content_btn').style.display = 'none';
	$('new_btn').style.display = 'none';
	$('reports_btn').style.display = 'none';

	$('quickFindContainer').style.display = 'none';
}

function doQuickFind()
{
	var formType= $F('quickFindFormType');
	var searchCriteria = $F('quickFindSearchString');
	$('quickFindSearchString').blur();
	if (formType === 'page')
	{
		var args =
		{
			searchCriteria: searchCriteria,
			searchTypeList: 'all',
			subsiteFilter: 0,
			subsiteFilterPath: commonspot.clientUI.state.location.get().siteurl,
			includeChildSubsites: 1,
			includeInactive: 'Always',
			orderBy: 'score',
			orderByDirection: 'Desc',
			recordsPerPage: 25
		};
		var url = '/commonspot/dashboard/dialogs/tools/search-results.html?' + Object.toQueryString(args);
		commonspot.lightbox.openDialog(url);
	}
	else // image
	{
		var args =
		{
			mode: 'quicksearch',
			searchString: searchCriteria,
			searchOperator: 'contains',
			searchTypeList: 'all',
			imageFilter: 'AllImages',
			subsiteFilter: 0,
			includeChildSubsites: 1,
			orderBy: 'DateContentLastModified',
			orderByDirection: 'desc'
		};
		var url = '/commonspot/dashboard/dialogs/tools/image-gallery-results.html?' + Object.toQueryString(args);
		commonspot.lightbox.openDialog(url);
	}
}

function stateToStr(modeNum)
{
	var modeStr =	  modeNum == 0 ? 'read'
						: modeNum == 1 ? 'author'
						: modeNum == 3 ? 'edit'
						: modeNum == 2 ? 'approve'
						: '99999'; // oops...
	return modeStr;
}

commonspot.index.reloadCommonspotPage = function()
{
	commonspot.lightbox.closeAllDialogs();
	setTimeout(window.location.reload(true),100);
}

/*
 * Function to call the delete confirmation dialog.
 */
function invokeCommonDelete()
{ 
	var pageObjects = commonspot.csPage;	
	commonspotLocal.pageList.deleteObject(pageObjects.id, parseInt(pageObjects.pagetype), pageObjects.title, false);
}


