﻿var STYLEMARKER = "¤";
var adBuilderMode = false;
var fullscreen_currentMode = "";
var mozilla = document.getElementById && !document.all;
//form Used by Find Users dialog
//selectiontype: string, either: 'activity' or 'global'. if activity, then the scope of the search for users in the current activity (session)
function openFindUsers(selectiontype, ctrlToClickOnComplete, clientId) 
{
	var url = "/GroupControls/SelectUsers.aspx?seltype=" + selectiontype + "&ctrlId=" + ctrlToClickOnComplete + "&clientId=" + clientId;
	var windowhandle = openWindow("SelectUsers", url,"No",800,340);
}

/* Admin */
function show(rowname,iframename,pageiterationCount) 
{
	var row = document.getElementById(rowname);
	if(row.style.display == "none")
		row.style.display = "";
	else
		row.style.display = "none";
	var iframe = document.getElementById(iframename);
	iframe.src = "/admin/logviewer/ShowHtml.aspx" + window.location.search + "&cnt=" + pageiterationCount;
}

function onFilterByDateSelected(filterdropdownid,fromrowid,torowid)
{
	var filterdropdown = document.getElementById(filterdropdownid);
	var fromrow = document.getElementById(fromrowid);
	var torow = document.getElementById(torowid);
	var RowHF = document.getElementById(fieldname);
	if(!fromrow || !torow || !fromrow) 
		return;  
		
	if(filterdropdown.value == 1) //All
	{
		fromrow.style.display = "none";
		torow.style.display = "none";
		RowHF.value=RowHF.value.replace(fromrowid.toString()+","+torowid.toString()+",","");
		RowHF.value=RowHF.value.replace(fromrowid.toString()+",","");
	}
	else if(filterdropdown.value == 2) //Before a date
	{
		fromrow.style.display = "";
		RowHF.value=RowHF.value.replace(fromrowid.toString()+","+torowid.toString()+",","");
		RowHF.value=RowHF.value.replace(fromrowid.toString()+",","");
		RowHF.value +=fromrowid.toString()+",";
		torow.style.display = "none";
	}
	else if(filterdropdown.value == 3) //after a date
	{
		fromrow.style.display = "";
		RowHF.value=RowHF.value.replace(fromrowid.toString()+","+torowid.toString()+",","");
		RowHF.value=RowHF.value.replace(fromrowid.toString()+",","");
		RowHF.value +=fromrowid.toString()+",";
		torow.style.display = "none";	
	}
	else if(filterdropdown.value == 5)
	{
		fromrow.style.display = "";
		RowHF.value=RowHF.value.replace(fromrowid.toString()+","+torowid.toString()+",","");
		RowHF.value=RowHF.value.replace(fromrowid.toString()+",","");
		RowHF.value +=fromrowid.toString()+",";
		torow.style.display = "none";	
	}
	else //between two dates
	{
		fromrow.style.display = "";
		torow.style.display = "";
		RowHF.value=RowHF.value.replace(fromrowid.toString()+","+torowid.toString()+",","");
		RowHF.value=RowHF.value.replace(fromrowid.toString()+",","");
		RowHF.value +=fromrowid.toString()+","+torowid.toString()+",";
	}	
}

function showRowNames()
{
	var rowHiddenfield = document.getElementById(fieldname);
	
	if (rowHiddenfield == null)
		return;	
	var rowsplit = rowHiddenfield.value.split(",");	
		
	if (rowsplit!=null)
	{
		for(var i=0;i<rowsplit.length;i++)
		{
			if (rowsplit[i]!="")
			{
				var row = document.getElementById(rowsplit[i]);
				row.style.display = "";
			}
		}
	}
}

/* Admin */

function onColorSelectionChange(dropdownId, tdid) 
{  
	var ddObj = document.getElementById(dropdownId);
	if(!ddObj) return;
	var index = ddObj.selectedIndex;
	if(index == 0) return;
	var value = ddObj.options[index].value;
	var tdobj = document.getElementById(tdid);
	tdobj.style.backgroundColor = "#" + value; 
}
//******************** folder area ******************//
function showRolesForSection(sectionToShow)
{
	var roleSection=document.getElementById(sectionToShow);	
		if(roleSection.style.display=="none"){
			roleSection.style.display="";			
		}
		else
			roleSection.style.display="none";
			show=1;	
}

function HideSection(sectionToShow)
{
	var roleSection=document.getElementById(sectionToShow);	
	roleSection.style.display=="none";
}

//******************************************************************************************//
//*****************************************************************************************************************************
//	Correction Scripts
//*****************************************************************************************************************************
var hilightDivSectionIndex = null;
var previewImgObj = null;
var isLatestVersion = false;

function showGeneratePanel() 
{
	toggleGenericWithCookie("generatePDFPanel","generatePDFPanel");
}
 
function ShowControl1HideControl2(control1,control2)
{
	showConfigurewf(control1);
	hideConfigureRow(control2); 
}

function hideConfigureRow(controlName) 
{
	var row = document.getElementById(controlName.toString());
	//keep the names of the rows that have been hidden
	var rowHiddenfield = document.getElementById(fieldname);
	if( row.style.display == "") 
	{
		row.style.display = "none";
		rowHiddenfield.value +=controlName.toString()+",";
	}
	else
	{
		row.style.display = "";
		rowHiddenfield.value=rowHiddenfield.value.replace(controlName.toString()+",","");
		rowHiddenfield.value=rowHiddenfield.value.replace(controlName.toString(),"");
	}
}

function showConfigurewf(controlName) 
{
	var row = document.getElementById(controlName.toString());
	//keep the names of the rows that have been opened
	var rowHiddenfield = document.getElementById(nameoffield);
	if( row.style.display == "none") 
	{
		row.style.display = "";
		rowHiddenfield.value +=controlName.toString()+",";
	}
	else
	{
		row.style.display = "none";
		rowHiddenfield.value=rowHiddenfield.value.replace(controlName.toString()+",","");
		rowHiddenfield.value=rowHiddenfield.value.replace(controlName.toString(),"");
	}
}

//*************************************************************************
//	Search panel user control
//	Note: Use the following functions: visibleRowNames() & hiddenRowNames()

function showhidePanel(control1,control2)
{
	showPanel(control1);
	hidePanel(control2); 
}

function hidePanel(controlName) 
{
	var row = document.getElementById(controlName.toString());
	//keep the names of the rows that have been hidden
	if( row.style.display == "") 
	{
		row.style.display = "none";
	}
	else
	{
		row.style.display = "";
	}
}

function showPanel(controlName) 
{
	var row = document.getElementById(controlName.toString());
	//keep the names of the rows that have been opened
	if( row.style.display == "none") 
	{
		row.style.display = "";
	}
	else
	{
		row.style.display = "none";
	}
}

function showSelectedColor(dropdownId, colorBoxId)
{
	var dropdown = document.getElementById(dropdownId);
	var colorBox = document.getElementById(colorBoxId);
	
	if(dropdown != null && colorBox != null)
	{
		if(dropdown.value != "-1")
		{ 
			colorBox.src = "/images/col.aspx?c=" + dropdown.value + "&w=10&h=10";
		}
		else
		{
			colorBox.src = "/images/col.aspx?c=FFFFFF&w=10&h=10";
		}
		SetImageTitle(colorBox, dropdown.value);
	}
} 

var LANG_NoWorkflow = "";
var LANG_WorkflowCompleted = "";
var LANG_WorkflowNotConfigured = "";
var LANG_WorkflowNotStarted = "";
var LANG_WorkflowTasksLate = "";
var LANG_ActivityLate = "";
var LANG_Plannedenddateapproaching = "";
var LANG_WorkflowTaskWaitingToBegin = "";
var LANG_ActivityOnSchedule = "";
var LANG_AllWorkflowStatus = "";

function SetImageTitle(colorBox, val)
{
	switch(val)
	{
		case "8B8989": colorBox.title = LANG_NoWorkflow; 
				break;
		case "BBCEE2": colorBox.title = LANG_WorkflowCompleted;
				break;		
		case "CDC9C9": colorBox.title = LANG_WorkflowNotConfigured;
				break;		
		case "EEE9E9": colorBox.title = LANG_WorkflowNotStarted;
				break;		
		case "FF6600": colorBox.title = LANG_WorkflowTasksLate;
				break;
		case "FF0000": colorBox.title = LANG_ActivityLate;
				break;		
		case "FFFF7E": colorBox.title = LANG_Plannedenddateapproaching;
				break;		
		case "CAFF70": colorBox.title = LANG_WorkflowTaskWaitingToBegin;
				break;		
		case "45C428": colorBox.title = LANG_ActivityOnSchedule;	
				break;		
		default : colorBox.title = LANG_AllWorkflowStatus;
				break;		
	}
}
//*************************************************************************	
	
function visibleRowNames()
{
	var rowHiddenfield = document.getElementById(nameoffield);
	if (rowHiddenfield == null)
		return;	
	var rowsplit=rowHiddenfield.value.split(",");	
	if (rowsplit!=null)
	{
		for(var i=0;i<rowsplit.length;i++)
		{
			if (rowsplit[i]!="")
			{
				var row = document.getElementById(rowsplit[i]);
				row.style.display = "";
			}
		}
	}
}

function hiddenRowNames()
{
	var hiddenfield = document.getElementById(fieldname);
	if (hiddenfield == null)
		return;	
	var splitrow=hiddenfield.value.split(",");
	if(splitrow!=null)
	{
		for(var j=0;j<splitrow.length;j++)
		{
			if (splitrow[j]!="")
			{
				var nRow=document.getElementById(splitrow[j]);
				nRow.style.display="none";
			}
		}
	}
}

function showPending() 
{
	var pendingSummary = document.getElementById("pendingSummary");
	if( pendingSummary.style.display == "none") 
		pendingSummary.style.display = "block";
	else
		pendingSummary.style.display = "none";
}

function toggle(objId) 
{
	var ObjectToToggle = document.getElementById(objId);
	if (ObjectToToggle == null)
		return;
	
	if( ObjectToToggle.style.display == "none") 
		ObjectToToggle.style.display = "block";
	else
		ObjectToToggle.style.display = "none";	
}

function toggleWithHiddenField(objId, hiddenFieldId) 
{
	var ObjectToToggle = document.getElementById(objId);
	var hiddenFieldObj = document.getElementById(hiddenFieldId);
	
	if (ObjectToToggle == null)
		return;
	
	if( ObjectToToggle.style.display == "none") 
	{
		ObjectToToggle.style.display = "block";
		
		if (hiddenFieldObj != null)
			hiddenFieldObj.value = "1";
	}
	else
	{
		ObjectToToggle.style.display = "none";	

		if (hiddenFieldObj != null)
			hiddenFieldObj.value = "0";
	}
}

function toggleOnChecked(checkBoxName,objToToggle)
{
	var checkboxObj = document.getElementById(checkBoxName);
	var objectToToggle = document.getElementById(objToToggle);
	
	if (objToToggle == null || checkboxObj == null) return;
	
	if ( checkboxObj.checked == true )
		objectToToggle.style.display = "block";
	else
		objectToToggle.style.display = "none";
}

function replaceNewLineControlChars(contents)
{
	var replacedValue = contents.replace("<newline>","\n");
	while( replacedValue.indexOf("<newline")> -1) 
	{
		replacedValue = replacedValue.replace("<newline>","\n");
	}
	return replacedValue;
}

function openTextbox(textboxtable, textboxName, textboxValue, spreadId, sectionId, commentId)
{	//check whether for the same textarea, a textbox is already open
	//if textbox is open,other links in same textarea will open the same textbox in that textarea
	//stores the textboxtable, textboxName, textboxValue, spreadId, sectionId, commentId in hiddenfield textboxNamesHF
	
	var textboxHiddenField = document.getElementById(textboxFieldname);
	var originalHiddenField = document.getElementById(textFieldname);
	var hiddenComment=document.getElementById(textboxValueFieldname);
	var hiddenFieldObj =document.getElementById(textboxValue);//gets the hidden field object

	if (textboxHiddenField.value.indexOf('|'+spreadId.toString()+'|'+sectionId.toString())>-1) 
	{	
		var textboxsplit=textboxHiddenField.value.split(",");
		for(var i=0;i<textboxsplit.length;i++)
        {
			if (textboxsplit[i].indexOf('|'+spreadId+'|'+sectionId)>-1)
			{	
				var texttable = document.getElementById(textboxsplit[i].split('|')[0]);
                texttable.style.display = "none";
                //remove the texttable name from the hidden field	
                textboxHiddenField.value=textboxHiddenField.value.replace(textboxsplit[i]+",",""); 
                if (texttable.id.toString()==textboxtable.toString())
					return;
                break;
			}
        }
	}
	var textboxTableObj = document.getElementById(textboxtable);
	var textbox= document.getElementById(textboxName.toString());
	textbox.value="";	
	textbox.value = replaceNewLineControlChars(hiddenFieldObj.value);
	
	if(textboxTableObj.style.display=="none")
	{	//check if original text is opened, the original textbox is closed before opening a comments textbox
		if (originalHiddenField.value.indexOf('|'+spreadId.toString()+'|'+sectionId.toString())>-1) 
		{	
			var originalSplit=originalHiddenField.value.split(",");	
			for(var j=0;j<originalSplit.length;j++)
			{
				if (originalSplit[j].indexOf('|'+spreadId+'|'+sectionId)>-1)
				{				
					var originalTable = document.getElementById(originalSplit[j].split('|')[0]);
					if(originalTable.style.display=="")
					{
						originalTable.style.display="none";
						//remove the texttable name from the hidden field	
						originalHiddenField.value=originalHiddenField.value.replace(originalSplit[j]+",",""); 						
						textboxTableObj.style.display = "";
						textboxHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +'|'+textboxName+",";
						hiddenComment.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentId +"<,>";
				
					}
					else
					{
						textboxTableObj.style.display = "";
//						textboxHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +",";
						textboxHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +'|'+textboxName+",";
						hiddenComment.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentId +"<,>";
				
					}
				}
			}
		}
		else
		{	
			textboxTableObj.style.display = "";
			textboxHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +'|'+textboxName+",";
			hiddenComment.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentId +"<,>";	
		}
	}
	GetStylesControlCodeCount(textboxName);	
}

