/**
 * manages lview
 */
commonspot.lview = {};
commonspot.lview.bHandleOuterFrameSizing = 1;
commonspot.lview.pageNavTimeOutID = 0;
commonspot.lview.shouldClearAllPanels = 0; // Used to decide whether clear lview panel contents or not

// Variables used in the context of non-CommonSpot navigation.
commonspot.lview.isNonCSNavigation = false; 				// Used for restoring panels, menus, etc; Loading page in iframe.
commonspot.lview.isNonCSNavigationSmallScope = false; // Used to check non-CS navigation in ui-watcher only (and killed).
commonspot.lview.isComingFromNonCSPage = false; 		// Used while initializing panels.

// Variable to hold a master list of enabled menu classes to enable/disable. Any menu class passed in enabledMenuClasses wll be added to this list.
commonspot.lview.allEnabledMenuClassesToCheck = '';

// Variable to hold a master list of visible menu classes that have ever been shown/hidden
commonspot.lview.allVisibleMenuClassesToCheck = '';

/*
 * basic specs
 */
commonspot.lview.BASE_MODE = 'lview'; // base mode that's us

/**
 * methods and data common to all lview modes (read/work/compare)
 */
commonspot.lview.common = {};

commonspot.lview.common.PAGE_IFRAME_ID = 'page_frame'; // also its name
commonspot.lview.common.FRAME_CONTAINER = 'left_framecontainer';

commonspot.isIE = (navigator.userAgent.indexOf('MSIE') == -1) ? 0 : 1;

/*
 * rtns a reference to the document displayed in the lview iframe
 */
commonspot.lview.common.getPageDoc = function()
{
	var lviewIframe = $(commonspot.lview.common.PAGE_IFRAME_ID)
	var pgDoc = lviewIframe.contentDocument;
	return pgDoc;
};

/*
 * rtns a reference to the window displayed in the lview iframe
 */
commonspot.lview.common.getPageWin = function()
{
	var lviewIframe = $(commonspot.lview.common.PAGE_IFRAME_ID)
	var pgWin = lviewIframe.contentWindow;
	return pgWin;
};

/*
 * rtns a reference to the left hand panel that is open in the accordion
 */
commonspot.lview.common.getOpenLeftPanel = function()
{
   var index = commonspot.data.uiState.lview.left.dsOpenFrame.getCurrentRow().openPanelIndex;
   return commonspot.data.uiState.lview.left.dsPanels.findRowsWithColumnValues({id: index});
};
/*
 * rtns a reference to the CS_UI object on the page shown in the lview iframe
 */
commonspot.lview.common.getCS_UIObj = function()
{
	var csUI;
	var pgWin = commonspot.lview.common.getPageWin();
	if(pgWin.CS_UI)
		csUI = pgWin.CS_UI;
	return csUI;
};

/*
 * close lview, ie, show standalone page
 */
commonspot.lview.common.close = function()
{
	if (commonspot.csPage.url)
		document.location.href = commonspot.csPage.url;
	else
		commonspot.dialog.client.alert('Invalid CommonSpot page.', {title: 'Error'});
};

commonspot.lview.currentPage = {};

/*
 * @return string: returns url of loader for the current lview page
 */
commonspot.lview.currentPage.getLoaderURL = function()
{
	return commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().loader;
};

/*
 * @return string: returns last time page loaded in milliseconds for the current lview page
 */
commonspot.lview.currentPage.getLoadTimestamp = function()
{
	return commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().loadtimestamp;
};

/*
 * updates dataset that tracks current lview page
 * @param string url: server-relative url of pg
 * @param int pageID
 * @param string subsiteRoot
 * @param string siteRoot 
 * @param boolean dontUpdateHash: optional. unless passed and true, update url hash with this change
 */
commonspot.lview.currentPage.set = function(url, pageID, title, pageType, ssContextInfo, dontUpdateHash)
{
	commonspot.clientUI.state.location.set(ssContextInfo);
	
	// Update currentPage dataset - will trigger obververs
	commonspot.data.uiState.lview.dsCurrentPage.update({url: url, pageid: pageID, title: title, pagetype: pageType});
	
	if(!dontUpdateHash)
		commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage();
};

/*
 * updates dataset that tracks URL, only, of current lview page
 * expects that arriving page will call commonspot.lview.currentPage.onPageArrival, to update other pg info
 * @param string url: server-relative url of pg
 */
