function comboboxProd () {
	$('#combobox-opcoes').slideToggle('slow');
}

function comboboxCont () {
	$('#combobox-opcoesCont').slideToggle('slow');
}



$(function(){
	
	$('#combobox-contato').click(comboboxCont);
	
	
	$('#cidade-encontrar').change(function(){
		link = $('#cidade-encontrar').val();
		$("#form-busca-lateral").attr('action', link);
		
	});
	
	
	$('#combobox-opcoesCont ul li a').click(function(event){

		link = $(this).attr('href');
		
		$("#area").attr('value', link);
		
		valor = $(this).text();	
		$('#combobox-contato-value').text(valor);
		
		comboboxCont();
		
        event.preventDefault(event);
        return false;
    });
	
	// Click do combobox (Mostra o combobox)
    $('#combobox-oplista').click(comboboxProd);
    
	// Efeito de hover do combobox 
    $('#combobox-opcoes li').mouseover(function(){
        $(this).css('color', '#A80203');
    }).mouseout(function(){
        $(this).css('color', '#000');
    })
	
	// bt compartilhar pagina Twitter    
    $('#bt-twitter').click(function(event){
        
		titulo = URLEncode(document.title);
		link = window.location;
		//titulo = URLEncode("Cimcal - materiais para construção");
		//link = "http://www.cimcal.com.br/";
		
		WidthO = $('body').outerWidth();
        Width = (WidthO / 2) - 400;

       myWindow = window.open("http://twitter.com/share?text=" + titulo + "&lang=pt&url=" + link, '', 'width=800,height=600,scrollbars=NO,toolbar=no,location=no,directories=no,status=no,menubar=no,top=50,left='+Width+' ');
	   
        event.preventDefault(event);
        return false;
    });
    
    
    // bt compartilhar pagina Facebook
    $('#bt-facebook').click(function(event){
        link = window.location;
		//link = "http://www.cimcal.com.br/";
		
		WidthO = $('body').outerWidth();
        Width = (WidthO / 2) - 400;

        myWindow = window.open("http://www.facebook.com/sharer.php?u=" + link, '', 'width=800,height=600,scrollbars=NO,toolbar=no,location=no,directories=no,status=no,menubar=no,top=50,left='+Width+' ');

        event.preventDefault(event);
        return false;
    });

	$("#nome-amigo").focus(function(){
    valorAntigo = $(this).attr('value');
    if ((valorAntigo == 'Nome do seu amigo') || (valorAntigo == 'Nome inválido')) {
        $('#nome-amigo').val("").css({'color':'#555555'});
	    }
	});
	
	$("#nome-amigo").blur(function(){
	    if ($('#nome-amigo').val() == '') {
	        $('#nome-amigo').val('Nome do seu amigo');
	    };
	});

	$("#email-amigo").focus(function(){
    valorAntigo = $(this).attr('value');
    if ((valorAntigo == 'Email do seu amigo') || (valorAntigo == 'E-mail inválido')) {
        $('#email-amigo').val("").css({'color':'#555555'});
	    }
	});
	
	$("#email-amigo").blur(function(){
	    if ($('#email-amigo').val() == '') {
	        $('#email-amigo').val('Email do seu amigo');
	    };
	});

	//indique
	$('#bt-indicar').click(function(event){
		nome = $('#nome-amigo').val();
	    email = $('#email-amigo').val();
		
	    error = false;
		
	    if (nome == '' || nome == 'Nome do seu amigo' || nome == 'Nome inválido'){
	         $('#nome-amigo').val("Nome inválido").css({'color' : 'red'})
	        error = true;
	    }
	
	    if (email == '' || email == 'Email do seu amigo' || email == 'E-mail inválido' || !validaEmail(email)) {
	         $('#email-amigo').val("E-mail inválido").css({'color' : 'red'})
	        error = true;
	    }
	
	    if (error == false) {
	        $.ajax({
	            type: 'post',
	            url: 'http://www.cimcal.com.br/ajax.php',
	            data: {
	                'acao': 'indique',
	                'email': email,
	                'nome': nome
	            },
	            dataType: 'json',
	            success: function(valor){
	                // cadastro corretamente
	                if (valor.error == true) {
						$('#nome-amigo').val("Nome do seu amigo");
						$('#email-amigo').val("Email do seu amigo");
						alert("Email enviado com sucesso!");
	                }
	                else{
	                    // Mostra Errors
	                    //$('#error-geral').html(valor.msg).fadeIn();
						alert("Não foi possivel enviar seu email, por favor tente novamente mais tarde!");
	                }
	            }
	        });
	    }
	    
	    
	    event.preventDefault(event);
	    return false;
	});
	
	$("#news-email").focus(function(){
    valorAntigo = $(this).attr('value');
    if ((valorAntigo == 'Digite seu e-mail') || (valorAntigo == 'E-mail inválido')) {
        $('#news-email').val("").css({'color':'#555555'});
	    }
	});
	
	$("#news-email").blur(function(){
	    if ($('#news-email').val() == '') {
	        $('#news-email').val('Digite seu e-mail');
	    };
	});
	
    //Valida cadastro a newsletter
	$('#bt-enviar-news').click(function(event){
	    email = $('#news-email').val();
	
	    error = false;
	
	    if (email == '' || email == 'Digite seu e-mail' || email == 'E-mail inválido' || !validaEmail(email)) {
	         $('#news-email').val("E-mail inválido").css({'color' : 'red'})
	        error = true;
	    }
	
	    if (error == false) {
	        $.ajax({
	            type: 'post',
	            url: 'http://www.cimcal.com.br/ajax.php',
	            data: {
	                'acao': 'neswletter',
	                'email': email
	            },
	            dataType: 'json',
	            success: function(valor){
	                // cadastro corretamente
	                if (valor.error == true) {
						alert(valor.msg);
						$('#news-email').val('Digite seu e-mail');
	                }
	                else{
						alert(valor.msg);
	                }
	            }
	        });
	    }
	    
	    
	    event.preventDefault(event);
	    return false;
	});
	
	////////////////////////////////////////////////////////////////////////////////////////
    // Enviar o Formulario de curriculo
    $('#bt-cadastrar').click(function(event){
    
        error = false;
        // valida Nome
        if ($('#tra-nome').val() == "") {
            $('#tra-nome').parents('.campo').children('.avisso').text('Por favor informe seu Nome');
            error = true;
        }
        else {
            $('#tra-nome').parents('.campo').children('.avisso').text('');
        }
		
		// Valida Email
        if ($('#tra-email').val() == "" ) {
            $('#tra-email').parents('.campo').children('.avisso').text('Por Favor informe seu E-mail');
            error = true;
        }
        else {
            $('#tra-email').parents('.campo').children('.avisso').text('');
            
            if (validaEmail($('#tra-email').val()) == false) {
                $('#tra-email').parents('.campo').children('.avisso').text('Por favor informe um E-mail valido');
                error = true;
            }
        }
        
		
		// valida assunto
        if ($('#tra-telefone').val() == "") {
            $('#tra-telefone').parents('.campo').children('.avisso').text('Por favor informe o Telefone');
            error = true;
        }
        else {
            $('#tra-telefone').parents('.campo').children('.avisso').text('');
        }
		
		if ($('#tra-assunto').val() == "") {
            $('#tra-assunto').parents('.campo').children('.avisso').text('Por favor informe o Assunto');
            error = true;
        }
        else {
            $('#tra-assunto').parents('.campo').children('.avisso').text('');
        }   

        
        // Valida mesagem		
        if ($('#tra-mensagem').val() == "") {
            $('#tra-mensagem').parents('.campo').children('.avisso').text('Por favor informe a Mensagem');
            error = true;
        }
        else {
            $('#tra-mensagem').parents('.campo').children('.avisso').text('');
        }
        
		if ($('#tra-arquivo').val() == "") {
			$('#tra-arquivo').parents('.campo').children('.avisso').text('Por favor anexe o currículo');
        	error = true;
		}else{
			$('#tra-arquivo').parents('.campo').children('.avisso').text('');
		}
		
		if ($('#tra-arquivo').val() != "") {
			
		  	var ext = $('#tra-arquivo').val().split('.').pop().toLowerCase();
		  	var allow = new Array('doc', 'pdf', 'docx');
		  	if (jQuery.inArray(ext, allow) == -1) {
		  		//alert('invalid extension!');
				
				$('#tra-arquivo').parents('.campo').children('.avisso').text('Extensão do arquivo inválida');
            	error = true;
		  	}else{
				$('#tra-arquivo').parents('.campo').children('.avisso').text('');
			}
		}
        
        if (error == true) {
            event.preventDefault(event);
        	return false;
        }

    });
	
	
	
		
	
	//efeito hover
	$("#agencia-netzee, #bt-enviar-news, #bt-indicar, .banner-list-mais a img, #bt-voltar a, #bt-cadastrar, #busca-lateral").mouseover(function(){
        $(this).fadeTo("fast", 0.80);
    });
    $("#agencia-netzee, #bt-enviar-news, #bt-indicar, .banner-list-mais a img, #bt-voltar a, #bt-cadastrar, #busca-lateral").mouseout(function(){
        $(this).fadeTo("fast", 1.00);
    });
	
	
	
	 ////////////////////////////////////////////////////////////////////////////////////////
    // Enviar o Formulario de contato 
    $('#bt-enviar-contato').click(function(event){
    
    
        error = false;
        // valida Nome
        if ($('#nome').val() == "") {
            $('#nome').parents('.campo').children('.avisso').text('Preencha o Nome');
            error = true;
        }
        else {
            $('#nome').parents('.campo').children('.avisso').text('');
        }
		
		// Valida Email
        if ($('#email').val() == "" ) {
            $('#email').parents('.campo').children('.avisso').text('Preencha o E-mail');
            error = true;
        }
        else {
            $('#email').parents('.campo').children('.avisso').text('');
            
            if (validaEmail($('#email').val()) == false) {
                $('#email').parents('.campo').children('.avisso').text('Preencha o E-mail corretamente, e-mail inválido');
                error = true;
            }
        }
        
		if ($('#area').val() == "") {
            $('#area').parents('.campo').children('.avisso').text('Selecione a Área');
            error = true;
        }
        else {
            $('#area').parents('.campo').children('.avisso').text('');
        } 
		
        // valida assunto
        if ($('#assunto').val() == "") {
            $('#assunto').parents('.campo').children('.avisso').text('Preencha o Assunto');
            error = true;
        }
        else {
            $('#assunto').parents('.campo').children('.avisso').text('');
        }  
		
		// valida telefone
        if ($('#telefone').val() == "") {
            $('#telefone').parents('.campo').children('.avisso').text('Preencha o Telefone');
            error = true;
        }
        else {
            $('#telefone').parents('.campo').children('.avisso').text('');
        }  

        
        // Valida mesagem		
        if ($('#mensagem').val() == "") {
            $('#mensagem').parents('.campo').children('.avisso').text('Preencha o Mensagem');
            error = true;
        }
        else {
            $('#mensagem').parents('.campo').children('.avisso').text('');
        }
        
        
        if (error == true) {
            return false;
        }
        else {

            dados = $('#form-contato').serialize();
            $('#carregando').html('<img src="http://www.cimcal.com.br/theme/img/carregando.gif" alt="carregando..." />').show();
            //$('#carregando').show();
            $('#form-contato fieldset').hide();
            
            $.ajax({
                header: {
                    "Content-Type": "text/html;  charset=ISO-8859-1"
                },
                type: "get",
                data: "acao=mensagem&" + dados,
                url: "http://www.cimcal.com.br/ajax.php",
                dataType: "json",
                success: function(valor){
                    
                    if (valor.mensagem == "true") {
						$('#carregando').html('<p class="verde">Mensagem enviada com sucesso, Obrigado.<br /> <a href="#" class="mostra-form" title="Exibir formulário">Exibir formulário</a></p>');
						$('#mensagem').val("");
						$('#telefone').val("");
						$('#assunto').val("");
						$('#email').val("");
						$('#nome').val("");
						$('#combobox-contato-value').text('Selecione a Área');
						$('#area').val("");
                    }
					if (valor.mensagem == "false") {
						
						$('#carregando').html('<p class="vermelho">Erro ao enviar mensagem, Por favor tente novamente.<br /> <a href="#" class="mostra-form" title="Exibir formulário">Exibir formulário</a></p>');
					}
					
                    
                    $('.mostra-form').live('click', function(event){
                        $('#form-contato fieldset').show();
                        $('#carregando').hide();
						
                        event.preventDefault(event);
                        return false;
                    });
                    
                    
                    event.preventDefault(event);
                    return false;
                }
            });
        }
        event.preventDefault(event);
        return false;
    });
	

	
	
	
	
    //////////////////////////////////////////////////////////////////////////////////////////
    // Color Box	
    $('a[rel="popup"]').colorbox({
        slideshow: true
    });
	
	$('a[rel="exeb"]').colorbox({
        rel: 'nofollow'
    });	
    
    ///////////////////////////////////////////////////////////////////////////
    // Links Externos 
    $('.externo').attr('target', '_blanck');
    
            
     ////////////////////////////////////////////////////////////////////////////////////////
    // Banner Index
    if ($('#slide-show .item').size() > 1) {
    
        var index = 0;
        var cont = 0;
        var total = $('#slide-show .item').size();
        var totalLink = total - 1;
        
        
        // Acresento os botoes de navegacao
        $('#slide-show .item').each(function(){
            cont++;
            elemento = $(this);
            
            // Atribui o id do elemento
            elemento.attr('id', 'ban-' + cont);
            
            
            $('#bt-banner').append('<a class="bt-banner" onclick="clearTimeout(bannerTempo);rotacionarBanner(this.id,' + total + ')" id="bt-' + cont + '"></a>');
            
            // Posiciono o link 
            $('#bt-' + cont).css('left', (50 + (cont * 27)));
            //totalLink = totalLink - 1;
            
            if (!(cont == total)) {
            
            }
        });
        
        rotacionarBanner("bt-1", total);
        
    }
	else {
		$('#ban-1').fadeIn();
	}        
            
            
}); //Finaliza a chamada da página