function originalOpenTextbox(textboxtable, textboxName, textboxValue, spreadId, sectionId, commentId, sectionIndex)
{	
	var originalHiddenField = document.getElementById(textFieldname);
	var textboxHiddenField = document.getElementById(textboxFieldname);
	var hiddenComment=document.getElementById(textValueFieldname);
	var hiddenFieldObj =document.getElementById(textboxValue);//gets the hidden field object

	if (originalHiddenField.value.indexOf('|'+spreadId.toString()+'|'+sectionId.toString())>-1) 
	{			
		var textboxsplit=originalHiddenField.value.split(",");
		for(var i=0;i<textboxsplit.length;i++)
        {
			if (textboxsplit[i].indexOf('|'+spreadId+'|'+sectionId)>-1)
			{				
				var texttable = document.getElementById(textboxsplit[i].split('|')[0]);
                //close original table
                texttable.style.display = "none";
                //remove the texttable name from the hidden field	
                originalHiddenField.value=originalHiddenField.value.replace(textboxsplit[i]+",",""); 
                if (texttable.id.toString()==textboxtable.toString())
					return;
                break;
			}
        }
	}
			
	var textboxTableObj = document.getElementById(textboxtable);
	var textbox= document.getElementById(textboxName.toString());

	textbox.value="";
	textbox.value = replaceNewLineControlChars(hiddenFieldObj.value);	
	if(textboxTableObj.style.display=="none")
	{
		if (textboxHiddenField.value.indexOf('|'+spreadId.toString()+'|'+sectionId.toString())>-1) 
		{	//check if comment text is opened, the comment textbox is closed before opening original textbox
			var utextboxsplit=textboxHiddenField.value.split(",");	
			for(var j=0;j<utextboxsplit.length;j++)
			{
				if (utextboxsplit[j].indexOf('|'+spreadId+'|'+sectionId)>-1)
				{				
					var utexttable = document.getElementById(utextboxsplit[j].split('|')[0]);
					if(utexttable.style.display=="")
					{
						utexttable.style.display="none";
						//remove the texttable name from the hidden field	
						textboxHiddenField.value=textboxHiddenField.value.replace(utextboxsplit[j]+",",""); 
						textboxTableObj.style.display="";
						originalHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +'|'+sectionIndex +'|'+textboxName +",";
						hiddenComment.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentId+'<|>'+sectionIndex +"<,>";
				
					}
					else
					{
						textboxTableObj.style.display = "";
						originalHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +'|'+sectionIndex +'|'+textboxName +",";
						hiddenComment.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentId+'<|>'+sectionIndex +"<,>";
				
								
					}
				}
			}
		}
		else
		{
			textboxTableObj.style.display = "";
			originalHiddenField.value +=textboxtable.toString()+'|'+spreadId+'|'+sectionId +'|'+commentId +'|'+sectionIndex +'|'+textboxName +",";
			hiddenComment.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentId+'<|>'+sectionIndex +"<,>";
		
			
		}
		
	}
	GetStylesControlCodeCount(textboxName);	
}

function originalTextChange(saveAllbutton,textboxName,commentID,sectionIndex)
{	
	//store the opened textboxName, comments and commentID in hiddenfield
	var button=document.getElementById(saveAllbutton.toString());
	var textbox=document.getElementById(textboxName.toString());
	
	var hiddenFieldTB=document.getElementById(textValueFieldname);
	button.disabled=false;
	hiddenFieldTB.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentID+'<|>'+sectionIndex +"<,>";
			
}

function textChange(saveAllbutton,textboxName,commentID)
{	
	//store the opened textboxName, comments and commentID in hiddenfield
	var button=document.getElementById(saveAllbutton.toString());
	var textbox=document.getElementById(textboxName.toString());
	
	var hiddenFieldTB=document.getElementById(textboxValueFieldname);
	button.disabled=false;
	hiddenFieldTB.value+=textboxName.toString()+'<|>'+textbox.value+'<|>'+commentID +"<,>";
}

function visibleTextboxNames()
{
	//used to set the textarea textbox+comments 
      var textboxHiddenField = document.getElementById(textboxFieldname);
      var buttonSaveAll = document.getElementById(saveAllbutton);
	  if (textboxHiddenField==null)		
			return;
		var textboxsplit=textboxHiddenField.value.split(",");
      
      var uTextboxHiddenField=document.getElementById(textboxValueFieldname);
      if(uTextboxHiddenField==null)
			return;
      var uTextboxSplit=uTextboxHiddenField.value.split("<,>");   
         
      //show comment
      for(var j=0;j<uTextboxSplit.length;j++)
      {
		var textbox = document.getElementById(uTextboxSplit[j].split('<|>')[0]);
		//alert(textbox);
		if (textbox!=null)
		{
			textbox.value = uTextboxSplit[j].split('<|>')[1];
			buttonSaveAll.disabled=false;
		}
      }
	  //show table
	  if (textboxsplit!=null)
	  {
			for(var i=0;i<textboxsplit.length;i++)
			{
				  if (textboxsplit[i]!="")
				  {
						var tableID = document.getElementById(textboxsplit[i].split('|')[0]); 
						tableID.style.display="";
				  }
			}
	   }		
}

function originalvisibleTextboxNames()
{
	//used to set the textarea textbox+comments 
      var textboxHiddenField = document.getElementById(textFieldname);
      var buttonSaveAll = document.getElementById(saveAllbutton);
	  if (textboxHiddenField==null)		
			return;
		var textboxsplit=textboxHiddenField.value.split(",");
      
      var uTextboxHiddenField=document.getElementById(textValueFieldname);
      if(uTextboxHiddenField==null)
			return;
      var uTextboxSplit=uTextboxHiddenField.value.split("<,>");   
         
      //show comment
      for(var j=0;j<uTextboxSplit.length;j++)
      {
		var textbox = document.getElementById(uTextboxSplit[j].split('<|>')[0]);
		//alert("original:" + textbox);
		if (textbox!=null)
		{
			textbox.value = uTextboxSplit[j].split('<|>')[1];
			buttonSaveAll.disabled=false;
		}
      }
      //show table
      if (textboxsplit!=null)
      {
            for(var i=0;i<textboxsplit.length;i++)
            {
                  if (textboxsplit[i]!="")
                  {
                        var tableID = document.getElementById(textboxsplit[i].split('|')[0]); 
						tableID.style.display="";
                  }
            }
	   }
}

var lastHilightDivObj = null;
//reference to the div object that is currently active
var activeDivObj = null;

//reference to div with overflow
var overflowDivObj = null;
var overflowActiveDivObj = null;

//handles the highlight of the preview spread

function prevMouseOver(divObj) 
{       
	if( divObj == lastHilightDivObj) 	
		return;
	if(divObj != null && lastHilightDivObj != null)
	    if(divObj.id == lastHilightDivObj.id)	
	        return;
    divObj.className +=" sthighlight";    
	lastHilightDivObj = divObj;	
}

//removes hilight from the preview spread
function prevMouseOut(divObj) 
{   
	if( lastHilightDivObj == null ) 
		return;	
	var cl = divObj.className;
	var i = cl.indexOf(" sthighlight");
	if(i<0) return;
	var res = cl.substring(0,i);
	if(res.length > i)
		res = cl.substring(i+ " sthighlight".length);
	divObj.className = res;
	lastHilightDivObj = null;
}
//removes hilight from the preview spread
var previousActiveHighlightDiv = null;

function setActiveHighlightDiv() 
{
	if(activeDivObj != null) 
	{
	    UnHighlightDiv();
		if(activeDivObj.style.display == "none")
			activeDivObj.style.display = "inline";

		//if(previousActiveHighlightDiv == activeDivObj) return;
	
	    activeDivObj.className +=" stactive";
		if(adBuilderMode == true)
		{
			activeDivObj.style.display = "inline";
			if(previousActiveHighlightDiv != null && previousActiveHighlightDiv.id != activeDivObj.id)
				previousActiveHighlightDiv.style.display = "none";
		}
		previousActiveHighlightDiv = activeDivObj;		
	}
}

function UnHighlightDiv()
{
	if(activeDivObj == null) return;
	if(previousActiveHighlightDiv != null && (previousActiveHighlightDiv != activeDivObj)) return;
	var cl = activeDivObj.className;
	var i = cl.indexOf(" stactive");
	if(i<0) return; // 'active highlight'
	var res = cl.substring(0,i);
	if(res.length > i)
		res = cl.substring(i+ " stactive".length);
	//alert(res);
	activeDivObj.className = res;
}

function correctionInitDivAreasWaitForLoad(previewImgId, hilightDivSectionIndex_Param, _isLatestVersion, showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId)
{
	isLatestVersion = _isLatestVersion;
	hilightDivSectionIndex = hilightDivSectionIndex_Param;
	previewImgObj = document.getElementById(previewImgId);
	waitForImageToLoad(showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId);		
	if(previewImgObj != null)
		previewImgObj.onload = function() { waitForImageToLoad(showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId); }
	if( !isLatestVersion ) 
	{
		//disable generate button if found..
		var genButton = document.getElementById("GeneratePDFButton");
		if(genButton != null) 
		{
			genButton.disabled = true;
		}
	}
}

function ClearShowHideSectionCheckboxes(showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId) 
{
	if (showHideSectionsCheckBoxId != null) 
	{
		var showHideSectionsCheckbox = document.getElementById(showHideSectionsCheckBoxId);
		if(showHideSectionsCheckbox != null) showHideSectionsCheckbox.checked = false;
	}
	
	if (showDifMapCheckBoxId != null) 
	{
		var showDifMapCheckbox = document.getElementById(showDifMapCheckBoxId);
		if(showDifMapCheckbox != null) showDifMapCheckbox.checked = false;
	}
	
	if (showHideAnnotationsCheckBoxId != null) 
	{
		var showHideAnnotationsCheckbox = document.getElementById(showHideAnnotationsCheckBoxId);
		if(showHideAnnotationsCheckbox != null) showHideAnnotationsCheckbox.checked = false;	
	}
	
	
	if (showHideModifiedCheckBoxId != null) 
	{
		var showHideModifiedCheckbox = document.getElementById(showHideModifiedCheckBoxId);
		if(showHideModifiedCheckbox != null) showHideModifiedCheckbox.checked = false;	
	}
}

function waitForImageToLoad(showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId) 
{
	if (previewImgObj != null)
	{
		if(previewImgObj.width < 10)
			setTimeout("waitForImageToLoad(" + showHideSectionsCheckBoxId + "," + showDifMapCheckBoxId + "," + showHideAnnotationsCheckBoxId + "," + showHideModifiedCheckBoxId + ")",10);
		else
		{
			correctionInitDivAreas();
			ShowHideSpreadItems(showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId);
		}
	}
}

function ShowHideSpreadItems(showHideSectionsCheckBoxId, showDifMapCheckBoxId, showHideAnnotationsCheckBoxId, showHideModifiedCheckBoxId)
{
    var showHideSectionsCheckBox = document.getElementById(showHideSectionsCheckBoxId);
    var showDifMapCheckBox = document.getElementById(showDifMapCheckBoxId);
    var showHideAnnotationsCheckBox = document.getElementById(showHideAnnotationsCheckBoxId);
    var showHideModifiedCheckBox = document.getElementById(showHideModifiedCheckBoxId);
    
    if(showHideSectionsCheckBox == null ||showHideAnnotationsCheckBox == null || showDifMapCheckBox == null || showHideModifiedCheckBox == null)
        return;
        
    ShowHideCorrectionDiv("secHilight_", !showHideSectionsCheckBox.checked);
    ShowHideCorrectionDiv("editIcon_", !showHideSectionsCheckBox.checked);
    ShowHideCorrectionDiv("regionDivs_", showDifMapCheckBox.checked);
    ShowHideCorrectionDiv("annotation_", !showHideAnnotationsCheckBox.checked);
    ShowHideCorrectionDiv("modified_", showHideModifiedCheckBox.checked);
}

var divModified = null;
function correctionInitDivAreas(addy) {
	//find all Correction DIV tags and reposition according to preview image.
	//previewImgObj = document.getElementById(previewImgId);
	var offsetX = GetAbsoluteLeft(previewImgObj);
	var offsetY = GetAbsoluteTop(previewImgObj);
	try { 
		if(typeof(addy) == "number") offsetY -= addy;
	} catch(e) {}
	var divName = "secHilight_";
	var editIconName = "editIcon_";
	var working = true;
	var cnt = 0;
	var factorX = ((previewImgObj.width/pagesInSpread) / pagewidth);
	var factorY = (previewImgObj.height / pageheight);
	
	PositionAndScaleObjects(divRegions, "secHilight_", adBuilderMode ? "none" : "inline", offsetX, offsetY, factorX, factorY, editIconName);

	//also correct the divs for the modified text areas
	if(divModified != null)
	{
		PositionAndScaleObjects(divModified, "modified_", "none", offsetX, offsetY, factorX, factorY, null);
	}

	//now hilight the active Section
	activeDivObj = null;
	if( hilightDivSectionIndex > -1 ) {
		divobj = document.getElementById("secHilight_" + hilightDivSectionIndex);
		if(divobj != null) 
		{
			activeDivObj = divobj;
			activeDivObj.style.cursor = "pointer";
			setActiveHighlightDiv();
		}
	}
	
	//also correct the divs for the difference map
	if( diffRegions.length > 0 ) {
		factorX = previewImgObj.width / diff_pagewidth;
		factorY = previewImgObj.height / diff_pageheight;
		var working = true;
		var cnt = 0;
		while(working) {
			var divobj = document.getElementById("regionDivs_" + cnt);
			if( divobj != null && diffRegions[cnt]!= null )
			{
				divobj.style.left = ((diffRegions[cnt].x1 * factorX) + offsetX) + "px";
				divobj.style.top = ((diffRegions[cnt].y1 * factorY) + offsetY) + "px";
				divobj.style.width  = (diffRegions[cnt].x2 - diffRegions[cnt].x1)*factorX + "px";
				divobj.style.height = (diffRegions[cnt].y2 - diffRegions[cnt].y1)*factorY + "px";
			} else {
				working = false;
			}
			cnt++;
		}
	}
	//setup the annotation images if present
	working = true;
	cnt = 0;
	var imgoffsetx = offsetX;
	var imgoffsety = offsetY;
	
	for(var annotcnt=0;annotcnt<annotIds.length;annotcnt++)
	{
		var annotation = annotIds[annotcnt];
		var imgobj = document.getElementById(annotation.ImageId);
		if( imgobj != null )
		{
			imgobj.style.zIndex = 100;
			
			var hideAnnoCheckbox= document.getElementById("ctl00_mainContent_showHideSpreadSections_fullScreen_showHideAnnotations");
			ShowHideItem(hideAnnoCheckbox, imgobj);

			//found the image, now reposition
			var scaleX = previewImgObj.width / annotationsPositions[annotcnt].sourcesizex;
			var scaleY = previewImgObj.height / annotationsPositions[annotcnt].sourcesizey;

			imgobj.style.left = ((annotationsPositions[annotcnt].x1 * scaleX) + imgoffsetx) + "px";
			imgobj.style.top = ((annotationsPositions[annotcnt].y1 * scaleY) + imgoffsety) + "px";
			//find annotation div
			var annotationDiv = document.getElementById(annotation.DivId);
			annotationDiv.style.position = "absolute";
			annotationDiv.style.left = ((annotationsPositions[annotcnt].x1*scaleX) + imgoffsetx) * factorX + "px";
			annotationDiv.style.top = ((annotationsPositions[annotcnt].y1*scaleY) + imgoffsety) * factorY + "px";
			//createAnnot(null,((annotationsPositions[annotcnt].x1) + imgoffsetx), ((annotationsPositions[annotcnt].y1) + imgoffsety));
		} 
	}
}

