var ultimoHash = "nope";
$(function(){
	$.history.init(function(url) {
        pageload(url == "" ? "" : url);
    }, { unescape: true });
	$("a[rel='load']").live('click', function(e) {
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		$.history.load(hash);
		return false;
	});

	$('#vid').maxImage({
		isBackground: true,
		overflow: "auto"
	});
	aplicaFuncoes()
	$(window).resize(function() {tamanhos()});
	$("#buscar").click(function(){
		if ($("#frmBusca").css('display') == 'none')
			$("#frmBusca").show();
		else
			$("#frmBusca").hide();
	});
	$('.data').keyup(function(event){
        formata('DATA', this, 10, event);
	})
	$('.data').blur(function(event){
		if (this.value.substr( 0, 2 ) > 31 ) {
			alert('O limite para os dias é 31.');
			this.value = "";
			this.focus();
		} else if (this.value.substr( 3, 2 ) > 12 ) {
			alert('O limite para os meses é 12.');
			this.value = "";
			this.focus();
		}
	});
	$('.numero').keydown(function(event){
        return somenteNumero(event);
	})
	$('.valor').keyup(function(event){
        return formata('VALOR', this, 10, event);
	})
	$('.telefone').keyup(function(event){
        return formata('TELEFONE', this, 12, event);
	})
	$('.cep').keyup(function(event){
        return formata('CEP', this, 9, event);
	})
	$('.cpf').keyup(function(event) {
        return formata('CPF', this, 9, event);
	})
	$('.cpf').blur(function(event) {
        if (!validarCPF(this.value))
        	this.value = "";
	})


});

function banner(){
	$("body").append('<div style="position: absolute;left: 0;right: 0; top: 0;z-index: 1000;" id="bannerAceitar"><img src="img/bannerFacebook/bg.png" style="width: 100%;height:100%"/><div style="background: url(\'img/bannerFacebook/imgFb.png\'); position: absolute; left: 50%; top: 50%; margin-left: -420px; margin-top: -300px; width: 839px;height: 600px; "><a href="#" style="position: absolute; right:30px;top:30px;" onclick="$(\'#bannerAceitar\').remove(); return false;"><img  style="border: none;" src="img/bannerFacebook/fechar.png" /></a><img src="img/bannerFacebook/texto.png" style="position: absolute; left:498px;top:469px;" /><a href="http://www.facebook.com/mixuse" onclick="$(\'#bannerAceitar\').remove();" target="face" style="position: absolute; left:420px;top:469px; border: none;"><img style="border: none;" src="img/bannerFacebook/like.png"/></a><a href="http://www.facebook.com/mixuse" onclick="$(\'#bannerAceitar\').remove();" target="face" style="position: absolute; left:608px;top:492px;"><img style="border: none;" src="img/bannerFacebook/curtir.png"/></a></div></div>')
	
/*	
	$.fancybox({
		'showCloseButton'		: false,
		'padding'		: 0,
		'autoScale'		: false,
		'transitionIn'	: 'none',
		'transitionOut'	: 'fade',
		'title'			: '',
		'width'			: 780,
		'height'		: 430,
		'href'			: './banners/bannerPais2011.swf',
		'type'			: 'swf',
		'swf'			: {
		   	'wmode'		: 'transparent',
			'allowfullscreen'	: 'false'
		}		
	});
	$('#fancybox-outer').css("background","transparent");
*/ 
}

function fechaFancy(){
	$.fancybox.close();
	//$('#fancybox-outer').css("background",'url("./img/bg85.png") repeat scroll 0 0 transparent');
}

