


//conta caracteres
function countChar( string, ch ){
	c = 0;
	for( t = 0; t < string.length; t++ ){
		if( string.charAt(t) == ch )c++;
	}
	return c;
}


/*
 * JavaScriptUtil version 1.0
 *
 * The JavaScriptUtil is a set of misc functions used by the other scripts
 *
 * Author: Luis Fernando Planella Gonzalez (lfpg_dev@terra.com.br)
 */





///////////////////////////////////////////////////////////////////////////////
// Constants
var JST_CHARS_NUMBERS = "0123456789";
var JST_CHARS_LOWER = "abcdefghijklmnopqrstuvwxyzçáéíóúãõâêôà";
var JST_CHARS_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZÇÁÉÍÓÚÃÕÂÊÔÀ";
var JST_CHARS_LETTERS = JST_CHARS_LOWER + JST_CHARS_UPPER;
var JST_CHARS_ALPHA = JST_CHARS_LETTERS + JST_CHARS_NUMBERS;

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns the reference to the named object
 * Parameters:
 *     name: The object's name
 *     source: The object where to search the name
 * Returns: The reference, or null if not found
 */
function getObject(objectName, source) {
    if (isEmpty(objectName)) {
        return null;
    }
	if(isEmpty(source)) {
        source = self;
    }
    //Check if the source is a reference or a name
	if(source.substring) {
        //It's a name. Try to find it on a frame
    	sourceName = source;
    	source = self.frames[sourceName];
    	if (source == null) source = parent.frames[sourceName];
      	if (source == null) source = top.frames[sourceName];
    	if (source == null) source = getObject(sourceName);
    	if (source == null) return null;
    }
    //Get the document
	var document = (source.document) ? source.document : source;
    //Check the browser's type
    if (document.all) {
        //Internet Explorer
        if (source[objectName]) return source[objectName];
        if (document[objectName]) return document[objectName];
        if (document.all[objectName]) return document.all[objectName];
    } else {
        //Netscape
        if (document.getElementById(objectName)) return document.getElementById(objectName);
        var collection = document.getElementsByName(objectName);
        if (collection.length == 1) return collection[0];
        if (collection.length > 1) return collection;
    }
	return null;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns if the object is an instance of the specified class
 * Parameters:
 *     object: The object
 *     clazz: The class
 * Returns: Is the object an instance of the class?
 */
function isInstance(object, clazz) {
    if ((object == null) || (clazz == null)) {
        return false;
    }
    if (object instanceof clazz) {
        return true;
    }
    var base = object.base;
    while (base != null) {
        if (base == clazz) {
            return true;
        }
        base = base.base;
    }
	return false;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns true if the object value represents a true value
 * Parameters:
 *     object: The input object. It will be treated as a string.
 *        if the string starts with 1, Y, N or S, it will be 
 *        considered true. False otherwise.
 * Returns: The boolean value
 */
function booleanValue(object) {
    if (object == true || object == false) {
        return object;
    } else {
        object = String(object);
        if (object.length == 0) {
            return false;
        } else {
            var first = object.charAt(0).toUpperCase();
            var trueChars = "T1YS";
            return trueChars.indexOf(first) != -1
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns the index of the object in array, -1 if it's not there...
 * Parameters:
 *     object: The object to search
 *     array: The array where to search
 *     startingAt: The index where to start the search (optional)
 * Returns: The index
 */
function indexOf(object, array, startingAt) {
    if ((object == null) || !(array instanceof Array)) {
        return -1;
    }
    if (startingAt == null) {
        startingAt = 0;
    }
    for (var i = startingAt; i < array.length; i++) {
        if (array[i] == object) {
            return i;
        }
    }
    return -1;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns if the object is in the array
 * Parameters:
 *     object: The object to search
 *     array: The array where to search
 * Returns: Is the object in the array?
 */
function inArray(object, array) {
    return indexOf(object, array) >= 0;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Checks or unchecks all the checkboxes
 * Parameters:
 *     object: The reference for the checkbox or checkbox array.
 *     flag: If true, checks, otherwise, unchecks the checkboxes
 */
function checkAll(object, flag) {
	if (typeof(object) == "undefined") {
    	return;
    }
	if (typeof(object) == "object") {
    	if (object.type == "checkbox") {
        	object.checked = flag;
        } else {
        	for (i = 0; i < object.length; i++) {
            	object[i].checked = flag;
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Gets the value of an element
 * Parameters:
 *     object: The reference for the element
 * Returns: The value or an Array containing the values, if there's more than one
 */
function getValue(object) {
    //Validates the object
	if (object == null) {
    	return null;
    }

    //Select elements or array of input elements
	if (typeof(object.length) != "undefined") {
        var ret = new Array();
    	if (typeof(object.options)!="undefined") {
            //Select element
        	for (i = 0; i < object.options.length; i++) {
            	if (booleanValue(object.options[i].selected)) {
                	ret[ret.length] = object[i].value;
                }
            }
        } else {
            //Array of elements: get each value
        	for (i = 0; i < object.length; i++) {
                temp = getValue(object[i]);
                if (!isEmpty(temp)) {
                	ret[ret.length] = temp;
                }
            }
        }
        //Checks the length to return an array or a direct value
    	return ret.length == 0 ? null : ret.length == 1 ? ret[0] : ret;
    }

    //Input elements
	if (typeof(object.type) != "undefined") {
        //Radios and checkboxes
    	if (object.type == "radio" || object.type == "checkbox") {
        	return booleanValue(object.checked) ? object.value : null;
        } else {
            //Other input elements
        	return object.value;
        }
    }

    //The last chance: It's a non input HTML element
	if (object.innerHTML) {
    	return object.innertHTML;
    }
    
    //Invalid object
	return null;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Sets the value of an element
 * Parameters:
 *     object: The reference for the element
 *     value: The value to be set
 */
function setValue(object, value) {

    //Validates the object
	if (object == null) {
    	return;
    }
    
    //Use an array
    var values;
    if (value instanceof Array) {
        values = value;    
    } else {
        values = [value];
    }

    //Select elements or array of input elements
	if (typeof(object.length) != "undefined") {
    	if (typeof(object.options)!="undefined") {
            //Select element
        	for (i = 0; i < object.options.length; i++) {
                var match = false;
                for (var k = 0; !match && k < values.length; k++) {
                    if (object[i].value == values[k]) {
                        match = true;
                    }                
                }
                object[i].selected = match;
            }
        } else {
            //Array of elements: set each value
        	for (i = 0; i < object.length; i++) {
            	setValue(object[i], values);
            }
        }
    }
    
    //Input elements
	if (typeof(object.type) != "undefined") {
        //Radios and checkboxes
    	if (object.type == "radio" || object.type == "checkbox") {
            var match = false;
            for (var i = 0; !match && i < values.length; i++) {
                if (object.value == values[i]) {
                    match = true;
                }                
            }
            object.checked = match;
        } else {
            //Other input elements: get the first value
        	object.value = values.length == 0 ? "" : values[0];
        }
    }
    
    //The last chance: It's a non input HTML element
	if (object.innerHTML) {
    	object.innertHTML = values.length == 0 ? "" : values[0];
    }
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns if an object is an empty instance ("" or null)
 * Parameters:
 *     object: The object
 * Returns: Is the object an empty instance?
 */
function isEmpty(object) {
    return String(object) == "" || object == null || typeof(object) == "undefined";
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Replaces all the occurences in the string
 * Parameters:
 *     string: The string
 *     find: Text to be replaced
 *     replace: Text to replace the previous
 * Returns: The new string
 */
function replaceAll(string, find, replace) {
    return String(string).split(find).join(replace);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Removes all whitespaces on the left side
 * Parameters:
 *     string: The string
 * Returns: The new string
 */
function ltrim(string) {
    string = String(string);
    var pos = 0;
    while (string.charAt(pos) == " ") {
        pos++;
    }
    return string.substr(pos);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Removes all whitespaces on the right side
 * Parameters:
 *     string: The string
 * Returns: The new string
 */
function rtrim(string) {
    string = String(string);
    var pos = string.length - 1;
    while (string.charAt(pos) == " ") {
        pos--;
    }
    return string.substring(0, pos + 1);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Removes all whitespaces on both left and right sides
 * Parameters:
 *     string: The string
 * Returns: The new string
 */
function trim(string) {
    return ltrim(rtrim(string));
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Make the string have the specified length, completing with the 
 * specified character on the left
 * Parameters:
 *     string: The string
 *     size: The string size
 *     chr: The character that will fill the string
 * Returns: The new string
 */
function lpad(string, size, chr) {
    string = String(string);
    if (size <= 0) {
        return "";
    }
    if (isEmpty(chr)) {
        chr = " ";
    } else {
        chr = String(chr).charAt(0);
    }
    while (string.length < size) {
        string = chr + string;
    }
    return string;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Make the string have the specified length, completing with the 
 * specified character on the reight
 * Parameters:
 *     string: The string
 *     size: The string size
 *     chr: The character that will fill the string
 * Returns: The new string
 */
function rpad(string, size, chr) {
    string = String(string);
    if (size <= 0) {
        return "";
    }
    chr = String(chr);
    if (isEmpty(chr)) {
        chr = " ";
    } else {
        chr = chr.charAt(0);
    }
    while (string.length < size) {
        string += chr;
    }
    return string;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Removes the specified number of characters 
 * from a string after an initial position
 * Parameters:
 *     string: The string
 *     pos: The initial position
 *     size: The crop size (optional, default=1)
 * Returns: The new string
 */
function crop(string, pos, size) {
    string = String(string);
    if (size == null) {
        size = 1;
    }
    if (size <= 0) {
        return "";
    }
    return left(string, pos) + mid(string, pos + size);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Removes the specified number of characters from the left of a string 
 * Parameters:
 *     string: The string
 *     size: The crop size (optional, default=1)
 * Returns: The new string
 */
function lcrop(string, size) {
    if (size == null) {
        size = 1;
    }
    return crop(string, 0, size);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Removes the specified number of characters from the right of a string 
 * Parameters:
 *     string: The string
 *     size: The crop size (optional, default=1)
 * Returns: The new string
 */
function rcrop(string, size) {
    string = String(string);
    if (size == null) {
        size = 1;
    }
    return crop(string, string.length - size, size);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Checks if the string contains only the specified characters
 * Parameters:
 *     string: The string
 *     possible: The string containing the possible characters
 * Returns: Do the String contains only the specified characters?
 */
function onlySpecified(string, possible) {
    string = String(string);
    possible = String(possible);
    for (var i = 0; i < string.length; i++) {
        if (possible.indexOf(string.charAt(i)) == -1) {
            return false;
        }
    }
    return true;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Checks if the string contains only numbers
 * Parameters:
 *     string: The string
 * Returns: Do the String contains only numbers?
 */
function onlyNumbers(string) {
    var possible = JST_CHARS_NUMBERS;
    return onlySpecified(string, possible);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Checks if the string contains only letters
 * Parameters:
 *     string: The string
 * Returns: Do the String contains only lettersts?
 */
function onlyLetters(string) {
    var possible = JST_CHARS_LOWER + JST_CHARS_UPPER;
    return onlySpecified(string, possible);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Checks if the string contains only alphanumeric characters (letters or digits)
 * Parameters:
 *     string: The string
 * Returns: Do the String contains only alphanumeric characters?
 */
function onlyAlpha(string) {
    var possible = JST_CHARS_NUMBERS + JST_CHARS_LOWER + JST_CHARS_UPPER;
    return onlySpecified(string, possible);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns the left most n characters
 * Parameters:
 *     string: The string
 *     n: The number of characters
 * Returns: The substring
 */
function left(string, n) {
    string = String(string);
    return string.substring(0, n);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns the right most n characters
 * Parameters:
 *     string: The string
 *     n: The number of characters
 * Returns: The substring
 */
function right(string, n) {
    string = String(string);
    return string.substr(string.length - n);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns n characters after the initial position
 * Parameters:
 *     string: The string
 *     pos: The initial position
 *     n: The number of characters (optional)
 * Returns: The substring
 */
function mid(string, pos, n) {
    string = String(string);
    if (n == null) {
        n = string.length;
    }
    return string.substring(pos, pos + n);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Returns all properties in the object, sorted or not, with the separator between them.
 * Parameters:
 *     object: The object
 *     sort: Must be sorted?
 *     separator: The separator between properties
 * Returns: The substring
 */
function debug(object, sort, separator) {
	if (object == null) {
        return "";
    }
    sort = booleanValue(sort == null ? true : sort);
	if (separator == null) {
        separator = "\n";
    }
    //Get the properties
	var properties = new Array();
	for (var property in object) {
    	properties[properties.length] = property + " = " + object[property];
    }
    //Sort if necessary
    if (sort) {
        properties.sort();
    }
    //Build the output
	return properties.join(separator);
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Escapes the string's special characters to their escaped form
 * ('\\' to '\\\\', '\n' to '\\n', ...) and the extraChars are escaped via unicode
 * (\\uXXXX, where XXXX is the hexadecimal charcode)
 * Parameters:
 *     string: The string to be escaped
 *     extraChars: The String containing extra characters to be escaped
 *     onlyExtra: If true, do not process the standard characters ('\\', '\n', ...)
 * Returns: The encoded String
 */
function escapeCharacters(string, extraChars, onlyExtra) {
    var ret = String(string);
    extraChars = String(extraChars || "");
    onlyExtra = booleanValue(onlyExtra);
    //Checks if must process only the extra characters
    if (!onlyExtra) {
        ret = replaceAll(ret, "\\", "\\\\");
        ret = replaceAll(ret, "\n", "\\n");
        ret = replaceAll(ret, "\r", "\\r");
        ret = replaceAll(ret, "\t", "\\t");
    }
    //Process the extra characters
    for (var i = 0; i < extraChars.length; i++) {
        var chr = extraChars.charAt(i);
        ret = replaceAll(ret, chr, "\\\\u" + lpad(new Number(chr.charCodeAt(0)).toString(16), 4, '0'));
    }
    return ret;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Unescapes the string, changing the special characters to their unescaped form
 * ('\\\\' to '\\', '\\n' to '\n', '\\uXXXX' to the hexadecimal ASC(XXXX), ...)
 * Parameters:
 *     string: The string to be unescaped
 *     onlyExtra: If true, do not process the standard characters ('\\', '\n', ...)
 * Returns: The unescaped String
 */
function unescapeCharacters(string, onlyExtra) {
    var ret = String(string);
    var pos = -1;
    var u = "\\\\u";
    onlyExtra = booleanValue(onlyExtra);
    //Process the extra characters
    /*
    do {
        pos = ret.indexOf(u);
        if (pos >= 0) {
            var charCode = parseInt(ret.substring(pos + u.length, pos + u.length + 4), 16);
            ret = replaceAll(ret, u + charCode, String.fromCharCode(charCode));
        }
    } while (pos >= 0);
    */
    //Checks if must process only the extra characters
    if (!onlyExtra) {
        ret = replaceAll(ret, "\\n", "\n");
        ret = replaceAll(ret, "\\r", "\r");
        ret = replaceAll(ret, "\\t", "\t");
        ret = replaceAll(ret, "\\\\", "\\");
    }
    return ret;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Writes the specified value to the cookie
 * Parameters:
 *     name: The name of the value
 *     value: The value
 */
function writeCookie(name, value) {
        var expires = new Date(2500, 12, 31);
        parent.document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString();
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Reads the specified value to the cookie
 * Parameters:
 *     name: The name of the value
 * Returns: The value
 */
function readCookie(name) {
    var query = name + "=";
    if (parent.document.cookie.length > 0) { // se existir cookies
        offset = parent.document.cookie.indexOf(query);
        if (offset != -1) { // se existe cookie
            offset += query.length;
            // index = começo do valor
            end = parent.document.cookie.indexOf(";", offset);
            // index = fim do valor
            if (end == -1) {
                end = parent.document.cookie.length;
            }
            return unescape(parent.document.cookie.substring(offset, end));
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
/*
 * A class that represents a key/value pair
 * Parameters:
 *     key: The key
 *     value: The value
 */
function Value(key, value) {
    this.key = key || "";
    this.value = value;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * A class that represents a Map
 * Parameters:
 *     values: The initial values array (optional)
 */
function Map(values) {
    this.values = values || new Array();

    /*
     * Adds the value to the map
     */
    this.putValue = function(value) {
        if (value instanceof Value) {
            this.values[this.values.length] = value;
        }
    }

    /*
     * Adds the value to the map
     */
    this.put = function(key, value) {
        this.putValue(new Value(key, value));
    }

    /*
     * Adds all the values to the map
     */
    this.putAll = function(map) {
        if (!(map instanceof Map)) {
            return;
        }
        var entries = map.getEntries();
        for (var i = 0; i < entries.length; i++) {
            this.putValue(entries[i]);
        }
    }
    
    /*
     * Returns the entry count
     */
    this.size = function() {
        return this.values.length;
    }
    
    /*
     * Returns the mapped entry
     */
    this.get = function(key) {
        for (var i = 0; i < this.values.length; i++) {
            var value = this.values[i];
            if (value.key == key) {
                return value.value;
            }
        }
    }
    
    /*
     * Returns the keys
     */
    this.getKeys = function() {
        var ret = new Array();
        for (var i = 0; i < this.values.length; i++) {
            ret[ret.length] = this.values[i].key;
        }
        return ret;
    }
    
    /*
     * Returns the values
     */
    this.getValues = function() {
        var ret = new Array();
        for (var i = 0; i < this.values.length; i++) {
            ret[ret.length] = this.values[i].value;
        }
        return ret;
    }
    
    /*
     * Returns the key/value entries
     */
    this.getEntries = function() {
        var ret = new Array();
        for (var i = 0; i < this.values.length; i++) {
            ret[ret.length] = this.values[i];
        }
        return ret;
    }
}
