
//======================================================
//               Ajax Implementation
//======================================================
function AjaxCall(url,callbackHandler,callbackId,postData,ProcessingMessage)
{
	var xmlHttp; 	
	var AsynchronousMode=false;
	var callback=false;
	
	if(typeof(callbackHandler)=="function")
		callback=true;
	
	if(callbackId)
		AsynchronousMode=true;
	
	if(callback)
		AsynchronousMode=true;	
	
	if(ProcessingMessage && ProcessingMessage!='')
		ProgressStart(ProcessingMessage);
	
	try 
	{ 
		xmlHttp = GetXmlHttpObject(); 
		
		if(AsynchronousMode)
			SendXmlHttpRequest();
		else
			return SendXmlHttpRequest();
	}
	catch(e)
	{
		alert("Your Session has expired due to slow network connection, please close the PowerXEditor window and try again. ");
		return false;
	} 

	function GetXmlHttpObject() 
	{
		var objXmlHttp;
		try 
		{   
			// Mozilla / Safari / IE7   
			objXmlHttp = new XMLHttpRequest();   
		} 
		catch (e) 
		{   
			// IE   
			//var st="MSXML2.XMLHTTP.5.0,MSXML2.XMLHTTP.4.0,MSXML2.XMLHTTP.3.0,MSXML2.XMLHTTP,Microsoft.XMLHTTP";
			//var XMLHTTP_IDS = [];
			//XMLHTTP_IDS = st.split(",");   
			var XMLHTTP_IDS = ['MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
			var success = false;   
			for (var i=0;i < XMLHTTP_IDS.length && !success; i++) 
			{   
				try 
				{   
					objXmlHttp = new ActiveXObject(XMLHTTP_IDS[i]);   
					success = true;   
				} catch (e) 
				{}   
			}   
			if (!success) 
			{   
				//throw new Error(’Unable to create XMLHttpRequest.’);   
			}   
			
		}   

		return objXmlHttp;
	}


	
	function SendXmlHttpRequest() 
	{ 
		try
		{
		
			if (xmlHttp != null && AsynchronousMode==true)
			{ 
				if (callback)
					xmlHttp.onreadystatechange = AjaxCallbackMethod;
			}	
			
			if (postData)
			{
				xmlHttp.open('POST', url, AsynchronousMode); 
				xmlHttp.setRequestHeader("Content-type","text/xml;charset=UTF-8;"); 
				xmlHttp.send(postData); 	
			}
			else
			{
				xmlHttp.open('GET', url, AsynchronousMode); 
				xmlHttp.setRequestHeader("Content-type","text/xml;charset=UTF-8;"); 
				xmlHttp.send(null); 
			}

			if(!AsynchronousMode)
			{
				ProgressStop();
				if(xmlHttp.status == 200)
				{
					return xmlHttp.responseText; 
				}
			}
		}
		catch(e)
		{
			return false;
		}
	}	



	//CallbackMethod will fire when the state 
	//has changed, i.e. data is received back 
	function AjaxCallbackMethod() 
	{ 
		try
		{
			//readyState of 4 or 'complete' represents 
			//that data has been returned 
			if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
			{
				if(xmlHttp.status == 200)
				{
					var response = xmlHttp.responseText; 
					ProgressStop();
					if(callback)	
					{
						if(callbackId)
						{
							callbackHandler(response,callbackId);
						}
						else
						{
							//alert('callbackHandler(response)');
							
							callbackHandler(response);
						}
					}
				}
				else
				{
					alert("Your Session has expired due to slow network connection, please close the PowerXEditor window and try again. ");
					ProgressStop();
					if(callback)
					{	
						callbackHandler(false);
					}
				}
			}
		}
		catch(e)
		{}
	}
}


//======================================================
//               End of : Ajax Implementation
//======================================================



//======================================================
//               Start of : Progress Bar
//======================================================
var PBDiv=null;
var docWindow;
function ProgressStart(msg)
{
	ProgressStop();
	
	if(typeof(msg)=="undefined")
		msg="Loading...";
	//if(window.parent.location.href.toLowerCase().indexOf("pxeeditor.aspx")>-1)
	//if(window.parent.window.document.url.toLowerCase().indexOf("pxeeditor.aspx")>-1)
	if(window.parent.window.location.href!=window.location.href)
		docWindow=window.parent.window.document;
	else
		docWindow=window.document;
		
	PBDiv=docWindow.createElement("DIV");
	PBDiv.setAttribute("id","progressdiv");
	var inHTML="";
	inHTML="<table height=100% width=100%><tr valign=middle><td align=center>";
	inHTML+="<table width='200' border='1' align='center' cellpadding='0' cellspacing='0' bordercolor='#AC9F02' style='border-collapse:collapse'>";
	inHTML+="<tr><td>";
	inHTML+="<table width='200' border='0' align='center' cellpadding='6' cellspacing='2' bgcolor='#FFFFBB'>";
    inHTML+="<tr><td style='font-family: Arial, Helvetica, sans-serif; font-size: 9pt'><div align='center' style='color: #FF0000'>"+msg+"</div></td>";
    inHTML+="</tr><tr><td id='tdBar'>"//<img src='../images/processing.gif' />";
    inHTML+="</td></tr></table></td></tr>"
	inHTML+="</td></tr></table>";
	PBDiv.innerHTML=inHTML;
	PBDiv.style.cssText="position:absolute;left:0px;top:0px;width:100%;height:100%;Z-INDEX:5001;";
	//PBDiv.style.cssText="position:absolute;left:0px;top:0px;width:100%;height:100%;Z-INDEX: 1001;BACKGROUND-COLOR:red";
	docWindow.body.appendChild(PBDiv);
	
	//a {cursor: pointer; cursor: hand;}
	
	var bar1= createBar(200,10,'white',1,'#AEAE53','black',85,7,3,'');
	bar1.showBar();
	
}

function ProgressStop()
{
	if(PBDiv)
	{
		clearInterval(bA.tid);
		bA=null;
		docWindow.body.removeChild(PBDiv);
	}
	PBDiv=null;
}



var w3c;
var ie;
var N=-1;
var bA=null;
function createBar(w,h,bgc,brdW,brdC,blkC,speed,blocks,count,action)
{
w3c=(docWindow.getElementById)?true:false;
ie=(docWindow.all)?true:false;
N=-1;
var t="";
if(ie||w3c){
if(ie)
	t='<div id="_xpbar'+(++N)+'" style="visibility:visible; overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';
else
	t='<div id="_xpbar'+(++N)+'" style="visibility:visible; position:relative;overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';

t+='<span id="blocks'+N+'" style="left:-'+(h*2+1)+'px; position:absolute; font-size:1px">';
for(i=0;i<blocks;i++){
t+='<span style="background-color:'+blkC+'; left:-'+((h*i)+i)+'px; font-size:1px; position:absolute; width:'+h+'px; height:'+h+'px; '
t+=(ie)?'filter:alpha(opacity='+(100-i*(100/blocks))+')':'-Moz-opacity:'+((100-i*(100/blocks))/100);
t+='"></span>';
}
t+='</span></div>';
var tdBar=docWindow.getElementById("tdBar");
tdBar.innerHTML=t;
//document.write(t);
bA=(ie)?docWindow.all['blocks'+N]:docWindow.getElementById('blocks'+N);
bA.bar=(ie)?docWindow.all['_xpbar'+N]:docWindow.getElementById('_xpbar'+N);
bA.blocks=blocks;
bA.N=N;
bA.w=w;
bA.h=h;
bA.speed=speed;
bA.ctr=0;
bA.count=count;
bA.action=action;
bA.togglePause=togglePause;
bA.showBar=function(){
this.bar.style.visibility="visible";
}
bA.hideBar=function(){
this.bar.style.visibility="hidden";
}
bA.tid=setInterval('startBar('+N+')',speed);
return bA;
}}

function startBar(bn){
var t=(ie)?docWindow.all['blocks'+bn]:docWindow.getElementById('blocks'+bn);
if(t)
{
	if(parseInt(t.style.left)+t.h+1-(t.blocks*t.h+t.blocks)>t.w){
	t.style.left=-(t.h*2+1)+'px';
	t.ctr++;
	if(t.ctr>=t.count){
	eval(t.action);
	t.ctr=0;
	}}else t.style.left=(parseInt(t.style.left)+t.h+1)+'px';
}
}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}
//======================================================
//               End of : Progress Bar
//======================================================



