/*  Ações de cadastro
 *
 *--------------------------------------------------------------------------*/
var cadastro = {
	login: function(form) {
		$(form).request({
			onComplete: function(transport) {
				var response = transport.responseText.evalJSON();

				switch(response.result) {
					case -2 : alert('Dados de login inválidos.'); break;
					case -1 : alert('Certifique-se que o e-mail é válido.'); break;
					case 1 : 
					case 2 : cadastro.loginEfetuado(response.nome); break;
					default : alert('Ocorreu um erro no login. Favor tente novamente.'); break;
				};
			}
		});
	},

	logout: function() {
		new Ajax.Request('http://www.rexona.com.br/site/modal_logout_envia.php', {
			onComplete: function(transport) {
				var response = transport.responseText;

				if (response == '1')
					cadastro.deslogado();
			}
		});
	},

	esqueciSenha: function() {
		var email = $('login')['email'].value;
		if (email.blank()) {
			alert('Preencha corretamente o formulário:\n\n- ' + $('login')['email'].title + ' é um campo obrigatório');
			$('login')['email'].focus();
			return false;
		}
		new Ajax.Request('http://www.rexona.com.br/site/modal_login_recuperar_senha.php', {
			method: 'post',
			parameters: {email: email},
			onComplete: function(transport) {
				var response = transport.responseText;

				if (response == '1') {
					alert('Sua senha foi encaminhada com sucesso para o e-mail indicado.');
					$('login')['senha'].focus();
				}
				else
					alert('Sua senha não pode ser recuperada. Certifique-se que o e-mail informado é o mesmo que foi utilizado na hora do cadastro.');
			}
		});
	},

	loginEfetuado: function(nome, notlogin) {
		if (!notlogin)
			modalLogin.hide();

		$('usuario').update(nome);

		cadastro.logado();
	},

	logado: function() {
		$$('.autenticacao').first().setStyle({display: 'none'});
		$$('.logado').first().setStyle({display: 'block'});
	},

	deslogado: function() {
		$$('.autenticacao').first().setStyle({display: 'block'});
		$$('.logado').first().setStyle({display: 'none'});
	},

	cadastrar: function(form) {
		$(form).request({
			onComplete: function(transport) {
				var response = transport.responseText.evalJSON();

				switch(response.retorno) {
					case -2: alert('O seu e-mail já está cadastrado.'); break;
					case -1: alert('Certifique-se que o e-mail é válido.'); break;
					case 1: cadastro.cadastroEfetuado(form, response.nome); break;
					default: alert('Ocorreu um erro no envio do seu cadastro. Favor tente novamente.'); break;
				};
			}
		});
	},

	cadastroEfetuado: function(form, nome) {
		// tracker sexo usuário
		if (form['sexo'][0].checked)
			GA.track('/site/cadastro/concluido_mm');
		else
			GA.track('/site/cadastro/concluido_ff');

		modalCadastro.hide();
		modalMensagem.show();

		if (nome)
			cadastro.loginEfetuado(nome);
	}
};

/*  Crop
 *
 *-------------------------------------------------------------------------*/
var coords, dimensions, modalCrop, imageCrop;

var openCrop = function(img, realname, width, height) {
	var preload = new Image();
	$('image-text').update('Carregando imagem...');
	preload.onload = function() {
		var largura = this.width + 38;
		var meio = largura / 2;
		var distancia = 470 - meio + 'px';

		$$('div.crop').first().setStyle({width: (largura)+'px', height: (this.height + 225) + 'px', left: distancia});
		$$('div.foto').first()
			.setStyle({width: this.width + 'px', height: this.height + 'px', margin: '14px auto 0'})
			.update('<img src="'+this.src+'" id="cropimage" alt="Crop" title="Crop" \/>');

		imageCrop = this._name;
		$('image-text').update(this._realname);
		modalCadastro.hide();
		modalCrop.show();
	};
	preload._name = img;
	preload._realname = realname;
	preload.src = 'http:\/\/www.rexona.com.br\/site\/arquivos\/temp_images\/' + img;
};

var sendCrop = function() {
	$('selecionado').value = imageCrop + ' || ' + Object.toJSON(Object.extend(coords, dimensions));

	var preview = $('imgCrop_cropimage');

	$('preview-cadastro').src = preview.src;
	//$('preview-cadastro').setStyle({position: 'absolute', width: Math.round(parseInt(preview.getStyle('width'), 10) * 0.5714) + 'px', top: Math.round(parseInt(preview.getStyle('top'), 10) * 0.5714) + 'px', left: Math.round(parseInt(preview.getStyle('left'), 10) * 0.5714) + 'px'});
	$('preview-cadastro').setStyle({position: 'absolute', width: preview.getStyle('width'), top: preview.getStyle('top'), left: preview.getStyle('left')});

	modalCrop.hide();
	modalCadastro.show();
};

var endCrop = function( cCoords, cDimensions ) {
	coords = cCoords;
	dimensions = cDimensions;
};

