$(document).ready(function(){
	
	abre_segmento(1);
			
	// JCAROUSEL
	jQuery('#mycarousel1').jcarousel({scroll: 1});
			
	// Plugin de marca d'água
	watermark.init();
		
	// Links para subir
	$("a[rel*=subir]").click(function(){
		$( 'html, body' ).animate( { scrollTop: 0 }, 'slow' );
	});
	
	// IMG INPUT 
	SI.Files.stylizeAll();	
	$("#ext").change(function() {
		$("#arquivo").attr("value",$("#ext").val());
	});
	
	// SELECT CUSTOM
	$('#sample1').SelectCustomizer();
	$('#sample2').SelectCustomizer();
	
	abre_segmento(1);	
	$('input[name=segmento]').val('1');
	
	/* FLASH HOME */
	var secao = $('body').attr('id');
	if (secao == 'home'){ 
		var altura = 409;
		$('#showcase').flash( {
			src 			: base_url + 'assets/site/swf/conceitual_home.swf',
			width 		: 628,
			height 		: altura,
			wmode 		: 'transparent',
			flashvars : {
				link 		: base_url
			}
		});
	}
	else {
		$('#showcase').append('<img src="'+ base_url + 'assets/site/swf/conceitual_'+secao+'.png" alt="conceitual_'+secao+'"/>')
	}	
		
	/* SCRIPTS NON OBSTRUCTIVE  */
	$('.language a').each(function() {
		$(this).click(function() {
			$.ajax({
				type: "POST",
				url: base_url+"index.php?on=home&in=setLang",
				data: 'lang='+$(this).attr('rel'),
				success: function(msg){
					if(msg != 'ok')
						jQuery.facebox("Erro na Transmissão. Tente mais tarde!");
					else {
						window.location = document.URL;
					}
				}
			});
		});
	});
	/* SCRIPTS NON OBSTRUCTIVE  */
		
	/* SCROLL ANIMATE */
	$('.scrollPage').click(function() {
		var elementClicked = $(this).attr("href");
		var destination = $(elementClicked).offset().top;
		$("html:not(:animated),body:not(:animated)").animate({
			scrollTop: destination-20
		}, 500 );
		return false;
	});
	/* SCROLL ANIMATE */
	
	/* MOSTRA - REVELA */
	$('.tgl').css('display', 'none'),
	$('#company .boxJVA').css('display', 'block')
	$('p', '#box-toggle').click(function() {
		$(this).next().slideToggle('slow')
		.siblings('.tgl:visible').slideToggle('fast');
	
		$(this).toggleText('','')
		.siblings('p').next('.tgl:visible').prev()
		.toggleText('','')
	});
	/* MOSTRA - REVELA */
	
	//MODAL YUOTUBE E VIMEO
		$("area[rel^='prettyPhoto']").prettyPhoto();
				
		$(".gallery:first a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook'});		

		$("#custom_content a[rel^='prettyPhoto']:first").prettyPhoto({
			custom_markup: '<div id="map_canvas" style="width:260px; height:265px"></div>',
			changepicturecallback: function(){ initialize(); }
		});

		$("#custom_content a[rel^='prettyPhoto']:last").prettyPhoto({
			custom_markup: '<div id="bsap_1259344" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div><div id="bsap_1237859" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6" style="height:260px"></div><div id="bsap_1251710" class="bsarocks bsap_d49a0984d0f377271ccbf01a33f2b6d6"></div>',
			changepicturecallback: function(){ _bsap.exec(); }
		});
		
});

function abre_segmento(id_segmento){
		
		var id_serv = $('input[name="obra"]').size() ? $('input[name="obra"]').val() : '';
		
		$.ajax({
			type		: "POST",
			url			: $('base').attr('href') + 'index.php?on=estrutura&in=ajax',
			data		: 'id_segmento='+id_segmento+'&id_serv='+id_serv,			
			success	: function(msg){
				if(msg == '')
					alert("Erro!");
				else {
					$('#resultado').html(msg);
					$('#sample2').SelectCustomizer();
					jQuery('#mycarousel1').jcarousel({scroll: 1});
				}
			}
		});
	
}

function voltar(){
	window.history.back(0);
}

function cadastra_news(url){
	var msg = "";
	if($('#nomeNews').val() == "Nome" || $('#nomeNews').val() == ""){
  	msg += "Preencha seu nome\n";
  }
  if($('#emailNews').val() == "" || $('#emailNews').val() == "E-mail"){
  	msg += "E-mail não preenchido.\n";
  } else if(!valEmail.test($('#emailNews').val())){
  	msg += "E-mail inválido.\n";
  }
  if(msg != ""){
  	alert(msg);
  } else {
  	$.ajax({
    	type: 'POST',
      url: url,
      data: "nome=" + $('#nomeNews').val() + "&email=" + $('#emailNews').val(),
      success: function(msg){
      	alert(msg);
      },
      error: function(msg){
      	alert("Erro ao cadastrar, tente novamente mais tarde!");
      }
    });
  }
}

function str_replace(haystack, needle, replacement) {
  var temp = haystack.split(needle);
  return temp.join(replacement);
}

function disabledFormButton(ct) {
  $(ct).attr('disabled','disabled').css('cursor','default').css('filter','alpha(opacity=40)').css('-moz-opacity','0.4').css('opacity','0.4');
}

function enabledFormButton(ct) {
  $(ct).attr('disabled','').css('cursor','pointer').css('filter','alpha(opacity=100)').css('-moz-opacity','1').css('opacity','1');
}

function hideError() {
	$("#retorno_erro").animate({
  	left: '+=50',
    height: 'toggle'
  }, 500, 
	function() {
  	$("#retorno_erro").html('');
  	$("#retorno_erro").css('display','block');
  });
  window.clearTimeout(timeoutID);
}

function topo() 	 {
  window.location = document.URL+'#';
}

function gotoAnchor(value) {
  var elementClicked = '#'+value;
  var destination = $(elementClicked).offset().top;
  $("html:not(:animated),body:not(:animated)").animate({
  	scrollTop: destination-20
  }, 500 );
}

var valEmail = /^[\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}\])$/;

