var arrProfilePages = null;
var iWinDiffX = 0;
var iWinDiffY = 0;
var iWinDiffH = 0;
var moActiveWin=null;
var mlWaitID = null;
var mlWaitCount = 0;
var msLastSavedProfileXML = "";
var PAGE_TYPE_STOCKPAGE = 1;
var PAGE_TYPE_OTHER = 2;
var PAGE_TYPE_HOMETAB = 3;

function activateUserProfile(profileID)
{	
	try{
		clearInterval(mlWaitID);
		moActiveWin = null;
		mlWaitCount = 0;
	}catch(e){}
	
	var profileName = "";
	var sFilter = "";
	var oPages = null;
	var xmlAll = xmlUserProfiles.documentElement;
	if (profileID!=null) 
		sFilter = "//*/profile" + "[@id$eq$'" + profileID + "']";
	else
		sFilter = "//*/profile" + "[isdefault='True']";
	
	
	oPages = xmlAll.selectNodes(sFilter);
	if (oPages!=null && oPages.length > 0)
	{
		if (profileID==null)
		{
			profileID= parseInt(oPages[0].getAttribute("id"),10);
		}
		profileName = oPages[0].selectSingleNode("name").text;
	}
	
	setActiveProfileID(profileID, profileName);	
	updateUserProfileDisplay(true, profileID, getProfileName(profileID));
	
	//Close all open windows first!
	try	{
		m_MainMenuWindow.closeStockPages(window);	
	}catch(e){}	
			
	sFilter += "/pages/page";	
	oPages = xmlAll.selectNodes(sFilter);
	if( oPages != null && oPages.length > 0){		
			
		arrProfilePages = oPages;
		
		var s = 'activateUserProfileSub(' + profileID + ',' + 0 + ');';			
		window.setTimeout(s,300);
		return;
	}	
	else
	{
		refreshProfileStatus('', profileID, 0, 0, true);
	}
}
//arrProfilePages activateUserProfile profileID
function activateUserProfileSub(profileID, pageIndex)
{
	try{
		clearInterval(mlWaitID);
		moActiveWin = null;
		mlWaitCount = 0;
	}catch(e){}
	
	if (arrProfilePages==null || arrProfilePages.length <= pageIndex)	
		return;
	
	var profileName = getProfileName(profileID);
	refreshProfileStatus(profileName, profileID, pageIndex+1, arrProfilePages.length);
		
	var i = parseInt(pageIndex,10);	
	var oPages = arrProfilePages;
	var systemID = -1;
	var pageType = -1;
	var pageID = -1;
	var pageUrl = "";
	var activeOnly = false;
	var bAutoFocus = false;
	var iClosing = 0;
						
	var node = oPages[i].selectSingleNode("system");
	if( node != null){
		systemID = node.text;
	} 
						
	node = oPages[i].selectSingleNode("pagetype");
	if( node != null){
		pageType = node.text;
	} 
						
	node = oPages[i].selectSingleNode("pageid");
	if( node != null){
		pageID = node.text;
	} 
						
	node = oPages[i].selectSingleNode("url");
	if( node != null){
		pageUrl = unescape(node.text);
	} 
	
	node = oPages[i].selectSingleNode("activestocksonly");
	if( node != null){
		var sActiveOnly = unescape(node.text);
		if(sActiveOnly=="true")
		{
			activeOnly = true;
		}
	}
	
	node = oPages[i].selectSingleNode("autofocus");
	if( node != null){
		var sAutoFocus = unescape(node.text);
		if(sAutoFocus=="true")
		{
			bAutoFocus = true;
		}
	}
	
	node = oPages[i].selectSingleNode("closing");
	if( node != null){
		iClosing = unescape(node.text);
	}
						
	var pageX = 0;
	var pageY = 0;
	var pageWidth = 0;
	var pageHeight = 0;	
	var oWin;
	if(pageType == PAGE_TYPE_STOCKPAGE || pageType == PAGE_TYPE_OTHER)
	{
		pageX = parseInt(oPages[i].selectSingleNode("x").text,10);
		pageY = parseInt(oPages[i].selectSingleNode("y").text,10);
		pageWidth = parseInt(oPages[i].selectSingleNode("width").text,10);
		pageHeight = parseInt(oPages[i].selectSingleNode("height").text,10);
	}
	try
	{
		if( pageType == PAGE_TYPE_STOCKPAGE)
		{ 
			oWin = OpenStockPageFromUserProfile(systemID, pageID, pageX-iWinDiffX, pageY-iWinDiffY, pageWidth+(iWinDiffX*2), pageHeight+(iWinDiffY + iWinDiffH), activeOnly, bAutoFocus, iClosing);
			PositionWin(oWin);
		}
		else if( pageType == PAGE_TYPE_OTHER)
		{
			oWin = OpenNonStockPageFromProfile(pageUrl, pageX-iWinDiffX, pageY-iWinDiffY, pageWidth+(iWinDiffX*2), pageHeight+(iWinDiffY + iWinDiffH));
			PositionWin(oWin);
		}		
		else if(pageType == PAGE_TYPE_HOMETAB)
		{
			try
			{
				if(m_MainMenuWindow != null)
				{
					var iHomeTabID = parseInt(oPages[i].selectSingleNode("defaulttab").text,10);
					m_MainMenuWindow.m_iHomePageTabID = iHomeTabID;
					//Now show the tab if we are reconnecting in pull
					//Check to see if the homepage was visible
					var mainFramePage = window.parent.frames('fraMain').document;
					var sMainPageURL = new String(mainFramePage.URL);
					if (sMainPageURL.toUpperCase().indexOf('HOME.ASP') != -1)
					{
						//OpenHomePage!
						var cell = new Object();
						cell.IsChild = true;
						m_MainMenuWindow.OpenHomePage(cell);
					}
				}
			}
			catch(e){};
		}
	}
	catch(e)
	{
		refreshProfileStatus(profileName, profileID, pageIndex+1, arrProfilePages.length, false);
		return;
	}
	if(pageType == PAGE_TYPE_STOCKPAGE || pageType == PAGE_TYPE_OTHER)
	{				
		if( !checkPopupBlocked(oWin))
		{
			refreshProfileStatus(profileName, profileID, pageIndex+1, arrProfilePages.length, false);
			return;
		}
	}
	moActiveWin = null;
	pageIndex++;		
	
	//For IGS, ENI and Composite, we need to wait for the page to load before doing the next on
	if( parseInt(systemID) == parseInt(SYSTEM_IGS) || parseInt(systemID) == parseInt(SYSTEM_COMPOSITE) || parseInt(systemID) == parseInt(SYSTEM_ENI) || IsReutersPageSystem(systemID)){
		moActiveWin = oWin;
		waitForWin(profileID, pageIndex, arrProfilePages.length);
	}else{
		var s = 'activateUserProfileSub(' + profileID + ',' + pageIndex + ');';			
		refreshProfileStatus(profileName, profileID, pageIndex, arrProfilePages.length, true);
		window.setTimeout(s,500);
	}
	
}
function PositionWin(oWin)
{
	try
	{
		if (oWin!=null)
		{				 
			if (pageX!=-32000 && pageY!=-32000)
			{				 
				oWin.moveTo(pageX-iWinDiffX, pageY-iWinDiffY);
				if (iWinDiffX ==0 && iWinDiffY==0)
				{
					iWinDiffY = oWin.screenTop-pageY;
					if (iWinDiffY<0) iWinDiffY = 0;					
						iWinDiffX = oWin.screenLeft-pageX;
					if (iWinDiffX<0) iWinDiffX = 0;
						iWinDiffH = iWinDiffX;										
					if (isXPSP2!=null && isXPSP2())
						iWinDiffH+=23;
					oWin.moveTo(pageX-iWinDiffX, pageY-iWinDiffY);					
				}
			}
			oWin.resizeTo(pageWidth+(iWinDiffX*2),pageHeight+(iWinDiffY + iWinDiffH));
		}			
	}
	catch(e){}
}
function waitForWin( profileID, pageIndex, profileLength){
	clearInterval(mlWaitID);
	mlWaitCount++;
	var s = '';

	var bPageFailed = false;
	try{
		bPageFailed = (moActiveWin.mbPageLoaded ==null || !moActiveWin.mbPageLoaded);
	}catch(e){}

	var profileName = getProfileName(profileID);
	//Check if the window is open, dead, closed or we have timed out!
	if(  mlWaitCount >= 20
		|| moActiveWin==null 
		|| moActiveWin.closed 
		|| bPageFailed == false){
		s = 'activateUserProfileSub(' + profileID + ',' + pageIndex + ');';		
		refreshProfileStatus(profileName, profileID, pageIndex, profileLength, true);
	}
	else{
		s = 'waitForWin(' + profileID + ',' + pageIndex + ',' + profileLength + ');';		
	}
	
	mlWaitID = window.setInterval(s,500);
}
function SetNodeValue(oNode, sName, sValue)
{
	var oSubNode = oNode.selectSingleNode(sName);
	if (oSubNode==null)
	{
		oSubNode = oNode.ownerDocument.createElement(sName);
		oNode.appendChild(oSubNode);
	}
	oSubNode.text = sValue;
}
function GetNodeValue(oNode, sName)
{
	var oSubNode = oNode.selectSingleNode(sName);
	if (oSubNode!=null)
		return oSubNode.text;
	else
		return null;
}
function addHomePageDataToXml(poXmlPages)
{
	try
	{
		if(m_MainMenuWindow!=null && m_MainMenuWindow.m_iHomePageTabID!=null)
		{
			var oXmlPageElem = xmlUserProfiles.createElement('page');
			poXmlPages.appendChild(oXmlPageElem);
			SetNodeValue(oXmlPageElem,'pageid',-1);
			SetNodeValue(oXmlPageElem,'pagetype',PAGE_TYPE_HOMETAB);
			SetNodeValue(oXmlPageElem,'defaulttab',m_MainMenuWindow.m_iHomePageTabID);
		}
	}
	catch(e){};
}
function MustExcludePage(psUrl)
{
	if (psUrl.indexOf("UserSettings.aspx")>=0 ||
		psUrl.indexOf("commentary_edit.asp")>=0 ||
		psUrl.indexOf("IRSInstrumentPicker.asp")>=0)
	{
		return true; //ignore
	}
	return false;
}
function addPageDataToXml(poXmlPages, poWin, piPageType)
{
	var oPageWindow = poWin;
	if( piPageType == PAGE_TYPE_STOCKPAGE){
		oPageWindow = poWin.Window;
	}
	var bIsXPSP2 = isXPSP2();			
	if( oPageWindow.closed != true)
	{
		var sUrl = "";
		try
		{
			if( poWin.m_bInFrame == null || poWin.m_bInFrame == false)
			{
				sUrl = oPageWindow.location.href;	
				if (MustExcludePage(sUrl)) return; //ignore
				var system = poWin.System;
				if( system == null)
				{
					system = -1;
				}
							
				var pageID = poWin.PageID;
				if( pageID == null )
				{
					pageID = -1;
				}
				
				var sActiveOnly = "false";
				if(oPageWindow.mbActiveStocksOnly!=null && oPageWindow.mbActiveStocksOnly)
				{
					sActiveOnly = "true";
				}
				var sAutoFocus = "false";
				if(oPageWindow.m_bAutoFocus!=null && oPageWindow.m_bAutoFocus)
				{
					sAutoFocus = "true";
				}
				var iClosing = 0;
				if(oPageWindow.m_iClosing!=null)
				{
					iClosing = oPageWindow.m_iClosing;
				}

				var x = oPageWindow.screenLeft;
				var y = oPageWindow.screenTop;		
//				if(bIsXPSP2){
//					x-=4;
//					y-=30;
//				}else{
//					x-=4;
//					y-=24;
//				}

				var width = oPageWindow.document.body.offsetWidth;
				var height = oPageWindow.document.body.offsetHeight;
				if (bIsXPSP2 && x!=-32000)
				{
					if (x<0) x=0;
					if (y<0) y=0;
					if (y+height>window.screen.availHeight) y = window.screen.availHeight-height-30;
					//causes problems with multiple screens. if (x+width>window.screen.availWidth) x = window.screen.availWidth-width-5;
				}
			
				sUrl = sUrl.replace(/&fromProfile=1/gi,"");
				var sEscapedUrl = sUrl;			
				if( piPageType == PAGE_TYPE_STOCKPAGE){
					sEscapedUrl = "";
				}
				
				var oXmlPageElem = xmlUserProfiles.createElement('page');
				poXmlPages.appendChild(oXmlPageElem);
				SetNodeValue(oXmlPageElem,'system',system);
				SetNodeValue(oXmlPageElem,'pageid',pageID);
				SetNodeValue(oXmlPageElem,'pagetype',piPageType);
				SetNodeValue(oXmlPageElem,'x',x);
				SetNodeValue(oXmlPageElem,'y',y);
				SetNodeValue(oXmlPageElem,'width',width);
				SetNodeValue(oXmlPageElem,'height',height);
				SetNodeValue(oXmlPageElem,'url',sEscapedUrl);
				SetNodeValue(oXmlPageElem,'activestocksonly',sActiveOnly);
				SetNodeValue(oXmlPageElem,'autofocus',sAutoFocus);
				SetNodeValue(oXmlPageElem,'closing',iClosing);
			}
		}
		catch(e)
		{
			//ignore - if couldn't get page location href - external site
		}
	}
}
function OpenMainWindowFromProfile(psURL, piX, piY, piWidth, piHeight)
{
}
function OpenNonStockPageFromProfile(psUrl, piX, piY, piWidth, piHeight) 
{
	if(m_iCalx<0)
	{
		piWidth-=4;
		piHeight-=4;
	}
	else
	{
		piWidth-=m_iCalx;
		piHeight-=m_iCalx;
	}
//	if(bIsXPSP2){
//		//allow for thick border
//		piWidth-=4;
//		piHeight-=4;
//	}
	
	var dataURL = new String(psUrl);
	if(dataURL.indexOf("PullMode=")>0)
	{
		dataURL = dataURL.replace("PullMode=" + !m_MainMenuWindow.gbPull, "PullMode=" + m_MainMenuWindow.gbPull);
	}
	else
	{
		if(dataURL.indexOf("?")>0)
		{
			dataURL+="&PullMode=" + m_MainMenuWindow.gbPull;
		}
		else
		{
			dataURL+="?PullMode=" + m_MainMenuWindow.gbPull;	
		}
	}
	if( dataURL.indexOf("&fromProfile=") == -1)
	{
	 	dataURL+= "&fromProfile=1";
	}
	try
	{
		m_MainMenuWindow.top.RemoveUnusedCharts();
	}
	catch(e){}
	
	var params = "height="+piHeight+",width="+ piWidth + ",channelmode=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=1,scrollbars=0,status=0,toolbar=0";
	if (piX!=-32000 && piY!=-32000)
	{
		if (m_iCalx<0)
		{
			params += ",left=" + piX + ",top=" + piY;
		}
		else
		{
			params += ",left=" + (piX-m_iCalx) + ",top=" + (piY-m_iCaly);		
		}
	}
	var oWin = window.open(dataURL, "", params);
	if( oWin != null)
	{
		if (piX!=-32000 && piY!=-32000)
		{
			//ruiiiiiiii
			if(m_iCalx<0)
			{
				m_iCalx = (oWin.screenLeft-piX);
				m_iCaly = (oWin.screenTop-piY);	
				
				oWin.moveBy(-m_iCalx,-m_iCaly);
			}
		}
		oWin.opener = m_MainMenuWindow;
		m_MainMenuWindow.top.SetPageRef(oWin);
	}
	return oWin;
}
			 