commonspot.lview.currentPage.setURL = function(url, dontUpdateHash, qstring)
{
   var dt = new Date().getTime();
	qstring = qstring ? qstring : '';
	commonspot.data.uiState.lview.dsCurrentPage.update({url: url, loadtimestamp: dt, qstring: qstring});
	
	if(!dontUpdateHash)
		commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage();
};

/*
 * called by cs pages arriving in lview iframe
 * @param string url: server-relative pg url
 * @param int pageID: pageID
 * @param string subsiteRoot
 * @param string siteRoot
 * @param string mode: contribute mode pg is in
 */
commonspot.lview.currentPage.onPageArrival = function( pageobj )
{
	var mode = pageobj.mode;
	var url = pageobj.url;
	var pageID = pageobj.id;
	var title = pageobj.title;
	var pageType = pageobj.pagetype;
	var subsiteRoot = pageobj.subsiteRoot; 
	var siteRoot = pageobj.siteRoot;
	var enabledMenuClasses = pageobj.enabledMenuClasses;
	var visibleMenuClasses = pageobj.visibleMenuClasses;
	var showSubmit = pageobj.showPageSubmit;
	var authorOK = pageobj.authorok;
	var approvalStatus = pageobj.approvalstatus; // Note casing (lower-cased).
	var temp = '';
	var subsiteContextInfo = pageobj.subsiteContext;
	// Clear page-transition timeout.
	clearTimeout(commonspot.lview.pageNavTimeOutID);

	if( pageType == 6 )  //( pageType != 0) // empty page set
	{
			commonspot.lview.handlePageNavTimeout();		// call same function as if it was a non-commonspot page
			return;
	}
	commonspot.data.uiState.lview.dsCurrentPageType.update({isValidCSPage: true});	
		
	// 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.lview.allEnabledMenuClassesToCheck) and 
	// if not, add it to the list.
	var allEnabledToCheck = '';
	var arrEnabledMenuClasses = enabledMenuClasses.split(',');	
	for (var i = 0; i < arrEnabledMenuClasses.length; i++)
	{
		temp = "," + arrEnabledMenuClasses[i] + ",";
		allEnabledToCheck = "," + commonspot.lview.allEnabledMenuClassesToCheck + ",";	// make sure list starts and ends with commas so we can find the class name exactly
		if (allEnabledToCheck.indexOf(temp) == -1) 
			commonspot.lview.allEnabledMenuClassesToCheck += ',' + arrEnabledMenuClasses[i];
	}	
	if (commonspot.lview.allEnabledMenuClassesToCheck.length > 0)
	{
		if (commonspot.lview.allEnabledMenuClassesToCheck.charAt(0) == ',')
			commonspot.lview.allEnabledMenuClassesToCheck = commonspot.lview.allEnabledMenuClassesToCheck.substring(1);
	}

	var allVisibleToCheck = '';
	var arrVisibleMenuClasses = visibleMenuClasses.split(',');	
	for (var i = 0; i < arrVisibleMenuClasses.length; i++)
	{
		temp = "," + arrVisibleMenuClasses[i] + ",";
		allVisibleToCheck = "," + commonspot.lview.allVisibleMenuClassesToCheck + ",";	// make sure list starts and ends with commas so we can find the class name exactly
		if (allVisibleToCheck.indexOf(temp) == -1) 
			commonspot.lview.allVisibleMenuClassesToCheck += ',' + arrVisibleMenuClasses[i];
	}	
	if (commonspot.lview.allVisibleMenuClassesToCheck.length > 0)
	{
		if (commonspot.lview.allVisibleMenuClassesToCheck.charAt(0) == ',')
			commonspot.lview.allVisibleMenuClassesToCheck = commonspot.lview.allVisibleMenuClassesToCheck.substring(1);
	}	
	
	// Restore context post non-CS navigation.
	if (commonspot.lview.isNonCSNavigation)
	{
		// Reset Non-CS navigation indicator.
		commonspot.lview.isNonCSNavigation = false;
		commonspot.lview.isComingFromNonCSPage = true;
		
		// Reset breadcrumbs: Note: Breadcrumbs are drawn afresh by default.
			
		// Show lview accordion panels.
		commonspot.lview.left.panelManager.setLeftPaneState('activeframe');
		
		// Show all of the Page View menus (dark blue menus).
		$('pagemenu').style.display = 'block';
	}
	else
		commonspot.lview.isComingFromNonCSPage = false;
	
	// Get "From-page" site.
	var location = commonspot.clientUI.state.location.get();
	var startSiteURL = location.siteurl;
	
	/* NEEDSWORK: compare is a mode of the dashboard, not the pg, so don't change dash to page's mode if comparing
		...but does a new pg ever arrive in lview when we're comparing? compare is in a new window*/		
	commonspot.lview.bHandleOuterFrameSizing = 1;		

	var _mode = commonspot.data.uiState.dsMode.getCurrentRow().mode;
	
	if (_mode != 'compare')
		commonspot.clientUI.state.mode.set(mode, true); // skip updating url hash for both of these...	

   var dt = new Date().getTime();   
  	commonspot.lview.currentPage.set(url, pageID, title, pageType, subsiteContextInfo, true);
	
	// Load the specified page in the main iframe & associated data.
	// Call to commonspot.lview.currentPage.loadPage() NOT needed here.	
	commonspot.lview.currentPage.loadPageData();	
	
   commonspot.data.uiState.menus.dsPageMenuClasses.update( 
											{enabledMenuClasses: enabledMenuClasses, 
											 visibleMenuClasses: visibleMenuClasses, 
											 showSubmit: showSubmit, 
											 pageid: pageID, 
											 loadtimestamp: dt, 
											 approvalStatus: approvalStatus} );

											 
	// Fix to put page in "author" mode if arrived at by clicking "Work on this Page" option in the entrance tab.
	// Note: setHashFromModeAndPage()is by-passed (in the IF part below) since it does not seem to do that.						 
	var hashArgs = commonspot.util.getHashArgs();
	var newMode = hashArgs.mode || commonspot.clientUI.state.mode.MYCS;
	if (commonspot.clientUI.isComingFromEntrance && newMode == 'author')
	{
		commonspot.clientUI.isComingFromEntrance = false;
		
		if (mode != 'author') // no need to set mode if already in author mode 7042
			commonspot.index.changeMode('work_on_this_page_my_changes_menu_item',1);
	}
	else
		commonspot.clientUI.state.mode.urlHash.setHashFromModeAndPage(); // update it now that they're both done	
	
	// disable blue page menus for authoring disabled site
	if (!authorOK)
		$('pagemenu').style.display = 'none';		

	// set initial state of page menu items and the display items they control
	commonspot.lview.common.breadcrumbs.menuItem.onDataChanged();
		
	// Get "To-page" site.
	location = commonspot.clientUI.state.location.get();
	var endSiteURL = location.siteurl;

	// Update siteName if from-page & to-page sites are different.
	if (endSiteURL != startSiteURL)
		$('siteName').innerHTML = location.sitename;
	
	// Show / hide Preview Button, Container, Element Tools and Add Element Links icons.
	if (mode == 'read')
	{
		$('preview').style.display = 'none';
		$('breadcrumb_mode_icons').style.display = 'none';	
	}
	else
	{
		$('preview').style.display = 'block';
		$('breadcrumb_mode_icons').style.display = 'block';	
	}
	
	// Show appropriate View menu option selected.
	commonspot.index.selectViewMenuMode(mode);

	//commonspot.lightbox.closeAllDialogs();			
};

