/**
 * montaXMLHTTP
 *
 * Cria o objeto XMLHTTP - conhecido vulgarmente como Ajax :)
 *
 * @return object
 */
function montaXMLHTTP() {

    var myObj=null;
    //Tenta chamar o activeX (IE5+/MSXML1)
    try {
        myObj=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
        try {
            //Tenta chamar o activeX (IE5.5+/MSXML2+)
            myObj=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                //Tenta chamar o objeto nativo (FF / Safari / Konqueror / Opera / etc)
                myObj=new XMLHttpRequest();
            }
            //O navegador não tem suporte
            catch(e) {
                myObj=false;
            }
        }
    }
    return myObj;
}

/**
 * gE
 *
 * Busca um elemento por seu id.
 *
 * @param string
 * @return string
 */
function gE(id) {

    // DOM Browsers:
    if (document.getElementById) {
      return document.getElementById(id);
    }

    // Others
    else if (document.all) {
        return document.all[id];
    }

    else
        return false;
}

/**
 * cE
 *
 * Cria um elemento.
 *
 * tag    = tag que será criada.
 * id     = id que será atribuído a esta nova tag.
 * inHtml = valor html de conteúdo desta tag.
 * classN = classe que esta nova tag terá.
 *
 * @param tag:string
 * @param id:string
 * @param classN:string
 * @param inHtml:string
 * @return object
 */
function cE(tag, id, inHtml, classN) {

    //Verifica se é possível criar o elemento
    if (!document.createElement)
        return false;

    var nE = null;

    //Cria o elemento
    nE=document.createElement(tag);

    //Adiciona os atributos ao elemento
    if(id)
        nE.id=id;
    if(classN)
        nE.className=classN;
    if(inHtml)
        nE.innerHTML=inHtml;

    //Retorna o elemento criado
    return nE;

}

/**
 * onlyNumber
 *
 * Exige que somente números sejam digitados no campo passado como referência
 *
 * @param event:event
 * @return bool
 */
function onlyNumber(event) {

    var cod = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if((cod >= 48 && cod <= 57) || (cod == 8) || (cod == 13) || (cod == 9))
        return true;
    else
        return false;

}

/**
 * mascaraTelefone
 *
 * Formata o telefone
 *
 * @param  object
 * @return boolean
 */
function mascaraTelefone(event, objeto) {

    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (keyCode >= 48 && keyCode <= 57) {
        with(objeto) {
            if (value.length == 0)
                value = value + "(";
            else if (value.length == 3)
                value = value + ")";
            else if (value.length == 8)
                value = value + "-";
        }
    } else if((keyCode == 8) || (keyCode == 13) || (keyCode == 9)){
        return true;
    } else {
        keyCode=0;
        return false;
    }
}

/**
 * mascaraCPF
 *
 * Formata o CPF
 *
 * @param  object
 * @return boolean
 */
function mascaraCPF(event, objeto) {

    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (keyCode >= 48 && keyCode <= 57) {
        with(objeto) {
            if (value.length == 3)
                value = value + ".";
            else if (value.length == 7)
                value = value + ".";
            else if (value.length == 11)
                value = value + "-";
        }
    } else if((keyCode == 8) || (keyCode == 13) || (keyCode == 9)){
        return true;
    } else {
        keyCode=0;
        return false;
    }
}

/**
 * mascaraCNPJ
 *
 * Formata o CNPJ
 *
 * @param  object
 * @return boolean
 */
function mascaraCNPJ(event, objeto) {

    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (keyCode >= 48 && keyCode <= 57) {
        with(objeto) {
            if (value.length == 2)
                value = value + ".";
            else if (value.length == 6)
                value = value + ".";
            else if (value.length == 10)
                value = value + "/";
            else if (value.length == 15)
                value = value + "-";
        }
    } else if((keyCode == 8) || (keyCode == 13) || (keyCode == 9)){
        return true;
    } else {
        keyCode=0;
        return false;
    }
}

/**
 * mascaraCEP
 *
 * Formata o CEP
 *
 * @param  object
 * @return boolean
 */
function mascaraCEP(event, objeto) {

    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (keyCode >= 48 && keyCode <= 57) {
        with(objeto) {
            if (value.length == 5)
                value = value + "-";
        }
    } else if((keyCode == 8) || (keyCode == 13) || (keyCode == 9)){
        return true;
    } else {
        keyCode=0;
        return false;
    }
}

/**
 * listCombox
 *
 * Busca o array de dados e exibe no local referenciado
 *
 * @param  string
 * @param  string || integer
 * @param  string
 * @return void
 */
var dadosAlunos = new Array();
function listCombox(idSelect, objOrigem, url, idHidden, id) {

    //Valida o valor
    if(!objOrigem.value || objOrigem.value == "" || objOrigem.value == 0)
        return false;

    var c = gE(idSelect);

    dadosAlunos.push(objOrigem.value);

    objButton = createButton(id);
    objOrigem.style.display = 'none';
    li = objOrigem.parentNode;
    li.appendChild(cE('span', 'span_aluno'+id, objOrigem.options[objOrigem.selectedIndex].innerHTML));
    li.appendChild(objButton);

    //Desabilita o salvar
    gE('salvar').disabled = true;

    if(!c) {
        //Habilita o botão
        objButton.setAttribute('onclick', 'editAluno(\''+id+'\', \''+url+'\');');
        objButton.onclick = new Function('editAluno(\''+id+'\', \''+url+'\');');
        //Habilita o salvar
        gE('salvar').disabled = false;
        return true;
    }

    if(c.style.display == 'none') {
        aux = id;
        while(aux<qtd_maxima_atletas) {
            selectAluno = gE('EquipeDescAluno'+(++aux));
            if(selectAluno) {
                if(selectAluno.style.display != 'none') {
                    c = selectAluno;
                    break;
                }
            }
        }
    }

    while(c.options.length>0)c.options[0]=null

    c.options[0]=new Option('--Aguarde--','--Aguarde--');
    c.disabled = true;
    req = montaXMLHTTP();
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {

                var dados = new Array;
                c.disabled = false;

                while(c.options.length>0)c.options[0]=null;

                eval(req.responseText);

                for(var i=0;i<dados.length;i++){
                    c.options[i]=new Option(dados[i]["text"], dados[i]["id"]);
                }
                //Habilita o botão
                objButton.setAttribute('onclick', 'editAluno(\''+id+'\', \''+url+'\');');
                objButton.onclick = new Function('editAluno(\''+id+'\', \''+url+'\');');
                //Habilita o salvar
                gE('salvar').disabled = false;

            } else {
                alert("Houve um problema ao obter os dados:\n" + req.statusText);
            }
        }
    }
    array_unique(dadosAlunos);
    req.open("GET", url+"/"+dadosAlunos.toString(), true);
    req.send(null);
}

