/**
 * All codes created by Ricardo in 2009-05-29(OWS)
 * v.: 3.1
 */
//var func_onload = [function(){}];
//
//function queueMonta_OnLoad(){
//    forIn(func_onload, function(f){
//        try{
//            f();
//        }catch(e){}
//    });
//}

//window.onload = queueMonta_OnLoad;
 
/**
 *  executa a funcao apos carregar a pagina
 *  @example onRead(function(){<br/>alert('funciona');<br/>})
 */
//function onRead(arg){
//    func_onload[func_onload.length] = arg;
//}
 
/**
 *  retorna o elemento com o id passado
 *  @example $("id")
 */
//function $(arg){
//    return document.getElementById(arg)
//}

/**
 *  retorna o valor do elemento com o id passado codificado
 *  @example $p("id")
 */
//function $p(arg){
//    return encodeURI($(arg).value)
//}

/**
 * abre popup
 * @example pop('index.jsp','titulo',400,400);
 */
function pop(u,t,w,h){
    window.open(u,t,'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,top='+(screen.height-h)/2+',left='+(screen.width-w)/2+',width='+w+',height='+h)
}

/**
 * formForParameters($('idForm'));<br/>
 * 'nome=value&nome=value...'
 */
function formForParameters(eRoot){
    var elementForParameter = function(e){
        if(e.type=='checkbox'){
            return encodeURI(e.name) + '='  + encodeURI(e.checked);
        }else if(e.name != null && e.value != null)
            return encodeURI(e.name) + '='  + encodeURI(e.value)
        return '';
    }
    var array = eRoot.elements;
    var retorno = elementForParameter(array[0]);
    for (var i = 1; i < array.length; i++)
        retorno += '&'+elementForParameter(array[i]);
    return retorno;
}

/**
 * valida formulario simples
 * @example valForm(eForm);
 */
function valForm(arg){
    arg.getElementsByTagName("input").forEach(function(e){
        if(e.value==null || e .value==""){
            alert('Por favor, preencha o campo '+e.name);
            e.focus();
        }
    });
}

/*------------------- validacao ---------------------*/
/**
 * valida cpf
 * @example valCPF(value);
 */
function valCPF(arg){
    var aux = [0,0,11];
    for(i=0;i<9;i++){
        aux[1]+=arg[i]*aux[2];
        aux[0]+=arg[i]*--aux[2];
    }
    aux[1] = ((((aux[0] = (aux[0]*10)%11)*2)+aux[1])*10)%11;
    return (aux[0]==arg[9] && aux[1]==arg[10]);
}

/**
 * valida email
 */
function valEmail(e){
    apos = e.value.indexOf("@");
    return (apos < 1 || e.value.lastIndexOf(".")-apos < 2);
}

/*----------------------------------------------------------*/

/**
 * mascara ex.: mascarar(this,'######-###');
 */
function mascarar(e, mascara) {
    var texto = mascara.substring(e.value.length);
    if(texto.substring(0,1) != mascara.substring(0,1))
        e.value += texto.substring(0,1);
}

/**
 * var array = [{id:'nome',tipo:'text',msg:'preencha o campo seu burro'}];
 * validateForm([{id:'nome',tipo:'text',msg:'preencha o campo seu burro'}]);
 */
function validateForm(array){
    var showMsg = function(_objJson,_e){
        if(_objJson.msg == null)
            alert('Por favor, preencha o campo '+_e.name.replace('_',' ')+'.');
        else
            alert(_objJson.msg);
        _e.focus();
        return false;
    }
    var fim = array.length;
    for (i = 0; i < fim; i++){
        var objJson = array[i];
        var e = $(objJson.id);
        var tipo = objJson.tipo;
        if(tipo=='text'){
            if(e.value == null || e.value == '')
                return showMsg(objJson,e);
        }else if(tipo=='email'){
            if(e.value == null || e.value == ''){
                return showMsg(objJson,e);
            }else{
                if(valEmail(e)){
                    alert('Por favor, preencha seu e-mail corretamente!');
                    e.focus();
                    return false;
                }
            }
        }else if(tipo=='cpf'){
            aux = e.value.replace('.','');
            aux = aux.value.replace('-','');
            if(valCPF(aux))
                return showMsg(objJson,e);
        }else if(tipo=='int'){
            if(e.value == null || e.value == ''){
                return showMsg(objJson,e);
            }else{
                aux = parseInt(e.value);
                e.value = aux;
                if(e.value=='NaN'){
                    e.value = '';
                    return showMsg(objJson,e);
                }
            }
        }
    }
    return true;
}

function contain(str,arg){
    return (str.indexOf(arg) > -1);
}

