var g_arrUF = {"1":{"idUF":"AC","Dsc_UF":"ACRE"},"2":{"idUF":"AL","Dsc_UF":"ALAGOAS"},"3":{"idUF":"AM","Dsc_UF":"AMAZONAS"},"4":{"idUF":"AP","Dsc_UF":"AMAP\u00c1"},"5":{"idUF":"BA","Dsc_UF":"BAHIA"},"6":{"idUF":"CE","Dsc_UF":"CEAR\u00c1"},"7":{"idUF":"DF","Dsc_UF":"DISTRITO FEDERAL"},"8":{"idUF":"ES","Dsc_UF":"ESP\u00cdRITO SANTO"},"9":{"idUF":"GO","Dsc_UF":"GOI\u00c1S"},"10":{"idUF":"MA","Dsc_UF":"MARANH\u00c3O"},"11":{"idUF":"MG","Dsc_UF":"MINAS GERAIS"},"12":{"idUF":"MS","Dsc_UF":"MATO GROSSO DO SUL"},"13":{"idUF":"MT","Dsc_UF":"MATO GROSSO"},"14":{"idUF":"PA","Dsc_UF":"PAR\u00c1"},"15":{"idUF":"PB","Dsc_UF":"PARA\u00cdBA"},"16":{"idUF":"PE","Dsc_UF":"PERNAMBUCO"},"17":{"idUF":"PI","Dsc_UF":"PIAU\u00cd"},"18":{"idUF":"PR","Dsc_UF":"PARAN\u00c1"},"19":{"idUF":"RJ","Dsc_UF":"RIO DE JANEIRO"},"20":{"idUF":"RN","Dsc_UF":"RIO GRANDE DO NORTE"},"21":{"idUF":"RO","Dsc_UF":"ROND\u00d4NIA"},"22":{"idUF":"RR","Dsc_UF":"RORAIMA"},"23":{"idUF":"RS","Dsc_UF":"RIO GRANDO DO SUL"},"24":{"idUF":"SC","Dsc_UF":"SANTA CATARINA"},"25":{"idUF":"SE","Dsc_UF":"SERGIPE"},"26":{"idUF":"SP","Dsc_UF":"S\u00c3O PAULO"},"27":{"idUF":"TO","Dsc_UF":"TOCANTINS"}};


$(document).ready(function(){
	$("button,input[type=submit],input[type=reset],input[type=button]").wrap("<span class='box-btn'></span>").addClass('btn');	
});

	function carregado(target) {
		var target = !target?'':target;
		try{
			if(target) {
				$(target).unblock();
			} else {
				$().unblock();
			}
		} catch(e) {
			
		}
	}
	function carregando(target,msg) {
		var target = !target?'':target;
		var msg = !msg?'':msg;
		
		if(target) {
			$(target).ready(function(){
				if(msg) {
					$(target).block({message:msg});
				} else {
					$(target).block();
				}
			});
		} else {
			if(msg) {
				$.blockUI({message:msg});
			} else {
				$.blockUI();
			}
		}	
	}
	
	$.ajaxSetup({
	  async: false
	});
	
	function setAsync(cs) {
		var cs = !cs?false:true;
		$.ajaxSetup({
		  async: cs
		});
	}
	
	/*
	$().ajaxStart(function(ev){
		
	});
	$().ajaxComplete(function(ev, xhr, s) { 
		carregado();
	});
	$().ajaxStop(function(ev){
		carregado();
	});
	$().ajaxError(function(ev){
		carregado();
	});
	$().ajaxSuccess(function(ev){
		carregado();
	});
	$().ajaxSend(function(request, settings){
		//carregando(Loading.msg);
	});
	*/
	
	


function rnd() { var dt = new Date(); return dt.getTime()+''; }

function linkRedirAnalitcs(url) {
	window.open(url);
	var urlAnalitcs = baseUrl + 'analitcs/url/'+url;
    $.ajax({
      type: "POST",
      url: urlAnalitcs,
      async: false,
      success: function(ret){
          if (!carregado){
             carregadoAjax();  
          }
          if (ret){eval('retorno = ' + ret + ';');}         
          
      }
    });
}


/**
 * Função que atualiza e mostra a data e hora atual... 
 *
 * @author Sósthenes Neto
 */
function showDataHoraAtual(){
    var objDate = new Date();

    var strDataHoraAtual = dataHoraAtual( objDate );

    $("#dataHora").text( strDataHoraAtual );
    
    setTimeout("showDataHoraAtual();",1000);
}
/**
 * Função que atualiza e mostra a data e hora atual... 
 *
 * @author Sósthenes Neto
 * @param  DATE objDate
 * @return STRING strDataHoraAtual
 */
 
function dataHoraAtual( objDate ){

    var dia     = objDate.getDate();
    var mes     = objDate.getMonth();
    var ano     = objDate.getFullYear();
    var hora    = objDate.getHours();
    var minuto  = objDate.getMinutes();
    var segundo = objDate.getSeconds();

    var dataAtual  = ( dia < 10 )? "0" : "";
        dataAtual += dia + " / ";
        dataAtual += ( (mes + 1) < 10 )? "0" : "";
        dataAtual += (mes + 1) + " / ";
        dataAtual += ano;
    
    var horaAtual  = ( hora < 10 )? "0" : "";
        horaAtual += hora + ":";
        horaAtual += ( minuto < 10 )? "0" : "";
        horaAtual += minuto + ":";
        horaAtual += ( segundo < 10 )? "0" : "";
        horaAtual += segundo;

    var strDataHoraAtual = dataAtual + ' ' + horaAtual;
    
    return strDataHoraAtual;
}
/**
 * Carrega dinamicamente um script JAVASCRIPT
 * 
 * @param  STRING srcScript
 * @author Sósthenes
 */
function loadScript( srcScript ){
    $('head').append(
        $( document.createElement('script') ).attr({
            type: 'text/javascript',
            src: srcScript
        })
    );
}

/**
 * Carrega dinamicamente um LINK CSS
 * 
 * @param  STRING srcCSS
 * @author Sósthenes
 */
 
function loadCSS( srcCSS, mediaCSS ){
    $('head').append(
        $( document.createElement('link') ).attr({
            rel: 'stylesheet',
            type: 'text/css',
            media: mediaCSS || 'screen,projection',
            href: srcCSS //+ "?_" + parseInt((Math.random()*1000000))
        })
    );
}

/**
 * Função para validação via ajax 
 * @param string controle, controle a ser chamado
 * Retorna o resultado do processamento fazendo um eval
 */
function ajaxValidate( controle, async, carregado){
    var retorno;
    
    async = (!async)?false:true;
    $.ajax({
      type: "POST",
      url: controle,
      async: async,
      success: function(ret){
          if (!carregado){
             carregadoAjax();  
          }
          if (ret){eval('retorno = ' + ret + ';');}         
          
      }
    });
    return retorno;
}


function preNextTabIndex( objQuery , e ){
    if(objQuery.attr('noEnter')){
        return;
    }
    var e=e||window.event;
    var k=e.charCode||e.keyCode||e.which;
    if( k == 13 ){
        nextTabIndex( objQuery );
    }
}
function nextTabIndex( objQuery ){
    objQuery.trigger('blur');
    
    var index = objQuery.attr('tabindex') || undefined;
    
    if (index != undefined){
        
        index = parseInt(index);
        index++;
        while( !$('[tabindex='+ index +']').is(':input') ){
            index++;
        }
        $('[tabindex='+ index +']').focus();

    }else{
        var container = $(":input").not(":disabled")
                                   .not(":hidden")
                                   .not("[noEntry]")
                                   .not("[readonly]");
        index = container.index( objQuery.get(0) );
        index += 1;
        var proxElem = container.eq( index );
//        alert( 'id: '+    proxElem.attr('id')+'\n'+
//               'class: '+ proxElem.attr('class') );
        proxElem.focus();
    }
}

