﻿$.validator.setDefaults({ 
			messages: {
				nome: {
						required: "Campo Nome é obrigatorio!",
						minlength: "Nome Inválido"
					},
					cidade: "Campo Cidade é obrigatorio!",
				telefone: "Campo Telefone é obrigatorio!",
				nome: "Campo Nome é obrigatorio!"
				
				/*dateISO: "Please enter a valid date (ISO).",
		number: "Please enter a valid number.",
		digits: "Please enter only digits.",
		creditcard: "Please enter a valid credit card number.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.validator.format("Please enter no more than {0} characters."),
		minlength: $.validator.format("Please enter at least {0} characters."),
		rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
		range: $.validator.format("Please enter a value between {0} and {1}."),
		max: $.validator.format("Please enter a value less than or equal to {0}."),
		min: $.validator.format("Please enter a value greater than or equal to {0}.")
		*/
	}
 
});

$(document).ready(function() {	
	$("input[name=chkbuscarEm][type='checkbox']").change(function()	
	{		
		var vName = $(this).val();
		$("input[name=chkbuscarEm][type='checkbox']").each( function() {
			if($(this).val() != vName)
				$(this).attr('checked',false)						
		});
	});
	 
	$('#FaleconoscoIDClic').fancybox({
			 	'padding': 0,
				'scrolling'		: 'no',
				'titleShow'		: false						
	});
	$('#CadastrarImovelIDClic').fancybox({
			 	'padding': 0,
				'scrolling'		: 'no',
				'titleShow'		: false						
	});
	$('#ReservarImovelIDClic').fancybox({
			 	'padding': 0,
				'scrolling'		: 'no',
				'titleShow'		: false						
	});
	
	$('#ReservarImovelIDClicIMG').fancybox({
			 	'padding': 0,
				'scrolling'		: 'no',
				'titleShow'		: false						
	});
	
	$("#frmFaleConosco").validate({
		submitHandler: function(form) {  
			//var idEmp = $("#empId").val()
			//var idLoginUser = $("#LogIdUser").val()
			//var formDados = $('#frmComentEmpresa').serialize();
			//var vDados = formDados + "&idemp=" + idEmp + "&iduser=" + idLoginUser;
						
			$.ajax({
				type: "POST",
				url: $("#frmFaleConosco").attr("action"),
				data: $("#frmFaleConosco").serialize(), 
				
				beforeSend: function(){
					//$('.enviando').show('slow');
				},
				success: function(data){
					if(data == 'S')
					{
						alert('Agradecemos seu contato, sua mensagem foi enviada com sucesso!');
					}else
					{						
						alert('Ocorreu em erro ao tentar enviar a mensagem, por favor, tente mais tarde!');		
					}
					$.fancybox.close();
				},
				error: function(){
					alert('Ocorreu em erro ao tentar enviar a mensagem, por favor, tente mais tarde!');
					$.fancybox.close();
				}
			});				
  			return false; 
		}, 
		rules: {
			nome: {
				required: true,
				minlength: 5
			},
			cidade: {
				required: true,
				minlength: 5
			},
			telefone: {
				required: true,
				minlength: 5
			},
			email:{
				required: true,
				email: true
			},
			departamento:{
				required: true
			},
			assunto: {
				required: true,
				minlength: 5
			},
			mensagem: {
				required: true,
				minlength: 5
			}
		}		
	});
	
	
	
	
	//FORMULARIO CADASTRO IMOVEL 
	$("#frmCadastroImovel").submit(function() {
			
			$.ajax({
				type: "POST",
				url: $(this).attr("action"),
				data: $(this).serialize(),
				
				beforeSend: function(){
					//$('#StatusMsg').show('slow');
				},
				success: function(data){
					if(data == 'S')
					{
						alert('Agradecemos seu contato, seu cadastro foi enviado com sucesso!');
						$.fancybox.close();						
					}else
					{
						alert('Ocorreu em erro ao tentar enviar o cadastro, por favor, tente mais tarde!');
						$.fancybox.close();
					}
				},
				error: function(){
					alert('Ocorreu em erro ao tentar enviar o cadastro, por favor, tente mais tarde!');
					$.fancybox.close();
				}
			});		

		 return false; 
	}); 
	
	//FORMULARIO RESERVA IMOVEL 
	$("#frmReservaImovel").submit(function() {
			
			$.ajax({
				type: "POST",
				url: $(this).attr("action"),
				data: $(this).serialize(),
				
				beforeSend: function(){
					$('#StatusMsg').show('slow');
				},
				success: function(data){
					if(data == 'S')
					{
						alert('Agradecemos seu contato, sua reserva foi enviado com sucesso!');
						//$('#StatusMsg').innerHTML = "Agradecemos seu contato, sua reserva foi enviado com sucesso!";
						$.fancybox.close();						
					}else
					{
						alert("Ocorreu em erro ao tentar enviar sua reserva, por favor, tente mais tarde!");
						//$('#StatusMsg').innerHTML = "Ocorreu em erro ao tentar enviar sua reserva, por favor, tente mais tarde!";
						$.fancybox.close();	
					}
					//$('#StatusMsg').show('slow');
					//$('.enviando').hide('slow');
					//clear form

				},
				error: function(){
					alert('Ocorreu em erro ao tentar enviar sua reserva, por favor, tente mais tarde!');
					$.fancybox.close();
					//$('#StatusMsg').innerHTML = "Ocorreu em erro ao tentar enviar sua reserva, por favor, tente mais tarde!";
					//$('#StatusMsg').show('slow');
				}
			});		

		 return false; 
	}); 
	
	
	//FORMULARIO CADASTRE-SE 
	$("#frmCadastrese").submit(function() {			
			//var senha = $("#senha").attr("value");			
			$.ajax({
				type: "POST",
				url: $(this).attr("action"),
				data: $(this).serialize(),
				
				beforeSend: function(){
					//$('#StatusMsg').show('slow');
				},
				success: function(data){
					if(data == 'S')
					{
						alert('Agradecemos seu contato, seu cadastro foi enviada com sucesso!');						
					}else
					{
						alert('Ocorreu em erro ao tentar enviar seu cadastro, por favor, tente mais tarde!');
					}
				},
				error: function(){
					alert('Ocorreu em erro ao tentar enviar a mensagem, por favor, tente mais tarde!');
				}
			});		

		 return false; 
	}); 
	
	
	//FORMULARIO PESQUISA IMOVEL
	$('#frmPesquisaImovelComprar').submit(function(){
		window.location.href = "http://www.chitolinaimobiliaria.com.br/index.asp?run=buscaimovel&" + $(this).serialize() +'&buscarEm=comprar';
		return false;
	});
	$('#frmPesquisaImovelAlugar').submit(function(){
						
		window.location.href = "http://www.chitolinaimobiliaria.com.br/index.asp?run=buscaimovel&" + $(this).serialize() +'&buscarEm=alugar';
		return false;
	});
	$('#frmPesquisaImovelPorCodigo').submit(function(){				
		window.location.href = "http://www.chitolinaimobiliaria.com.br/index.asp?run=buscaimovel&" + $(this).serialize() +'&buscarEm=codigo';
		return false;
	});
	
	$('#frmPesquisaImovelEsquerdo').submit(function(){
		var vN =  $("input[name=chkbuscarEm][type='checkbox']:checked").val();
		window.location.href = "http://www.chitolinaimobiliaria.com.br/index.asp?run=buscaimovel&" + $(this).serialize() +'&buscarEm=' + vN;
		return false;
	});
	
	//FORMULARIO INFORMAÇÕES IMOVEL 
	$("#frmInformacaoImovel").submit(function() {
			
			$.ajax({
				type: "POST",
				url: $(this).attr("action"),
				data: $(this).serialize(),
				
				beforeSend: function(){
					//$('#StatusMsg').show('slow');
				},
				success: function(data){
					if(data == 'S')
					{
						alert('Agradecemos seu contato, sua solicitação de informação foi enviada com sucesso!');						
					}else
					{
						alert('Ocorreu em erro ao tentar enviar sua solicitação, por favor, tente mais tarde!');						
					}
				},
				error: function(){
					alert('Ocorreu em erro ao tentar enviar sua solicitação, por favor, tente mais tarde!');					
				}
			});		

		 return false; 
	}); 
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//novo cadastro
	$("#formCriarCadastro").bind("submit", function(e) {
	//$('#signInFormErrors').hide();
	//$('#signInFormErrors ul').html('');
	//alert($(this).serialize());
	$.fancybox.resize();
	$.post("/criar_novo_usuario.asp", $(this).serialize(), function(response){
			//alert("resposta --> " +response.user.nome);
		if (response.success) {
			alert('ok logado');
			//userSuccessfullyLogged(response.user.name.split(' ').shift());
		} else {
			for (var error in response) {
				alert(response[error]);
				//$('#signInFormErrors ul').append('<li>' + response[error] + '</li>');
			}
				alert('q erro');
			//$('#signInFormErrors').slideDown(function(){
				//$.fancybox.resize();
			//});
		}
	}, 'json');
	return false;
	});
	

	
	/* Using custom settings */
	
	//$("a#inline").fancybox({
		//'hideOnContentClick': true
	//});

	/* Apply fancybox to multiple items */
	
	//$("a.group").fancybox({
		//'transitionIn'	:	'elastic',
		//'transitionOut'	:	'elastic',
		//'speedIn'		:	600, 
		//'speedOut'		:	200, 
		//'overlayShow'	:	false
	//});
	
});