/*-------------------------------------FUNÇÕES-------------------------------------*/
// Function Rotaciona banner
function rotacionarBanner(idBanner, total){


    atualElemento = $('#' + idBanner);
    atualNumero = atualElemento.attr('id');
    atualNumero = parseInt(atualNumero.replace('bt-', ''));
    atualElemento = $('#ban-' + atualNumero);
    
    $('.bt-banner').removeClass('ativo');
    
    if (atualNumero == total) {
        mostraElemento = $('#ban-1');
        $('#bt-' + total).addClass('ativo');
        atualNumero = 1;
    }
    else {
        mostraElemento = atualElemento.next();
		
		
        $('#bt-' + ( atualNumero )).addClass('ativo');
        atualNumero++;
    }
    
    $('#slide-show .item').css('display', 'none').fadeOut('slow');
    mostraElemento.css('display', 'block').fadeIn('slow');
    
    
    
    bannerTempo = setTimeout('rotacionarBanner("bt-' + atualNumero + '", ' + total + ');', 10000)
    return true;
}



function validaEmail(mail){
    var er = RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if (er.test(mail) == false) {
        return false;
    }
    
    return true;
}
function getPageScroll(){
    var xScroll, yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
    }
    else 
        if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        }
        else 
            if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft;
            }
    arrayPageScroll = new Array(xScroll, yScroll);
    return arrayPageScroll;
};

