var url = '';
var atual;

function replace(text) {
	text = text.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$1" target="_blank">$1</a>')
	text = text.replace(/(^|\s)@(\w+)/g, '$1<a href="http://www.twitter.com/$2" target="_blank">@$2</a>');
	return text.replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2" target="_blank">#$2</a>');
}

function date(date){
	date = date.split(' ');
	time = date[3].split(':');
	return changeDay(date[0]) + ', ' + date[2] + ' de ' + changeMonth(date[1]) + ' - ' + parseInt(time[0] - 2) + ':' + time[1] + ':' + time[2];
}

function changeDay(day){
	switch(day){
		case 'Fri':
			return 'Sexta';
		case 'Thu':
			return 'Quinta';
		case 'Wed':
			return 'Quarta';
		case 'Tue':
			return 'Terça';
		case 'Mon':
			return 'Segunda';
		case 'Sun':
			return 'Domingo';
		case 'Sat':
			return 'Sábado';
	}
}

function changeMonth(month){
	switch(month){
		case 'Jan':
			return 'Janeiro';
		case 'Feb':
			return 'Fevereiro';
		case 'Mar':
			return 'Março';
		case 'Apr':
			return 'Abril';
		case 'May':
			return 'Maio';
		case 'Jun':
			return 'Junho';
		case 'Jul':
			return 'Julho';
		case 'Aug':		
			return 'Agosto';
		case 'Sep':
			return 'Setembro';
		case 'Oct':
			return 'Outubro';
		case 'Nov':
			return 'Novembro';
		case 'Dec':
			return 'Dezembro';
	}
}

getTweets = function(username, callback){
	requestURL = "http://twitter.com/statuses/user_timeline/" + username + ".json?callback=?&count=5";
	$.ajaxSetup({ cache: false }); 
	$.getJSON(requestURL, callback);
	$.ajaxSetup({ cache: true }); 
}