//=======================================
//          General Purpose (Mozilla)
//=======================================

	function StartTopDocument(editor)
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
			return;
			
		var editdoc=editor.GetDocument();
		var editwin=editor.GetWindow();
		
		//var FText=editdoc.getElementsByTagName("P").item(0).innerHTML;
		var FText=editdoc.getElementsByTagName("P").item(0).textContent;
		var nfound=true;
		
		while(nfound)
		{
			nfound= editwin.find(FText, false, true, false, true, false, false);
		}
		var sel=editwin.getSelection();
		var range=sel.getRangeAt(0);
		range.collapse(true);
	}		
	
	
	function SetBookmark(editor)
	{
		try
		{
			var editdoc=editor.GetDocument();
			
			if(navigator.appName.lastIndexOf("Microsoft")!=-1)
			{
				editdoc=editor.GetDocument();
				var objselect   = editdoc.selection;
				var rangeCursor = objselect.createRange();
				
				var BookMark="<SPAN ID='Bookmark1'></SPAN>";

				var obj=editdoc.getElementById("Bookmark1");
				if(obj)
				{
					RemoveBookmark(editor)
				}				
				rangeCursor.collapse(false);
				rangeCursor.pasteHTML(BookMark);	
				obj=editdoc.getElementById("Bookmark1");
				return obj;
			}
			else
			{
				var editwin=editor.GetWindow();
				var sel=editwin.getSelection();
				var range=sel.getRangeAt(0);
				var obj=editdoc.getElementById("Bookmark1");
				if(obj)
				{
					RemoveBookmark(editor)
				}				
				range.collapse(true);
				var docFragment = range.createContextualFragment("<SPAN ID='Bookmark1'></SPAN>");
				range.insertNode(docFragment);
				range.collapse(false);
				obj=editdoc.getElementById("Bookmark1");
				return obj;
			}
		}
		catch(ex)
		{}
	}
	
	function RemoveBookmark(editor)
	{
		try
		{
			var editdoc=editor.GetDocument();
			
			var BookmarkNode=editdoc.getElementById("Bookmark1");
			if(BookmarkNode)
			{
				
				if(navigator.appName.lastIndexOf("Microsoft")!=-1)
				{
					BookmarkNode.outerHTML="";
				}
				else
				{
					var rr=SetSelectionByNode(BookmarkNode,true);
					var range= editdoc.createRange();
					range.selectNode(BookmarkNode);
					range.deleteContents();
					range.collapse(false);
				}
			}
		}
		catch(ex)
		{}
	}


	function RemoveNode(editor,NodeId)
	{
		try
		{
			var editdoc=editor.GetDocument();
			
			var BookmarkNode=editdoc.getElementById(NodeId);
			if(BookmarkNode)
			{
				
				if(navigator.appName.lastIndexOf("Microsoft")!=-1)
				{
					BookmarkNode.outerHTML="";
				}
				else
				{
					var rr=SetSelectionByNode(BookmarkNode,true);
					var range= editdoc.createRange();
					range.selectNode(BookmarkNode);
					range.deleteContents();
					range.collapse(false);
				}
			}
		}
		catch(ex)
		{}
	}



	function SearchElements(tagName,className,parentElement)	//Return Element Collection
	{
		
		if(!parentElement)
			return false;
		
		
		if(!tagName && !className)
			return false;
			
		if(tagName=="" && className=="")
			return false;
		
		var ElementList=[];
		var objList;
		
		if(tagName!="")
		{
			objList=parentElement.getElementsByTagName(tagName);
		}
		else
		{
			objList=child_nodes[parentElement];
		
		}
		if(className=="")
			return objList;
			
		if(className!="")
		{
			for(var i=0;i<objList.length;i++)
			{
				if(objList[i].className.toLowerCase()==className.toLowerCase())
					ElementList[ElementList.length]=objList[i];	
			}
		}
		
		return ElementList;
	}


	function LTrim(str)
	{	
		try
		{			
			var returnValue="";
			if (str.length>0)
			{				
				for(var i=0;str.charAt(i)==" ";i++);
				returnValue= str.substring(i,str.length);
			}			
			return returnValue;
		}
		catch(e)
		{
		}
	}

	function trim(s) 
	{
		try
		{
			while (s.substring(0,1) == ' ') 
			{
				s = s.substring(1,s.length);
				}
			while (s.substring(s.length-1,s.length) == ' ')
				{
				s = s.substring(0,s.length-1);
			}
				return s;
		}
		catch(e)
		{}
	}
	
	function Evalute(s) 
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
				return eval(s);
		}
		else
		{
			var h = document.getElementsByTagName("HEAD")[0];
			var o = document.createElement("SCRIPT");

			o.text = s;
			h.appendChild(o);
			h.removeChild(o);
		}
	}

	function getHTMLOfSelection(editor)//CC
	{
	
		var doc=editor.GetDocument();
		var win=editor.GetWindow();
		var range;
		if (document.selection && document.selection.createRange) 
		{
			range = doc.selection.createRange();
			if (doc.selection.type == "Control")
				return range.item(0).outerHTML;
			else 
				return range.htmlText;
		}
		else if (window.getSelection) 
		{
			var selection = win.getSelection();
			if (selection.rangeCount > 0) 
			{
				range = selection.getRangeAt(0);
				var clonedSelection = range.cloneContents();
				var div = document.createElement('div');
				div.appendChild(clonedSelection);
				return div.innerHTML;
			}
			else 
			{
				return '';
			}
		}
		else 
		{
			return '';
		}
	}

	function Selection_GetParentElement(editor)
	{
		var range=Get_Range(editor);
		return Range_GetParentElement(range);
	}

	//=================   Text Range  =========================	
	function Get_Range(editor)
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
			var editdoc=editor.GetDocument();
			var objselect=editdoc.selection;
			var range = objselect.createRange();	
			return range;
		}
		else
		{
			var editwin=editor.GetWindow();
			var sel = editwin.getSelection();
			var range= sel.getRangeAt(0);
			return range;
		}
	}
	
	
	function Get_RangeText(range)
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
			return range.htmlText;
		}
		else
		{
			var clonedSelection = range.cloneContents();
			var div = document.createElement('div');
			div.appendChild(clonedSelection);
			return div.innerHTML;
		}
	}
	
	function Get_RangeTextContent(range)
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
			return range.text;
		}
		else
		{
			var clonedSelection = range.cloneContents();
			var div = document.createElement('div');
			div.appendChild(clonedSelection);
			return div.textContent;
		}
	}
	
	function Set_RangeText(range,text)
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
			try
			{
				range.pasteHTML(text);
				return true;
			}
			catch(e)
			{
				return false;
			}
		}
		else
		{
			range.deleteContents();
			var documentFragment = range.createContextualFragment(text);
			range.insertNode(documentFragment);
			range.collapse(false);
			return true;
		}			
	}

	function Range_GetParentElement(range)//CC
	{
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
			if(!editdoc)
			{
				var	editorTemp=window.document.getElementById(Editor_ClientID);
				editdoc=editorTemp.GetDocument();
			}
			if(editdoc.selection.type=="Control")
				return range.item(0);	
			else 
				return range.parentElement();	
		}
		
		var so=range.startOffset;
		var eo=range.endOffset;
		var sc=range.startContainer;
		var ec=range.endContainer;
		
		if(so==eo&&sc==ec)
		{
			if(sc.nodeType==3)//TextNode
			{	
				return sc.parentNode;
			}
			return sc;
		}
		
		if(eo-so==1&&sc==ec)
			if(!sc.childNodes[so])
				return sc.parentNode;
			else
				return sc.childNodes[so];
		
		var arr1=[];
		for(var snode=sc;snode!=null;snode=snode.parentNode)
			arr1[arr1.length]=snode;
		arr1.reverse();
		
		var arr2=[];
		for(var snode=sc;snode!=null;snode=snode.parentNode)
			arr2[arr2.length]=snode;
		arr2.reverse();
		
		var pn=null;
		var len=Math.min(arr1.length,arr2.length);
		for(var i=0;i<len;i++)
		{
			if(arr1[i]==arr2[i])
				pn=arr1[i];
			else
				break;
		}
		if(pn.nodeType==3)
			pn=pn.parentNode;
			
		return pn;
	}