/**
 * funcao para trabalhar com abas
 *
 * id da div root: ows-aba-root
 * classe das abas: ows-aba //contudo
 */
function selectAba(eA,id){
    eRoot = $('ows-aba-root');
    forIn(eRoot.getElementsByTagName('div'),function(e){
        if(contain(e.className,'ows-aba-on'))
            e.className = 'ows-aba-off';
        if(e.className=='ows-aba')
            e.style.display = 'none';
    });
    $(id).style.display = 'block';
    eA.className = 'ows-aba-on';
}

/**
 * funcao para trabalhar com abas
 *
 * id da div root: ows-aba-root
 * classe das abas: ows-aba //contudo
 */
function selectAba2(eA,id){
    eRoot = $('ows-aba-root2');
    forIn(eRoot.getElementsByTagName('div'),function(e){
        if(contain(e.className,'ows-aba-on'))
            e.className = 'ows-aba-off';
        if(e.className=='ows-aba')
            e.style.display = 'none';
    });
    $(id).style.display = 'block';
    eA.className = 'ows-aba-on';
}

/**
 * Varre um vetor<br/>
 */
function forIn(vetor,callback){
    max = vetor.length;
    for (i = 0; i < max; i++)
        callback(vetor[i]);
}

function getLT(offsetTrail){
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {
        left:offsetLeft,
        top:offsetTop
    };
}

/**
 * so numeros
 */
function toInt(v){
    return v.replace(/\D/g,"")
}

/**
 * mascaras
 */
function msk(arg){
    var v = arg.value;
    return{
        moeda:function(){
            v=v.replace(/\D/g,"");
            v=v.replace(/(\d{1})(\d{1,2})$/,"$1,$2");
            if(parseFloat(v.replace(',','.')) > 100)
                v = float2moeda(v.replace(',','.'));
            arg.value = v;
            return v;
        } ,
        telefone: function(){
            v=v.replace(/\D/g,"");
            v=v.replace(/^(\d\d)(\d)/g,"($1) $2");
            v=v.replace(/(\d{4})(\d)/,"$1-$2");
            arg.value = v;
            return v;
        } ,
        cpf: function(){
            v=v.replace(/\D/g,"");
            v=v.replace(/(\d{3})(\d)/,"$1.$2");
            v=v.replace(/(\d{3})(\d)/,"$1.$2");
            v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2");
            arg.value = v;
            return v;
        } ,
        cnpj: function(){
            v=v.replace(/\D/g,"");
            v=v.replace(/^(\d{2})(\d)/,"$1.$2");
            v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3");
            v=v.replace(/\.(\d{3})(\d)/,".$1/$2");
            v=v.replace(/(\d{4})(\d)/,"$1-$2");
            arg.value = v;
            return v;
        } ,
        romanos: function(){
            v=v.toUpperCase();
            v=v.replace(/[^IVXLCDM]/g,"");
            while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
                v=v.replace(/.$/,"");
            arg.value = v;
            return v;
        } ,
        site: function(){
            v=v.replace(/^http:\/\/?/,"");
            dominio=v;
            caminho="";
            if(v.indexOf("/")>-1)
                dominio=v.split("/")[0];
            caminho=v.replace(/[^\/]*/,"");
            dominio=dominio.replace(/[^\w\.\+-:@]/g,"");
            caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"");
            caminho=caminho.replace(/([\?&])=/,"$1");
            if(caminho!="")
                dominio=dominio.replace(/\.+$/,"");
            v="http://"+dominio+caminho;
            arg.value = v;
            return v;
        }
    }
}

function float2moeda(num) {
    x = 0;
    if(num<0) {
        num = Math.abs(num);
        x = 1;
    }
    if(isNaN(num)) num = "0";
    cents = Math.floor((num*100+0.5)%100);
    num = Math.floor((num*100+0.5)/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));
    ret = num + ',' + cents;
    if (x == 1) ret = ' - ' + ret;
    return ret;
}

/**
 * Codifica��o base64
 */
function base64(){
    
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    return {
        encode :function(input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;

            do {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);

                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;

                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }

                output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                keyStr.charAt(enc3) + keyStr.charAt(enc4);
            } while (i < input.length);

            return output;
        }

        ,
        decode : function(input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;

            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

            do {
                enc1 = keyStr.indexOf(input.charAt(i++));
                enc2 = keyStr.indexOf(input.charAt(i++));
                enc3 = keyStr.indexOf(input.charAt(i++));
                enc4 = keyStr.indexOf(input.charAt(i++));

                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;

                output = output + String.fromCharCode(chr1);

                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            } while (i < input.length);

            return output;
        }
    }
}