﻿var STYLEMARKER = "¤";
var adBuilderMode = false;
var fullscreen_currentMode = "";
var mozilla = document.getElementById && !document.all;
var postBackElementId = "";

String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

//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, folderId) 
{
	var url = "/GroupControls/SelectUsers.aspx?seltype=" + selectiontype + "&ctrlId=" + ctrlToClickOnComplete + "&folderId=" + folderId;
	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";
}

//*************** user administration **********************
function onUserSelectionChange(dropdownuserid,dropdownclientid)
{
	var userDropdown = document.getElementById(dropdownuserid);
	if(!userDropdown) return;
	var clientDropdown = document.getElementById(dropdownclientid);
	if(!clientDropdown) return;
	var value = userDropdown.value;
	if(value!=20) //20 is value of client
	{
		clientDropdown.value = -1;
	}
}

var userRelationNotclientAlert = "";
function onClientSelectionChange(userdropdown, clientdropdown) 
{
	var user = document.getElementById(userdropdown);
	var client = document.getElementById(clientdropdown);
	if(user != null && client != null ) 
	{
		var val = user.value;
		if(val != 20)
		{
			alert(userRelationNotclientAlert);
			client.value = -1;
		}
	}
	else return;
}
//******************************************************************************************//
//*****************************************************************************************************************************
//	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(obj) 
{
	var ObjectToToggle = document.getElementById(obj);
	if (ObjectToToggle == null)
		return;
	
	if( ObjectToToggle.style.display == "none") 
		ObjectToToggle.style.display = "block";
	else
		ObjectToToggle.style.display = "none";	
}

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)
		{
			try {
			setTimeout("waitForImageToLoad(" + showHideSectionsCheckBoxId + "," + showDifMapCheckBoxId + "," + showHideAnnotationsCheckBoxId + "," + showHideModifiedCheckBoxId + ")",10);
			} catch(e) {}
		}
		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);
}

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(typeof(divModified) != "undefined")
	{
		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;
	if(typeof(annotIds) != "undefined")
	{
		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;

				var left = ((annotationsPositions[annotcnt].x1 * scaleX) + imgoffsetx);
				imgobj.style.left = left + "px";
				var top = ((annotationsPositions[annotcnt].y1 * scaleY) + imgoffsety);
				imgobj.style.top = top + "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";
				annotationDiv.style.left = (left + 15) + "px";
				annotationDiv.style.top = (top + 15) + "px";
			} 
		}
	}
}
var corDivsHandled = 0;
var corDivsTotal = -1;

function PositionAndScaleObjectsStruct(objs,divName,visibility,offsetX,offsetY,factorX,factorY,editIconName){
	this.objs = objs;
	this.divName = divName;
	this.visibility = visibility;
	this.offsetX = offsetX;
	this.offsetY = offsetY;
	this.factorX = factorX;
	this.factorY = factorY;
	this.editIconName = editIconName;
}
var psObjParams = null;
function PositionAndScaleObjects(objs, divName, visibility, offsetX, offsetY, factorX, factorY, editIconName)
{
	//alert(corDivsHandled);
//	if(typeof(objs) == "undefined")
//	{
//		objs = psObjParams.objs;
//		divName = psObjParams.divName;
//		visibility = psObjParams.visibility;
//		offsetX = psObjParams.offsetX;
//		offsetY = psObjParams.offsetY;
//		factorX = psObjParams.factorX;
//		factorY = psObjParams.factorY;
//		editIconName = psObjParams.editIconName;
//	} else {
//		psObjParams = new PositionAndScaleObjectsStruct(objs, divName, visibility, offsetX, offsetY, factorX, factorY, editIconName)
//		alert(psObjParams.divName);
//	}
	if(objs.length == 0) return;
	
	var working = true;
	var cnt = corDivsHandled;
	var itemsProcessedInLoop = 0;
	var imgWidth = previewImgObj.width;
	var imgHeight = previewImgObj.height;
	var showEditIcon = ShowHideItemGetValue( document.getElementById("ctl00_mainContent_showHideSpreadSections_fullScreen_showHideSections") );
	while(working) {
		var obj = objs[cnt];
		if(obj == null) { working = false; break; }
		var divobj = document.getElementById(divName + cnt);
		if( divobj != null )
		{
			//found the div, now reposition
			var newx = Math.round(obj.x1 * factorX);
			var newy = Math.round(obj.y1 * factorY);
			divobj.style.left = (newx + offsetX) + "px";
			divobj.style.top = (newy + offsetY) + "px";
			var newwidth = Math.ceil((obj.x2 - obj.x1)*factorX);
			divobj.style.width  = newwidth + "px";
			//clip right edge
			var newHeight = Math.abs(Math.ceil((obj.y2 - obj.y1)*factorY));
			divobj.style.height = newHeight + "px";
			//position corresponding editIcon accordingly
			if(editIconName != null) 
			{
				var editIcon = document.getElementById(editIconName + cnt);
				if(editIcon!=null)
				{
					editIcon.style.left = (newx + newwidth + 10) + "px";
					editIcon.style.top = (newy + offsetY - 10) + "px";
					if(showEditIcon)
						editIcon.style.display = "inline";
					else
						editIcon.style.display = "none";
				}
			}
		} else {
			working = false;
		}
		cnt++;
	}
}