commonspot.lview.currentPage.fromSameSite = function()
{
};

commonspot.lview.currentPage.fromOtherSiteOtherCustomerAnon = function()
{
};

commonspot.lview.currentPage.fromOtherSiteOtherCustomerAuth = function()
{
};

commonspot.lview.currentPage.fromOtherSiteSameCustomer = function()
{ 
};

/**
 * Function to handle timeout during page navigation most likely caused by navigation to an external page.
 */
commonspot.lview.handlePageNavTimeout = function()
{
	// Clear page-transition timeout.
	clearTimeout(commonspot.lview.pageNavTimeOutID);
	
	// bail if a dialog is up, assuming it's switchmode failure, which will reload us correctly
	if(commonspot.lightbox.stack.length > 0)
		return;
	
	// Set Non-CS navigation indicator.
	commonspot.lview.isNonCSNavigation = true;

	commonspot.data.uiState.lview.dsCurrentPageType.update({isValidCSPage: false});
	// Clear lview panels.
	commonspot.lview.left.panelManager.setLeftPaneState('inactiveframe');
	
	// Clear the breadcrumb bar. Add link to return to last CS page.
	$('breadcrumbs').innerHTML = '<span id="breadcrumbsMsg">Return to <a href="javascript:;" onclick="commonspot.lview.goToLastCSPage();">last CommonSpot page</a></span>';
	
	// Hide all of the Page View menus (dark blue menus).
	$('pagemenu').style.display = 'none';
	
	// Hide Preview Button, Container, Element Tools and Add Element Links icons on breadcrumb bar if in Read mode or on non-CS page.
	$('preview').style.display = 'none';
	$('breadcrumb_mode_icons').style.display = 'none';	
};

