// This file contains Workbook related functionality 
var showPopup = null;
//var showPopupExtra = null;
var WB_messageContainer = null;
var WB_TipContainer = null;
var WB_TipDefaultText = null;
var WB_DefaultButtonClicked = true;

function WB_SetNonDefaultButtonClick()
{
	WB_DefaultButtonClicked = false;
}
//This is as BPP Input Box functionality to check if user has entered anything and pressed Move on
function WB_CheckEntryforInputBox(ctrID)
{
	var inputBox = document.getElementById(ctrID);
	if (typeof(WB_originalText) != 'undefined' && Trim(inputBox.value.toLowerCase()) == WB_originalText.toLowerCase())
		document.getElementById(ctrID).value="";	
}
//Function used to go to Next Page, i.e. hiddenpage value+1
function WB_NextPage()
{
	if (tipOpen == 1 || errorOpen == 1) //If Tip/Error Window is open do nothing and return;
		return false;
	
	// To check if the small pop-up window for Add/ChangeText is open to not
	if (showPopup && !showPopup.closed)
	{
		showPopup.focus();
		return;
	}

	var step = document.forms[0]._hdnPage.value;
	document.forms[0]._hdnPage.value = parseInt(step, 10) + 1;
}

//Function used to go to Next Page, i.e. hiddenpage value+1
function WB_NextPageSubmit()
{
	WB_NextPage();
	document.forms[0].submit();
}

function WB_PrevPage()
{
/*
	if (tipOpen == 1 || errorOpen == 1) //If Tip/Error Window is open do nothing and return;
		return;
	
	// To check if the small pop-up window for Add/ChangeText is open to not
	if (showPopup && !showPopup.closed)
	{
		showPopup.focus();
		return;
	}
*/

	var step = document.forms[0]._hdnPage.value;
	document.forms[0]._hdnPage.value = parseInt(step, 10) - 1;
}

function WB_SamePage()
{
	if (tipOpen == 1 || errorOpen == 1) //If Tip/Error Window is open do nothing and return;
		return;
	
	// To check if the small pop-up window for Add/ChangeText is open to not
	if (showPopup && !showPopup.closed)
	{
		showPopup.focus();
		return;
	}
}

//Function used to go to a given section
function WB_GoToSection(sectionID)
{
	if (tipOpen == 1 || errorOpen == 1) //If Tip/Error Window is open do nothing and return;
		return;
	document.forms[0]._hdnPage.value = -1;
	document.forms[0]._hdnSection.value = sectionID;
}

//Function used to go to a given section
function WB_GoToSectionSubmit(sectionID)
{
	if (tipOpen == 1 || errorOpen == 1) //If Tip/Error Window is open do nothing and return;
		return;
	document.forms[0]._hdnPage.value = -1;
	document.forms[0]._hdnSection.value = sectionID;
	document.forms[0].submit();
}

function WB_Submit()
{
	document.forms[0].submit();
}

function WB_GoToPage(pageID)
{
	if(tipOpen == 1 || errorOpen == 1) //If Tip/Error Window is open do nothing and return;
		return;
	document.forms[0]._hdnPage.value = parseInt(pageID, 10);
}

function WB_EmbedSound(url)
{
	if (url && url.length > 0)
	{		
		document.write("<embed src='" + url + "' autoplay='true'  autostart='true' height='0' width='0'></embed>");			
		var v = navigator.userAgent.toLowerCase();
		if(v.indexOf("msie") > -1)
		{
			document.write("<bgsound src='" + url + "' id='soundPlay'>");
		}
	}
}

