JSEntries = new Class({

	l: null,
	buyersGuideCount: 0,
	tinyMCEInited: false,
	strings: {
		salvar: {
			pt: 'salvar',
			en: 'saving'
		},
		aguarde: {
			pt: 'Aguarde...',
			en: 'Wait...'
		},
		enviar: {
			pt: 'Enviar',
			en: 'Send'
		},
		enviarVerbo: {
			pt: 'enviar',
			en: 'sending'
		},
		reset: {
			pt: 'Limpar',
			en: 'Reset'
		},
		erroNome: {
			pt: 'N&atilde;o escreveu o seu nome',
			en: 'You didn\'t tell us your name'
		},
		emailBranco: {
			pt: 'N&atilde;o escreveu o seu e-mail',
			en: 'You didn\'t tell us your e-mail'
		},
		comentarioBranco: {
			pt: 'N&atilde;o escreveu o seu coment&aacute;rio',
			en: 'You didn\'t write your comment'
		},
		emailInvalido: {
			pt: 'O e-mail que escreveu &eacute; inv&aacute;lido',
			en: 'Your e-mail is not valid'
		},
		erroRecaptcha: {
			pt: 'As palavras anti-spam n&atilde;o foram escritas correctamente',
			en: 'The anti-spam words were not entered correctly'
		},
	},

	// ----------------------------------------------------------------------------------------------------
	initialize: function(l) {

		this.l = l;

	},

	// ----------------------------------------------------------------------------------------------------
	verifica: function(form) {

		var errorArray = new Array();

		// Codigo
		var id = $('id').value = $('id').value.clean();
		if(id == '') errorArray.push('N&atilde;o escreveu um c&oacute;digo<br /><span class="nota">Escreva um c&oacute;digo com um caractere ou mais</span>');
		else {
			var idOriginal = $chk($('id_original')) ? $('id_original').value : null;
			if(id != idOriginal) {
				var codigoRequest = new Request.HTML({
					url: 'modulos/entries/verificar_id.ajax.php',
					async: false,
					onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
						if(responseHTML.clean() != 0) this.errorArray.push('J&aacute; existe uma entrada com este c&oacute;digo:<br /><span class="nota">' + responseHTML + '</span>');
					}
				});
				codigoRequest.errorArray = errorArray;
				codigoRequest.get({l: this.l, id: id});
			}
		}

		// Titulo
		var titulo = $('titulo').value = $('titulo').value.clean();
		if(titulo == '') errorArray.push('N&atilde;o escreveu um t&iacute;tulo<br /><span class="nota">Escreva um t&iacute;tulo com um caractere ou mais</span>');

		// Novo autor
		if($('id_autor').value == 0) {
			var novoAutor = $('novo_autor').value = $('novo_autor').value.clean();
			if(novoAutor == '') errorArray.push('N&atilde;o escreveu o nome do novo autor<br /><span class="nota">Escreva um nome com um caractere ou mais</span>');
			else {
				var autorRequest = new Request.HTML({
					url: 'modulos/authors/verifica_autor_novo.ajax.php',
					async: false,
					onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
						if(responseHTML.clean() != 0) this.errorArray.push('J&aacute; existe um autor com este nome');
					}
				});
				autorRequest.errorArray = errorArray;
				autorRequest.get({nome: novoAutor});
			}
		}

		// Buyers guide novos
		var nome, link, c = 1;
		for(var n = 0; n < this.buyersGuideCount; n++) {
			if($chk($('nome_novo_buyers_guide_' + n)) && $chk($('link_novo_buyers_guide_' + n))) {
				nome = $('nome_novo_buyers_guide_' + n).value = $('nome_novo_buyers_guide_' + n).value.clean();
				if(nome == '') errorArray.push('N&atilde;o escreveu o nome do ' + c + '&ordm; novo buyer\'s guide');
				link = $('link_novo_buyers_guide_' + n).value = $('link_novo_buyers_guide_' + n).value.clean();
				if(link == '') errorArray.push('N&atilde;o escreveu o link do ' + c + '&ordm; novo buyer\'s guide');
				c++;
			}
		}
		
		// Se houver erros mostra-los, caso contrario enviar o formulario
		if(errorArray.length) utils.mostraErrorArray(errorArray, this.strings.salvar[this.l]);
		else {
			form.set('action', 'entries/' + id)
			form.submit();
		}

	},

	// ----------------------------------------------------------------------------------------------------
	over: function(id) {

		$('tr_' + id).setStyle('background', '#FFFFFF');
		$('div_comandos_' + id).setStyle('display', 'block');

	},

	// ----------------------------------------------------------------------------------------------------
	out: function(id) {

		$('tr_' + id).setStyle('background', 'none');
		$('div_comandos_' + id).setStyle('display', 'none');

	},

	// ----------------------------------------------------------------------------------------------------
	mostraSumario: function(id) {

		new Request.HTML({
			url: 'modulos/entries/get_sumario.ajax.php',
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				(function() {$('div_sumario_' + id).set('html', responseHTML).setStyle('display', 'block');}).delay(1000);
			}
		}).get({
			l: infoPagina.l,
			id: id
		});

	},

	// ----------------------------------------------------------------------------------------------------
	escondeSumario: function(id) {

		$('div_sumario_' + id).setStyle('display', 'none');

	},

	// ----------------------------------------------------------------------------------------------------
	apaga: function(id, titulo, porAjax) {

		msgr.show({
			tipo: 'confirm',
			titulo: 'Apagar?',
			html: porAjax ? 'Apagar a entrada <strong>' + id + ': ' + titulo + '</strong>?' : 'Apagar esta entrada?',
			onComplete: function(ok) {
				if(!ok) return;
				if(porAjax) {
					new Request.HTML({
						url: 'modulos/entries/apagar.ajax.php',
						onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
							// Retirar a tr da entrada
							$('tr_' + id).dispose();
							// Se for ultimo de uma letra, apaga-la
							var letra = titulo.substring(0, 1).toUpperCase();
							if($('table_letra_' + letra).getChildren()[0].getChildren().length == 1) {
								$('div_letra_' + letra).dispose();
							}
							// Se tiver sido recentemente editada, apagar a referencia
							if($chk($('div_recent_' + id))) $('div_recent_' + id).dispose();
						}
					}).get({l: entries.l, id: id});
				} else document.location.href = 'entries/apagar/' + id;
			}
		});

	},

	// ----------------------------------------------------------------------------------------------------
	seleccionaAutor: function() {

		if($('id_autor').value == 0) {
			$('novo_autor').setStyle('display', 'inline');
			$('novo_autor').focus();
		} else {
			$('novo_autor').setStyle('display', 'none');
		}

	},

	// ----------------------------------------------------------------------------------------------------
	getDateFromId: function(id) {
	
		var dataBruta = $(id).value;
		if(dataBruta == null) return;
		var dataPartida = dataBruta.split('-');
		var dia =  dataPartida[2];
		var mes = dataPartida[1].valueOf() - 1;
		var ano = dataPartida[0];
		return new Date(ano, mes, dia);

	},

	// ----------------------------------------------------------------------------------------------------
	criaCalendarios: function() {

//		MooTools.lang.setLanguage("en-US");
		new DatePicker('data_criacao', {
			pickerClass: 'datepicker_dashboard',
			format: '%Y-%m-%d'
		});
		new DatePicker('data_modificacao', {
			pickerClass: 'datepicker_dashboard',
			format: '%Y-%m-%d'
		});
		return;



		var data = this.getDateFromId('calendario_criacao');
		Calendar.setup({
			flat         : 'calendario_criacao',			// ID of the parent element
			flatCallback : function(calendar) {				// our callback function
				// Beware that this function is called even if the end-user only
				// changed the month/year.  In order to determine if a date was
				// clicked you can use the dateClicked property of the calendar:
				if(calendar.dateClicked) {
					$('calendario_criacao').setStyle('display', 'none');
					var d = calendar.date.getDate();     	 // integer, 1..31
					var m = 1 + calendar.date.getMonth();    // integer, 0..11
					var a = calendar.date.getFullYear();
					if(String(d).length < 2) d = '0' + d;
					if(String(m).length < 2) m = '0' + m;
					$('data_criacao').value = a + '-' + m + '-' + d;
					$('data_criacao').setStyle('display', 'inline');
				}
			},
			daFormat     : "%d-%m-%Y",
			date         : data
		});
		$('calendario_criacao').addEvent('mouseleave', function() {
			entries.escondeCalendario('criacao');
		});

		var data = this.getDateFromId('calendario_modificacao');
		Calendar.setup({
			flat         : 'calendario_modificacao',			// ID of the parent element
			flatCallback : function(calendar) {				// our callback function
				// Beware that this function is called even if the end-user only
				// changed the month/year.  In order to determine if a date was
				// clicked you can use the dateClicked property of the calendar:
				if(calendar.dateClicked) {
					$('calendario_modificacao').setStyle('display', 'none');
					var d = calendar.date.getDate();     	 // integer, 1..31
					var m = 1 + calendar.date.getMonth();    // integer, 0..11
					var a = calendar.date.getFullYear();
					if(String(d).length < 2) d = '0' + d;
					if(String(m).length < 2) m = '0' + m;
					$('data_modificacao').value = a + '-' + m + '-' + d;
					$('data_modificacao').setStyle('display', 'inline');
				}
			},
			daFormat     : "%d-%m-%Y",
			date         : data
		});
		$('calendario_modificacao').addEvent('mouseleave', function() {
			entries.escondeCalendario('modificacao');
		});


	},

	// ----------------------------------------------------------------------------------------------------
	mostraCalendario: function(tipo) {

/*		if(tipo != 'criacao' && tipo != 'modificacao') return;

		if(tipo == 'criacao') {
			$('data_criacao').setStyle('display', 'none');
			$('calendario_criacao').setStyle('display', 'block');
		} else {
			$('data_modificacao').setStyle('display', 'none');
			$('calendario_modificacao').setStyle('display', 'block');
		}
*/
	},

	// ----------------------------------------------------------------------------------------------------
	escondeCalendario: function(tipo) {

/*		if($chk($('data_' + tipo)) && $chk($('calendario_' + tipo))) {
			$('data_' + tipo).setStyle('display', 'inline');
			$('calendario_' + tipo).setStyle('display', 'none');
		}
*/
	},

	// ----------------------------------------------------------------------------------------------------
	toggleFormComentario: function() {

		if($('div_comentario_novo').getStyle('display') == 'none') {
			if(!this.tinyMCEInited) {
				utils.initTinyMCESimples();
				this.tinyMCEInited = true;
			}
			$('div_comentario_novo').setStyle('display', 'block');
			$('name').focus();
		} else $('div_comentario_novo').setStyle('display', 'none');

	},

	// ----------------------------------------------------------------------------------------------------
	getComentarios: function(id) {

		$('div_comentarios').innerHTML = '';
		new Request.HTML({
			url: 'modulos/entries/get_comentarios.ajax.php',
			async: true,
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				$('div_comentarios').innerHTML = responseHTML;
			}
		}).get({l: this.l, id: id});

	},

	// ----------------------------------------------------------------------------------------------------
	verificaComentario: function(id) {

		$('btn_submit').value = this.strings.aguarde[this.l];

		var errorArray = new Array();

		// Name
		var name = $('name').value = $('name').value.clean();
		if(name == '') errorArray.push(this.strings.erroNome[this.l]);

		// E-mail
		var email = $('email').value = $('email').value.clean();
		if(email == '') errorArray.push(this.strings.emailBranco[this.l]);
		else if(!utils.emailCheck(email)) errorArray.push(this.strings.emailInvalido[this.l]);

		// Comentario
		var comment = tinyMCE.get('comment').getContent();
		if(comment == '') errorArray.push(this.strings.comentarioBranco[this.l]);

		// Recaptcha
		var recaptchaRequest = new Request.HTML({
			url: 'modulos/recaptcha-php-1.10/verifica.ajax.php',
			async: false,
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				if(responseHTML.clean() != 1) {
					this.errorArray.push(entries.strings.erroRecaptcha[entries.l]);
					Recaptcha.reload();
				}
			}
		});
		recaptchaRequest.errorArray = errorArray;
		recaptchaRequest.get({
			recaptcha_challenge_field: $('recaptcha_challenge_field').value,
			recaptcha_response_field: $('recaptcha_response_field').value
		});

		// Se houver erros mostra-los, caso contrario enviar o formulario
		if(errorArray.length) {
			utils.mostraErrorArray(errorArray, this.strings.enviarVerbo[this.l]);
			$('btn_submit').value = this.strings.enviar[this.l];
		} else {
			new Request.HTML({
				url: 'modulos/entries/gravar_comentario.ajax.php',
				async: true,
				onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
					$('btn_submit').value = entries.strings.enviar[entries.l];
					msgr.show({
						tipo: 'info',
						html: responseHTML
					});
				}
			}).get({
				id: id,
				name: name,
				email: email,
				comment: comment
			});
			this.toggleFormComentario();
			this.getComentarios(id);
		}

	},

	// ----------------------------------------------------------------------------------------------------
	apagaComentario: function(id) {

		msgr.show({
			tipo: 'confirm',
			titulo: 'Apagar?',
			html: 'Apagar este coment&aacute;rio?',
			onComplete: function(ok) {
				if(!ok) return;
				new Request.HTML({
					url: 'modulos/entries/apagar_comentario.ajax.php',
					onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
						$('div_comentario_' + id).dispose();
					}
				}).get({id: id});
			}
		});

	},

	// ----------------------------------------------------------------------------------------------------
	adicionaBuyersGuide: function() {

		// div do novo buyersGuide
		var buyersGuideDiv = new Element('div', {
			id: 'div_novo_buyers_guide_' + this.buyersGuideCount
		});

		// nome do novo buyersGuide
		var buyersGuideNome = new Element('input', {
			type: 'text',
			name: 'nome_novo_buyers_guide_' + this.buyersGuideCount,
			id: 'nome_novo_buyers_guide_' + this.buyersGuideCount,
			style: 'width: 150px; margin-bottom: 2px;',
			value: 'Nome'
		});

		// Link
		var buyersGuideLink = new Element('input', {
			type: 'text',
			name: 'link_novo_buyers_guide_' + this.buyersGuideCount,
			id: 'link_novo_buyers_guide_' + this.buyersGuideCount,
			style: 'width: 200px; margin-bottom: 2px;',
			value: 'Link'
		});

		// a do novo buyersGuide
		var buyersGuideA = new Element('a', {
			id: 'a_novo_buyers_guide_' + this.buyersGuideCount,
			href: 'javascript: entries.removeBuyersGuide(' + this.buyersGuideCount + ')',
			html: 'Remover'
		});

		// A div agarra o texto e o a; o fieldset agarra a div
		buyersGuideDiv.grab(buyersGuideNome);
		buyersGuideDiv.appendText(' ');
		buyersGuideDiv.grab(buyersGuideLink);
		buyersGuideDiv.appendText(' ');
		buyersGuideDiv.grab(buyersGuideA);
		$('div_buyers_guide').grab(buyersGuideDiv);

		var a_copy = $('a_novo_buyers_guide').clone(true, true);
		$('a_novo_buyers_guide').destroy();
		$('div_buyers_guide').grab(a_copy);
		buyersGuideNome.select();

		this.buyersGuideCount++;
//		$('BoxOverlay').setStyle('height', window.getScrollHeight());

	},

	// ----------------------------------------------------------------------------------------------------
	removeBuyersGuide: function(id) {

		$('div_novo_buyers_guide_' + id).destroy();

	}

});

