var validate = false;
var base_url = $('base').attr('href');

var old_img;

$(document).ready(function(){
	$('.galeria_1').jcarousel();
	$('.galeria_1 li a').click(function() {
		$('.galeria_1 li a').removeClass('selected');
		$(this).addClass('selected');
		$('#contentFotosInterna img').attr('src', $(this).attr('href'));
		atualiza_prev_next();
		return false;
	});
	
	$('#contentFotosInterna #prev').click(function() {
		var selected = $('.galeria_1 li a.selected');
		var index = $('.galeria_1 li a').index(selected);
		$('.galeria_1 li a:eq('+(index-1)+')').click();
	});

	$('#contentFotosInterna #next').click(function() {
		var selected = $('.galeria_1 li a.selected');
		var index = $('.galeria_1 li a').index(selected);
		$('.galeria_1 li a:eq('+(index+1)+')').click();
	});
	
	atualiza_prev_next();
	validation_start();
});

function Numero(e)
{
  navegador = /msie/i.test(navigator.userAgent);
  if (navegador)
   var  tecla = event.keyCode;
  else
   var tecla = e.which;

  if(tecla > 47 && tecla < 58) // numeros de 0 a 9
	return true;
  else
	{
	  if (tecla != 8) // backspace
		return false;
	  else
		return true;
	}
}

function atualiza_prev_next() {
	var length = $('.galeria_1 li a').length;
	var selected = $('.galeria_1 li a.selected');
	var index = $('.galeria_1 li a').index(selected);
	
	if (index == 0)
		$('#contentFotosInterna #prev').css('visibility', 'hidden');
	else
		$('#contentFotosInterna #prev').css('visibility', '');
		
	if (index >= (length - 1))
		$('#contentFotosInterna #next').css('visibility', 'hidden');
	else
		$('#contentFotosInterna #next').css('visibility', '');
}

function validate_envia_comentario() {
	$('#form_comentario').submit(function() {
		elemento = $('#carregando_envia_comentario');
		if ( ! elemento.is(':visible')) {

			// Validação
			clear($(this));

			var nome = $(this).find('input[name="nome"]');
			var email = $(this).find('input[name="email"]');
			var texto = $(this).find('textarea[name="texto"]');

			if(nome.val() == ''){
				error(nome);
			}

			if(email.val() == ''){
				error(email);
			}
			else if ( ! checkMail(email.val())) {
				error(email);
			}

			if(texto.val() == ''){
				error(texto);
			}

			if (validate) {
				elemento.show();

				$.ajax({
					type: "POST",
					dataType: 'text',
					data: $('#form_comentario').serialize(),
					url: base_url + 'blog/home/grava_comentario',
					cache: false,
					success: function(resp) {
						$('.enviandoForm').show();
						elemento.hide();
					},
					error: function() {
						elemento.hide();
					}
				});

				$('#form_comentario').find('input:not([type="hidden"]), textarea').val('');
			}

		}
		return false;
	});
}

function validate_cadastro(){
	$("#frm-cadastro").submit(function(){
		//valida_cpf();
		clear($(this));
		var msg = [];
		var cpf = $('#cpf').val();
		elemento = $('#carregando_envia_cadastro');
		if ( ! elemento.is(':visible')) {
			$('#msgSucesso').hide();

			if($('#nome').val() == ''){
				error('#nome');
				msg.push('Informe o seu nome.');
			}
			if($('#email').val() == ''){
				error('#email');
				msg.push('Informe o seu e-mail.');
			}
			else if(!checkMail($('#email').val())){
				error('#email');
				msg.push('Informe um e-mail válido.');
			}

			if ($('#ddd').val() == '') {
				error('#ddd');
				msg.push('Informe o DDD do telefone.');
			}

			if ($('#cpf').val() != '') {

				var cpf = $('#cpf').val();

				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)){
					error('#cpf');
					msg.push('Cpf inválido.');
				}
			
				if (cpf.length < 11) {
					error('#cpf');
					msg.push('Cpf inválido.');
				}
			}


			if ($('#telefone').val() == '') {
				error('#telefone');
				msg.push('Informe o telefone.');
			}


			if($('#cidade').val() == ''){
				error('#cidade');
				msg.push('Selecione uma cidade.');
			}
			if ( ! isValidDate($('#dia').val() + '/' + $('#mes').val() + '/' + $('#ano').val())) {
				error('#dia');
				error('#mes');
				error('#ano');
				msg.push('Data de aniversário inválida.');
			}

			if (validate) {
				elemento.show();

				$.ajax({
					type: "POST",
					dataType: 'text',
					data: $('#frm-cadastro').serialize(),
					url: base_url + 'cadastro/envia_cadastro',
					cache: false,
					success: function(resp) {
						$('#msgSucesso').show();
						elemento.hide();
					},
					error: function() {
						elemento.hide();
					}
				});

				$('#frm-cadastro').find('input:not([type="hidden"]), textarea').val('');
			}
		}

		return false;
	});
}
function valida_contato(){
	$("#form-contato").submit(function(){
		clear($(this));
		var msg = [];
		elemento = $('#carregando_envia_cadastro');
		if ( ! elemento.is(':visible')){ 
			$('#msgSucesso').hide();

		if($('#nome').val() == ''){
			error('#nome');
			msg.push('Informe o seu nome.');
		}
		if($('#email').val() == ''){
			error('#email');
			msg.push('Informe o seu e-mail.');
		}
		else if(!checkMail($('#email').val())){
			error('#email');
			msg.push('Informe um e-mail válido.');
		}

		if ($('#ddd').val() == '') {
			error('#ddd');
			msg.push('Informe o DDD do telefone.');
		}

		if ($('#telefone').val() == '') {
			error('#telefone');
			msg.push('Informe o telefone.');
		}

		if($('#cidade').val() == ''){
			error('#cidade');
			msg.push('Selecione uma cidade.');
		}
		if($('#mensagem').val() == ''){
			error('#mensagem');
			msg.push('Digite sua mensagem.');
		}


		if ( ! validate) {
			if (msg.length > 0) {
				var msgModal = "<div id=\"topoValida\"><b>Os seguintes problemas foram encontrados:</b><br /><br /></div>";
				for(var i in msg) {
					msgModal += '<span>' + msg[i] + '</span><br/>';
				}
//				abrir(msgModal);
			}
			return false;
		}

		if (validate) {
			elemento.show();
			$.ajax({
					type: "POST",
					dataType: 'text',
					data: $('#form-contato').serialize(),
					url: base_url + 'cadastro/envia_contato',
					cache: false,
					success: function(resp) {
						$('#msgSucesso').show();
						elemento.hide();
					},
					error: function() {
						elemento.hide();
					}
				});

			$("#form-contato").unbind();
			$("#form-contato").submit();
		}
		}
		return false;
	});
}

