function get() {
    var retorno = {};
    var url = window.location.href.split("?");

    if(url[1]) {
        var gets = url[1].split("&");
        for(var i=0; gets[i]; i++) {
            var partes = gets[i].split("=");
            retorno[partes[0]] = partes[1];
        }
    }

    return retorno;
}

function incluirObsevacaoPedido(textarea) {
    document.cookie = "observacaopedido=" + textarea.value;
}

function pegaAjaxObj(){
    var ajax = "";
    try {
        ajax = new XMLHttpRequest();
    } catch(e) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(ee) {
            try{
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(eee) {
                ajax = false;
            }
        }
    }
    return ajax;
}

function build_register_form(pessoa, include_in, src_button) {
    // apaga o formulario se ele existir
    span = include_in.parentNode.getElementsByTagName("span")
    if(span.length){
        span = span[0]
        span.parentNode.removeChild(span)
    }

    // cria o formulario
    include_in.parentNode.appendChild(build_form(pessoa == "FÍSICA" ? "fisica" : "juridica",src_button))
}

function build_form(pessoa, src_button) {
    spanform = document.createElement("span")
    npessoa = {"fisica":0,"juridica":1}

    labels = [
        [
            'Nome',
            'Como é chamado',
            'CPF',
            'RG',
            'Profissão',
            'Data de nascimento',
            'Endereço',
            'Complemento',
            'Bairro',
            'Cidade',
            'UF',
            'CEP',
            'Telefone',
            'Celular',
            'Fax',
            'Contato',
            'Site',
            'E-mail',
            'Login',
            'Senha',
            'Confirmação de Senha',
            'Lembrete'
        ],
        [
            'Razão Social',
            'Nome Fantasia',
            'CNPJ',
            'IE',
            'Ramo de Atividade',
            'Data de fundação',
            'Endereço',
            'Complemento',
            'Bairro',
            'Cidade',
            'UF',
            'CEP',
            'Telefone',
            'Celular',
            'Fax',
            'Contato',
            'Site',
            'E-mail',
            'Login',
            'Senha',
            'Confirmação de Senha',
            'Lembrete'
        ]
    ]

    legends = [
        ['Dados Pessoais', 'Endereço','Contato','Dados de Acesso'],
        ['Dados da Empresa', 'Endereço','Contato','Dados de Acesso']
    ]

    { //cadastro pessoal
        fscp = build_fieldset("pessoal",legends[npessoa[pessoa]][0])

        nomerazaosocial_label = build_label(labels[npessoa[pessoa]][0], "nomerazaosocial")
        nomerazaosocial = build_input("text","nomerazaosocial")
        nomerazaosocial.setAttribute("maxlength",60)
        nomerazaosocial.value = urldecode(getCookie("nomerazaosocial") ? getCookie("nomerazaosocial") : "")
        fscp.childNodes[1].appendChild(nomerazaosocial_label)
        fscp.childNodes[1].appendChild(nomerazaosocial)
        fscp.childNodes[1].appendChild(document.createElement("br"))

		if(pessoa == "juridica") {
			apelidofantasia_label = build_label(labels[npessoa[pessoa]][1], "apelidofantasia")
			apelidofantasia = build_input("text","apelidofantasia")
			apelidofantasia.setAttribute("maxlength",60)
			apelidofantasia.value = urldecode(getCookie("apelidofantasia") ? getCookie("apelidofantasia") : "")
			fscp.childNodes[1].appendChild(apelidofantasia_label)
			fscp.childNodes[1].appendChild(apelidofantasia)
			fscp.childNodes[1].appendChild(document.createElement("br"))
		}

        cpfcnpj_label = build_label(labels[npessoa[pessoa]][2], "cpfcnpj")
        cpfcnpj = build_input("text","cpfcnpj")
        cpfcnpj.setAttribute("maxlength",18)
        
        if(pessoa == 'fisica') {
            cpfcnpj.onfocus = function() {
                mascara('###.###.###-##', this);
            }
            cpfcnpj.onkeydown = function(e) {
                e = e || window.event
                return isInt(e.keyCode)
            }
        } else {
            cpfcnpj.onfocus = function() {
                mascara('##.###.###/####-##', this);
            }
            cpfcnpj.onkeydown = function(e) {
                e = e || window.event
                return isInt(e.keyCode)
            }        
        }

        cpfcnpj.value = urldecode(getCookie("cpfcnpj") ? getCookie("cpfcnpj") : "")
        fscp.childNodes[1].appendChild(cpfcnpj_label)
        fscp.childNodes[1].appendChild(cpfcnpj)
        fscp.childNodes[1].appendChild(document.createElement("br"))

        rgie_label = build_label(labels[npessoa[pessoa]][3], "rgie")
        rgie = build_input("text","rgie")
        rgie.setAttribute("maxlength",30)
        rgie.value = urldecode(getCookie("rgie") ? getCookie("rgie") : "")
        fscp.childNodes[1].appendChild(rgie_label)
        fscp.childNodes[1].appendChild(rgie)
        fscp.childNodes[1].appendChild(document.createElement("br"))

        profissaoramoatividade_label = build_label(labels[npessoa[pessoa]][4], "profissaoramoatividade")
        profissaoramoatividade = build_input("text","profissaoramoatividade")
        profissaoramoatividade.setAttribute("maxlength",40)
        profissaoramoatividade.value = urldecode(getCookie("profissaoramoatividade") ? getCookie("profissaoramoatividade") : "")
        fscp.childNodes[1].appendChild(profissaoramoatividade_label)
        fscp.childNodes[1].appendChild(profissaoramoatividade)
        fscp.childNodes[1].appendChild(document.createElement("br"))

        nascimentofundacao_label = build_label(labels[npessoa[pessoa]][5], "nascimentofundacao")
        nascimentofundacao = build_input("text","nascimentofundacao")
        nascimentofundacao.setAttribute("maxlength",40)
		nascimentofundacao.onfocus = function() {mascara("##/##/####", this)}
        nascimentofundacao.value = urldecode(getCookie("nascimentofundacao") ? getCookie("nascimentofundacao") : "")
        fscp.childNodes[1].appendChild(nascimentofundacao_label)
        fscp.childNodes[1].appendChild(nascimentofundacao)

        spanform.appendChild(fscp)
    }
    { //endereço
        fsen = build_fieldset("pessoal",legends[npessoa[pessoa]][1])

        endereco_label = build_label(labels[npessoa[pessoa]][6], "endereco")
        endereco = build_input("text","endereco")
        endereco.setAttribute("maxlength",60)
        endereco.value = urldecode(getCookie("endereco") ? getCookie("endereco") : "")
        fsen.childNodes[1].appendChild(endereco_label)
        fsen.childNodes[1].appendChild(endereco)
        fsen.childNodes[1].appendChild(document.createElement("br"))

        complemento_label = build_label(labels[npessoa[pessoa]][7], "complemento")
        complemento = build_input("text","complemento")
        complemento.setAttribute("maxlength",40)
        complemento.value = urldecode(getCookie("complemento") ? getCookie("complemento") : "")
        fsen.childNodes[1].appendChild(complemento_label)
        fsen.childNodes[1].appendChild(complemento)
        fsen.childNodes[1].appendChild(document.createElement("br"))

        bairro_label = build_label(labels[npessoa[pessoa]][8], "bairro")
        bairro = build_input("text","bairro")
        bairro.setAttribute("maxlength",30)
        bairro.value = urldecode(getCookie("bairro") ? getCookie("bairro") : "")
        fsen.childNodes[1].appendChild(bairro_label)
        fsen.childNodes[1].appendChild(bairro)
        fsen.childNodes[1].appendChild(document.createElement("br"))

        cidade_label = build_label(labels[npessoa[pessoa]][9], "cidade")
        cidade = build_input("text","cidade")
        cidade.setAttribute("maxlength",30)
        cidade.value = urldecode(getCookie("cidade") ? getCookie("cidade") : "")
        fsen.childNodes[1].appendChild(cidade_label)
        fsen.childNodes[1].appendChild(cidade)
        fsen.childNodes[1].appendChild(document.createElement("br"))

        uf_label = build_label(labels[npessoa[pessoa]][10], "uf")
        uf = build_input("text","uf")
        uf.setAttribute("maxlength",2)
        uf.value = urldecode(getCookie("uf") ? getCookie("uf") : "")
        fsen.childNodes[1].appendChild(uf_label)
        fsen.childNodes[1].appendChild(uf)
        fsen.childNodes[1].appendChild(document.createElement("br"))

        cep_label = build_label(labels[npessoa[pessoa]][11], "cep")
        cep = build_input("text","cep")
        cep.setAttribute("maxlength",9)
        cep.onfocus = function() { mascara('#####-###', this) }
        cep.onkeydown = function(e) {
            e = e || window.event
            return isInt(e.keyCode)
        }
        cep.value = urldecode(getCookie("cep") ? getCookie("cep") : "")
        fsen.childNodes[1].appendChild(cep_label)
        fsen.childNodes[1].appendChild(cep)

        spanform.appendChild(fsen)
    }
    { //contato
        fsct = build_fieldset("pessoal",legends[npessoa[pessoa]][2])

        telefone_label = build_label(labels[npessoa[pessoa]][12], "telefone")
        telefone = build_input("text","telefone")
        telefone.setAttribute("maxlength",15)
        telefone.value = urldecode(getCookie("telefone") ? getCookie("telefone") : "")
        fsct.childNodes[1].appendChild(telefone_label)
        fsct.childNodes[1].appendChild(telefone)
        fsct.childNodes[1].appendChild(document.createElement("br"))

        celular_label = build_label(labels[npessoa[pessoa]][13], "celular")
        celular = build_input("text","celular")
        celular.setAttribute("maxlength",15)
        celular.value = urldecode(getCookie("celular") ? getCookie("celular") : "")
        fsct.childNodes[1].appendChild(celular_label)
        fsct.childNodes[1].appendChild(celular)
        fsct.childNodes[1].appendChild(document.createElement("br"))

        fax_label = build_label(labels[npessoa[pessoa]][14], "fax")
        fax = build_input("text","fax")
        fax.setAttribute("maxlength",15)
        fax.value = urldecode(getCookie("fax") ? getCookie("fax") : "")
        fsct.childNodes[1].appendChild(fax_label)
        fsct.childNodes[1].appendChild(fax)
        fsct.childNodes[1].appendChild(document.createElement("br"))

        contato_label = build_label(labels[npessoa[pessoa]][15], "contato")
        contato = build_input("text","contato")
        contato.setAttribute("maxlength",40)
        contato.value = urldecode(getCookie("contato") ? getCookie("contato") : "")
        fsct.childNodes[1].appendChild(contato_label)
        fsct.childNodes[1].appendChild(contato)
        fsct.childNodes[1].appendChild(document.createElement("br"))

        site_label = build_label(labels[npessoa[pessoa]][16], "site")
        site = build_input("text","site")
        site.setAttribute("maxlength",255)
        site.value = urldecode(getCookie("site") ? getCookie("site") : "")
        fsct.childNodes[1].appendChild(site_label)
        fsct.childNodes[1].appendChild(site)
        fsct.childNodes[1].appendChild(document.createElement("br"))

        email_label = build_label(labels[npessoa[pessoa]][17], "email")
        email = build_input("text","email")
        email.setAttribute("maxlength",255)
        email.value = urldecode(getCookie("email") ? getCookie("email") : "")
        fsct.childNodes[1].appendChild(email_label)
        fsct.childNodes[1].appendChild(email)

        spanform.appendChild(fsct)
    }
    { // dados de acesso
        fsda = build_fieldset("pessoal",legends[npessoa[pessoa]][3])

        login_label = build_label(labels[npessoa[pessoa]][18], "login")
        login = build_input("text","login")
        login.setAttribute("maxlength",40)
        login.value = urldecode(getCookie("login") ? getCookie("login") : "")
        fsda.childNodes[1].appendChild(login_label)
        fsda.childNodes[1].appendChild(login)
        fsda.childNodes[1].appendChild(document.createElement("br"))

        senha_label = build_label(labels[npessoa[pessoa]][19], "senha")
        senha = build_input("password","senha")
        senha.setAttribute("maxlength",40)
        fsda.childNodes[1].appendChild(senha_label)
        fsda.childNodes[1].appendChild(senha)
        fsda.childNodes[1].appendChild(document.createElement("br"))

        csenha_label = build_label(labels[npessoa[pessoa]][20], "csenha")
        csenha = build_input("password","csenha")
        csenha.setAttribute("maxlength",40)
        fsda.childNodes[1].appendChild(csenha_label)
        fsda.childNodes[1].appendChild(csenha)
        fsda.childNodes[1].appendChild(document.createElement("br"))

        lembrete_label = build_label(labels[npessoa[pessoa]][21], "lembrete")
        lembrete = build_input("text","lembrete")
        lembrete.setAttribute("maxlength",40)
        lembrete.value = urldecode(getCookie("lembrete") ? getCookie("lembrete") : "")
        fsda.childNodes[1].appendChild(lembrete_label)
        fsda.childNodes[1].appendChild(lembrete)
        fsda.childNodes[1].appendChild(document.createElement("br"))

        spanform.appendChild(fsda)
    }
    { // botao enviar
        enviar_registro_a = document.createElement("a")
        enviar_registro_a.href="#";
        enviar_registro_a.className = "botao"
        enviar_registro_a.onclick = function(){
            if(csenha.value != senha.value){
                alert("Senha e confirmação de senha não coincidem");
                senha.focus();
                return false;
            }
            if(!login.value){
                alert("Login deve ser preenchido!");
                login.focus();
                return false;
            }
            if(senha.value.length < 6){
                alert("Senha deve ser ter no mínimo 6 carateres!");
                senha.focus();
                return false;
            }
            sendForm('frmCadastro');
        }
        enviar_registro_img = document.createElement("img")
        enviar_registro_img.src = src_button;
        enviar_registro_img.alt = "cadastrar";
        enviar_registro_a.appendChild(enviar_registro_img);
        spanform.appendChild(build_input("hidden","enviar_registro"))
        spanform.appendChild(enviar_registro_a)
        spanform.appendChild(document.createElement("br"))
    }

    return spanform;
}

