//WE USE foo TO REFER TO THE EDITABLE AREA OF THE SITE EDITOR 
//initialImages is an array that will get populated at the time of loading
//It will contain the list of images that is present at the loading time
var initialImages;
var finalImages;
var finalCount;
global_reload = false
global_addnew=false;
//source Array is used to keep track of the resources images/flash objects
//referenced inside the foo.document that is initially loaded.  This is populated 
//by the method loadAfter() by reading in images,embeds object arrays.
//This array will be used at the time of saving,deleting,saveas processes. 
source = new Array();
//This function is called at the time of loading
//It sets the location of foo and turns on the designmode of mshtml editor 
//we call the reload function to get the latest copy of the page in the editable area.
//then we moveon to call the loadAfter() method after 200 ms.  
function loading()
{
	//foo.location.href=document.all("pageurl").value;
	//alert(document.all("pageurl").value);
	/*
	var fso, f;
	fso = new ActiveXObject("Scripting.FileSystemObject");
	f = fso.OpenTextFile(document.all("pageurl").value, 1);
	var test123 = f.ReadAll();
	f.Close();
	alert(test123);
	alert(document.all("pageurl").value+"...");
	tinyMCE.get("ajaxfilemanager").setContent(document.all("pageurl").value);
	
	//tinyMCE.get('ajaxfilemanager').getContent();
	*/
	//tinyMCE.activeEditor.setContent('asfdasdfasda');
	/*
	foo.document.designMode = 'On';
	if(global_reload == true) {
		global_reload=false;
	}
	foo.location.reload();
	*/
	window.setTimeout("loadAfter()",200);
}
//loadAfter() method is called initially by the loading() method.
//It checks for the readystate of the document inside foo every 200 ms till it is set 'complete'.
//Once it is complete it sets focus to the foo.
//(i) 	It takes the images array from foo.document
//		Then it loops through the array and check for images starting with "ug","sg","sl".
//		Upon finding such images we insert the imagename into 'source' array.
//(ii)	It takes the embeds array from foo.document.
//			Then it loops through the array and check for embed objects starting with "fl"
//			Upon finding such objects we insert the objectname into 'source' array.
//(iii)	We set the popup menu by calling the onContextmenu of foo.document from which we call the 
//		goContext() method. The goContext() is responsible for displaying the formatted
//		popup menu in the clicked location
//(iv)	If the page inside foo is a guestbook, we set the value code inside the span "guestbook_span"
//		to an image "images/3.jpg".  Since it may generate an error for non-guestbook pages we have
//		written that inside a try..catch  block.	
function loadAfter() {
    //alert(tinyMCE.get('ajaxfilemanager').getContent());
	if(foo.document.readyState != "complete") {
		window.setTimeout("loadAfter()",200);
		return;
	}
	foo.focus();
	initialImages = foo.document.images;
	var initCount=initialImages.length;
	var strTemp="";
	for(i=0;i<initCount;i++) {
		strTemp=initialImages[i].src;
		strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
		var strTemp2=strTemp.substr(0,2);
		if(strTemp2 == "ug" || strTemp2 == "sg" || strTemp2 == "sl") {
			source.push(strTemp);	
		}
	}
	initialEmbeds = foo.document.embeds;
	initCount = initialEmbeds.length;
	for(i=0;i<initCount;i++) {
		strTemp=initialEmbeds[i].src;
		strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
		if(strTemp.substr(0,2) == "fl") {
			source.push(strTemp);	
		}
	}
	foo.document.onkeypress =goDelete;
	foo.document.onkeydown =goDelete1;
	foo.document.oncontextmenu = function(){
			    if (!foo.event.ctrlKey){
			     goContext();
			     return false;
			    }
			   }
                           alert(document.getElementById("guestbook_span").innerHTML);
	try{		   
	foo.document.getElementById("guestbook_span").innerHTML = "<img src=\"" + document.all("basiclocation").value + "/images/3.jpg\">";
        
	}
	catch(e){}
}

function goDelete1(evt){
//delete by click delete
	if(foo.document.selection.type !="None"){
	  if(foo.event.keyCode=="46"){
	    var oSel = foo.document.selection.createRange(); 
		oSel.text="";
	  }
	  
	
	}
}
function goDelete(evt){
//delete by click d
	if(foo.document.selection.type !="None"){
	  if(foo.event.keyCode=="100"){
	    var oSel = foo.document.selection.createRange(); 
		oSel.text="";
	  }
	  return false;
	
	}


}
//This function is called multiple times for executing commands on foo.
//It first checks for SelMode.  IF SelMode == 2 then we alert the user that he is permitted  
//to do this only in design mode.  Also showHtml() function is called that takes the user to 
//design mode. 
function changeFont(tFont) {
	try{
		if (SelMode == 2) {
			document.all("showhtml").checked=false;
			ShowHtml();
			foo.focus();
			alert('Please use this option in the design mode.');
			return false;
		}
	}catch(e){} 
	foo.document.execCommand(tFont);
	foo.focus();	
}
//called from formatbar.inc(shortcutmenu) when user changes the font
function doFont(t) {
	foo.document.execCommand('FontName',false,t[t.selectedIndex].value);
	foo.focus();
	t.selectedIndex=0;
}
	//size changing
//called from formatbar.inc(shortcutmenu) when user changes the size 	
	function doSize(t) {
		foo.document.execCommand('FontSize',true,t[t.selectedIndex].value);
		foo.focus();
		t.selectedIndex=0;
	}
	
	var Mode = "1";
	//called from editor.php
	//used to set the height of the editable area
	function setHeight() {
		//height = 119
		height = 5
		
		if (Mode == 2)
		{ 
			height = 87
		}
		return (document.body.clientHeight-height)
	}
	//called from formatbar.inc
	//sets the appearance of the buttons in the shortcutmenu on mousedown	
	function button_down(eButton){
		eButton.style.borderBottom = "buttonhighlight solid 1px";
		eButton.style.borderLeft = "buttonshadow solid 1px";
		eButton.style.borderRight = "buttonhighlight solid 1px";
		eButton.style.borderTop = "buttonshadow solid 1px";
	}
	//called from formatbar.inc
	//sets the appearance of the buttons in the shortcutmenu on mouseover	
	function button_over(eButton){
		if (eButton.style.borderBottom != "buttonhighlight 1px solid")
		{
		eButton.style.borderBottom = "buttonshadow solid 1px";
		eButton.style.borderLeft = "buttonhighlight solid 1px";
		eButton.style.borderRight = "buttonshadow solid 1px";
		eButton.style.borderTop = "buttonhighlight solid 1px";
		}
	}
	//called from formatbar.inc
	//sets the appearance of the buttons in the shortcutmenu on mouseout	
	function button_out2(eButton){
		if (eButton.style.borderBottom != "buttonhighlight 1px solid")
		{
		eButton.style.borderColor = "threedface";
		}
		eButton.style.borderColor = "threedface";
	}
	//called from formatbar.inc
	//sets the appearance of the buttons in the shortcutmenu on mouseout	
	function button_out(eButton){
		eButton.style.borderColor = "threedface";
	}
	var SlectedColor = null;
	//changes the font color/highlights the selected text
	//decides to change the font color or to highlight the selected text based on input parameter
	//IF colorType == 1 then 
	//	change font color of the selected text 
	//ELSE IF colorType == 2 then
	//	highlight the selected text
	//END IF	
	function changefontcolor(colorType){
		try{
		          if(colorType == 1){
		   			SeletedRange = foo.document.selection.createRange();
									
				   if(SeletedRange.queryCommandValue('ForeColor')){
				   		// SlectedColor = foo.queryCommandValue('ForeColor').toString(16);
							 SlectedColor = SeletedRange.queryCommandValue('ForeColor').toString(16);
							
							while(SlectedColor.length < 6)
						     SlectedColor = '0' + SlectedColor;
						    SlectedColor = SlectedColor.substr(4) + SlectedColor.substr(2, 2) + SlectedColor.substr(0, 2);
						   }
		           }
					
				  if(SlectedColor == null)
				   var Callcolordialog = colordialog.ChooseColorDlg();
				  else
				   var Callcolordialog = colordialog.ChooseColorDlg(SlectedColor);

  				  Callcolordialog = Callcolordialog.toString(16);
				  if (Callcolordialog.length < 6) {
				   var Temp = "000000".substr(0,6-Callcolordialog.length);
				   Callcolordialog = Temp.concat(Callcolordialog);
				  }
 
				  Command = (colorType == 2) ? 'BackColor' : 'ForeColor';
				  foo.document.execCommand(Command, false, Callcolordialog);
				  SlectedColor = Callcolordialog;
		}
		catch(e) {alert(e);}
  
 	}

 //New
 //Create a table in foo
 //function called from menu and shortcutmenu
 //(i)	checked for SelMode
 //		IF SelMode == 2 then user alerted that table insertion can be done only in design mode
 //		showHtml() called to take the user to the design mode
 //(ii)	tblpro.php is called with arguments cellPadding & cellSpacing set to 1
 //		The return values from the tblpro.php is set to res.
 //		using foo.document.createElement() we create a table element and
 //		set the outerHtml of the created element the new html table string constructed based on the
 //		return values from the tblpro.php page.
 function Createtable(){
	 try{
		 try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
			}
		}catch(e){} 
		foo.focus();
	 TbObj = new Object();
	  TbObj.cellPadding = 1;
	  TbObj.cellSpacing = 2;
		 res = showModalDialog('tblpro.php', TbObj, 'dialogWidth: 336px; dialogHeight: 216px; center: yes; resizable: no; scroll: no; status: no;');
		 if(res){
		   foo.focus();
		   SelParent = foo.document.selection.createRange().parentElement();
		   NewTable = foo.document.createElement('<table>');
		   SelParent.appendChild(NewTable);
		   if(res.width=="" && res.width <10)
		     res.width=100;
		   //HTMLTable = "<table" + (res.width ? ' width=' + res.width : '') + " border=" + res.border + " cellpadding=" + res.cellPadding + " cellspacing=" + res.cellSpacing + (res.bgColor ? ' bgcolor = ' + res.bgColor : '') + (res.background ? ' background=' + res.background : '') + ">";        
		   StrNewTable = "<table width=" + res.width + "  border=" + res.border + " cellpadding=" + res.cellPadding + " cellspacing=" + res.cellSpacing + ' bgcolor = ' + res.bgColor + ">";        
		   for(i=0; i<res.rows; i++){
		    StrNewTable = StrNewTable + "<tr>";
		    for(j=0; j<res.columns; j++)
		     StrNewTable = StrNewTable + "<td>&nbsp;</td>"
		    StrNewTable = StrNewTable + "</tr>"
		   }       			
		   StrNewTable = StrNewTable + "</table>"
		   NewTable.outerHTML = StrNewTable;
		 }  
	 }
	 catch(e){}
 }
 
 //called in table operations like adding a new row,new column etc. 
 //checks if the selection is inside a table cell
 //(i)	returns true if inside a table cell and assigns values for PointedTD,PointedTR,
 //		PointedTBODY,PointedTable
 //(ii)	returns false if not inside a table cell , alert the user to place the cursor 
 //		inside a table cell 
 function CheckcursorIsinTableCell(){
     foo.focus();

	if(document.selection.type != "Control"){
	  
	           var pointedElem = document.selection.createRange().parentElement();
			   while(pointedElem.tagName.toUpperCase() != "TD" && pointedElem.tagName.toUpperCase() != "TH"){
			    pointedElem = pointedElem.parentElement
			    if(pointedElem == null)
			     break
			   }
			   
			   if(pointedElem){
					    PointedTD = pointedElem
					    PointedTR = PointedTD.parentElement
					    PointedTBODY =  PointedTR.parentElement
					    PointedTable = PointedTBODY.parentElement
					    return true
			   }else{
			    alert("Please place the cursor inside the table cell");
				return false;
			   }	
	  }
	  
 }