//This is an optimizer helper for it's equivalent method ShowHideItem
function ShowHideItemGetValue(checkboxObj, obj)
{
	if(checkboxObj != null )
	{
		if(fullscreen_currentMode == "Normal") //normal mode, show/hide item depending on checkbox value
		{
			if(checkboxObj.checked)
				return false;
			else	
				return true;	
		}
		else //compare mode, hide item
			return false;	//obj.style.display = "none";
	}
	else
	{
		return true;	//obj.style.display = "inline";
	}
}

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 = new Object();
var originalSectionTextContentsStyleArrayCount = new Object();
var lastButtonSaveToCheckId = null;

//Receives normal DOM object
function CheckTextChange(textareaObj)
{
	if(lastButtonSaveToCheckId == null) 
		return;
	var tval = pk_fixnewlines_textarea(textareaObj.value);
	var origNew = pk_fixnewlines_textarea(originalSectionTextContents[textareaObj.id]);

	var okButton = $get(lastButtonSaveToCheckId);
	if(okButton != null) 
		SetButtonDisabled(okButton, origNew != tval)
}

//changes the classname to buttondisabled or button depending of value
function SetButtonDisabled(buttonObj, enable)
{
	var button = $(buttonObj);
	if(enable)
	{
		button[0].disabled = false;
		button.attr("className", "button");
	}
	else
	{
		button[0].disabled = true;
		button.attr("className", "buttondisabled");
	}
	
}

function checkStyles(textAreaId, warningDivId, saveTextChangesButtonId) 
{
	var textareaObj = $("#" + textAreaId);
	var warningDivObj = $("#" + warningDivId);
	var textEditorEnabled = typeof(useRichTextEditor) != "undefined" && useRichTextEditor ? true : false;
	lastButtonSaveToCheckId = saveTextChangesButtonId;

    var styleArray = textareaObj.val().split(STYLEMARKER);
    
    if(textEditorEnabled)
    {
        if(tinyMCE.isGecko)
            styleArray = tinyMCE.getContent().split("&curren;");
	    else
	        styleArray = tinyMCE.getContent().split(STYLEMARKER);
	}
	var showWarningDiv = false;
	if( originalSectionTextContentsStyleArrayCount[textAreaId] != (styleArray.length) )
	{
	    if(textEditorEnabled)
	    {
	        tinyMCE.setContent(curSectionTextContents[textAreaId]);
	    }
	    else
	    {
		    var scrollY = textareaObj.scrollTop();
		    var domTextareaObj =textareaObj[0];	//get non-jquery object
		    var curCursorPos = GetCursorPosition(domTextareaObj);
		    textareaObj.val(curSectionTextContents[textAreaId]);
		    setCaretPosition(domTextareaObj, curCursorPos);
		    textareaObj.scrollTop(scrollY);
		}
		showWarningDiv = true;
		FixPNG();
	} 
	//disabled/enabled save button if contents is different.
	CheckTextChange(textareaObj[0]);//pass in non jquery obj.
	
	//check if ignore term warning present
	var ignoreTermCheckBox = $(".ignoreSaveWarning > input");
	if(ignoreTermCheckBox.length == 0)
	{
		//if checkbox is not visible, then reset value	
//		if(!showWarningDiv) 
//			curSectionTextContents[textAreaId] = textEditorEnabled ? tinyMCE.getContent() : textareaObj.val();
	}
	if(!showWarningDiv) 
		curSectionTextContents[textAreaId] = textEditorEnabled ? tinyMCE.getContent() : textareaObj.val();

	if(!showWarningDiv) 
		return;
	//restore text
	//textareaObj.val(originalSectionTextContents[textAreaId]);
	textareaObj.val(curSectionTextContents[textAreaId]);
	//position the div area correctly
	var tx = textareaObj.position().left;
	var ty = textareaObj.position().top;
	var addy = 10;
	var scrolloverflowdiv = $get("overflowYSpecial");
	if(scrolloverflowdiv!= null)
	{
		//var scrolly = scrolloverflowdiv.scrollTop;
		//ty -= scrolly;
	}
	var newx = (textareaObj.width() - warningDivObj.width()) / 2 + tx;
	warningDivObj.css( { top: (ty + addy), left: newx } );	
	warningDivObj.show();
}