function aplicaFuncoes(){
	tamanhos();

	$(".ampliar").fancybox({
		'overlayOpacity'	: 0.9,
		'autoScale'			: false,
		'titlePosition'		: 'over',
		'overlayColor'		: '#111'
	});

	$("#anoAtual").click(function(){
		$("#listaAno").slideToggle();
	});

	if($("#slider").length){
		$("#slider").easySlider({
			auto: false, 
			prevText: 		'<img src="./img/setaEsq.png" alt="&lt;" title="Anterior" border="0">',
			nextText: 		'<img src="./img/setaDir.png" alt="&gt;" title="Pr&oacute;ximo" border="0">',
			width: 930,
			height:101
		});
	}

	$("#atbutton").html('');
	
	//alert(document.location.href);
	addthis_share.url = document.location.href;
	//	alert(addthis_share.url);
	addthis.url = document.location.href;
	addthis.button("#atbutton");

	galeria();
	produtos();
	$(".youtube").click(function() {
		$.fancybox({
			'padding'			: 0,
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'title'				: this.title,
			'width'				: 680,
			'height'			: 495,
								  
			'href'				: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
			'type'				: 'swf',
			'swf'				: {
									'wmode'	: 'transparent'
								},
			'allowfullscreen'	: 'true',
			'overlayOpacity'	: 0.9	,
			'overlayColor'		: '#111'
		});
		
		return false;
	});	
	$(".ampliaDivas").click(function() {
		$.fancybox({
			'padding'			: 0,
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'title'				: this.title,
			'width'				: 'auto',
			'height'			: 'auto',
								  
			'href'				: this.href,

			'allowfullscreen'	: 'true',
			'overlayOpacity'	: 0.9	,
			'overlayColor'		: '#111'
		});
		
		return false;
	});
}

function colecao(){

   	var aleat = Math.random() * 6;
   	aleat = Math.floor(aleat) + 1; 
	$('#load').fadeOut().html('');
	$('#marcacacao').fadeOut();
	
//	var swf = linha;
	var flash = '<div id="vid" style="width:720px;height:480px;" >';
	flash = flash+'<object  classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + $(window).width()+ '" height="'+$(window).width()+'"id="video" align="middle">';
	flash = flash+'<param name="allowScriptAccess" value="sameDomain" />';
	flash = flash+'<param name="allowFullScreen" value="false" />';
	flash = flash+'<param name="movie" value="./swf/factory'+ aleat +'.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#FFFFFF" /><param name="wmode" value="transparent" /><param name="salign" value="t" />';
	flash = flash+'<embed src="./swf/factory'+ aleat +'.swf" salign="t" wmode="transparent" quality="high" bgcolor="#FFFFFF" width="' + $(window).width()+ '" height="'+$(window).width()+'" name="video" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
	flash = flash+'</object></div>';
	flash = flash+'<div style="position:absolute;left:0;top:0;width:100%;height:100%;background:url(\'./img/malha.gif\')"></div>';
	$("#fundo").html(flash);
}

var colecao_atual = "factoryGirl";
function menuColecao(qual){
	var ar1 = Array();
	ar1["factoryGirl"]="0";
	ar1["edie"]="1";
	ar1["peggy"]="2";
	ar1["twiggy"]="3";
	ar1["veruschka"]="4";
	ar1["penelope"]="5";
	ar1["luna"]="6";

	var ar2 = Array();
	ar2[0]="factoryGirl";
	ar2[1]="edie";
	ar2[2]="peggy";
	ar2[3]="twiggy";
	ar2[4]="veruschka";
	ar2[5]="penelope";
	ar2[6]="luna";
	
	if((ar1[qual] != undefined)||((qual == 'voltar')||(qual == 'prev')||(qual == 'prox'))){
		$("#navfactory").show()
	}else{
		$("#navfactory").hide()
	}
	
	if(qual == "prox"){
		if((parseInt(ar1[colecao_atual])+1) > 6){
			colecao_atual = "factoryGirl";
			$("#factoryGirl").animate({'left':'0px'})
			$(".linhasfactory").animate({'left':'930px'})
		}else{
			$("#"+ar2[(parseInt(ar1[colecao_atual])+1)]).animate({'left':'0px'})
			$("#"+ar2[ar1[colecao_atual]]).animate({'left':'-930px'})
			colecao_atual = ar2[(parseInt(ar1[colecao_atual])+1)];
		}
	}else if(qual == "prev"){
		if((parseInt(ar1[colecao_atual])-1) < 0){
			colecao_atual = "luna";
			$("#luna").animate({'left':'0px'})
			$("#factoryGirl").animate({'left':'-930px'})
			$(".linhasfactory").not($("#luna")).not("#factory").animate({'left':'-930px'})
		}else{
			$("#"+ar2[(parseInt(ar1[colecao_atual])-1)]).animate({'left':'0px'})
			$("#"+ar2[ar1[colecao_atual]]).animate({'left':'930px'})
			colecao_atual = ar2[(parseInt(ar1[colecao_atual])-1)];
		}
	}else if(qual == 'voltar'){
		colecao_atual = "factoryGirl";
		$("#factoryGirl").animate({'left':'0px'})
		$(".linhasfactory").animate({'left':'930px'})
	}else{
		for(i=0; i < parseInt(ar1[qual]); i++){
			$("#"+ar2[i]).animate({'left':'-930px'})
		}
		
		colecao_atual = qual; 
		$("#"+qual).animate({'left':'0px'})
		$("#factoryGirl").animate({'left':'-930px'})
	}
	if(colecao_atual=="factoryGirl"){
		$("#navfactory").hide()
	}

}


