var site = $('meta[name=root]').attr('content');
var page = $('meta[name=page]').attr('content');
var param = $('meta[name=param]').attr('content');
var url = $('meta[name=url]').attr('content');
var cords = $('meta[name=cords]').attr('content');

$(document).ready( function() {

   menuNovo();
   segueMenu();
   horizontalClientes();   
  
   menuLista();
   
   maskNews();
   
   restritaGaleria();
   
   if (page == 'home') {
      setFlash();
      htmlBanner1();
      htmlBanner2();
   }

   if (page == 'contato') {
      mapa();
      enviaContato();
      $(".jqtransform").jqTransform();
   }

   enviaNews();
   
   if (page == 'produtos') {
      flashImg();      
   }
   
   menuInterna();
   
   if (page == 'obras') {
      //controlaMenu();
   }
   
   if (page == 'informativos' || page == 'diferencial' || page == 'obras') {
      galeria();
   }
   
   if (page == 'empresa') {
      $('.empresa-fotos a').fancybox();
   }
   
   $('.images-restrita a').fancybox();
   
   if (page == 'trabalhe') {
	  controlaTipo();
	  duplicaFormacao();
	  duplicaExperiencia();
   }
   
   enviaTrocaSenha();

});

function mapa() {
   if (document.getElementById('gmaps')) {
      if (typeof google == 'undefined')
         return;
      var latlng = cords.split(',');

      latlng = new google.maps.LatLng(latlng[0],latlng[1]);

      var mapDiv = document.getElementById('gmaps');
      var map = new google.maps.Map(mapDiv, {
         center: latlng,
         zoom: 14,
         mapTypeId: google.maps.MapTypeId.ROADMAP,
         disableDefaultUI: true,
         navigationControl: true,
         navigationControlOptions: {
            position: google.maps.ControlPosition.LEFT,
            style: google.maps.NavigationControlStyle.SMALL
         }
      });

      var marker = new google.maps.Marker({
         position: latlng,
         map: map,
         icon:"site/images/marker.png",
         title: "Viero"
      });
   }
}

function setFlash() {
   addFlash(site + "/site/files/bin/banner.swf", "982", "300", "flashContent", "transparent", "10", {});
}

function get_url() {
  return site;
}

function addFlash(file, width, height, id, wmode, version,flashvars) {
   var params = {
      'wmode':wmode
   };
   var attributes = {
      'id':id
   };
   swfobject.embedSWF(file, id, width, height, version,"site/js/expressInstall.swf", flashvars, params, attributes)
}

function segueMenu() {     
   $(".menu-item-hover").click(
      function() {
         var link = $(this).find("a").attr("href");        
         window.location = link;        
         return false;
      }
   );   
}

function menuNovo() {
   var posIni = "-75px";
   var posFimTitle = "25px";
   var posFimSubtitle = "40px";
   var posFimIcon = "68px";

   var selecionado;   
   
   $(".menu-item-hover").each( function() {      
      selecionado = $(this).find('a').attr("name");    
      if (selecionado == page) {
         $(this).find('.menu-item').css({
            'background':'none'
         });
      }
   });
      
   $(".menu-item-hover").hover( function() {
      
      selecionado = $(this).find('a').attr("name");

      if (selecionado != page) {

         if(jQuery.browser.msie) {
            if(jQuery.browser.version < 9) {
               $(this).find(".menu-item").stop().css({
                  'display':'none'
               },100);
            } else {
               $(this).find(".menu-item").stop().animate({
                  'opacity':'0'
               },100);
            }
         } else {
            $(this).find(".menu-item").stop().animate({
               'opacity':'0'
            },100);
         }
   
         $(this).find('h3').stop().animate({
            'top':posFimTitle
         },900,'easeOutExpo');
   
         $(this).find('h4').stop().animate({
            'top':posFimSubtitle
         },600,'easeOutExpo');
   
         $(this).find('.menu-item-icon-hover').stop().animate({
            'top':posFimIcon
         },400,'easeOutExpo');
         
      }

   }, function() {
      
      selecionado = $(this).find('a').attr("name");

      if (selecionado != page) {

         if(jQuery.browser.msie) {
            if(jQuery.browser.version < 9) {
               $(this).find(".menu-item").stop().css({
                  'display':'block'
               });
            } else {
               $(this).find(".menu-item").stop().animate({
                  'opacity':'1'
               },1000);
            }
         } else {
            $(this).find(".menu-item").stop().animate({
               'opacity':'1'
            },1000);
         }
   
         $(this).find('h3').stop().animate({
            'top':posIni
         },900,'easeOutExpo');
   
         $(this).find('h4').stop().animate({
            'top':posIni
         },600,'easeOutExpo');
   
         $(this).find('.menu-item-icon-hover').stop().animate({
            'top':posIni
         },400,'easeOutExpo');
         
      }

   });
}