function PositionAndScaleObjects(objs, divName, visibility, offsetX, offsetY, factorX, factorY, editIconName)
{
	if(objs.length == 0) return;
	var working = true;
	var cnt = 0;
	while(working) {
		var divobj = document.getElementById(divName + cnt);
		if( divobj != null )
		{
			//found the div, now reposition
			var newx = Math.floor(objs[cnt].x1 * factorX);
			var newy = Math.ceil(objs[cnt].y1 * factorY);
			divobj.style.left = (newx + offsetX) + "px";
			divobj.style.top = (newy + offsetY) + "px";
			var newwidth = Math.ceil((objs[cnt].x2 - objs[cnt].x1)*factorX);
			divobj.style.width  = newwidth + "px";
			//clip right edge
			if((newx + newwidth) > previewImgObj.width)
			{
				var dif = (newx + newwidth) - previewImgObj.width ;
				divobj.style.pixelWidth -= dif;
			}
			divobj.style.height = (objs[cnt].y2 - objs[cnt].y1)*factorY + "px";
			if(divobj.style.pixelHeight + newy > previewImgObj.height)
			{
				var dif = (newy + divobj.style.pixelHeight) - previewImgObj.height;
				divobj.style.pixelHeight -= dif;
			}
			divobj.style.display = visibility;
			//position corresponding editIcon accordingly
			if(editIconName != null) 
			{
				var editIcon = document.getElementById(editIconName + cnt);
				if(editIcon!=null) //edit icon only available for Fullscreen proofing
				{
					editIcon.style.left = (newx + offsetX + (divobj.offsetWidth) - 10) + "px";
					editIcon.style.top = (newy + offsetY - 10) + "px";
					
					var hideSectionCheckbox= document.getElementById("ctl00_mainContent_showHideSpreadSections_fullScreen_showHideSections");
					ShowHideItem(hideSectionCheckbox, editIcon);
				}
			}
			//if(cnt == -1)
			{
				var finaly = newy + offsetY;
				var cury = GetAbsoluteTop(divobj);
				var diff = finaly - cury;
				var newprojectedy = finaly + diff;
				//alert("finaly=" + finaly + "\ncury=" + cury + "\ndiff=" + diff + "\nnewprojectedy=" + newprojectedy);
				//divobj.style.top = finaly + diff;
				cury = GetAbsoluteTop(divobj);
				//alert("cury=" + cury);
			}
		} else {
			working = false;
		}
		cnt++;
	}
}

function ShowHideItem(checkboxObj, obj)
{
	if(checkboxObj != null && obj != null)
	{
		if(fullscreen_currentMode == "Normal") //normal mode, show/hide item depending on checkbox value
		{
			if(checkboxObj.checked)
				obj.style.display = "none";
			else	
				obj.style.display = "inline";
		}
		else //compare mode, hide item
			obj.style.display = "none";
	}
	else
	{
		obj.style.display = "inline";
	}
}

//save the original text here...
var originalSectionTextContents = "";
var originalSectionTextContentsStyleArrayCount = new Object;

function checkStyles(textAreaId, warningDivId, saveTextChangesButtonId) 
{
	var textareaObj = document.getElementById(textAreaId);
	var warningDivObj = document.getElementById(warningDivId);
	var textEditorEnabled = typeof(useRichTextEditor) != "undefined" && useRichTextEditor ? true : false;

	//position the div area correctly
	var tx = textareaObj.style.left;
	var ty = textareaObj.style.top;
	var addy = 40; //for proofing
	if(adBuilderMode)
	{
		//this is adbuilder
		tx = GetAbsoluteLeft(textareaObj);
		ty = GetAbsoluteTop(textareaObj);
		addy = -10;
	}
	var newx = Math.ceil((parseInt(textareaObj.offsetWidth) - parseInt(warningDivObj.style.width)) / 2) + tx;	
	warningDivObj.style.left = (newx) + "px";
	warningDivObj.style.top = (ty + addy) + "px";
	
	var okButton = document.getElementById(saveTextChangesButtonId);

    var styleArray = textareaObj.value.split(STYLEMARKER);
    
    if(textEditorEnabled)
    {
        if(tinyMCE.isGecko)
            styleArray = tinyMCE.getContent().split("&curren;");
	    else
	        styleArray = tinyMCE.getContent().split(STYLEMARKER);
	}
	
	if( originalSectionTextContentsStyleArrayCount[textAreaId] != (styleArray.length) )
	{
	    if(textEditorEnabled)
	    {
	        tinyMCE.setContent(curSectionTextContents);
	    }
	    else
	    {
		    var scrollY = textareaObj.scrollTop;
		    var curCursorPos = GetCursorPosition(textareaObj);
		    textareaObj.value = curSectionTextContents;
		    setCaretPosition(textareaObj, curCursorPos);
		    textareaObj.scrollTop = scrollY;
		}
        
		warningDivObj.style.display = "inline";	
		FixPNG();
	}
	curSectionTextContents = textEditorEnabled ? tinyMCE.getContent() : textareaObj.value;
}

function HideWarningDiv(warningDivId, textareaId)
{
	var warningDivObj = document.getElementById(warningDivId);
	warningDivObj.style.display = "none";
    
    if(typeof(useRichTextEditor) == "undefined" || !useRichTextEditor)
    {
		if(textareaId == null) return;
	    
	    var textareaObj = document.getElementById(textareaId);
	    textareaObj.style.display = "";	
    	
	    //refocus textarea
	    textareaObj	.focus();
	}
}

//holds the text contents value used for proofing and adbuilder styles count system
var curSectionTextContents = "";