function menuLinhaProduto(linha){
	var loc = document.location.href;
	loc = loc.split('/');
    dir = ((loc[loc.length - 3]=='ing')||(loc[loc.length - 3]=='esp'))?"../":"./";
	$('#load').html('');
	$('#load').hide();
	$('#marcacacao').hide();
	var swf = linha;
	var flash = '<div id="vid" style="width:720px;height:480px;" >';
	flash = flash+'<object  classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + $(window).width()+ '" height="'+$(window).width()+'"id="video" align="middle">';
	flash = flash+'<param name="allowScriptAccess" value="sameDomain" />';
	flash = flash+'<param name="allowFullScreen" value="false" />';
	flash = flash+'<param name="movie" value="'+ dir +'swf/'+ swf +'" /><param name="quality" value="high" /><param name="bgcolor" value="#FFFFFF" /><param name="wmode" value="transparent" /><param name="salign" value="t" />';
	flash = flash+'<embed src="'+ dir +'swf/'+ swf +'" salign="t" wmode="transparent" quality="high" bgcolor="#FFFFFF" width="' + $(window).width()+ '" height="'+$(window).width()+'" name="video" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
	flash = flash+'</object></div>';
	flash = flash+'<div style="position:absolute;left:0;top:0;width:100%;height:100%;background:url(\''+ dir +'img/malha.gif\')"></div>';
	$("#fundo").html(flash);
}

function mostraLinhaProdutos(){
	$('#marcacacao').fadeIn();
	//$('#load').show();
}