/**
 * Percorre os elementos da tela jogando as mácaras de acordo com o tipo
 */
function loadMask( target ){
	$(target + " input,textarea,select" ).each(function(){
//    $( target + " :input" ).each(function(){    ### não precisa de pegar todas as entradas do "target"...
        switch (this.getAttribute('appType')) {
            case 'hora':
                $.mask.addPlaceholder('H',"[0-2]");
                $.mask.addPlaceholder('M',"[0-5]");
                $.mask.addPlaceholder('N',"[0-9]");
                $.mask.addPlaceholder('O',"[0-3]");
                
                $(this).css({'width':'40px'})
                       .mask("HN:MN")
                       .bind ('keypress', function(){
                           formatHour( $(this) );
                       });
                break;
            
            case 'atividadeEconomica':
                $(this).css({'width':'55px'})
                       .numeric()
                       .bind( 'keydown', function(){
                           formatAtividadeEconomica( $(this) );
                       });
                break;
            case 'cep':
                $(this).css({'width':'60px'})
                       .mask("99.999-999");
                break;
            
            case 'codigoNatureza':
                $(this).css({'width':'60px'})
                       .mask("999-9");
                break;
                        
            case 'float':
                $(this).numeric(".")
                       .floatnumber(".", 2);
                break;
            
			case 'currency':
				if(($(this).val()+'').indexOf(',')==-1) { $(this).val($(this).val()+',00') }
				//$(this).val(soNumeros($(this).val()+'','.,'));
				$(this).maskMoney({decimal:",",thousands:"."});
                $(this).css('text-align','right');
                break;			
			    
            case 'number':
                $(this).numeric(".")
                       .floatnumber(".", 0);
                break;

            case 'onlyNumber':
                $(this).numeric();
                break;
                
            case 'date':
                $.mask.addPlaceholder('A',"[0-3]");
                $.mask.addPlaceholder('B',"[0-9]");
                $.mask.addPlaceholder('C',"[0-1]");
                $.mask.addPlaceholder('D',"[0-9]");
                
				
				$(this).css({'width':'70px'})
                       .mask("AB/CD/9999")
                       .blur(function(){
                           isDate($(this));
                       });
                break;
                
            case 'email':
                $(this).blur(function(){
                    isEmail($(this));
                });
                break;
                
            case 'cpf':
                $(this).css({'width':'90px'})
                       .mask("999.999.999-99")
                       .blur(function(){
                           isCpf($(this));
                       });
                break;
                
            case 'cnpj':
                $(this).css({'width':'110px'})
                       .mask("99.999.999/9999-99")
                       .blur(function(){
                           isCnpj($(this));
                       });
                break;
                
            case 'nire':
                $(this).css({'width':'80px'});
                $(this).blur(function(){
                    isNire($(this));
                });
                $(this).mask("99 9 9999999-9");
                $(this).bind ('keypress', function(){
                    /*if( $(this).getValUnMasked().length == 11 ){
                        if (isNire($(this))) {
                            nextTabIndex( $(this) );
                        }
                    }*/
                });
                break;
                
			case 'protocolo':
                $(this).css({'width':'70px'});
                $(this).bind('blur', function(){
                	$(this).val( getProtocolo( $(this).val() ) ); 
                    isProtocolo( $(this) );
                });
                $(this).mask("99/999999-9");
                $(this).bind ('keypress', function(){
                    if( $(this).getValUnMasked().length == 9 ){
                        removeShowMsg();
                        if (isProtocolo($(this))) {
                            nextTabIndex( $(this) );
                        }
                    }
                });
                break;

            case 're_fcn':
                $(this)
                            .css({'width':'95px'})
                            .mask("aa9999999999999",{placeholder:""})
                            .css({'text-transform':'uppercase'})
                            .bind('blur',function(){
                            	isReFcn( $(this) );
                            });
                break;
                
            case 'codigoCargoFuncao':
                $(this).bind('blur', function(){
                    $(this).val( getCodigoCargoFuncao( $(this).val() ) );
                });
                break;    
                
        }
        
        $(this).bind('keyup',function(e){
            preNextTabIndex( $(this) , e )
        });
    });
    
    $(".saidaAutomatica").bind('keypress', function(){
        if( $(this).getValUnMasked().length == $(this).attr('maxlength') ){
            nextTabIndex( $(this) );
        }
    });
/*    
    $( target ).bind('keypress',function(e){
        e=e||window.event;
        var k=e.charCode||e.keyCode||e.which;
        //alert( k );
        if( k == 112 ){ 
            mostraAjuda();
            return false;
        }
    });
*/
}


$(document).ready(function(){
    loadMask( 'body' );
});

/**
 * Retorna as informações de um input sem a máscara.
 * 
 * @param ARRAY arrAddCaracteres com os caracteres que são para remover do valor também.
 * @return o valor sem os caracteres de mascara e/ou os caracteres no array enviado por parâmetro. 
 */
$.fn.getValUnMasked = function(arrAddCaracteres) {
    var sValue = $(this).val();
    sValue = sValue.toString().replace( /[\-\.\/\:\_\s]/g, "" );
    if( arrAddCaracteres ){ 
        var i;
        var j;
        for(j=0;j<arrAddCaracteres.length;j++){
            i = 0;            
            while ( i < sValue.length ){
                sValue = sValue.toString().replace( arrAddCaracteres[j], "" );
                i++;
            }
        }
    }
    return sValue;
};

/**
 * Funções para retornar valor de String sem espaçamentos
 */
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

function removeShowMsg(){$('#showMsgSiarco').remove();}

function showMsg( msg, objJquery ){
    
    var top  = objJquery.offset().top; 
    var left = objJquery.offset().left;

    $("#showMsgSiarco").remove();
    var str   = '<div id="showMsgSiarco">';
        str  += '	<div  class="msg"> '+msg+'</div>';
        str  += '</div>';
    
    //objJquery.parent().append(str);
    //alert(objJquery.parent().get());
    $(objJquery).after(str);

    //var targetOffset = objJquery.offset().top;
    //$('html,body').animate({scrollTop: targetOffset-70}, 500);
    objJquery.bind('change', function(){ $("#showMsgSiarco").remove(); });
    
}

function showMsg__OLD( msg, objJquery ){
    
    var top  = objJquery.offset().top; 
    var left = objJquery.offset().left;

    $("#showMsgSiarco").remove();
    var str   = '<div id="showMsgSiarco"  style="z-index:1000; position:absolute; top:'+(top - 60)+'px; left:'+(left + 10)+'px;">';
        str  += '   <table cellpadding="0" cellspacing="0" >';
        str  += '       <tr>';
        str  += '           <td class="balaoLeft" style="height: 60px;width: 38px;">&nbsp;</td>';
        str  += '           <td  style="padding-bottom:24px;" class="balaoCenter"> '+msg+'</td>';
        str  += '           <td class="balaoRight" style="height: 60px;width: 15px;">&nbsp;</td>';
        str  += '       </tr>';
        str  += '   </table>';
        str  += '</div>';
    
    //objJquery.parent().append(str);
    //alert(objJquery.parent().get());
    $(document.body).append(str);

    var targetOffset = objJquery.offset().top;
    $('html,body').animate({scrollTop: targetOffset-70}, 500);
    objJquery.bind('change', function(){ $("#showMsgSiarco").remove(); });
    
}
/*
 * Caixas de diálogo
 */



/*
 * Mensagem de alerta
 */