function OpenStockPageFromUserProfile(piProductCode, piPageID, piX, piY, piWidth, piHeight, pbActiveStocksOnly, pbAutoFocus, piClosing){

	if(m_iCalx<0)
	{
		piWidth-=4;
		piHeight-=4;
	}
	else
	{
		piWidth-=m_iCalx;
		piHeight-=m_iCalx;
	}
//	if(bIsXPSP2){
//		//allow for thick border
//		piWidth-=4;
//		piHeight-=4;
//	}
	
	var params = "height="+piHeight+",width="+ piWidth +",center=No,help=No,resizable=Yes,status=No,titlebar=no,location=no,toolbar=no,menubar=no";
	if (piX!=-32000 && piY!=-32000)
	{
		if (m_iCalx<0)
		{
			params += ",left=" + piX + ",top=" + piY;
		}
		else
		{
			params += ",left=" + (piX-m_iCalx) + ",top=" + (piY-m_iCaly);		
		}
	}
		
	if (piProductCode==parseInt(SYSTEM_IGS) || piProductCode==parseInt(SYSTEM_COMPOSITE)
	 || piProductCode==parseInt(SYSTEM_ENI) || IsReutersPageSystem(piProductCode))
		params +=",scrollbars=no";	//no scrollbars for igs, eni and composite
	else 
		params +=",scrollbars=yes";
	var oWin = window.open("","",params, true);
	if( oWin != null)
	{
		if (piX!=-32000 && piY!=-32000)
		{
			//ruiiiiiiii
			if(m_iCalx<0)
			{
				m_iCalx = (oWin.screenLeft-piX);
				m_iCaly = (oWin.screenTop-piY);	
				
				oWin.moveBy(-m_iCalx,-m_iCaly);
			}
		}
		oWin.opener = m_MainMenuWindow;
		m_MainMenuWindow.OpenStockPageFromProfile(piPageID, piProductCode, oWin, pbActiveStocksOnly, pbAutoFocus, piClosing);
	}
	return oWin;
}
			