/**
 * Function to take user back to the last CS page from an external page on click of the breadcrumbs link.
 */
commonspot.lview.goToLastCSPage = function()
{
	// Set flag to indicate from-non-CS navigation.
	commonspot.lview.isComingFromNonCSPage = true;
	commonspot.lview.isNonCSNavigationSmallScope = true;
	
	commonspot.lview.currentPage.loadPage();
};

commonspot.lview.currentPage.onPageUnload = function()
{
	clearTimeout(commonspot.lview.pageNavTimeOutID);
	commonspot.lview.pageNavTimeOutID = setTimeout(commonspot.lview.handlePageNavTimeout, 5000);
};

/* 
 * Function to cause the main IFRAME to load the page specified in the dsCurrentPage dataset
 */
commonspot.lview.currentPage.loadPage = function()
{
	var qstring = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().qstring;
	var url = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().url;
	var lviewIframe = top.$(commonspot.lview.common.PAGE_IFRAME_ID);
	if (qstring)
		url = url + qstring;
	url = commonspot.lview.currentPage.getPageFrameUrl(url);
	
	if ((url && (lviewIframe.src.indexOf(url) == -1)) || commonspot.lview.isNonCSNavigation)
		lviewIframe.src = url;
	else
		clearTimeout(commonspot.lview.pageNavTimeOutID);
};

commonspot.lview.currentPage.getPageFrameUrl = function(url)
{
	if(url && (url.indexOf('cs_pgIsInLView') < 0))
	{
		var separator = (url.indexOf('?') >= 0) ? '&' : '?';
		url += separator + 'cs_pgIsInLView=1';
	}
	return url;
};

/*
 * Function to load data for the current lview page.
 */
commonspot.lview.currentPage.loadPageData = function()
{
	var left_framecontainer = $(commonspot.lview.common.FRAME_CONTAINER);
	var curRow = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow();
	var pageID = curRow.pageid;
	if (left_framecontainer && commonspot.lview.left)
	{
		var currentPanelIndex = commonspot.data.uiState.lview.left.dsOpenFrame.getCurrentRow().openPanelIndex;
		var curPanelObj = commonspot.data.uiState.lview.left.dsPanels.findRowsWithColumnValues({panelid: currentPanelIndex}, true);
		commonspot.lview.left.panelManager.updatePanel(curPanelObj, 2, commonspot.data.uiState.lview.left.dsPanels.getRowNumber(curPanelObj));
	}
	if (pageID > 0)
	{
      var pgWin = commonspot.lview.common.getPageWin();		
		var loader = commonspot.clientUI.state.location.getLoaderURL('subsiteurl');
		var dsRoot = {datasetRoot: commonspot.data.page};
		var cmdCollection = commonspot.ajax.commandEngine.commandCollectionFactory.getInstance(loader);
		if (curRow.pagetype == 0)
		{
			cmdCollection.add('Page', 'getInfo', {pageID: pageID}, dsRoot);
			cmdCollection.add('PageSecurity', 'getUserRights', {pageID: pageID}, dsRoot);
			cmdCollection.add('Page', 'getParentTemplates', {pageID: pageID}, dsRoot); // NEEDSWORK

			var mode = commonspot.data.uiState.dsMode.getCurrentRow().mode;
			cmdCollection.send();
		}

	}		
};


commonspot.lview.currentPage.switchPageModeCmdResponseHandler = function(command, xmlStr, xmlDoc, responseStatus)
{
	var responseNodes = tmt.xml.evaluateXPath(xmlDoc, '/item/data/pagemode');
	if(responseNodes.length == 1 && responseNodes[0].textContent)
	{
		var requestedMode = command.commandArgs.requestedMode;
		var newMode = responseNodes[0].textContent;
		if (newMode != requestedMode)
			alert('lview.currentPage.switchPageModeCmdResponseHandler was unable to change the page to ' + requestedMode + ', got ' + newMode + ' instead.');
		else if(newMode != commonspot.data.uiState.dsMode.getCurrentRow().mode)
		{
			var lviewDoc = commonspot.lview.common.getPageDoc();
			if(lviewDoc && lviewDoc.commonspot && lviewDoc.commonspot.csPage && lviewDoc.commonspot.csPage.mode && lviewDoc.commonspot.csPage.mode == newMode)
				{}
			else
				lviewDoc.location.reload();
		}
	}
	else
		alert('lview.currentPage.switchPageModeCmdResponseHandler encountered an error handling the server response.');
};


