/*	
	This script totals up the width of all images within a selection or in the current file.
	It will include image buttons (<input type=image..>) in the tally 

	This is of use when checking shim rows, troubleshooting layout issues etc..

	by Sam Foster (sam@sam-i-am.com)
	april 4th, 2000. 
	
*/
var app = Application;
var active = app.ActiveDocument;
var strReport ="no images found"; // default value for no matches

// re to match the img tags. (this gets changed later when matching the <input type=image...)
var re = /<img [^>]*width="*(\d+)"*[^>]*>/i; 

var resultRowLen = 30; // total character length of the report "table".

function Main() {

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


	// check IMG widths in this string (selection / file)
	// test first
	if(re.test(strText)) 
	{
		var strReport ="";
		var arImgWidths = totalWidths(strText);
	
		// build report and sum widths for total
		strReport += "IMG widths were: \n";
		for(i=0; i<arImgWidths.length; i++) {
			intTotalWidths+= parseInt(arImgWidths[i]);
			thisWidth = parseInt(arImgWidths[i]);
			thisWidth = formatResult(thisWidth);
			strReport += thisWidth + "\n";
		}
		strReport += formatResult("____") + "\n";
		strReport += formatResult(intTotalWidths) + "\n";
	}	

	// check INPUT TYPE = IMAGE widths
	// switch in the new regular expression
	re = /<input type="*image"* [^>]*width="*(\d+)"*[^>]*>/i; 

	// test first
	if(re.test(strText)) 
	{
		arImageTypeEqualsImageWidths = totalWidths(strText);
	
		// build report and sum widths for total
		strReport += "\nINPUT IMAGEs were found,\ntheir widths were: \n";
		for(i=0; i<arImageTypeEqualsImageWidths.length; i++) {
			intTotalWidths+= parseInt(arImageTypeEqualsImageWidths[i]);
			strReport += formatResult(arImageTypeEqualsImageWidths[i]) + "\n";
		}
		strReport += formatTotal("TOTAL:", intTotalWidths) + "\n";
	}

	// deliver report 
	alert(strReport);


}


function totalWidths(strText)
{
	var arWidths = new Array();
	for(i=0; re.test(strText); i++) {	
		arResults = re.exec(strText);

		// [0] holds the last matched characters
		strText= strText.substring(RegExp.lastIndex);
		arWidths[i]=arResults[1];
	}
	return arWidths;

}

// misc functions..
function alert(txt) {
	app.MessageBox(txt, "HomeSite: Total Image Widths",0);
}


function formatResult(thisInt) 
{
	strPaddedResult="";
	
	paddingLen = resultRowLen - thisInt.toString().length;
	for(s=0;s<paddingLen;s++) {strPaddedResult +="  "};
	strPaddedResult +=  thisInt;
	return strPaddedResult;
}

function formatTotal(strLabel, total)
{
	strTotal = "";
	for(f=0;f<paddingLen+3;f++) {strTotal +="_"};

	strFormattedTotal = formatResult(total);
	strTotal += "\n" + strLabel + strFormattedTotal.substring(strLabel.length * 2);
	return strTotal;
}