function checkPopupBlocked(poWin){
	if( poWin == null){
		//alert("Unable to re-open your profile. Please switch off any pop-up blockers.");
		return false;
	}
	return true;				
}

function getProfileName(profileID)
{
	var oXmlProfile;
	var oXmlNodeList;
	var oXml;
	oXml = xmlUserProfiles.cloneNode(true);
		
	if(profileID!=null && profileID != -1)
	{
		oXmlNodeList = xmlUserProfiles.selectNodes('//profile[@id="' + profileID + '"]');				
		if (oXmlNodeList!=null && oXmlNodeList.length > 0)
			return profileName = oXmlNodeList[0].selectSingleNode("name").text;
	}
	return false;
}

function getActiveProfileID()
{
	return m_MainMenuWindow.mi_ActiveProfile;
}

function setActiveProfileID(profileID, profileName)
{
	m_MainMenuWindow.mi_ActiveProfile = profileID;
	if (profileName!=null) m_MainMenuWindow.ms_ActiveProfileName = profileName;
}

function getProfilesEnabled() 
{
	if(m_MainMenuWindow)
		return m_MainMenuWindow.mb_ProfilesEnabled;
	else return false;
}
function setProfilesEnabled(value) 
{
	if(m_MainMenuWindow)
		m_MainMenuWindow.mb_ProfilesEnabled=value;
}
function getProfilesAutoSave() 
{
	if(m_MainMenuWindow)
		return m_MainMenuWindow.mb_ProfilesAutoSave;
	else return false;
}
function setProfilesAutoSave(value) 
{
	if(m_MainMenuWindow)
		m_MainMenuWindow.mb_ProfilesAutoSave=value;	
}

function getProfilesWarnWhenClosingMenus() 
{
	var topWindow = null;
	if(window.opener) topWindow = window.opener.top;
	else topWindow = window.top;
	
	if(topWindow)
		var ignoreWarnings = topWindow._ignoreUserWarnings;
	
	return(!ignoreWarnings);
}

function setProfilesWarnWhenClosingMenus(value) 
{
	var topWindow = null;
	if(window.opener) topWindow = window.opener.top;
	else topWindow = window.top;
	
	if(topWindow)
		topWindow._ignoreUserWarnings=!value;
}

function getProfilesProductToolbarDockPosition() 
{
	var topWindow = null;
	if(window.opener) topWindow = window.opener.top;
	else topWindow = window.top;
	
	if(topWindow)
		return topWindow.ToolbarFrame._productToolbarDockPosition;
	else return 'top';
}

function setProfilesProductToolbarDockPosition(value)
{
	var topWindow = null;
	if(window.opener) topWindow = window.opener.top;
	else topWindow = window.top;
	
	if(topWindow)
		topWindow.ToolbarFrame.displayToolbar(value);
}

function autoSaveProfile()
{
	saveCurrentUserProfile();
}