/*
 * function to dim and undim lview page area
 * NEEDSWORK: wip, also not called yet
 */
commonspot.lview.currentPage.dimIframe = function(dim)
{
	var opacity = dim ? 0.3 : 1.0;
	var backgroundColor = dim ? '#669' : '#fff';
	var lviewIframe = $(commonspot.lview.common.PAGE_IFRAME_ID);
	lviewIframe.style.opacity = opacity;
	lviewIframe.style.backgroundColor = backgroundColor;
};

commonspot.lview.common.layoutManager = {};
commonspot.lview.common.layoutManager.onDataChanged = function(dataset)
{
	var lviewModeSelect = $('mode_select');
	lviewModeSelect.onchange = 'commonspot.clientUI.state.mode.set(this.options[this.selectedIndex].value)';
};

commonspot.data.uiState.lview.dsShowLeftSide.addObserver(commonspot.lview.common.menuManager);
commonspot.data.uiState.lview.dsContributeModeLocked.addObserver(commonspot.lview.common.menuManager);

/*
 * menu management common to all of lview
 */
commonspot.lview.common.menus = {};

commonspot.lview.common.menus.init = function()
{
	var menuOptions =
	{
		menuBarID: 'pageCommonMenu',
		doMenuPositioning: false
	};
	var menuDefs =
	{
		page_props_btn: 'page_props_menu',
		page_actions_btn: 'page_actions_menu',
		page_manage_btn: 'page_manage_menu',
		page_links_btn: 'page_links_menu',
		page_templates_btn: 'page_templates_menu',
		page_view_btn: 'page_view_menu'
	};
	var pageMenuBar = new cs_MenuBar(menuOptions, menuDefs);
};

commonspot.lview.common.menus.setPageButtonState = function(showSubmit, approvalStatus, enabledMenuClasses)
{
	top.$('submit').style.display = showSubmit ? 'block' : 'none';
	
	var hasAuthorRights = commonspot.util.hasPermission('PageAuthor', enabledMenuClasses);
	var canActivate = hasAuthorRights && (approvalStatus != 0); // approvalStatus == SitePages.ApprovalStatus: 0=active, 1=inactive, 2=activate when published
	top.$('activate').style.display = canActivate ? 'block' : 'none';
};

/*
 * base class to manage security-related updates to lview page menus
 */
commonspot.lview.common.menus.securityUpdateClass = function()
{
   //var lviewIframe = $(commonspot.lview.common.PAGE_IFRAME_ID)
   this.dataset = commonspot.data.uiState.menus.dsPageMenuClasses;
  	this.dataset.addObserver(this);
};

/*
 * observer that adjust page menu items based on user's rights on this pg
 * @param spry_dataset dataset
 * NEEDSWORK: what items get enabled and disabled, by what?
 */
commonspot.lview.common.menus.securityUpdateClass.prototype.onDataChanged = function(dataset)
{
	var data = this.dataset.getCurrentRow();

	// enable/disable menu classes
	commonspot.util.enableFromMenuFields(data.enabledMenuClasses, commonspot.lview.allEnabledMenuClassesToCheck );	

	// show/hide menu classes
	commonspot.util.showFromMenuFields(data.visibleMenuClasses, commonspot.lview.allVisibleMenuClassesToCheck );	

   commonspot.lview.common.menus.setPageButtonState(data.showSubmit,data.approvalStatus,data.enabledMenuClasses);
};


// create instance
commonspot.lview.common.menus.securityUpdate = new commonspot.lview.common.menus.securityUpdateClass();


/*
 * lview breadcrumbs package
 */
commonspot.lview.common.breadcrumbs = {};

/*
 * Show Breadcrumbs menu item class
 */
commonspot.lview.common.breadcrumbs.menuItemClass = function()
{ 		
	this.dataset = commonspot.data.uiState.lview.dsShowBreadcrumbs;
	this.menuItemID = 'show_breadcrumbs_menu_item';
	// NEEDSWORK: should update layout and menu item when lview loads, based on dataset, but onPostLoad doesn't fire
	// 	think that's because we're not registered yet
	// tried calling onDataChanged() right after instantiation, be html object doesn't exist yet
	//		need another init phase to do this right
	// problem is the same for all these show.hide menu items
	//this.onPostLoad = this.onDataChanged; 
	this.dataset.addObserver(this);
};

/*
 * menu item click handler
 */
