/*
 * REQUIRED: prototype.js
*/
 
 
/* APLICA UMA FUNÇÃO AO EVENTO DE UM OBJETO */
function createMethodReference(object, methodName) {

    return function () {
        object[methodName].apply(object, arguments);
    };

}

/*
 * IMPRIME UM HTML ( returnString ) 
 * NA POSIÇÃO ( position )
 * DENTRO DO OBJETO DEFINIDO
 * CASO NÃO TENHA OBJETO DEFINIDO ELE INCLUI EM flipComponents
 * 
 * */
function newComponent(returnString, position, object){
    try {

        object = (object) ? object : $('flipComponents');
        switch(position){
            case "before": // ANTES DO OBJETO
                new Insertion.Before(object, returnString);
                break;
            case "after": // DEPOIS DO OBJETO
                new Insertion.After(object, returnString);
                break;
            case "bottom": // NO FINAL DENTRO DO OBJETO
                new Insertion.Bottom(object, returnString);
                break;
            default: // NO INÍCIO DENTRO DO OBJETO
                new Insertion.Top(object, returnString);
                break;
        }

    }catch(e) { logError("functions.js:newComponent", e); }
}

/* APLICA UMA ESTILO A UM OBJETO */
function setStyle(obj, classe) {

    obj.setAttribute("className",classe);
}

/* BUSCA A POSIÇÃO LEFT DE UM OBJETO A PARTIR DO PONTO ZERO DO BODY */
function findPosX(obj){
    return Position.cumulativeOffset(obj)[0];
}

/* BUSCA A POSIÇÃO TOP DE UM OBJETO A PARTIR DO PONTO ZERO DO BODY */
function findPosY(obj){
    return Position.cumulativeOffset(obj)[1];
}    


Array.prototype.inArray = function (value){
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
    try {
        var i;
        for (i=0; i < this.length; i++) {
            // Matches identical (===), not just similar (==).
            if (this[i] === value) {
                return true;
            }
        }
        return false;
    }catch(e) { logError("functions.js:inArray", e); }
};
    
/* LOCALIZA UM VALOR EM UM ARRAY */
function inArray(needle, haystack) {
    return haystack.inArray(needle);
/*
    try {
        for (var i = 0; i < haystack.length; i++) {
            if (haystack[i] == needle) {
                return true;
            }
        }
        return false;

    }catch(e) { logError("functions.js:inArray", e); }
*/
}    

/*
 * CONVERTE UM ARRAY PARA SEPARAÇÃO COM VIRGULA EX.:( arg1, arg2, arg3, ... )
 * UTILIZADO PRINCIPALMENTE PARA REPASSAR ARGUMENTOS DE UMA FUNÇÃO PARA OUTRA FUNÇÃO SEM PRECISAR SABER QUANTOS ARGUMENTOS EXISTEM
 */
function arrayToArgs(arrayArgs, ini, end){
    try{

        end    = (isUndefined(end)) ? 0 : end;
        args   = "";
    
        for(var i = ini; i < arrayArgs.length-end; i++){
            if(isString(arrayArgs[i]))
                arrayArgs[i] = simpleQuote(arrayArgs[i]);
            args += (i == ini) ? arrayArgs[i] : ", "+arrayArgs[i];
        }
        return args;

    }catch(e) { logError("functions.js:arrayToArgs", e); }
}

function redirecionar(uri){
    document.location = uri;
    return true;
}


function getElementsByTagNames(obj, list) {
    try {
        if (!obj) var obj = document;
        var tagNames = list.split(',');
        var resultArray = new Array();
        for (var i=0;i<tagNames.length;i++) {
            var tags = obj.getElementsByTagName(tagNames[i]);
            for (var j=0;j<tags.length;j++) {
                resultArray.push(tags[j]);
            }
        }
        var testNode = resultArray[0];
        if (!testNode) return [];
        if (testNode.sourceIndex) {
            resultArray.sort(function (a,b) {
                    return a.sourceIndex - b.sourceIndex;
            });
        }
        else if (testNode.compareDocumentPosition) {
            resultArray.sort(function (a,b) {
                    return 3 - (a.compareDocumentPosition(b) & 6);
            });
        }
        return resultArray;

    }catch(e) { logError("functions.js:getElementsByTagNames", e); }
}


function makeList(string, separator){
    return string.split(separator);
}

/* BUSCA A POSIÇÃO X E Y DO MOUSE NA TELA ( ÁREA ÚTIL DO BODY ) */
var xScroll = "";
var yScroll = "";
function getMouse(e){
    try {

        if(document.all) e = event;
    
        xScroll = e.clientX;
        yScroll = e.clientY;
//        window.status = xScroll+" : "+yScroll;
        return false;

    }catch(e) { logError("functions.js:getMouse", e); }
}
//document.documentElement.onmousemove = getMouse;