//=================   End of : Text Range  =========================	



//=================   Node  =========================	
function getInnerText(node)//CC 
{
	var str = "";
	if(navigator.appName.lastIndexOf("Microsoft")!=-1)
	{
		str=node.innerText;
	}
	else
	{
		str=node.textContent;
	}
	return str;
}
function getInnerHTMLCC(node)//CC 
{
	var str = "";
	for (var i=0; i<node.childNodes.length; i++)
		str += getOuterHTMLCC(node.childNodes.item(i));
	return str;
}

function getOuterHTMLCC(node) //CC
{
	var str = "";

	switch (node.nodeType) 
	{
		case 1: // ELEMENT_NODE
			str += "<" + node.nodeName;
			for (var i=0; i<node.attributes.length; i++) 
			{
				if (node.attributes.item(i).nodeValue != null) 
				{
					str += " "
					str += node.attributes.item(i).nodeName;
					str += "=\"";
					str += node.attributes.item(i).nodeValue;
					str += "\"";
				}
			}

			if (node.childNodes.length == 0 && leafElems[node.nodeName])
				str += ">";
			else 
			{
				str += ">";
				str += getInnerHTML(node);
				str += "<" + node.nodeName + ">"
			}
			break;
			
		case 3:	
			str += node.nodeValue;
			break;
		
		case 4: 
			str += "<![CDATA[" + node.nodeValue + "]]>";
			break;
				
		case 5: 
			str += "&" + node.nodeName + ";"
			break;

		case 8: 
			str += "<!--" + node.nodeValue + "-->"
			break;
	}

	return str;
}


var _emptyTags = {"IMG":true,"BR":true,"INPUT": true,"META":true,"LINK":true,"PARAM": true,"HR":true};

function getOuterHTML(node)
{
	if(navigator.appName.lastIndexOf("Microsoft")!=-1)
	{
		return node.outerHTML;
	}
	else
	{
		var div = document.createElement('div');
		var CopyOfNode=node.cloneNode(true);
		div.appendChild(CopyOfNode);
		return div.innerHTML;
		
		
		var attrs = node.attributes;

		var str = "<" + node.tagName;
		/*
		if(node.className!="")
		{
			str += " " + "class" + "=\"" + node.className + "\"";
		}
		
		if(node.id!="")
		{
			str += " " + "id" + "=\"" + node.id + "\"";
		}
		*/
		try
		{
			for (var i = 0; i < attrs.length; i++)
			{
				/*
				if(attrs[i].name.toLowerCase()!='class' && attrs[i].name!='id')
				{
					str += " " + attrs[i].name + "=\"" + attrs[i].value + "\"";
				}
				*/
				str += " " + attrs[i].name + "=\"" + attrs[i].value + "\"";
			} 
		}
		catch(ex)
		{}
	    
		if (_emptyTags[node.tagName])
			return str + ">";

		return str + ">" + node.innerHTML + "</" + node.tagName + ">";
	}
}

function setOuterHTML(node,sHTML) 
{
   if(navigator.appName.lastIndexOf("Microsoft")!=-1)
   {
		node.outerHTML=sHTML;
   }
   else
   {
		
		var r = node.ownerDocument.createRange();
		r.setStartBefore(node);
		var df = r.createContextualFragment(sHTML);
		node.parentNode.replaceChild(df, node);
	}
}

function setNodeAttribute(node,attName,attValue)
{
	if(!node.getAttribute(attName)) //if attribute not available
	{
		if(navigator.appName.lastIndexOf("Microsoft")==-1)
		{
			var headHtml="<"+node.tagName;
			for( var i = 0; i<node.attributes.length;  i++ )
			{
				if(node.attributes[i].specified==true)
					headHtml += ' '+ node.attributes[i].name + '="'+ node.attributes[i].value + '"';
			}
			headHtml +=' '+attName+'="'+ attValue +'">'+node.innerHTML+'</p>';
			setOuterHTML(node,headHtml);
		}	
		else
		{
			node.setAttribute(attName,attValue);
		}
	}
	else //ID available
	{
		node.setAttribute(attName,attValue);
	}

}


function ContentExplorerSelection(str,editorObj)
{
	try
	{
		
		if(typeof(editorObj)=='undefined')
		{
			editorObj = window.document.getElementById(Editor_ClientID);
		}
		var tmp_editdoc;
		var tmp_editwin;
	    
		tmp_editdoc= editorObj.GetDocument();
		tmp_editwin=editorObj.GetWindow();
		var objToSelect=tmp_editdoc.getElementById(str);
		SetSelectionByNode(objToSelect,true,editorObj);			
	}
	catch(e)
	{}
}

function SetSelectionByNode(node,isView,editorObj,isSelected)
{
	
	if(typeof(editorObj)=='undefined')
    {
		editorObj = window.document.getElementById(Editor_ClientID);
    }
    if(typeof(isSelected)=='undefined')
		isSelected=true;
		
    var tmp_editdoc;
    var tmp_editwin;
    
	tmp_editdoc= editorObj.GetDocument();
	tmp_editwin=editorObj.GetWindow();
	var TxtRange;
	if (!isView)
		isView=true;
	if(navigator.appName.lastIndexOf("Microsoft")!=-1)
	{
		if(node.innerText!="")
		{
			TxtRange = tmp_editdoc.body.createTextRange();
			TxtRange.moveEnd("textedit");
			TxtRange.moveToElementText(node);
			if(isSelected)
				TxtRange.select();
		}
	}
	else
	{
		var sel=tmp_editwin.getSelection();
		//Safari
		if(sel.setBaseAndExtent)
			sel.setBaseAndExtent(node,0,node,child_nodes(node).length || 1);
		else
			sel.selectAllChildren(node);
			
		TxtRange=sel.getRangeAt(0);
		if(!isSelected)
			TxtRange.collapse(true);
	}
	if(isView==true)
	{
		var objPos=findPos(node);
		tmp_editwin.scrollTo(objPos[0],objPos[1]);
	}
	return TxtRange;
}