/**
 *
 * @access public
 * @return void
 **/
function createButton(i){
    objButton = cE('input', 'bt_aluno'+i);
    objButton.setAttribute('value', 'Editar');
    objButton.setAttribute('type', 'button');
    return objButton;
}

/**
 *
 * @access public
 * @return void
 **/
function editAluno(ident, action){

    //Desabilita o salvar
    gE('salvar').disabled = true;

    //Remove o aluno
    objSelect  = gE('EquipeDescAluno'+ident);
    aux = new Array();
    j = 0;
    for(i=0;i<dadosAlunos.length;i++) {
        if(objSelect.value != dadosAlunos[i]) {
            aux[j] = dadosAlunos[i];
            j++;
        }
    }
    dadosAlunos = aux;

    objSelect.style.display = 'inline';
    objButton = gE('bt_aluno'+ident);
    objButton.parentNode.removeChild(objButton);
    objSpan = gE('span_aluno'+ident);
    objSpan.parentNode.removeChild(objSpan);

    var c = gE('EquipeDescAluno'+ident);
    while(c.options.length>0)c.options[0]=null

    c.options[0]=new Option('--Aguarde--','--Aguarde--');
    c.disabled = true;
    req = montaXMLHTTP();
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {

                var dados = new Array;
                c.disabled = false;

                while(c.options.length>0)c.options[0]=null;

                eval(req.responseText);

                for(var i=0;i<dados.length;i++){
                    c.options[i]=new Option(dados[i]["text"], dados[i]["id"]);
                }
                //Habilita o botão
                objButton.setAttribute('onclick', 'editAluno(\''+ident+'\', \''+action+'\');');
                objButton.onclick = new Function('editAluno(\''+ident+'\', \''+action+'\');');

                //Habilita o salvar
                gE('salvar').disabled = false;

            } else {
                alert("Houve um problema ao obter os dados:\n" + req.statusText);
            }
        }
    }
    array_unique(dadosAlunos);
    req.open("GET", action+"/"+dadosAlunos.toString(), true);
    req.send(null);


    //Desabilida e zera os selects abaixo
    aux = ident;
    while(aux<qtd_maxima_atletas) {
        selectAluno = gE('EquipeDescAluno'+(++aux));
        if(selectAluno) {
            if(selectAluno.style.display != 'none') {
                selectAluno.disabled = true;
                while(selectAluno.options.length>0)selectAluno.options[0]=null;
                selectAluno.options[0]=new Option('Selecione o Aluno acima','Selecione o Aluno acima');
            }
        }
    }

}

/**
 * selectAllHoras
 *
 * Marca ou desmarca todos os checkboxes
 *
 * @param  object
 * @return void
 */
var btSelectMembros = false;
function selectAllHoras(objBtSelectMembros){
    //Busca os checkboxes
    var objForm    = gE('form_horas');
    var elForm     = objForm.elements;
    var Mylength   = elForm.length;
    //Loop para percorrer todos os elementos
    for (var i=0; i<Mylength; i++) {

        //Pega o elemento
        MyElement = elForm[i];

        //Realiza a ação conforme o elemento
        switch(MyElement.type) {
            case 'checkbox':
                MyElement.checked = btSelectMembros;
                break;
        }
    }

    if(btSelectMembros) {
        btSelectMembros = false;
        objBtSelectMembros.value = "Cancelar a disponibilidade total";
    }
    else {
        btSelectMembros = true;
        objBtSelectMembros.value = "Disponibilidade total";
    }
}

/**
 * http://kevin.vanzonneveld.net
 *
 * +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
 * *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld']);
 * *     returns 1: true
 */
function array_unique( array ) {
    var p, i, j;
    for(i = array.length; i;){
        for(p = --i; p > 0;){
            if(array[i] === array[--p]){
                for(j = p; --p && array[i] === array[p];);
                i -= array.splice(p + 1, j - p).length;
            }
        }
    }

    return true;
}


function combox(divid, valor, url) {

    var c = gE(divid);

    while(c.options.length>0)c.options[0]=null

    c.options[0]=new Option('--Aguarde--','--Aguarde--');
    c.disabled = true;
    req = montaXMLHTTP();
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {

                var dados = new Array;
                c.disabled = false;

                while(c.options.length>0)c.options[0]=null;

                eval(req.responseText);

                for(var i=0;i<dados.length;i++){
                    c.options[i]=new Option(dados[i]["text"],dados[i]["id"]);
                }

            } else {
                alert("Houve um problema ao obter os dados:\n" + req.statusText);
            }
        }
    }
    req.open("GET", url+valor, true);
    req.send(null);
}