﻿var manage = {
    form: document.forms[0],
    removerValidacao: '',
    blnTemSalvar: false,
    initialize: function(){
    
        //var inputs = document.getElementsByTagName('input');
        var inputs = document.forms[0].elements;
        for(x=0;x<inputs.length;x++){
            if(!inputs[x].getAttribute('disabled')){
                if(inputs[x].getAttribute('btnSalvar') == 'true'){
                    manage.blnTemSalvar = true;
                    addEvent(inputs[x],'click',function(){return manage.validaForm();});
                }else{
                    if(inputs[x].getAttribute('foco') == 'true')
                        inputs[x].focus();
                       
                }
                if(inputs[x].getAttribute('tooltip_help')){
                    var nohPai = inputs[x].parentNode;
                    var a = document.createElement('a');
                    var img = document.createElement('img');
                    var span = document.createElement('span');                 
                    a.href ='#';
                    a.className = 'dcontexto';
                    img.src = 'img/pagina1/btn/btnAjuda2.gif';                    
                    span.innerHTML = inputs[x].getAttribute('tooltip_help');
                   a.appendChild(img);
                    a.appendChild(span);
                    nohPai.appendChild(a);                                        
                }
            }
        }
        if(!manage.blnTemSalvar){
            if(document.getElementById('Toolbar_Salvar')) addEvent(document.getElementById('Toolbar_Salvar'),'click',function(){return manage.validaForm();});
            if(document.getElementById('Toolbar1_Salvar')) addEvent(document.getElementById('Toolbar1_Salvar'),'click',function(){return manage.validaForm();});
            if(document.getElementById('btnSalvar')) addEvent(document.getElementById('btnSalvar'),'click',function(){return manage.validaForm();});
            if(document.getElementById('btnSalvar2')) addEvent(document.getElementById('btnSalvar2'),'click',function(){return manage.validaForm();});
        }
    },
    validaForm: function(){
        var form = manage.form;
        var splRemValidacoes = manage.removerValidacao.split('#');
        for(i=0;i<form.length;i++){
            if(!form[i].getAttribute('disabled')){
                if(manage.verificaRemocaValidacao(splRemValidacoes, form[i].id)){
                    if(form[i].getAttribute('valida') == 'true'){
                        if(form[i].value.trim().replace("'","") == ''){
                            alert('Campo Obrigatório: ' + form[i].getAttribute('validamsg'));
                            form[i].focus();
                            return false;
                        }
                    }
                    if(form[i].getAttribute('type') == 'DATA' && form[i].value.trim() != ''){
                        if(!check_date(form[i])) return false;
                    }else{
                        if((form[i].getAttribute('type') == 'NUMÉRICO' && form[i].value.trim() != '') && isNaN(form[i].value.replace('.',',').trim())){
                            alert('Valor inválido!');
                            form[i].focus();
                            return false;
                        }else{
                            if((form[i].getAttribute('type') == 'MONETÁRIO' && form[i].value.trim() != '') && isNaN(form[i].value.replace(',','.').trim())){
                               alert('Valor inválido!');
                                form[i].focus();
                                return false; 
                            }
                        }
                    }            
                }
            }
        }
        return true;
    },
    verificaRemocaValidacao: function(arrRem, id){
        for(y=0;y<arrRem.length;y++)
            if(arrRem[y] == id) return false;
        return true;
    }
}
/****************************************************************/
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
}
/****************************************************************/
function addEvent(obj, evType, fn){
    if (obj.addEventListener) //Non-IE
	    obj.addEventListener(evType, fn, true)
    if (obj.attachEvent) //IE
	    obj.attachEvent('on' + evType, fn)
}
/****************************************************************/
function removeEvent(obj, evType, fn){
    if (obj.removeEventListener) //Non-IE
	    obj.removeEventListener(evType, fn, false)
    if (obj.detachEvent) //IE
	    obj.detachEvent('on' + evType, fn)
}
/****************************************************************/
function getScrollYX(){
    var scrOfX = 0, scrOfY = 0;
    if(typeof(window.pageYOffset) == 'number' ){
	    //Netscape compliant
	    scrOfY = window.pageYOffset;
	    scrOfX = window.pageXOffset;
    }else 
	    if(document.body && (document.body.scrollLeft || document.body.scrollTop)){
		    //DOM compliant
		    scrOfY = document.body.scrollTop;
		    scrOfX = document.body.scrollLeft;
	    }else 
		    if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)){
			    //IE6 standards compliant mode
			    scrOfY = document.documentElement.scrollTop;
			    scrOfX = document.documentElement.scrollLeft;
		    }
    return [scrOfY, scrOfX];
}
/****************************************************************/
function GetSize(){
	var myWidth = 0, myHeight = 0;
	if(typeof( window.innerWidth ) == 'number'){
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}else 
		if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)){
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		}else 
			if(document.body && (document.body.clientWidth || document.body.clientHeight)){
				//IE 4 compatible
				myWidth = document.body.clientWidth;
				myHeight = document.body.clientHeight;
			}
		return [myHeight, myWidth];
}
/****************************************************************/
function check_date(DATA) {
    var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
    var msgErro = 'Formato inválido de data.';
    var vdt = new Date();
    var vdia = vdt.getDay();
    var vmes = vdt.getMonth();
    var vano = vdt.getYear();
    if ((DATA.value.match(expReg)) && (DATA.value!='')){
        var dia = DATA.value.substring(0,2);
        var mes = DATA.value.substring(3,5);
        var ano = DATA.value.substring(6,10);
        if((mes==04 && dia > 30) || (mes==06 && dia > 30) || (mes==09 && dia > 30) || (mes==11 && dia > 30)){
        alert("Dia incorreto !!! O mês especificado contém no máximo 30 dias.");
        DATA.focus();
        return false;
    } else{ //1
        if(ano%4!=0 && mes==2 && dia>28){
            alert("Data incorreta!! O mês especificado contém no máximo 28 dias.");
            DATA.focus();
            return false;
        } else{ //2
            if(ano%4==0 && mes==2 && dia>29){
                alert("Data incorreta!! O mês especificado contém no máximo 29 dias.");
                DATA.focus();
                return false;
            } else{ //3
                return true;
            } //3-else
        }//2-else
    }//1-else
    } else { //5
        alert(msgErro);
        DATA.focus();
        return false;
    } //5-else
}
function GetEventDispatched(eEvent,ReturnProperty){
		switch(ReturnProperty){
		case "target" :								
		case "srcElement" :		
			return eEvent.target ? eEvent.target : eEvent.srcElement; 
		case "fromElement" :
		case "relatedTarget" :
			return eEvent.fromElement ? eEvent.fromElement : eEvent.relatedTarget; 
		}	
    }