var cancelCrop = function() {
	$('image-text').update('Selecione uma foto do seu computador.');
	$('selecionado').value = '';
	modalCrop.hide();
	modalCadastro.show();
}

/* Cria campo para enviar foto
 *
 *-------------------------------------------------------------------------*/
var fileInput = function() {
	//var element = $$('.preview').first();
	
	//element.update('<img src="http://www.rexona.com.br/site/media/images/avatares/1.jpg" alt="Foto" id="preview-cadastro" /></div><div class="input"><b id="image-text">Selecione uma foto do seu computador.</b>');
	//element.insert('<iframe src="http://www.rexona.com.br/site/modal_cadastro_upload.php" id="iupload" scrolling="no" marginheight="0" marginwidth="0" frameborder="0"></iframe>');
	//$('iupload').setStyle({width: '72px', height: '17px', cursor: 'pointer', overflow: 'hidden', border: '0', margin: '0', padding: '0', background: '#000', 'float': 'right', display: 'inline', margin: '5px 14px 0 0'});
};


/*  Window Load
 *
 *--------------------------------------------------------------------------*/
var modalMensagem, modalLogin, modalCadastro, modalEmailAmigo, modalNewsletter, modalRegulamento;

Event.observe(window, 'load', function() {
	// modais
	modalRegulamento = new pModal('http://www.rexona.com.br/site/modal_desafio_fashion_regulamento.php', {className: 'regulamento', autoScroll: false});
	modalRegulamento.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));
	});
	modalRegulamento.addListener(pModalEvent.ONSHOW, function() {
		$('concursocutural-regulamento').focus();

		var dimensions = window.getDimensions();
		var scrolls = window.getPageScroll();

		this.setStyle({top: scrolls.top + (dimensions.windowHeight - parseInt(this.getStyle('height'), 10)) / 2 + 'px'});
	});

	modalRegulamentoTwitter = new pModal('http://www.rexona.com.br/site/modal_desafio_fashion_regulamento_twitter.php', {className: 'regulamento', autoScroll: false});
	modalRegulamentoTwitter.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));
	});
	modalRegulamentoTwitter.addListener(pModalEvent.ONSHOW, function() {
		$('concursocutural-regulamento').focus();

		var dimensions = window.getDimensions();
		var scrolls = window.getPageScroll();

		this.setStyle({top: scrolls.top + (dimensions.windowHeight - parseInt(this.getStyle('height'), 10)) / 2 + 'px'});
	});

	modalEmailAmigo = new pModal('http://www.rexona.com.br/site/modal_post_email.php', {className: 'post-email', autoScroll: false});
	modalEmailAmigo.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));
	});
	modalEmailAmigo.addListener(pModalEvent.ONSHOW, function() {
		$('seu-nome').focus();

		var universo = this.params[1];
		var idPost = this.params[2];
		var tituloPost = this.params[3];

		if (!idPost || !universo)
			this.hide();

		var dimensions = window.getDimensions();
		var scrolls = window.getPageScroll();

		this.setStyle({top: scrolls.top + (dimensions.windowHeight - parseInt(this.getStyle('height'), 10)) / 2 + 'px'});

		$('universo').value = universo;
		$('post-id').value = idPost;
		$('post-titulo').value = tituloPost;
	});

	modalNewsletter = new pModal('http://www.rexona.com.br/site/modal_newsletter.php', {className: 'newsletter', autoScroll: false});
	modalNewsletter.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));
	});
	modalNewsletter.addListener(pModalEvent.ONSHOW, function() {
		GA.track('/site/mais/newsletter/acesso');
		$('newsletter-email').focus();

		var dimensions = window.getDimensions();
		var scrolls = window.getPageScroll();

		this.setStyle({top: scrolls.top + (dimensions.windowHeight - parseInt(this.getStyle('height'), 10)) / 2 + 'px'});
	});

	modalMensagem = new pModal('http://www.rexona.com.br/site/modal_cadastro_mensagem.php', {className: 'mensagem'});
	modalMensagem.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));
	});

	modalLogin = new pModal('http://www.rexona.com.br/site/modal_login.php', {className: 'login'});
	modalLogin.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));

		this.body.content.select('a.sem-login').first()
			.cancelEvent()
			.observe('click', function() {
				this.hide();
				modalCadastro.show();
			}.bind(this));

		this.body.content.select('a.esqueceu-senha').first()
			.cancelEvent()
			.observe('click', function() { cadastro.esqueciSenha(); }.bind(this));
		
		Validacao.start();
	});
	modalLogin.addListener(pModalEvent.ONSHOW, function() { $('login-email').focus(); });
	
	modalCadastro = new pModal('http://www.rexona.com.br/site/modal_cadastro.php', {className: 'cadastro'});
	modalCadastro.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', this.hide.bind(this));

		// avatares para o cadastro
		$('foto').observe('click', function() {
			$('selecionado')._avatar = $('selecionado').value;
			$('selecionado').value = $('selecionado')._foto || '';

			$(this).up()
				.next('.foto').setStyle({display: 'block'})
				.next().setStyle({display: 'none'});
		});
		$('avatar').observe('click', function() {
			$('selecionado')._foto = $('selecionado').value;
			$('selecionado').value = $('selecionado')._avatar || '';

			$(this).up()
				.next('.foto').setStyle({display: 'none'})
				.next().setStyle({display: 'block'});
		});

		this.body.content.select('.lista-avatares a').each(function(element, i) {
			element.observe('click', function() {
				$('selecionado').value = i + 1;

				$(this)
					.addClassName('selected')
					.siblings().invoke('removeClassName','selected');
			});
		});

		Validacao.start();
		fileInput();
	});
	modalCadastro.addListener(pModalEvent.ONSHOW, function() { $('cadastro-nome').focus(); });

	modalCrop = new pModal('http://www.rexona.com.br/site/modal_cadastro_crop.php', {className: 'crop'});
	modalCrop.addListener(pModalEvent.ONCOMPLETE, function() {
		this.body.content.select('a.fechar').first()
			.cancelEvent()
			.observe('click', function() {
				$('image-text').update('Selecione uma foto do seu computador.');
				$('selecionado').value = '';
				this.hide();
			}.bind(this));
		this.body.content.select('a.voltar').first()
			.cancelEvent()
			.observe('click', cancelCrop);
		this.body.content.select('a.ok').first()
			.cancelEvent()
			.observe('click', sendCrop);
	});
	modalCrop.addListener(pModalEvent.ONSHOW, function() {
		$('preview').update();
		this.cropper = new Cropper.ImgWithPreview('cropimage', {
			minWidth: 40, 
			minHeight: 40,
			previewWidth: 40,
			previewHeight: 40,
			ratioDim: { x: 40, y: 40 },
			displayOnInit: true, 
			onEndCrop: endCrop,
			previewWrap: 'preview'
		});
	});

	// Botoes do menu topo que abrem modais
	$$('a[rel=login]').first()
		.cancelEvent()
		.observe('click', function() { modalLogin.show(); });

	$$('a[rel=cadastro]').first()
		.cancelEvent()
		.observe('click', function() { modalCadastro.show(); });

	$$('a[rel=sair]').first()
		.cancelEvent()
		.observe('click', function() { cadastro.logout(); });