function CheckStylesPre()
{
	setTimeout("eval(checkStyles(tmp_textareaId, tmp_warningdivId, tmp_saveTextChangesButtonId))", 200);
	//checkStyles(tmp_textareaId, tmp_warningdivId, tmp_saveTextChangesButtonId);
}

function BindHandlersForPasteRebind(textareaObj)
{
	var ta = $get("ctl00_mainContent_textCorrectionDiv");
	if(ta == null) return;
	if(!mozilla)
		ta.onpaste = CheckStylesPre;
	else
		ta.addEventListener("paste", CheckStylesPre, true);
}

var tmp_textareaId, tmp_warningdivId, tmp_saveTextChangesButtonId;
function BindHandlersForPaste(textareaId, warningDivId, saveTextChangesButtonId)
{
	var ta = $get(textareaId);
	if(ta == null) return;
	
	tmp_textareaId = textareaId; tmp_warningdivId = warningDivId; tmp_saveTextChangesButtonId = saveTextChangesButtonId;
	if(!mozilla)
	{
		ta.onpaste = CheckStylesPre;
	}
	else
		ta.addEventListener("paste", CheckStylesPre, true);
}

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 = new Array();

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;
	try {
	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	= "";
	} catch (e) {}
	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)
	{
		if(postBackElementId.indexOf("checkTerm") > 0) 
		{
			CheckTextChange(textareaObj);
			return;
		}
		//check if ignore term warning present
		var ignoreTermCheckBox = $(".ignoreSaveWarning > input");
		if(ignoreTermCheckBox.length > 0)
		{
			//if checkbox is visible, then don't reset value
			return;
		}
		originalSectionTextContents[textboxName] = textareaObj.value;
		originalSectionTextContentsStyleArrayCount[textboxName] = originalSectionTextContents[textboxName].split(STYLEMARKER).length;
		curSectionTextContents[textboxName] = originalSectionTextContents[textboxName];
	}
}

function GetStylesControlCodeCountForEditor(textboxId, styleMarkerSpan)
{
    originalSectionTextContents[textboxId] = tinyMCE.getContent();
    originalSectionTextContentsStyleArrayCount[textboxId] = originalSectionTextContents[textboxId].split(styleMarkerSpan).length;
    curSectionTextContents[textboxId] = originalSectionTextContents[textboxId];
}

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_');
	AnnotationsToggle();
	if (obj.checked)
	{
		ShowHideCorrectionDiv('annotationDiv_',false);
		ShowHideCorrectionDiv('annotContents_',false);
		ResetAnnoIcons();
	}
	clearAllDrawnLines();
}

function 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 closeEditWindow(id)
{
	toggleGeneric(id);
	UnHighlightDiv();
}