var tempo_tootip=0;
var el_tootip=null;
addEvent(window,"load", function(){
    var cbo =  document.getElementsByTagName("select");
    var txt =  document.getElementsByTagName("input");
    for (i=0;i<cbo.length ;i++){
        if (cbo[i].getAttribute("tooltip_help")){
            addEvent(cbo[i], "mouseover", function(evt){            
                var el =  GetEventDispatched(evt,"target");
                el_tootip =  el;
                tempo_tootip=setTimeout(function(){                  
                    if(el_tootip) parent.abreBoxMsg(200,50,"Mensagem Ajuda",el_tootip.getAttribute("tooltip_help"), 3000);                    
                },1000);
             });
            addEvent(cbo[i], "mouseout", function(evt){    
                clearTimeout(tempo_tootip);
                el_tootip=null;
            }); 
        }                  
    }
    for (i=0;i<txt.length ;i++){
        if (txt[i].type=="text" && txt[i].getAttribute("tooltip_help")){
            addEvent(txt[i], "mouseover", function(evt){            
                var el =  GetEventDispatched(evt,"target");
                el_tootip =  el;
                tempo_tootip=setTimeout(function(){                
                    if(el_tootip) parent.abreBoxMsg(200,50,"Mensagem Ajuda",el_tootip.getAttribute("tooltip_help"), 3000);
                },1000);
              });
            addEvent(txt[i], "mouseout", function(evt){    
                clearTimeout(tempo_tootip);
                el_tootip=null;
            });                                
        }
    }    
});
/****************************************************************/
function abreBoxMsg(plargura, paltura, ptitulo, ptexto, ptempoAlerta){
    var box = windowBox;
    with(box){
        largura = plargura;
        altura = paltura;
        titulo = ptitulo;
        texto = ptexto;
        tipo = 0;
        tempoAlerta = ptempoAlerta;
        criaBox();
    }
}
/****************************************************************/
function abreBoxOK(plargura, paltura, ptitulo, ptexto){
    var box = windowBox;
    with(box){
        largura = plargura;
        altura = paltura;
        titulo = ptitulo;
        texto = ptexto;
        tipo = 2;
        criaBox();
    }
}
/****************************************************************/
function abreBoxIframe(plargura, paltura, ptitulo, purl, pExecuta){
    var box = windowBox;
    with(box){
        largura = plargura;
        altura = paltura;
        titulo = ptitulo;
        url = purl;
        tipo = 3;
        if(pExecuta) executa = pExecuta;
        criaBox();
        return false;
    }
}
/****************************************************************/
function abreBoxQuestion(plargura, paltura, ptitulo, ptexto,  pobj){
    var box = windowBox;
    with(box){
        largura = plargura;
        altura = paltura;
        titulo = ptitulo;
        texto = ptexto;
        tipo = 1;
        obj = pobj;
        if(obj) executa = function(){windowBox.obj.onclick = ''; windowBox.obj.click();};
        criaBox();
        return false;        
    }
}
/****************************************************************/
function confirmExclusao(obj){
    return confirm("Tem certeza de que deseja excluir o registro?");    
    //parent.abreBoxQuestion(265, 30, '<center>Confirmação</center>', 'Tem certeza de que deseja excluir o registro?', obj);
    //return false;
}