function setCaretPosition(elem, caretPos) {
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
function GetCursorPosition(node) {
	if(node.selectionStart) return node.selectionStart;
	else if(!document.selection) return 0;
	var c		= "\001";
	var sel	= document.selection.createRange();
	var dul	= sel.duplicate();
	var len	= 0;
	dul.moveToElementText(node);
	sel.text	= c;
	len		= (dul.text.indexOf(c));
	sel.moveStart('character',-1);
	sel.text	= "";
	return len;
}
function hideWarningDiv(warningDivId)
{
	var warningDivObj = document.getElementById(warningDivId);
	if (warningDivObj != null)
		warningDivObj.style.display = "none";
}

function GetStylesControlCodeCount(textboxName)
{
	var textareaObj = document.getElementById(textboxName);
	if (textareaObj != null)
	{
		originalSectionTextContents = textareaObj.value;
		originalSectionTextContentsStyleArrayCount[textboxName] = originalSectionTextContents.split(STYLEMARKER).length;
		curSectionTextContents = originalSectionTextContents;
	}
}

function GetStylesControlCodeCountForEditor(textboxId, styleMarkerSpan)
{
    originalSectionTextContents = tinyMCE.getContent();
    originalSectionTextContentsStyleArrayCount[textboxId] = originalSectionTextContents.split(styleMarkerSpan).length;
    curSectionTextContents = originalSectionTextContents;
}

function correctionDivToggle(nameToToggle) {
	var divName = nameToToggle;
	var working = true;
	var cnt = 0;
	
	while(working) {
		var divobj = document.getElementById(divName + cnt);
		if( divobj != null )
		{
			if ( divobj.style.display != "none" )
				divobj.style.display = "none";
			else
				divobj.style.display = "block";
		} else {
			working = false;
		}
		cnt++;
	}
}

function ToggleModifiedTextFrames()
{
	correctionDivToggle("modified_");
}

function ResetAnnoIcons()
{
	var annoIconName = 'annotation_';
	var working = true;
	var cnt = 0;
	
	while(working) 
	{
		var annoIcon = document.getElementById(annoIconName + cnt);
		if( annoIcon != null )
		{
			annoIcon.onmousedown = function(){};
			annoIcon.style.cursor = "hand";
		}
		else 
			working = false;
		cnt++;
	}
}

function ShowHideAnno(obj)
{
	correctionDivToggle('annotation_');
	if (obj.checked)
	{
		ShowHideCorrectionDiv('annotationDiv_',false);
		ShowHideCorrectionDiv('annotContents_',false);
		ResetAnnoIcons();
	}
	clearAllDrawnLines();
}

function ToggleSpreadItems(show)
{
	//alert('ToggleSpreadItems _ ' + show);
	ShowHideCorrectionDiv('secHilight_',show);
	ShowHideCorrectionDiv('editIcon_',show);
	ShowHideCorrectionDiv('regionDivs_',show);
	ShowHideCorrectionDiv('annotation_',show);
}

var disableScroll = false;
function HideAllDivRegions()
{
	disableScroll = true;
	ToggleSpreadItems(false);
	activeDivObj = null;
}

function ShowHideCorrectionDiv(nameToToggle, show)
{
	var divName = nameToToggle;
	var working = true;
	var cnt = 0;
	
	while(working) {
		var divobj = document.getElementById(divName + cnt);
		if( divobj != null )
		{
			if (show)
			{
				if( divobj.style.display != "block" )
					divobj.style.display = "block";
			}
			else
			{
				if( divobj.style.display != "none" )
					divobj.style.display = "none";
			}
		} 
		else 
		{		
			working = false;
		}
		cnt++;
	}
}
var activeSectionIndex;//used in corFull

function UpdateActiveSectionIndex(index)
{
	activeSectionIndex = index;
}

function doClick(divObj, repeaterName) {
	var textCorrDiv = document.getElementById("ctl00_mainContent_textCorrectionDiv");
	if((textCorrDiv!=null) && previousActiveHighlightDiv != null && (divObj.id == previousActiveHighlightDiv.id) && (textCorrDiv.style.display=="block"))
	{
		textCorrDiv.style.display = "none";
		return;
	}
	//get the index of the div tag. name is: "secHilight_1"
	var index;
	var divIdSplit = new Array(2);
	divIdSplit = divObj.id.split("_");
	if(divIdSplit[0] == "modified")
		index = ModifiedIndexArray[divIdSplit[1]];
	else
		index = divIdSplit[1];
	
	//Used in corFull
	activeSectionIndex = index;
	//find the A tag						
	var indexstr = parseInt(index,10)+1;
	if( indexstr < 10) indexstr = "0" + indexstr; 
	var atag = document.getElementById(repeaterName + "_ctl" + indexstr + "_link");
	
	if(atag == null )
		alert("Please change to Text view before clicking on a text area.\n\nClick the Text tab next to the spread tab.");
	else
	{
		if(mozilla) //var set in annotation.js
			eval(atag.href);
		else
		{
			atag.click();	//must be IE then
		}	
	}
	
}

function positionTextCorDiv(obj)
{
	var divObjId = "secHilight_"+parseInt(obj);
	var divObj = document.getElementById(divObjId);
	activeDivObj = divObj;
	setActiveHighlightDiv();
	//TODO : Pass id to the function
	var textCorrDiv = document.getElementById("ctl00_mainContent_textCorrectionDiv");
	textCorrDiv.style.height = "auto";
	textCorrDiv.style.width = "auto";
	textCorrDiv.style.width = "500px";
	
	var divObjTop = parseInt(divObj.style.top);
	var divObjHeight = parseInt(divObj.style.height);
	var divObjLeft =  parseInt(divObj.style.left);
	var divObjWidth =  parseInt(divObj.style.width);
	
	var textCorDivTop = divObjTop+divObjHeight;
	var textCorDivLeft = parseInt(divObjLeft+(divObjWidth/2),10);
	
	var windowHeight = 0;
	var textCorHeight = 0;
	var textCorWidth = 0;
	
	var clientW = 0;
	
	if(textCorrDiv.offsetHeight == 0) 
	{
		textCorrDiv.style.display = "block";
	}

	textCorHeight = textCorrDiv.offsetHeight;	
	textCorWidth = parseInt(textCorrDiv.style.width,10);
	if(textCorrDiv.offsetHeight == 0) 
	{
//		textCorrDiv.style.display = "none";
	}

	if (window.innerHeight)//FireFox
	{
		clientW = window.innerWidth;
		windowHeight = window.innerHeight;
	}  
	else if (document.body.clientHeight) //IE
	{
		clientW = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	if(textCorHeight <= 0) 
		textCorHeight = 254; //TODO: To remove default height
	if ( (textCorDivTop + textCorHeight) > windowHeight ) //if panel goes out of window, position it on top of div area
	{
		newy = windowHeight - textCorHeight - 20;
		if(!IsBrowserIE()) newy -= 20;
		if(newy < 0) newy = 10;
		textCorrDiv.style.top = newy + "px";
		textCorrDiv.style.left = divObjLeft + "px";
	}
	else
	{
		textCorrDiv.style.top= (textCorDivTop - 10) + "px"; //Subtracted 10 to cater for shade around textCorDiv
	}
	//check if out of bounds x axis
	var newX = textCorDivLeft-10;
	if(parseInt(newX + textCorWidth,10) > clientW) 
	{
		newX = parseInt(clientW-textCorWidth,10);
	}
	textCorrDiv.style.left = (newX-20) + "px"; //Subtracted 10 to cater for shade around textCorDiv
	if(parseInt(textCorrDiv.style.left,10) < 0)
		textCorrDiv.style.left = "5px";
	textCorrDiv.style.display = "block";
	return;

	var textCorrShadeImg = document.getElementById("ctl00_mainContent_textCorrection_textCorrShadeImage");
	//if(textCorrShadeImg!=null)
	//	textCorrShadeImg.style.height = (textCorrDiv.offsetHeight) + "px";
	setFloatingDivzIndex("ctl00_mainContent_textCorrectionDiv");
	FixPNG();
}


// Ajax

var hasBeenSet = false;
var prm;
var updatingElementId; //holds the element being updated

function pageLoad( )
{
	if(!hasBeenSet)
	{
		prm = Sys.WebForms.PageRequestManager.getInstance( );
		prm.add_pageLoaded( PageLoadedHandler );
		//prm.add_pageLoaded( MoveObjectsToRootPageLoad );
		prm.add_beginRequest( BeginRequestHandler );
		prm.add_endRequest( EndRequestHandler );
	}
	hasBeenSet = true;
}
		
function BeginRequestHandler( sender, args ) 
{
    var postBackElement = args.get_postBackElement();
    FadeUpdatingElement(postBackElement.id);
}

function EndRequestHandler( sender, args ) 
{
	UnFadeUpdatingElement(); //unfade the element after async postback completes
}

function FadeUpdatingElement(postBackElementId)
{
	//determine which element to fade //add new ones here
	if(postBackElementId.indexOf("folderList_hierarchical") >= 0 )
		updatingElementId = "fileListDiv";
	else if (postBackElementId.indexOf("assetFileList_fileRepeater") >= 0 )
		updatingElementId = "imageInfoFilter";
  
    //fade the element
    var updatingElementObj = document.getElementById(updatingElementId);
	if (updatingElementObj != null)
	{
		//updatingElementObj.style.color = "gray";
		//updatingElementObj.style.filter = "alpha(opacity=50);";
		//updatingElementObj.style.opacity = ".40";
	}
}

function UnFadeUpdatingElement()
{
	var updatingElementObj = document.getElementById(updatingElementId);
	if (updatingElementObj != null)
	{
		updatingElementObj.style.filter = "";
		updatingElementObj.style.opacity = "";
	}
	updatingElementId = "";
}
                   
function PageLoadedHandler( sender, args )
{
	/* *** Print check *** */
//	var prm = Sys.WebForms.PageRequestManager.getInstance(); 
//    prm._doPostBack('printTabLink','');
//    
//	var url = window.location;
//	var printRegex = "print=true";
//	var queryResult = url.toString().search(printRegex);
//	if( queryResult != -1)
//		getPrint();
	/* ***End Print check *** */
	
	//Signatur-activity overview
	var assetFilesDiv = document.getElementById('ctl00_mainContent_assetFilesDetails');
	if(assetFilesDiv != null)
	{
		var showHideLink = document.getElementById('ctl00_mainContent_showHide');
		if(showHideLink != null && assetFilesDiv.scrollHeight < 110)
		{
			showHideLink.onclick = "";
			showHideLink.removeAttribute('href');
			showHideLink.setAttribute('onclick','javascript:return false;');
		}
	}
	
	var dataItems = args.get_dataItems();
	var obj = dataItems['ctl00_mainContent_textCorrectionUpdatePanel'];
	if(obj != null)
		positionTextCorDiv(obj);
	
	GetStylesControlCodeCount('ctl00_mainContent_textCorrection_fullScreen_sectionText');
	var textCorrDiv = document.getElementById("ctl00_mainContent_textCorrectionDiv");
	
	var sectionIndex = dataItems['ctl00_mainContent_textCorrectionDiv'];
	if( sectionIndex != null)
	{
		var editIconObj = document.getElementById("editIcon_" + sectionIndex );
		if (editIconObj != null)
			editIconObj.src = "/images/proofPanel/edited.png";
		textCorrDiv.style.display = "none";
	}
	
	var normalProofSectionIndex = dataItems['ctl00_mainContent_corTextCorrectionDiv'];
	if(normalProofSectionIndex != null)
	{
		var normalProofEditIconObj = document.getElementById("editIcon_" + normalProofSectionIndex);
		if(normalProofEditIconObj != null)
			normalProofEditIconObj.src = "/images/proofPanel/edited.png";
	}
	
	var textNavigatorDiv = document.getElementById("textNavigatorDiv");
	if( textNavigatorDiv != null && textNavigatorDiv.style.display == "block" )
	{ 
		var linkButtonId = dataItems['ctl00_mainContent_textNavigatorUpdatePanel'];
		if(linkButtonId !=null)
		{
			var linkButton = document.getElementById(linkButtonId);
			linkButton.scrollIntoView();
			linkButton.focus();
		}
	}
	FixPNG();
	
	var hiddenField = document.getElementById("ctl00_mainContent_regionCellId");
	if (hiddenField != null)
	{
		var selectedRegionCell = document.getElementById(hiddenField.value);
		if (selectedRegionCell != null)
		{
			var regionDiv = document.getElementById("ctl00_mainContent_selectRegionDiv");
			
			if (regionDiv != null)
			{
				regionDiv.style.top = GetAbsoluteTop(selectedRegionCell);
				regionDiv.style.left = GetAbsoluteLeft(selectedRegionCell);		
			}
		}
	}
} 

function openWindow(windowName, url, showScrollbars,width, height) {
	//window.open("/Correction/previewImage.aspx?url=" + url);
	var maxWidth = 1023;
	if(width == null) width=(screen.width-200);
	if(width > maxWidth) width = maxWidth;
	if(height == null) height=(screen.height-200);
	if(windowName == null) windowName = "undefinedname";

	var left = 400;
	var top = 400;
	
	if (window.innerHeight)
	{
		top = (window.innerHeight/2) - (height/2) + screenY;
		left = (window.innerWidth/2) - (width/2) + screenX;
	}  
	else if (document.body.clientHeight)
	{
		top =(document.body.clientHeight/2) - (height/2) + screenTop;
		left = (document.body.clientWidth/2) - (width/2) + screenLeft;
	}

	var scrollbars = "yes";
	var resizable="yes";

	if( showScrollbars != null ) 
		scrollbars = showScrollbars;
	
	window.open(url, windowName,"resizable=" + resizable +",height=" + height + ",width=" + width + ",left=" + left + ",top=" + top + ",status=yes,scrollbars=" + scrollbars +",toolbar=no,menubar=no,location=no");
}

//*****************************************************************************************************************************
function Region(x1,y1,x2,y2) 
{
	this.x1 = x1;
	this.y1 = y1;
	this.x2 = x2;
	this.y2 = y2;
}

function AnnotationRegion(x1,y1,sourcesizex,sourcesizey) 
{
	this.x1 = x1;
	this.y1 = y1;
	this.sourcesizex = sourcesizex;
	this.sourcesizey = sourcesizey;
}


function mouseX(evt) {
	if (evt.pageX) 
		return evt.pageX;
	else if (evt.clientX)
		return evt.clientX + (document.documentElement.scrollLeft ?	document.documentElement.scrollLeft : document.body.scrollLeft);
	else 
		return null;
}
function mouseY(evt) {
	if (evt.pageY) 
		return evt.pageY;
	else if (evt.clientY)
		return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	else 
		return null;
}


function GetAbsoluteLeft(oNode){
    var oCurrentNode=oNode;
    var iLeft=0;
    while(oCurrentNode && oCurrentNode.tagName!="BODY"){
    iLeft+=oCurrentNode.offsetLeft;
    oCurrentNode=oCurrentNode.offsetParent;
    }    
    //alert("Left: " + oNode.offsetLeft + "\nAbsolute Left: " + iLeft);
    return(iLeft);
}

function GetAbsoluteLeftUsingStyle(oNode){
    var oCurrentNode=oNode;
    var iLeft=0;
    while(oCurrentNode && oCurrentNode.tagName!="BODY"){
		var posx = parseInt(oCurrentNode.style.left,10);
		if(!isNaN(posx))
			iLeft += posx;
	    oCurrentNode = oCurrentNode.parentNode;
    }    
    return(iLeft);
}

function GetAbsoluteTop(oNode)
{
    var oCurrentNode = oNode;
    var iTop = 0;
    while(oCurrentNode && oCurrentNode.tagName!="BODY"){
	    iTop += oCurrentNode.offsetTop;
		oCurrentNode=oCurrentNode.offsetParent;
    }
    return(iTop);
}

function GetAbsoluteTopUsingStyle(oNode){
    var oCurrentNode = oNode;
    var iTop = 0;
    while(oCurrentNode && oCurrentNode.tagName!="BODY"){
		var posy = parseInt(oCurrentNode.style.top,10);
		if(!isNaN(posy))
			iTop += posy;
		oCurrentNode = oCurrentNode.parentNode;
    }    
    return(iTop);
}

function toggletrace() 
{
	var traceobj = document.getElementById("traceinfo");
	traceobj.style.display = "inline";
}

function AssetApprovalFormShow(event, id, fileId, folderId)
{
	// the 'event' parameter is required by firefox + is compatible with IE
	var curstyle;
	var obj = document.getElementById("ApprovalPopUp");
	//var hiddenfield = document.getElementById("fileId");
	var hiddenFileId = document.getElementById(fileIdFieldName);
	hiddenFileId.value = fileId;
	
	var hiddenFolderId = document.getElementById(folderIdFieldName);
	hiddenFolderId.value = folderId;

	var curstyle = obj.style.display;
	
	if( curstyle == "none" ) {
		var newy = mouseY(event) + 5;
		if( newy < 0 ) newy = 0;		
		obj.style.top = newy+"px"; // 'px' is required, else wont display in firefox

		var newx = mouseX(event) - 40;
		if( newx < 0 ) newx = 0;
		obj.style.left = newx+"px";// 'px' is required, else wont display in firefox
		obj.style.display = "inline";
	} else {
		obj.style.display = "none";
	}	
}

function ApprovalFormShow(event,id, fileid) 
{
	// the 'event' parameter is required by firefox + is compatible with IE
	var curstyle;
	var obj = document.getElementById("ApprovalPopUp");
	//var hiddenfield = document.getElementById("fileId");
	var hiddenfield = document.getElementById(fileIdFieldName);
	hiddenfield.value = fileid;
	curstyle = obj.style.display;
	
	if( curstyle == "none" ) {
		var newy = mouseY(event) + 5;
		if( newy < 0 ) newy = 0;		
		obj.style.top = newy+"px"; // 'px' is required, else wont display in firefox

		var newx = mouseX(event) - 40;
		if( newx < 0 ) newx = 0;
		obj.style.left = newx+"px";// 'px' is required, else wont display in firefox
		obj.style.display = "inline";
	} else {
		obj.style.display = "none";
	}	
}


//form appproval
function FolderApprovalFormShow(id, folderid) 
{
	var curstyle;
	var obj = document.getElementById("FolderApprovalPopUp");
	//var hiddenfield = document.getElementById("fileId");
	var hiddenfield = document.getElementById(selectedFolderId);
	hiddenfield.value = folderid;
	curstyle = obj.style.display;
	
	if( curstyle == "none" ) {
		var newy = mouseY(event) + 5;
		if( newy < 0 ) newy = 0;
		obj.style.top = newy;

		var newx = mouseX(event) - 40;
		if( newx < 0 ) newx = 0;
		obj.style.left = newx;
		obj.style.display = "inline";
	} else {
		obj.style.display = "none";
	}
}
//form approval

function showContextMenu(fileId) 
{
	var isLatestVersionObj = document.getElementById("ctl00_mainContent_isLatestVersion");
	if(isLatestVersionObj != null)
	{
		if(isLatestVersionObj.value == "false") 
			return;
	}
	displayShortcutMenu(fileId);
	return false;
}

function expandSection(obj) 
{
	//obj is the DIV object containing the link. Find the next div and show-hide it
	var par = obj.parentNode;
	var matchcnt = 0;
	var node;
	var imgNode = null;
	for(var i=0;i<par.childNodes.length;i++) 
	{
		node = par.childNodes[i];
		if( node.tagName == "DIV" )
			matchcnt++;
		if( matchcnt == 2)
		{	
			//locate img node
			//alert(node.innerHTML);
			//alert(node.childNodes.length);
			for(var n=0;n<node.childNodes.length;n++) 
			{
				var tmpnode = node.childNodes[n];
				if( tmpnode.tagName == "IMG" )
				{
					imgNode = tmpnode;
					break;
				}
			}
		}
		if( matchcnt == 3)
			break;
	}
	if( node.style.display == "none" )
	{
		node.style.display = "block";
		if( imgNode != null ) 
			imgNode.src = "/images/icons/minus.gif";
	}
	else
	{
		node.style.display = "none";
		if( imgNode != null ) 
			imgNode.src = "/images/icons/plus.gif";
	}
}


function validateSendMail(Event)
{
	return true;
	if ((document.getElementById(CheckedEmailItems) == null) || (document.getElementById(CheckedEmailItems).value == ""))
	{	
		document.getElementById("ErrorTable").style.display = "block";
		return false;
	}
	return true;
}


function RecordCheckedItem(elementId,ObjCheckbox) 
{ 	
	if (ObjCheckbox.checked)
	{		
		if (document.getElementById(CheckedEmailItems) != null)
		{
			// add in the list
			document.getElementById(CheckedEmailItems).value = ObjCheckbox.id +","+ document.getElementById(CheckedEmailItems).value;
			document.getElementById("ErrorTable").style.display = "none";		
		}	
	}
	else
	{
		// if present in the list then remove 		
		var HiddenFieldContent = document.getElementById(CheckedEmailItems).value;
		var myArray = HiddenFieldContent.split(',');
		var NewList= "";
		
		for(var i=0; i<myArray.length-1; i++)
		{		
			if (myArray[i] == "")								
				continue;
							
			if (myArray[i]!=ObjCheckbox.id)				
				NewList = myArray[i]+","+NewList;
		}
		document.getElementById(CheckedEmailItems).value = NewList;		
	}

}

function toggleTableRow(tableRowName,checkboxName) 
{
	// used in mailform.aspx
	var ObjectToToggle = document.getElementById(tableRowName);
	if (ObjectToToggle == null)
		return;
	var Checkbox = document.getElementById(checkboxName);

	if (Checkbox.checked)
		{
            try 
				{   // to show a table row in firefox we should use the value 'table-row'           
					ObjectToToggle.style.display="table-row";            
				} 
			catch(e) 
				{              
					ObjectToToggle.style.display = "block";            
				}						
		}
	else
		ObjectToToggle.style.display = "none";				
}


function moveFocusToPasswordTextBoxFunction()
{
	if (window.event.keyCode == 13)        
    {
        //prevent from submitting the form
        event.returnValue = false;
        event.cancel = true;
        
        //Get the text box and then set the focus
        var obj =document.getElementById('loginbox_Password');
        obj.focus();
	}
}

//******************************************************
// WORKFLOW Scripts
//******************************************************
var lastSelectedWorkflowTaskId = null;
var lastToggleTaskObj = null;
var lastHighlightClassName = null;
function toggleNext(obj) 
{
	//hilight current row
	var rowClass = obj.className;
	
	//unselect the last hilighted row
	if(lastToggleTaskObj != null) 
	{
		toggleClassName(lastToggleTaskObj, "selected", "normal");
		lastToggleTaskObj.className = lastHighlightClassName;
		toggleGeneric(lastSelectedWorkflowTaskId);
		onMouseOutWF(lastToggleTaskObj);
	}
	
	//change the className to show HILIGHTed row
	if(obj != lastToggleTaskObj)
	{
		lastSelectedWorkflowTaskId = obj.id + "2";
		lastToggleTaskObj = obj;
		lastHighlightClassName = obj.className;	//store the current classname
		toggleClassName(obj, "selected", "normal");
		toggleGeneric(obj.id + "2");
	} else {
		lastSelectedWorkflowTaskId = null;
		lastToggleTaskObj = null;
		lastHighlightClassName = null;
	}
		
	var objPlus2 = document.getElementById(obj.id + "2");
	var hiddenTaskExpandedObj = document.getElementById(expandedTasksClientId);
	if(objPlus2.style.display == "block")
	{
		hiddenTaskExpandedObj.value = obj.id;
	}
	else
	{
		hiddenTaskExpandedObj.value = -1;
	}
}

function expandSelectedWorkflowTasks(id)
{
	if(id=="") return;
	var obj = document.getElementById(id);
	if( obj == null ) return;
	toggleNext(document.getElementById(id));
	
	var taskDateControlTableId = GetCookie("WorkflowTaskAdd_Expand");
	if( taskDateControlTableId != null)
	{
		showHideGeneric(taskDateControlTableId,true);
	}
}

function toggleClassName(obj, hilightName, normalName) 
{
	if(obj == null) return;
	if(obj.className != hilightName)
		obj.className = hilightName;
	else
		obj.className = normalName;
	return obj.className;
}

//TODO: Refactor, similar function 'toggle' exists
function toggleGeneric(id) 
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	if( obj.style.display == "none") 
        obj.style.display = "";
	else
		obj.style.display = "none";
}

function ToggleHistory(id,imageId) 
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	var textCorrShadeImg = document.getElementById(imageId);
	
	if( obj.style.display == "none") 
	{
		obj.style.display = "block";
		if(textCorrShadeImg!=null)
		{
			var historyDivHeight = parseInt(obj.offsetHeight)+10;
			if(textCorrShadeImg.style.height!="")
				textCorrShadeImg.style.height= parseInt(textCorrShadeImg.style.height)+historyDivHeight;
			else
				textCorrShadeImg.height= parseInt(textCorrShadeImg.height)+historyDivHeight;				
		}
	}
	else
	{		
		var historyDivHeight = parseInt(obj.offsetHeight);
		if(textCorrShadeImg!=null)
		{
			if(textCorrShadeImg.style.height!="")
				textCorrShadeImg.style.height= parseInt(textCorrShadeImg.style.height)-parseInt(historyDivHeight)-10;
			else
				textCorrShadeImg.height= parseInt(textCorrShadeImg.height)-historyDivHeight-10;
		}
		obj.style.display = "none";
	}
	FixPNG();
}