$(document).ready(function(){
	var username = 'Folha_Regional';
	$.ajaxSetup({ cache: false });
    getTweets(username, function(json, status){
		var content = '';
		$.each(json, function(i){
			content += '<li>' + replace(this['text']) + '<br /><em><a href="http://www.twitter.com/' + username + '/status/' + this['id_str'] + '" target="_blank">' + date(this['created_at']) + '</a></em></li><br />';
		});
		$('#twitter').html(content);
	});

	$('#folharegional').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folharegional&edicao=' + $('#folharegional').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folharegional&edicao=' + $('#folharegional').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhacidades').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhacidades&edicao=' + $('#folhacidades').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhacidades&edicao=' + $('#folhacidades').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhasaude').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhasaude&edicao=' + $('#folhasaude').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhasaude&edicao=' + $('#folhasaude').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhaveiculos').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhaveiculos&edicao=' + $('#folhaveiculos').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhaveiculos&edicao=' + $('#folhaveiculos').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhaimoveis').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhaimoveis&edicao=' + $('#folhaimoveis').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhaimoveis&edicao=' + $('#folhaimoveis').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhaespeciais').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhaespeciais&edicao=' + $('#folhaespeciais').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhaespeciais&edicao=' + $('#folhaespeciais').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhafestas').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhafestas&edicao=' + $('#folhafestas').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhafestas&edicao=' + $('#folhafestas').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#folhanews').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if (!window.open('ler.php?cat=folhanews&edicao=' + $('#folhanews').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folhanews&edicao=' + $('#folhanews').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#bellacasa').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if(!window.open('ler.php?cat=bellacasa&edicao=' + $('#bellacasa').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=bellacasa&edicao=' + $('#bellacasa').val();
				$.fancybox({'href' : '#login_form', 'onClosed' : function(){ atual.val(0);} });
			}*/
		}
	});
	
	$('#folharural').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				if(!window.open('ler.php?cat=folharural&edicao=' + $('#folharural').val())){
					desbloqueie();
				}
			/*}
			else{
				url = 'ler.php?cat=folharural&edicao=' + $('#folharural').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$('#oferecimento').click(function(){
		if (!window.open('ler.php?cat=edicaododia&edicao=' + $('#edicaododia').val())){
			desbloqueie();
		}
		$.fancybox.close();
	});
	
	$('#edicaododia').change(function(e){
		e.preventDefault();
		if ($(this).val() != 0){
			atual = $(this);
			//if (getCookie('hash') && getCookie('code')){
				//$('#imgEdicaoDoDia').attr('src', 'edicoes/edicaododia/' + $('#edicaododia').val() +'/oferecimento.jpg');
				
				
				/*$.fancybox({
					'href' : '#oferecimento', 
					'width' : 400,
					'onCleanup' : fechaOferecimento
				});*/
				
				if (!window.open('ler.php?cat=edicaododia&edicao=' + $('#edicaododia').val())){
					desbloqueie();
				}
				
				/*$(function () {
					var img = new Image();
					$(img).load(function () {
						$(this).hide();
						$('#loader').html(this);
						$(this).show();
					}).error(function () {
					}).attr('src', 'http://www.jornalfolharegional.com/edicoes/edicaododia/' + $('#edicaododia').val() + '/oferecimento.jpg');
				});*/
			/*}
			else{
				url = 'ler.php?cat=edicaododia&edicao=' + $('#edicaododia').val();
				$.fancybox({'href' : '#login_form',});
			}*/
		}
	});
	
	$("#signupForm").validate({
		rules: {
			pgto: "required",
			forma: "required",
			nome: "required",
			cpfcnpj: "required",
			nascimento: "required",
			email: {
				required: true,
				email: true
			},
			endereco: "required",
			cep: "required",
			cidade: "required",
			telefone: "required"
		},
		messages: {
			pgto: "",
			forma: "",
			nome: "Requerido",
			cpfcnpj: "Requerido",
			nascimento: "Requerido",
			email: "Digite um e-mail válido",
			endereco: "Requerido",
			cep: "Requerido",
			cidade: "Requerido",
			telefone: "Requerido"
		}
	});
	
	$('#formLogin').validate({
		rules : {
			email : {
				required: true,
				email: true
			},
			senha: 'required'
		},
		messages:{
			email: 'Informe um email válido',
			senha: 'Informe sua senha'
		}
	});
	
	$('#formCadastro').validate({
		rules : {
			nomeCadastro: 'required',
			emailCadastro: {
				required: true,
				email: true
			},
			senhaCadastro: 'required'
		},
		messages : {
			nomeCadastro: 'Informe seu nome',
			emailCadastro: 'Informe um email válido',
			senhaCadastro: 'Informe uma senha'
		}
	});
	
	$('#formLogin').bind('submit', function(e) {
		e.preventDefault();
		
		if ($('#formLogin').valid()){
			$.fancybox.showActivity();
			$.ajax({
				type	: 'POST',
				cache	: false,
				url		: 'ajax.php',
				dataType: 'json',
				data	: {action: 'login', email: $('#email').val(), senha: $('#senha').val()},
				success : function(response) {
					$.fancybox.hideActivity();
					
					if (response[0] != 'erro'){
						setCookie('code', response[0], 1);
						setCookie('hash', response[1], 1);
						
						if (atual.attr('id') == 'edicaododia'){
							$.fancybox({'href' : '#oferecimento', 'width' : 400});
						}
						else{
							window.open(url);
						}
						
						atual.val(0);
						$.fancybox.close();
					}
					else{
						alert('Login inválido');
					}
				}
			});
		}
	});
	
	$('#formCadastro').bind('submit', function(e){
		e.preventDefault();
		
		if ($('#formCadastro').valid()){
			$.fancybox.showActivity();
			$.ajax({
				type	: 'POST',
				cache	: false,
				url		: 'ajax.php',
				dataType: 'json',
				data	: {action: 'cadastro', nome: $('#nomeCadastro').val(), email: $('#emailCadastro').val(), senha: $('#senhaCadastro').val()},
				success : function(response) {
					$.fancybox.hideActivity();
					setCookie('code', response[0], 1);
					setCookie('hash', response[1], 1);
					$.fancybox.close();
					if (!window.open(url)){
						desbloqueie();
					}
				}
			});
		}
	});
	
	var rotation = function (){
		$("#img").rotate({
			angle:0, 
			animateTo:360, 
			callback: rotation
		});
	}
	
	if ($('#img').length > 0){
		rotation();
	}
});

function fechaOferecimento(){
	if (!window.open('ler.php?cat=edicaododia&edicao=' + $('#edicaododia').val())){
		desbloqueie();
	}
	$.fancybox.close();
}



function openRadio() {
	var leftStr = (screen.width-200) / 2;
	var topStr = (screen.height-100)/ 2 - 50;
	windowProperties = 'toolbar=no,menubar=no,scrollbars=no,statusbar=no,height=100,width=200,left='+leftStr+',top='+topStr;
	var popRadio = window.open('radio.php', '', windowProperties);
}
function openAtendimento() {
	var leftStr = (screen.width-400) / 2;
	var topStr = (screen.height-500)/ 2 - 50;
	windowProperties = 'toolbar=no,menubar=no,scrollbars=no,statusbar=no,height=500,width=400,left='+leftStr+',top='+topStr;
	var popRadio = window.open('atendimento.php', '', windowProperties);
}

function setCookie(c_name,value,exdays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value = escape(value) + ((exdays == null) ? '' : '; expires=' + exdate.toUTCString());
	document.cookie=c_name + '=' + c_value;
}

function getCookie(c_name){
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name){
			return unescape(y);
		}
	}
}

function desbloqueie(){
	alert('O seu navegador está bloqueando as popups.\nVocê deve desbloquea-las para prosseguir com a leitura');
}