function share() {
    var delay = 400;
    function hideMenu() {
        if (!$('.custom_button').data('in') && !$('.hover_menu').data('in') && !$('.hover_menu').data('hidden')) {
            $('.hover_menu').fadeOut('fast');
            $('.custom_button').removeClass('active');
            $('.hover_menu').data('hidden', true);
        }
    }
    $('.custom_button, .hover_menu').mouseenter(function() {
        $('.hover_menu').fadeIn('fast');
        $('.custom_button').addClass('active');
        $(this).data('in', true);
        $('.hover_menu').data('hidden', false);
    }).mouseleave(function() {
        $(this).data('in', false);
        setTimeout(hideMenu, delay);
    });    
};
function produtos(){
	if($('.mostraProduto').length){
		$('.produto0').show();

		function prod(n){
			if ($('.p'+n).css('display') =='none'){ 
				//$('.imagemProduto').hide();

				if ($('.p0').css('display') !='none')$('.p0').hide('slow');
				if ($('.p1').css('display') !='none')$('.p1').hide('slow');
				if ($('.p2').css('display') !='none')$('.p2').hide('slow');
				if ($('.p3').css('display') !='none')$('.p3').hide('slow');
				if ($('.p4').css('display') !='none')$('.p4').hide('slow');
				if ($('.p5').css('display') !='none')$('.p5').hide('slow');
				if ($('.p6').css('display') !='none')$('.p6').hide('slow');
				if ($('.p7').css('display') !='none')$('.p7').hide('slow');
				if ($('.p8').css('display') !='none')$('.p8').hide('slow');
				if ($('.p9').css('display') !='none')$('.p9').hide('slow');
				if ($('.p10').css('display') !='none')$('.p10').hide('slow');

				//$('.imagemProduto').show();
				$('.produto'+n).show('slow');
			};	
		}

		$('.mostraProduto0').click(function(){ prod(0) });
		$('.mostraProduto1').click(function(){ prod(1) });
		$('.mostraProduto2').click(function(){ prod(2) });
		$('.mostraProduto3').click(function(){ prod(3) });
		$('.mostraProduto4').click(function(){ prod(4) });
		$('.mostraProduto5').click(function(){ prod(5) });
		$('.mostraProduto6').click(function(){ prod(6) });
		$('.mostraProduto7').click(function(){ prod(7) });
		$('.mostraProduto8').click(function(){ prod(8) });
		$('.mostraProduto9').click(function(){ prod(9) });
		$('.mostraProduto10').click(function(){ prod(10) });


		$('.descProd').click(function(){ $('.modoUso').hide();$('.texto').show(); $(this).addClass("marcado");$('.mMu').removeClass("marcado"); });
		$('.mMu0').click(function(){ $('.modoUso0, .texto0').toggle(); $('.mMu0,.descProd0').toggleClass("marcado"); });
		$('.mMu1').click(function(){ $('.modoUso1, .texto1').toggle(); $('.mMu1,.descProd1').toggleClass("marcado"); });
		$('.mMu2').click(function(){ $('.modoUso2, .texto2').toggle(); $('.mMu2,.descProd2').toggleClass("marcado"); });
		$('.mMu3').click(function(){ $('.modoUso3, .texto3').toggle(); $('.mMu3,.descProd3').toggleClass("marcado"); });
		$('.mMu4').click(function(){ $('.modoUso4, .texto4').toggle(); $('.mMu4,.descProd4').toggleClass("marcado"); });
		$('.mMu5').click(function(){ $('.modoUso5, .texto5').toggle(); $('.mMu5,.descProd5').toggleClass("marcado"); });
		$('.mMu6').click(function(){ $('.modoUso6, .texto6').toggle(); $('.mMu6,.descProd6').toggleClass("marcado"); });
		$('.mMu7').click(function(){ $('.modoUso7, .texto7').toggle(); $('.mMu7,.descProd7').toggleClass("marcado"); });
		$('.mMu8').click(function(){ $('.modoUso8, .texto8').toggle(); $('.mMu8,.descProd8').toggleClass("marcado"); });
		$('.mMu9').click(function(){ $('.modoUso9, .texto9').toggle(); $('.mMu9,.descProd9').toggleClass("marcado"); });
		$('.mMu10').click(function(){ $('.modoUso10, .texto10').toggle(); $('.mMu10,.descProd10').toggleClass("marcado"); });

		$('#aplicaFish').Fisheye({
			maxWidth: 40,
			items: 'a',
			itemsText: 'span',
			container: '.dock-container2',
			itemWidth: 60,
			proximity: 80,
			alignment : 'left',
			valign: 'bottom',
			halign : 'center'
		});



	}
}

function pageload(hash) {
	if (hash != ultimoHash){
//alert(hash)
if(hash == "/produtos.php?l=9&promo" ){

	$.fancybox({
			'width'				: 670,
			'height'			: 685,
			'autoScale'			: false,
			'padding'			: 0,
			'href'				: './compre.php',
			'title'   			: 'compre',
			'titleShow'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'overlayOpacity'	: 0.9,
			'overlayColor'		: '#111'/*,
			'modal'				: true*/
		});
}
		if(hash) {
			$('#loading').show();
			$.get("."+hash, function(data){
				$('#marcacacao').fadeIn();//show();
				$('#load').html(data);
				aplicaFuncoes();
				$('#loading').hide();
			});		
	
		} else {
			$('#loading').show();
			$('#marcacacao').hide();
			$.get("./home.php", function(data){
				$('#marcacacao').hide();
				$('#load').html(data)
				aplicaFuncoes();
				$('#loading').hide();
			});		
			
			var loc = document.location.href;
			loc = loc.split('/');
			home = loc[loc.length - 1];
            lingua = loc[loc.length - 2];
			if (home == "" && lingua != 'esp' && lingua != 'ing'){
            	banner();
            }
		}
		ultimoHash = hash;
		//$('#load').delay(1000);
		$('#load').show();
	}
}