//Function that will be used to download the User work to .Doc file
function WB_Save()
{
	document.forms[0]._hdnUserPressedSave.value = "yes";
	WB_NextPage();
}
function WB_NewTopic()
{
	document.forms[0]._hdnNewTopic.value = "newtopic";
	document.forms[0].submit();
}
function WB_Print()
{
	var frameName = 'iframePrintHeaderOption';
	var frameSrc = 'ShowHeaderPrintOptions.aspx?slp=0';
	if (!ShowPopupLoadingOnce(frameSrc, frameName))
	{
		window.frames[frameName].PageLoad();
	}
}
// This function will be used for publishing menu print, in case the end print format is different
function WB_EndPrint()
{
	var frameName = 'iframePrintHeaderOption';
	var frameSrc = 'ShowHeaderPrintOptions.aspx?slp=1';
	if (!ShowPopupLoadingOnce(frameSrc, frameName))
	{
		window.frames[frameName].PageLoad();
	}
}
function WB_OpenPrintWindow(url, name)
{
	if (!name) name = 'PrintPopup';
	if (!url) url = '';
	return Merit_Popup(url, 500, 400, name);
}
function WB_LoadPrint(printWin, url)
{
	if (!printWin)
		printWin = showPopup;
	if (printWin)
	{
		printWin.location.href = url;
	}
}
function WB_PositionScroll(divIdToPosition)
{
	var divToPosition = document.getElementById(divIdToPosition);
	divToPosition.scrollTop = divToPosition.scrollHeight;
}
function WB_Notepad_ScrollToView(objTable, rowIndex)
{
	var divToPosition = document.getElementById('div_' + objTable.id);
	var rowPosition = WB_Notepad_GetRowTopInTable(objTable, rowIndex);
	var rowHeight = objTable.rows[rowIndex].scrollHeight;
	var screenTop = divToPosition.scrollTop;
	var screenBottom = screenTop + parseInt(divToPosition.clientHeight, 10);
	var rowBottom = rowPosition + rowHeight;

	if (screenTop >= rowPosition)
	{
		divToPosition.scrollTop = rowPosition;
	}
	else
	{
		if (rowPosition <= screenBottom)
		{
			// scroll only by the height of the row if needed
			if (rowBottom > screenBottom)
				divToPosition.scrollTop += (rowBottom - screenBottom);
		}
		else
		{
			// below the screen area
			divToPosition.scrollTop += (rowBottom - screenBottom);
		}
	}
	//alert("ScreenTop - " + screenTop + '\r\nScreenBottom - ' + screenBottom + '\r\nRowPosition - ' + rowPosition + '\r\nRowHeight - ' + rowHeight);
}
function WB_Notepad_GetRowTopInTable(objTable, rowIndex)
{
	var top=0;
	for (var idx=0; idx<rowIndex; idx++)
	{
		top += objTable.rows[idx].scrollHeight;
	}
	return top;
}
function ShowPopupLoadingOnce(frameSrc, frameName)
{
	var frame = document.getElementById(frameName);
	var loaded = false;

	// First open the print window, empty, so that it does not have to be opened in the page-load of the print-heder-option page.
	// this is done to avoid it being blocked 
	showPopup = WB_OpenPrintWindow();
	
	if ((!frame.src) || (frame.src.indexOf(frameSrc) == -1))
	{
		frame.src = frameSrc;
		loaded = true;
	}
	frame.style.display = 'block';
	// Below has been added to handle the print showheaderoptions page 
	// there instead of setting the display to hide, we are setting the visibility, as the page crashes otherwise in safari
	frame.style.visibility = 'visible';
	return loaded;
}
function WB_SpellCheck()
{
	if (WB_SpellURL!='undefined')
	{
		PopupWindow(WB_SpellURL + '?id='+WB_SpellCheckControlID, 540, 440)
	}
}
function WB_WordProcessor()
{
	if(navigator.appName.toLowerCase()=='netscape')
	{
		alert(wordmessageForSafari);
		WB_OpenPrintWindow('ShowWorkbookInput.aspx', 'body');
		
	}
	else
	{
		var r=document.forms[0].txtWordProcAreaid.createTextRange();
		r.select();
		r.execCommand('copy');
		ERROR_Show('Error1',strMessageOFwordprocessor,strHeadingOFwordprocessor);
	}
}

//Function used to set the message in the span of Message control
function WB_SetMessageText(messageText, append)
{
	if (WB_messageContainer)
	{
		var container = document.getElementById(WB_messageContainer);
		if (null == append)
			append = true;
			
		if (append)
		{
			if(DTL_isAdditionalMessageAdded == 0)
			{
				container.innerHTML += messageText;
				DTL_isAdditionalMessageAdded = 1;
			}
		}
		else 
		{
			container.innerHTML = messageText;
		}
	}
}