/* VERIGICA SE O PARAMETRO É UM OBJETO DO INTERNET EXPLORER */
function isIEObject(a){
    return isObject(a) && typeof a.constructor != 'function';
}

/* VERIGICA SE O PARAMETRO É UM ARRAY */
function isArray(a) {
    return isObject(a) && a.constructor == Array;
}

/* VERIGICA SE O PARAMETRO É UM BOOLEAN */
function isBoolean(a) {
    return typeof a == 'boolean';
}

/* VERIGICA SE O PARAMETRO É UM EMPTY */
function isEmpty(o) {
    var i, v;
    if (isObject(o)) {
        for (i in o) {
            v = o[i];
            if (isUndefined(v) && isFunction(v)) {
                return false;
            }
        }
    }
    return true;
}

/* VERIGICA SE O PARAMETRO É UMA FUNÇÃO */
function isFunction(a) {
    return typeof a == 'function';
}

/* VERIGICA SE O PARAMETRO É NULO */
function isNull(a) {
    return typeof a == 'object' && !a;
}

/* VERIGICA SE O PARAMETRO É UM NUMERO */
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/* VERIGICA SE O PARAMETRO É UM OBJETO */
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

/* VERIGICA SE O PARAMETRO É UMA STRING */
function isString(a) {
    return typeof a == 'string';
}

/* VERIGICA SE O PARAMETRO ESTÁ INDEFINIDO */
function isUndefined(a) {
    return typeof a == 'undefined';
}

/* VERIGICA SE O PARAMETRO ESTÁ INDEFINIDO */
function isUndefined_(a) {
    return eval("typeof "+a+" == 'undefined'");
}

/* INCLUI ASPAS SIMPLES OU DUPLAS EM UMA STRING */
function quote (string, type){
    return (type == "'") ? simpleQuote(string) : doubleQuote(string);
}

/* INCLUI ASPAS DUPLAS EM UMA STRING */
function doubleQuote (string){
    return '"'+string+'"';
}

/* INCLUI ASPAS SIMPLES EM UMA STRING */
function simpleQuote (string){
    return "'"+string+"'";
}

/* RETORNA O VALOR DE UM PARAMETRO GET */
function getQueryString( parametro ) {
    try {

        if(isUndefined(parametro))
            return document.location.search;
    
        var re = new RegExp( parametro + "=([^\\&]*)", "i" );
        var a = re.exec( document.location.search );
        if ( a == null ) return "";
        return a[1];

    }catch(e) { logError("functions.js:getQueryString", e); }
}

/* MOSTRA OU OCULTA UM OBJETO */
function display(obj) {
    try{
        if(!isUndefined(obj.style)){
            if (obj.style.display == "none"){
                obj.style.display = "block";
                return true;
            }else{
                obj.style.display = "none";
                return false;
            }
        }
    }catch(e) { logError("functions.js:display", e); }
}

/* RETORNA A POSIÇÃO DO OBJETO NA ARVORE DOM */
function getDomIndice(obj){
    try{

        for(var i = 0; i < obj.parentNode.childNodes.length; i++){
            if(obj.parentNode.childNodes[i] == obj)
                return i;
        }

    }catch(e) { logError("functions.js:getDomIndice", e); }
}

/* RETORNA UM PRÓXIMO "IRMÃO" DE UM OBJETO */
function nextChild(obj){
    domIndice = getDomIndice(obj);
    return obj.parentNode.childNodes[domIndice+1];
}

/* */
function getStyleProp(oElm, strCssRule){
    try {
        var strValue = "";
        if(document.defaultView && document.defaultView.getComputedStyle){
            strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
        }
        else if(oElm.currentStyle){
            strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
                return p1.toUpperCase();
            });
            strValue = oElm.currentStyle[strCssRule];
        }
        return strValue;

    }catch(e) { logError("functions.js:getStyleProp", e); }
}


/* APLICA O ESTILO DISPLAY EM TODOS OS OBJETOS COM TAG(tagName) DA PÁGINA */
function displayObjects(tagName, styleDisplay){

    selects = document.getElementsByTagName(tagName);

    for(var i = 0; i < selects.length; i++){
        selects[i].style.display = styleDisplay;
    }

}