function FullScreenToggleGeneric(id,cellId)
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	var td = document.getElementById(cellId);
	var signOffShadeImg = document.getElementById("ctl00_mainContent_spreadSignOff_signOffShadeImg");
	var left = GetAbsoluteLeft(td);
	var top = GetAbsoluteTop(td);
	//alert("td.style.left= " + td.style.left +"\ntd.style.top= " + td.style.top);	
	if( obj.style.display == "none") 
	{
		obj.style.left = left + "px";
		obj.style.top = (parseInt(top)+33) + "px";
		obj.style.display = "block";
		setFloatingDivzIndex(id);
		//alert("obj.style.left= " + obj.style.left + "\nobj.style.top = " + obj.style.top );
		var spreadSignOffDiv = document.getElementById("spreadSignOff");
		if(spreadSignOffDiv != null)
		{
			var h = parseInt(spreadSignOffDiv.offsetHeight) + 20;
			signOffShadeImg.style.height = h + "px";
		}
    }
	else
		obj.style.display = "none";
	FixPNG();	
}

//TODO : Refactor - remove hard coded ids
//pass id instead of index
function FullScreenToggleGenericScrollIntoView(id,index,cellId)
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	var pdf = document.getElementById( "ctl00_mainContent_pdfPreviewImage");
	
	if( obj.style.display == "none") 
	{			
		var td = document.getElementById(cellId);
		var left = GetAbsoluteLeft(td);
		var top = GetAbsoluteTop(td);	
		obj.style.display = "block";		
		var selectedItem; 		
		if(parseInt(index)<10)
			index="0"+index;
			
		if (id == "spreadNavigatorDiv")
		{
			//selectedItem = document.getElementById("ctl00_mainContent_spreadNavigator_fullScreen_corSpreadNavRepeater_ctl" + index + "_pdfPreviewImage");
			//if(selectedItem!=null)
			//{
				//selectedItem.scrollIntoView();
				//selectedItem.focus();
			//}
			//position selected item at center of spread navigator
			//var contentsDiv = document.getElementById("contents");
			//var divHeight = contents.style.height;
			//var divScrollHeight = contents.scrollHeight;
			//var totalScroll = parseInt(contents.scrollTop) + parseInt(divHeight);
			//if(totalScroll < divScrollHeight)
			//{
				//var newScrollTop = ( contents.scrollTop - 250 );
				//contentsDiv.scrollTop = newScrollTop ;
			//}			
			obj.style.top = (parseInt(top)+33) + "px";
			obj.style.left = 2 + "px";
		}	

		else if (id == "textNavigatorDiv")
		{
			obj.style.top = (parseInt(top)+33) + "px";
			obj.style.left = left + "px";
			//selectedItem = document.getElementById("ctl00_mainContent_textNavigator_fullScreen_corSectionNavRepeater_ctl" + index + "_link");
			//if(selectedItem!=null)
			//{
				//selectedItem.scrollIntoView();
				//selectedItem.focus();
			//}
		}
		setFloatingDivzIndex(id);
    }
	else
		obj.style.display = "none";
	FixPNG();	
}

function expandCollapseFromCookie(cookieName, toggleBodyId, toggleImageId, toggleImageShow, toggleImageHide)
{
	var cookie = GetCookie(cookieName);

	if(cookie != null && cookie != "CookieDeleted")
	{
		toggleExpandColapseWithCookie(cookieName, toggleBodyId, toggleImageId, toggleImageShow, toggleImageHide);
	}	
}

function toggleExpandColapseWithCookie(cookieName, toggleBodyId, toggleImageId, toggleImageShow, toggleImageHide)
{
	var toggleBody = document.getElementById(toggleBodyId);
	var toggleImage = document.getElementById(toggleImageId);
	
	if(toggleBody == null) return;
	if(toggleImage == null) return;

	if(toggleBody.style.display == "none") 
	{
		toggleBody.style.display = "";
		toggleImage.src = toggleImageHide;
		DeleteCookie(cookieName, "CookieDeleted");
	}
	else
	{
		toggleBody.style.display = "none";
		toggleImage.src = toggleImageShow;
		SetCookie(cookieName, 'Collapse');
	}
}

function genericExpandFromCookie(name) 
{
	var value = GetCookie(name);
	if( value != null)
		toggleGenericWithCookie(name,value);
}

function toggleGenericWithCookie(name, id) 
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	if( obj.style.display == "none") 
	{
		obj.style.display = "";
		SetCookie(name,id);
	}
	else
	{
		obj.style.display = "none";
		DeleteCookie(name);
	}
	
}



function showHideGeneric(id, show) 
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	if(show)
		obj.style.display = "block";
	else
		obj.style.display = "none";
}
function onMouseOverWF(rowObj)
{
	if(rowObj.className == "hover" || rowObj.className == "normal")
		rowObj.className = "hover";
	if(rowObj.className == "active")
		rowObj.className = "activewithhover";
}
function onMouseOutWF(rowObj)
{
	if(rowObj.className == "hover" || rowObj.className == "normal")
		rowObj.className = "normal";
	if(rowObj.className == "activewithhover")
		rowObj.className = "active";
}
//******************************************************
// Field validation routines
//******************************************************
var field = null;
function FocusControl(obj)
{
	field = obj;
	setTimeout("field.focus()",100);
	setTimeout("field.select()",150);
}

var IncorrectDateFormat = "";
function CheckDate(obj) 
{
	var ok = IsValidDate(obj.value, null);
	if(!ok) 
	{
		alert(IncorrectDateFormat);
		FocusControl(obj);
	}
}

function FixInputDate(obj) 
{
	if (obj == null)
	{
		return;
	}
	
	var dateString = obj.value.trim();
	
	if ((dateString.length == 0) || (!IsInteger(dateString)) || (dateString.indexOf('-') >= 0) || ((dateString.length != 6) && (dateString.length != 8)))
	{
		return;
	}
	
	if (dateString.length == 6)
	{
		dateString = dateString.substr(0, 2) + '-' + dateString.substr(2, 2) + '-20' + dateString.substr(4, 2);
	}
	else
	{
		dateString = dateString.substr(0, 2) + '-' + dateString.substr(2, 2) + '-' + dateString.substr(4, 4);
	}
	
	if (IsValidDate(dateString, null))
	{
		obj.value = dateString;
	}
}

function IsInteger(text)
{
	var validChars = "0123456789";
	var isInteger = true;
	var character;
 
	for (index = 0; index < text.length && isInteger == true; index++) 
	{ 
		character = text.charAt(index); 
		
		if (validChars.indexOf(character) == -1) 
		{
			isInteger = false;
		}
	}
	
	return isInteger;
}

var InputNotNumber = "";
function CheckInteger(obj) 
{
	var intValue = parseInt(obj.value, 10);
	// if this is not an integer
	var ok = !isNaN(intValue);
	
	if(!ok) 
	{
		alert(InputNotNumber);
		FocusControl(obj);
	}
}

function IsValidDate(dateText, dateField, returnDateObject){
	var checkstr = "0123456789";
	var Datevalue = "";
	var DateTemp = "";
	var seperator = ".";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
   err = 0;
   DateValue = dateText;
   /* Delete all chars except 0..9 */
   for (i = 0; i < DateValue.length; i++) {
	  if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
	     DateTemp = DateTemp + DateValue.substr(i,1);
	  }
   }
   DateValue = DateTemp;
   /* Always change date to 8 digits - string*/
   /* if year is entered as 2-digit / always assume 20xx */
   if (DateValue.length == 6) {
      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
   if (DateValue.length != 8) {
      err = 19;}
   /* year is wrong if year = 0000 */
   year = DateValue.substr(4,4);
   if (year == 0) {
      err = 20;
   }
   /* Validation of month*/
   month = DateValue.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* Validation of day*/
   day = DateValue.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* Validation leap-year / february / day */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* if 00 ist entered, no error, deleting the entry */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   if (err == 0) {
      //DateField.value = day + seperator + month + seperator + year;
      if(returnDateObject) 
      {
	      var resultDate = new Date();
	      resultDate.setFullYear(year, month-1, day);
	      return resultDate;
	  }
      return true;
   }
   else {	/* Error-message if err != 0 */
	  if(dateField != null) {
		FocusControl(dateField);
	  }
   }
   return false;
}

//calcdif vars...
var DAYS_CF			= 86400000;       // 24 * 60 * 60 * 1000
//caller is either: 'dates', 'offset', or 'duration'
var originalStartDate = new Array(5);
var originalEndDate = new Array(5);
var DATE_FORMAT_STRING = "dd-MM-yyyy";

function CalcDiff(index, callerType) 
{
	var startDateObj	= document.getElementById(dateController_startDate[index].controlId);
	var endDateObj		= document.getElementById(dateController_endDate[index].controlId);
	var durationObj		= document.getElementById(dateController_duration[index].controlId);
	var offsetDayObj	= document.getElementById(dateController_offset[index].controlId);
	
	originalStartDate[index] = IsValidDate(dateController_startDate[index].value,null,true);
	originalEndDate[index] = IsValidDate(dateController_endDate[index].value,null,true);
	
	//check offset valid
	if(offsetDayObj == null) return;	//this might cause problems if we want to calculate other stuff (but without the offsetdayobj)
	var intValue = parseInt(offsetDayObj.value, 10);
	if(isNaN(intValue)) return;
	var offsetDays = intValue;
	//check duration valid
	intValue = parseInt(durationObj.value, 10);
	if(isNaN(intValue)) return;
	var duration = intValue;
	
	if(IsValidDate(startDateObj.value,null,true) && IsValidDate(endDateObj.value,null,true)) 
	{
		var inputStartDate = IsValidDate(startDateObj.value,null,true);
		var inputEndDate = IsValidDate(endDateObj.value,null,true);

		if(callerType == 'duration')
		{
			var dif = new TimeSpan(inputEndDate-inputStartDate);
			inputEndDate = inputStartDate.addDays(duration-1);
		}
		if(callerType == 'dates') 
		{ }
		if(callerType == 'offset')
		{
			inputStartDate = originalStartDate[index].addDays(offsetDays);
			inputEndDate = originalEndDate[index].addDays(offsetDays);
		}
		var durationInt = Math.round((inputEndDate-inputStartDate) / DAYS_CF) + 1;
		//set values after all...
		startDateObj.value = inputStartDate.format(DATE_FORMAT_STRING);
		endDateObj.value = inputEndDate.format(DATE_FORMAT_STRING);
		durationObj.value = durationInt;
		
		//offset allways from the ORIGINAL start date
		var realOrigStartDate = IsValidDate(dateController_startDate[index].value,null,true);
		offsetDayObj.value = Math.round((inputStartDate-realOrigStartDate) / DAYS_CF);
	}
	CalcDiff_UseMultiple(index);
	CalculateOffsetValue(index,callerType);	
}