//Want to set the items selected in ParaNotepad in DoubleNotepad so that they can appear in Request.
//So Calling another function in addition to Action
//Same function is also called for Single Notepad.
function setSelectedIndex(ctl)
{
	var Notepad = document.getElementById(ctl);
	var NotepadLen = Notepad.options.length;

//Here I want all items to be selected before submitting the page
//but I dont want the topic sentence to be selected so the check
//else part because, if by chance user selects an entry and then clicks ok then that
//entry was going selected, and if this was the case with topic sentence then
//topic sentence was getting added twice, so we deselect any entry before it goes to the next page.
	for (i=0;i<NotepadLen;i++)
	{	
		if(Notepad.options[i].id.toLowerCase()!="topic_sentence" )
			Notepad.options[i].selected = true;
		else if (Notepad.options[i].selected)
			Notepad.options[i].selected = false;
	}
}

//If there is a child-window open like ChangeText
//and if user is trying to take the focus to main window without any action on
//child window then set the focus back on child window.
function checkForChildWindow()
{
	if (showPopup && !showPopup.closed)
		showPopup.focus();
		
	//check for extra popup window in case of print
	//if (showPopupExtra && !showPopupExtra.closed)
		//showPopupExtra.focus();
}
function checkForChildWindow1()
{
	if (showPopup && !showPopup.closed )
		window.setTimeout("FocusOnPopUp()",700);
}
function FocusOnPopUp()
{
	showPopup.focus();
}

//function popupCenterForADD(popURL,popHeader,popWidth, popHeight,punchType, tableID)
function popupCenterForADD(popURL,popHeader,popWidth,popHeight,punchType,tableID)
{
	if (typeof(WindowSize) != "undefined")
		{
	popHeight = popHeight + (WindowSize-13)*5;
		}
	
	if((tipOpen && tipOpen == 1 )|| (topicOpen && topicOpen == 1) || (alertOpen && alertOpen==1) || (errorOpen && errorOpen==1)) 
		return;
	popLeft = 0;
	popTop = 0;
	if(screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
		popTop = (screen.height / 2) - (popHeight/2)
	}
	showPopup = window.open(popURL+'?windowHeader='+ popHeader + '&punchType='+ punchType + '&tableID='+ tableID,'Popup','width='+ popWidth +', height='+ popHeight +', left='+ popLeft +',top='+ popTop+',resizable=0,scrollbars=1,status=0')
	if (!showPopup)
	{
		alert(Merit_PopupBlockedMessage);
	}
}
function popupCenter(objCurrSelected, popHeader, tblID, popURL, popWidth, popHeight)
{
	if((tipOpen && tipOpen == 1 )|| (topicOpen && topicOpen == 1))
		return;
		
	//if no entry has been selected
	if (objCurrSelected == null)
	{
		ERROR_Show('Error1',strSelectEntry,strSelectEntryHeader);
		return;
	}
	
	//if topic sentence is selected
	if (objCurrSelected.id == "non-editable")
	{
		ERROR_Show('Error1',strChangeTopicSen,strErrHeader);
		return;
	}
	
	var textValue = objCurrSelected.getAttribute("textValue");
	
	if (null != textValue && textValue=="#SYSTEM_NEWLINE")
	{
		ERROR_Show('Error1',strChangeParagraphMarker,strChangeParagraphMarkerHeader);
		return;
	}

	//If an entry from Paragraph Notepad is selected and
	//ChangeText of Writing NP is clicked it should just return
	var objTable = document.getElementById(tblID);
	
	if (typeof(WindowSize) != "undefined")
	{
	popHeight = popHeight + (WindowSize-13)*5;
	}
	if(navigator.appName.toLowerCase()=='netscape')
	{
		if(objCurrSelected.parentNode.parentNode.id != objTable.id)
			return;
	}
	else
	{
		if(objCurrSelected.parentElement.parentElement.id != objTable.id)
			return;
	}

	popLeft = 0;
	popTop = 0;
	if(screen)
	{
		popLeft = (screen.width / 2) - (popWidth/2)
		popTop = (screen.height / 2) - (popHeight/2)
	}
	showPopup = window.open(popURL+'?selectedRowID='+ objCurrSelected.rowIndex +'&windowHeader='+ popHeader + '&tableID='+ tblID, 'Popup','width='+ popWidth +', height='+ popHeight +', left='+ popLeft +',top='+ popTop+', resizable=0,scrollbars=1,status=0');
}

function populateText(ctlTextBox)
{
	if (parseInt(selectedRowID, 10)>=0)
	{
		var parentTable = window.opener.document.getElementById(strTableID);
		
		var txtBx = document.getElementById(ctlTextBox);
		txtBx.focus();
		txtBx.value = parentTable.rows[selectedRowID].getAttribute("textValue");
	}
}