function alertMsg( msg, tipo , obj, funcao){
    obj = (!obj)?"":obj;
	funcao = (!funcao)?"":funcao; //se o parametro funcao nao for fornecido atribui o valor "" para a funcao;
    var strTipo;
    switch( tipo ){
        case 1:
            strTipo = "Sucesso";    
        break;
        case 2:
            strTipo = "Aviso";  
        break;
        case 3:
            strTipo = "Erro";   
        break;
        default:
            strTipo = "Aviso";  
        break;
    }
    
    attTarget = 'target=""';
    if(obj) {
//        if(obj.id) {
//            attTarget = 'target="'+ obj.id +'"'; 
// corrigido esse detalhe. por Sósthenes.
        if($(obj).attr('id')) {
            attTarget = 'target="'+ $(obj).attr('id') +'"';
        }
    }
    $("#showMsgSiarco").remove();
    $("#dialogSiarco").remove();
    var strDiv  = '<div class="dialogSiarco" id="dialogSiarco" style="z-index:100; display:none; cursor: default">';
            strDiv += '<div class="dialogSiarcoTitulo" style="cursor: default;">&nbsp;Aviso</div>';
            strDiv += '<div class="dialogSiarcoContainer'+strTipo+'">';
            strDiv += msg;
            strDiv += '</div>';
            strDiv += '<div class="dialogSiarcoBarraButton">';
            strDiv += '<button id="buttonDialog" class="ok" '+ attTarget +'></button>';
            strDiv += '</div>';
        strDiv += '</div>';                 

    $(document.body).append(strDiv);

    $('#buttonDialog').click(function(){
        $.unblockUI($('#dialogSiarco'));
        idTarget = $(this).attr('target');
        if(idTarget) {
            objTarget = $('#'+idTarget);
            if(objTarget) {
                objTarget.focus();
            }
        }
		setTimeout(funcao, 500);
    });
    
    $.blockUI($('#dialogSiarco'));
}

function confirmMsg( msg , funcaoSim, funcaoNao){
    var retorno = false;
    var saida = false;
    $("#showMsgSiarco").remove();
    $("#dialogSiarco").remove();
    var strDiv  = '<div class="dialogSiarco" id="dialogSiarco" style="z-index:100; display:none; cursor: default">';
            strDiv += '<div class="dialogSiarcoTitulo" style="cursor: default;">&nbsp;Pergunta</div>';
            strDiv += '<div class="dialogSiarcoContainerConfirm">';
            strDiv += msg;
            strDiv += '</div>';
            strDiv += '<div class="dialogSiarcoBarraButton">';
            strDiv += '<button id="buttonSim" class="sim"></button>';
            strDiv += '<button id="buttonNao" class="nao" style="margin-left:20px;"></button>';
            strDiv += '</div>';
        strDiv += '</div>';                 

    $(document.body).append(strDiv);
    
    $('#buttonNao').click(function(){
        retorno = false;
                saida = true;
        $.unblockUI(); 
		setTimeout('eval('+funcaoNao+');',500);
    });
    
    $('#buttonSim').click(function(){
        retorno = true;
                saida = true;
        $.unblockUI();
		setTimeout('eval('+funcaoSim+');',500);
    });
    
    $.blockUI($('#dialogSiarco'));
    $("#dialogSiarco").draggable({handle: "#dialogSiarcoTitulo"});
    
    
    return retorno;
}

function choiceDialog(titulo, msg, textBtn1, textBtn2, funcao1, funcao2){
	var retorno = false;
	$('#dialogSiarco').remove();
	var strDiv  = '<div class="dialogSiarco" id="dialogSiarco" style="z-index:100; display:none; cursor: default">';
            strDiv += '<div class="dialogSiarcoTitulo" style="cursor: default;">&nbsp;'+ titulo +'</div>';
            strDiv += '<div class="dialogSiarcoContainerConfirm">';
            strDiv += msg;
            strDiv += '</div>';
            strDiv += '<div class="dialogSiarcoBarraButton">';
            strDiv += '<button id="button1" style="width:80px;">'+ textBtn1 +'</button>';
            strDiv += '<button id="button2" style="margin-left:20px; width:80px;">'+ textBtn2 +'</button>';
            strDiv += '</div>';
        strDiv += '</div>';                 

    $(document.body).append(strDiv);
    
    $('body').keypress(function(e){
	  var kC  = (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
      var Esc = (window.event) ?   
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
	  if (kC == Esc) {
	  	$.unblockUI();
	  }
	});
	
	$('#button1').click(function(){
        retorno = false;
                saida = true;
        $.unblockUI();
		setTimeout(funcao1,500);
    });
    
    $('#button2').click(function(){
        retorno = true;
                saida = true;
        $.unblockUI();
		setTimeout(funcao2,500);
    });
    
    $.blockUI($('#dialogSiarco'));
    $("#dialogSiarco").draggable({handle: "#dialogSiarcoTitulo"});
    
    
    return retorno;	
}


/**
 * Cria um Dialog.
 * Quando TOP e LEFT não forem especificados o Dialog será centralizado.
 */
function loadDialog( id, titulo, path, width, height, top, left){
    if( typeof(path)=='object' ){
       var html  = path.html();
    }else{
       var html = $.ajax({
                        url: path,
                        async: false
                    }).responseText;
    }
	
  $("#"+id+'_titulo"').remove();  
  $("#"+id+'_principal').remove();  
  $("#"+id).remove();
  $("#"+id+'_shadow').remove();
  $("#"+id+'_shadow2').remove();
  $("#"+id+'_container').remove();

  if(!top){
  	top = ( ($(window).height()/2) - (height/2) );
  	top = top<0?0:top;  //evita que a barra de titulo do Dialog fique fora da tela 
  }
  if(!left){
  	left = ( ($(window).width()/2) - (width/2) );
  	left = left<0?0:left;   //evita que a lateral esquerda do Dialog fique fora da tela
  }
    
  var strDiv  = '<div id="'+id+'_container"	class="loadDialogSiarcoContainer">';
   	  strDiv += '<div id="'+id+'_principal"	class="loadDialogSiarcoPrincipal"	style="z-index:101;	top:'+ top +'px; left:'+ left +'px;	width:'+width+'px;	height:'+height+'px;">';
      strDiv += '<div id="'+id+'_shadow"  	class="loadDialogSiarcoShadow1" 	style="z-index:98;  top:8px;				left:8px;					width:'+width+'px;	height:'+height+'px;"></div>';
      strDiv += '<div id="'+id+'_shadow2"	class="loadDialogSiarcoShadow2"		style="z-index:99;  top:5px;				left:5px;					width:'+width+'px;	height:'+height+'px;"></div>';
      strDiv += '<div id="'+id+'"        	class="loadDialogSiarco"         	style="z-index:100;	top:0px;				left:0px;					width:'+width+'px;	height:'+height+'px;">';
      strDiv += '<div class="dialogSiarcoTitulo" id="'+id+'_titulo" onclick="removeShowMsg();">&nbsp;'+titulo+'<input type="button" class="fecharDialog" id="buttonDialogFechar'+id+'"></input></div>';
      strDiv += html;
      strDiv += '</div>';
      strDiv += '</div>';
      strDiv += '</div>';

  
  $(document.body).append(strDiv);
    
	$('#buttonDialogFechar'+id).click(function(){
        closeDialog( id );
  	});
  
    $('body').keypress(function(e){
	  var kC  = (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
      var Esc = (window.event) ?   
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
	  if (kC == Esc) {
	  	$.unblockUI();
	  }
	});

	$('#showMsgSiarco').remove();
	loadMask( '#' + id );
    
	$("#"+id+"_principal").draggable({handle: "#"+id+"_titulo"});
}
function closeDialog( idDialog ){
    //  acao de fechar padrao do Dialog  /////////////////////////////
    var id = idDialog;                                              //
    $('#'+id).fadeOut();                                            //
    $("#"+id+'_titulo"').fadeOut();                                 //
    $("#"+id+'_principal').fadeOut();                               //
    $("#"+id+'_shadow').fadeOut();                                  //
    $("#"+id+'_shadow2').fadeOut();                                 //
    $("#"+id+'_container').fadeOut();                               //
    $('#showMsgSiarco').fadeOut();                                  //
    var t0 = setTimeout('$("#'+id+'").remove();',1000);             //
    var t1 = setTimeout('$("#'+id+'_shadow").remove();',1000);      //
    var t2 = setTimeout('$("#'+id+'_shadow2").remove();',1000);     //
    var t3 = setTimeout('$("#'+id+'_titulo").remove();',1000);      //
    var t4 = setTimeout('$("#'+id+'_principal").remove();',1000);   //
    var t5 = setTimeout('$("#'+id+'_container").remove();',1000);   //
  	onClose();                                                      //
    //////////////////////////////////////////////////////////////////
}
function onClose(){
  return true;
}

/**
 * Função de validação de formulário
 * @param Object form, recebe um formulario ou uma div para fazer a validação
 * @return bool,  retorna um booleano
 */
function validateForm(form){
    
    var retorno = true;
    
    form.find('input, select, textarea')
        .filter(':enabled')
        .each(function() {
        
            if( retorno ) {
                //valida os campos obrigatorios
                if(this.getAttribute('required')) {
                    if( this.getAttribute('type') == 'radio' || 
                        this.getAttribute('type') == 'checkbox' ) {
                        
                            switch( this.getAttribute('type') ) {
                                case 'radio':
                                    var radio = $("input[@type=radio][@name=" + this.getAttribute('name') + "][@checked]").val();
                                    
                                    if ( radio == null ) {
                                        var msg = 'O campo ' + this.getAttribute('fieldLabel') + ' é de preenchimento obrigatório.' ;
                                        showMsg( msg, $("#"+ this.getAttribute('id')) );
                                        retorno = false;
                                    }
                                break;
                            }
                        
                    }else{
                        if( this.value == '' ){
                            var msg = 'O campo ' + this.getAttribute('fieldLabel') + ' é de preenchimento obrigatório.' ;
                            showMsg( msg, $("#"+ this.getAttribute('id')) );
                            this.focus();
                            retorno = false;
                        }
                    }
                }

                if (retorno) {
                    switch (this.getAttribute('appType')) {
                        case 'date':
                            if (!isDate($("#" + this.getAttribute('id')), true)) {
                                retorno = false;
                            }
                            break;
                            
                        case 'email':
                            if (!isEmail($("#" + this.getAttribute('id')), true)) {
                                retorno = false;
                            }
                            break;
                            
                        case 'cpf':
                            if (!isCpf($("#" + this.getAttribute('id')), true)) {
                                retorno = false;
                            }
                            break;
                            
                        case 'cnpj':
                            if (!isCnpj($("#" + this.getAttribute('id')), true)) {
                                retorno = false;
                            }
                            break;
                            
                        case 'nire':
                            if (!isNire($("#" + this.getAttribute('id')), true)) {
                                retorno = false;
                            }
                            break;
                            
                        case 'protocolo':
                            
                            if (!isProtocolo($("#" + this.getAttribute('id')), true)) {
                                retorno = false;
                            }
                            break;
                    }
                }
            }
        });

    return retorno;
}

function isCpf(objJquery, msg){
    var i;

    var s = objJquery.getValUnMasked();
    if (!s){ 
        if( !msg ){
            $("#showMsgSiarco").remove();
        }
        return true; 
    }

    var c = s.substr(0,9);
    if (c == "000000000" || c == "111111111" || c == "222222222" || 
    c == "333333333" || c == "444444444" || c == "555555555" || c == "666666666" || 
    c == "777777777" || c == "888888888" || c == "999999999")
    {
        showMsg( 'CPF inválido', objJquery );
        return false;
    }

    var dv = s.substr(9,2);
    var d1 = 0;
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(10-i);
    }

    if (d1 == 0){
        showMsg( 'CPF inválido', objJquery );
        return false;
    }

    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1)
    {
        showMsg( 'CPF inválido', objJquery );
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(11-i);
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1)
    {
        showMsg( 'CPF inválido', objJquery );
        return false;
    }
    
    if( !msg ){
        $("#showMsgSiarco").remove();
    }
    
    return true;
}