function findPos(node)
{
	var curleft = curtop = 0;
	if (node.offsetParent)
	{
		curleft = node.offsetLeft;
		curtop = node.offsetTop;
		while (node = node.offsetParent)
		{
			curleft += node.offsetLeft;
			curtop += node.offsetTop;
		}
	}
	return [curleft,curtop];
}
//=================   Node  =========================	






//============================================================================
//				Nodes methods (firstChild,lastChild,childNodes
//			  Gecko (whitespace/tab/enter) ignored function for DOM
//============================================================================

/**
 * Throughout, whitespace is defined as one of the characters
 *  "\t" TAB \u0009
 *  "\n" LF  \u000A
 *  "\r" CR  \u000D
 *  " "  SPC \u0020
 *
 * This does not use Javascript's "\s" because that includes non-breaking
 * spaces (and also some other characters).
 */


/**
 * Determine whether a node's text content is entirely whitespace.
 *
 * @param nod  A node implementing the |CharacterData| interface (i.e.,
 *             a |Text|, |Comment|, or |CDATASection| node
 * @return     True if all of the text content of |nod| is whitespace,
 *             otherwise false.
 */
function is_all_ws( nod )
{
  // Use ECMA-262 Edition 3 String and RegExp features
  return !(/[^\t\n\r ]/.test(nod.data));
}


/**
 * Determine if a node should be ignored by the iterator functions.
 *
 * @param nod  An object implementing the DOM1 |Node| interface.
 * @return     true if the node is:
 *                1) A |Text| node that is all whitespace
 *                2) A |Comment| node
 *             and otherwise false.
 */

function is_ignorable( nod )
{
  return ( nod.nodeType == 8) || // A comment node
         ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
}

/**
 * Version of |previousSibling| that skips nodes that are entirely
 * whitespace or comments.  (Normally |previousSibling| is a property
 * of all DOM nodes that gives the sibling node, the node that is
 * a child of the same parent, that occurs immediately before the
 * reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest previous sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_before( sib )
{
  while ((sib = sib.previousSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/**
 * Version of |nextSibling| that skips nodes that are entirely
 * whitespace or comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest next sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_after( sib )
{
  while ((sib = sib.nextSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/**
 * Version of |lastChild| that skips nodes that are entirely
 * whitespace or comments.  (Normally |lastChild| is a property
 * of all DOM nodes that gives the last of the nodes contained
 * directly in the reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The last child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function last_child( par )
{
  var res=par.lastChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.previousSibling;
  }
  return null;
}

/**
 * Version of |firstChild| that skips nodes that are entirely
 * whitespace and comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The first child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function first_child( par )
{
  var res=par.firstChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.nextSibling;
  }
  return null;
}

/**
 * Version of |data| that doesn't include whitespace at the beginning
 * and end and normalizes all whitespace to a single space.  (Normally
 * |data| is a property of text nodes that gives the text of the node.)
 *
 * @param txt  The text node whose data should be returned
 * @return     A string giving the contents of the text node with
 *             whitespace collapsed.
 */
function data_of( txt )
{
  var data = txt.data;
  // Use ECMA-262 Edition 3 String and RegExp features
  data = data.replace(/[\t\n\r ]+/g, " ");
  if (data.charAt(0) == " ")
    data = data.substring(1, data.length);
  if (data.charAt(data.length - 1) == " ")
    data = data.substring(0, data.length - 1);
  return data;
}

function child_nodes(parNode)
{
	var Nodes=[];
	if(!parNode)
		return;
		
	var cur = first_child(parNode);
	while (cur)
	{
		Nodes[Nodes.length]=cur;
		cur = node_after(cur);
	}
	return Nodes;
}

/* Changed by Archana on 23-08-2007
function AllowCitation(editor,TFR)
{
	try
	{
		TFR=TFR.toLowerCase();
		var ele=Selection_GetParentElement(editor);
		
		if(CitationStyles[ele.className.toLowerCase()])
		{
			var val=CitationStyles[ele.className.toLowerCase()].toLowerCase();		
			if(val.lastIndexOf(TFR)!=-1)
				return true;
			else
				return false;
		}
		else
			return false;	
	}
	catch(ex)
	{}
}

*/

function AllowCitation(editor,TFR)
{
	try
	{
		TFR=TFR.toLowerCase();
		var ele=Selection_GetParentElement(editor);
			if(ele.className.toUpperCase()!="FIGCIT" && ele.className.toUpperCase()!="TBCIT" && ele.className.toUpperCase()!="BIBCIT" && ele.className.toUpperCase()!="FTNCIT")
			{
				while(ele.tagName.toUpperCase()!="P" && ele.tagName.toUpperCase()!="BODY")
					ele=ele.parentNode;		
			}	
			
		if(typeof(CitationStyles[ele.className.toLowerCase()])=="undefined")
		{
			return true;
		}
		else
		{
			var val=CitationStyles[ele.className.toLowerCase()].toLowerCase();		
			if(val.lastIndexOf(TFR)!=-1)
				return false;
			else
				return true;
		}
				
	}
	catch(ex)
	{}
}

//-------------------------------------------------------Jaffe Style
function SearchStartDIV_Procedure(range,ProcClass)
{
	var tempParent=Range_GetParentElement(range);
	while(tempParent.className!=ProcClass)
	{
		if(tempParent.tagName=="BODY" || tempParent.tagName=="FORM")
			return;
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
			tempParent=tempParent.parentNode;
			//tempP=tempP.parentElement();
		else
			tempParent=tempParent.parentNode;
	}
	return tempParent;
}
function FindReferenceExist(editor)
{

	var range=Get_Range(editor);
	var checkRef=false;
	var ref_list;
	if(!editdoc)
		editdoc=editor.GetDocument();
	var topProcDIV=SearchStartDIV_Procedure(range,"protected");
	if(!topProcDIV)
		return false;
	var elementNode =SearchElements("ol","references",topProcDIV)[0];
	if(!elementNode)
		checkRef=false;
	else{				
		ref_list=child_nodes(elementNode); 
		if(ref_list.length>0) // search reference is found
			checkRef=true;
	}
	return checkRef;
}
function FindCitationAllowedCheck(editor,imgBtnName)
{
	var allowC="TFRN";
	var retVar;
	if(imgBtnName.toLowerCase().indexOf("reference.gif")>-1)
		allowC="R";
	if(imgBtnName.toLowerCase().indexOf("addtable.gif")>-1)
		allowC="T";
	if(imgBtnName.toLowerCase().indexOf("figure.gif")>-1)
		allowC="F";	
	if(imgBtnName.toLowerCase().indexOf("footnote.gif")>-1)
		allowC="N";	
	retVar=AllowCitation(editor,allowC);
	return retVar;
}

//------------------------END-------------------------------Jaffe Style