function updateText(ctlUpdateBox)
{
	var parentTable = window.opener.document.getElementById(strTableID);
	var textVal = document.getElementById(ctlUpdateBox);

	textVal.value = textVal.value.replace(/\r|\n|\r\n/g, "");

	if (window.opener && !window.opener.closed)
	{
		if (Trim(textVal.value) == '')
		{
			ERROR_Show('Error1',noInput,noInputHeader,ctlUpdateBox);
			return ;
		}
		
/*		
this may not be needed as they are logically doing nothing
check if they have been added as work-arounds in case of mozilla or safari - 
if not, remove them
		//Case BPP
		var strAttrib = parentTable.rows[selectedRowID].getAttribute("attribSetTo");
		if (null != strAttrib)
		{	
			parentTable.rows[selectedRowID].setAttribute("attribSetTo", strAttrib);
		}
		
		var strobjID = parentTable.rows[selectedRowID].getAttribute("objID");
		if (null != strobjID)
		{	
			parentTable.rows[selectedRowID].setAttribute("objID", strobjID);
		}

*/
		
		parentTable.rows[selectedRowID].setAttribute("textValue", textVal.value);
		
		//innerText is not supported in Mozilla, instead it supports textContent, so this solution
		var elem = parentTable.rows[selectedRowID].cells[3];
		if (typeof(elem.textContent) != "undefined")
			elem.textContent = textVal.value;
		else
			elem.innerText = textVal.value;
	}
	window.close();

	// This is to set the focus back to the OK button
	var okButton = window.opener.okButtonControlID;
	var okControl = window.opener.document.getElementById(okButton);
	if (okControl && okControl.focus && !okControl.disabled)
	{
		okControl.focus();
	}
}
function WB_DemoMessage(action,pid)
{
	var frameName = 'iframeNotAvailableMessage';
	var frameSrc = "NotAvailableMessage.aspx?sp="+ action + "&pid=" + pid;
	var frame = document.getElementById(frameName);
	if ((!frame.src) || (frame.src.indexOf(frameSrc) == -1))
	{
		frame.src = frameSrc;
		frame.style.display = 'block';
		frame.style.visibility = 'visible';
	}
	else
	{
		frame.style.display = 'block';
		frame.style.visibility = 'visible';
		frame.contentWindow.PageLoad();
	}
}

function WB_FitnessDemoMessage(action,pid)
{
	var frameName = 'iframeNotAvailableMessage';
	var frameSrc = "../Punch/NotAvailableMessage.aspx?sp="+ action + "&pid=" + pid;
	var frame = document.getElementById(frameName);
	if ((!frame.src) || (frame.src.indexOf(frameSrc) == -1))
	{
		frame.src = frameSrc;
		frame.style.display = 'block';
		frame.style.visibility = 'visible';
	}
	else
	{
		frame.style.display = 'block';
		frame.style.visibility = 'visible';
		frame.contentWindow.PageLoad();
	}
}

function SetDivStyle(divId,height,width)
{
	var mf=0, dmf=0; //dmf is multiplication factor for double notepads and mf is for single notepads
	div = document.getElementById(divId);
	var browser=navigator.appName;
	var b_version=navigator.appVersion;	
	if (browser=="Netscape")
	    {
		 div.style.minHeight=height; 
		 mf += 0.02;
		 dmf+= 0.01;
	    }
	 else if (browser=="Microsoft Internet Explorer")
	 {
		div.style.height=height;
	 }
	if (navigator.userAgent.indexOf('Safari')!=-1)
		div.style.overflow='auto';
	
	switch (screen.width)
	{
		case 800: 
			mf = 0.50;
			dmf = 0.22; 
			break;
		case 1024:
			mf += 0.60;
			dmf += 0.27;
			break;
		case 1152:
			mf += 0.65;
			dmf += 0.30;
			break;
		case 1280:
			mf += 0.68;
			dmf += 0.32
			break; 
		default:
			mf = 0.60;
			dmf = 0.27;
	}
	if (typeof(width)!='undefined')	
		div.style.width = screen.width * dmf;
	else
		{
		div.style.width = screen.width * mf;
		//if (width == 't' && screen.width >=1280)
			//div.style.width = screen.width * 0.70; //adjusted width for triple notepad at higher resolution
		}
	
	
}