//Adjust multiple controller dates 
function CalcDiff_UseMultiple(index, callerType) 
{
	var nr1_dateEndDate = GetDate(dateController_endDate[index].controlId);
	if(dateController_duration[index+1] == null) return;
	var nr2_durationObj = document.getElementById(dateController_duration[index+1].controlId);
	var nr2_dateStartObj = document.getElementById(dateController_startDate[index+1].controlId);
	var nr2_dateEndObj = document.getElementById(dateController_endDate[index+1].controlId);
	var nr2_lockDateObj = document.getElementById(lockDates[index+1]);
	var nr3_lockDateObj = document.getElementById(lockDates[index+2]);
	
	var nr2_offsetObj = document.getElementById(dateController_duration[index+1].controlId);

	//handle only one controller
	if(nr2_lockDateObj == null) return;
	if(!nr2_lockDateObj.checked)
	{
		if(nr2_durationObj != null && isNaN(parseInt(nr2_durationObj.value))) return;
		nr2_dateStartObj.value = nr1_dateEndDate.addDays(1).format(DATE_FORMAT_STRING);		
		nr2_dateEndObj.value = nr1_dateEndDate.addDays(parseInt(nr2_durationObj.value )).format(DATE_FORMAT_STRING);
		
		dateController_startDate[index+1].value = nr1_dateEndDate.addDays(1).format(DATE_FORMAT_STRING);
		dateController_endDate[index+1].value = nr2_dateEndObj.value;
	}
	
	if(nr3_lockDateObj != null) 
	{
		if(!nr3_lockDateObj.checked) 
		{
			var nr2_dateEndDate = GetDate(dateController_endDate[index+1].controlId);
			var nr3_durationObj = document.getElementById(dateController_duration[index+2].controlId);
			var nr3_dateStartObj = document.getElementById(dateController_startDate[index+2].controlId);
			var nr3_dateEndObj = document.getElementById(dateController_endDate[index+2].controlId);
			
			var nr3_offsetObj = document.getElementById(dateController_duration[index+2].controlId);

			if(nr3_durationObj != null && isNaN(parseInt(nr3_durationObj.value))) return;
			
			nr3_dateStartObj.value = nr2_dateEndDate.addDays(1).format(DATE_FORMAT_STRING);		
			nr3_dateEndObj.value = nr2_dateEndDate.addDays(parseInt(nr3_durationObj.value)).format(DATE_FORMAT_STRING);	
			
			dateController_startDate[index+2].value = nr2_dateEndDate.addDays(1).format(DATE_FORMAT_STRING);
			dateController_endDate[index+2].value = nr3_dateEndObj.value;
		}
	}
}

function CalculateOffsetValue(changedIndex,callerType)
{
    var working = true;
    var index = 1;
    
    while(working)
    {
        if(typeof(dateController_offset[index+1]) != 'undefined' && typeof(dateController_startDate[index+1]) != 'undefined' && typeof(dateController_endDate[index]) != 'undefined')
        {
            var offsetObj = document.getElementById(dateController_offset[index+1].controlId);
            var startDateObj = document.getElementById(dateController_startDate[index+1].controlId); 
            var endDateObj = document.getElementById(dateController_endDate[index].controlId); 
            
            if(offsetObj != null && startDateObj != null && endDateObj != null)
            {
                if(index+1 != changedIndex)
                {
                    var diff = Math.round((GetDate(startDateObj.id) - GetDate(endDateObj.id))/DAYS_CF);
                    
                    if(diff >= 0)
                        offsetObj.value = diff - 1;
                    else
                        offsetObj.value = diff + 1;
                }
                index++;
            }
            else 
                working = false;
        }
        else
            working = false;
    }
}

function GetDate(id) 
{
	var obj = document.getElementById(id);
	var dateVal = IsValidDate(obj.value,null,true);
	return dateVal;
}

function ControlAndValue(controlId, value)
{
	this.controlId = controlId;
	this.value = value;
}

function TaskHelper(wfid, title, startdate, enddate, duration, enableNotification, daysBefore) 
{
	this.wfid = wfid;
	this.title = title;
	this.startdate = startdate; //IsValidDate(startdate,null,true);
	this.enddate = enddate;		//IsValidDate(enddate,null,true);;
	this.duration = duration; 
	this.enableNotification = enableNotification;
	this.daysBefore = daysBefore;
}

//Occurs when a user selects a specific task in the workflow configurator dropdown
function TaskListOnChange(index, objectId, daysBeforeNotificationHFId)
{
    var object = document.getElementById(objectId);
    if(object == null)
        return;
        
	var daysBeforeNotificationHF = document.getElementById(daysBeforeNotificationHFId);
	if(daysBeforeNotificationHF == null) 
		return;
		
	first = true;
	var selValue = object.options[object.selectedIndex].value;
	var selIndex = object.selectedIndex;
	
	if (selIndex == 0 || selValue < 0)
	{	
	    DeleteCookie('WorkflowTaskAdd_Expand');
		showHideGeneric(taskDateControlTableId[index],false);	//true means Show
		return;
	}
	else 
	{
		showHideGeneric(taskDateControlTableId[index],true);	//true means Show
		SetCookie("WorkflowTaskAdd_Expand",taskDateControlTableId[index]);
	}
	
	var task = tasks[index][selIndex-1];
	var nameObj			= document.getElementById(dateController_name[index].controlId);
	var startDateObj	= document.getElementById(dateController_startDate[index].controlId);
	var endDateObj		= document.getElementById(dateController_endDate[index].controlId);
	var durationObj		= document.getElementById(dateController_duration[index].controlId);
	var offsetDayObj	= document.getElementById(dateController_offset[index].controlId);
	var enableNotificationObj = document.getElementById(dateController_enableNotification[index].controlId);
	var daysBeforeObj = document.getElementById(dateController_daysBefore[index].controlId+"_textbox");
	
	nameObj.value							= task.title; 
	dateController_startDate[index].value	= task.startdate; 
	dateController_endDate[index].value		= task.enddate; 
	dateController_duration[index].value	= task.duration; 
	dateController_offset[index].value		= 0;

	if(task.enableNotification == "True")
		enableNotificationObj.checked = true;
	else
		enableNotificationObj.checked = false;
	
	TriggerOnClickEvent(enableNotificationObj);		
	daysBeforeObj.value	= task.daysBefore;
	daysBeforeNotificationHF.value = daysBeforeObj.value;	//add value to hidden field
	
	var tmpdate = IsValidDate(task.startdate,null,true);
	startDateObj.value	= tmpdate.format(DATE_FORMAT_STRING); //task.startdate.format(DATE_FORMAT_STRING);
	
	tmpdate = IsValidDate(task.enddate,null,true);
	if(endDateObj != null) endDateObj.value	= tmpdate.format(DATE_FORMAT_STRING);	
	if(durationObj != null) durationObj.value	= task.duration;
	
	CalcDiff_UseMultiple(index,null);
	CalcDiff_UseMultiple( (index-1)<0 ? 0 : index-1,null);
}

function TriggerOnClickEvent(checkbox)
{
	if (window.event) //IE
		checkbox.fireEvent('onclick');
	else
	{
		/* when triggering click event, value for check box also changing
		   if value = true, then changed to false and vice versa.
		   so need to reset value again. (Only when adding a task)
		*/
		checkbox.checked = !checkbox.checked;	
		var evt = document.createEvent("MouseEvents");
		evt.initEvent("click", true, true); 
		checkbox.dispatchEvent(evt);
		
		//if checkbox is disabled, then uncheck check box (only when adding a task group)
		if(checkbox.disabled) checkbox.checked = false;
	}
}

function proofIndexToggle(controlName) 
{	
	var selectedClassName = "correctionApplyChangesGroupSelected";
	var newClassName = toggleClassName(document.getElementById(controlName), selectedClassName, "correctionApplyChangesGroupNormal");
	toggleGeneric(controlName + "Controls");

	if( newClassName == selectedClassName)
	{
		SetCookie("proofIndex",controlName);
	}
}

function proofIndexExpand() 
{
	var controlName = GetCookie("proofIndex");
	if( controlName != null && document.getElementById(controlName) != null)
		proofIndexToggle(controlName);
		
	//check proofing group also
	controlName = GetCookie("generatePDFPanel");
	if( controlName != null && document.getElementById(controlName) != null)
		toggleGenericWithCookie(controlName, controlName);
}

function ConfirmationPrompt(message)
{ 	
	var answer = confirm(message)

	if (answer)
		return true;
	else
		return false;
}

function IsValidMail()
{ 		
	// TODO : kiran - read the username textbox and check if the username is a valid email address.
	return true;
}

function DisableEnterKey(e) 
{
	if (e.keyCode)
		keycode=e.keyCode;
	else
		keycode=e.which;

	if (keycode == 13) //Enter key is pressed!!
		return false;
	else
		return true;
}

//guidance
//*************** guidance hide/show **********************
function ShowGuidance(sectionToShow, link)
{
	return;
	var roleSection=document.getElementById(sectionToShow);	
	var link=document.getElementById(link);	
	var anchorText=link.innerHTML;
		
	if(roleSection.style.display=="none")
	{
		roleSection.style.display="";	
		link.title="Click to hide details";	
	}		
	else
	{
		roleSection.style.display="none";						
		link.title="Click to show details";	
	}
	
	//Height of guidance panel should be 200 pixels
	var guidanceMainPanel=document.getElementById(guidanceMainPanelControl);
	guidanceMainPanel.style.height="200px";
	var guidancePanel=document.getElementById(guidancePanelControl);
	guidancePanel.style.height="180px";	
}

function SetGuidanceControlAndSetCookie(controlId, imageId, contentPageModuleName,reset)
{	
	var div=document.getElementById(controlId);				
	var img=document.getElementById(imageId);			
	var guidanceFrame=document.getElementById('guidanceFrame');
	var guidanceRow=document.getElementById('guidanceRow');
	guidanceRow.style.display="";
	
	var guidanceCookie=GetCookie(contentPageModuleName);	
	if (guidanceCookie)
	{				
		if(reset=='true')		
		{
			DeleteCookie(contentPageModuleName);
			if(guidanceCookie=="show")
				SetCookie(contentPageModuleName,"hide");
			else
				SetCookie(contentPageModuleName,"show");					
			//get cookie after reset
			guidanceCookie=GetCookie(contentPageModuleName);			
		}			
		if(guidanceCookie=='show')		
		{														
			img.src='/images/FLGuidance_Orange.gif';	
			div.style.display=""; 							
			guidanceFrame.style.display="";
			if(CheckIfNoGuidancePresent()==true){
				div.className='noGuidanceExpanded';
				guidanceFrame.className='noGuidanceExpanded';
			}
			else
			{
				div.className='guidanceExpanded';	//when guidance present		
				guidanceFrame.className='guidanceExpanded';
			}				
				
		}
		else if(guidanceCookie=='hide')
		{										
			div.className='guidanceCollapse';
			guidanceFrame.className='guidanceCollapse';
			img.src='/images/FLGuidance_LightBlue.gif';					
		}
	}
	else //if cookie null
	{	
		DeleteCookie(contentPageModuleName);	
		SetCookie(contentPageModuleName,"hide");					
		div.className='guidanceCollapse';
		guidanceFrame.className='guidanceCollapse';					
		img.src='/images/FLGuidance_LightBlue.gif';	
	}	
	div.style.top = guidanceFrame.style.top;
	div.style.left = guidanceFrame.style.left;
	guidanceFrame.style.display="";
	img.setAttribute("title","Click to show/hide guidance");
	img.style.cursor="pointer";	
}

function CheckIfNoGuidancePresent()
{			
	return;
	var guidancePresent=false;	
	var span=document.getElementById(noGuidanceControlName);		
	var guidancePanel=document.getElementById(guidancePanelControl);	
	var stringToSearch='No guidance available for this page';	
	if(span==null)
		return false;
		
	if(IsBrowserIE)
	{				
		if(span.innerText==stringToSearch)
			guidancePresent=true;						
		//guidancePanel.style.display="";			
	}
	
	if(IsBrowserNetscape)
	{
		if(span.textContent==stringToSearch)
			guidancePresent=true;					
		///guidancePanel.style.display="";		
	}	
	if(!guidancePresent)		
		guidancePanel.style.scrollbars
	return guidancePresent;
}

//checks if browser is internet explorer
function IsBrowserIE()
{
	var browserName=navigator.appName;
	if(browserName.toLowerCase()=="microsoft internet explorer")
		return true;
	else 
		return false;
}

//checks if browser is netscape
function IsBrowserNetscape()
{
	var browserName=navigator.appName;
	if(browserName.toLowerCase()=="netscape")
		return true;
	else 
		return false;
}

function IsBrowserSafari()
{
	var browserVersion = navigator.appVersion;
	if(browserVersion.indexOf("Safari") > -1)
		return true;
	else
		return false;
}