//--------------------------New
function ToolbarButtonStateChange(editor,imgNameList)
{
	var imageList;
	if(navigator.appName.lastIndexOf("Microsoft")!=-1)
	{
		imageList=editor.all.tags("IMG");
	}
	else
	{
		imageList=editor.getElementsByTagName("IMG");
	}

	var len=imageList.length;
	if(!imgNameList)
		imgNameList="reference.gif,addtable.gif,figure.gif,accept.gif,reject.gif,footnote.gif";
	var imgNameListArr=imgNameList.split(",");
	var lenInnerList=imgNameListArr.length;
	var checkRef=false;
	for(var i=0;i<len;i++)
	{
		var img=imageList[i];
		//reference
		for(var j=0;j<lenInnerList;j++)
		{
			if(img.src.toLowerCase().indexOf(imgNameListArr[j])>-1 || img.src.toLowerCase().indexOf("grey_"+imgNameListArr[j])>-1)
			{
				if(img.src.toLowerCase().indexOf("reference.gif")>-1 || img.src.toLowerCase().indexOf("addtable.gif")>-1 || img.src.toLowerCase().indexOf("figure.gif")>-1 || img.src.toLowerCase().indexOf("footnote.gif")>-1)
				{
					checkRef=FindCitationAllowedCheck(editor,img.src);
					/*
					if(checkRef && img.src.toLowerCase().indexOf("reference.gif")>-1)
						checkRef=FindReferenceExist(editor);
					*/		// Only for Jaffe
					
				}
				if(img.src.toLowerCase().indexOf("accept.gif")>-1 || img.src.toLowerCase().indexOf("reject.gif")>-1)
				{
					checkRef=IsAcceptRejectClass(editor);
				}
				ToolBarEnableDisable(img,checkRef);
			}
		}
	}			
}
///////////////////////////////////////////
function ToolBarEnableDisable(Img,Enable)
{
	var buttonImgName=Img.src;
	buttonImgName=buttonImgName.toLowerCase().substring(buttonImgName.lastIndexOf("/")+1);
	var imgPath="../CuteSoft_Client/CuteEditor/Themes/Custom/images/";
	var imgAttribute;
	var imgAttribute1;
	var disableAttText="return false;//";
	if(navigator.appName.lastIndexOf("Microsoft")!=-1)
	{
		var disableAttText1="grey_";
		imgAttribute=Img.attributes["src"].value;
		imgAttribute1=Img.attributes["onclick"].value;
		var aaa;
		if(Enable)
		{
			if(imgAttribute.indexOf(disableAttText1)>-1)
			{
				imgAttribute1=imgAttribute1.replace(disableAttText,"");
				Img.attributes["onclick"].value=imgAttribute1;

				imgAttribute1=imgAttribute1.replace("(","");
				imgAttribute1=imgAttribute1.replace(")","");
				imgAttribute1=imgAttribute1.replace("return","");
				aaa=eval(imgAttribute1);

				Img.detachEvent("onclick",aaa);
				Img.attachEvent("onclick",aaa);

				buttonImgName=buttonImgName.replace("grey_","");				
				Img.attributes["src"].value=imgPath+buttonImgName;
			}
			
		}
		else
		{
			if(imgAttribute.indexOf(disableAttText1)==-1)
			{
				Img.attributes["onclick"].value=disableAttText+imgAttribute1;
				
				imgAttribute1=imgAttribute1.replace("(","");
				imgAttribute1=imgAttribute1.replace(")","");
				imgAttribute1=imgAttribute1.replace("return","");
				aaa=eval(imgAttribute1);
				
				Img.detachEvent("onclick",aaa);
				Img.detachEvent("onclick",aaa);

				Img.attributes["src"].value=imgPath+"grey_"+buttonImgName;
			}
		}
	}
	else
	{
		imgAttribute=Img.getAttribute("onclick");
		if(Enable)
		{
			if(imgAttribute.indexOf(disableAttText)>-1)
			{
				imgAttribute=imgAttribute.replace(disableAttText,"");
				Img.setAttribute("onclick",imgAttribute);
				buttonImgName=buttonImgName.replace("grey_","");
				Img.setAttribute("src",imgPath+buttonImgName);
			}
			
		}
		else
		{
			if(imgAttribute.indexOf(disableAttText)==-1)
			{
				Img.setAttribute("onclick",disableAttText+imgAttribute);
				Img.setAttribute("src",imgPath+"grey_"+buttonImgName);
			}
		}
	}
}
/////////////////////////////////////////

// Context Menu for Track changes
var MoveDirection="NEXT";
var posEnd="";
function IsAcceptRejectClass(editorTemp,returnID)
{
	if(!editorTemp)
		editorTemp=window.document.getElementById(Editor_ClientID);
	var rng=Get_Range(editorTemp);
	var rngPar=Range_GetParentElement(rng);
	var retVal=false;
	var retObjVal;
	while(rngPar.tagName!="P")
	{	
		if(rngPar.tagName.toLowerCase()=="body" || rngPar.tagName.toLowerCase()=="form")
		{
			return false;
		}
		/*
		if(rngPar.tagName.toLowerCase()=="span" && (rngPar.className.toLowerCase()=="hdadded" || rngPar.className.toLowerCase()=="hddeleted"))		
			if(rngPar.parentNode.tagName.toLowerCase()=="a" && rngPar.parentNode.name.toLowerCase()=="diff")
			{
				retVal=true;
				break;
			}
		rngPar=rngPar.parentNode;
		*/
		
		if(rngPar.tagName.toLowerCase()=="span" && (rngPar.className.toLowerCase()=="hdadded" || rngPar.className.toLowerCase()=="hddeleted"))		
		{
			retVal=true;
			break;
		}
		if(rngPar.tagName.toLowerCase()=="a" && rngPar.name.toLowerCase()=="diff")
		{
			rngPar=CheckForChildSpan(rngPar);
			retVal=true;
			break;
		}

		rngPar=rngPar.parentNode;
	}
	if(returnID)
		return rngPar;
	else
		return retVal;
}

function CheckForChildSpan(objAnchor)
{
	var childSpan=SearchElements("span","HDAdded",objAnchor);
	if(childSpan.length>0)
		return childSpan[0];

	childSpan=SearchElements("span","HDDeleted",objAnchor);
	if(childSpan.length>0)
		return childSpan[0];
}

function HandleMenu_Accept()
{
	var obj=IsAcceptRejectClass(null,true);
	
	/////Next Change Selection	
	var tmp_editor=window.document.getElementById(Editor_ClientID);
	var nextObj=getTrackNextPreviousNode(MoveDirection,tmp_editor)
		
	var objParent=obj.parentNode;
	if(obj.className.toLowerCase()=="hdadded")
		setOuterHTML(obj,obj.innerHTML);
	else if (obj.className.toLowerCase()=="hddeleted")
		setOuterHTML(obj,"");

	CheckForAnchorRemoval(objParent);

	g_Doc_Edited=true;//Document Edited	
	
	if(nextObj)
		SetSelectionByNode(nextObj,true,tmp_editor);
	else
		alert("PowerXEditor reached at "+posEnd+" of document.");	
}
function CheckForAnchorRemoval(objAnchor)
{
	//For Aptara check: No need to anchor removal
	if(g_matchType!="html match")
		return;	

	var childSpan=SearchElements("span","HDAdded",objAnchor);
	if(childSpan.length>0)
		return;

	childSpan=SearchElements("span","HDDeleted",objAnchor);
	if(childSpan.length>0)
		return;

	setOuterHTML(objAnchor,objAnchor.innerHTML);
}