function ShowSaveWorkAlert(source)
{
	if(typeof(tblWNotepadId) != "undefined" && typeof(generateHdnVarFname) != "undefined")
	{
		var abc = generateHdnVarFname + "('" + tblWNotepadId + "',true)";
		eval(generateHdnVarFname + "('" + tblWNotepadId + "',true)")
	}
		
	WB_SubmitLink(source);
}

var timeoutOpen;
var controlFocus;
function Timeout_Show(controlId, message, header, ctlID)
{
	if((tipOpen && tipOpen == 1 )|| (topicOpen && topicOpen == 1) || errorOpen == 1)
		return;
		
	timeoutOpen=1;
	var timeoutDiv = document.getElementById(controlId + "_msg");
	
	if (timeoutDiv)
	{
	 if (message)
		{
			var messageSpan = document.getElementById(controlId + "_hgcTimeoutMessage");
			var headerSpan = document.getElementById(controlId + "_hgcTimeoutHeader");
			messageSpan.innerHTML = message;
			headerSpan.innerHTML = header;
			ShowLayerOverPage(timeoutDiv);	
		}

		if(ctlID != null)
		{
			controlFocus=document.getElementById(ctlID);
		}
		var control= document.getElementById('btnClose');
 		if (control != null && control.focus && !control.disabled)
		{	
			setTimeout("document.getElementById('btnClose').focus()", 200);
		}
	}
	
}

function Timeout_Hide(controlId)
{
	var timeoutDiv = document.getElementById(controlId + "_msg");
	HideLayerOverPage(timeoutDiv);
	timeoutOpen = 0;
	if (controlFocus && controlFocus.focus && !controlFocus.disabled)
	{
		controlFocus.focus();
	}
}
function SetDivProgress(divId,count)
{
	var pix;
	var frmWrkbook = false;
	var div = document.getElementById(divId +'_'+count);
	var Mainbar1 = document.getElementById('fitnessMain1');
	var Mainbar2 = document.getElementById('fitnessMain2');
	if (Mainbar1 == null && Mainbar2 == null)
	{
		frmWrkbook = true;
	}
	var browser=navigator.appName;
	var b_version=navigator.appVersion;	
	
	if (browser=="Netscape")
	   {
		switch (screen.width)
			{
				case 800:
						if (frmWrkbook)
							pix = count/100 * 406;
						else
							pix = count/100 * 241;
						break;
				case 1024:
						if (frmWrkbook)
							pix = count/100 * 537;
						else
							pix = count/100 * 318;
						break;
				case 1152:
						if (frmWrkbook)
							pix = count/100 * 612;
						else
							pix = count/100 *365;
						break;
				case 1280:
						if (frmWrkbook)
							pix = count/100 * 682;
						else
							pix = count/100 * 407;
						break;
			}
		div.style.width = pix;
		if (pix==0)
			div.style.border = 0;
	   }
	else
		return;	

}

function FitnessTip_Show(controlId, message, header, ctlID)
{
	//if((tipOpen && tipOpen == 1 )|| (topicOpen && topicOpen == 1) || errorOpen == 1)
	//	return;
		
	//timeoutOpen=1;
	
	var fitnessDiv = document.getElementById(controlId + "_fitnessTip");
	
	if (fitnessDiv)
	{
	 if (message)
		{	
			var messageSpan = document.getElementById(controlId + "_hgcFitnessTipMessage");
			var headerSpan = document.getElementById(controlId + "_hgcFitnessTipHeader");
			messageSpan.innerHTML = message;
			headerSpan.innerHTML = header;
			ShowLayerOverPage(fitnessDiv);	
		}

		if(ctlID != null)
		{
			controlFocus=document.getElementById(ctlID);
		}
		var control= document.getElementById('btnClose');
 		if (control != null && control.focus && !control.disabled)
		{	
			setTimeout("document.getElementById('btnClose').focus()", 200);
		}
	}
	
}

function FitnessTip_Hide(controlId)
{
	var fitnessDiv = document.getElementById(controlId + "_fitnessTip");
	HideLayerOverPage(fitnessDiv);
	
	if (controlFocus && controlFocus.focus && !controlFocus.disabled)
	{
		controlFocus.focus();
	}
}