function validate_novo_comentario() {
	$("#form_comentario").submit(function(){
		clear($(this));

		var msg = [];

		if($('#nome').val() == ''){
			error('#nome');
			msg.push('Informe o seu nome.');
		}

		if ( ! validate) {
			if (msg.length > 0) {
				var msgModal = "<div id=\"topoValida\"><b>Os seguintes problemas foram encontrados:</b><br /><br /></div>";
				for(var i in msg) {
					msgModal += '<span>' + msg[i] + '</span><br/>';
				}
				abrir(msgModal);
			}
			return false;
		}

		if (validate) {
			$("#frm-cadastro").unbind();
			$("#frm-cadastro").submit();
		}

		return false;
	});
}

function validate_form_busca_topo() {
	$('#frm_busca_topo').submit(function() {
		var busca = $(this).find('input[name="termo"]');

		if (busca.val() == '' || busca.val() == '/busca') {
			$(this).find('.imageInputWrapper').css('border', 'solid 1px #F52A8F');
			return false;
		}
	});
}

function error(selector) {
	$(selector).addClass('error');
	validate = false;
}

function clear(obj){
	obj.find('.error').removeClass('error');
	validate = true;
}

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

    if(typeof(mail) == "string"){
        if(er.test(mail)){return true;
    }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
            return true;
        }
    }
	
    return false;
}

function validation_start() {
	validate_cadastro();
	validate_envia_comentario();
	valida_contato();
	validate_form_busca_topo();
}

function isValidDate(dateStr, format) {
	if (format == null) {
		format = "DMY";
	}
	format = format.toUpperCase();
	if (format.length != 3) {
		format = "DMY";
	}
	if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) ||
		(format.indexOf("Y") == -1) ) {
		format = "MDY";
	}
	if (format.substring(0, 1) == "Y") { // If the year is first
		var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
		var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
	} else if (format.substring(1, 2) == "Y") { // If the year is second
		var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
		var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
	} else { // The year must be third
		var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
		var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	}
	// If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
	if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) {
		return false;
	}
	var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
	// Check to see if the 3 parts end up making a valid date
	if (format.substring(0, 1) == "M") {
		var mm = parts[0];
	} else
	if (format.substring(1, 2) == "M") {
		var mm = parts[1];
	} else {
		var mm = parts[2];
	}
	if (format.substring(0, 1) == "D") {
		var dd = parts[0];
	} else
	if (format.substring(1, 2) == "D") {
		var dd = parts[1];
	} else {
		var dd = parts[2];
	}
	if (format.substring(0, 1) == "Y") {
		var yy = parts[0];
	} else
	if (format.substring(1, 2) == "Y") {
		var yy = parts[1];
	} else {
		var yy = parts[2];
	}
	if (parseFloat(yy) <= 50) {
		yy = (parseFloat(yy) + 2000).toString();
	}
	if (parseFloat(yy) <= 99) {
		yy = (parseFloat(yy) + 1900).toString();
	}
	var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
	if (parseFloat(dd) != dt.getDate()) {
		return false;
	}
	if (parseFloat(mm)-1 != dt.getMonth()) {
		return false;
	}
	return true;
}