/****************************************************************/
function MostraEscondeDetalhe(img){
    var divDetalhe = document.getElementById('divDetalhe');
    if(divDetalhe.style.display == 'none'){
        divDetalhe.style.display = 'block';
        img.src = 'img/imenos.gif';
        img.alt = 'Ocultar Detalhe!';
    }else{
        divDetalhe.style.display = 'none';    
        img.src = 'img/imais.gif';
        img.alt = 'Mostrar Detalhe!';
    }
}
/****************************************************************/
function RetornaTecla(event){
    return event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
}
/****************************************************************/
function autoIframe(obj) { 
   try{
      //alert(obj.contentDocument.offsetHeight);
      frame = obj;
      innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
      objToResize = (frame.style) ? frame.style : frame;
      if (innerDoc.body.scrollHeight != 0)           
      {        
        objToResize.height = innerDoc.body.scrollHeight; //+ 10; // Firefox        
      }
      else
      {        
        obj.height = 350;
        document.getElementById("divGradiente").style.height = "440px";     
        obj.scrolling = "auto";            
      }
   }
   catch(err){
      window.status = err.message;
   }
}
/****************************************************************/
function setTitulo(sTitulo)
{
    document.getElementById('divtitSecao').innerHTML = sTitulo;
}

function AbrePesquisa(Titulo, Tipo, Campo, Adicional){
    if(Adicional == undefined) 
        Adicional = '';
    return parent.abreBoxIframe(400, 320, Titulo, 'frmPesquisa.aspx?Tipo=' + Tipo + '&Valor=' + Campo.value + Adicional, function(){Campo.focus();});
}

 function AbrePesquisaFarmacia(codItem, codRequis, tipoRequisicao, codProduto){
    return parent.abreBoxIframe(400, 320, 'Materiais', 'frmPesquisa.aspx?Tipo=5' + '&codItem=' + codItem + '&codRequis=' + codRequis + '&TipoRequisicao=' + tipoRequisicao + '&codProduto='+ codProduto, function(){});
}

function AbrePesquisaHorarios(codPrescr, codItem, codHorario, Horario, Cont, Periodo, Atendimento){
    return parent.abreBoxIframe(400, 100, 'Horários', 'frmPesquisa.aspx?Tipo=6&codPrescr=' + codPrescr + '&codItem=' + codItem + '&codHorario=' + codHorario + '&Horario=' + Horario + '&Cont=' + Cont + '&Periodo=' + Periodo + '&Atendimento= ' + Atendimento, function(){});
}

function AbreBoxObs(arrItens, tipo, status, codigo){
    return parent.abreBoxIframe(300, 200, 'Observação', 'frmSendObs.aspx?arrCodItens=' + arrItens + '&tipo='+ tipo +'&status='+ status + '&codRequis='+ codigo + '', function(){});
}


 function select_form(seta_item,selecionado){
  if (selecionado == 1){
     document.getElementById(seta_item).style.backgroundImage = "url('img/left_form_selected.jpg')";
     
  }
  else {
     document.getElementById(seta_item).style.backgroundImage = "url('img/left_form_select.jpg')";
  }
 }

function showHide(obj, bool)
{
    if(bool)
        document.getElementById(obj).style.display= 'block';
    else
       document.getElementById(obj).style.display= 'none'; 
}

// função para não deixar que a página abra no frame abaixo
function VerifyFrame(nomePag){
    if(self.parent.frames.length>0) self.parent.location=nomePag;
}   

function HabilitaDesabilitaCombos(valor){
    var cboVia = document.getElementById('cboVia');
    var cboPeriodo = document.getElementById('cboPeriodo');
    
    if(valor != ''){
        cboVia.selectedIndex = 0;
        cboPeriodo.selectedIndex = 0;
        cboVia.disabled = true;
        cboPeriodo.disabled = true;
    }else{
        cboVia.disabled = false;
        cboPeriodo.disabled = false;
    }
}
function ativaDesativaCampos(id, bool)
{
    if(bool)
        document.getElementById(id).disabled = false;
    else
        document.getElementById(id).disabled = true;
}