/*
var startFancybox = function (elem) {
    jq(elem).fancybox({
        'padding': 0,
        'scrolling' : 'no',
        'titleShow' : false,
        'onClosed': function(el) {
            if (jq('#userIsLogged').val() === '1') {
                switch (jq(el).attr('id')) {
                    case 'newPOI':
                        window.location.href = '/local/create.html';
                        break;
                    case 'submitReview':
                        jq('#logoff').hide();
                        jq('#logged').show();
                        jq("#form_resenha").submit();
                        break;
                    case 'reportPOI':
                        window.location.href = '/local/report/' + jq('#poiId').val();
                        break;
                    case 'editPoiInfo':
                    case 'linkEditPoiInfo':
                        if(pageObj.user.id === jq('#poiUserId').val()) {
                            window.location.href = '/local/create.html?lbsid=' + jq("#poiId").val() + '&edit=1';
                        } else {
                            window.location.href = '/local/edit/' + jq("#poiId").val() + '.html';
                        }
                        break;
                    case 'addPhoto':
                    	location.reload();
                    	// TODO: fazer o combo de foto abrir automagicamente
                    	//document.location.pathname + addUrlParam(document.location.search, '&openPhotoUpload','1');
                    	break;
                    default:
                        var redir = jq(document).getUrlParam("redir");
                        if (redir) {
                            window.location.href = redir;
                        } else {
                            location.reload();
                        }
                        break;
				}
			} else {
				var tmp = jq('#rpx_iframe').attr('src').replace(/redir=.*$/i, 'redir='+jq('#poiUrlInput').val());
				jq('#rpx_iframe').attr('src', tmp);
			}
		},
		'onStart': function(e) {
			jq("#forgotPasswdForm, #recoverPasswdMessage, #signInFormErrors, #loginErrors").hide();
			jq("#forgotPasswd").show();
			if (jq(e).attr('id') === 'submitReview') {
				jq.cookie('comment',jq('#comment').val(), { path: '/' });
				jq.cookie('rating',jq('.stars:checked').val(), { path: '/' });
				var redirUrl = jq('#form_resenha').attr('action');
				var tmp = jq('#rpx_iframe').attr('src').replace(/redir=.*$/i, 'redir='+redirUrl);
				jq('#rpx_iframe').attr('src', tmp);
			}
		}
	});
};

startFancybox('#loginLink, #newPOI, #newAccount');

jq('#forgotPasswd, #signIn').click(function(){
	var id = jq(this).attr('id');
	var link = (id === 'signIn') ? '.create' : this;
	jq(link).fadeOut();
	jq('#' + id + 'Form').slideDown(function(){
		jq.fancybox.resize();
	});
});

jq("#apontadorSignIn form#forgotPasswdForm").bind("submit", function(e) {
	jq('#recoverPasswdMessage').hide().removeClass('success').removeClass('error').html('');
	jq.fancybox.resize();
	jq.post("/accounts/forgotPasswd.html", jq(this).serializeArray(), function(response){
		if (response.success) {
			jq('#recoverPasswdMessage')
				.addClass('success')
				.html("Sua senha foi enviada para " + response.user.email)
				.slideDown(function(){
					jq.fancybox.resize();
				});
		} else {
			jq('#recoverPasswdMessage')
				.addClass('error')
				.html('Não foi possível enviar o e-mail')
				.slideDown(function(){
					jq.fancybox.resize();
				});
		}
	}, 'json');
	return false;
});

userSuccessfullyLogged = function (loggedName){
	jq('#loggedName').html(loggedName);
	jq('#userIsLogged').val('1');
	jq.fancybox.close();
};

jq("#signInForm").bind("submit", function(e) {
	jq('#signInFormErrors').hide();
	jq('#signInFormErrors ul').html('');
	jq.fancybox.resize();
	jq.post("/accounts/createAccountAjax.html", jq(this).serializeArray(), function(response){
		if (response.success) {
			userSuccessfullyLogged(response.user.name.split(' ').shift());
		} else {
			for (var error in response) {
				jq('#signInFormErrors ul').append('<li>' + response[error] + '</li>');
			}
			jq('#signInFormErrors').slideDown(function(){
				jq.fancybox.resize();
			});
		}
	}, 'json');
	return false;
});

jq("#apontadorSignIn form#form_login").bind("submit", function(e) {
	jq('#loginErrors').hide();
	jq('#loginErrors .list-error').html('');
	jq.fancybox.resize();

	var valid = true;
	if (jq('#user_email_login').val().length < 1) {
		jq('#loginErrors .list-error').append('<li>E-mail não pode estar em branco.</li>');
		valid = false;
	}
	if (jq('#user_password_login').val().length < 1) {
		jq('#loginErrors .list-error').append('<li>Senha não pode estar em branco.</li>');
		valid = false;
	}
	if (!valid) {
		jq('#loginErrors').slideDown(function(){
			jq.fancybox.resize();
		});
		return false;
	} else {
		jq.post("/accounts/ajaxLogin.html", jq(this).serializeArray(), function(response){
			if (response.success) {
				userSuccessfullyLogged(response.user.name.split(' ').shift());
			} else {
				jq('#loginErrors .list-error').append('<li>' + response.email + '</li>');
				jq('#loginErrors').slideDown(function(){
					jq.fancybox.resize();
				});
			}
		}, 'json');
	}
	return false;
});
*/