function formatCurrency(num) {
//    alert( num );
//    num = num.toString().replace(/\$|\./g,'');
	var result = num;
	if(result+''!='') {
			num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num))
				num = "0";
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/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));
		//        num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
			result = (((sign)?'':'-') + num + ',' + cents);
	}
    return result;
//    return (((sign)?'':'-') + '$' + num + '.' + cents);
}


function formatHour(objQuery){

    var dig1 = objQuery.val().substr(0,1);
    var dig2 = objQuery.val().substr(1,1);
    var dig3 = objQuery.val().substr(3,1); 
    var dig4 = objQuery.val().substr(4,1);

    dig1 = (dig1 != '_')? parseInt(dig1) : '_';
    dig2 = (dig2 != '_')? parseInt(dig2) : '_';
    dig3 = (dig3 != '_')? dig3 : '_';
    dig4 = (dig4 != '_')? dig4 : '_';

    if(dig1 == 2){
        if(dig2 > 3){
          objQuery.val( (dig1+'')  + '_:' + (dig3+'') + (dig4+'') ).caret(1);
        }
    }
}
function formatAtividadeEconomica(objQuery){
//    alert (objQuery.val().length);
 
    if( objQuery.val().length == 4 ){
        objQuery.val( objQuery.val()+'-');
    }
    if( objQuery.val().length == 6 ){
        objQuery.val( objQuery.val()+'/');
    }
}


function isDate(objJquery, msg){
    
    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}$/;
    
    if ( !objJquery.getValUnMasked() ){
        if( !msg ){
            $("#showMsgSiarco").remove();
        }
        return true;
    }
    
    if (reDate.test(objJquery.val())) {
        if( !msg ){
            $("#showMsgSiarco").remove();
        }
        return true;
    } else {
        showMsg( 'Data inválida', objJquery );
        return false;
    }
}


function validaEmail(val) {
	var reEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	if (!reEmail.test(val) || val+''=='') {
		return false;
	}
	return true;
}

