String.prototype.trim = function(){
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

String.prototype.startsWith = function(t){
	return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
};

String.prototype.has = function(t){
	return (this.toLowerCase().indexOf(t.toLowerCase()) >= 0);
};

function isBlank(value){
	return value == null || value.trim() == '';
}

function isNotBlank(value){
	return value != null && value.trim() != '';
}

function limpaValorNaCombo(campo, idCombo, event){
	var texto = jQuery(campo).val();
	var combo = jQuery('#' + idCombo);
	
}

function achaValorNaCombo(campo, idCombo, event){
	var texto = jQuery(campo).val();
	var combo = jQuery('#' + idCombo);
	
	var done = false; 
	
	if(!keyIn([9, 16, 17,18], event)){
		if(texto == ''){
			if (event.type != "blur") { combo.val('');}
			return true;
		}
		
		jQuery.each(combo.children('option'), function(){
			if(!done){
				var option = jQuery(this);
				//if(option.val().startsWith(texto) || option.text().startsWith(texto)){
				if(option.text().startsWith(texto)){
					combo.val(option.val());
					done = true;
					combo.change();
					return true;
				}
			}
		});
		if(!done){
			jQuery.each(combo.children('option'), function(){
				if(!done){
					var option = jQuery(this);
					if(option.text().has(texto)){
						combo.val(option.val());
						done = true;
						combo.change();
						return true;
					}
				}
			});
		}
		
	}
}

function setaComboPorTexto(texto, idCombo){
	var combo = jQuery('#' + idCombo);
	jQuery.each(combo.children('option'), function(){
		var option = jQuery(this);
		if(option.text() == texto){
			combo.val(option.val());
			return;
		}
	});
}

function setaComboPorInicioTexto(texto, idCombo){
	var combo = jQuery('#' + idCombo);
	jQuery.each(combo.children('option'), function(){
		var option = jQuery(this);
		if(option.text().startsWith(texto)){
			combo.val(option.val());
			return;
		}
	});
}

function onlyNumbers(e){
	var key = '';
	var strCheck = '0123456789';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	if (whichCode == 8) return true;   // BackSpace
	if (whichCode == 0) return true;   // Del
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	}
	
	return true;
}

function completarZerosEsquerda(maxLength, value) {
	restante = parseInt(maxLength) - parseInt(value.length);
	novoValor = "";
	for(i=0; i<restante; i++) {
		novoValor = novoValor + "0";
	}
	novoValor = novoValor + value;
	return (novoValor);
}

function checkMaxLength(obj, maxLength){
	if (jQuery(obj).val().length > maxLength)
		jQuery(obj).val(jQuery(obj).val().substring(0,maxLength));
}

function eliminaZeroEsquerda(numero){
	var achouDiferenteZero = false;
	var i = 0;
	while (i < numero.length){
		if (numero[i]!="0")	break;	
		i++;
	}
	return(numero.substring(i, numero.length));
}

function toDate(string){
	var date = new Date();
	var dia, mes, ano;
	split = string.split("/");
	
	dia = parseInt(split[0], 10);
	mes = parseInt(split[1], 10)-1;
	ano = parseInt(split[2], 10);
	
	date.setFullYear(ano, mes, dia);
	
	return date;
}

function comparaDatas(data1, data2){
	var d1 = toDate(data1);	
	var d2 = toDate(data2);	
	
	if (d1 == d2){
		return 0;
	} else if (d1 < d2){
		return -1;
	} else if (d1 > d2){
		return 1;
	}
}


function verificaDataValida(dataX){
	  var result = true;
	  
	  //Dia Mes e Ano
	  var reDate = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	  
	  //Mes e Ano
	  //var reDate = /^((0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	  
	  if(reDate.test(dataX)== false){
	     result = false;
	  }
	  return result;
}