commonspot.lview.common.breadcrumbs.menuItemClass.prototype.onClick = function()
{
	var show = !this.dataset.getCurrentRow().show;
	this.dataset.update({show: show}); 
	 
	// Set Breadcrumb's show hide status in Cookies 
	var showBreadcrumbs = readCookie('showBreadcrumbs') || 1; 
	showBreadcrumbs = show = (showBreadcrumbs == 1)? 0 : 1; 
	this.dataset.update({show: show});  
	 
	createCookie('showBreadcrumbs', showBreadcrumbs, 1);  
};

/*
 * menu item dataset observer; shows/hides breadcrumbs, checks/unchecks menu item
 */
commonspot.lview.common.breadcrumbs.menuItemClass.prototype.onDataChanged = function(dataset)
{
	var show = this.dataset.getCurrentRow().show;
	 
	if(show)
		$('breadcrumbs_toolbar').show();
	else
		$('breadcrumbs_toolbar').hide();
	commonspot.util.menus.checkItem(show, this.menuItemID);  
};

// create instance
commonspot.lview.common.breadcrumbs.menuItem = new commonspot.lview.common.breadcrumbs.menuItemClass();


/*
 * base class for rendering of breadcrumbs
 */
commonspot.lview.common.breadcrumbs.rendererClass = function()
{
	this.dsModeInfo = commonspot.data.uiState.dsMode;
	this.dsPageInfo = commonspot.data.page.Page_getInfo;
	this.dsPageInfo.addObserver(this);	
};

/*
 * observer that renders breadcrumbs when its target dataset changes
 */
commonspot.lview.common.breadcrumbs.rendererClass.prototype.onDataChanged = function(dataset)
{
	var pageInfo = this.dsPageInfo.getCurrentRow();
	var pageURL = pageInfo.subsiteurl + pageInfo.filename;
	var pageTitle = pageInfo.title;
	var modeString = commonspot.csPage.publicationState + ' - ' + this.dsModeInfo.getCurrentRow().title;
	var parentElement = top.$('breadcrumbs');	
	if (commonspot.csPage.requestedVersionTimestamp != '')
	{
		modeString = '';
		pageTitle = commonspot.csPage.title;
	}	 
	this.render(parentElement, pageURL, pageTitle, modeString);
	 
	// Show hide Breadcrumbs as per the cookie variable.
	var showBreadcrumbs = readCookie('showBreadcrumbs') || 1; 		 
	 
	if( showBreadcrumbs == 1 )  
		$('breadcrumbs_toolbar').show();   
	else
	{
		$('breadcrumbs_toolbar').hide();  
		$('show_breadcrumbs_menu_item').removeClassName('checkedMenuItem');
	}    
};

commonspot.lview.common.breadcrumbs.rendererClass.prototype.render = function(parentElement, pageURL, pageTitle, mode)
{
	addDir = function(parentElement, cumulativePath, title)
	{
		var span = document.createElement('span');
		span.className = 'directory';
		var link = document.createElement('a');
		link.href = "javascript: commonspot.lview.common.breadcrumbs.onClick('" + cumulativePath + "')";
		link.innerHTML = title;
		link.title = cumulativePath;
		span.appendChild(link);
		parentElement.appendChild(span);
	};
	addElement = function(parentElement, tagName, content, htmlAttributes)
	{
		elem = document.createElement(tagName);
		elem.innerHTML = content;
		for(var a in htmlAttributes)
			elem[a] = htmlAttributes[a];
		parentElement.appendChild(elem);
	};
	
	var location, title;
	var aPath = pageURL.split('/');
	var cumulativePath  = '/';
	parentElement.innerHTML = '';
	
	location = commonspot.clientUI.state.location.get();
	
	if (location.sitetype == 1)
		addDir(parentElement, cumulativePath, location.sitename);

	for (var i = 1; i < aPath.length - 1; i++)
	{
		cumulativePath += aPath[i] + '/';
		title = aPath[i];
		addDir(parentElement, cumulativePath, title);
	}
	addElement(parentElement, 'span', pageTitle, {id: 'page_title', className: 'file', title: pageURL});
	if (mode != '')
		addElement(parentElement, 'span', '(' + mode + ')', {id: 'page_mode_status'});
	
};

// create instance
commonspot.lview.common.breadcrumbs.renderer = new commonspot.lview.common.breadcrumbs.rendererClass();

/**
 * Function to open "Subsite Listing" dialog on click of breadcrumb subsite.
 */
commonspot.lview.common.breadcrumbs.onClick  = function(path)
{
	commonspot.dialog.client.show('/commonspot/dashboard/dialogs/pageview/subsite-listing.html?subsite=' + path);	
};

/*
 * adjusts anything in lview that needs regular updates
 */