function HandleMenu_Reject()
{
	var obj=IsAcceptRejectClass(null,true);
	
	/////Next Change Selection	
	var tmp_editor=window.document.getElementById(Editor_ClientID);
	var nextObj=getTrackNextPreviousNode(MoveDirection,tmp_editor)
		
	var objParent=obj.parentNode;
	if(obj.className.toLowerCase()=="hdadded")
		setOuterHTML(obj,"");			
	else if (obj.className.toLowerCase()=="hddeleted")
		setOuterHTML(obj,obj.innerHTML);
	CheckForAnchorRemoval(objParent);
		
	g_Doc_Edited=true;//Document Edited
	
			
	if(nextObj)
		SetSelectionByNode(nextObj,true,tmp_editor);
	else
		alert("PowerXEditor reached at "+posEnd+" of document.");
}

//====================== Track Changes Next/Previous 
function TrackChangesListLoad(tmp_editdoc)
{
	var TrackList=[];
	if(g_matchType=="html match")
	{
		var trList=tmp_editdoc.getElementsByName("diff");
		for(var i=0;i<trList.length;i++)
		{
			var obj={};
			obj.TrackID=trList[i].id;
			obj.TrackItem=trList[i];
			obj.TrackPosition=findPos(trList[i]);
			TrackList[i]=obj;
		}
	}
	else
	{
		var trList=tmp_editdoc.getElementsByTagName("span");
		var j=0;
		for(var i=0;i<trList.length;i++)
		{
			if(trList[i].className!=null)
			{
				if(trList[i].className.toLowerCase()=="hdadded" || trList[i].className.toLowerCase()=="hddeleted")
				{
					var obj={};
					obj.TrackID=j+1;
					obj.TrackItem=trList[i];
					obj.TrackPosition=findPos(trList[i]);
					TrackList[j++]=obj;
				}
			}
		}
	
	}
	return TrackList;
}			


function getCursorPosition(editor1)
{
	var ele=SetBookmark(editor1);
	var pos=findPos(ele);
	RemoveBookmark(editor1);
	return pos;
}		
	
function TrackNextPreviousSelect(moveType,tmp_editor)
{
	var	tmp_editdoc = tmp_editor.GetDocument();
	//var tmp_editwin = tmp_editor.GetWindow();
	var TrackList=TrackChangesListLoad(tmp_editdoc);
	var rngMain=Get_Range(editor1);
	var rngParent=Range_GetParentElement(rngMain);
	var TrackNode;
	if(rngParent.tagName.toLowerCase()=="body" || rngParent.tagName.toLowerCase()=="form")
	{
		if(TrackList.length>0)
		{
			TrackNode=TrackList[0].TrackItem;
			SetSelectionByNode(TrackNode,true,tmp_editor);
		}
		ToolbarButtonStateChange(tmp_editor)
		return;
	}
	//var rngParentPos=findPos(rngParent);
	var rngParentPos;
	//If No Track selected then find actual position of cursor 
	if(Get_RangeTextContent(rngMain)=="")
	//If No Track selected then find range parent element; 
		rngParentPos=getCursorPosition(tmp_editor);
	else
		rngParentPos=findPos(rngParent);
	
	if(moveType=="NEXT")
	{
		posEnd="end";
		for(var i=0;i<TrackList.length;i++)
		{
			if(rngParentPos[1]==TrackList[i].TrackPosition[1])
			{
				if(rngParentPos[0]<TrackList[i].TrackPosition[0])
				{
					TrackNode=TrackList[i].TrackItem;
					break;
				}
			}
			else if(rngParentPos[1]<TrackList[i].TrackPosition[1])
			{
				TrackNode=TrackList[i].TrackItem;
				break;
			}
		}		
	}
	else if(moveType=="PREVIOUS")
	{
		posEnd="begining";
		for(var i=TrackList.length-1;i>=0;i--)
		{
			if(rngParentPos[1]==TrackList[i].TrackPosition[1])
			{
				if(rngParentPos[0]>TrackList[i].TrackPosition[0])
				{
					TrackNode=TrackList[i].TrackItem;
					break;
				}
			}
			else if(rngParentPos[1]>TrackList[i].TrackPosition[1])
			{
				TrackNode=TrackList[i].TrackItem;
				break;
			}
		}
	}
	if(TrackNode)
	{
		SetSelectionByNode(TrackNode,true,tmp_editor);
		ToolbarButtonStateChange(tmp_editor)
	}
	else
		alert("PowerXEditor reached at "+posEnd+" of document.");
	MoveDirection=moveType;
}

function getTrackNextPreviousNode(moveType,tmp_editor)
{
	var	tmp_editdoc = tmp_editor.GetDocument();
	//var tmp_editwin = tmp_editor.GetWindow();
	var TrackList=TrackChangesListLoad(tmp_editdoc);
	var rngMain=Get_Range(editor1);
	var rngParent=Range_GetParentElement(rngMain);
	var TrackNode;
	if(rngParent.tagName.toLowerCase()=="body" || rngParent.tagName.toLowerCase()=="form")
	{
		if(TrackList.length>0)
		{
			TrackNode=TrackList[0].TrackItem;
			SetSelectionByNode(TrackNode,true,tmp_editor);
		}
		ToolbarButtonStateChange(tmp_editor)
		return;
	}
	//var rngParentPos=findPos(rngParent);
	var rngParentPos;
	//If No Track selected then find actual position of cursor 
	if(Get_RangeTextContent(rngMain)=="")
	//If No Track selected then find range parent element; 
		rngParentPos=getCursorPosition(tmp_editor);
	else
		rngParentPos=findPos(rngParent);
	
	if(moveType=="NEXT")
	{
		posEnd="end";
		for(var i=0;i<TrackList.length;i++)
		{
			if(rngParentPos[1]==TrackList[i].TrackPosition[1])
			{
				if(rngParentPos[0]<TrackList[i].TrackPosition[0])
				{
					TrackNode=TrackList[i].TrackItem;
					//****if(rngParent.parentNode.id.toLowerCase()==TrackNode.id.toLowerCase())
					//****		continue;
					//For Aptara check: No id is given for span
					if(rngParent==TrackNode)
						continue;
					break;
				}
			}
			else if(rngParentPos[1]<TrackList[i].TrackPosition[1])
			{
				TrackNode=TrackList[i].TrackItem;
				break;
			}
		}		
	}
	else if(moveType=="PREVIOUS")
	{
		posEnd="begining";
		for(var i=TrackList.length-1;i>=0;i--)
		{
			if(rngParentPos[1]==TrackList[i].TrackPosition[1])
			{
				if(rngParentPos[0]>TrackList[i].TrackPosition[0])
				{
					TrackNode=TrackList[i].TrackItem;
					//****if(rngParent.parentNode.id.toLowerCase()==TrackNode.id.toLowerCase())
					//****	continue;
					//For Aptara check: No id is given for span			
					if(rngParent==TrackNode)
						continue;
					break;
				}
			}
			else if(rngParentPos[1]>TrackList[i].TrackPosition[1])
			{
				TrackNode=TrackList[i].TrackItem;
				break;
			}
		}
	}
	return TrackNode;
	MoveDirection=moveType;
}

// Local Save Calling in PowerXEditor.asx javascript    // Add into module.js

function LocalSave(editor1)
{
	try
	{
		var html=editor1.getHTML();
		var encryptedHTM="";
		/*for(var i=0;i<html.length-1;i++)
		{	
			var strChar=html.substring(i,1);
			var acNum=strChar.charCodeAt(0);
			if((acNum+112)<=255)
				acNum=acNum+112;		
			encryptedHTM=encryptedHTM+(String.fromCharCode(acNum));
		}*/
		encryptedHTM=html;
		if(navigator.appName.lastIndexOf("Microsoft")!=-1)
		{
			var win=window.open('about:blank','','height=50,width=50');
			win.moveTo(0,0);
			win.document.write(encryptedHTM);
			win.document.execCommand("saveas",true,"PXELocalChapter.htm");
			win.close();
		}
		else
		{
			WriteFileInFF(encryptedHTM);
		
		}
	}
	catch(ex)
	{
		alert(ex.message);
	}
}