//Insert Column Left
//Checks if the cursor is inside a table cell using CheckcursorIsinTableCell().
//Once the function CheckcursorIsinTableCell() is called we get 
//	PointedTD,PointedTR,PointedTBODY,PointedTable variables inside the calling function
//IF true then
//	we insert a blank column to the left of the selected cell
//END IF
 function InsertColumbefore(){
   
		 if (CheckcursorIsinTableCell()){
		   Movecolumn = (PointedTR.cells.length-1) - (PointedTD.cellIndex)
		   TotalRows = PointedTable.rows
		   for(i=0;i<TotalRows.length;i++){
		    rowCount = TotalRows[i].cells.length - 1
		    WheretoInsert = rowCount - Movecolumn
		    if(WheretoInsert < 0)
		     WheretoInsert = 0
		    newCell = TotalRows[i].insertCell(WheretoInsert)
		    newCell.innerHTML = " "
		   }	
		  }
 }
//Insert Column Right
//Checks if the cursor is inside a table cell using CheckcursorIsinTableCell().
//Once the function CheckcursorIsinTableCell() is called we get 
//	PointedTD,PointedTR,PointedTBODY,PointedTable variables inside the calling function
//IF true then
//	we insert a blank column to the right of the selected cell
//END IF
function InsertColumafter(){
   
		 if (CheckcursorIsinTableCell()){
		   Movecolumn = (PointedTR.cells.length-1) - (PointedTD.cellIndex + 1)
		   TotalRows = PointedTable.rows
		   for(i=0;i<TotalRows.length;i++){
		    rowCount = TotalRows[i].cells.length - 1
		    WheretoInsert = rowCount - Movecolumn 
		    if(WheretoInsert < 0)
		     WheretoInsert = 0
		    newCell = TotalRows[i].insertCell(WheretoInsert)
		    newCell.innerHTML = " "
		   }	
		  }
 }
 //Insert Row Above
//Checks if the cursor is inside a table cell using CheckcursorIsinTableCell().
//Once the function CheckcursorIsinTableCell() is called we get 
//	PointedTD,PointedTR,PointedTBODY,PointedTable variables inside the calling function
//IF true then
//	we insert a blank row to the top of the selected cell
//END IF
 function InsertRowbefore(){
  if(CheckcursorIsinTableCell()){
   var TotCols = 0
   TotRows = PointedTR.cells
   for(var i=0;i<TotRows.length;i++) 
    TotCols = TotCols + TotRows[i].getAttribute('colSpan')
   var Newtablerow = PointedTable.insertRow(PointedTR.rowIndex)
   for(i = 0; i < TotCols; i++){
    Newtablecolumn = Newtablerow.insertCell()
    Newtablecolumn.innerHTML = " "
   }
  }	
 }
 //Insert Row Below
//Checks if the cursor is inside a table cell using CheckcursorIsinTableCell().
//Once the function CheckcursorIsinTableCell() is called we get 
//	PointedTD,PointedTR,PointedTBODY,PointedTable variables inside the calling function
//IF true then
//	we insert a blank row to the bottom of the selected cell
//END IF
function InsertRowafter(){
  if(CheckcursorIsinTableCell()){
   var TotCols = 0
   TotRows = PointedTR.cells
   for(var i=0;i<TotRows.length;i++) 
    TotCols = TotCols + TotRows[i].getAttribute('colSpan')
   var Newtablerow = PointedTable.insertRow(PointedTR.rowIndex + 1)
   for(i = 0; i < TotCols; i++){
    Newtablecolumn = Newtablerow.insertCell()
    Newtablecolumn.innerHTML = " "
   }
  }	
 }

//Delete Row
//Checks if the cursor is inside a table cell using CheckcursorIsinTableCell().
//Once the function CheckcursorIsinTableCell() is called we get 
//	PointedTD,PointedTR,PointedTBODY,PointedTable variables inside the calling function
//IF true then
//	deletes the row of the selected cell
//END IF
function DeleteRow(){
  if(CheckcursorIsinTableCell())
   PointedTable.deleteRow(PointedTR.rowIndex)
 }
//Delete Column
//Checks if the cursor is inside a table cell using CheckcursorIsinTableCell().
//Once the function CheckcursorIsinTableCell() is called we get 
//	PointedTD,PointedTR,PointedTBODY,PointedTable variables inside the calling function
//IF true then
//	deletes the column of the selected cell
//END IF
 function DeleteColumn(){
  if(CheckcursorIsinTableCell()){
   Movecolumn = (PointedTR.cells.length-1) - (PointedTD.cellIndex)
   TotalRows = PointedTable.rows
   for(var i=0;i<TotalRows.length;i++){
    LastRow = TotalRows[i].cells.length - 1
    DeleteR = LastRow - Movecolumn
    if(DeleteR < 0)
     DeleteR = 0
    Totalcells = TotalRows[i].cells
    if(Totalcells[DeleteR].colSpan > 1)
     Totalcells[DeleteR].colSpan = Totalcells[DeleteR].colSpan - 1
    else
     TotalRows[i].deleteCell(DeleteR)
   }
  }
 }
 //Modify Table of menu
 //(i)	call CheckcursorIsinTableCell() to get the variable PointedTable
 //(ii)	open modifytable.php, with arguments PointedTable
 //(iii)get the user given values to res
 //		set the properties of PointedTable to the ones the user has given
 function ModifyTable(){
	
	  TbObj = new Object();
	  TbObj.cellPadding = 1;
	  TbObj.cellSpacing = 2;
	  if(CheckcursorIsinTableCell()){
	 // alert(PointedTable.rows.length);
        res = showModalDialog('modifytable.php', PointedTable, 'dialogWidth: 360px; dialogHeight: 220px; center: yes; resizable: no; scroll: no; status: no;');
 
			 if(res){
				 	try{
					    if(res.width)
					     PointedTable.width = res.width;
					    else
					     PointedTable.removeAttribute('width',0);
					}catch(e){}
					try{
					    if(res.cellPadding)
					     PointedTable.cellPadding = res.cellPadding;
					    else
					     PointedTable.removeAttribute('cellPadding',0);
					}catch(e){}
					    
					  try{
					  if(res.bgColor)
					     PointedTable.bgColor = res.bgColor;
					    else
					     PointedTable.removeAttribute('bgColor',0);
					}catch(e){}
					try{					
					    if(res.background)
					     PointedTable.background = res.background;
					    else
					     PointedTable.removeAttribute('background',0);
					}catch(e){}
					try{					
					  if(res.cellSpacing)
					     PointedTable.cellSpacing = res.cellSpacing;
					    else
					     PointedTable.removeAttribute('cellSpacing',0);
					}catch(e){}
					
					try{						 
						if(res.border)
					     PointedTable.border = res.border;
					    else
					     PointedTable.removeAttribute('border',0);
					}catch(e){}
					try{
						if(res.borderColor)
					     PointedTable.borderColor = res.borderColor;
					    else
					     PointedTable.removeAttribute('borderColor',0);
					}catch(e){}
					try{						 
					    if(res.align)
					     PointedTable.align = res.align;
					    else
					     PointedTable.removeAttribute('align',0);
					}catch(e){}
						 
					}
	}		
	
 }
 //Modify Cell of menu
 //(i)	call CheckcursorIsinTableCell() to get the variable PointedTD
 //(ii)	open modifycell.php with PointedTD as the argument
 //(iii)get the user given values to res
 //		set the user given values to PointedTD
 function ModifyCell(){
  if(CheckcursorIsinTableCell()){
   res = showModalDialog('modifycell.php', PointedTD, 'dialogWidth: 370px; dialogHeight: 250px; center: yes; resizable: no; scroll: no; status: no;');
   if(res){
    PointedTD.colSpan = res.colSpan;
    PointedTD.rowSpan = res.rowSpan;
    if(res.width)
     PointedTD.width = res.width;
    else
     PointedTD.removeAttribute('width',0);

    if(res.height)
     PointedTD.height = res.height;
    else
     PointedTD.removeAttribute('height',0);
    
    if(res.bgColor)
     PointedTD.bgColor = res.bgColor;
    else
     PointedTD.removeAttribute('bgColor',0);

    if(res.background)
     PointedTD.background = res.background;
    else
     PointedTD.removeAttribute('background',0);

		  if(res.align && !res.align.match(/^None$/i))
     PointedTD.align = res.align;
    else
     PointedTD.removeAttribute('align',0);

	  	if(res.vAlign && !res.vAlign.match(/^None$/i))
     PointedTD.vAlign = res.vAlign;
    else
     PointedTD.removeAttribute('vAlign',0);
   }
  }else{
   //alert('Please put the cursor in the cell you want to edit first.');
  }
 } 