function build_fieldset(classe, legend) {
    fieldset = document.createElement("fieldset")
    
    divform = document.createElement("div")
    divform.className="form"

    if(classe) {
        fieldset.className=classe
    }

    if(legend) {
        legendx = document.createElement("legend")
        legendx.appendChild(document.createTextNode(legend))
        fieldset.appendChild(legendx)
    }

    fieldset.appendChild(divform)
    return fieldset
}

function build_label(label, label_for){
    labelx = document.createElement("label")
    labelx.setAttribute("for",label_for)
    labelx.appendChild(document.createTextNode(label))
    return labelx
}

function build_input(type, name){
    input = document.createElement("input")
    input.type=type
    input.name=name
    return input
}

function urldecode( str ) {

    // transforma str em uma string
    str = str + ''

    // troca todos os + por espaço
    str = str.split('+').join(' ')

    // divide str em um array de carateres
    strarr = str.split('');

    // inverso de chr
    // String.charCodeAt(0);

    iniciacod = false // será true logo após o carater encontrado seja % e voltará a ser false dois laços depois
    letter = 0 // será incrementado até 2 quando iniciacod for true e depois voltará pra 0
    hexcodletter = '' // será usado para concatenar e guardar o codigo hexadecimal encontrado após o carater % até este ser convertido
    codletter = '' // será usado para armazenar temporariamente o codigo decimal do carater até este ser convertido em carater

    // percorre cada carater da string str
    for(i=0;strarr[i];i++) {

        // se encontrar o carater %, indica que os próximos dois carateres representarão o código hexadecimal de um carater unicode codificado
        if(strarr[i] == '%') {
            iniciacod = true // iniciacod passa a ser true até entrar nos dois proximos laços
            strarr[i] = '' // elimina este carater pois não será mais usado.
        }

        // se iniciacod for true
        if(iniciacod) {

            /* se letter for 0 indica que iniciacod acabou de ser convertido para true, e o carater atual que deveria ser % deve ter
            sido anulado, portanto no próximo laço, deverá ser tratado o primeiro carater que representa o codigo hexadecimal
            de um carater unicode codificado, só deverá entrar aqui quando letter for maior que zero. */
            if(letter) {
                hexcodletter += strarr[i] // concatena os dois carateres encontrados após %.
                strarr[i] = '' // apaga o carater atual, pois não será mais usado
                
                // quando complementar os dois laços após % então entra nesse loop. A variavel letter representa esse valor
                if(letter == 2) {
                    letter = -1 // reseta letter, após sair dessa condição a instrução 'letter++' tornará o valor desta variavel 0
                    iniciacod = false; // converte iniciacod para false, pois já foram capturados os dois carateres que representam o codigo hexadecimal do carater unicode codificado

                    // converte o codigo hexadecimal para decimal e converte o mesmo para string, pois se continuasse 
                    // inteiro 0xxx que representa o codigo decimal do carater unicode codificado seria convertido para xxx
                    // e não seria convertido abaixo para o carater correto
                    codletter = '0' + hexdec(hexcodletter) + ''

                    hexcodletter = '' // reseta o valor de hexcodletter, pois o seu valor já foi convertido para decimal
                    strarr[i] = String.fromCharCode(codletter) // converte o codigo do caracter para caracter (chr)
                    codletter = '' // reseta o valor de codletter, pois o seu valor já foi convertido para caracter (chr)
                }
            }
            letter++ // incrementa letter
        }
    }
    
    str = strarr.join('') // junta todos os carateres do array para torná-lo a string convertida.

    return str // retorna a string convertida :)
}