function isEmail(objJquery, msg){

    var reEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
    
	if( !objJquery.val() ){ 
		if( !msg ){
			$("#showMsgSiarco").remove();
		}
		return true;
	}
    
    if (reEmail.test(objJquery.val())) {
        if( !msg ){
            $("#showMsgSiarco").remove();
        }
        return true;
    } else {
        showMsg( 'E-mail inválido', objJquery );
        return false;
    }
}
function isCnpj(objJquery, msg) {

               var CNPJ = objJquery.getValUnMasked();
			   
               if( !CNPJ ){
                  if( !msg ){
                    $("#showMsgSiarco").remove();
                  }
                  return true;
               }
               
               erro = new String;
               if (CNPJ.length < 14) erro += "é necessario preencher corretamente o número do CNPJ! \n\n";
//               if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
//                    if (erro.length == 0) erro += "é necessário preencher corretamente o número do CNPJ! \n\n";
//               }
                //substituir os caracteres que não são números
              if(document.layers && parseInt(navigator.appVersion) == 4){
                      x = CNPJ.substring(0,2);
                      x += CNPJ. substring (3,6);
                      x += CNPJ. substring (7,10);
                      x += CNPJ. substring (11,15);
                      x += CNPJ. substring (16,18);
                      CNPJ = x;
              } else {
                      CNPJ = CNPJ. replace (".","");
                      CNPJ = CNPJ. replace (".","");
                      CNPJ = CNPJ. replace ("-","");
                      CNPJ = CNPJ. replace ("/","");
              }
              var nonNumbers = /\D/;
              if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
              var a = [];
              var b = new Number;
              var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
              for (i=0; i<12; i++){
                      a[i] = CNPJ.charAt(i);
                      b += a[i] * c[i+1];
}
              if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
              b = 0;
              for (y=0; y<13; y++) {
                      b += (a[y] * c[y]);
              }
              if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
              if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                      erro +="CNPJ inválido";
              }
              if (erro.length > 0){
                showMsg( erro, objJquery );
                return false;
              }
              
              if( !msg ){
                $("#showMsgSiarco").remove();
              }
              
              return true;
}
function isNire( objJquery, msg ) {

	if(! objJquery.getValUnMasked() ){
		return true;
	}

	var nr_nire = objJquery.getValUnMasked();
	var i = 0;
      while ( i < nr_nire.length )
      {
          nr_nire = nr_nire.toString().replace(" ","");
          i++;
      }
	
	soma = nr_nire.substring(9,10) * 2 +
	nr_nire.substring(8,9) * 3 +
	nr_nire.substring(7,8) * 4 +
	nr_nire.substring(6,7) * 5 +
	nr_nire.substring(5,6) * 6 +
	nr_nire.substring(4,5) * 7 +
	nr_nire.substring(3,4) * 8 +
	nr_nire.substring(2,3) * 9 +
	nr_nire.substring(1,2) * 10 +
	nr_nire.substring(0,1) * 2;
	
    
	if ((11 - soma%11) > 9) {
		dv = (11 - soma%11)-10;
	} else {
		dv = 11 - soma%11;
	}
	if (dv != nr_nire.substring(10,11)) {
		showMsg( 'NIRE inválido', objJquery );
		return false;
	}
	
	if( !msg ){
		$("#showMsgSiarco").remove();
	}
	
	return nr_nire;
}
function isProtocolo( objJquery, msg ){
    var soma1   = 0;
    var dv1     = 0;
    var proto   = objJquery.getValUnMasked();

	//Alterado por Luca Martins
    //$("#showMsgSiarco").remove();
    
    if( !proto ){
        //showMsg( 'valor do protocolo vazio', objJquery );
        return true;
    }

    soma1 =   (substr(proto,8,1)  * 2) 
            + (substr(proto,7,1)  * 3) 
            + (substr(proto,6,1)  * 4) 
            + (substr(proto,5,1)  * 5) 
            + (substr(proto,4,1)  * 6) 
            + (substr(proto,3,1)  * 7) 
            + (substr(proto,2,1)  * 8) 
            + (substr(proto,1,1)  * 9); 
   
    if((11-mod(soma1,11)) < 10) {
        dv1 = 11 - mod(soma1,11);
    } else {
        dv1 = 0;
    }
    if(to_char(dv1) != substr(proto,9,1)) {
        showMsg( 'Protocolo inválido', objJquery );
//        objJquery.focus();
        return false;
    }

    return proto;
}

function isReFcn( objJquery ){
    var reFcn = objJquery.getValUnMasked();
	if(!reFcn){
		$("#showMsgSiarco").remove();
		return;
	}
	
	if(reFcn.substr(2,1) != 1 && reFcn.substr(2,1) != 2){
		showMsg( 'RE/FCN inválido', objJquery );
        return false;
	}
	
	$("#showMsgSiarco").remove();
    return reFcn;
}

/*** funções para o protocolo ***/
function to_char(character) { 
    return character+''; 
}
function substr(character, number, length) {
    number = number-1;
    return character.substring(number,number+length);
}
function mod(dividendo,divisor) {
    return Math.round(dividendo - (Math.floor(dividendo/divisor)*divisor));
}
function lpad(number, length, character){
  rtn="";
  rtn = number.toString();
  size = length - rtn.length;
  for (i=0; i < size; i++)
  {
    rtn = character + rtn;
  }
  return rtn;
}
/*** funções para o protocolo ***/


function focarElemento(elemento){
	var targetOffset = $('#formField_imprCod').offset().top;
	elemento.focus();
	$('html,body').animate({scrollTop: targetOffset-100}, 500);
}


function openPopup( path, width, height ) {
    var jan = window.open( path, "JANELA", "width = "+width+",  height= "+height+",directories=no, channelmode=no,fullscreen=no,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,titlebar=no,toolbar=no");
    jan.focus();
}

function gerarRelatorio( form, width, height ){
    openPopup( '', width, height );
    form.attr('target', 'JANELA');
    form.submit();
}

$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form') {
            return $(':input', this).clearForm();
        }
        if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'hidden') {
            this.value = '';
        }
        else if (type == 'checkbox' || type == 'radio') {
                this.checked = false;
        }
        else if (tag == 'select') {
                this.selectedIndex = -1;
        }
    });
};

function getNumberExtenso(num, obj){
    
    var extenso = ajaxValidate("ajax-common/getnumberextenso/id/" + num);
    obj.val(extenso);
    //obj.attr("disabled","disabled");
}

function hasRequerimentoFcn(objJquery){
    
    if(!objJquery.val())
    {
        return true;
    }    
    var requerimentoFcn = ajaxValidate("ajax-common/getinforequerimentofcn/id/" + objJquery.val());
    
    if (requerimentoFcn == '' || requerimentoFcn == null) {
        
        if(!confirm('Arquivo temporário não recebido. Problema na transmissão. Contate o administrador do sistema. Clique em sim para Protocolar Manualmente ou em cancelar para Aguardar transmissão para protocolar.')){
            return false;
        }
    }    
    return true;
}

/**
 * Função verifica se data_1  {operador}  data_2
 * {operador} = '>','<','=','!='
 * se sim: return true
 * se não: return false 
 */
function verificaData( data_1 , data_2 , operador ){
    var dia_data_1 = substr( data_1, 1, 2 );
    var mes_data_1 = substr( data_1, 4, 2 );
    var ano_data_1 = substr( data_1, 7, 4 );
    var data_formato_EUA_1 = mes_data_1+'/'+dia_data_1+'/'+ano_data_1;
    var data_formatada_1   = new Date( data_formato_EUA_1 );

    var dia_data_2 = substr( data_2, 1, 2 );
    var mes_data_2 = substr( data_2, 4, 2 );
    var ano_data_2 = substr( data_2, 7, 4 );
    var data_formato_EUA_2 = mes_data_2+'/'+dia_data_2+'/'+ano_data_2;
    var data_formatada_2   = new Date( data_formato_EUA_2 );
    
    //alert( data_1 +'  '+ operador +'  '+ data_2);
    //alert( data_formatada_1 +'  '+ operador +'  '+ data_formatada_2);
    
    var retorno = false;
    switch( operador ){
        case '>':
            retorno = (data_formatada_1 > data_formatada_2)? true : false;
            break;
        case '<':
            retorno = (data_formatada_1 < data_formatada_2)? true : false;
            break;
        case '=':
            retorno = (data_formatada_1 == data_formatada_2)? true : false;
            break;
        case '!=':
            retorno = (data_formatada_1 != data_formatada_2)? true : false;
            break;
    }
    return retorno;
}



function comparaDataForm(dataInicial,dataFinal,dataAtual){

var dataInicial;
var dataFinal;
var dataAtual;

if(dataInicial == ''){
		alert(acento('Preencher+o+campo+PER%CDODO+INICIAL.'));
		return false;
	}else if(dataFinal == ''){
		alert(acento('Preencher+o+campo+PER%CDODO+FINAL.'));
		return false;
	}else if ( parseInt( dataInicial.split( "/" )[2].toString() + dataInicial.split( "/" )[1].toString() + dataInicial.split( "/" )[0].toString() ) > parseInt( dataFinal.split( "/" )[2].toString() + dataFinal.split( "/" )[1].toString() + dataFinal.split( "/" )[0].toString() ) ){
		alert(acento('A+data+inicial+deve+ser+menor+que+a+data+final'));
		return false;
	}else if ( parseInt( dataFinal.split( "/" )[2].toString() + dataFinal.split( "/" )[1].toString() + dataFinal.split( "/" )[0].toString() ) > parseInt( dataAtual.split( "/" )[2].toString() + dataAtual.split( "/" )[1].toString() + dataAtual.split( "/" )[0].toString() ) ){
		alert(acento('A+data+final+deve+ser+menor+que+a+data+atual'));
		return false;
	}else if ( parseInt( dataFinal.split( "/" )[2].toString() + dataFinal.split( "/" )[1].toString() + dataFinal.split( "/" )[0].toString() ) < parseInt( dataInicial.split( "/" )[2].toString() + dataInicial.split( "/" )[1].toString() + dataInicial.split( "/" )[0].toString() ) ){
		alert(acento('A+data+final+n%E3o+pode+ser+inferior+%E0+data+inicial'));
		return false;
	}else{
		return true
	}
}