var _lastClickedId = "";
function clickLink(obj) 
{
	if(mozilla)
	{
		return;
//		if(_lastClickedId == obj.id) return;
//		_lastClickedId = obj.id;
//		if(obj.onclick != null)
//		{
//			//signature:
//			//	function onclick(event) { ... }
//			//replace onclick with local name, invoke name. that's it
//			var method = obj.onclick.toString();
//			if(method.toLowerCase().indexOf("confirm") > -1) { alert("ERROR: ClickLink for FF does not support confirm!"); return }

//			method = method.replace("onclick(event)", "_localClick()");
//			//strip away the { } and other stuff
//			method = method.replace("javascript:","");
//			//method = method.replace("return
//			method = method.trim();
//			//now start method by invoking the new method
//			method = "_localClick(); " + method;
//			setTimeout(method, 0);
//			setTimeout("ClearLastClickedId()",400);
//		}
////		var evt = document.createEvent("MouseEvents");
////		evt.initEvent("click", true, true); 
////		obj.dispatchEvent(evt);
//		if(obj.onclick.toLower().indexOf("return false") > -1) return;
//		if(obj.onclick.toLower().indexOf("return(false)") > -1) return;
//		document.location = obj.href;
//		//if page is in async, then register for endrequest event so we can clear the lastclicked variable
//		if(Sys.WebForms == undefined) return;
//		var tmp_prm = Sys.WebForms.PageRequestManager.getInstance();
//		tmp_prm.add_endRequest( eval("_lastClickedId = ''" ));		
	}
	else
		obj.click();
}

function ClearLastClickedId()
{
	_lastClickedId = "";
}

function doClick(divObj, repeaterName) {
	var textCorrDiv = document.getElementById("ctl00_mainContent_textCorrectionDiv");
	if((textCorrDiv!=null) && previousActiveHighlightDiv != null && (divObj.id == previousActiveHighlightDiv.id) && (textCorrDiv.style.display=="block"))
	{
		UnHighlightDiv();
		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)
{
	BindHandlersForPasteRebind();
	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 set, then dont reposition textframe
	if(typeof("textCorrectionDivFixedPosition") != "undefined" && textCorrectionDivFixedPosition)	
	{
		textCorrDiv.style.display = "block";
		return;
	}
	var scrolledX=0, scrolledY=0;
	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 (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 + scrolledY ) //if panel goes out of window, position it on top of div area
	{
		newy = (windowHeight+scrolledY) - 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 + scrolledX) 
	{
		newX = parseInt((clientW + scrolledX)-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 = null;
var app = null;
var updatingElementId; //holds the element being updated

function pageLoad( )
{
	if(!hasBeenSet)
	{
		if(Sys.WebForms == undefined) return;
		prm = Sys.WebForms.PageRequestManager.getInstance( );
		prm.add_pageLoaded( PageLoadedHandler );
		//prm.add_pageLoaded( MoveObjectsToRootPageLoad );
		prm.add_beginRequest( BeginRequestHandler );
		prm.add_endRequest( EndRequestHandler );
		if(Sys.Application == undefined) return;
		app = Sys.Application;
	}
	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";
		updatingElementId = imageInfoFilterId;
  
    //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 )
{
	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 );
		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();
} 

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,hastext) 
{
	this.x1 = x1;
	this.y1 = y1;
	this.x2 = x2;
	this.y2 = y2;
	this.hasText = hastext;
}

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 = $get(id);
	if(obj == null) return;
	if( obj.style.display == "none") 
        obj.style.display = "block";
	else
		obj.style.display = "none";
}

function moveOutAndHide(id)
{
	var obj = $get(id);
	if(obj == null) return;
	obj.style.left = "-400px";
	toggleGeneric(id);
}

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("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 );
    }
	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 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);
	}
}

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;
}

//checks if browser is internet explorer
function IsBrowserIE()
{
	var browserName=navigator.appName;
	if(browserName.toLowerCase()=="microsoft internet explorer")
		return true;
	else 
		return false;
}

function IsBrowserChrome()
{
	var browserName=navigator.userAgent;
	if(browserName.toLowerCase().indexOf("safari") > 0 || browserName.toLowerCase().indexOf("chrome") > 0)
		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,e)
{
	//the purpose of this function is to allow the enter key to 
	//point to the correct button to click.
    var key;

    if(window.event)
		key = window.event.keyCode;     //IE
    else       
		key = e.which;     //firefox
    
    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();
			CancelEvent(e);
        }
    }
}