function hexdec(hex_string) {
    hex_string = (hex_string + '').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

function sendForm(id){
    formx = document.getElementById(id)
    formx.submit();
}

function getCookie(strCookie){
    var strNomeIgual = strCookie + "=";
    var arrCookies = document.cookie.split(';');

    for(var i = 0; i < arrCookies.length; i++){
        var strValorCookie = arrCookies[i];
        while(strValorCookie.charAt(0) == ' '){
            strValorCookie = strValorCookie.substring(1, strValorCookie.length);
        }
        if(strValorCookie.indexOf(strNomeIgual) == 0){
            return strValorCookie.substring(strNomeIgual.length, strValorCookie.length);
        }
    }
    return null;
}

window.onload = function() {
    if(window.location.toString().match(/index\.php\?tool\=atendimento\&dep\=[^&]*\&nome\=[^&]*\&atendendo\=true(#)?$/)) {
        window.setInterval("leChat()",1000);
    }
    ordenaPopups();
}

function ordenaPopups() {
    var conteudo = document.getElementById("conteudo");

    // dimensões da área de conteudo
    var pxc = conteudo.offsetLeft + 10;
    var pyc = conteudo.offsetTop + 10;

    // limite da área de conteudo
    plim = conteudo.offsetWidth + conteudo.offsetLeft;

    inp = 0;

    // altura do maior popup(mais alto)
    alt = 0;

    // limite vertical onde começa a proxima fila de popups
    limv = pyc;

    var divs = document.getElementsByTagName("div");
    for(var i=0; divs[i]; i++) {
        if(divs[i].id.substring(0, 3) == "pop") { // Every popup name is prefixed with "pop".
            var img = divs[i].getElementsByTagName("img").item(1);
            divs[i].style.width = img.width + "px";
            // se o posicionamento do proximo popup for ultrapassar os limites do conteudo
            // então passa para baixo 
            if(pxc + divs[i].offsetWidth > plim) {
                pxc = conteudo.offsetLeft + 10;

                // muda o limite vertical onde começam os novos popups
                limv += alt + 5;

                alt = 0;

                divs[i].style.left = pxc + "px"
                divs[i].style.top = limv + "px"

                pxc += divs[i].offsetWidth + 5;
            } else {
                divs[i].style.left = pxc + "px"
                divs[i].style.top = limv + "px"

                pxc += divs[i].offsetWidth + 5;
            }

            // move o popup para a area de conteudo

            // altura do maior popup
            if(divs[i].offsetHeight > alt) {
                alt = divs[i].offsetHeight;
            }

            // prepara para o proximo popup
            popid = "pop" + (++inp);

        }
    }
}

// Função de debug
function pao(object) {
    for (i in object) {
        document.write("<b>"+i+"</b>:" + object[i] + "<br />");
    }
}

function fechaPopup(popup) {
    cookiepopups = getCookie("popups");
    
    jaexistepopup = false;
    if(cookiepopups) {
        arraypopups = cookiepopups.split("|");
        for(i in arraypopups) if(arraypopups[i] == popup.id) jaexistepopup = true;
    }

    if(!jaexistepopup) document.cookie = "popups=" + (cookiepopups ? cookiepopups+"|" : "") + popup.id;
    popup.style.display="none";
}

function vertical_padding_auto(objeto) {
	if(objeto) {
		var div = document.createElement("div")
		for(var i = objeto.childNodes.length-1; i >= 0; i--) {
			div.insertBefore(objeto.childNodes[i], div.firstChild);
		}
		objeto.appendChild(div)
		div.style.padding = Math.floor((objeto.offsetHeight - div.offsetHeight) / 2) + "px 0"
	}
}

// mascara versão 1.0 - 15/19/2010 - jairhumberto@gmail.com
function mascara(m, o) {
	o.onkeyup = function(e) {
		e = e || window.event
		if(e.keyCode != 8) {
			var array_m = m.split('')
			var array_o_value = o.value.split('')
			retorno = new Array()
			for(var i=0; array_o_value[i]; i++) {
				retorno[i] = array_m[i] == '#' ? array_o_value[i] : array_m[i]
				if(i == array_o_value.length - 1) while(array_m[++i] && array_m[i] != '#') retorno[i] = array_m[i]
			}
			o.value = retorno.join('')
		}
	}
}

String.prototype.replaceall = function(o, s) {
	var str = this.split('');
	var nstr = new Array();
	for(var i=0; str[i]; i++) nstr[i] = str[i] == o ? s : str[i]
	return nstr.join('');
}

String.prototype.find = function(c) {
	var str = this.split('');
	for(var i=0; str[i]; i++) if(str[i] == c) return true
	return false;
}

function isInt(kc) {
	if((kc >= 48 && kc <= 57) || (kc >= 96 && kc <= 105) || teclaFuncional(kc)) return true
	return false;
}

function isDouble(o, kc) {
	o.value = o.value.replaceall(",",".");
	if((!o.value.find(".") || (kc != 194 && kc != 110)) && (isInt(kc) || kc == 194 || kc == 110)) return true;
	else return false;
}

function teclaFuncional(kc) {
	if(kc == 8 || kc == 9 || kc == 12 || kc ==13 || kc == 27 || (kc >= 33 && kc <= 40) || kc == 45 || kc == 46 || kc == 144 || kc == 145 || (kc >= 16 && kc <= 20) || (kc >= 91 && kc <= 93) || (kc >= 112 && kc <= 123)) return true
	return false
}