//Sets the position of the divs in proof reader
function SetDivPosition(position)
{	
	var moveTop=0;
	if(CheckIfNoGuidancePresent()) //if no guidance present, guidance control expands by 40px 
		moveTop=40;
	else //if guidance present, guidance control expands by 100px
		moveTop=100;
	
	var divArray=document.getElementsByTagName('div');
	//reset position of all divs that highlights text areas in spread 
	for(var i=0; i<divArray.length;i++)
	{		
		if(divArray[i].id.length>10)
		{
			//get only div that highlights text areas in spread
			if(divArray[i].id.substring(0,10)=='secHilight')
			{			
				var offTop=divArray[i].offsetTop;				
				var currentPos=Math.ceil(offTop);				
				if(position=='maximize' && offTop>0)													
					divArray[i].style.top=(currentPos+moveTop)+"px";					
				else//when minimizing guidance control, move div up by the amount it has increased previously
					divArray[i].style.top=(currentPos-moveTop)+"px";										
			}
		}
	}
}



function DoButtonClick(buttonName, eventHandle)
{
	//the purpose of this function is to allow the enter key to 
	//point to the correct button to click.
    var key;
    
	if (!eventHandle)
	{
		//IE
		key = window.event.keyCode;
		eventHandle = window.event; 
	}
	else
	{
		//firefox
		key = eventHandle.which;
	}
	
    if (key == 13)
    {
		//Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn != null)
        {
			//If we find the button click it
			btn.click();
        }

		if (eventHandle.stopPropagation)
		{ 
			eventHandle.stopPropagation(); 
		}
		else
		{ 
			eventHandle.cancelBubble = true; 
		}

		if (eventHandle.preventDefault)
		{
			eventHandle.preventDefault();
		}
		else
		{ 
			eventHandle.returnValue = false;
		}
    }
}

//Checks whether an option has been selected when approving/unapproving a spread
function CheckSelection(id, message)
{		
	var radioSpan = document.getElementById(id).firstChild;	//because of .net span controls
	var radioName = radioSpan.name;
	var radioObjs = document.getElementsByName(radioName);
	var radioLength = radioObjs.length;
	for(var i = 0; i < radioLength; i++) 
		if(radioObjs[i].checked == true) 
			return true;
	alert(message);		
	return false;
}

var emailRecipientCount = 0;
function EnableSendmailButton(obj, sendmailButtonId)
{
	var sendmailButton = document.getElementById(sendmailButtonId);
	
	if (obj.checked)
		emailRecipientCount++;
	else
		emailRecipientCount--;
		
	if (emailRecipientCount < 1) 
		sendmailButton.disabled = true;
	else
		sendmailButton.disabled = false;
}

function ImagesAllLoaded() 
{
	for(var i=0; i<document.images.length; i++)
	{
		if(parseInt(document.images[i].style.width,10)==0)
		{
			return false;
		}
	}
	return true;
}

var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
function FixPNG()
{
	if ((version >= 5.5 && version < 7) && (document.body.filters)) 
	{
		if(!ImagesAllLoaded())
		{
			setTimeout("FixPNG()",10000);
			return;
		}
	   for(var i=0; i<document.images.length; i++)
	   {
		  var img = document.images[i];
		  var imgName = img.src.toUpperCase();
		  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		  {
			 if(IsVisible(img))
			 {
				 var imgID = (img.id) ? "id='" + img.id + "' " : "";
				 var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				 var imgStyle = "display:inline-block;" + img.style.cssText ;
				 if (img.align == "left") imgStyle = "float:left;" + imgStyle;
				 if (img.align == "right") imgStyle = "float:right;" + imgStyle;
				 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
				 var strNewHTML = "<span " + imgID + imgClass + imgTitle
				 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
				 img.outerHTML = strNewHTML;
				 i = i-1;
			 }
		  }
	   }
	}
}

function IsVisible(obj)
{
    var visible = true;
    while(obj.style.display!="none" )
    {
		if(obj.parentElement!=null)
        {
			obj=obj.parentElement;                  
            if(obj==document.body) 
            {
				return visible;
            }
        }      
   }
   return false;
}

/* *******************************************************************************************************************/
//var moveObjectsToRootArray = new Array();

//function MoveDOMSection(sourceObj)
//{
//	var targetObj = document.getElementById("temporaryPlaceHolder");
//	alert(sourceObj.outerHTML);
//	targetObj.innerHTML = sourceObj.outerHTML;
//	sourceObj.innerHTML = "";
//	
////	for(var cnt=0;cnt<moveObjectsToRootArray.length;cnt++)
////	{
////		var obj = document.getElementById(moveObjectsToRootArray[cnt]);
////		if(obj != null)
////			obj.style.display = "inline";
////	}	
//}

//function MoveObjectsToRootPageLoad(sender, args)
//{
//	for(var cnt=0;cnt<moveObjectsToRootArray.length;cnt++)
//	{
//		var obj = document.getElementById(moveObjectsToRootArray[cnt]);
//		if(obj != null)
//			MoveDOMSection(obj);
//	}
//}
/* *******************************************************************************************************************/
function CenterObject(divObjName) 
{	
	var overflowType = false;	//if position is skewed (because of overflow) we return true
	var obj = document.getElementById(divObjName);
	if(obj == null) return;
	
	var top, left;
	var height;
	var width;
	
	if (window.innerHeight)
	{	
		height = parseInt(obj.style.height);
		width = parseInt(obj.style.width);
		
		top = Math.round((window.innerHeight/2) - (height/2) + window.scrollY);
		left = Math.round((window.innerWidth/2) - (width/2) + window.scrollX);
	}  
	else if (document.body.clientHeight)
	{
		height = obj.style.pixelHeight;
		width = obj.style.pixelWidth;
		
		top = Math.ceil((document.body.clientHeight - height)/2) + document.body.scrollTop; //alert("top: "+top);
		left = Math.ceil((document.body.clientWidth - width)/2) + document.body.scrollLeft; //alert("left: "+left);
	}
	
	obj.style.top = top+"px"; 
	obj.style.left = left+"px"; 
	
	
	//now we have set the position of the object. Any overflow issues to compensate for?
	var absLeft = GetAbsoluteLeftUsingStyle(obj); 
	if(absLeft == 0 && left > 0) absLeft = left;
	if(absLeft != left && absLeft != 0)
		overflowType = true;
	obj.style.left = (left - (absLeft - left)) + "px";
	var absTop = GetAbsoluteTopUsingStyle(obj); 
	if(absTop == 0 && top > 0) absTop = top;
	obj.style.top = (top - (absTop - top)) + "px"; 
	return overflowType;
}

function Showdeadcenterdiv(xWidth,yHeight,divid) {
	// First, determine how much the visitor has scrolled

	var scrolledX, scrolledY;
	if( self.pageYOffset ) {
	scrolledX = self.pageXOffset;
	scrolledY = self.pageYOffset;
	} else if( document.documentElement && document.documentElement.scrollTop ) {
	scrolledX = document.documentElement.scrollLeft;
	scrolledY = document.documentElement.scrollTop;
	} else if( document.body ) {
	scrolledX = document.body.scrollLeft;
	scrolledY = document.body.scrollTop;
	}

	// Next, determine the coordinates of the center of browser's window

	var centerX, centerY;
	if( self.innerHeight ) {
	centerX = self.innerWidth;
	centerY = self.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) {
	centerX = document.documentElement.clientWidth;
	centerY = document.documentElement.clientHeight;
	} else if( document.body ) {
	centerX = document.body.clientWidth;
	centerY = document.body.clientHeight;
	}

	// xWidth is the width of the div, yHeight is the height of the
	// div passed as arguments to the function:
	var leftOffset = scrolledX + (centerX - xWidth) / 2;
	var topOffset = scrolledY + (centerY - yHeight) / 2;
	// The initial width and height of the div can be set in the
	// style sheet with display:none; divid is passed as an argument to // the function
	var o=document.getElementById(divid);
	var r=o.style;
	r.position='absolute';
	r.top = topOffset + 'px';
	r.left = leftOffset + 'px';
	r.display = "block";
} 

function CenterAndResizeOnBrowser(centerObjId,resizeObjId)
{
	var maxX, addx;
	var maxY, addy;
	if (browser.isIE)
	{
		maxX = document.body.offsetWidth;
		maxY = document.body.offsetHeight-100;
		addy = document.body.scrollTop; addx = document.body.scrollLeft; 
	}
	if (browser.isNS)
	{
		maxX = window.innerWidth;
		maxY = window.innerHeight-100;
		addy = window.scrollY; addx = window.scrollX; 
	}
	var centerObj = document.getElementById(centerObjId);
	var resizeObj = document.getElementById(resizeObjId);
	
	var objWidth = (0.8 * maxX);
	var objHeight = (0.8 * maxY+10);
	if (resizeObj != null)
	{
		resizeObj.style.width = objWidth + "px";
		resizeObj.style.height = objHeight + "px";
	}
	
	if(centerObj != null)
	{
		centerObj.style.left = ((maxX/2) - (objWidth/2)) + addx + "px";
		centerObj.style.top = ((maxY/2) -	(objHeight/2)) + addy + "px";
	}
}


function Scrolling(movedDivId, toMoveDivId) 
{
	var toMoveDiv = document.getElementById(toMoveDivId);			
	var movedDiv = document.getElementById(movedDivId);
	toMoveDiv.scrollLeft = movedDiv.scrollLeft;
}

function SetCursorToTextEnd(textControlID)
{
    var text = document.getElementById(textControlID);
    if (text != null )
    {
        if (text.createTextRange)
        {
            var FieldRange = text.createTextRange();
            FieldRange.moveStart('character', text.value.length);
            FieldRange.collapse();
            FieldRange.select();
        }
    }
}

function SendAndClose( selectedFileId, selectedFolderId, selectedAssetIdPlaceHolderId )
{
	if ( selectedFileId != null && selectedFolderId != null )
	{
		if(IsBrowserIE())
		{
			window.dialogArguments.fileId = selectedFileId;
			window.dialogArguments.folderId = selectedFolderId;
			//window.parent.opener.FileSelected(selectedFolderId, selectedFileId);
			window.returnValue=true;
			window.close();
		}
		else // FireFox
		{
			var query = window.parent.location.search;
			var p1 = query.indexOf("selectedAssetIdPlaceHolderId");
			if(p1 > 0)
			{
				p1 = p1 + "selectedAssetIdPlaceHolderId=".length;
				var tmpSelectedAssetIdPlaceHolderId = "";
				var p2 = query.indexOf("&", p1);
				if(p2 < 0) 
					tmpSelectedAssetIdPlaceHolderId = query.substring(p1);
				else
					tmpSelectedAssetIdPlaceHolderId = query.substring(p1,p2);
			}
			window.parent.opener.FileSelected(selectedFolderId, selectedFileId, tmpSelectedAssetIdPlaceHolderId);
		}
	}
}

function SelectedAssetFile()
{
	var fileId;
	var folderId;
}

function ConfirmAndOpenSelectAssetDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder, confirmChange, confirmChangeMessage)
{
	var openDialog = false;
	if (confirmChange == "True")
		openDialog = ConfirmationPrompt(confirmChangeMessage);
	else
		openDialog = true;
	if (openDialog)
		OpenSelectAssetDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder);
}

function OpenSelectAssetDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder)
{
	var popUpWidth = 0.8 * screen.availWidth;
	if(popUpWidth < minPopUpWidth)
		popUpWidth	 = minPopUpWidth
		
	var popUpHeight = 0.8 * screen.height;
	if(popUpHeight < minPopUpHeight)
		popUpHeight = minPopUpHeight;
	if(IsBrowserIE())
	{
		if(wnd.showModalDialog(dlgURL,SelectedAssetFile,"dialogHeight:" + popUpHeight + "px;dialogWidth:" + popUpWidth + "px;") == true)
//			window.open(dlgURL,'name','height= '+ popUpHeight +'px,width=' + popUpWidth + 'px,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes ,modal=yes');
		{
			FileSelected(SelectedAssetFile.folderId, SelectedAssetFile.fileId, selectedFileAndFolderIdHolder)
		}
	}
	else // FireFox
	{
		assetWindowFirefox = window.open(dlgURL,'name','height= '+ popUpHeight +'px,width=' + popUpWidth + 'px,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes ,modal=yes');	
	}
}


var assetWindowFirefox = null;

function FileSelected(selectedFolderId, selectedFileId, selectedAssetIdPlaceHolderId)
{
	//Update the select asset file control
	var folderAndFileHiddenObj = document.getElementById(selectedAssetIdPlaceHolderId);
	folderAndFileHiddenObj.value = selectedFolderId + "," + selectedFileId;
	__doPostBack(folderAndFileHiddenObj.id);
	if(!IsBrowserIE())
		setTimeout("DelayedFirefoxClose()",2000);
}

function DelayedFirefoxClose()
{
	if(assetWindowFirefox != null)
		assetWindowFirefox.close();
}
/*************************************************************************/

function Preview(fileUploadobj, imageObjId, textboxId) 
{
	var file = fileUploadobj.value   	
	var imageObj = document.getElementById(imageObjId);			
   	
	if (fileUploadobj.value.length<=0 || imageObj == null) return;

	var i = file.lastIndexOf(".");			
	if(i < 0)	return;
	var extension = file.substring(i, file.length+1);
	var basePath = "/images/icons/files/16x16_";
	
	switch(extension)
	{
		case".doc":
			imageObj.src = basePath + "doc.gif";
			break;
		case".pdf":
			imageObj.src = basePath + "pdf.gif";
			break;
		case".xls":
			imageObj.src = basePath + "xls.gif";
			break;
		case".txt":
			imageObj.src = basePath + "txt.gif";
			break;
		case".zip":
		case".rar":
			imageObj.src = basePath + "zip.gif";
			break;
		case".png":
		case".gif": 
		case".tiff":
		case".tif": 
		case".jpg":
		case".jpe":
		case".jpeg": 
		case".bmp":
			imageObj.src = basePath + "jpg.gif";
			break;
		default:
			imageObj.src = basePath + "undefined.gif";
			break;			
	}
	
	var i = file.lastIndexOf("\\");
	if(i > -1)
	{
	    var fileName = file.substring(i+1, file.length);	
	    var filesHF = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_FilesHiddenField"); 
	    if(filesHF != null)
	        filesHF.value += fileName + "|" ;
	}
}
/*************************************************************************/
function printPage()
{
	var prtContent = document.getElementById("form1");
	var WinPrint = window.open('', '', 'left=350,top=30,width=600,height=842,status=0,scrollbars=1');
	WinPrint.document.write('<HTML>');
	WinPrint.document.write('<HEAD>');
	WinPrint.document.write('<link type="text/css" rel="stylesheet" href="/include/style_print_1.aspx" media="print,screen"/>');
	WinPrint.document.write('</HEAD>');		
	WinPrint.document.write('<body>');
	WinPrint.document.write( prtContent.innerHTML);
	WinPrint.document.write('</body>');
	WinPrint.document.write('</HTML>');
	WinPrint.document.close();
	WinPrint.focus();
	WinPrint.print();
	WinPrint.close();
}