function URLEncode(texto){
    var plaintext = retirarAcento(texto);
    
    if (encodeURIComponent()) { // OLD Browser mode
        // The Javascript escape and unescape functions do not correspond
        // with what browsers actually do...
        var SAFECHARS = "0123456789" + // Numeric
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
        "abcdefghijklmnopqrstuvwxyz" +
        "-_.!~*'()"; // RFC2396 Mark characters
        var HEX = "0123456789ABCDEF";
        
        var encoded = "";
        for (var i = 0; i < plaintext.length; i++) {
            var ch = plaintext.charAt(i);
            if (ch == " ") {
                encoded += "+"; // x-www-urlencoded, rather than %20
            }
            else 
                if (SAFECHARS.indexOf(ch) != -1) {
                    encoded += ch;
                }
                else {
                    var charCode = ch.charCodeAt(0);
                    if (charCode > 255) {
                    /*
                     alert( "Unicode Character '"
                     + ch
                     + "' cannot be encoded using standard RFC2396 encoding.\n" +
                     "(URL encoding only supports 8-bit characters.)\n" +
                     "A space (+) will be substituted." );
                     encoded += "+";
                     */
                    }
                    else {
                        encoded += "%";
                        encoded += HEX.charAt((charCode >> 4) & 0xF);
                        encoded += HEX.charAt(charCode & 0xF);
                    }
                }
        } // for
        return encoded;
    }
    else { // Modern browser mode
        return encodeURIComponent(plaintext);
    }
    
    
    return false;
};
function retirarAcento(texto){
    var varString = texto
    var stringAcentos = new String('àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ');
    var stringSemAcento = new String('aaeouaoaeioucuAAEOUAOAEIOUCU');
    
    var i = new Number();
    var j = new Number();
    var cString = new String();
    var varRes = '';
    
    for (i = 0; i < varString.length; i++) {
        cString = varString.substring(i, i + 1);
        for (j = 0; j < stringAcentos.length; j++) {
            if (stringAcentos.substring(j, j + 1) == cString) {
                cString = stringSemAcento.substring(j, j + 1);
            }
        }
        varRes += cString;
    }
    return varRes;
}


/*
 * Mapa 
 */

function loadMapa(lat, lng, map) {
   if (GBrowserIsCompatible()) {
	 
	  var map = new GMap2(document.getElementById(map));
	     
      map.setCenter(new GLatLng(lat, lng), 15);   

	  map.addControl(new GLargeMapControl());
	 
      map.setMapType(G_NORMAL_MAP);
      
      var point = new GPoint (lng, lat);
      var marker = new GMarker(point); 

      map.addOverlay(marker);
   }
}