Text = {
    AutoComplete : function(text,evt){
        try{    
            k =  String.fromCharCode(crossBrowser.key(evt));
            if(k=="2" && evt.shiftKey ){
                var el  = crossBrowser.srcElem(evt);
                el.value+=text;
                Text.SelectText(el,text);
            }   
        }catch(e){};          
    },
    //------------------------------------------------
    SelectText : function (el,text){
        var textRange = el.createTextRange();
        textRange.findText(text);
        textRange.select(el);      
    }

}

/**********************************************************
Validação
**********************************************************/
function go(url) { window.location.href = url; }
function o(id) { return document.getElementById(id); }
function ce(el) { return document.createElement(el); }


var sendForm = false;
function x_validaCampos(e)
{
	validaCampos(e);
}
function validaCampos(e) {
    var validateAction = true;
    var validateRealTime = true;
    var it;
    var frm = document.forms[0];
    var el = frm.getElementsByTagName('input');
    var cbo = frm.getElementsByTagName('select');

    if (e.type == 'click') sendForm = true;

    o('divListaErros').innerHTML = '';
    o('divListaErros2').innerHTML = '';

    for (c = 0; c < el.length; c++) {
        if (typeof (el[c].getAttribute('required')) == 'string') {
            if (el[c].value == '') {
                it = ce('div');
                it.innerHTML = 'O campo <b>' + el[c].getAttribute('title') + '</b> não foi preenchido<br>';
                o('divListaErros').appendChild(it);
                validateAction = false;
            }
        }
        //---------------- 
        if (typeof (el[c].getAttribute('format')) == 'string') {
            if (el[c].value != '') {
                var msg = checkDate(el[c]);
                if (msg != '') {
                    it = ce('div');
                    it.innerHTML = 'Campo <b>' + el[c].getAttribute('title') + '</b>: ' + msg;
                    o('divListaErros2').appendChild(it);
                    
                }
            }
        }
    }
    //----------------
    for (n = 0; n < cbo.length; n++) {
        if (typeof (cbo[n].getAttribute('required')) == 'string') {
            if (cbo[n].selectedIndex == 0) {
                it = ce('div');
                it.innerHTML = '<b>' + cbo[n].getAttribute('title') + '</b> não foi selecionado<br>';
                o('divListaErros').appendChild(it);
                validateAction = false;
            }
        }
    }
    //----------------
    if (validateAction) {
        o('divAlerta').style.display = 'none';
    }
    else {
        o('divAlerta').style.display = '';

        if (e.type == 'blur') {
            if (sendForm)
                o('divListaErros').style.display = '';
            else
                o('divListaErros').style.display = 'none';
        } else
            o('divListaErros').style.display = '';
    }
    return (validateAction);
}


/**********************************************************
Verifica se a data digitada existe
**********************************************************/
function checkDate(txt) {
    var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
    var msgErro = '';
    var vdt = new Date();
    var vdia = vdt.getDay();
    var vmes = vdt.getMonth();
    var vano = vdt.getYear();

    if (txt.value != '') {
        if (txt.value.match(expReg)) {
            var dia = txt.value.substring(0, 2);
            var mes = txt.value.substring(3, 5);
            var ano = txt.value.substring(6, 10);

            if ((mes == 04 && dia > 30) || (mes == 06 && dia > 30) || (mes == 09 && dia > 30) || (mes == 11 && dia > 30)) {
                msgErro = 'Dia incorreto !!! O mês especificado contém no máximo 30 dias';
            } else {
                if (ano % 4 != 0 && mes == 2 && dia > 28) {  //a4
                    msgErro = 'Data incorreta!! O mês especificado contém no máximo 28 dias';
                } else {
                    if (ano % 4 == 0 && mes == 2 && dia > 29) { //a5
                        msgErro = 'Data incorreta!! O mês especificado contém no máximo 29 dias';
                    }
                }
            }
        } else {
            msgErro = 'Data em formato incorreto';
        }
    }
    return msgErro
}

/**********************************************************
Mascara de data
**********************************************************/
function mascaraData(campoData) {
    var data = campoData.value;

    if (data.length == 2) {
        data = data + '/';
        campoData.value = data;
    }
    if (data.length == 5) {
        data = data + '/';
        campoData.value = data;
    }
    return true;
}

/**********************************************************
Retorna "false" se a tecla digitada nao for numerica     
**********************************************************/
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;

    if (charCode == 8 || charCode == 46)
        evt.srcElement.value = '';

    if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105))
        return false;

    return true;
}


/****************************
Gerenciamento de Cookies 
****************************/

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function checkCookie() {
    var show = getCookie("show");
    if (show != null && show != "") {
        if (show == '0')
            return false;
        else
            return true
    } else
        return true;
}