function horizontalClientes() {

   $('#galeria-clientes').horizontalmove({
      page:  0,
      time:  1000,
      ease:  'easeInOutExpo',
      main:  '.horizontalmove-main:first',
      mask:  '.horizontalmove-mask:first',
      left:  '.horizontalmove-left',
      right: '.horizontalmove-right',
      item:  '.horizontalmove-item',
      onComplete: function(data) {
         //data = true
      },
      callBack: function(page) {
         currentPage(page);
      }
   });

   $('#pagination li a').click( function() {
      var page = $(this).attr('href');
      instance.setPage(page);
      return false;
   });
}

function horizontalGaleria() {

   $('#galeria').horizontalmove({
      page:  0,
      time:  1000,
      
      ease:  'easeInOutExpo',
      main:  '.horizontalmove2-main:first',
      mask:  '.horizontalmove2-mask:first',
      left:  '.horizontalmove2-left',
      right: '.horizontalmove2-right',
      item:  '.horizontalmove2-item',
      onComplete: function(data) {
         //data = true
      }
   });
}

function currentPage(page) {
   $('#pagina-atual').html((parseInt(page) + 1) + "");
}

function menuLista() {
   var selecionado;

   $('.menu-lista ul li').each( function() {
      selecionado = $(this).find('a').attr("name");
      if (selecionado == param) {
         $(this).find('a').css({
            "font-weight": "bold",
            "backgroundPosition": "-160px 0"
         });
      } else {
         $(this).find('a').css({
            "backgroundPosition": "0 0"
         });
      }
   });
   
   var anim = $('.menu-lista ul li').first().find('a').attr("name");
   if (param == 0) {
      $('.menu-lista ul li').first().find('a').css({
         "font-weight": "bold",
         "backgroundPosition": "-160px 0"
      });   
   }
   
   $('.menu-lista li a').hover( function() {
      selecionado = $(this).attr("name");
      if (selecionado != param) {
         if ($(this).attr("name") != anim || param != 0) {
            $(this).find('a').stop(true).animate({
               color:'white'
            });
            $(this).stop().animate({
               backgroundPosition:"-160px 0"
            },700,'easeOutExpo')
         }
      }
   }, function() {
      selecionado = $(this).attr("name");
      if (selecionado != param) {
         if ($(this).attr("name") != anim || param != 0) {
            $(this).stop().animate({
               backgroundPosition:"0 0"
            },700,'easeOutExpo')
         }
      }
   }
   );

}