function verifyPrint()
{	
	var url = window.location;
	var printRegex = "Signatur/Activity/Overview.aspx";
	var printRegex2 = "Signatur/Activity/Overview.aspx";
	var queryResult = url.toString().search(printRegex);
	var queryResult2 = url.toString().search(printRegex2);
	
	if( queryResult != -1 || queryResult2 != -1)
		overviewPrint();
	else
		window.print();
}

function overviewPrint()
{	
	var WinOpen = window.open();
	WinOpen.document.writeln('<HTML><HEAD><title>Print Preview</title><LINK href="/include/print.aspx"  type="text/css" rel="stylesheet">')
	WinOpen.document.writeln('<LINK href="/include/print.aspx"  type="text/css" rel="stylesheet" media="print"><base target="_self"></HEAD>')
	WinOpen.document.writeln('<body MS_POSITIONING="GridLayout" bottomMargin="0" leftMargin="0" topMargin="0" rightMargin="0">');
	WinOpen.document.writeln('<form  method="post">');
	WinOpen.document.writeln('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right><INPUT ID="PRINT" class="buttonPrint" type="button" value="Print" onclick="javascript:location.reload(true);window.print();"><INPUT ID="CLOSE" class="buttonPrint" type="button" value="Close" onclick="window.close();"></TD></TR><TR><TD></TD></TR></TABLE>');
	WinOpen.document.writeln(document.getElementById("mainDiv").innerHTML);
	WinOpen.document.writeln('</form></body></HTML>');		
}

function getPrint()
{	
	var WinOpen = window.open();
	WinOpen.document.write('<HTML><HEAD><title>Print Preview</title>')
	WinOpen.document.write('<LINK href="/include/style_print_1.aspx"  type="text/css" rel="stylesheet" media="print,screen"><base target="_self"></HEAD>')
	WinOpen.document.write('<body MS_POSITIONING="GridLayout" bottomMargin="0" leftMargin="0" topMargin="0" rightMargin="0">');
	WinOpen.document.write('<form  method="post">');
	WinOpen.document.write('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right><INPUT ID="PRINT" class="button noprint" type="button" value="Print" onclick="javascript:location.reload(true);window.print();"><INPUT ID="CLOSE" type="button" value="Close" class="button" onclick="window.close();"></TD></TR><TR><TD></TD></TR></TABLE>');
	WinOpen.document.write(document.getElementById("mainDiv").innerHTML);
	WinOpen.document.write('</form></body></HTML>');			
}
/*********************************Signatur****************************************/
function CheckMaxCharacters(textboxId, maxCharacters, warningImageId)
{
	var textboxObj = document.getElementById(textboxId);
	if(textboxObj != null)
	{
		var warningImageObj = document.getElementById(warningImageId);
		if(warningImageObj != null)
		{
			if(textboxObj.value.length > maxCharacters)
			{
				var excess = textboxObj.value.length - maxCharacters;
				warningImageObj.title = excess + " tegn flere end tilladt!";
				warningImageObj.style.display = "block";
			}
			else
			{
				warningImageObj.style.display = "none";
			}
		}
	}
}

function UnCheckRadioButtons(radioId, templateDivId)
{
	var radioObj = document.getElementById(radioId);
	var templateDiv = document.getElementById(templateDivId);
	if(typeof(templateHasBeenSelected) == "undefined" || templateHasBeenSelected == false) 
	{
		if(radioObj != null)
		{
			var radioButtCount = radioObj.getElementsByTagName('tr')[0].getElementsByTagName('td').length;
			for(var i = 0 ; i < radioButtCount ; i++)
			{
				var radioButt = radioId + "_" + i;
				var radioButtObj = document.getElementById(radioButt);
				
				if(radioButtObj.checked == true && radioButtObj !=null )
					radioButtObj.checked = false;
			}
		}
		if(templateDiv != null)
			templateDiv.style.display = "none"; 
	}
}

function toggleGenericWithCookie(name, id, imageId, blockImageSrc, noneImageSrc) 
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	var image = document.getElementById(imageId);
	if( obj.style.display == "none") 
	{
		obj.style.display = "";
		var tBodyCookie = GetCookie(name);
		DeleteCookie(name);
		if (image != null)
			image.src = blockImageSrc;
	}
	else
	{
		obj.style.display = "none";
		SetCookie(name,id);
		if (image != null)
			image.src = noneImageSrc; 
	}
}

function toggleList(tBodyId, imageId, blockImageSrc, noneImageSrc)
{
	if(tBodyId=="") return;
	var obj = document.getElementById(tBodyId);
	if( obj == null ) return;
	var image = document.getElementById(imageId);
	
	if(obj.style.display == "")
	{
		obj.style.display = "none";
		if (image != null)
			image.src = noneImageSrc; 
	}
	else
	{
		obj.style.display = "";
		if (image != null)
			image.src = blockImageSrc;
	}
}

function Annotation(annotationId, annotationImageIconId, annotDivId, annotationImgId, textareaId)
{
	this.Id = annotationId;
	this.ImageIconId = annotationImageIconId;
	this.DivId = annotDivId;
	this.ImageId = annotationImgId;
	this.TextAreaId = textareaId;
}

function ToggleMediaSection(name, id, imageId, blockImageSrc, noneImageSrc, enableCookie) 
{
	var obj = document.getElementById(id);
	if(obj == null) return;
	var image = document.getElementById(imageId);
	if( obj.style.display == "none") 
	{
		obj.style.display = "";
		if(enableCookie)
			SetCookie(name);
		if (image != null)
			image.src = blockImageSrc;
	}
	else
	{
		obj.style.display = "none";
		if(enableCookie)
			DeleteCookie(name);
		if (image != null)
			image.src = noneImageSrc; 
	}
}

function SetMediaSectionFromCookie(tBodyId, imageId, blockImageSrc, noneImageSrc)
{
	if(tBodyId=="") return;
	var obj = document.getElementById(tBodyId);
	if( obj == null ) return;
	var image = document.getElementById(imageId);
	
	var tBodyCookie = GetCookie(tBodyId);
	if(tBodyCookie != null)
	{
		obj.style.display = "";
		if (image != null)
			image.src = blockImageSrc; 
	}
	else
	{
		obj.style.display = "none";
		if (image != null)
			image.src = noneImageSrc;
	}
}

var _lastClickedId = "";
function clickLink(obj) 
{
	__doPostBack(obj.id.replace(/_/g, "$"),'');
}

function CheckForFileUploadAutoSubmit(fileUploadId, attachLinkId, waitForActionId, waitForActionInnerId)
{
	var fileUploadObj = $get(fileUploadId);
	var attachLinkObj = $get(attachLinkId);
	var waitForActionObj = $get(waitForActionId);
	var waitForActionInnerObj = $get(waitForActionInnerId);

	waitForActionObj.style.display = 'block';
	ShowDeadCenterDivObj(71,71,waitForActionInnerObj);	

	clickLink(attachLinkObj);
	
	return true;
}

function ShowDeadCenterDivObj(xWidth, yHeight, divObj)
{
	var scrolledX, scrolledY;
	var centerX, centerY;
	
	if( self.pageYOffset )
	{
		scrolledX = self.pageXOffset;
		scrolledY = self.pageYOffset;
	}
	else if( document.documentElement && document.documentElement.scrollTop )
	{
		scrolledX = document.documentElement.scrollLeft;
		scrolledY = document.documentElement.scrollTop;
	}
	else if( document.body ) 
	{
		scrolledX = document.body.scrollLeft;
		scrolledY = document.body.scrollTop;
	}

	if( self.innerHeight )
	{
		centerX = self.innerWidth;
		centerY = self.innerHeight;
	}
	else if( document.documentElement && document.documentElement.clientHeight )
	{
		centerX = document.documentElement.clientWidth;
		centerY = document.documentElement.clientHeight;
	}
	else if( document.body )
	{
		centerX = document.body.clientWidth;
		centerY = document.body.clientHeight;
	}

	var leftOffset = scrolledX + (centerX - xWidth) / 2;
	var topOffset = scrolledY + (centerY - yHeight) / 2;
	var divObjStyle=divObj.style;

	divObjStyle.position = 'absolute';
	divObjStyle.top = topOffset + 'px';
	divObjStyle.left = leftOffset + 'px';
	divObjStyle.display = "block";
} 

function WaitForActionStart(waitForActionDivId)
{
	$get(waitForActionDivId).style.display = 'block';
}

function OnSigTextBoxChange(textBoxId, divId)
{
	var textBox = document.getElementById(textBoxId);
	var div = document.getElementById(divId);
	
	if (textBox != null && div != null)
	{
		div.innerHTML = FixHtmlForOutput(textBox.value);
		
		if (div.innerHTML == '')
		{
			div.innerHTML = '-';
		}
	}
}

function OnSigDropDownListChange(dropDownId, divId)
{
	var dropDown = document.getElementById(dropDownId);
	var div = document.getElementById(divId);
	
	if (dropDown != null && div != null)
	{
		if (dropDown.selectedIndex >= 0)
		{
			div.innerHTML = dropDown.options[dropDown.selectedIndex].text;
		}
		else
		{
			div.innerHTML = '-';
		}
	}
}

function OnSigCheckBoxChange(checkBoxId, divId, checkedText, uncheckedText)
{
	var checkBox = document.getElementById(checkBoxId);
	var div = document.getElementById(divId);
	
	if (checkBox != null && div != null)
	{
		if (checkBox.checked)
		{
			div.innerHTML = checkedText;
		}
		else
		{
			div.innerHTML = uncheckedText;
		}
	}
}

function FixHtmlForOutput(value)
{
	var valueFixed = value.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br/>').replace(/\r\n/g, '<br/>');
	return valueFixed;
}

function ShowHideRows(rowsName, show)
{
	var rows = document.getElementsByName(rowsName);
	var row = document.getElementById(rowsName);
	
	if (rows != null)
	{
		if (show == 1)
		{
			for(var n=0; n < rows.length; n++)
			{
				rows[n].style.display = "";
			}
		}
		else
		{
			for(var n=0; n < rows.length; n++)
			{
				rows[n].style.display = "none";
			}
		}
	}

	if (row != null)
	{
		if (show == 1)
			row.style.display = "";
		else
			row.style.display = "none";
	}
}

function ClearTextBoxOnDropDownSelected(dropDownId, textBoxId)
{
	var dropDown = document.getElementById(dropDownId);
	var textBox = document.getElementById(textBoxId);
	
	if (dropDown != null && textBox != null)
	{
		if (dropDown.selectedIndex > 0)
		{
			textBox.value = "";
		}
	}
}

function ClearDropDownSelectedOnTextBoxChanged(textBoxId, dropDownId)
{
	var textBox = document.getElementById(textBoxId);
	var dropDown = document.getElementById(dropDownId);
	
	if (dropDown != null && textBox != null)
	{
		if (dropDown.selectedIndex > 0 && Trim(textBox.value) != "")
		{
			dropDown.selectedIndex = 0;
		}
	}
}

function Trim(stringToTrim)
{
	return stringToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function SetFocusControl(controlId, selectTextIfTextBox)
{
	var control = document.getElementById(controlId);

	if (control != null)
	{
		try 
			{
				control.scrollIntoView(false);
			} 
		catch(e) { }						

		try 
			{
				control.focus();
			} 
		catch(e) { }	
		
		if (control.type == "text")
		{
			if (selectTextIfTextBox)
			{
				control.selectionStart = 0;
				control.selectionEnd = control.value.length;
			}
			else
			{
				control.selectionStart = 0;
				control.selectionEnd = 0;
			}
		}
	}
}

function fakeRepeaterCheckBoxClick(repeaterCheckBoxId, fakeRoleCheckBoxButtonId, fakeCheckBoxResultId, repeaterCheckBoxIdentifierText)
{
	var repeaterCheckBox = document.getElementById(repeaterCheckBoxId);
	var fakeRoleCheckBoxButton = document.getElementById(fakeRoleCheckBoxButtonId);
	var fakeCheckBoxResult = document.getElementById(fakeCheckBoxResultId);

	if (repeaterCheckBox != null && fakeRoleCheckBoxButton != null && fakeCheckBoxResult != null)
	{	
		if (repeaterCheckBox.checked)
		{
			fakeCheckBoxResult.value = repeaterCheckBoxIdentifierText + "_1";
		}
		else
		{
			fakeCheckBoxResult.value = repeaterCheckBoxIdentifierText + "_0";
		}

		fakeRoleCheckBoxButton.click();
	}
}

function showCheckedItems(checkBoxList, textbox, noneText)
{
	var elementRef = document.getElementById(checkBoxList);
	var checkBoxArray = elementRef.getElementsByTagName('input');
	var controlText = document.getElementById(textbox);
	var checkedValues = '';
	var labelArray= '';
	
	for (var i=0; i<checkBoxArray.length; i++) 
	{
		var checkBoxRef = checkBoxArray[i];

		if (checkBoxRef.checked == true)
			labelArray = checkBoxRef.parentNode.getElementsByTagName('label');
		else
			labelArray = '';
			
		if (labelArray.length > 0)
		{
			if (checkedValues.length > 0)
				checkedValues += ', ';

			checkedValues += '[' + labelArray[0].innerHTML + ']';  	
		}	
	}

	if (checkedValues == "")
		checkedValues = noneText;

	if (IsBrowserIE())
		controlText.innerText = checkedValues;
	else
		controlText.textContent = checkedValues;
}

function ConfirmTwoDifferentValues(objId1, objId2, message)
{
	var obj1 = document.getElementById(objId1);
	var obj2 = document.getElementById(objId2);

	if (obj1 != null && obj2 != null && obj1.value != obj2.value)
		return confirm(message);
	else
		return true;
}