function validaContact(){
  msg = "";
  if($("#nome").val() == "" || $("#nome").val() == "Nome"){
  	msg += "Nome não preenchido.\n";
  }
  if($("#email").val() == "" || $("#email").val() == "E-mail"){
  	msg += "E-mail não preenchido.\n";
  } else if(!valEmail.test($("#email").val())){
  	msg += "E-mail inválido.\n";
  }
  if($("#telefone").val() == "" || $("#telefone").val() == "Telefone"){
  	msg += "Telefone não preenchido.\n";
  }
	if($("#estado").val() == "" || $("#estado").val() == "Estado"){
		msg += "Estado não preenchido.\n";
	}
	if($("#cidade").val() == "" || $("#cidade").val() == "Cidade"){
		msg += "Cidade não preenchido.\n";
	}
	if($("#area").val() == "" || $("#area").val() == "Área de interesse"){
		msg += "Sua área de interesse não preenchida.\n";
	}
  if($("#empresa").val() == "" || $("#empresa").val() == "Empresa"){
  	msg += "Empresa não preenchido.\n";
  }
  if($("#message").val() == "" || $("#message").val() == "Descreva sua necessidade"){
  	msg += "Sua mensagem não foi preenchida.\n";
  }
  if(msg != ""){
  	msg = "Os seguintes campos são obrigatórios:\n\n" + msg;
    alert(msg);
    return false;
  } else {
  	return true;
  }
}

