// Ativar o PNGFIX na página

function PNGFix(){
	
	$(document).ready(function(){ 
        $(document).pngFix(); 
    });	
	
	}


//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// MOSTRA/ESCODE DIV ///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////

function ShowHide(txt1,txt2){
	
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {

// choose text for the show/hide link
var showText="["+ txt1 +"]";
var hideText="["+ txt2 +"]"; 

// append show/hide links to the element directly preceding the element with a class of "toggle"
$(".show-hide").prev().append('<a href="#" class="toggleLink">'+showText+'</a>');

// hide all of the elements with a class of 'toggle'
$('.show-hide').hide();

// capture clicks on the toggle links
$('a.toggleLink').click(function() {

// change the link text depending on whether the element is shown or hidden
if ($(this).text()==showText) {
$(this).text(hideText);
}
else {
$(this).text(showText);
}

// toggle the display
$(this).parent().next('.show-hide').toggle('slow');

// return false so any link destination is not followed
return false;

}); 
});

	
} // fim da função 

//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// GERAR CALEDÁRIO ///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////



function Calendario(onde){

$.dpText = {
	TEXT_PREV_YEAR		:	'Ano anterior',
	TEXT_PREV_MONTH		:	'Mês anterior',
	TEXT_NEXT_YEAR		:	'Próximo ano',
	TEXT_NEXT_MONTH		:	'Próximo mês',
	TEXT_CLOSE			:	'Fechar',
	TEXT_CHOOSE_DATE	:	'Clique aqui para escolher a data.'
}
$(function()
{
	$(""+ onde +"").datePicker() 
});


}




//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// GERAR CALEDÁRIO - DE / PARA ///////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////




function CalendarioDP(){

$(function()
            {
				$('.calendarioDP').datePicker()
				$('#dtinicio').bind(
					'dpClosed',
					function(e, selectedDates)
					{
						var d = selectedDates[0];
						if (d) {
							d = new Date(d);
							$('#dtfim').dpSetStartDate(d.addDays(1).asString());
						}
					}
				);
				$('#dtfim').bind(
					'dpClosed',
					function(e, selectedDates)
					{
						var d = selectedDates[0];
						if (d) {
							d = new Date(d);
							$('#dtinicio').dpSetEndDate(d.addDays(-1).asString());
						}
					}
				);
            });

	
} // fim da função 





//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// APLICAÇÃO DE MÁSCARAS PARA FORMULÁRIOS VIA JQUERY /////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////




function Mascara(onde,tipo){

jQuery(function($){

	switch(tipo){
	
	case "data":
	$(""+ onde +"").mask("99/99/9999");
	break;
	
	case "cep":
	$(""+ onde +"").mask("99999-999");
	break;
	
	case "cepGMAP":
	$(""+ onde +"").mask("99999-999"); 
	break;
	
	case "fone":
	$(""+ onde +"").mask("(99) 9999-9999");
	break;
	
	case "cpf":
	$(""+ onde +"").mask("999.999.999-99");
	break;
	
	case "cnpj":
	$(""+ onde +"").mask("99.999.999/9999-99");
	break;
	
	}

});

	
}



//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// VALIDAÇÃO DE FORMULÁRIOS VIA JQUERY ///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////



function ValidarForm(w){
	
$.metadata.setType("attr", "validate");
	$(document).ready(function() {
	$(""+w+"").validate();
});
	jQuery.validator.setDefaults({
	debug: true,
	success: "valid"

}); 
	}




/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
// FUNCÃO PARA PEGAR ENDEREÇO PELO CEP //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////



function PegarEndereco() {
	
			
			if($("#cep").val() == "" || $("#cep").val() == "__.___-___" ){
			alert("Preencha o CEP!");
			return false;
			}			
			
			$(".fm_loadEnd").show();
			//$(".fm_loadEnd").highlightFade({color:'#FF0000',speed:1000,iterator:'sinusoidal'});
			
			// Se o campo CEP não estiver vazio
			if($.trim($("#cep").val()) != ""){
				/*
					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()
				*/
				$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
					// o getScript dá um eval no script, então é só ler!
					//Se o resultado for igual a 1
			  		if(resultadoCEP["resultado"]){
						// troca o valor dos elementos
						$("#txtLogradouro").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
						$("#txtBairro").val(unescape(resultadoCEP["bairro"]));
						$("#txtCidade").val(unescape(resultadoCEP["cidade"]));
						$("#txtEstado").val(unescape(resultadoCEP["uf"]));
					
						$(".fm_loadEnd").remove();
					
					}else{
						alert("Endereço não encontrado.");
						$(".fm_loadEnd").remove();
					} 
				});
			}
	}
	
	
	
	
	
	
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// JQUERY CARROSSEL ////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////