function CancelEvent(e)
{
	if (browser.isIE || $.browser.safari)
	{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	else
	{
		e.preventDefault();
	}
}

function RedirectAndCancelEvent(newUrl, e)
{
	CancelEvent(e);	
	window.location = newUrl;
	
	return 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 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);
	if(toMoveDiv != null && movedDiv != null)
		toMoveDiv.scrollLeft = movedDiv.scrollLeft;
}

function ScrollingVert(movedDivId, toMoveDivId) 
{
	var toMoveDiv = document.getElementById(toMoveDivId);			
	var movedDiv = document.getElementById(movedDivId);
	if(toMoveDiv != null && movedDiv != null)
		toMoveDiv.scrollTop = movedDiv.scrollTop;
}

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,cropValuesHolderId )
{
	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
		{
			if(cropValuesHolderId != null) 
			{
				var cropData=  window.parent.opener.document.getElementById(cropValuesHolderId);
				cropData.value="";
            }
                
			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;
	var cropValuesHolderId;
}

//userType can be SAUser or FLUser
function ConfirmAndOpenSelectAssetDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder, confirmChange, confirmChangeMessage,cropValuesHolderId, userType, guidvalue)
{
	var openDialog = false;
	if (confirmChange == "True")
		openDialog = ConfirmationPrompt(confirmChangeMessage);
	else
		openDialog = true;
	if (openDialog)
		OpenSelectAssetDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder,cropValuesHolderId,userType);
}

var tmp_productDbModified = "";
var _productDbModified = false;

function OpenSelectAssetDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder,cropValuesHolderId, userType)
{
	var showSmallPopUp = false;
	if(userType.toString() == "SAUser")
		showSmallPopUp = true;
	if(showSmallPopUp)
	{
		var popUpWidth = 640;
		var popUpHeight = 640;
	}
	else
	{
		var popUpWidth = 0.99 * screen.availWidth;
		if(popUpWidth < minPopUpWidth)
			popUpWidth	 = minPopUpWidth
			
		var popUpHeight = 0.99 * screen.height;
		if(popUpHeight < minPopUpHeight)
			popUpHeight = minPopUpHeight;
	}
	tmp_productDbModified = _productDbModified;
	_productDbModified = false;
	var left = (screen.availWidth - popUpWidth) / 2;
	var top = (screen.height - popUpHeight) / 2;
	if(IsBrowserIE())
	{
	    SelectedAssetFile.cropValuesHolderId=cropValuesHolderId;
		if(wnd.showModalDialog(dlgURL,SelectedAssetFile,"dialogHeight:" + popUpHeight + "px;dialogWidth:" + popUpWidth + "px;") == true)
		{

			var cropValuesHolder =  document.getElementById(SelectedAssetFile.cropValuesHolderId);
            if(cropValuesHolder != null)
                cropValuesHolder.value = "";
        
			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,left=' + left + ',top=' + top);	
	}
}

function CroppedImageData()
{
	var xCord;
	var yCord;
	var width;
	var height;
	var conversionRatio;
	var sRatio;
	var cropImageWidth;
	var cropImageHeight;
}

function ConfirmAndOpenCropImageDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder, confirmChange, confirmChangeMessage, cropValuesHolderId)
{
	var openDialog = false;
	if (confirmChange == "True")
		openDialog = ConfirmationPrompt(confirmChangeMessage);
	else
		openDialog = true;
	if (openDialog)
		OpenCropImageDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder, cropValuesHolderId);
}