function enviaContato() {

   $("#form-contato").submit( function() {
      return false;
   });
   var options = {
      beforeSubmit:  showRequest,
      success:       showResponse
   };

   function showRequest(formData, jqForm, options) {

   }

   function showResponse(data) {
      if($.trim(data) == "true") {
         $("#erro-form").html("Enviado com sucesso.");

         $("#form-contato").clearForm();

         setTimeout( function() {
            $("#erro-form").html("");
         },5000);
      } else {

         $("#erro-form").html("Erro desconhecido.");

         setTimeout( function() {
            $("#erro-form").html("");
         },5000);
      }
   }

   $("#form-contato").validate({
      rules: {
         'nome': {
            required:true
         },
         'email': {
            required:true,
            email:true
         },
         'fone': {
            required:true
         },
         'departamento': {
            required:true
         },
         'assunto': {
            required:true
         },
         'msg': {
            required:true
         }
      },
      messages: {
         nome: {
            required:"Nome :: Obrigatório<br/>"
         },
         email: {
            required:"E-mail :: Obrigatório<br/>",
            email:"E-mail :: Inválido<br/>"
         },
         fone: {
            required:"Telefone :: Obrigatório<br />"
         },
         departamento: {
            required:"Departamento :: Obrigatório<br />"
         },
         assunto: {
            required:"Assunto :: Obrigatório<br />"
         },
         msg: {
            required:"Mensagem :: Obrigatório<br />"
         }
      },
      submitHandler: function() {
         $("#erro-form").html("Aguarde um momento . . .");
         $("#form-contato").ajaxSubmit(options);
      },
      errorLabelContainer: $("#erro-contato-form")
   });
}

function enviaNews() {

   $("#form-news").submit( function() {
      return false;
   });
   var options = {
      beforeSubmit:  showRequest,
      success:       showResponse
   };

   function showRequest(formData, jqForm, options) {

   }

   function showResponse(data) {
      if($.trim(data) == "true") {
         $("#erro-news").html("Enviado com sucesso.");

         $("#form-news").clearForm();

         setTimeout( function() {
            $("#erro-news").html("");
         },2000);
      } else {

         $("#erro-news").html("Erro desconhecido.");

         setTimeout( function() {
            $("#erro-news").html("");
         },2000);
      }
   }

   $("#form-news").validate({
      rules: {
         'nome_news': {
            required:true
         },
         'email_news': {
            required:true,
            email:true
         }
      },
      messages: {
         nome_news: {
            required:"Nome :: Obrigatório<br />"
         },
         email_news: {
            required:"E-mail :: Obrigatório<br />",
            email:"E-mail :: Inválido<br />"
         }
      },
      submitHandler: function() {
         $("#erro-news").html("Aguarde um momento . . .");
         $("#form-news").ajaxSubmit(options);
      },
      errorLabelContainer: $("#erro-form-news")
   });
}

function flashImg() {
   var flash;
   var divId;
   
   $('.flash').each(function(){
      
      flash = $(this).find('a').attr("href");
      divId = $(this).attr("id");

      addFlash(flash, "500", "220", divId , "transparent", "10", {});
            
   });
}

function menuInterna() {
   $(".pagina-topo div").click(
      function() {
         var link = $(this).find("a").attr("href");        
         window.location = link;        
         return false;
      }
   );    
}

function controlaMenu() {
   var size;
   var cont = 0;
   if (param == 0) {
      $(".menu-lista ul li").each(function() {
         cont++;
         if (cont > 10) {
            $(this).css({
               'display' : 'none'
            });
         }
      });
   } else {
      $("#mais-obras").css({
         'display' : 'none'
      });
   }

   $("#mais-obras").click(function() {
      $(".menu-lista ul li").each(function() {
         $(this).css({
            'display' : 'block'
         });
      });
      $(this).css({
         'display' : 'none'
      });
   });
      
}

function abreFoto(target){
   try{
      var temp = $(target).attr('data-foto');

      var img = $('<img id="jquery-big" src="' + temp + '" style="display:none;"/>');

      $('.main-img').addClass('load');   

      img.load(
          function(){
              $(this).fadeIn();
          }
      );
      
      $('.main-img').html('').append(img);
            
   }catch(e){
      //console.log(e);
   }
   return false;
}

function galeria() {
   
   $(".faixa-ver-fotos a, .diferencial-img").fancybox({
      'onStart'           : function() {$.scrollTo( 30, 700 );},
      'onComplete'        : function() {
          horizontalGaleria();
          goturbo();
      },
      'height'          : '100%' ,
      'transitionIn'    : 'fade',
      'transitionOut'   : 'fade',
      'scrolling'       : 'no',
      'padding'         : '0',
      'centerOnScroll'  : true,
      'type'            : 'ajax'
  });   
  
}