function WriteFileInFF(output) 
{
	//var savefile = "PXELocalChapter.htm";
	
	try 
	{
		//about:config
		//signed.applets.codebase_principal_support=true
		//alert(netscape.security.PrivilegeManager.isPrivilegeEnabled("UniversalXPConnect"));
		//user_pref("signed.applets.codebase_principal_support", true);			
	} catch (e) 
	{
		alert("Permission to save file was denied.");
	}
	// get the path to the user's home (profile) directory
	/*const DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1","nsIProperties");
	try { 
		path=(new DIR_SERVICE()).get("ProfD", Components.interfaces.nsIFile).path; 
	} catch (e) {
		alert("error");
	}
	// determine the file-separator
	if (path.search(/\\/) != -1) 
	{
		path = path + "\\";
	} else 
	{
		path = path + "/";
	}
	savefile = path+savefile;*/
	

	var savefile = "c:\\PXELocalChapter.htm";
	try 
	{
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	} catch (e) 
	{
		alert("Permission to save file was denied.");
	}
	var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
	file.initWithPath(savefile);
	if ( file.exists() == false ) {
		alert( "Creating file... " );
		file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
	}
	var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance( Components.interfaces.nsIFileOutputStream );
	/* Open flags 
	#define PR_RDONLY       0x01
	#define PR_WRONLY       0x02
	#define PR_RDWR         0x04
	#define PR_CREATE_FILE  0x08
	#define PR_APPEND      0x10
	#define PR_TRUNCATE     0x20
	#define PR_SYNC         0x40
	#define PR_EXCL         0x80
	*/
	/*
	** File modes ....
	**
	** CAVEAT: 'mode' is currently only applicable on UNIX platforms.
	** The 'mode' argument may be ignored by PR_Open on other platforms.
	**
	**   00400   Read by owner.
	**   00200   Write by owner.
	**   00100   Execute (search if a directory) by owner.
	**   00040   Read by group.
	**   00020   Write by group.
	**   00010   Execute by group.
	**   00004   Read by others.
	**   00002   Write by others
	**   00001   Execute by others.
	**
	*/
	outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
	//var output = "File handling in Javascript";
	var result = outputStream.write( output, output.length );
	outputStream.close();
	//alert("file saved"+"\n"+savefile);
}
/*/////////////////////////////////////////
		Context menu property   //sachin tyagi
		//Modified By Arun Tiwary
/////////////////////////////////////////*/
var PropertyMenuItem;
function Menu_property(menuItem)
{
	/*var height=610; // IE PC
	var width=450; // IE PC
	
	if(window.navigator.platform.toLowerCase().indexOf("mac")!=-1) 
	{
		height=height;
		width=width+12;					
	}
	else
	{
		if(navigator.appName.lastIndexOf("Microsoft")==-1)
		{
			height=height+85;
			width=width+15;					
		}
	}*/
	try
	{	
		GetChapterImageStatus();
		//var returnVal=showModalDialogBox("../Editor/PropertyPage.aspx?imageList="+imageList,menuItem,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;center:yes;help:no;status:no;resizable:no;scroll:no");	
		//var returnVal=showModalDialogBox("../Editor/PropertyPage.aspx",menuItem,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;center:yes;help:no;status:no;resizable:no;scroll:no");	
		//var returnVal=showModalDialogBox("../Editor/PropertyPage.aspx",menuItem,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;center:yes;help:no;status:no;resizable:no;scroll:no");	
		
		PropertyMenuItem=menuItem;
		
		PropertyPageCal();
	}
	catch(e)
	{
		//alert(e.message);
	}
}
 
 
 /*/////////////////////////////////////////
 check images are inserted for this chapter or not
		Sanjeev Kumar Verma 16th June 2008
/////////////////////////////////////////*/
 function GetChapterImageStatus()
 {
	try
	{
		if(document.getElementById('hdnChapterImageStatus').value!="updated")
		{
			// Start To find out all the figures into the chapter		
			if(!editor)
			{			
				editor = document.getElementById(Editor_ClientID); 			
			}
			var editdoc1=editor.GetDocument();
			
			var Figure = editdoc1.getElementsByTagName('img');
			var seprateArr;
			var imageList1="";
				
				for(var i = 0; i < Figure.length; i++)
				{
					if(Figure[i].attributes["latexeq"]!=null)
						continue;
					seprateArr=Figure[i].src.split("/");
					imageList1=imageList1 +seprateArr[seprateArr.length-1] + '|'
				}
			
				returnVal1 = AjaxCall("../Editor/SaveAjaxFigureName.aspx",null,null,imageList1);
				
				document.getElementById('hdnChapterImageStatus').value="updated";
			// End To find out all the figures into the chapter	
		}
			
	}
	catch(e)
	{
	}
 }
 
/* Table Functions */

var copyMultipleCellArr=[];
function copyMultipleCell(editor)	//Mukesh
{
	if(!editor)
	{			
		editor = document.getElementById(Editor_ClientID); 
	}
	
	var doc=editor.GetDocument();
	var win=editor.GetWindow();
	var range;
	copyMultipleCellArr=[];

	if (document.selection && document.selection.createRange) 
	{
		range = doc.selection.createRange();
		
		var StartRange=range.duplicate();
		StartRange.collapse();
		var sTD=SearchPreviousElement(StartRange.parentElement(),"TD");
		
		if(sTD.tagName!="TD")  
		{
			alert("Invalid selection.");
			return;
		}
			
		var EndRange=range.duplicate();
		EndRange.collapse(false);
		var lTD=SearchPreviousElement(EndRange.parentElement(),"TD");
		
		if(lTD.tagName!="TD")  
		{
			alert("Invalid selection.");
			return;
		}		
		var sTR=sTD.parentNode;
		if(sTR.tagName!="TR")
			return;
		
		var lTR=lTD.parentNode;
		if(lTR.tagName!="TR")
			return;
		
		//Check for Mulitple row selection
		if(sTR.rowIndex!=lTR.rowIndex)
		{
			alert("Multiple copy cell allowed for Sinle Row. ")
			return;
		}
		
		
		for(var i=sTD.cellIndex;i<=lTD.cellIndex;i++)
		{
			copyMultipleCellArr[copyMultipleCellArr.length]=sTR.cells[i].innerHTML;
		}	
		
	}
	else if (window.getSelection) 
	{
		var selection = win.getSelection();
		var range;
		var rowno=0;
		for(var i=1;i<=selection.rangeCount;i++)
		{
			range = selection.getRangeAt(i-1);
			var obj=range.startContainer;
			if(obj.tagName!="TR")
				obj=SearchPreviousElement(obj,"TD")	
			
			//Check for Mulitple row selection
			if(obj.tagName=="TR")
			{
				if(rowno==0)
					rowno=obj.rowIndex;
				else if(rowno>0)
				{
					if(rowno!=obj.rowIndex)
					{
						alert("Multiple delete cell allowed for Sinle Row. ")
						return ;
					}
				}
			}
			////
			
			if(obj.tagName=="TR")
				copyMultipleCellArr[copyMultipleCellArr.length]=obj.childNodes[range.startOffset].innerHTML;
			else if(obj.tagName=="TD")
				copyMultipleCellArr[copyMultipleCellArr.length]=obj.innerHTML;
		}
	}
}