function CarrosselWL(id){
	
	/*function mycarousel_initCallback(carousel) {
    jQuery('.jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

    jQuery('.jcarousel-scroll select').bind('change', function() {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });

    jQuery('#'+id+'-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#'+id+'-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
}; */

// Ride the carousel...
jQuery(document).ready(function() {
    jQuery("#"+id+"").jcarousel({
        scroll: 1,
        //initCallback: mycarousel_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});
	
	} // fim função Carrossel 




////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////	
//// JQUERY TOOLTIP ////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////

function ToolTip(){
	
	$(function() { 
			   
	$("#tooltip").corner(); 
	$(".tool").tooltip({  
    track: true, 
    delay: 0, 
    showURL: false, 
    opacity: 1,  
    fixPNG: true, 
    //showBody: " - ", 
    //extraClass: "pretty fancy",
    top: 10, 
    left: 10,
	fade:350
});			   
			   
	});
	
	
	}

function ToolTipAjuda(){
	
	$(".ajuda").tooltip({ 
    track: true, 
    delay: 0, 
    showURL: false, 
    opacity: 1, 
    fixPNG: true, 
    //showBody: " - ", 
    //extraClass: "pretty fancy",
    top: 10, 
    left: 10,
	fade:350
}); 

	
	} // fim da função ToolTipAjuda


function Tool(onde){
	
	$(""+ onde +"").tooltip({
	track: true,
	delay: 0,
	showURL: false,
	fixPNG: true,
	showBody: " - ",
	top: -15,
	left: 5,
	fade:250
});
	
	} // fim da função tooltip
	
	
	

//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// JQUERY FORM AJAX ////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////



function FormAjax(divform, divresp, pgreq, metodo){
	
	   // Quando o documento for lido
   $(document).ready(function() {
       // quando o formulário for submetido
       $("#"+divform+"").submit(function() {
           // Aqui exibimos um texto na div #resposta assim que a requisição é iniciada
           $(this).ajaxStart(function() {
               $("#"+divresp+"").text("Processando...").show();
           });
           // opções a serem enviadas pela função
           var options = {
               target: "#"+divresp+"", // destino: onde será exibida a resposta da página requisitada, no caso a div #resposta
               url: ""+pgreq+"", // aqui a página que será requisitada
               type: "post", // metodo de envio, post ou get
               // caso a função tenha sucesso
               success: function(resposta) {
                   // mostra a resposta na div resposta e exibe a div
                   $("#"+ divresp +"").text(resposta).show();
               }
           }
          
           // aqui eu envio os dados com as opções
           $(this).ajaxSubmit(options);
           // isso é para que o formulário não envio os dados, pois os mesmos serão enviados por ajax
           return false;
       });
   });
	
}//fim da função form ajax



//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// JQUERY e GOOGLE MAPS ////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////  

function WLMapa(endereco,empresa,logo){

var logoIMG = "<img src='"+logo+"'/>";

jQuery('#GMAWL').jmap('init', {'mapType':'map','mapCenter':[-3.72106,-38.544674],'mapZoom':13});

        jQuery('#GMAWL').jmap('SearchAddress', {
            'query': endereco,
            'returnType': 'getLocations'
        }, function(result, options) {
            
            var valid = Mapifies.SearchCode(result.Status.code);
            if (valid.success) {
            jQuery.each(result.Placemark, function(i, point){
               
			jQuery('#GMAWL').jmap('init', {'mapType':'map','mapCenter':[point.Point.coordinates[1],point.Point.coordinates[0]],'mapZoom':15});	   
			   
			   jQuery('#GMAWL').jmap('AddMarker',{
                        'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                        'pointHTML': logoIMG +"<br><b>"+ empresa +"</b><br>"+ endereco						
						
                    }); 
			    });
            } else {
                jQuery('#GMAErro').val(valid.message);
            }
        });
   
   WLRota(endereco); 
   
} // fim da funcao WLMapa
 
function WLRota(pontofinal){
	
	jQuery(document).ready(function(){
                    
                     jQuery('#bntTracarRota').click(function(){
						
						if(WLFormRota() == true ){
						
						var enderecoCli = $("#sltTipoEnd").val() +" "+ $("#txtLogradouro").val() + ", " + $("#txtNum").val() + ", "+ $("#txtCep").val() + ", BRA "; 
						
						
						$("#formrota").fadeOut(500); 
						$("#rotaload").fadeIn(500);
						$("#GMAWLPP").fadeIn(500);
						
						// Criando a rota //////////////////////////////////////////
						
						 jQuery('#GMAWL').jmap('SearchDirections', {
                            'query': 'from:'+ enderecoCli + ' to:'+ pontofinal,
                            'panel':'#GMAWLPP'
                        }, function(result, options) {
                                    var valid = Mapifies.SearchCode(result.getStatus());
                                    if (valid.success) {
                                        jQuery.each(result.Placemark, function(i, point){
                                            jQuery('#GMAWL').jmap('AddMarker',{
                                                'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
                                                'pointHTML':point.address
                                            });
                                        });

                   } else {
                                            jQuery('#GMAErro').val(valid.message);
                   }
				   
						$("#rotaload").fadeOut(500);
						$("#GMANovaConsulta").fadeIn(500);
				   
                
				});
					   ///////////////////////////////////////////////////////////
					   
														
							$("#btnNovaConsulta").click(function(){
								$("#formrota").fadeIn(500);
								$("#GMAWLPP").fadeOut(500);
								$("#GMANovaConsulta").fadeOut(500);								
							});
                					
					}// fim da condição para acontecer o evento.
						
					return false;  	
            });
       });
	
} // fim da função WLRota 


function WLFormRota(){ 
	
			if($("#sltTipoEnd").val() == ""){
			$("#sltTipoEnd").highlightFade({color:'red',speed:1000,iterator:'sinusoidal'});
			return false; }
			
			else if($("#txtLogradouro").val() == ""){
			$("#txtLogradouro").highlightFade({color:'red',speed:1000,iterator:'sinusoidal'});
			return false; }
			
			else if($("#txtNum").val() == ""){
			$("#txtNum").highlightFade({color:'red',speed:1000,iterator:'sinusoidal'});
			return false; }
			
//			else if($("#txtCep").val() == ""){
//			$("#txtCep").highlightFade({color:'red',speed:1000,iterator:'sinusoidal'});
//			return false; }
		
			else{ return true;}					
						
} // fim da função WLFormRota


//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// JQUERY ABAS /////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////


function JAbas(onde){
	
	$(document).ready(function() {
      $.tabs(""+ onde +"");
        });
} 

//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// JQUERY TIME AGO DEFAULTS ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////

function TimeAgo(){
	
	jQuery.timeago.settings.strings = {
	suffixAgo: "atrás",
	suffixFromNow: "a partir de agora",
	seconds: "menos de um minuto",
	minute: "cerca de um minuto",
	minutes: "%d minutos",
	hour: "cerca de uma hora",
	hours: "cerca de %d horas",
	day: "um dia",
	days: "%d dias",
	month: "cerca de um mês",
	months: "%d meses",
	year: "cerca de um ano",
	years: "%d anos"
	
	};
	
} // fim da função time ago/


//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// JQUERY TABLE SORTER /////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////// 

function TableSorter(onde){
	
	$(function() { 
			   
		$("#"+onde+"").tablesorter({widgets: ['zebra']});
		
	});	
	
}// fim da função TableSorter


//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//// Bloquer ////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////


function jqBlocker(txt,onde) { 
	
  if(txt == null){txt = " Aguarde...";}
	
	$(document).ready(function() { 
			
			$(onde).block({ 
				message: '<span class="txtblocker"><img src="http://10.1.1.3/intranet/imagens/load2.gif"/>'+ txt +'</span>',
				overlayCSS: { backgroundColor: '#ffffff', opacity: '0.95'},
				css: { border: 'none', width:'90%'}
				 
			});  
 
		//setTimeout($.unblockUI,10000);
			
	}); // fim do document ready 
	
} // fim da função jqBlocker