function goturbo() {   
   $('.horizontalmove2-item a').click(function(){
      abreFoto(this);
      return false;
   });
}

function htmlBanner1() {
   
   var total = $('.box-quadrado-azul-claro').length;
   var banner = [];   
   var i = 0;
   var cont = 1;
   
   $('.box-quadrado-azul-claro').each(function() {
      if (i != 0) {
         $(this).hide();
      }
      banner[i++] = $(this);
   });
   
   setInterval(function() {    
      if (cont > 0) {
         banner[cont-1].fadeOut('slow');
      } else {
         banner[total-1].fadeOut('slow');
      }
      banner[cont].fadeIn('slow');
      cont++;  
      if (cont == total) {
         cont = 0;
      }
   }, 5000);
   
   $('.box-quadrado-azul-claro').click(
      function() {
         var link = site + '/obras';        
         window.location = link;        
         return false;
      }
   ); 
      
}

function htmlBanner2() {
   
   var total = $('.box-quadrado-azul-escuro').length;
   var banner = [];   
   var i = 0;
   var cont = 1;
   
   $('.box-quadrado-azul-escuro').each(function() {
      if (i != 0) {
         $(this).hide();
      }
      banner[i++] = $(this);
   });
   
   setInterval(function() {    
      if (cont > 0) {
         banner[cont-1].fadeOut('slow');
      } else {
         banner[total-1].fadeOut('slow');
      }
      banner[cont].fadeIn('slow');
      cont++;  
      if (cont == total) {
         cont = 0;
      }
   }, 5000);
   
   $('.box-quadrado-azul-escuro').click(
      function() {
         var link = site + '/produtos';        
         window.location = link;        
         return false;
      }
   ); 
      
}  

function controlaTipo(){	
	verificaTrabalhe();
	
	$('input[name=tipo]').change(function() {
		var tipo = $('input[name=tipo]:checked').val();
		if (tipo == 'formulario') {
			window.location.href=site + "/trabalhe/1";
		} else {
			window.location.href=site + "/trabalhe/2";
		}		
		verificaTrabalhe();
		$("#erro-trab").html("");
		$("#erro-trab-form").html("");
	});	
}

function duplicaFormacao() {
	var contFormacao = 2;
	
	$('#add-formacao').click(function(){
		
		var formacao = "<h1>FORMAÇÃO " + contFormacao + "</h1>" +            
		           "<p class='trabalhe-grau'>" +
		               "<label class='grau'>GRAU DE INSTRUÇÃO</label>" +
		               "<input type='text' name='grau" + contFormacao + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-curso'>" +
		               "<label class='curso'>CURSO</label>" +
		               "<input type='text' name='curso" + contFormacao + "'/>" +
		            "</p>" +            
		            "<p class='trabalhe-instituicao'>" +
		               "<label class='instituicao'>INSTITUIÇÃO</label>" +
		               "<input type='text' name='instituicao" + contFormacao + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-conclusao'>" +
		               "<label class='conclusao'>DATA DE CONCLUSÃO</label>" +
		               "<input type='text' name='conclusao" + contFormacao + "'/>" +
		            "</p>" +
		            "<div class='both'></div>";
		
		$('#formacao').append(formacao);
		contFormacao++;
		$('#qtdFormacao').val(parseInt($('#qtdFormacao').val()) + 1);
	});
}