//End Table Insertion 

//showhtml
//Function used to switch between Design view/HTML View
//IF SelMode == 1 then user is in Design mode
//IF SelMode == 2 then user is in HTML mode
//By default user is in the design mode
var SelMode=1;
 function ShowHtml() {
  if (SelMode == 1) {
   selctedrange = foo.document.selection.createRange();
   Htmltext = selctedrange.htmlText;

   foo.document.body.innerText = foo.document.documentElement.outerHTML.replace(/&amp;/g, '&');
   code = foo.document.body.innerHTML;
   code = code.replace(/(&lt;([\s\S]*?)&gt;)/gi, "<font color=#000080>$1</font>")
   code = code.replace(/(&lt;(table|tbody|th|tr|td|\/table|\/tbody|\/th|\/tr|\/td)([\s\S]*?)&gt;)/gi, "<font color=#008080>$1</font>")
   code = code.replace(/(&lt;!--([\s\S]*?)&gt;)/gi, "<font color=#808080>$1</font>")
   code = code.replace(/(&lt;img([\s\S]*?)&gt;)/gi, "<font color=#800080>$1</font>")
   code = code.replace(/(&lt;(a|\/a)([\s\S]*?)&gt;)/gi, "<font color=#008000>$1</font>")
   code = code.replace(/(&lt;(script|\/script)([\s\S]*?)&gt;)/gi,"<font color=#800000>$1</font>")
   foo.document.body.innerHTML = code;
   foo.document.body.runtimeStyle.fontFamily = "Verdana"
   foo.document.body.runtimeStyle.fontSize = "10pt"
   foo.document.body.runtimeStyle.bgColor = '#FFFFFF';
   foo.document.body.runtimeStyle.color = '#000000';
   foo.document.body.runtimeStyle.text = '#000000';
   foo.document.body.runtimeStyle.background = '';
   foo.document.body.runtimeStyle.marginTop = '10px';
   foo.document.body.runtimeStyle.marginLeft = '10px';

   Selectednewrange = foo.document.selection.createRange();
   r = foo.document.body.createTextRange();
   if(Htmltext && r.findText(Htmltext)){
    r.select();
    r.scrollIntoView();
   }

   foo.document.onkeypress = function(){
    if(foo.event.shiftKey && foo.event.keyCode == 13){
     sRange = foo.document.selection.createRange();
     sRange.text = '<BR>';
    }
   }

   SelMode = 2;
  }else{
   foo.document.body.innerHTML = foo.document.body.innerText;
   foo.document.body.runtimeStyle.cssText = "";
   foo.document.onkeypress = '';
   SelMode = 1;
  }
 }

//end showhtml

//Form Show
//Function isAllowed()
//checks if the editing operations are permitted by checking isContentEditable
//If editable it returns true
//else returns false
function isAllowed() {
		var sel
		var obj
			
			sel = foo.document.selection
			
			if (sel.type != "Control")
			{
				obj = sel.createRange().parentElement()
			} else {
				obj = sel.createRange()(0)
			}
			
			if (obj.isContentEditable) {
				return true
			} else {
				return false
			}

		return true
			
	}
//Function isCursorInForm()
//Checks if cursor is inside a form element
//Referred from modifyForm()
//returns true if cursor is inside a form
function isCursorInForm() {
		if (document.selection.type != "Control") {
                          var elem = document.selection.createRange().parentElement()
                          while (elem.tagName != "FORM")
                          {
                            elem = elem.parentElement
                            if (elem == null)
                              break
                          }
				if (elem) {
					selectedForm = elem
					return true
				}
		}
	}

//Function insertForm()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF isAllowed() == true then
//	open insertform.php to get the user values and insert a form
//END IF
function insertForm() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
			}
		}catch(e){} 
		foo.focus();
		if (isAllowed())
		{
			var leftPos = (screen.availWidth-500) / 2
			var topPos = (screen.availHeight-400) / 2 
	 		insertFormWin = window.open('insertform.php','','width=450,height=400,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}
	}

//Function modifyForm()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF isAllowed() == true AND isCursorinForm() == true then
//	open modifyForm.php which will modify the present form
//END IF
function modifyForm() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please modify form in design mode.');
				return;
			}
		}catch(e){} 
		if (isAllowed)
		{

		if (isCursorInForm()) {
			var leftPos = (screen.availWidth-500) / 2
			var topPos = (screen.availHeight-400) / 2 
	 		modifyFormWin = window.open('modifyform.php','','width=470,height=310,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

//Function doTextField()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF userSelection == CONTROL then
//	IF userSelection is a textbox control then show the user modifytextfield.php END IF
//ELSE
//	show the user inserttextfield.php
//END IF
function doTextField() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please add text field in design mode.');
				return;
			}
		}catch(e){} 
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-400) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if ((oControlRange(0).type.toUpperCase() == "TEXT") || (oControlRange(0).type.toUpperCase() == "PASSWORD")) {
					selectedTextField = foo.document.selection.createRange()(0);
					textFieldWin = window.open('modifytextfield.php','','width=440,height=320,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			textFieldWin = window.open('inserttextfield.php','','width=440,height=320,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}

//Function doTextArea()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF userSelection == CONTROL then
//	IF userSelection is a textarea control then show the user modifytextarea.php END IF
//ELSE
//	show the user inserttextarea.php
//END IF
function doTextArea() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please add textarea in design mode.');
				return;
			}
		}catch(e){} 

		if (isAllowed())
		{

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-400) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "TEXTAREA") {
					selectedTextArea = foo.document.selection.createRange()(0);
					textFieldWin = window.open('modifytextarea.php','','width=440,height=290,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				return true;
			}	
		} else {
			textFieldWin = window.open('inserttextarea.php','','width=440,height=290,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}
//Function doHidden()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF userSelection == CONTROL then
//	IF userSelection is a hidden control then show the user modifyhidden.php END IF
//ELSE
//	show the user inserthidden.php
//END IF
function doHidden() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please add hidden field in design mode.');
				return;
			}
		}catch(e){} 

		if (isAllowed())
		{

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-400) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if (oControlRange(0).type.toUpperCase() == "HIDDEN") {
					selectedHidden = foo.document.selection.createRange()(0);
					hiddenWin = window.open('modifyhidden.php','','width=500,height=250,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			hiddenWin = window.open('inserthidden.php','','width=500,height=250,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}	
//Function doButton()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF userSelection == CONTROL then
//	IF userSelection is a button control then show the user modifybutton.php END IF
//ELSE
//	show the user insertbutton.php
//END IF
function doButton() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please add button field in design mode.');
				return;
			}
		}catch(e){} 
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-400) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if ((oControlRange(0).type.toUpperCase() == "RESET") || (oControlRange(0).type.toUpperCase() == "SUBMIT") || (oControlRange(0).type.toUpperCase() == "BUTTON")) {
					selectedButton = foo.document.selection.createRange()(0);
					buttonWin = window.open('modifybutton.php','','width=500,height=280,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			buttonWin = window.open('insertbutton.php','','width=500,height=280,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}	
//Function doCheckbox()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF userSelection == CONTROL then
//	IF userSelection is a checkbox control then show the user modifycheckbox.php END IF
//ELSE
//	show the user insertcheckbox.php
//END IF
function doCheckbox() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please add checkbox field in design mode.');
				return;
			}
		}catch(e){} 
		if (isAllowed())
		{

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-400) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if (oControlRange(0).type.toUpperCase() == "CHECKBOX") {
					selectedCheckbox = foo.document.selection.createRange()(0);
					checkboxWin = window.open('modifycheckbox.php','','width=500,height=280,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			checkboxWin = window.open('insertcheckbox.php','','width=500,height=280,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}
//Function doRadio()
//if selMode == 2 user asked to go to design mode to perform the operation
//	user taken to design mode by calling showHtml().
//IF userSelection == CONTROL then
//	IF userSelection is a radiobutton control then show the user modifyradio.php END IF
//ELSE
//	show the user insertradio.php
//END IF
function doRadio() {
		try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
				foo.focus();
				alert('Please add radio field in design mode.');
				return;
			}
		}catch(e){} 
		if (isAllowed()) {

		var leftPos = (screen.availWidth-500) / 2
		var topPos = (screen.availHeight-400) / 2 

		if (foo.document.selection.type == "Control") {
			var oControlRange = foo.document.selection.createRange();
			if (oControlRange(0).tagName.toUpperCase() == "INPUT") {
				if (oControlRange(0).type.toUpperCase() == "RADIO") {
					selectedRadio = foo.document.selection.createRange()(0);
					radioWin = window.open('modifyradio.php','','width=500,height=280,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
				}
				return true;
			}	
		} else {
			radioWin = window.open('insertradio.php','','width=500,height=280,scrollbars=no,resizable=no,titlebar=0,top=' + topPos + ',left=' + leftPos);
		}

		}
	}	