function buscar(){
	function processKey(e){
		if (e.which == 13) {
			document.location ='./#/busca.php?b=' + document.frmBuscar.busca.value;
			pageload('/busca.php?b=' + document.frmBuscar.busca.value);
		}
	}
	if (navigator.appName == 'Netscape')
		document.onkeypress = processKey;
	else {
		if (window.event.keyCode == 13){
			document.location ='./#/busca.php?b=' + document.frmBuscar.busca.value;
			pageload('/busca.php?b=' + document.frmBuscar.busca.value);
		}
	}
}

function eventos(evento){
	$.fancybox({
			'width'				: 550,
			'height'			: 380,
			'autoScale'			: false,
			'padding'			: 0,
			'href'				: './inscricaoEventos.php?cod_evento='+evento,
			'title'   			: 'Inscrição',
			'titleShow'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'overlayOpacity'	: 0.9,
			'overlayColor'		: '#111'
		});
$('#fancybox-outer').css("background",'url("./img/bg85.png") repeat scroll 0 0 transparent');	
}

function makingOf(){
	$.fancybox({
		'padding'			: 0,
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'title'				: this.title,
		'width'				: 680,
		'height'			: 495,
							  
		'href'				: 'http://www.youtube.com/v/TINzl4y6GB4&autoplay=1',
		'type'				: 'swf',
		'swf'				: {
								'wmode'	: 'transparent'
							},
		'allowfullscreen'	: 'true',
		'overlayOpacity'	: 0.9	,
		'overlayColor'		: '#111'
	});
    
    
}

function newsletter() {
	$.fancybox({
			//'orig'			: $(this),
			'width'				: 550,
			'height'			: 415,
			'autoScale'			: false,
			'padding'			: 0,
			'href'				: './newsletter.php',
			'title'   			: 'Newsletter',
			'titleShow'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'overlayOpacity'	: 0.9	,
			'overlayColor'		: '#111'
		});
$('#fancybox-outer').css("background",'url("./img/bg85.png") repeat scroll 0 0 transparent');
}

function trabalheConoscoNC() {
	$.fancybox({
			//'orig'			: $(this),
			'width'				: 550,
			'height'			: 400,
			'autoScale'			: false,
			'padding'			: 0,
			'href'				: './trabalheConoscoNC.php',
			'title'   			: 'Política de privacidade',
			'titleShow'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'iframe',
			'overlayOpacity'	: 0.9	,
			'overlayColor'		: '#111'
		});
$('#fancybox-outer').css("background",'url("./img/bg85.png") repeat scroll 0 0 transparent');
}

function tamanhos(){
	//alert($(window).height())
	var browserName=navigator.appName; 
	if (browserName=="Microsoft Internet Explorer")
 	{
 		if ($('#load').height() < $(window).height()-163)
			$('#site').css("height",$(window).height()-163);
		else
			$('#site').css("height","auto");
 	} else
 	{
		$('#site').css("min-height",$(window).height()-163);
	}
	//$('#footer').css("top",$('#site').height());
	//alert($(window).height())
	
	
	//$('#vid').attr("style","height:"+$(window).width()+"px;width:"+$(window).width()+"px;");

}