/*	$$('a[rel=_blank]').each(function(e) {
		if (e.href.search('post=') > -1 )
			e.observe('click', function() {
				var idPost = e.href.match(/post=(.*)/).last();
				new Ajax.Request('', {
					onComplete: function() {
					}
				});
			});
	});*/

	// links
	actionByRel('termos-uso', function() { window.callWindow({url: 'termos_uso.php', width: 516, height: 460, scrollbars: 1}); });
});

/*  Envio de post por e-mail
 *
 *--------------------------------------------------------------------------*/
var post = {
	emailAmigo: function(form) {
		$(form).request({
			onComplete: function(transport) {
				var response = transport.responseText;

				universo = $('universo').value == 'M' ? 'man' : 'women';
				titulo = $('post-titulo').value;

				switch (response) {
					case '-1': alert('Certifique-se que os e-mails são válidos.'); break;
					case '1': alert('Artigo enviado com sucesso.'); GA.track('/site/' + universo + '/comentarios/' + titulo); $(form).reset(); modalEmailAmigo.hide(); break;
					default: alert('Não foi possível enviar o e-mail. Tente novamente mais tarde.'); break;
				}
			}
		});
	},
	
	comentar: function(form) {
		$(form).request({
			onComplete: function(transport) {
				var response = transport.responseText;
				var link = location.href.indexOf('&comentario') > -1 ? '' : '&comentario=1'; 

				universo = $('universo').value == 'M' ? 'man' : 'women';
				titulo = $('post-titulo').value;

				switch (response) {
					case '1': alert('Comentário enviado com sucesso.'); GA.track('/site/' + universo + '/comentarios/' + titulo); $(form).reset(); setTimeout(function() { location.href = location.href + link; } , 700); break;
					default: alert('Não foi possível enviar o comentário. Tente novamente mais tarde.'); break;
				}
			}
		});
	}
};

/*  Newsletter
 *
 *--------------------------------------------------------------------------*/
var newsletter = function(form) {
	$(form).request({
		onComplete: function(transport) {
			var response = transport.responseText;

			switch (response) {
				case '-2': alert('Seu e-mail já está cadastrado!'); break;
				case '-1': alert('Seu e-mail não pode ser cadastrado. Certifique-se que o e-mail é válido.'); break;
				case '1': alert('Seu e-mail foi cadastrado com sucesso!'); GA.track('/site/mais/newsletter/concluido'); $(form).reset(); modalNewsletter.hide(); break;
				default: alert('Não foi cadastrar seu e-mail. Tente novamente mais tarde.'); break;
			}
		}
	});
}