function pasteMultipleCell(editor)	//Mukesh
{
	if(!editor)
	{			
		editor = document.getElementById(Editor_ClientID); 
	}
	var doc=editor.GetDocument();
	var win=editor.GetWindow();
	var range;
	
	if (document.selection && document.selection.createRange) 
	{
		range = doc.selection.createRange();
		
		var StartRange=range.duplicate();
		StartRange.collapse();
		var sTD=SearchPreviousElement(StartRange.parentElement(),"TD");
		
		if(sTD.tagName!="TD")  
		{
			alert("Invalid selection.");
			return;
		}
			
		var EndRange=range.duplicate();
		EndRange.collapse(false);
		var lTD=SearchPreviousElement(EndRange.parentElement(),"TD");
		if(lTD.tagName!="TD")  
		{
			alert("Invalid selection.");
			return;
		}		
		var sTR=sTD.parentNode;
		if(sTR.tagName!="TR")
			return;
		
		var lTR=lTD.parentNode;
		if(lTR.tagName!="TR")
			return;
		
		//Check for Mulitple row selection
		if(sTR.rowIndex!=lTR.rowIndex)
		{
			alert("Multiple paste cell allowed for Sinle Row. ")
			return;
		}
			
		var replacedCellCount=0;
		for(var i=sTD.cellIndex;i<=lTD.cellIndex;i++)
		{
			if(replacedCellCount>=copyMultipleCellArr.length)
				break;
				
			sTR.cells[i].innerHTML=copyMultipleCellArr[replacedCellCount];
			replacedCellCount++;
		}	
		
	}
	else if (window.getSelection) 
	{
		var selection = win.getSelection();
		var range;
		
		var replacedCellCount=0;
		var rowno=0;
		for(var i=1;i<=selection.rangeCount;i++)
		{
			if(replacedCellCount>=copyMultipleCellArr.length)
				break;
				
			range = selection.getRangeAt(i-1);
			var obj=range.startContainer;
			if(obj.tagName!="TR")
				obj=SearchPreviousElement(obj,"TD")	
			
			//Check for Mulitple row selection
			if(obj.tagName=="TR")
			{
				if(rowno==0)
					rowno=obj.rowIndex;
				else if(rowno>0)
				{
					if(rowno!=obj.rowIndex)
					{
						alert("Multiple delete cell allowed for Sinle Row. ")
						return ;
					}
				}
			}
			////
			
			if(obj.tagName=="TR")
				obj.childNodes[range.startOffset].innerHTML=copyMultipleCellArr[replacedCellCount];
			else if(obj.tagName=="TD")
				obj.innerHTML=copyMultipleCellArr[replacedCellCount];
				
			
			replacedCellCount++;
		}
	}
}


function deleteMultipleCell(editor)	//Mukesh
{
	if(!editor)
	{			
		editor = document.getElementById(Editor_ClientID); 
	}
	var doc=editor.GetDocument();
	var win=editor.GetWindow();
	var range;
	
	if (document.selection && document.selection.createRange) 
	{
		range = doc.selection.createRange();
		
		var StartRange=range.duplicate();
		StartRange.collapse();
		var sTD=SearchPreviousElement(StartRange.parentElement(),"TD");
		
		if(sTD.tagName!="TD")  
		{
			alert("Invalid selection.");
			return;
		}
			
		var EndRange=range.duplicate();
		EndRange.collapse(false);
		var lTD=SearchPreviousElement(EndRange.parentElement(),"TD");
		if(lTD.tagName!="TD")  
		{
			alert("Invalid selection.");
			return;
		}		
		var sTR=sTD.parentNode;
		if(sTR.tagName!="TR")
			return;
		
		var lTR=lTD.parentNode;
		if(lTR.tagName!="TR")
			return;
		
		//Check for Mulitple row selection
		if(sTR.rowIndex!=lTR.rowIndex)
		{
			alert("Multiple delete cell allowed for Sinle Row. ")
			return;
		}
		
		var replacedCellCount=0;
		var rowno=0;
		for(var i=sTD.cellIndex;i<=lTD.cellIndex;i++)
		{
			sTR.cells[i].innerHTML="";
		}	
		
	}
	else if (window.getSelection) 
	{
		var selection = win.getSelection();
		var range;
		
		var replacedCellCount=0;
		var rowno=0;
		for(var i=1;i<=selection.rangeCount;i++)
		{
			range = selection.getRangeAt(i-1);
			var obj=range.startContainer;
			if(obj.tagName!="TR")
				obj=SearchPreviousElement(obj,"TD")	
			
			//Check for Mulitple row selection
			if(obj.tagName=="TR")
			{
				if(rowno==0)
					rowno=obj.rowIndex;
				else if(rowno>0)
				{
					if(rowno!=obj.rowIndex)
					{
						alert("Multiple delete cell allowed for Sinle Row. ")
						return ;
					}
				}
			}
			////
			
			if(obj.tagName=="TR")
				obj.childNodes[range.startOffset].innerHTML="&nbsp;";
			else if(obj.tagName=="TD")
	
				obj.innerHTML="&nbsp;";
				
		}
	}
}

function SearchPreviousElement(currentNode,tagName)
{
	for(var e=currentNode;e!=null;e=e.parentNode)
	{
		if(e.parentNode != null)
		{
			if(e.tagName==tagName)
			return e;
		}
	}
	return null;
}

//Blocking F5 in PXE PC(FF & IE)
function attach_BlockKeyCode()
{ 
	try
	{
		setF5EventListener(disableFormKey);
	}
	catch(ex)
	{
		setTimeout("attach_BlockKeyCode()",1000);	
	}
}
setTimeout("attach_BlockKeyCode()",1000);

var version = navigator.appVersion; 
function disableFormKey (evt) 
{
	var blockkey=false;
	var event;
	if (evt) 
	{
		event = evt;
	}
	else if (window.event) 
	{
		event = window.event;
	}
	
	if (event) 
	{
		var keyCode = event.keyCode ? event.keyCode : event.charCode;
		if (keyCode == 116) 
		{
			blockkey=true;
		}
		if(!blockkey)
			return true;
			
		if ((version.indexOf('MSIE') != -1))
		{
			event.keyCode = 0;
			event.returnValue = false;
			return false;
		}
		else
		{
			if(event.charCode)
				return true;
			if (event.preventDefault) 
			{
				event.preventDefault();
			}
			return false;
		}
	}
}

function setF5EventListener (eventListener) {
   if (document.addEventListener) {
     document.addEventListener('keypress', eventListener, true);
   }
   else if (document.attachEvent) {
     document.attachEvent('onkeydown', eventListener);
   }
   else {
     document.onkeydown = eventListener;
   }

}

function unsetF5EventListener (eventListener) {
   if (document.removeEventListener) {
     document.removeEventListener('keypress', eventListener, true);
   }
   else if (document.detachEvent) {
     document.detachEvent('onkeydown', eventListener);
   }
   else {
     document.onkeydown = null;
   }
} 
//Blocking F5 in PXE PC(FF & IE)


function isInteger(s)
{
	try
	{
	  for (var i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);
         if (!isDigit(c))
          return false;
      }
      return true;
 	}catch(e){}
}

 function isDigit (c)
 {
     return ((c >= "0") && (c <= "9"))
 }