commonspot.lview.common.uiWatcher = function()
{
	if(commonspot.data.uiState.dsMode.getCurrentRow().baseMode == commonspot.lview.BASE_MODE)
	{
		commonspot.lview.common.layoutManager.adjustLayout();
	}
};

/*
 * called regularly to resize and reposition objects in lview layout
 */
commonspot.lview.common.layoutManager.adjustLayout = function()
{
	/*
	 * NEEDSWORK:
	 * 	- ideally we don't do any of this, hopefully better css could make some or all of it unnccessary
	 * 		vertical probably is needed
	 * 		horizontal only needed for Firefox, IE adjusts by itself w current css
	 * 	- if window is too small, pagemenu btns wrap, or lview_right drops below left
	 * 		don't know a way around that
	 * 	- overflowY = 'scroll' is temp until constant size accordion
	 */

	// resize left side to available height
   if (!$(commonspot.lview.common.FRAME_CONTAINER))
      return;
	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';

	var tabData = commonspot.data.uiState.lview.left.dsOpenFrame.getCurrentRow();
   var furnitureHt = 111 + (tabData.tabCount * 20);
   var lviewht = winSize.height - furnitureHt;
	commonspot.data.uiState.lview.left.dsOpenFrame.update({panelHeight: lviewht});
	lviewIframe.style.height = lviewht + 'px';
};

/*
 * adjusts iframe to fit in space remaining after left side shows or not
 */
 
commonspot.lview.common.layoutManager.stretchRight = function ()
{	// NEEDSWORK: doesn't work right
	var left = $('lview_left');
   var leftSideWidth = parseInt(left.offsetWidth);
   var show = '';
	var panesContainer = $(commonspot.lview.left.PANES_CONTAINER);

   if (leftSideWidth != 0)
   {
      leftSideWidth = 0;
		if(panesContainer)
			panesContainer.style.display = 'none';
      show = false;
   }   
   else
   {
      leftSideWidth = 192;
		if(panesContainer)
			panesContainer.style.display = '';
      show = true;
   }
	left.style.width = leftSideWidth + "px";
   if (show)
      commonspot.lview.left.panelManager.onShow(show);
	var backgroundImage = 'url(/commonspot/dashboard/images/controls/toggle_' + (show ? 'left' : 'right') + '_orange.gif)';
	$('toggle').style.backgroundImage = backgroundImage;      
};


/**
 * methods and data common to all lview contribute modes
 */
commonspot.lview.contribute = {};

/**
 * authorModeUIClass: base class for objs that manage Show Containers, Show Element Tools, Show New Element Links
 * 
 * @param {String} csUIFunctionName: name of CS_UI function to call
 */
commonspot.lview.contribute.authorModeUIClass = function(csUIFunctionName)
{
	this.csUIFunctionName = csUIFunctionName;
};
commonspot.lview.contribute.authorModeUIClass.prototype.onClick = function()
{
	var csUI = commonspot.lview.common.getCS_UIObj();
	if(csUI && csUI.status)
		csUI.status[this.csUIFunctionName](true);
};

// create instances
commonspot.lview.contribute.showContainers = new commonspot.lview.contribute.authorModeUIClass('showContainerTools');
commonspot.lview.contribute.showElementTools = new commonspot.lview.contribute.authorModeUIClass('showElementTools');
commonspot.lview.contribute.showNewElementLinks = new commonspot.lview.contribute.authorModeUIClass('showNewElementLinks');



commonspot.data.uiState.lview.dsCompare.addObserver(commonspot.lview.contribute.menuManager);


/*
 * manages lview read mode
 */
commonspot.lview.read = {};


/**
 * manages lview work mode
 */
commonspot.lview.work = {};


/**
 * manages lview compare mode
 */
commonspot.lview.compare = {};


commonspot.lview.compare.compareManager = {};
commonspot.lview.compare.compareManager.onDataChanged = function(dataset)
{
};
commonspot.data.uiState.lview.dsCompare.addObserver(commonspot.lview.compare.compareManager);

commonspot.lview.page = {};
var pageState = '';

/*
 * Show the confirmation for activate/deactivate of page.
 */
