﻿/*
VERSION:
10/9/2009 1.0.3.1	Rewrote the method `truncate` to fix a bug where it was returning null if the string was smaller than the truncation.
12/8/2008	1.0.3	Added method `tag`. Added static methods trim, rtrim and ltrim.
9/2/2008	1.0.2	Fixed variable error in method `truncate`.
					Added static method `convert` to the String object.
7/1/2008	1.0.1	Added method `stripTags`.
			1.0.0	Begin versioning.
*/
/* STRING PROTOTYPE METHODS ----------------------------------------------- */
String.prototype.repeat = function(n) {
	if(isNaN(n) || n == null || n == '' || n <= 0) { return this; }
	n = Math.floor(n);
	var s = "";
	for(var i = n; i > 0; i--) { s += this; }
	return s;
};
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,'');
};
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,'');
};
String.prototype.stripTags = function(){
	return this.replace(/<(.|\n)+?>/g, '');
}
String.prototype.trim = function() {
	return this.replace(/^\s+/,'').replace(/\s+$/,'');
};
String.prototype.tag = function(tag, args) {
	var s = '<' + tag;
	switch(typeof(args)) {
		case 'object' :
			for(var arg in args) {
				s += ' ' + arg + '="' + htmEncode(args[arg]) + '"';
			}
			break;
		case 'string' :
			s += ' ' + args.trim();
			break;
	}
	return s + '>' + this + '</' + tag + '>';
}
String.prototype.truncate = function(n) {
	if(!isNaN(n) && n != '' && n < this.length) {
		return this.substring(0, n);
	}
	return this+'';
};

/* STRING STATIC METHODS ----------------------------------------------- */
String.convert = function(v) {
	//if v is anything other than a string or number, return empty string
	return typeof v != 'string' || typeof v != 'number' ? '' : v + '';
};
String.trim = function(s) {
	if(typeof s == 'string') {
		return s.replace(/^\s+/,'').replace(/\s+$/,'');
	} else {
		return s;
	}
};
String.rtrim = function(s) {
	if(typeof s == 'string') {
		return s.replace(/\s+$/,'');
	} else {
		return s;
	}
};
String.ltrim = function(s) {
	if(typeof s == 'string') {
		return s.replace(/^\s+/,'');
	} else {
		return s;
	}
};

/* UTILITY FUNCTIONS FOR STRINGS --------------------------------------------- */

function escapeHTML (str) {
	//from prototype.js
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};