function OpenCropImageDialog(wnd, minPopUpWidth, minPopUpHeight, dlgURL, selectedFileAndFolderIdHolder, cropValuesHolderId)
{
	popUpWidth	 = minPopUpWidth
	popUpHeight = minPopUpHeight;

	tmp_productDbModified = _productDbModified;
	_productDbModified = false;

	if(IsBrowserIE())
	{
		if(wnd.showModalDialog(dlgURL,CroppedImageData,"dialogHeight:" + popUpHeight + "px;dialogWidth:" + popUpWidth + "px;scroll:no;status:no;resizable:no;center:yes") == true)
		{
            SetCropImageValues(CroppedImageData.xCord,CroppedImageData.yCord,CroppedImageData.width,CroppedImageData.height,cropValuesHolderId,CroppedImageData.conversionRatio,CroppedImageData.sRatio, CroppedImageData.cropImageWidth, CroppedImageData.cropImageHeight);
		}
	}
	else // FireFox
	{
		assetWindowFirefox = window.open(dlgURL,'name','height= '+ popUpHeight +'px,width=' + popUpWidth + 'px,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes,screenX=250,screenY=250');	
	}
	return false;
}

function  cropClosePopUpFromMain(x,y,width,height,cropvaluesholderid,conversionRatio,sRatio, cropImageWidth, cropImageHeight)
{
    SetCropImageValues(x,y,width,height,cropvaluesholderid,conversionRatio,sRatio, cropImageWidth, cropImageHeight);
        
	if(typeof(_productDbModified) != "undefined")
		setTimeout("RestoreProductDbModifiedValue()", 1000);

     if(!IsBrowserIE())
         setTimeout("DelayedFirefoxClose()",2000);  
}

function SetCropImageValues(x,y,width,height,cropvaluesholderid,conversionRatio,sRatio, cropImageWidth, cropImageHeight)
{
    var cropValuesHolder =  document.getElementById(cropvaluesholderid);
    if(cropValuesHolder != null)
    {
        cropValuesHolder.value = "<CropData><X>" + x+"</X><Y>"+y+"</Y><Width>"+width+"</Width><Height>"+height+"</Height><ResizeRatio>"+conversionRatio+"</ResizeRatio><AspectRatio>"+sRatio + "</AspectRatio><CropImageWidth>"+cropImageWidth+"</CropImageWidth><CropImageHeight>" + cropImageHeight + "</CropImageHeight></CropData>";
    }
    __doPostBack(cropvaluesholderid);
}

var assetWindowFirefox = null;

function FileSelected(selectedFolderId, selectedFileId, selectedAssetIdPlaceHolderId)
{
	//Update the select asset file control
	var folderAndFileHiddenObj = document.getElementById(selectedAssetIdPlaceHolderId);
	folderAndFileHiddenObj.value = selectedFolderId + "," + selectedFileId;
	//adbuilder setdirty check
	if(typeof(SetDirty) == "function")
		SetDirty(selectedAssetIdPlaceHolderId);

	__doPostBack(folderAndFileHiddenObj.id);
	
	if(typeof(_productDbModified) != "undefined")
		setTimeout("RestoreProductDbModifiedValue()", 1000);

	if(!IsBrowserIE())
		setTimeout("DelayedFirefoxClose()",2000);
}

function RestoreProductDbModifiedValue()
{
	_productDbModified = tmp_productDbModified;
}

function DelayedFirefoxClose()
{
	if(assetWindowFirefox != null)
		assetWindowFirefox.close();
}

/**********************************************************/
 function updateLabelOnTextChanged(textboxId, labelId)
{
    var textbox = document.getElementById(textboxId);
    var label = document.getElementById(labelId);
    label.innerHTML = textbox.value
}
/*************************************************************************/
function AttachFile()
{
	var indexHF = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_indexHiddenField");
	var removeDivIdHF = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_removeDivIdHiddenField");		
	if(indexHF == null || removeDivIdHF == null) return;
	if(indexHF.value == "")
		var index = 1;
	else
		var index = indexHF.value;

	var prevFileUploadObj = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_fileupload_" + (parseInt(index,10)-1).toString()); 
	
	if(prevFileUploadObj != null)
	if(prevFileUploadObj.value.length<=0)
	{
		alert("No image yet selected");
		return;
	}
	
	if(removeDivIdHF.value == "")
	{
		var divObj = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_contentRow_" + index);
	}
	else
	{
		var splitRemoveHF = removeDivIdHF.value.split(',');	
		if(splitRemoveHF[0] != "")
		{
			var divObj = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_contentRow_" + splitRemoveHF[0]);			
			removeDivIdHF.value = removeDivIdHF.value.replace(splitRemoveHF[0]+",", "")	
		}
	}
	
	var attachFileLink = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_AddMoreFilesLink");
	
	if(divObj != null)
	{
		divObj.style.display = "";
		index++;
		indexHF.value = index;
		
		if(attachFileLink != null)
		{
			if(index >= 10)
				attachFileLink.disabled = true;
		}
	}
}