function galeria(){
	
	if ($("#album").length){
		// We only want these styles applied when javascript is enabled
		//$('div.navigation').css({'width' : '240px', 'float' : 'left'});
		$('div.content').css({'display': 'block'});

		// Initially set opacity on thumbs and add
		// additional styling for hover effect on thumbs
		var onMouseOutOpacity = 0.67;
		$('#thumbs ul.thumbs li').opacityrollover({
			mouseOutOpacity:   onMouseOutOpacity,
			mouseOverOpacity:  1.0,
			fadeSpeed:         'fast',
			exemptionSelector: '.selected'
		});
	
		// Initialize Advanced Galleriffic Gallery
		var gallery = $('#thumbs').galleriffic({
			delay:                     2500,
			numThumbs:                 6,
			preloadAhead:              2,
			enableTopPager:            true,
			enableBottomPager:         false,
			maxPagesToShow:            10,
			imageContainerSel:         '#slideshow',
			controlsContainerSel:      '#controls',
			captionContainerSel:       '#caption',
			loadingContainerSel:       '#loading',
			renderSSControls:          true,
			renderNavControls:         true,
			playLinkText:              'Iniciar Slideshow',
			pauseLinkText:             'Parar Slideshow',
			prevLinkText:              '&lsaquo; Anterior',
			nextLinkText:              'Pr&oacute;xima &rsaquo;',
			nextPageLinkText:          '&rsaquo;',
			prevPageLinkText:          '&lsaquo;',
			enableHistory:             false,
			autoStart:                 false,
			syncTransitions:           true,
			defaultTransitionDuration: 900,
			onSlideChange:             function(prevIndex, nextIndex) {
				// 'this' refers to the gallery, which is an extension of $('#thumbs')
				this.find('ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);
			},
			onPageTransitionOut:       function(callback) {
				this.fadeTo('fast', 0.0, callback);
			},
			onPageTransitionIn:        function() {
				this.fadeTo('fast', 1.0);
			}
		});	
	}
}


function formata(tipo,campo,tammax, teclapres) {
    var tecla=(window.event)?event.keyCode:teclapres.which;
    vr = campo.value;

    switch(tipo)
	{
    	case 'CPF':
    		if (tecla != 8)
    		{
		        vr = vr.replace( ".", "" );
		        vr = vr.replace( ".", "" );
		        vr = vr.replace( "-", "" );
		        tam = vr.length ;
		        if (tam > 3) {
		            vr = vr.substr( 0, 3 ) + '.' +  vr.substr( 3, tam );
		        }
		        if (tam > 6) {
		            vr = vr.substr( 0, 7 ) + '.' +  vr.substr( 7, tam );
		        }
		        if (tam > 9) {
		            vr = vr.substr( 0, 11 ) + '-' +  vr.substr( 11, tam );
		        }
		
		        if (tam == 3) {
		            vr = vr.substr( 0, 3 ) + '.' +  vr.substr( 3, tam );
		        }
		        if (tam == 6) {
		            vr = vr.substr( 0, 7 ) + '.' +  vr.substr( 7, tam );
		        }
		        if (tam == 9) {
		            vr = vr.substr( 0, 11 ) + '-' +  vr.substr( 11, tam );
		        }
		        campo.value = vr;
			}
			break;
			
    	case 'CEP':
	    	
			vr = vr.replace( "-", "" );
			tam = vr.length ;
			if (tam > 5) {
				vr = vr.substr( 0, 5 ) + '-' +  vr.substr( 5, tam );
			}
	        campo.value = vr;
			
			break;
    	
		case 'DATA':
	        vr = vr.replace( "/", "" );
	        vr = vr.replace( "/", "" );
	        tam = vr.length ;
	        if (tam > 2) {
	            vr = vr.substr( 0, 2 ) + '/' +  vr.substr( 2, tam );
	        }
	        if (tam > 4) {
	            vr = vr.substr( 0, 5 ) + '/' +  vr.substr( 5, tam );
	        }
	        campo.value = vr;
     	break;       
	    
		case 'TELEFONE':
			vr = campo.value;
			vr = vr.replace( " ", "" );
			vr = vr.replace( ".", "" );
			tam = vr.length;
			if (tam > 2) {
				vr = vr.substr( 0 , 2 ) + ' ' +  vr.substr( 2, tam );
			}
			if (tam > 7) {
			  	vr = vr.substr( 0 , 7 ) + '.' +  vr.substr( 7, tam );
			}
			campo.value = vr;
			break;

	    case 'VALOR':
	    
			while (vr.indexOf(".") > -1)
				vr = vr.replace('.','');
			while (vr.indexOf(" ") > -1)
				vr = vr.replace(' ','');

			vr = vr.replace( "R$", "" );
			vr = vr.replace( ",", "" );
			var centavos = vr.substring(vr.length-2)
			centavos = (centavos.length > 0)?','+centavos:centavos;
			vr = vr.substring(0,vr.length-2)

			var sinal = (vr < 0)?"-":'';
			if (sinal == '-')
				vr.replace('-','');
			for (var i = 0; i < Math.floor((vr.length-(1+i))/3); i++) {
				if (vr.substring(0,vr.length-(4*i+3)) != '-')
					vr = vr.substring(0,vr.length-(4*i+3))+'.'+vr.substring(vr.length-(4*i+3));
			}
			if (vr.indexOf('-') > -1)
				sinal = '';
			vr = sinal + vr + centavos;
			campo.value = vr;
			break;


	}
}




function somenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58) || (tecla > 94 && tecla < 106) || tecla == 0 || tecla == 8 || tecla == 9) 
		return true;
    else 
		return false;
}