commonspot.lview.page.setActivationState = function(state)
{	
	var title = '';
	pageState = state;
	
	if(state == 'Active')
	{ 
		confirm_text = 'Are you sure you wish to activate the page?<br /><br />' +
			  	          '<font style="font-weight:normal">This page will become visible to all users with Read permissions.</font>';
 		title = 'Confirm Activate';
	}
 	else
 	{ 
 		confirm_text = 'Are you sure you wish to deactivate the page?<br /><br />' +
				      '<font style="font-weight:normal">Inactive pages can only be viewed by contributors with Author, Edit, Design, Style or Admin permissions.</font>';				  
		title = 'Confirm Deactivate';					
 	} 
	
	var pageID = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().pageid;
	var lockParams = {subtitle: '', title: title, confirm_callback: 'setActivateDeactivate', confirm_text: confirm_text, checklockPageID: pageID};
	var confirmurl = '/commonspot/dashboard/dialogs/common/common-confirm.html?' + top.Object.toQueryString(lockParams);
	commonspot.lightbox.openDialog(confirmurl);	 
};

/*
 * Callback funtion: activate/deactivate page.
 */
commonspot.lview.page.setActivateDeactivate = function()
{ 
	var msg = (pageState == 'Active') ? 'Activating page. Please wait...' : 'Deactivating page. Please wait...';		
	//overlayLongDiv added in index.css	
	commonspotNonDashboard.util.displayMessageOverlay('lview', 'overlayDivStyle overlayLongDiv', msg);	 
	var commonspotLocalData = {};	
	commonspotLocalData.Page_SaveActivationState = new commonspot.spry.Dataset({ xpath: commonspot.data.STRUCT_XPATH });
	var LOADER_URL = commonspot.clientUI.state.location.getLoaderURL('subsiteurl');		
	var pageID = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().pageid;	
	var collectionOptions = {onCompleteCallback: onCompleteCallback_StatusCmds, onCollectionError: onCollectionError_StatusCmds, closeOnError: 1};
	var cmds = commonspot.ajax.commandEngine.commandCollectionFactory.getInstance(LOADER_URL, collectionOptions);
	var cmdOptions = {datasetRoot: commonspotLocalData, datasetName: 'Page_SaveActivationState' };
	
	cmds.add('Page', 'SaveActivationState', {pageID: pageID, State: pageState}, cmdOptions);  	
	cmds.send();
};

function onCompleteCallback_StatusCmds()
{
	if( this.hasAnyError )
		return;
	window.location.reload(true);
}

function onCollectionError_StatusCmds()
{
	commonspotNonDashboard.util.hideMessageOverlay('lview');
}

/**
 * Function to clear all the panels in Lview (lview_left)
 */
commonspot.lview.clearPanel = function()
{	
	var arrIframs = $('lview_left').getElementsByTagName('iframe');
	
	commonspot.lview.shouldClearAllPanels = 1;
	
	if ((arrIframs != null) && (arrIframs.length > 0))
	{
		for (var i = 0; i < arrIframs.length; i++)
		{					
			try
			{
				var iframeObject = $(arrIframs[i].id);
				
				//if ((iframeObject != null) && (iframeObject.contentWindow != null) && (iframeObject.contentWindow.document.baseURI != "about:blank"))
				if ( iframeObject && iframeObject.contentWindow && (iframeObject.contentWindow.document.baseURI != "about:blank"))
				{
					iframeObject.contentWindow.panelClear();
				}
			}
			catch (err)
			{
				alert("Error in clear panel. Error(s):" + err);
			}
		}
	} 
}

function createCookie(name,value,days)
{
	if (days) { 
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";
	}
};

function readCookie(cookiename)
{
   var cookie_start = document.cookie.indexOf(cookiename + "=");
  
   var cookie_value;
   if(cookie_start > 0)
   {
		cookie_value = document.cookie.charAt(cookie_start + cookiename.length +1);
        return cookie_value;
    }
   return '';	
};


/*
 * Function to open the lightbox dialog after refreshing the page.
 */
commonspot.lview.openDialogAfterPageLoad = function(pageHash, dialogUrl, refreshInterval, pageID, tryCnt, isAllDlgClosed)
{  	 
	if( isAllDlgClosed != true )
	{
		commonspot.lightbox.closeAllDialogs();	
		isAllDlgClosed = true;
	}
	window.location.hash = pageHash; 
		
	if( tryCnt <= 20 )
	{ 
		var currentPageID = commonspot.data.uiState.lview.dsCurrentPage.getCurrentRow().pageid;
		
		if(top.commonspot.csPage && (pageID == currentPageID || tryCnt == 20))
		{ 
			commonspot.lightbox.openDialog(dialogUrl);
			return;
		}  
		
		tryCnt = tryCnt + 1;
		setTimeout("commonspot.lview.openDialogAfterPageLoad('"+ pageHash +"','"+ dialogUrl +"',"+ refreshInterval +","+ pageID + "," + tryCnt + ",true)", refreshInterval);
	}	 
} 