function RemoveFile(divId)
{
	var indexHF = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_indexHiddenField");
	if(indexHF == null) return;
	
	if(indexHF.value == "")
		var index = 0;
	else
		var index = indexHF.value;
		
	var divObj = document.getElementById(divId);
	var j = divId.lastIndexOf("_");

	if(j < 0) return;
	
    var removeDivId = divId.substring(j+1, divId.length);
	
	var removeDivIdHF = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_removeDivIdHiddenField");		
	
	if (divObj != null) 
	{
		if(removeDivIdHF != null)
			removeDivIdHF.value += removeDivId + ",";
		
		divObj.style.display = "none";
		index--;
		indexHF.value = index;
		
		var attachMoreFiles = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_AddMoreFilesLink");
		if(attachMoreFiles != null)
			attachMoreFiles.disabled = false
		
			
		var fileUploadObj = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_fileupload_" + removeDivId);
    	var filesHF = document.getElementById("ctl00_mainContent_UploadMultipleFilesControl_FilesHiddenField"); 
    	if(fileUploadObj == null && filesHF == null) return;
    	
    	var path = 	fileUploadObj.value;
    	if(path.length >= 0)
    	{
    	    var i = path.lastIndexOf("\\");				
    	    if(i > -1)
    	    {
    	        var fileName = path.substring(i+1, path.length);
    	        var removeFileName = fileName + "|";
    	        filesHF.value = filesHF.value.replace(removeFileName, "");
    	    }
    	}
	}
}

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 Annotation(annotationId, annotationImageIconId, annotDivId, annotationImgId, textareaId)
{
	this.Id = annotationId;
	this.ImageIconId = annotationImageIconId;
	this.DivId = annotDivId;
	this.ImageId = annotationImgId;
	this.TextAreaId = textareaId;
}

	
/*************************************************************************/
function print()
{
	var prtContent = document.getElementById("mainDiv");
	var WinPrint = window.open('', '', 'left=350,top=30,width=600,height=842,status=0');
	WinPrint.document.write('<HTML>');
	WinPrint.document.write('<HEAD>');
	WinPrint.document.write('<link type="text/css" rel="stylesheet" href="/include/style_print_1.css" 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 GetRadioButtonListSelectedValue(id)
{
	var radioObj = document.getElementById(id);
	if(radioObj != null)
	{
		var radioButtCount = radioObj.getElementsByTagName('tr')[0].getElementsByTagName('td').length;
		for(var i = 0 ; i < radioButtCount ; i++)
		{
			var radioButt = id + "_" + i;
			var radioButtObj = document.getElementById(radioButt);
			if( radioButtObj !=null && radioButtObj.checked == true )
				return radioButtObj.value;
		}
	}
}

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
	if(topOffset<0) topOffset = 0;
	var o=document.getElementById(divid);
	var r=o.style;
	r.position='absolute';
	r.top = topOffset + 'px';
	r.left = leftOffset + 'px';
	r.display = "block";
} 

function Border(obj)
{
	if(obj.className.indexOf("border") > 0)
		obj.className = obj.className.substring(0,obj.className.indexOf("border"));
	else
		obj.className += "border";
}	

//aligns browser textarea input to be the same across platform and browser.
function pk_fixnewlines_textarea (val) {             
  // Adjust newlines so can do correct character counting for MySQL. MySQL counts a newline as 2 characters.
  if (val.indexOf('\r\n')!=-1); // this is IE on windows. Puts both characters for a newline, just what MySQL does. No need to alter
  else if (val.indexOf('\r')!=-1)
	val = val.replace ( /\r/g, "\r\n" );        // this is IE on a Mac. Need to add the line feed
  else if (val.indexOf('\n')!=-1)
	val = val.replace ( /\n/g, "\r\n" );        // this is Firefox on any platform. Need to add carriage return
  else 
	;                                           // no newlines in the textarea  
  return val;
}

//*****************
var maintainScrollArray = new Array();
function MaintainScrollPosition(objId, pageRequestManager)
{
	this.ObjId = objId;
	this.ScrollTop = 0;
	this.ScrollLeft = 0;
	if(!hasBeenSet) pageLoad();
}
function _InitScrollPosition() 
{
	for(var n=0;n<maintainScrollArray.length;n++)
	{
		var obj = $get(maintainScrollArray[n].ObjId);
		maintainScrollArray[n].ScrollTop = obj.scrollTop;
	}
}
function _RestoreScrollPosition() 
{
	for(var n=0;n<maintainScrollArray.length;n++)
	{
		var obj = $get(maintainScrollArray[n].ObjId);
		obj.scrollTop = maintainScrollArray[n].ScrollTop;
	}
}
MaintainScrollPosition.prototype.InitScrollPosition = _InitScrollPosition;
MaintainScrollPosition.prototype.RestoreScrollPosition = _RestoreScrollPosition;
//*****************
var lastOptionObj = null;
function ClickRowAndSetHiddenValue(objClicked, idToStore, idOfHiddenVariabe)
{
	if(lastOptionObj != null) 
	{
		toggleClassName(lastOptionObj, "popupRowSelected", "");
	}
	toggleClassName(objClicked, "popupRowSelected", "");
	lastOptionObj = objClicked;
	
	//update the hidden variable
	$("#" + idOfHiddenVariabe).val(idToStore);
}
///**********************************************************
var DomObjectController = {
		Objects : new Array(),
		AjaxAlreadyBound : false,
		
		AddObject : function(objId) {
			DomObjectController.BindAjaxPostBack();
			DomObjectController.Objects.push(new DomObject(objId, null, null) );
		},
		
		StoreProperties : function()
		{
			for(var n=0;n<DomObjectController.Objects.length;n++)
			{
				var jObj = $("#" + DomObjectController.Objects[n].Id);
				//alert("obj: " + DomObjectController.Objects[n].Id + ", found: " + jObj.length + ", scrollPos=" + jObj.scrollTop());
				if(jObj.length == 0) 
					continue;
				DomObjectController.Objects[n].ScrollPos = jObj.scrollTop();
				DomObjectController.Objects[n].Height = jObj.height()+2;
			}
		},
		
		RestoreProperties : function() 
		{
			for(var n=0;n<DomObjectController.Objects.length;n++)
			{
				var jObj = $("#" + DomObjectController.Objects[n].Id);
				//alert("obj: " + DomObjectController.Objects[n].Id + ", found: " + jObj.length + ", scrollPos=" + DomObjectController.Objects[n].ScrollPos);
				if(jObj.length == 0) 
					continue;
				jObj.scrollTop(DomObjectController.Objects[n].ScrollPos);
				jObj.height( DomObjectController.Objects[n].Height );
			}			
		},
		
		BindAjaxPostBack : function ()
		{
			if(prm == null || DomObjectController.AjaxAlreadyBound) 
				return;
			prm.add_endRequest(DomObjectController.AjaxEndRequest);
			prm.add_beginRequest(DomObjectController.AjaxBeginRequest);
			DomObjectController.AjaxAlreadyBound = true;
		},
		
		AjaxBeginRequest : function()
		{
			DomObjectController.StoreProperties();
		},

		AjaxEndRequest : function()
		{
			DomObjectController.RestoreProperties();
		}
	}

	function DomObject(objId, scrollPos, height)
	{
		this.Id = objId;
		this.ScrollPos = scrollPos;
	}

function SetFocusControl(controlId, selectTextIfTextBox)
{
	var control = document.getElementById(controlId);

	if (control != null)
	{
		try 
		{
			control.scrollIntoView(false);jaq
		} 
		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 OnStandardTextBoxChange(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 OnStandardDropDownListChange(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 FixHtmlForOutput(value)
{
	var valueFixed = value.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br/>').replace(/\r\n/g, '<br/>');
	return valueFixed;
}

//**********************************************************************************************