function validarCPF(cpf) {
	// Verifica se o campo é nulo
	if (cpf != '') {
		cpf = cpf.replace(".","");
		cpf = cpf.replace(".","");
		cpf = cpf.replace("-","");
		if (cpf != "11111111111" && cpf != "22222222222" && cpf != "33333333333" && cpf != "44444444444" && cpf != "55555555555" && cpf != "66666666666" && cpf != "77777777777" && cpf != "88888888888" && cpf != "99999999999" && cpf != "00000000000"){
			// Aqui começa a checagem do cpf
			var POSICAO, I, SOMA, DV, DV_INFORMADO;
			var DIGITO = new Array(10);
			DV_INFORMADO = cpf.substr(9, 2); // Retira os dois últimos dígitos do número informado
			
			// Desmembra o número do cpf na array DIGITO
			for (I=0; I<=8; I++) {
			  DIGITO[I] = cpf.substr( I, 1);
			}
			
			// Calcula o valor do 10º dígito da verificação
			POSICAO = 10;
			SOMA = 0;
			   for (I=0; I<=8; I++) {
			      SOMA = SOMA + DIGITO[I] * POSICAO;
			      POSICAO = POSICAO - 1;
			   }
			DIGITO[9] = SOMA % 11;
			   if (DIGITO[9] < 2) {
			        DIGITO[9] = 0;
			}
			   else{
			       DIGITO[9] = 11 - DIGITO[9];
			}
			
			// Calcula o valor do 11º dígito da verificação
			POSICAO = 11;
			SOMA = 0;
			   for (I=0; I<=9; I++) {
			      SOMA = SOMA + DIGITO[I] * POSICAO;
			      POSICAO = POSICAO - 1;
			   }
			DIGITO[10] = SOMA % 11;
			   if (DIGITO[10] < 2) {
			        DIGITO[10] = 0;
			   }
			   else {
			        DIGITO[10] = 11 - DIGITO[10];
			   }
			
			// Verifica se os valores dos dígitos verificadores conferem
			DV = DIGITO[9] * 10 + DIGITO[10];
			   if (DV != DV_INFORMADO) {
			      alert('CPF inválido');
			      return false;
			   } else {
					return true;	
			   }
		} else {
			alert("CPF inválido");
			return false;
		}
	}
}

function setUf(uf){
	$('#uf').val(uf);
	if (uf != "")
		$.post('encontre.php?uf='+uf+'&interesse='+$('#interesse').val(), function(data) {
			$('#cod_cidade').html(data);
			$('#cod_cidade').attr("disabled", false);
		})
	else {	
		$('#cod_cidade').html("<option value=''>Escolha...</option>");
		$('#cod_cidade').attr("disabled", true);
	}
	
}

function buscaSaloesOuRepresentantes(cod_cidade) {
	if (cod_cidade != "")
	{
		$('#carregamento').show();
		$('#mapa').hide();
		$.post('encontre.php?cod_cidade='+cod_cidade+'&interesse='+$('#interesse').val(), function(data){
			$('#cont').html(data);
			$('#carregamento').hide();
					
		})
	} else {
		$('#cont').html('');
		$('#mapa').show();
	}	
}
