// mudar tamanho da fonte da materia
jQuery(function () {
	var tamanhoAtual = 12;

	var mudarTamanho = function (dir) {
		if(dir == '-' && tamanhoAtual <= 12)
		return false;

		if(dir == '+')
		tamanhoAtual++;
		else
		tamanhoAtual--;

		jQuery('#texto-materia').css('fontSize', tamanhoAtual);
	};

	jQuery('#aumentar-fonte, #diminuir-fonte').click(function () { return false; });
	jQuery('#aumentar-fonte').bind('click', function () { mudarTamanho('+'); });
	jQuery('#diminuir-fonte').bind('click', function () { mudarTamanho('-'); });

	$('#rodape-news').submit(function(){
		var email = $('#newsletter_mail').val();
		if (validarEmail(email)) {
			$.post('/newsletter.php', { email: email }, function(data) {
				if (parseInt(data) == 1) {
					var _gaq = _gaq || [];
  					_gaq.push(['_setAccount', $("#id_analytics").val()]);
 					_gaq.push(['_setDomainName', $("#domain_analytics").val()]);
  					_gaq.push(['_setAllowHash', true]);
  					_gaq.push(['_trackPageview','/cadastro-newsletter-ok/']);

  					(function() {
    					var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    					ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  					})();

					alert('Seu e-mail foi cadastrado com sucesso.');
					$('#newsletter_mail').val('');

				} else if(parseInt(data) == 2) {
					alert('E-mail já cadastrado.');

				} else {
					alert('Não foi possível cadastrar seu e-mail.');

				}
			});

		} else {
			alert('E-mail inválido');
		}
		return false;
	});

});

// Validar Email o.O
function validarEmail(email){
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(email) == "string"){
		if(er.test(email)){ return true; }
	}else if(typeof(email) == "object"){
		if(er.test(email.value)){
			return true;
		}
	}else{
		return false;
	}
}