/* RETURNA O TAMANHO ÚTIL DA JANELA */
function getUtilWindowSize(simbol){
    try{

        var x,y;
        if (self.innerHeight) // all except Explorer
        {
            x = self.innerWidth;
            y = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
            // Explorer 6 Strict Mode
        {
            x = document.documentElement.clientWidth;
            y = document.documentElement.clientHeight;
        }
        else if (document.body) // other Explorers
        {
            x = document.body.clientWidth;
            y = document.body.clientHeight;
        }
    
        return x+simbol+y;

    }catch(e) { logError("functions.js:getUtilWindowSize", e); }
}




/*
String.
    method('entityify', function () {
        return this.replace(/&/g, "&amp;").replace(/</g,
            "&lt;").replace(/>/g, "&gt;");
    }).
    method('quote', function () {
        var c, i, l = this.length, o = '"';
        for (i = 0; i < l; i += 1) {
            c = this.charAt(i);
            if (c >= ' ') {
                if (c == '\\' || c == '"') {
                    o += '\\';
                }
                o += c;
            } else {
                switch (c) {
                case '\b':
                    o += '\\b';
                    break;
                case '\f':
                    o += '\\f';
                    break;
                case '\n':
                    o += '\\n';
                    break;
                case '\r':
                    o += '\\r';
                    break;
                case '\t':
                    o += '\\t';
                    break;
                default:
                    c = c.charCodeAt();
                    o += '\\u00' + Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }
            }
        }
        return o + '"';
    }).
    method('supplant', function (o) {
        var i, j, s = this, v;
        for (;;) {
            i = s.lastIndexOf('{');
            if (i < 0) {
                break;
            }
            j = s.indexOf('}', i);
            if (i + 1 >= j) {
                break;
            }
            v = o[s.substring(i + 1, j)];
            if (!isString(v) && !isNumber(v)) {
                break;
            }
            s = s.substring(0, i) + v + s.substring(j + 1);
        }
        return s;
    }).
    method('trim', function () {
        return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
    }); 
*/



/************************ FUNÇÕES TMPS ***********************/
//
///*
// * CRIA UM SCRIPT 
// * TESTA SE O SCRIPT FOI CARREGADO
// * REQUISITA O PRÓXIMO SCRIPT
// * */
//function include_dom(script_filename, nextFunction) {
//alert(nextFunction);
//    var js = document.createElement('script');
//    js.setAttribute('src', script_filename);
//    js.setAttribute('language', 'javascript');
//    js.setAttribute('type', 'text/javascript');
//
//    if(js.attachEvent){
//        js.attachEvent("onreadystatechange", function() { return nextFunction(); });
//    }else if (js.addEventListener){
//        js.addEventListener("load", nextFunction, true);
//    }
//
//    var html_doc = document.getElementsByTagName('head').item(0);
//    html_doc.appendChild(js);
//    return true;
//
//}
//
///*
// * VERIFICA SE O SCRIPT JÁ FOI INSERIDO, CASO JÁ EXISTA, PARA A EXECUÇÃO
// * ADICIONA O SCRIPT NO ARRAY included_files
// * CHAMA A FUNÇÃO include_dom PARA INCLUIR O SCRIPT
// * SCRIPT PHP PARA O OBJETO ESPECIFICADO E INCLUI EM UM ARRAY : FUNCIONA PARA QUE O ARQUIVO NÃO SEJA ICLUSO 2 VEZES
// * */
//var included_files = new Array();
//function include_once(script_filename, nextFunction) {
//
//    if (!inArray(script_filename, included_files)) {
//        included_files[included_files.length] = script_filename;
//        include_dom(script_filename, nextFunction);
//    }
//}
//
//function includesToolAll(array, index){
//    
//    if(array.length > index){
//        include_once(array[index++], includesToolAll);
//    }
//}


/*
 * 
 */
try{

    var included_files = new Array();
    var funcGlobal = "";
    var includeClass       = Class.create();
    includeClass.prototype = {
        initialize: function () {
            this.index = 0;
            this.array = new Array();
        },
    
        newItem: function (item) {
            this.array[this.array.length] = item;
        },
    
        include: function (){
    
            if(this.array.length > this.index){
    
    //            alert(this.array[this.index]);
                scriptName = this.array[this.index++];
    
                if (!inArray(scriptName, included_files)) {
                    included_files[included_files.length] = scriptName;
    
                    var js = document.createElement('script');
                    js.setAttribute('src', scriptName);
                    js.setAttribute('language', 'javascript');
                    js.setAttribute('type', 'text/javascript');
            
                    var funcAtual = this;
                    if(js.attachEvent){
                        js.attachEvent("onreadystatechange", function() { return funcAtual.include(); });
                    }else if (js.addEventListener){
                        js.addEventListener("load", function() { return funcAtual.include(); }, true);
                    }
            
                    var html_doc = document.getElementsByTagName('head').item(0);
                    html_doc.appendChild(js);
                    return true;
    
                }
    
            }
    
        }
    
    };

}catch(e) { logError("functions.js:includeClass", e); }
/************************ FUNÇÕES TMPS ***********************/