function acento(resultado){
 	resultado = resultado.replace(/\+/g," "); // Substitue o "+" por um espaço.
    resultado = unescape(resultado); // Desfaz o que a função urlencode(); fez.
    return resultado;
}


function dropDownCategorias(objAppend) {
	var html = tree_secoes.getHTML();
	//$('body').prepend(html);
	$(objAppend).prepend('<span id="teste" style="display: none;">' + html + '</span><input type="text" id="dep_mcdropdown" name="dep"  value="" />');
	//alert(tree_secoes.getHTML())
	var html = $('#teste > ul').html();
	$('#teste').html('<ul id="tree_secoes_mcdropdown" class="mcdropdown_menu">' + html + '</ul>');

	$('#dep_mcdropdown').mcDropdown('#tree_secoes_mcdropdown',{
		showACOnEmptyFocus: true,
		delim: " » " 
	});
	
}
function display_secoes_sidebar(aCategories, iCurID, iDepth, initLevel, endLevel) {
	iCurID 		= !iCurID?'':iCurID;
	iDepth 		= !iDepth?0:iDepth;
	initLevel 	= !initLevel?0:initLevel;
	endLevel 	= !endLevel?'':endLevel;
	
	CategoryID = 'idSecao';
	Name = 'Nom_Secao';
	ParentID= 'idSecaoPai';
	Lineage = 'lineage';
	Level= 'nivel';
	
	endLevel_aux = (endLevel+""=="")?iDepth:endLevel;
	iNumRecords = $(aCategories).size();
	
	strHTML = "<ul>";
	pos = 0;
	
	for(i in aCategories) {
		key = i;
		valor = aCategories[i];
		if(valor[ParentID]+"" == iCurID+"") {
			Link = baseUrlModule + "produtos/lista/idsecao/" + valor[CategoryID];
			if(valor[ParentID]+""!="") {
				Link = Link + '/idsecaop/' + valor[ParentID];
			}
			str_selected = "";
			
			if(iDepth>=initLevel && iDepth<=endLevel_aux) {
				strHTML += "<li class='nivel_" + iDepth + "_li pos_" + pos + "'><span class='nivel_" + iDepth + "'><a href=\"" + Link + "\" " + str_selected + ">";
				strHTML += valor[Name] + "</a></span> " + display_secoes_sidebar(aCategories, valor[CategoryID], iDepth+1, initLevel, endLevel);
				strHTML += "</li>";
				strHTML += "";
						
				pos++;
			} else {
				strHTML += display_secoes_sidebar(aCategories, valor[CategoryID], iDepth+1, initLevel, endLevel);
				strHTML += "";
			}
		}
	}
	strHTML += "</ul>";
	strHTML = replaceSubstring(strHTML,'<ul></ul>','');
	strHTML = replaceSubstring(strHTML,'<ul><ul>','<ul>');
	strHTML = replaceSubstring(strHTML,'</ul></ul>','</ul>');
	return strHTML;
	
}

function populaCombo(obj,objArr,idx,nom) { var html = ''; for(i in objArr) { html+='<option value="'+objArr[i][idx]+'">'+objArr[i][nom]+'</option>'; } $(obj).append(html); }

	replaceSubstring = function(inputString, fromString, toString) {
	   // Goes through the inputString and replaces every occurrence of fromString with toString
	   var temp = inputString;
	   if(temp+'' != '0') {
			if(!temp) {
				return temp;
			}
	   }
	   
	   if (fromString+'' == "") {
		  return inputString;
	   }
	   
	   
	   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
		  while (temp.indexOf(fromString) != -1) {
			 var toTheLeft = temp.substring(0, temp.indexOf(fromString));
			 var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
			 temp = toTheLeft + toString + toTheRight;
		  }
	   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
		  var midStrings = new Array("~", "`", "_", "^", "#");
		  var midStringLen = 1;
		  var midString = "";
		  // Find a string that doesn't exist in the inputString to be used
		  // as an "inbetween" string
		  while (midString == "") {
			 for (var i=0; i < midStrings.length; i++) {
				var tempMidString = "";
				for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
				if (fromString.indexOf(tempMidString) == -1) {
				   midString = tempMidString;
				   i = midStrings.length + 1;
				}
			 }
		  } // Keep on going until we build an "inbetween" string that doesn't exist
		  // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
		  while (temp.indexOf(fromString) != -1) {
			 var toTheLeft = temp.substring(0, temp.indexOf(fromString));
			 var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
			 temp = toTheLeft + midString + toTheRight;
		  }
		  // Next, replace the "inbetween" string with the "toString"
		  while (temp.indexOf(midString) != -1) {
			 var toTheLeft = temp.substring(0, temp.indexOf(midString));
			 var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
			 temp = toTheLeft + toString + toTheRight;
		  }
	   } // Ends the check to see if the string being replaced is part of the replacement string or not
	   return temp; // Send the updated string back to the user
	} // Ends the "replaceSubstring" function
	
	
	
function isNumber(digito){
	temp = 0;
	digito = digito+'';
	var Digitos="0123456789";
	if(Digitos.indexOf(digito)!=-1) {
		temp=1;
	}
	return temp;
}

function isObject(v) { return (typeof(v) == 'object'); }
function isString(v) { return (typeof(v) == 'string'); }
function soNumeros(campo,validos) {
	var numeros = "0123456789";
	numeros = (validos)?numeros+validos:numeros;
	valor = isObject(campo)?campo.value+'':campo+'';
	valor = (valor==undefined)?'':valor;
	valor_aux = "";
	for(i=0;i<valor.length;i++) {
		char = valor.charAt(i);
		if(numeros.indexOf(char)!=-1) {
			valor_aux = valor_aux + char;
		}
	}
	return valor_aux+"";
}


function arrayFindGlobais(ary,element) {
	// for(i in ary) {
		// var v = ary[i]+'';
		// if(v+''==element+'') { 
			// return i; 
		// }
	// }
	// return -1;
	for(var i=0; i<ary.length; i++){if(ary[i]+'' == element+''){ return 1;}}return 0;
}

function call_user_func_array (cb, parameters) {
    // Call a user function which is the first parameter with the arguments contained in array 
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/call_user_func_array
    // +   original by: Thiago Mata (http://thiagomata.blog.com)
    // +   revised  by: Jon Hohle
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: call_user_func_array('isNaN', ['a']);
    // *     returns 1: true
    // *     example 2: call_user_func_array('isNaN', [1]);
    // *     returns 2: false
    var func;
 
    if (typeof cb == 'string') {
        if (typeof this[cb] == 'function') {
            func = this[cb];
        } else {
            func = (new Function(null, 'return ' + cb))();
        }
    } else if (cb instanceof Array) {
        func = eval(cb[0]+"['"+cb[1]+"']");
    }
     
    if (typeof func != 'function') {
        throw new Error(func + ' is not a valid function');
    }
 
    return func.apply(null, parameters);
}


// jQuery Alert Dialogs Plugin
//
// Version 1.0
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 29 December 2008
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;OK&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;Cancelar&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Atenção';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			  '<div class="popup_container_borda corner">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', function() {
							$.alerts._reposition();
						});
					break;
					case false:
						$(window).unbind('resize');
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);