function verificaDataMesAnoValida(dataX){
	  var result = true;
	  
	  //Dia Mes e Ano
	  //var reDate = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	  
	  //Mes e Ano
	  var reDate = /^((0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	  
	  if(reDate.test(dataX)== false){
	     result = false;
	  }
	  return result;
}

function calcularIdade(dataNascimento, outraData){
	var statusNascimento  = verificaDataValida(dataNascimento);
	var statusOutra = verificaDataValida(outraData);

	if((statusNascimento == true && statusOutra == true)){
		var arrayNascimento = dataNascimento.split("/");
		var diaNascimento = parseFloat(eliminaZeroEsquerda(arrayNascimento[0]));
		var mesNascimento = parseFloat(eliminaZeroEsquerda(arrayNascimento[1]));
		var anoNascimento = parseFloat(eliminaZeroEsquerda(arrayNascimento[2]));
		
		var arrayOutra = outraData.split("/");
		var diaOutra = parseFloat(eliminaZeroEsquerda(arrayOutra[0]));
		var mesOutra = parseFloat(eliminaZeroEsquerda(arrayOutra[1]));
		var anoOutra = parseFloat(eliminaZeroEsquerda(arrayOutra[2]));
		
		var idade = anoOutra - anoNascimento;
		
		if ((mesOutra > mesNascimento) || ((mesOutra == mesNascimento) && (diaOutra >= diaNascimento))){
			return idade;
		} else {
			return (idade - 1);
		}

		//if ((mesOutra >= mesNascimento) && (diaOutra >= diaNascimento)){
		//	idade++;
		//}
		//return idade;
	} else {
		return '';
	}
}

function anoDeData(data){
	var status = verificaDataValida(data);

	if((status == true)){
		var ano = parseInt(eliminaZeroEsquerda(data.substring(6)));
		return ano;
	} else {
		return '';
	}
}

function diaDeData(data){
	var status = verificaDataValida(data);

	if((status == true)){
		var dia = parseInt(eliminaZeroEsquerda(data.substring(0, 2)));
		return dia;
	} else {
		return '';
	}
}

function mesDeData(data){
	var status = verificaDataValida(data);

	if((status == true)){
		var mes = parseInt(eliminaZeroEsquerda(data.substring(3, 5)));
		return mes;
	} else {
		return '';
	}
}

function trataAspas(str)
{
	i = 0;
	strDest = '';
	while (i < str.length)
	{
		if (str.substring(i, i+1) == '"')
			strDest = strDest + "\\u0022";
		else if (str.substring(i, i+1) == "'")
			strDest = strDest + "\\u0027";	
		else
			strDest = strDest + str.substring(i, i+1);
		i++;
	}
	return(strDest);
}

function copiarCampo(ori, dest)
{
	dest.val(ori.val());
}

function acionaEnter(event, formulario) 
{   
    var keynum;   

    if(window.event) 
    { //IE   
        keynum = event.keyCode;   
    } 
    else if(event.which) 
    { 
        // Netscape/Firefox/Opera   
        keynum = event.which;   
    }   
    if( keynum==13) 
    { 
        eval(formulario).submit();   
    }   
}



function acionaEnterJSF(event, nomeForm, idComponente) 
{   
    var keynum;   
    if(window.event) 
    { //IE   
    	keynum = event.keyCode;   
    } 
    else if(event.which) 
    { 
    	// Netscape/Firefox/Opera   
        keynum = event.which;   
    }   
    if( keynum==13) 
    { 
    	document.getElementById(nomeForm+":"+idComponente).click();
    }   
}




function validaCnes1(cnes){
	var retorno = true;
	var mensagem = "";
	var mensagemFinal = "";


	if(cnes == null || cnes.trim == ""){
		 retorno = false;
	}
	if(cnes.length != 7){
		 retorno = false;
	}

	var digito = parseInt(cnes.substr(cnes.length - 1, 1));

	var codigo = '00000' + cnes.substr(0, cnes.length - 1);
	codigo = codigo.substr(codigo.length - 6, 6)

	var magic = 7;
	var soma = 0;

	for(var i = 0; i < codigo.length; i++){
	soma += parseInt(codigo.substr(i, 1)) * magic--;
	}

	var check = 11 - (parseInt(soma) % 11);
	if(check == 11){
    	check = 0;
	} else {
	   if(check != 10){
	     check = 11 - (soma % 11);
	   }
	}

	if(check == digito){
		retorno =true;
	}else{
		
        retorno = false;
	}	

	if (retorno == false){		
        retorno = false;
	        
	}	

	return retorno;

 }

function showHideLoader(id, show){
	if(show){
		jQuery("#" + id).show();
	}else{
		jQuery("#" + id).hide();
	}
}

function showWaitRequestLoader(){
	jQuery('#divPopupAguarde').attr("disabled", false);
	//jQuery('#divPopupAguarde').jqm({ajax: urlWait, modal: true, trigger: false, overlay: 60}).jqmShow();
	jQuery('#divPopupAguarde').jqm({modal: true, trigger: false, overlay: 60}).jqmShow();
}

function closeWaitRequestLoader(){
	jQuery('#divPopupAguarde').jqmHide();
}

function selectAll(selector){
	jQuery(selector).children("option").attr("selected","selected");
}

function validaAnos(anoInicio, anoFim){
	return anoInicio != "" && anoInicio.indexOf("_") == -1 && anoFim != "" && anoFim.indexOf("_") == -1 && 
	       parseInt(anoFim, 10) >= parseInt(anoInicio, 10);
}

function bloqueiaCaracteresInvalidos(){
	var tecla = window.event.keyCode;
  
	tecla = String.fromCharCode(tecla);
	
	if(tecla == "\\" || tecla == "/" || tecla == ":" || 
	   tecla == "*" || tecla == "?" || tecla == "\"" || 
	   tecla == "<" || tecla == ">" || tecla == "|" ||
	   tecla == ";" || tecla == "," || tecla == "."){
		window.event.keyCode = 0;
	}
}

function MascaraTelefone(telefone){ 
    if(mascaraInteiro(telefone)==false){ 
    	event.returnValue = false; 
    }        
    return formataCampo(telefone, '00 0000-0000', event); 
}

function MascaraCPF(cpf){
    if(mascaraInteiro(cpf)==false){
            event.returnValue = false;
    }       
    return formataCampo(cpf, '000.000.000-00', event);
}

function showLoading(data){
	var img = jQuery(data.source).parent().find("img.loading"); // Pegar o elemento img que est� dentro do mesmo container do select
    var ajaxStatus = data.status; // Can be "begin", "complete" and "success".

    switch (ajaxStatus) {
        case "begin": // This is called right before ajax request is been sent.
            img.show();
            break;

        case "complete": // This is called right after ajax response is received.
        	img.hide();
            break;

        case "success": // This is called when ajax response is successfully processed.
        	img.hide();
            break;
    }
}

function imprimirGrafico(url, callback){
	var popW = 800;
	var popH = 600;
	var winleft = (screen.width - popW) / 2;
	var winUp = (screen.height - popH) / 2;
	winProp = 'width='+popW+',height='+popH+',left='+winleft+',top='+winUp+',scrollbars=yes,resizable';
	newwindow=window.open(url,'',winProp);
	if (callback) callback(newwindow.document);
	//newwindow.print();
}

function sortPickList(e) {
	//item = e.item
	//fromList = e.from
	//toList = e.toList
	//type = e.type (type of transfer; command, dblclick or dragdrop)
	//ordenaSelectAlfa(e.from);
	//ordenaSelectAlfa(e.toList);
}

function ordenaUlPorTexto(ul){
    var o = new Array();
    ul.children().each(function(i, li){
        o[o.length] = li.innerHTML;
    });
    
    o = o.sort(
        function(a,b){ 
            if ((a.text+"") < (b.text+"")) { return -1; }
            if ((a.text+"") > (b.text+"")) { return 1; }
            return 0;
        } 
    );

    var html = "";
    for (i=0; i<o.length; i++){
    	ul.children().each(function(j, li){
            if (o[i] == li.innerHTML)
            	html;
        });
    	
        obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
    }
}

function gerarImagemGrafico(chart){
	if ($.jqplot.use_excanvas){
		alertNavegadorNaoSuportado.show();
//		alert('A vers\u00E3o deste navegador n\u00E3o suporta esta funcionalidade');
		return;
	}
	
	jQuery("#conteudoImagem").html(jQuery("#" + chart).jqplotToImageElemStr());
	if (jQuery("#conteudoImagem img").attr('height') > 600)
		jQuery("#conteudoImagem img").attr('height', 600);
	popupImagemGrafico.show();
}

function salvarImagemGrafico(chart){
	if ($.jqplot.use_excanvas){
		alertNavegadorNaoSuportado.show();
		return;
	}
	
	jQuery("#" + chart).jqplotSaveImage();
}

function selecionarMenuModelo(){
	var p = window.location.href.indexOf("Modelo", 0);
	var modelo = "btn" + window.location.href.substring(p, window.location.href.indexOf("/", p));
	jQuery("a." + modelo).removeClass(modelo).addClass(modelo + "Sel");
}

function isLayoutMobile() {
	return is_touch_device() || jQuery(window).width() < 910;
}

function is_touch_device() {
	 return (('ontouchstart' in window)
	      || (navigator.MaxTouchPoints > 0)
	      || (navigator.msMaxTouchPoints > 0));
}

function initResponsive(){
	jQuery(document).ready(function () {
	    jQuery(".bt-menu").click(function (event) {
	        jQuery(".menu_modelos").animate({ left: "0px" }, 300);
	        jQuery("#menuPanoPreto").show();
	        event.preventDefault();
	    });
	    
	    jQuery("#menuPanoPreto").click(function (event) {
	    	esconderMenuSuspenso();
	    	event.preventDefault();
	    });
	    
	    jQuery(window).resize(function(e){
	    	if (jQuery(window).width() > 900 && jQuery(".menu_modelos").is(":visible"))
	    		esconderMenuSuspenso();
	    });
	});	
}

function esconderMenuSuspenso(){
	if (jQuery(".menu_modelos").css("z-index") != "9999") return;
	
	jQuery(".menu_modelos").animate({ left: "-140px" }, 300);
    jQuery("#menuPanoPreto").hide();
}