function duplicaExperiencia() {
	var contExperiencia = 2;
	
	$('#add-experiencia').click(function(){
		
		var experiencia = "<h1>EXPERIÊNCIA PROFISSIONAL " + contExperiencia + "</h1>" +		            
		            "<p class='trabalhe-exp1'>" +
		               "<label class='empresa'>EMPRESA</label>" +
		               "<input type='text' name='empresa" + contExperiencia + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-exp2'>" +
		               "<label class='telEmpresa'>TELEFONE</label>" +
		               "<input type='text' name='telEmpresa" + contExperiencia + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-exp1'>" +
		               "<label class='cargo'>CARGO</label>" +
		               "<input type='text' name='cargo" + contExperiencia + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-exp2'>" +
		               "<label class='remuneracao'>ÚLTIMA REMUNERAÇÃO</label>" +
		               "<input type='text' name='remuneracao" + contExperiencia + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-exp2-data'>" +
		               "<label class='entrada'>DATA DE ENTRADA</label>" +
		               "<input type='text' name='entrada" + contExperiencia + "'/>" +
		            "</p>" +
		            "<p class='trabalhe-exp2-data'>" +
		               "<label class='saida'>DATA DE SAÍDA</label>" +
		               "<input type='text' name='saida" + contExperiencia + "'/>" +
		            "</p>" +
		            "<div class='both'></div>" +
		            "<p class='trabalhe-atividades'>" +
		                "<label for='atividades'>ATIVIDADES REALIZADAS</label>" +
		               	"<textarea cols='' rows='' name='atividades" + contExperiencia + "'/></textarea>" +
	            	"</p>";
		            		
		$('#experiencia').append(experiencia);
		contExperiencia++;
		$('#qtdExperiencia').val(parseInt($('#qtdExperiencia').val()) + 1);
	});
}

function verificaTrabalhe() {	
	
	$("input[name=cpf]").mask("999.999.999-99");
	$("input[name=nascimento]").mask("99/99/9999");
	$("input[name=conclusao1]").mask("99/99/9999");
	$("input[name=entrada1]").mask("99/99/9999");
	$("input[name=saida1]").mask("99/99/9999");
	
   $("#form-trabalhe").submit( function() {
      return false;
   });
   var options = {
      beforeSubmit:  showRequest,
      success:       showResponse
   };

   function showRequest(formData, jqForm, options) {

   }

   function showResponse(data) {
      if($.trim(data) == "true") {
         $("#erro-trab").html("Enviado com sucesso.");

         $("#form-trabalhe").clearForm();

         setTimeout( function() {
            $("#erro-trab").html("");
         },5000);
      } else {

         $("#erro-trab").html("Erro desconhecido.");

         setTimeout( function() {
            $("#erro-trab").html("");
         },5000);
      }
   }
   
   var tipo = $('input[name=tipo]:checked').val();
   
   $("#form-trabalhe").validate({
      rules: {
      	 'emailAnexo': {
            required:true,
            email:true
         },
         'curriculo': {
            required:true
         },
         'nome': {
            required:true
         },
         'email': {
            required:true,
            email:true
         },
         'fone': {
            required:true
         },
         'cpf': {
         	required:true,
         	cpf:true
         },
         'sexo': {
         	required:true
         },
         'civil': {
         	required:true
         },
         'filhos': {
         	required:true
         },
         'nascimento': {
         	required:true
         },
         'endereco': {
         	required:true
         },
         'bairro': {
         	required:true
         },
         'cidade': {
         	required:true
         },
         'area': {
         	required:true
         },
         'grau': {
         	required:true
         },
         'curso': {
         	required:true
         },
         'instituicao': {
         	required:true
         },
         'conclusao': {
         	required:true
         },
         'informatica': {
         	required:true
         },
         'ingles': {
         	required:true
         },
         'espanhol': {
         	required:true
         }
      },
      messages: {
      	emailAnexo: {
            required:"E-mail :: Obrigatório<br />",
            email:"E-mail :: Inválido<br />"
         },
         curriculo: {
            required:"Currículo :: Obrigatório<br />"
         },
         nome: {
            required:"Nome :: Obrigatório<br />"
         },
         email: {
            required:"E-mail :: Obrigatório<br />",
            email:"E-mail :: Inválido<br />"
         },
         fone: {
            required:"Telefone :: Obrigatório<br />"
         },
         cpf: {
            required:"CPF :: Obrigatório<br />"
         },
         sexo: {
         	required:"Sexo :: Obrigatório<br />"
         },
         civil: {
         	required:"Estado Civil :: Obrigatório<br />"
         },
         filhos: {
         	required:"Filhos :: Obrigatório<br />"
         },
         nascimento: {
         	required:"Nascimento :: Obrigatório<br />"
         },
         endereco: {
         	required:"Endereço :: Obrigatório<br />"
         },
         bairro: {
         	required:"Bairro :: Obrigatório<br />"
         },
         cidade: {
         	required:"Cidade :: Obrigatório<br />"
         },
         area: {
         	required:"Área de Interesse :: Obrigatório<br />"
         },
         grau: {
         	required:"Grau :: Obrigatório<br />"
         },
         curso: {
         	required:"Curso :: Obrigatório<br />"
         },
         instituicao: {
         	required:"Instituição :: Obrigatório<br />"
         },
         conclusao: {
         	required:"Data de Conclusão :: Obrigatório<br />"
         },
         informatica: {
         	required:"Conhecimentos em Informática :: Obrigatório<br />"
         },
         ingles: {
         	required:"Inglês :: Obrigatório<br />"
         },
         espanhol: {
         	required:"Espanhol :: Obrigatório<br />"
         }
      },
      submitHandler: function() {
         $("#erro-trab").html("Aguarde um momento . . .");
         $("#form-trabalhe").ajaxSubmit(options);
      },
      errorLabelContainer: $("#erro-trab-form")
   });
   			 
}