String.prototype.repeat = function(l){
	var idx = l<0?0:l+1;
	return new Array(idx).join(this);
};
jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}


	function tiraAcento(text) {
		  //text = text.replace(new RegExp('[ÁÀÂÃ]','gi'), 'A'); //maiuscula
		  text = text.replace(new RegExp('[ÁÀÂÃ]','g'), 'A');
		  text = text.replace(new RegExp('[áàâã]','g'), 'a');
		  text = text.replace(new RegExp('[ÉÈÊ]','g'), 'E');
		  text = text.replace(new RegExp('[éèê]','g'), 'e');
		  text = text.replace(new RegExp('[ÍÌÎ]','g'), 'I');
		  text = text.replace(new RegExp('[íìî]','g'), 'i');
		  text = text.replace(new RegExp('[ÓÒÔÕ]','g'), 'O');
		  text = text.replace(new RegExp('[óòôõ]','g'), 'o');
		  text = text.replace(new RegExp('[ÚÙÛ]','g'), 'U');
		  text = text.replace(new RegExp('[úùû]','g'), 'u');
		  text = text.replace(new RegExp('[Ç]','g'), 'C');
		  text = text.replace(new RegExp('[ç]','g'), 'c');
	  return text;
	} 
	
	var p_arrIdxFilterArray = new Array();
	function filterArray(arr,v,k,operador) {
		var k = !k?'':k;
		var operador = !operador?'':operador+'';
		p_arrIdxFilterArray = new Array();
		var v = v+'';
		var arrResult = new Array();
		if(v+''=='') {
			arrResult = arr;
		} else {
				if(k+''!='') {
					for(i in arr) {
						var row = arr[i];
						for(field in row) {
							if(field+''==k+'') {
								var value = row[field]+'';
								var valueLower = value.toLowerCase();
								var valueLower_SemAcentos = tiraAcento(valueLower);
								
								var arrV = v.split(' ');
								var qtd = 0;
								var qtdSearch = 0;
								//for(iLoop=0;iLoop<arrV.length;iLoop++) {
								for(iLoop in arrV) {
									var vAux = arrV[iLoop];
									if(vAux+''!='') {
											qtd++;
											var vLower = vAux.toLowerCase();
											var vLower_SemAcentos = tiraAcento(vLower)+'';
											//var boSearch = valueLower.indexOf(vLower);
											var boSearch_SemAcentos = valueLower_SemAcentos.indexOf(vLower_SemAcentos);
											//if(boSearch!=-1 || boSearch_SemAcentos!=-1) {
											
											//alert(operador + ' ---- ' + valueLower_SemAcentos + ' = ' + vLower_SemAcentos);
											switch(operador) {
												case '<>' :
														if(boSearch_SemAcentos==-1) {
															arrResult[i+''] = row;
															p_arrIdxFilterArray[qtdSearch] = i+'';
															qtdSearch++;
														}
													break;
												case '=' :
														if(valueLower_SemAcentos+''==vLower_SemAcentos+'') {
															arrResult[i+''] = row;
															p_arrIdxFilterArray[qtdSearch] = i+'';
															qtdSearch++;
														}
													break;
												default :
														if(boSearch_SemAcentos!=-1) {
															arrResult[i+''] = row;
															p_arrIdxFilterArray[qtdSearch] = i+'';
															qtdSearch++;
														}
													break;
											}
									}
								}
								if(qtd+''!=qtdSearch+'') {
									arrResult.splice(i+'', 1);
									//arrResult[i] = new Array();							
								}
							}
						}
						//break;
					}
				} else {
					for(i in arr) {
						var row = arr[i];
						for(field in row) {
							var value = row[field]+'';
							var valueLower = value.toLowerCase();
							var valueLower_SemAcentos = tiraAcento(valueLower);
							
							var arrV = v.split(' ');
							var qtd = 0;
							var qtdSearch = 0;
							//for(iLoop=0;iLoop<arrV.length;iLoop++) {
							for(iLoop in arrV) {
								var vAux = arrV[iLoop];
								if(vAux+''!='') {
										qtd++;
										var vLower = vAux.toLowerCase();
										var vLower_SemAcentos = tiraAcento(vLower);
										//var boSearch = valueLower.indexOf(vLower);
										var boSearch_SemAcentos = valueLower_SemAcentos.indexOf(vLower_SemAcentos);
										//if(boSearch!=-1 || boSearch_SemAcentos!=-1) {
										switch(operador) {
											case '<>' :
													if(boSearch_SemAcentos==-1) {
														arrResult[i+''] = row;
														p_arrIdxFilterArray[qtdSearch] = i+'';
														qtdSearch++;
													}
												break;
											case '=' :
													if(valueLower_SemAcentos+''==vLower_SemAcentos+'') {
														arrResult[i+''] = row;
														p_arrIdxFilterArray[qtdSearch] = i+'';
														qtdSearch++;
													}
												break;
											default :
													if(boSearch_SemAcentos!=-1) {
														arrResult[i+''] = row;
														p_arrIdxFilterArray[qtdSearch] = i+'';
														qtdSearch++;
													}
												break;
										}
								}
							}
							if(qtd+''!=qtdSearch+'') {
								arrResult.splice(i+'', 1);
								//arrResult[i] = new Array();							
							}
						}
						//break;
					}
				}
		}
		
		var arrResultNew = new Array();
		for(i in arrResult) {
			var row = arrResult[i];
			if(isObject(row)) {
				arrResultNew.push(row);
			}
		}
		
		
		
		return arrResultNew;
	}
	this.loadScreenshot = function() {
		$(".screenshot").hover(function(e){
			this.t = this.title;
			this.a = this.alt;
			this.r = $(this).attr('rel');
			this.title = "";	
			var c = (this.t != "") ? "<br/>" + this.t : "";
			var a = (this.a != "") ? this.a : this.src;
			var dt = new Date();
			var rnd = dt.getTime();
			$("body").append("<p id='screenshot'><img src='"+ this.r +"?"+rnd+"' alt='"+a+"' onError='$(this).remove()'  />"+ c +"</p>");
			$("#screenshot")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");
				
				//$(this).removeClass('screenshot')
		},
		function(){
			this.title = this.t;	
			$("#screenshot").remove();
		});	
		$(".screenshot").mousemove(function(e){
			$("#screenshot")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px");
		});	
	}
	
	function reverse(inp) {
	  var inp = !inp?'':inp;
	  var outp = 0;
	  for (i = 0; i <= inp.length; i++) {
		outp = inp.charAt (i) + outp
	  }
	  return outp;
	} 
	
	function getRadicalUrlImage(url) {
		var strRev = reverse(url);
		var arr = (strRev+'').split('.');
		var size = (arr[0]+'').length;
		var radical = (url+'').substring(0,(url.length-size));
		return radical;
	}
	
	function getFileNameUrl(url) {
		var strRev = reverse(url);
		var arr = (strRev+'').split('/');
		var size = (arr[0]+'').length;
		var radical = (url+'').substring((url.length-size),url.length);
		return radical;
	}
	
	getUrlValidImage = function(url){
		var result  = url;
		var arrEXT = ('jpg,gif,png,tif,bmp,jpeg').split(',');
		var radical = getRadicalUrlImage(url+'');
		
		for(i in arrEXT) {
			var ext = arrEXT[i];
			var urlNew = radical + ext;
			$('body').append('<div id="testimg" ><img src="'+urlNew+'" onerror="$(this).remove()" /></div>');
			var objIMG = $('#testimg').find('img').get(0);
			var w = $(objIMG).width();
			$('#testimg').remove();
			if(w) {
				return urlNew;
			}
		}
		return result;
	}
	
	function dateFormatDefault(dt) {
		var dt = !dt?'':dt+'';
		if(dt) {
			if(dt.indexOf('-')!=-1) {
				var part = dt.split(' ');
				var data = part[0];
				var time = part[1];
				
				var arrData = data.split('-');
				var dataNew = '';
				
				if((arrData[0]+'').length+''=='4') {
						dataNew = arrData[2] + '/' + arrData[1] + '/' + arrData[0];
					return dataNew + ' ' + time;
				} else {
						dataNew = arrData[0] + '/' + arrData[1] + '/' + arrData[2];
					return dataNew + ' ' + time;
				}
			} else if(dt.indexOf('/')) {
				
			}
		}
	}
	

	var cep = function() {
		this.strCEP = '';
		this.resultadoCEP = new Array();
		this.fnretorno = '';
		
		this.setCEP = function(v) {
			this.strCEP = !v?'':$.trim(v)+'';
		}
		
		this.getFrete = function() {
			var FRETE_PAC 			= '41106';
			var FRETE_SEDEX 		= '40010';
			var FRETE_SEDEX_10 		= '40215';
			var FRETE_SEDEX_HOJE 	= '40290';
			var FRETE_E_SEDEX 		= '81019';
			var FRETE_MALOTE 		= '44105';
			var FRETE_SEDEX_COBRAR 	= '44105';
			var FRETE_ENC_NORMAL 	= '41017';
			
			var FRETE = FRETE_E_SEDEX;
			
			var url = "http://www.correios.com.br/encomendas/precos/calculo.cfm?resposta=Xml&servico="+FRETE+"&cepOrigem=70680200&cepDestino=73025045&peso=1&MaoPropria=N&valorDeclarado=&avisoRecebimento=N";
			var result = '';
			var urlLocal = baseUrlModule + 'actionpub/getcep/cep/' + this.strCEP;			
			$.ajax({
			  url: urlLocal,
			  async: false,
			  success: function(data) {
				result = data;
			  }
			});
			
			/*
			$.getScript(url,function(a,b){
			});
			*/
			
			
			return result;
		}
		
		this.getEndereco = function() {
			//tipo_logradouro,logradouro,bairro,cidade,uf
			this.resultadoCEP["resultado"] = 0;
			if(this.strCEP+'' != ""){  
				/* 
					Para conectar no serviço e executar o json, precisamos usar a função 
					getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros 
					dataTypes não possibilitam esta interação entre domínios diferentes 
					Estou chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no formulário 
					http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val() 
				*/
				var fnretorno = this.fnretorno;
				$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+this.strCEP, function(){  
					// o getScript dá um eval no script, então é só ler!  
					//Se o resultado for igual a 1  
					if(resultadoCEP["resultado"]){  
						for(i in resultadoCEP) {
							resultadoCEP[i] = unescape(resultadoCEP[i]);
						}
						this.resultadoCEP = resultadoCEP;
						if(fnretorno) {
							func = fnretorno;
							var arrArg = new Array();
							arrArg.push(resultadoCEP);
							html = func.apply('',arrArg);
						}
						
						// troca o valor dos elementos  
						/*
						$("#rua").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));  
						$("#bairro").val(unescape(resultadoCEP["bairro"]));  
						$("#cidade").val(unescape(resultadoCEP["cidade"]));  
						$("#estado").val(unescape(resultadoCEP["uf"]));  
						*/
					}else{  
						//alert("Endereço não encontrado");  
					}  
				});  
				
			}  
			return this.resultadoCEP;
		}
	}
	
	
	
	function getSaldacao() {
		var d = new Date();
		var hour = d.getHours();
		if(hour < 5) { return "Boa Noite"; }
		else
		if(hour < 8)
		{ return "Bom Dia"; }
		else
		if(hour < 12) { return "Bom Dia!"; }
		else
		if(hour < 18) { return "Boa tarde"; } else { return "Boa noite"; }


	}
	
	
	//alert(getEndereco('70680200'));

	
	var time_fnMouseOverIMG = '';
	function fnMouseOverIMG_remove(objIMG) {
		clearTimeout(time_fnMouseOverIMG);
		time_fnMouseOverIMG = setTimeout("$('#img_preview').remove()",300);
	}
	function bnr_previewMouseOverIMG(objIMG) {
		var top  = $(objIMG).offset().top; 
		var left = $(objIMG).offset().left;
		var screenW = $('body').width();
		var screenH = $('body').height();
		var diff_w = screenW-left;
		var diff_h = screenH-top;
		
		var src = $(objIMG).attr('src')+'';
		var objA = $(objIMG).parents('a').get(0);
		//var strImage = $(objIMG).outerHTML();
		clearTimeout(time_fnMouseOverIMG);
		$('#img_preview').remove();
		$(objA).attr('onMouseout',"fnMouseOverIMG_remove()");
		
		var addStyle = diff_w<500?' margin: 50px 0px 0px -300px; ':' margin: 50px 0px 0px 0px; ';
		//addStyle += diff_h<500?' margin-top: -50px !important; ':'';
		
		var strImage = '<img id="img_preview" src="'+src+'" style="border: solid 2px #444; position: absolute;z-index:1000;'+addStyle+'" onMouseover="clearTimeout(time_fnMouseOverIMG);" onMouseout="fnMouseOverIMG_remove();" />';
		//alert($(objIMG).outerHTML());
		//$(this).before('<img src="'+src+'" style="position: absolute;" />')

		$(objA).before(strImage);
	}
	function trim(stringToTrim) {
		var stringToTrim = stringToTrim+'';
		return stringToTrim.replace(/^\s+|\s+$/g,"");
	}
	
	function toHTML(html) {
		var html = !html?'':html;
		html = replaceSubstring(html,'"','&quot;');
		html = replaceSubstring(html,"'",'&apos;');
		//html = replaceSubstring(html,'""','&quot;');
		//&apos;
		return html;
	}
	
	function getRequests() {
			var result = new Array();
			//var search = document.location.search+'';
			var search = QUERY_STRING+'';
			if(search) {
				search = search.substring(0,1)+''=='?'?search.substring(1,search.length):search;
				
				//alert(unescape(search))
				var arrS = search.split('&');
				for(i in arrS) {
					var row = arrS[i];
					var arrAux = row.split('=');
					result[(arrAux[0]+'').toLowerCase()] = (arrAux[1]+'').toLowerCase();
					//alert((arrAux[0]+'').toLowerCase() + ' = ' + (arrAux[1]+'').toLowerCase())
				}
			}
			return result;
	}
	
	function getQuerystrings(invalidos,validos) {
		var invalidos = !invalidos?'':invalidos+'';
		var validos = !validos?'':validos;
		var arrinvalidos = new Array();
		
		
		arr = invalidos.split(',');
		for(i in arr) {
			arrinvalidos[arr[i]] = arr[i];
		}
		
		
		
		var arr = getRequests();
		var tGlue = '', retVal = '';
		for(i in arr) {
			boInv = !arrinvalidos[i]?'':'1';
			if(boInv+''=='') {
				retVal += tGlue + i +'=' + arr[i];
				tGlue = '&';
			}
		}
		return retVal;
	}

	function implode (glue, pieces) {
		// Joins array elements placing glue string between items and return one string  
		// 
		// version: 1004.2314
		// discuss at: http://phpjs.org/functions/implode    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Waldo Malqui Silva
		// +   improved by: Itsacon (http://www.itsacon.net/)
		// +   bugfixed by: Brett Zamir (http://brett-zamir.me)
		// *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: 'Kevin van Zonneveld'
		// *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
		// *     returns 2: 'Kevin van Zonneveld'
		var i = '', retVal='', tGlue='';
		if (arguments.length === 1) {        pieces = glue;
			glue = '';
		}
		if (typeof(pieces) === 'object') {
			if (pieces instanceof Array) {            return pieces.join(glue);
			}
			else {
				for (i in pieces) {
					retVal += tGlue + pieces[i];                tGlue = glue;
				}
				return retVal;
			}
		}    else {
			return pieces;
		}
	}
	
	setCookie = function(cs,v,d) {
		cs = !cs?'':cs+'';
		d = !d?10:d;
		if(cs) {
			delCookie(cs);
			$.cookie(cs, v, { path: '/', expires: d });
		}
	}
	getCookie = function(cs) {
		cs = !cs?'':cs+'';
		if(cs) {
			return $.cookie(cs);
		}
	}
	delCookie = function(cs) {
		cs = !cs?'':cs+'';
		if(cs) {
			$.cookie(cs, null);
		}
	}
	
	
