// by Johnson Cheung (http://www.wahon.net/~johnson/)
// Last update : April 26, 2007
// checked on
//	IE		: 5.0, 6.0
//	Mozilla	: 1.7
//	Netscape	: 4.78, 7.01
//	Opera	: 7.53, 9.20
//	Avant	: 9.02
//	Firefox	: 2.0.0.1

// Extension
// Implement the trim function to the String class
// Implement the replaceAll function to the String class
// Implement the clength function to count the byte length of a string
// Implement the cleftstring function to grab the substring by given a byte length

// String AddSpaceBetweenDblByte(String)
//	- Adding a space between all double bytes characters
// String formatCurrency(Double)
//	- Format the double into a currency display

function AddSpaceBetweenDblByte(sProStr) {
	var sRtnStr = "";
	var bPrevChi = false;
	for (iASBD=0;iASBD<sProStr.length;iASBD++) {
		iAsc = sProStr.charCodeAt(iASBD);
		if ((iAsc < 0) || (iAsc > 255)) {
			if (bPrevChi) sRtnStr = sRtnStr + " ";
			bPrevChi = true;
		} else {
			bPrevChi = false;
		}
		sRtnStr = sRtnStr + sProStr.charAt(iASBD);
	}
	return sRtnStr;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

String.prototype.replaceAll = function(sFind, sReplace) {
	var sResult = this;

	while (sResult.indexOf(sFind)>-1) {
		pos = sResult.indexOf(sFind);
		sResult = "" + (sResult.substring(0, pos) + sReplace + sResult.substring((pos + sFind.length), sResult.length));
	}

	return sResult;
}

String.prototype.ltrim = function() {
	var x=this;
	x=x.replace(/^\s*(.*)/, "$1");
	return x;
}
String.prototype.rtrim = function() {
	var x=this;
	sSpaceChe = /\s/;
	while (sSpaceChe.test(x.substring(x.length-1,x.length))) x = x.substring(0,x.length-1);

	return x;
}
String.prototype.trim = function() {
	return this.rtrim().ltrim();
}

String.prototype.clength = function() {
	var iL=0;
	var x=this;
	for (iCL=0;iCL<x.length;iCL++) {
		iAsc = x.charCodeAt(iCL);
		if ((iAsc < 0) || (iAsc > 255)) {
			iL += 2;
		} else {
			iL += 1;
		}
	}

	return iL;
}

String.prototype.cleftstring = function(iBytes) {
	var result="";
	var iL=0;
	var x=this;
	for (iCLS=0;iCLS<x.length;iCLS++) {
		iAsc = x.charCodeAt(iCLS);
		if ((iAsc < 0) || (iAsc > 255)) {
			iL += 2;
			if (iL <= iBytes) result += x.charAt(iCLS);
		} else {
			iL += 1;
			if (iL <= iBytes) result += x.charAt(iCLS);
		}
	}

	return result;
}