jQuery.validator.addMethod("cpf", function(value, element) {
	value = value.replace('.','');
	value = value.replace('.','');
	cpf = value.replace('-','');
	while(cpf.length < 11) cpf = "0"+ cpf;
	var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
	return true;
}, "CPF :: Inválido.<br>");

function maskNews() {
	var anterior = "";
	
	$("#form-news input, #form-area input").focus(function() {
		if ($(this).val() == $(this).attr("title")) {
			anterior = $(this).val();
			$(this).val("");
		}		
	});
	$("#form-news input, #form-area input").blur(function() {
		if ($(this).val() == "") {
			$(this).val(anterior);
		}	
	});
}

function restritaGaleria() {
	
    $('.intranet-lista div').each(function(){
      //$(this).css('height', $(this).height());
    }).hide();
    $('.intranet-lista li').click(function(){
      $(this).next('li').find('div').slideToggle();
    });

    if (window.location.hash) {
      try {
        $(window.location.hash).next('div').show();
      }catch(e){}
    }
	
}

function enviaTrocaSenha() {
	
   $("#form-alterar").submit( function() {
      return false;
   });
   var options = {
      beforeSubmit:  showRequest,
      success:       showResponse
   };

   function showRequest(formData, jqForm, options) {

   }

   function showResponse(data) {
      if($.trim(data) == "true") {
      	
         $("#erro-alterar").html("Dados alterados com sucesso.");

         $("#form-alterar").clearForm();

         setTimeout( function() {
            $("#erro-alterar").html("");
         },5000);
         
      } else if ($.trim(data) == "incorreto") {
      	
      	 $("#erro-alterar").html("Dados incorretos.");
      	 
      	 setTimeout( function() {
            $("#erro-alterar").html("");
         },2000);
         
      } else {

         $("#erro-alterar").html("Erro desconhecido.");

         setTimeout( function() {
            $("#erro-alterar").html("");
         },5000);
         
      }
   }

   $("#form-alterar").validate({
      rules: {
         'login': {
         	required:true,
            email:true
         },
         'atual': {
         	required:true
         },
         'nova1': {
            required:true
         },
         'nova2': {
            required:true
         }
      },
      messages: {
         login: {
            required:"E-mail :: Obrigatório<br />",
            email:"E-mail :: Inválido<br />"
         },
         atual: {
         	required:"Senha Atual :: Obrigatório<br />"
         },
         nova1: {
         	required:"Nova Senha :: Obrigatório<br />"
         }, 
         nova2: {
         	required:"Nova Senha :: Obrigatório<br />"
         }
      },
      submitHandler: function() {
         $("#erro-alterar").html("Aguarde um momento . . .");
         $("#form-alterar").ajaxSubmit(options);
      },
      errorLabelContainer: $("#erro-form-alterar")
   });
	
}