//End Form Show

//Insert Link
//Function loading() called at the time of page loading 
var sUploadsList = new Array();
onload = function(){
		loading();
	}
	
//function insertInternalLink(chk)
//called at 3 locations in menu file
//insert link,insert mail link, insert anchor
//check for SelMode.  If SelMode == 2 then user alerted to go to design mode 
//	and user taken to design mode.end 
//(i)	insert link
//		chk will be 1 for link insertion to exsting pages
//		call insertinternal.php, along with type as GET parameter
//		type is the value of the element "type".
//		The return value from the page is the pagename the link should point to
//(ii)	insert mail link
//		chk will be 2 for mail link insertion
//		call insertmail.php, along with type as GET parameter
//		type is the value of the element "type".
//		The return value from the page is the mailto link
//(iii)	insert anchor link
//		chk will be 3 for link insertion to external references
//		call insertanchor.php, along with type as GET parameter
//		type is the value of the element "type".
//		The return value from the page is the external reference the link should point to
//FROM the return value of (i) or (ii) or (iii) a link is created using execCommand('CreateLink')
function insertInternalLink(chk) {
	try{
		if (SelMode == 2) {
			document.all("showhtml").checked=false;
			ShowHtml()
			foo.focus();
			alert('Please select a text or image.');
			return; 
		}
	}catch(e){} 
	
	if(foo.document.selection.type == 'None'){
   alert('Please select text or image first.');
  }else{
   sSel = new Object();
   sSel.defLinkColor = foo.document.body.link ? foo.document.body.link : '#0000ff';

   if(foo.document.selection.type == "Control"){
    var oControlRange = foo.document.selection.createRange();
    if(oControlRange(0).tagName.toUpperCase() == "IMG")
     oSel = oControlRange(0).parentNode;
   }else{
    oSel = foo.document.selection.createRange().parentElement();
   }

   sRange = foo.document.selection.createRange();

   if(sRange.queryCommandValue('ForeColor')){
    sSel.linkcolor = sRange.queryCommandValue('ForeColor').toString(16);
    while(sSel.linkcolor.length < 6)
     sSel.linkcolor = '0' + sSel.linkcolor;
    sSel.linkcolor = sSel.linkcolor.substr(4) + sSel.linkcolor.substr(2, 2) + sSel.linkcolor.substr(0, 2);
   }
   if(sRange.queryCommandState('Underline', false, null))
    sSel.linkDec = 'underline';

   if(oSel.tagName != 'A'){
    firedObj = oSel;
    while(firedObj.tagName != "BODY" && firedObj.tagName != "A")
     firedObj = firedObj.parentElement;
    if(firedObj.tagName == 'A')
     oSel = firedObj;
   }

   if(oSel.tagName == "A"){
    if(oSel.childNodes[0] && oSel.childNodes[0].tagName){
     tmpObj = oSel.childNodes[0];
     while(!tmpObj.tagName == 'FONT' && typeof(tmpObj.childNodes[0]) != 'undefined')
      tmpObj = tmpObj.childNodes[0];
     
     if(tmpObj.tagName == 'FONT' && tmpObj.outerHTML && tmpObj.outerHTML.match(/<font[^>]*onmouseover/i)){
      if(temp = tmpObj.outerHTML.match(/this\.color='#([0-9a-fA-F]*)/i))
       sSel.hovercolor = temp[0].replace(/.*'#/, '');
      if(temp = tmpObj.outerHTML.match(/textDecoration='([^']*)/i))
       sSel.hoverDec = temp[0].replace(/.*'/, '');
     }
    }

    sSel.popup = oSel.target == '_blank' ? true : false;

    if(oSel.outerHTML.match(/onclick=/ig) && oSel.onclick.match(/^open\(/)){
      sHref = oSel.onclick.replace(/^.*\/|['|"].*$/g, '');
      sSel.popup = true;
      sSel.res = oSel.onclick.replace(/^.*resizable=|;.*$/g, '');
      sSel.status = oSel.onclick.replace(/^.*status=|;.*$/g, '');
      sSel.tool = oSel.onclick.replace(/^.*toolbar=|;.*$/g, '');
      sSel.width = oSel.onclick.replace(/^.*width=|;.*$/g, '');
      sSel.height = oSel.onclick.replace(/^.*height=|;.*$/g, '');
    }else{
     sHref = unescape(oSel.href);
    }

    if(sHref.match(/@/)){
     sSel.type = 3;
     sSel.url = sHref.replace(/^mailto:( )*/ig, '');
    }else if(sHref.match(/^http:\/\/guestbook/i)){
     sSel.type = 1;
     sSel.url = sHref;
    }else if(sHref.match(/usr/ig) || !sHref.match(/http:/ig)){
     sHref = sHref.replace(/(.)*\//ig, '');
     match = false;
     for(key in sUploadsList)
      match = sUploadsList[key] == sHref;
     if(match){
      sSel.type = 4;
      sSel.url = sHref;
     }else{
      sSel.type = 1;
      sSel.url = sHref ? sHref : 'index.html';
     }
    }else{
     sSel.type = 2;
     sSel.url = sHref;
    }   
   }
   strUrlParam="?type=" + document.getElementById("type").value;
	if(chk == 1)
	{
	res=showModalDialog('insertinternal.php' + strUrlParam, null, 'dialogWidth: 280px; dialogHeight: 210px; center: yes; resizable: no; scroll: no; status: no;');
	}
	else if(chk == 2)
	{
	res=showModalDialog('insertmail.php', sSel, 'dialogWidth: 280px; dialogHeight: 210px; center: yes; resizable: no; scroll: no; status: no;');
	}
	else if(chk == 3)
	{
	res=showModalDialog('insertanchor.php', sSel, 'dialogWidth: 280px; dialogHeight: 210px; center: yes; resizable: no; scroll: no; status: no;');
	}
	if(res && res.url){
    oNewSelection = foo.document.selection.createRange();
    if(foo.document.selection.type == "Control"){
     selectedImage = foo.document.selection.createRange()(0);
     selectedImage.border = selectedImage.border ? selectedImage.border : 0;
    }

    oNewSelection.execCommand("CreateLink",false,res.url);
	}
  }

}
//End Insert Link

//insert br
//function inserttag(sTag)
//Called from menu - insert Line Break
//using pasteHTML()  we paste the <br> tag
function inserttag(sTag){
  foo.focus();
  foo.document.selection.createRange().pasteHTML("<br>");
}
//end insert br

//Special characters
//get the popup reference to the variable cPopup
//cPopup is used in the function showMenu() 
//---------var cPopup = window.createPopup();
//The div named charmenu is passed into this first argument of the function
//'charmenu' is present in the editor.php which shows special characters 
//The function displays the charmenu div in the specified location
 function showMenu(menu, width, height){
  var lefter = event.clientX ;
  var leftoff = event.offsetX;
  var topper = event.clientY;
  var topoff = event.offsetY;
  var cPopup = window.createPopup();
  var cPopBody = cPopup.document.body;
  
  var HTMLContent = eval(menu).innerHTML
  cPopBody.innerHTML = HTMLContent
  cPopup.show(lefter, topper - 80, width, height, document.body);
  
  return false;
 }
//function insertChar(oChar)
//On clicking any character on the div it invokes this function
//The innerHTML of the td of the div hich contains special characters is pasted in the selected area
function insertChar(oChar) {
	var cPopup = window.createPopup();

 // foo.focus();
  var sel = foo.document.selection;
  var rng = sel.createRange();
  rng.pasteHTML(oChar.innerHTML)
  cPopup.hide()
 }
//End special Characters

//Page Properties
//called from menu to modify page properties
//check if SelMode == 2 
//IF true then user asked to come to Design mode and taken to Design mode by calling showHtml()
//Else open page pageprop.php that will modify the page properties.
 function ModifyProperties(){
	try{
		if (SelMode == 2) {
			document.all("showhtml").checked=false;
			ShowHtml()
		}
	}catch(e){} 
  open('pageprop.php','','width=740,height=340,scrollbars=no,toolbar=0');
 }
//End PageProperties

//Insert image
//This function is called from menu.js and from the popup window of foo
//check if SelMode == 2
//(i)	IF true then user asked to come to Design mode and taken to Design mode by calling showHtml()
//(ii)	open page insertimage.php which gives the user 3 options , 
//		(a)	upload a new image(returns uploadimage.php),
//		(b)	insert from user gallery(returns usergallery.php)
//		(c)	insert from system gallery(returns ourgallery.php)
//(iii)	based on the return value a new window is opened with the previouly obtained page url
//(iv)	From this window we get another url, the url of the image and we insert this image 
//		into the page using execCommand('InsertImage').	
 function insertImage() {
	 try{
			if (SelMode == 2) {
				document.all("showhtml").checked=false;
				ShowHtml()
			}
		}catch(e){} 
		foo.focus();
	  var strUrl="type=" + document.getElementById("type").value;
	 res = showModalDialog('insertimage.php', null, 'dialogWidth: 300px; dialogHeight: 190px; center: yes; resizable: no; scroll: no; status: no;');	 
	if(res != null && res.url != "") {
		winHeight=0;
		winWidth=0;
		if(res.url != "uploadimage.php") {
			winHeight=500;
			winWidth=360;
		}
		else {
			winHeight=240;
			winWidth=300;
		}
		res = showModalDialog(res.url + "?" + strUrl, null, 'dialogWidth: ' + winWidth + 'px; dialogHeight: ' + winHeight + 'px; center: yes; resizable: no; scroll: auto; status: no;');	 
		if(res != null && res.url != "") {
			imagePath=res.url;
			document.getElementById('foo').contentWindow.document.execCommand('InsertImage', false, imagePath);
		}
	}
 }
//End Insert Image

//Insert flash
//This function is called from menu.js and from the popup window of foo
//check if SelMode == 2
//(i)	IF true then user asked to come to Design mode and taken to Design mode by calling showHtml()
//(ii)	open page insertflash.php which gives the user 2 options , 
//		(a)	upload a new flash object(returns type == 1),
//		(b)	insert from prevously uploaded flash objects(returns type==2,and,url to flash object)
//(iii)	If return type == 1 then we open uploadflash.php page(returns url to flash object) 
//(iv)	From this url of the object we insert the flash object 
//		into the page using PasteHTML() of <embed> tag by calling SelectFlash() function.	
function insertFlash() {
	try{
		if (SelMode == 2) {
			document.all("showhtml").checked=false;
			ShowHtml()
		}
	}catch(e){} 
	foo.focus();
	imagePath="";
	var strUrl="type=" + document.getElementById("type").value;
	res = showModalDialog('insertflash.php?' + strUrl, null, 'dialogWidth: 300px; dialogHeight: 180px; center: yes; resizable: no; scroll: no; status: no;');	 
	if(res != null && res.type == 1) {
		res = showModalDialog('uploadflash.php?' + strUrl, null, 'dialogWidth: 260px; dialogHeight: 190px; center: yes; resizable: no; scroll: no; status: no;');	 
	}
	if(res != null && res.url != "") {
		imagePath=res.url;
		SelectFlash(imagePath);	
	}		
	}
//called from insertFlash()
//this function inserts a flash object through <embed> using PasteHTML() function .
function SelectFlash(FlashName)
	{
		var sel = foo.document.selection;

		if (sel != null)
		{
			var rng = sel.createRange();
			
			if (rng != null)
			{
				FlashObject = '<embed src="' + FlashName +
				'" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash"></embed>';
				rng.pasteHTML(FlashObject);
			}
		}
	}
//End Insert Flash



//Add/Edit/Remove Page
	// Add a page 
	//(i)	Before adding a page we ask the  user whether to save the present page before
	//		proceeding to add a new page.
	//(ii)	open page insertpage.php that takes in options along with new page name and returns
	//		those values to res 			
	//(iii)	We check if the newpagename is already present using the function ifPagePresent(res.name)
	//		If true then we alert the user to enter a new name for the page and return back.
	//(iv)	If the user has opted the new page to be a guestbook and the present page is also a guestbook 
	//		we alert the user that only one copy of guestbook is allowed and return back.
	//(v)	If the user has not opted to save the present page before creating a new page we set the 
	//		actiontype as "newpage",other post parameters and postback the page.
	//(vi)	If the user has opted to save the present page and create a new page we set the
	//		actiontype as "saveandcreate", other post parameters and postback the page by calling the 
	//		savePage(2).'2' indicates that the actiontype should be set as "saveandcreate". 
	function addPage() {
			var saveAndProceed=confirm("Do you want to save your current page before creating a new one?");
			res = showModalDialog('insertpage.php', null, 'dialogWidth: 360px; dialogHeight: 250px; center: yes; resizable: no; scroll: no; status: no;');	
			if(res.type == "" || res.name == "") {
				return;	
			}
			else if(ifPagePresent(res.name)) {
				alert("Duplicate page name. Try another name for the page.");
				return;
			}
			//alert(document.all("guestbook").value + " and res.gb = " + res.gb);
			if(document.getElementById("guestbook").value == "yes" && res.gb == "yes") {
				alert("Cannot have two copies of guestbook.");
				return;
			}
			if(document.getElementById("guestbook").value == "yes") {
				global_addnew = true;
			}
			
			if(saveAndProceed != true) {
				document.getElementById("pagetype").value=res.type;
				document.getElementById("editpage").value=res.name;
				document.getElementById("gbnew").value=res.gb;
				document.getElementById("actiontype").value="newpage";
				document.getElementById("PageDetails").submit();
			}
			else{
				document.getElementById("pagetype").value=res.type;
				document.getElementById("editpage").value=res.name;
				document.getElementById("gbnew").value=res.gb;
				savePage(2);
			}
		}
	//Take a new page in editable area
	//(i)	assign the new page name to the editpage parameter
	//(ii)	get from the user if he wants to save the changes to the present page before moving to the 
	//		next page.
	//(iii)	If user says no then set actiontype as "edit" and postback the page
	//(iv)	if user says yes then call savePage(3) 
	//		actiontype is set as "saveandedit" and page is posted back
    function editPage() {
			if(document.getElementById("cmbPages").value == "") {
				return;
			}
			else if(document.getElementById("cmbPages").options[document.getElementById("cmbPages").selectedIndex].text == document.getElementById("presentpage").value) {
				alert('You are in the same page you are trying to edit.');
				return;
			}
			document.getElementById("editpage").value=document.getElementById("cmbPages").value;
			var saveAndProceed=confirm("Do you want to save your current page before editing the next page?");
			if(saveAndProceed != true) {
				document.getElementById("actiontype").value="edit";
				document.getElementById("PageDetails").submit();
			}
			else{
				savePage(3);
			}
		}
	//function to remove the page
	//(i)	check if the page has been completely loaded to the editable area
	//		if no then alert the user to wait till it gets completely loaded and return.
	//(ii)	Ask the user if he is sure on proceeding with the delete operation
	//		If no return back
	//(iii)	call checkForActual() that gets the imagelist to the deletedimages parameter.  The imagelist
	//		contains those names that was present the time this page was initially loaded.
	//(iv)	editpage parameter is set the name of the page to be deleted.
	//(v)	checkid parameter is incremented by one(this takes care of refresing the page
	//		and resource.txt file not getting modified) 
	//(vi)	actiontype is set as "delete"
	//(vii)	page is posted back
	function removePage() {
		/*
			if(foo.document.readyState != "complete") {
				alert('Please wait till the page gets loaded completely before performing any operation.');	
				return;
			
			}
			*/
			if(confirm("Are you sure you want to delete " + document.getElementById("presentpage").value + "?")) {
			if(document.getElementById("cmbPages").options[document.getElementById("cmbPages").selectedIndex].text != document.getElementById("presentpage").value) {
				alert("Page Mismatch!");
				return;
			}
			document.getElementById("deletedimages").value = checkForActual();
			document.getElementById("editpage").value=document.getElementById("cmbPages").value;
			if(isNaN(document.getElementById("checkid").value) || document.getElementById("checkid").value.length <= 0 || (parseInt(document.getElementById("checkid").value) <= 0)) {
				document.getElementById("checkid").value=1;
			}
			else {
				document.getElementById("checkid").value = parseInt(document.getElementById("checkid").value) + 1;
			}
			document.getElementById("actiontype").value="delete";
			document.getElementById("PageDetails").submit();
			}
		}
	//function to save the page : function savePage(a)
	//(i)	check if the page has been completely loaded to the editable area
	//		if no then alert the user to wait till it gets completely loaded and return.
	//(ii)	IF SelMode == 2 then take the user to design mode by calling showHtml()
	//(iii)	make formatting changes
	//(iv)	If guestbook == "yes" then check if the user has altered the guestbook_span.
	//		If yes then alert the user not to modify the guestbook placeholder and return.
	//		else call replaceguestbook() that replaces the image in the span with the php code.
	//(v)	Assign the total contents of the editable area to 5 POST parameters by dividing
	//		the total content by 5
	//(vi)	IF a !=  4 then
	//			(a)	assign deletedimages parameter the name of images returned by checkForDeleted() 
	//			(b)	assign newimages parameter the name of images returned by checkForNew()
	//		ELSE
	//			(a)	assign deletedimages parameter ""
	//			(b)	assign newimages parameter the name of images returned by checkForFinal()
	//(vi)	Assign actiontype parameter value based on the input value of a.
	//(vii)	checkid parameter is incremented by one(this takes care of refresing the page
	//		and resource.txt file not getting modified) 
	//(viii)page is posted back	
	function savePage(a) {
//            alert(document.getElementById('editor1').value);
//            alert('asdasd');
//            var oEditor =     FCKeditorAPI.GetInstance("editor1").GetXHTML(true);
//
//      alert(oEditor);
//      alert('asdasd');
var editor = CKEDITOR.instances.editor1.getData();
//alert( editor);
		var content = document.getElementById('editor1').value;
                var content = CKEDITOR.instances.editor1.getData();
                var basiclocation= document.getElementById('basiclocation').value;
		var indexOfSpan=0;
		//alert(content);
		/*
		if(foo.document.readyState != "complete") {
			alert('The page you are trying to save has not yet loaded completely. Please wait for the page to load completely.');	
			return;
		}
		
		try{
			if (SelMode == 2) {
				ShowHtml()
			}
		}catch(e){}
*/
		document.getElementById("EditorHTM").value = content;
		re = /&amp;/g
		document.getElementById("EditorHTM").value = document.getElementById("EditorHTM").value.replace(re,'&')
		if(document.getElementById("guestbook").value == "yes") {
                    var repString='<span id="guestbook_span"><img src="'+basiclocation+'/images/3.jpg" />';
			indexOfSpan=document.getElementById("EditorHTM").value.indexOf(repString);
			if(indexOfSpan == -1) {
				if(global_addnew == true) {
					alert('Please do not alter the image present as a placeholder for your guestbook.');	
					return;
				}
			}
			else {
				replaceGuestbook(indexOfSpan);
			}
		}

		htmlLength = document.getElementById("EditorHTM").value.length

		myHTML = document.getElementById("EditorHTM").value
		mcLength = myHTML.length / 5;
//alert(content);
		//document.getElementById("EditorHTM").value = content;
		//document.all("EditorHTM2").value = myHTML.substr(mcLength, mcLength*2 + 1);
		//document.all("EditorHTM3").value = myHTML.substr(mcLength*2+1, mcLength*3 + 1);
		//document.all("EditorHTM4").value = myHTML.substr(mcLength*3+1, mcLength*4 + 1);
		//document.all("EditorHTM5").value = myHTML.substr(mcLength*4+1, myHTML.length);
		if(a != 4) {
		document.getElementById("deletedimages").value = checkForDeleted();
		document.getElementById("newimages").value = checkForNew();
		}
		else {
			document.getElementById("deletedimages").value = "";
			document.getElementById("newimages").value = checkForFinal();
		}
		switch(a) {
			case 1:	
					document.getElementById("actiontype").value = "save";
					break;
			case 2:		
				document.getElementById("actiontype").value = "saveandcreate";
				break;
			case 3:		
				document.getElementById("actiontype").value = "saveandedit";
				break;
			case 4:		
				document.getElementById("actiontype").value = "saveas";
				break;
			case 5:		
				document.getElementById("actiontype").value = "saveandexit";
				break;
			default:
					alert("Invalid function call.");
					return;
		}
		if(isNaN(document.getElementById("checkid").value) || document.getElementById("checkid").value.length <= 0 || (parseInt(document.getElementById("checkid").value) <= 0)) {
			document.getElementById("checkid").value=1;
		}
		else {
			document.getElementById("checkid").value = parseInt(document.getElementById("checkid").value) + 1;
		}
		//return;
		document.getElementById("PageDetails").submit();
		}
//function called when saveAs clicked in menu
//(i)	check if guestbook parameter value is set as "yes"
//		If yes then alert the user that only one guestbook is permitted.
//(ii)	open saveas.php page that reads in a newpagename and returns the name to res.
//(ii)	If the newpagename is present in the site then alert the user about duplicate page name.
//		return back.
//(iii)	editpage parameter set as newpagename.
//(iv)	call savePage(4) to postback the page and save it in new name. 	
function savePageAs() {
		if(document.getElementById("guestbook").value == "yes") {
			alert("Cannot have two copies of guestbook.");
			return;
		}
		res = showModalDialog('saveas.php', null, 'dialogWidth: 340px; dialogHeight: 180px; center: yes; resizable: no; scroll: no; status: no;');	
		if(res.name == "") {
			return;	
		}
		else if(ifPagePresent(res.name)) {
			alert("Duplicate page name. Try another name for the page.");
			return;
		}
		document.getElementById("editpage").value=res.name;
		savePage(4);
	}
//function to save and exit
//call savePage(5)	to save the page and exit
function saveAndExit() {
		savePage(5);
	}	
//check functionality
function fooLoad() {
//foo.document.onkeydown = test;
}
//testing functionality
function test() {
	}
//function that gives the list of images deleted from the page	
//process() function checks the source array that contains ug_,sg_,sl_,fl_ images/objects with
//the final image list and final embed list.
//processFlag is set to true once processing is done. Hence calling process() multiple times won't repeatedly go through the 
//process actually.  processFlag is checked initially before starting the process. 
//IF it is being called for the first time then
//	(a)	get the images reference to finalImages
//	(b)	get the embeds reference to finalEmbeds
//	(c)	get total count of source Array to sourceCount
//	(d)	get total finalImages count to finalCount
//	(e)	get total finalEmbeds count to finalEmbedCount
//	(f)	LOOP till sourceCount
//	(g)		IF starting two characters of source[i] == "fl" THEN
//	(h)			LOOP till finalEmbedCount
//	(i)				check if each of the finalEmbeds array element contains source[i]
//					IF yes THEN
//						set source[i] = ""
//						set finalEmbeds[index] = ""
//						break the LOOP(h)
//					END IF
//				END LOOP(h)
//	(j)		ELSE(g)
//	(k)			LOOP till finalSourceCount
//	(l)				check if each of the finalImages array element contains source[i]
//					IF yes THEN
//						set source[i] = ""
//						set finalImages[index] = ""
//						break the LOOP(k)
//					END IF
//				END LOOP(k)
//			END IF(g)
//		END LOOP(f)
//Once this function is completed the source array will contain the list of deleted images
//and the finalImages/finalEmbeds array will contain the new images entered.
//This function is called from checkForDeleted() and checkForNew()
var processFlag=false;
function process() {
	if(processFlag == false) {
		processFlag=true;
			var content = CKEDITOR.instances.editor1.getData();
			//finalImages = foo.document.images;
			//finalEmbeds = foo.document.embeds;
			finalImages = content.images;
			finalEmbeds = content.embeds;
			i=0;
			var sourceCount=source.length;
			if (typeof(finalImages) != "undefined") 
				var finalCount=finalImages.length;
                        else
				var finalCount=0;

                        if (typeof(finalEmbedCount) != "undefined")
				var finalEmbedCount = finalEmbeds.length;
                        else
				var finalEmbedCount=0;
			
			while(i < sourceCount) {
				if(source[i] != "") {
					var strTemp=source[i];
						if(strTemp.substr(0,2) == "fl") {
							j=0;
							while(j < finalEmbedCount) {
								if(finalEmbeds[j].src != "") {
									var strTemp2 = finalEmbeds[j].src;
									if(strTemp == strTemp2.substr((strTemp2.lastIndexOf("/") + 1),(strTemp2.length))) {
										source[i]="";
										finalEmbeds[j].src="";
										break;
									}
								}
								j++;
							}
						}
						else {
							j=0;
							while(j < finalCount) {
								if(finalImages[j].src != "") {
									var strTemp2 = finalImages[j].src;
									if(strTemp == strTemp2.substr((strTemp2.lastIndexOf("/") + 1),(strTemp2.length))) {
										source[i]="";
										finalImages[j].src="";
										break;
									}
								}
								j++;
							}
						}
				}
				i++;
			}
	}
}
//Creates a pipe seperated image list 
//(i)	calls process() that gets the deleted images in the source array and new images in the finalImages/finalEmbeds array
//(ii)	loops through the source array and create a pipe separated string with the names in the source array and returns the string.
function checkForDeleted() {
	var strDeleted = "";
	process();
	var sourceCount=source.length;
	for(i=0;i<sourceCount;i++) {
		if(source[i] != "") {
			strDeleted = strDeleted + source[i] + "|";
		}
	} 
	if(strDeleted.length > 0) {
		strDeleted = strDeleted.substr(0,strDeleted.length-1);
	}
	//alert(strDeleted);
	return strDeleted;
}
//Creates a pipe seperated image list 
//(i)	calls process() that gets the deleted images in the source array and new images in the finalImages/finalEmbeds array
//(ii)	loops through the finalImages/finalEmbeds array and create a pipe separated string with the names in the 
//		finalImages/finalEmbeds array and returns the string.
function checkForNew() {
	var strNew = "";
	var strTemp;
	process();
//        alert(document.getElementById('editor1').value);
	var content = CKEDITOR.instances.editor1.getData();
	var finalImages = content.images;
	if (typeof(finalImages) != "undefined") 
		var finalCount=finalImages.length;
	else
		var finalCount=0;
	var strTemp="";
	for(i=0;i<finalCount;i++) {
		if(finalImages[i].src != "") {
			strTemp=finalImages[i].src;
			strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
			var strTemp2=strTemp.substr(0,2);
			if(strTemp2 == "ug" || strTemp2 == "sg" || strTemp2 == "sl") {
				strNew = strNew + strTemp + "|";
			}
		}
	}
	if (typeof(finalEmbeds) != "undefined") 
		finalCount = finalEmbeds.length;
	else
		finalCount = 0;
	for(i=0;i<finalCount;i++) {
		if(finalEmbeds[i].src != "") {
			strTemp=finalEmbeds[i].src;
			strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
			if(strTemp.substr(0,2) == "fl") {
				strNew = strNew + strTemp + "|";
			}
		}
	}
	strTemp
	if(strNew.length > 0) {
		strNew = strNew.substr(0,strNew.length-1);
	}
	//alert(strNew);
	return strNew;
}
//Here we do not call process()
//Hence the list of images/objects[flash] at the time of loading will be present in the source array
//We create a pipe separated list of these images/objects into a string and returns that string 
function checkForActual() {
	var strActual = "";
	i=0;
	var sourceCount=source.length;
	while(i < sourceCount) {
		if(source[i] != "") {
				strActual = strActual + source[i] + "|";
		}
		i++;
	}
	if(strActual.length > 0) {
		strActual = strActual.substr(0,strActual.length-1);
	}
	//alert(strActual);
	return strActual;
}
//Here we do not call process()
//Hence the list of images/objects[flash] at the time of action will be present in the finalImages/finalEmbeds array
//We create a pipe separated list of these images/objects into a string and returns that string 
function checkForFinal() {
	var strActual = "";
	i=0;
	var content = CKEDITOR.instances.editor1.getData();
	//finalImages = foo.document.images;
	//finalEmbeds = foo.document.embeds;
	
	finalImages = content.images;
	finalEmbeds = content.embeds;
	
	var finalCount=finalImages.length;
	var finalEmbedCount=finalEmbeds.length;
	
	var strTemp="";
	while(i < finalCount) {
		strTemp=finalImages[i].src;
		strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
		var strTemp2=strTemp.substr(0,2);
		if(strTemp2 == "ug" || strTemp2 == "sg" || strTemp2 == "sl") {
				strActual = strActual + strTemp + "|";
			}
		i++;
	}
	i=0;
	while(i < finalEmbedCount) {
		strTemp=finalEmbeds[i].src;
		strTemp=strTemp.substr((strTemp.lastIndexOf("/") + 1),(strTemp.length));
		if(strTemp.substr(0,2) == "fl") {
				strActual = strActual + strTemp + "|";
			}
		i++;
	}
	if(strActual.length > 0) {
		strActual = strActual.substr(0,strActual.length-1);
	}
	return strActual;
}
//returns true if the name passed into the function (strName) is present in the pagelist of the site
//We check the combobox cmbPages to see if strName exists.
//Else it returns false
function ifPagePresent(strName) {
	var flag=false;
	var tempCount=document.getElementById("cmbPages").options.length;
	for(i=0;i<tempCount;i++) {
		if(document.getElementById("cmbPages").options[i].text == strName) {
				flag=true;
				break;
			}	
	}
	return flag;
}
//Add/Edit/Remove Page

//Preview Site
//A new window is opened with the workarea path to the pageName.
	function previewSite(loc,id,pageName) {
		var leftPos = (screen.availWidth-500) / 2;
		var topPos = (screen.availHeight-400) / 2 ;
		var strUrl = "../workarea/" + loc + "/" + id + "/" + pageName;
		insertFormWin = window.open(strUrl,'','width=' + screen.availWidth + ',height=' + screen.availHeight + ',scrollbars=yes,resizable=yes,titlebar=0,top=' + topPos + ',left=' + leftPos);
	}
//End Preview Site

//Publish Site
//If type parameter == "new" THEN
//	that means it is a non-published site
//	direct him to publishpage.php
//	this is done by posting the form "publishPage" back with the pubpage parameter to "publishpage"
//ELSE
//	that means it is a published site
//	direct him to the postpublish.php
//	this is done by setting the action element of the publishpage form to "../postpublish.php?type=editpage"
//END IF
function publishSite() {
		if(document.getElementById("type").value == "new") {
			document.getElementById("pubpage").value="publishpage";
			document.getElementById("publishPage").method="post";
			document.getElementById("publishPage").action="./editor.php";
			document.getElementById("publishPage").submit();
		}
		else {
			document.getElementById("publishPage").method="post";
			document.getElementById("publishPage").action="../postpublish.php?type=editpage";
			document.getElementById("publishPage").submit();
		}
	}
//Check if SelMode == 2 then take the user to design mode by calling showHtml()
//call foo.print()
function printDocument() {
			try{
				if (SelMode == 2) {
					document.all("showhtml").checked=false;
					ShowHtml()
				}
			}catch(e){} 
			foo.print();
		}
//user is asked if he is sure of exiting the document
//If yes then he is directed to usermain.php
function  exitDocument() {
			if(confirm("Are you sure you want to exit this document?")) {
				location.href="../usermain.php";
			}
		}	
//End Publish Site

//Right click on frame
//This section contains the popup window that is shown as the context menu
oPopup = window.createPopup();
 oPopX = oPopY = 0;
 cntLayer = '';

 cntCut = '<div class=cntItem onclick="javascript:parent.changeFont(\'Cut\');"  onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/cut.gif align=absmiddle>&nbsp;&nbsp;Cut</div>';
 disCut = '<div disabled class=cntItem><IMG SRC=images/cut.gif align=absmiddle>&nbsp;&nbsp;Cut</div>';
 cntCopy = '<div class=cntItem onclick="javascript:parent.changeFont(\'Copy\');"  onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/copy.gif align=absmiddle>&nbsp;&nbsp;Copy</div>';
 disCopy = '<div disabled class=cntItem><IMG SRC=images/copy.gif align=absmiddle>&nbsp;&nbsp;Copy</div>';
 cntPaste = '<div class=cntItem onclick="javascript:parent.changeFont(\'Paste\');"  onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/pastee.gif align=absmiddle>&nbsp;&nbsp;Paste</div>';
 cntAddGr = '<div class=cntItem onclick="javascript:parent.addGraphicalText(0);" onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/grafxtxt.gif align=absmiddle>&nbsp;&nbsp;Add Graphical Text</div>';
 cntEditGr = '<div class=cntItem onclick="javascript:parent.addGraphicalText(1);" onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/text.gif align=absmiddle>&nbsp;&nbsp;Edit Graphical Text</div>';
 cntInsImg = '<div class=cntItem onclick="javascript:parent.insertImage();" onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/picinsert.gif align=absmiddle>&nbsp;&nbsp;Insert Image / Logo</div>';
 cntChFlash = '<div class=cntItem onclick="parent.insertFlash();" onmouseover="parent.overSub(this);"  onmouseout="parent.outSub(this);"><IMG SRC=images/insertflash.gif align=absmiddle>&nbsp;&nbsp Add flash images</div>';
 cntHead = '<div class=cntNest>';
 cntFoot = '</div>';
 var imageId="";
var imageObject=null;	
//This function is called for the onContextMenu() and this takes care of displaying the contextmenu as a table.
function goContext(){
  cntRange = foo.document.selection.createRange();
  cntRes = '';
  imageId="";
  sImgSel = foo.event.srcElement.tagName == 'IMG';
  firedObj = foo.event.srcElement;
  imageObject=null;
  if(firedObj.tagName != 'A')
   while(firedObj.tagName != "BODY" && firedObj.tagName != "A")
    firedObj = firedObj.parentElement;
  sLinkSel = firedObj.tagName == 'A';
  rows = 0;

if(sImgSel){
   imageId=foo.event.srcElement.src;
   imageObject=foo.event.srcElement;
	var strTemp=imageId.substr((imageId.lastIndexOf("/") + 1),(imageId.length))
	var strTemp2=strTemp.substr(3,10);
	if(strTemp2 == "company" || strTemp2 == "caption" || strTemp2 == "logoima" || strTemp2 == "innerco" || strTemp2 == "innerca" || strTemp2 == "innerlo") {   
		strTemp2=strTemp.substr(0,2);
		if(strTemp2 == "tp") {
			text = cntAddGr;
			cntRes += text;
			rows++;
		}
		else if(strTemp2 == "ug") {
			text = cntEditGr;
			cntRes += text;
			rows++;
		}
	}
  }
  else {
	  cntRes += cntInsImg;
	  rows++;
	  cntRes += cntChFlash;
	  rows++;
	  }
	

  if(!cntRange.text && !cntRange.length)
   cntRes += disCut + disCopy;
  else
   cntRes += cntCut + cntCopy;

  cntRes += cntPaste;
  rows += 3;

  oPopup.document.body.innerHTML = cntRes;
  oPopX = foo.event.x;
  oPopY = foo.event.y;
  oStyleSheet = oPopup.document.createStyleSheet();
  oStyleSheet.addRule('.cntItem', 'background-color:#cccccc; border:1px solid black; border-top: 1px solid white; border-left:1px solid white; height:19px; color:black; font-family:verdana; font-weight:bold; padding:2px; padding-left:10px; font-size:8pt; cursor:default; behavior: url(inc/sContext.htc);');
  oStyleSheet.addRule('.cntSub', 'background-color:#cccccc; background-image:url(img/arr.gif); background-repeat:no-repeat; background-position:right; border:1px solid black; border-top: 1px solid white; border-left:1px solid white; height:19px; color:black; font-family:verdana; font-weight:bold; padding:2px; padding-left:10px; font-size:8pt; cursor:default;');
  oStyleSheet.addRule('.cntNest', 'border:2px solid black; border-top:2px solid #cccccc; border-left:2px solid #cccccc; background-color:#666666;');
  if(SelMode == 1) {
	  oPopup.show(oPopX, oPopY, 207, rows*21, foo.document.body);
  }
  document.body.onmouseup = foo.document.body.onmouseup = oPopup.document.body.onclick = cntHide;
 }
 
//called for hiding the contextmenu table
function cntHide(){
  oPopup.hide(); 
 }
//This function is called from the contextmenu table
//The goContext() method which is called at onContextMenu() sets the src of the image(if it is an image) to imageId
//and the object reference to imageObject.  This imageId is used to decide whether to show the imageeditor.php which
//helps the user to add text/image to the given caption/logo/company images.
//We take the 7 characters from the 3 rd character, check if the image is valid for edition
//(only the following images - tp_logoimage.jpg/gif, tp_companyimage.jpg/gif, tp_captionimage.jpg/gif
//tp_innerlogoimage.jpg/gif, tp_innercompanyimage.gif, tp_innercaptionimage.jpg/gif are allowed to be edited)
// If then call the imageeditor.php and set the url returned by imageeditor.php to the imageObject.src.
function addGraphicalText(strSrc) {
	var strTemp=imageId.substr((imageId.lastIndexOf("/") + 1),(imageId.length));
	var strTemp2 = strTemp.substr(3,10);
	var strUrl="type=" + document.getElementById("type").value + "&imagename=" + strTemp;
	if(strTemp2 == "company" || strTemp2 == "caption" || strTemp2 == "logoima" || strTemp2 == "innerco" || strTemp2 == "innerca" || strTemp2 == "innerlo") {
		res = showModalDialog('imageeditor.php?' + strUrl, null, 'dialogWidth: 600px; dialogHeight: 600px; center: yes; resizable: no; scroll: yes; status: no;');	
		if(res == null || res.name == null || res.name == "") {
			return;	
		}
		imageObject.src="./images/" + res.name;			
	} 
}
//caled from popup menu 
//Used to change the backgroundcolor of the td 
function overSub(sNest){
  sNest.style.backgroundColor = '#ffffff';
 }
//called from popup menu
//Used to change the backgroundcolor of the td 
 function outSub(sNest){
  sNest.style.backgroundColor = '#cccccc';
 }
//End Right Click


//guestbook replace section called from savepage
//This is used to replace the image placeholder of guestbook with php script
//
function replaceGuestbook(indexOfSpan) {

var strNew = '<SPAN id=guestbook_span>' + 
'<?php $filename = \'gb.txt\';' +
'' +
'if (is_writable($filename)) {' +
'if (!$handle = fopen($filename, \'a+\')) {' +
'$message.= "Cannot open file ($filename)";' +
'exit;' +
'}' +
'If($_GET["act"]=="post"){' +
'$message= "";' +
'$content = addslashes($_POST["name"])."`|^".$_POST["email"]."`|^".$_POST["matter"]."`|^".date("Y-m-d")."~`|\\n";' +
'if (fwrite($handle, $content) === FALSE) {' +
'$message.= "Cannot write to file ($filename)";' +
'exit;' +
'}' +
'' +
'$message.= "Thank you. Your Guest book entry added";' +
'fseek($handle, 0);' +
'' +
'}' +
'' +
'$displaycontents.="<table align=center width=70%><tr><td align=center><font face=verdana size=2><b>Current GuestBook Entries<br>&nbsp;</b></font></td></tr>";' +
' ' +
'if(filesize($filename)>0){' +
'' +
'$readcontents = @fread($handle, filesize($filename));' +
'$entryarray=explode("~`|\\n",$readcontents);' +
'' +
'' +
'for' + '($' + 'i' + '=0;' + '$i<' + ' count' + '($entryarray)' + '-1;' + '$i' + '++){' +
'' +
'$valuearray' + '=' + 'explode(' + '"`|^",' + '$entryarray[' + '$i]);' +
'$displaycontents.="<tr><td align=left bgcolor=#dddddd><font face=verdana size=2>Posted &nbsp;by &nbsp;".stripslashes($valuearray[0])."( ".$valuearray[1]." ) &nbsp;on&nbsp; ".$valuearray[3]."</font></td></tr>";' +
'$displaycontents.="<tr><td align=left valign=top><font face=verdana size=2><br>".$valuearray[2]."</font></td></tr>";' +
'$displaycontents.="<tr><td align=left valign=top>&nbsp;</td></tr>";' +
'' +
'' +
'}' +
'' +
'' +
'}else{' +
'' +
'$displaycontents.="<tr><td align=center valign=top><font face=verdana size=2>Sorry! Guest book is empty.</font></td></tr>";' +
'' +
'}' +
'$displaycontents.="</table>";' +
'fclose($handle);' +
'' +
'' +
'} else {' +
'' +
'$message.= "The file $filename is not writable.Please provide write permission to it";' +
'' +
'}' +
'' +
'' +
'' +
'' +
' /**/ ?> ' +
'<script>' +
'function checkMail(email)' +
'{' +
'var str1=email;' +
'var arr=str1.split(\'@\');' +
'var eFlag=true;' +
'if(arr.length != 2)' +
'{' +
'eFlag = false;' +
'}' +
'else if(arr[0].length <= 0 || arr[0].indexOf(\' \') != -1 || arr[0].indexOf("\'") != -1 || arr[0].indexOf(\'"\') != -1 || arr[1].indexOf(\'.\') == -1)' +
'{' +
'eFlag = false;' +
'}' +
'else' +
'{' +
'var dot=arr[1].split(\'.\');' +
'if(dot.length < 2)' +
'{' +
'eFlag = false;' +
'}' +
'else' +
'{' +
'if(dot[0].length <= 0 || dot[0].indexOf(\' \') != -1 || dot[0].indexOf(\'"\') != -1 || dot[0].indexOf("\'") != -1)' +
'{' +
'eFlag = false;' +
'}' +
'' +
'for(i=1;i < dot.length;i++)' +
'{' +
'if(dot[i].length <= 0 || dot[i].indexOf(\' \') != -1 || dot[i].indexOf(\'"\') != -1 || dot[i].indexOf("\'") != -1 || dot[i].length > 4)' +
'{' +
'	  eFlag = false;' +
'}' +
'}' +
'}' +
'}' +
'return eFlag;' +
'}' +
'function validate(){' +
'' +
'if(document.gbForm.name.value=="" ){' +
'' +
'alert("Please enter your name");' +
'document.gbForm.name.focus();' +
'' +
'}else if (document.gbForm.email.value==""){' +
'' +
'alert("Please enter your email");' +
'document.gbForm.email.focus();' +
'' +
'}else if(checkMail(document.gbForm.email.value)==false){' +
'' +
'alert(\'Invalid mail format\');' +
'document.gbForm.email.focus();' +
'return false;' +
'' +
'}else if (document.gbForm.matter.value==""){' +
'' +
'alert("Please enter your matter");' +
'document.gbForm.matter.focus();' +
'' +
'}else{' +
'' +
'document.gbForm.submit();' +
'}' +
'' +
'}' +
'</script>' +
'<?php' +
'echo $displaycontents;' +
'?>' +
'<table width="100%"  border="0" align="center">' +
'<tr>' +
'<td>&nbsp;</td>' +
'</tr>' +
'<tr>' +
'<td align="center"><form name="gbForm" method="post" action="<?php $_SERVER[\'PHP_SELF\']; ?>?act=post">' +
'<fieldset style="width:400px;">' +
'<table width="100%"  border="0">' +
'<tr align="center">' +
'<td colspan="3"><br>' +
'<strong><font face=verdana size=2>Add your guestbook entry</font> </strong><br>&nbsp;</td>' +
'</tr>' +
'<tr>' +
'<td width="100%" align="center" colspan=3><font face=verdana size=1 color=red><?php echo $message; ?></font></td>' +
'</tr>' +
'<tr>' +
'<td width="45%" align="right"><font face=verdana size=2>Your Name</font></td>' +
'<td width="3%">&nbsp;</td>' +
'<td width="52%" align="left" valign="top"><input name="name" type="text" id="name"></td>' +
'</tr>' +
'<tr>' +
'<td>&nbsp;</td>' +
'<td>&nbsp;</td>' +
'<td>&nbsp;</td>' +
'</tr>' +
'<tr>' +
'<td align="right"><font face=verdana size=2>Your Email Address</font></td>' +
'<td>&nbsp;</td>' +
'<td align="left" valign="top"><input name="email" type="text" id="email"></td>' +
'</tr>' +
'<tr>' +
'<td>&nbsp;</td>' +
'<td>&nbsp;</td>' +
'<td>&nbsp;</td>' +
'</tr>' +
'<tr>' +
'<td align="right"><font face=verdana size=2>Guest Book Matter</font></td>' +
'<td>&nbsp;</td>' +
'<td align="left" valign="top">            <textarea name="matter" id="matter"></textarea></td>' +
'</tr>' +
'<tr>' +
'<td>&nbsp;</td>' +
'<td>&nbsp;</td>' +
'<td>&nbsp;</td>' +
'</tr>' +
'<tr align="center">' +
'<td colspan="3"><input type="button" value="Sign Guest Book" onclick=validate();></td>' +
'</tr>' +
'</table>' +
'</fieldset>' +
'</form></td>' +
'</tr>' +
'</table>';
document.getElementById("EditorHTM").value = document.getElementById("EditorHTM").value.substr(0,indexOfSpan) + strNew + document.getElementById("EditorHTM").value.substr((indexOfSpan+56+document.getElementById("basiclocation").value.length),document.getElementById("EditorHTM").value.length);
}
//end guestbook replace function