function coloca_mascara(objCampo, mascara) {
	switch(mascara) {
		//000.000.000-00
		case 'cpf':
		objCampo.value = somente_numero(objCampo.value);
		pri = objCampo.value.substring(0,3);
		seg = objCampo.value.substring(3,6);
		ter = objCampo.value.substring(6,9);
		qua = objCampo.value.substring(9,11);

		objCampo.value = pri+
		((seg!='') ? '.'+seg : '')+
		((ter!='') ? '.'+ter : '')+
		((qua!='') ? '-'+qua : '');
		break;

		//00.000.000/0000-00
		case 'cnpj':
		objCampo.value = somente_numero(objCampo.value);
		pri = objCampo.value.substring(0,2);
		seg = objCampo.value.substring(2,5);
		ter = objCampo.value.substring(5,8);
		qua = objCampo.value.substring(8,12);
		qui = objCampo.value.substring(12,14);

		objCampo.value = pri+
		((seg!='') ? '.'+seg : '')+
		((ter!='') ? '.'+ter : '')+
		((qua!='') ? '/'+qua : '')+
		((qui!='') ? '-'+qui : '');
		break;

		//(00) 0000-0000
		case 'telefone':
		objCampo.value = somente_numero(objCampo.value);

		pri = objCampo.value.substring(0,2);
		seg = objCampo.value.substring(2,6);
		ter = objCampo.value.substring(6,10);

		objCampo.value = ((pri!='') ? pri+'-' : '')+
		((seg!='') ? seg : '')+
		((ter!='') ? '.'+ter : '');
		break;

		//00000-000
		case 'cep':
		objCampo.value = somente_numero(objCampo.value);

		pri = objCampo.value.substring(0,5);
		seg = objCampo.value.substring(5,8);

		objCampo.value = pri+
		((seg!='') ? '-'+seg : '');
		break;

		//00/00/0000
		case 'data':
		objCampo.value = somente_numero(objCampo.value);

		pri = objCampo.value.substring(0,2);
		seg = objCampo.value.substring(2,4);
		ter = objCampo.value.substring(4,8);

		objCampo.value = pri+
		((seg!='') ? '/'+seg : '')+
		((ter!='') ? '/'+ter : '')
		break;

		//00/0000
		case 'venc_cartao':
		objCampo.value = somente_numero(objCampo.value);

		pri = objCampo.value.substring(0,2);
		seg = objCampo.value.substring(2,6);

		objCampo.value = pri+
		((seg!='') ? '/'+seg : '')
		break;

		//0000 0000 0000 0000
		case 'cartao':
		objCampo.value = somente_numero(objCampo.value);

		pri = objCampo.value.substring(0,4);
		seg = objCampo.value.substring(4,8);
		ter = objCampo.value.substring(8,12);
		qua = objCampo.value.substring(12,16);

		objCampo.value = pri+
		((seg!='') ? '-'+seg : '')+
		((ter!='') ? '-'+ter : '')+
		((qua!='') ? '-'+qua : '');
		break;

		case 'numero':
		objCampo.value = somente_numero(objCampo.value);
		break;

		case 'letra':
		objCampo.value = somente_letras(objCampo.value);
		break;

		//1.000.000.000.000,00
		case 'moeda':
		len = 20
		cur = objCampo
		n   = '0123456789';
		d   = objCampo.value;
		l   = d.length;
		r   = '';

		if ( l > 0 ) {
			z = d.substr(0,l);
			s = '';
			a = 0;

			for ( i=0; i < l; i++ ) {
				c = d.charAt(i);
				if ( n.indexOf(c) > a ) {
					a  = -1;
					s += c;
				};
			};
			l = s.length;
			t = len - 1;
			if ( l > t ) {
				l = t;
				s = s.substr(0,t);
			}
			if ( l > 2 ) {
				r = s.substr(0,l-2)+','+s.substr(l-2,2);
			}
			else {
				if ( l == 2 ) {
					r='0,'+s;
				}
				else {
					if ( l == 1 ) {
						r = '0,0'+s;
					}
				}
			}
			if ( r == '' ) {
				r = '0,00';
			}
			else {
				l=r.length;
				if (l > 6) {
					j  = l%3;
					w  = r.substr(0,j);
					wa = r.substr(j,l-j-6);
					wb = r.substr(l-6,6);
					if ( j > 0 ) {
						w+='.';
					};
					k = (l-j)/3-2;
					for ( i=0; i < k; i++ ) {
						w += wa.substr(i*3,3)+'.';
					};
					r = w + wb;
				}
			}
		}
		if ( cur.value.length == len || cur.value.length > len ) {
			cur.value = cur.value.substring(0 ,len);
			return false;
		}
		else {
			if ( r.length <= len )
			{
				cur.value = r;
			}
			else {
				cur.value = z;
			};
		}
		break;
	}
}

function somente_numero(numero){
	var validos = "0123456789";
	var numero_ok = '';
	for(i = 0; i < numero.length; i++){
		if(validos.indexOf(numero.substr(i,1)) != -1)	{
			numero_ok += numero.substr(i,1);
		}
	}
	return numero_ok;
}

function somente_letras(letra) {
	var validos  = "_abcdefghijklmnopkrstuvxzywABCDEFGHIJKLMNOPKRSTUVXZYW";
	var letra_ok = '';

	for(i = 0; i < letra.length; i++)	{
		if(validos.indexOf(letra.substr(i,1)) != -1){
			letra_ok += letra.substr(i,1);
		}
	}
	return letra_ok;
}
