/*	
	Script name: PowerPaste
	author: sam AT sam-i-am.com
	date:  Thursday, September 14, 2000

	Purpose: This script replaces key characters of the selection or current file into their escaped html character entities 
	indispensable for code listings
	
	Changes:	
	Monday, October 09, 2000
	- fixed restored selection so it works correctly over single line (oops :)

	Friday, October 06, 2000
	- fixed restored selection so it works correctly over multiple lines
	
	Thursday, September 14, 2000	
	- selection is restored to the length of the new escaped string
	
*/

var app = Application;
var active = app.ActiveDocument;

function Main() {

  // if there is a selection, use this 
  // otherwise use the whole active file
	var strText = app.ActiveDocument.SelText ? app.ActiveDocument.SelText : active.Text;
	var strScope = app.ActiveDocument.SelText ? "selection" : "file";

	// capture the position of the selection if there is one	
	if(strScope == "selection") var selectStart = active.SelStart;

	// local variable for the new string to be returned
	strNew = strText;
	
	// match and replace & for &amp;  
	  var matchAmp = /\&/gi;
	  strNew = strNew.replace(matchAmp,"&amp;");
	
	// match and replace < for &lt;  
	  var matchLt = /</gi;
	  strNew = strNew.replace(matchLt,"&lt;");
	
	// match and replace > for &gt;  
	  var matchGt = />/gi;
	  strNew = strNew.replace(matchGt,"&gt;");
	 
	// match and replace " for &quot;  
	  var matchQuot = /"/gi;
	  strNew = strNew.replace(matchQuot,"&quot;");

	eval("app.ActiveDocument." +  ((app.ActiveDocument.SelText) ? "SelText" : "Text") + "= strNew");
	
	// reset selection to encompass all the new string
	active.SelStart = selectStart;

	var matchEOL = /\n/gi;
	if (matchEOL.test(strNew)) // check for line endings 
	{
		intLineEndings = strNew.match(matchEOL).length;
		active.SelLength = Math.ceil(strNew.length - (intLineEndings+1 / 2));
	}
	else  // selection doesn't contain line endings, no need to adjust
	{
		active.SelLength = strNew.length;
	}
	
}
// misc functions..
function alert(txt) {
	app.MessageBox(txt, "HomeSite: Total Image Widths",0);
}
