
/**
 * @author      DucthuanX
 * @link        http://www.ducthuan.info
 * @copyright   (c) 2007 Nguyen Duc Thuan <me at ducthuan dot info>
 */
if ('undefined' == typeof Ducthuans) {
    alert('This component needs Ducthuans.js to work properly');
}

/**
 * Trim left string
 * @param {String} str
 */
String.prototype.ltrim = function(){
    return this.replace(/^\s*/, '');
};

/**
 * Trim right string
 * @param {String} str
 */
String.prototype.rtrim = function(){
    return this.replace(/\s*$/, '');
};

/**
 * Trim left and right string
 * @param {Object} str
 */
String.prototype.trim = function(){
    return this.ltrim().rtrim();
};

/**
 * Removes all spaces from string
 * @param {Object} str
 */
String.prototype.removeSpaces = function(){
    return this.replace(/\s+/g, '');
};

/**
 * Trims left and right string, replaces all spaces with one space
 * @param {Object} str
 */
String.prototype.trimAll = function(){
    return this.trim().replace(/\s+/g, ' ');
};

/**
 * Checks a string for valid email format
 * @param {String} str
 */
String.prototype.isEmail = function(){
    if (this.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/)) {
        return true;
    }
    else {
        return false;
    }
};

/**
 * Encode special HTML characters
 */
String.prototype.encodeHtml = function(){
    var str = this.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/"/g, '&quot;');
    str = str.replace(/&/g, '&amp;');
    
    return str;
};

/**
 * Decode special HTML characters
 */
String.prototype.decodeHtml = function(){
    var str = this.replace(/&lt;/g, '<');
    str = str.replace(/&gt;/g, '>');
    str = str.replace(/&quot;/g, '"');
    str = str.replace(/&amp;/g, '&');
    
    return str;
};

/**
 * Counts num. of words inside a stirng
 * @param {Boolean} isHtml is the string an HTML string or not?
 * @return {String}
 */
String.prototype.countWords = function(isHtml){
    var str = this;

    if (true == isHtml) {
        str = str.replace(/<[^>]+>/g, '');
    }
    
    str = str.replace(/[-']+/g, '').replace(/(&\w+?;|\d|\W|_)+/g, ' ').trimAll();

    if ('' == str) {
        return 0;
    }
    
    return str.split(' ').length;
};