// ----------
// COOKIES
// ----------

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	var i = '';

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {

	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// ----------
// Jquery JSON
// ----------
(function($){$.toJSON=function(o)
	{if(typeof(JSON)=='object'&&JSON.stringify)
	return JSON.stringify(o);var type=typeof(o);if(o===null)
	return"null";if(type=="undefined")
	return undefined;if(type=="number"||type=="boolean")
	return o+"";if(type=="string")
	return $.quoteString(o);if(type=='object')
	{if(typeof o.toJSON=="function")
	return $.toJSON(o.toJSON());if(o.constructor===Date)
	{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
	hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
	if(o.constructor===Array)
	{var ret=[];for(var i=0;i<o.length;i++)
		ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
		var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
		name='"'+k+'"';else if(type=="string")
		name=$.quoteString(k);else
		continue;if(typeof o[k]=="function")
		continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
		return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
		{if(typeof(JSON)=='object'&&JSON.parse)
		return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
		{if(typeof(JSON)=='object'&&JSON.parse)
		return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
		return eval("("+src+")");else
		throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
		{if(string.match(_escapeable))
			{return'"'+string.replace(_escapeable,function(a)
			{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
			return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);

/**
* ------------------------------------
* 	FAVORITOS COOKIE
* ------------------------------------
*/
// Inicia dando replace no rodapé
jQuery(document).ready(function(){
	jQuery('#texto-materia div.c-sobre-a-masb').each(function(index) {
		var si = jQuery(this);
		jQuery('#tpl-masb').append(si);
	});

	getImoveisFavoritos();
	eventoBotaoFavoritar();
});

function eventoBotaoFavoritar(){
	$('.link-favorito').hover(function(){
		$(this).find('span').show();
		$(this).find('span').addClass('link-favorito');
	},function(){
		$(this).find('span').hide();
	});
}

// Adiciona favorito ao cookie
function addImoveisFavoritos(titulo, url){
	var favoritos = Get_Cookie('masb-imoveis-fav');

	if(favoritos != null && favoritos.length != 0){
		var obj = jQuery.parseJSON(favoritos);

		for(var i = 1; i <= obj.quantidade; i++ ){
			var x = eval('obj.url'+i);
			if(x == url){
				alert('Imóvel já adicionado!');
				return;
			}
		}

		obj.quantidade++;
		eval('obj.titulo'+(obj.quantidade)+'="'+titulo+'"');
		eval('obj.url'+(obj.quantidade)+'="'+url+'"');

		Set_Cookie('masb-imoveis-fav',jQuery.toJSON(obj),1,'/','','');
	}else{
		var obj = new Object;
		obj.quantidade = 1;
		obj.titulo1 = titulo;
		obj.url1 = url;

		Set_Cookie('masb-imoveis-fav',jQuery.toJSON(obj),1,'/','','');
	}

	alert('Imóvel favoritado com sucesso!');

	getImoveisFavoritos();
	return;
}

function delImoveisFavoritos(id){
	var favoritos = Get_Cookie('masb-imoveis-fav');

	if(favoritos != null && favoritos.length != 0){
		var obj = jQuery.parseJSON(favoritos);
		for(var i = 1; i <= obj.quantidade; i++){
			if(i >= id){
				if(i == obj.quantidade){
					eval('obj.titulo'+id+' = null;');
					eval('obj.url'+id+' = null;');
					obj.quantidade--;
				}else{
					eval('obj.titulo'+id+' = obj.titulo'+(id+1));
					eval('obj.url'+id+' = obj.url'+(id+1));
				}
			}
		}
		if(obj.quantidade == 0){
			Delete_Cookie('masb-imoveis-fav');
		}else{
			Set_Cookie('masb-imoveis-fav',jQuery.toJSON(obj),1,'/','','');
		}

		getImoveisFavoritos();
	}
}

// Replace no rodapé
function getImoveisFavoritos(){
	var favoritos = Get_Cookie('masb-imoveis-fav');
	jQuery('.favoritos-rodape').html('');
	//alert(favoritos);
	if(favoritos != null && favoritos.length != 0){
		//alert('getImoveisFavoritos: '+favoritos);

		var obj = jQuery.parseJSON(favoritos);
		var lista = '';
		var i = obj.quantidade >= 3 ? (obj.quantidade - 3) + 1 : 1;

		// Criando lista de favoritos
		for(var f = i + 3; i < f; i++){
			if(typeof eval('obj.titulo'+i) == 'undefined')
			break;

			lista += '<li>';
			lista += '<a style="display: none;" href="javascript: void(0);" onclick="delImoveisFavoritos('+i+');">Remover</a>';
			lista += '<a href="'+eval('obj.url'+i)+'">'+eval('obj.titulo'+i)+'</a>';
			lista += '</li>';
		}

		jQuery('.favoritos-rodape').html(lista);
	}else{
		jQuery('.favoritos-rodape').html('<li>Conheça os <a href="/imoveis/">empreendimentos MASB</a> e escolha os seus favoritos.</li>');
	}
}
/**
* ------------------------------------
* 	FAVORITOS COOKIE FIM
* ------------------------------------
*/

/**
* ------------------------------------
* 	ATENDIMENTO FORM CONTATO
* ------------------------------------
*/
function loadAtendimentoForm(){
	jQuery('.atendimento-formcontato').submit(function(){
		var input_nome = jQuery("input[name$='nome']");
		var input_email = jQuery("input[name$='email']");
		var input_ddd = jQuery("input[name$='ddd']");
		var input_fone = jQuery("input[name$='fone']");
		var input_assunto = jQuery("input[name$='assunto']");

		if (input_nome.val().length < 1) {
			alert ( 'Nome não preenchido!' );
			return false;
		} else if (input_email.val() == '' || input_email.val().length <= 1) {
			alert ( 'Email não preenchido!' );
			return false;
		} else if (!validarEmail ( input_email.val() )) {
			alert ( 'Email inválido!' );
			return false;
		} else if (input_ddd.val() == '' || input_ddd.val().length <= 1) {
			alert ( 'DDD não preenchido!' );
			return false;
		} else if (input_fone.val() == '' || input_fone.val().length <= 1) {
			alert ( 'Telefone não preenchido!' );
			return false;
		}else{
			$.ajax({
				type: 'POST',
				url: '../_php/atendimento-contato.php',
				data: jQuery(this).serialize(),
				success: function(data) {
					alert(data);
				}
			});

			return false;
		}
	});
}
/**
* ------------------------------------
* 	ATENDIMENTO FORM CONTATO FIM
* ------------------------------------
*/

jQuery(function () {
    $('#fieldEmailAmigo2').focus(function () {
        if ($(this).val() == 'Digite o e-mail do seu amigo') {
            $(this).val('');
        }
    }).blur(function () {
        if (!$.trim($(this).val())) {
            $(this).val('Digite o e-mail do seu amigo');
        }
    });
    $('#formEmailAmigo').submit(function(e) {
        var self = this;
        e.preventDefault();
	    var email = $('#fieldEmailAmigo2').val();
	    if (validarEmail(email)) {
	        var params = {
	            email: email,
	            url: window.location.href
            };
		    $.post('/_php/compartilhe-email.php', params, function(response) {
		        var msg = response == '1' ? 'E-mail enviado com sucesso' :
		            'Não foi possível enviar o e-mail, tente novamente mais tarde';
                alert(msg);
                if (response == '1') {
                    self.reset();
                }
		    });
	    } else {
		    alert('E-mail inválido');
	    }
    });
});


