/*  Look JavaScript ext Prototype
 *--------------------------------------------------------------------------*/
var preImages = [];
var IMAGES = ['1-como-funciona.jpg', '2-o-que-eu-ganho.jpg', '3-quero-participar.jpg', 'background.jpg', 'btn-concluir.gif', 
'btn-confirme-seu-cadstro.gif', 'btn-fechar.gif', 'btn-procurar.gif', 'btn-procurar-desabilitado.gif', 'btn-pronto-envie-minha-foto.gif', 
'btn-zoom-in.gif', 'btn-zoom-out.gif', 'label-background-ano.gif', 'label-background-ano.jpg', 'label-background-cidade.jpg', 
'label-background-dia.gif', 'label-background-dia.jpg', 'label-background-email.jpg', 'label-background-mes.gif', 'label-background-mes.jpg', 
'label-background-nome.jpg', 'label-background-telefone.jpg', 'label-background-uf.jpg', 'label-checkbox.jpg', 'marcacao-foto.gif', 
'marcacao-foto.jpg', 'marcacao-foto-background.jpg', 'marcacao-foto-desabilitada.gif', 'marcacao-foto-desabilitada.jpg', 'player-background.jpg', 
'rexona.gif', 'rexona-teens.gif', 'txt-arrase-no-look.gif', 'txt-data-de-nascimento.gif', 'txt-envie-sua-foto.gif', 'txt-parabens.gif', 
'txt-quero-participar.gif', 'txt-rexona-teens-dance.gif', 'unilever.gif', 'vencedoras-dance.jpg'];

var Estados = ['AC','AL','AM','AP','BA','CE','DF','ES','GO','MA','MG','MS','MT','PA','PB','PE','PI','PR','RJ','RN','RO','RR','RS','SC','SE','SP','TO'];

var modalLockerClassName = 'locker',
	modalBodyClassName = 'modal-body',
	modalContentClassName = 'modal-content',
	modalRegulamentoClassName = 'modal-regulamento';

var initialX, initialY, x, y, activeMove = false;

var Look = {
	session: undefined,
	numberCropImages: 0,
	info: {},
	
	init: function() {
		/* preload all images */
		this.preload();

		/* modal */
		this.locker = new Element('div', {className: modalLockerClassName});
		this.modalBody = new Element('div', {className: modalBodyClassName});
		this.modalContent = new Element('div', {className: modalContentClassName});

		/* regulamento */
		this.modalRegulamento = new Element('div', {className: modalRegulamentoClassName});
		this.modalRegulamentoLoaded = false;

		/* set modal height/width */
		this.modalSetSize();
		window.onresize = function () {
			this.modalSetSize();
		}.bind(this);

		/* hide modal */
		this.modalHide();

		/* append modal */
		$(document.body).insert({bottom: this.locker});
		$(document.body).insert({bottom: this.modalBody});
		$(this.modalBody).insert({bottom: this.modalContent});
		$(this.modalBody).insert({bottom: this.modalRegulamento});
	},

	preload: function() {
		var total = IMAGES.length;
		for (var x = 0; x < total; x++) {
			preImages[x] = new Image();
			preImages[x].src = 'media/images/'+IMAGES[x];
		}
	},

	modalShow: function() {
		this.locker.show();
		this.modalBody.show();
		this.modalContent.show();
		this.modalRegulamento.hide();
		$('_banner-swf').setStyle({visibility:'hidden'});
	},
	modalHide: function() {
		this.locker.hide();
		this.modalBody.hide();
		this.modalContent.hide();
		if ($('_banner-swf'))
			$('_banner-swf').setStyle({visibility:'visible'});
	},
	modalSetSize: function() {
		if (!(this.locker && this.modalBody))
			return false;

		/* window.getDimensions: pageWidth, pageHeight, windowWidth, windowHeight */
		var dimensions = window.getDimensions();
		this.locker.setStyle({height: dimensions.pageHeight + 'px'});
		this.modalBody.setStyle({height: dimensions.pageHeight + 'px'});
	},

	startSession: function(session) {
		switch(session) {
			case 'fotos': 
				this.sessionFotos();
				break;
			case 'crop': 
				if (arguments[1])
					this.sessionCrop(arguments[1], arguments[2], arguments[3]);
				break;
			case 'confirmacao': 
				this.sessionConfirmacao();
				break;
			case 'regulamento': 
				this.sessionRegulamento(arguments[1]);
				break;
			case 'termos': 
				this.sessionTermos();
				break;
			default: 
				this.sessionCadastro();
				break;
		}
	},
	closeSession: function() {
		this.modalHide();
		initialX = 0;
		initialY = 0;
		x = 0;
		y = 0;
		activeMove = false;
		this.cropImage = false;
		this.modalContent.update();
		this.numberCropImages = 0;
	},

	sessionCadastro: function() {
		this.modal('cadastro');
		this.session = 'cadastro';
	},
	sessionFotos: function() {
		this.modal('cadastro_fotos');
		this.session = 'fotos';
	},
	sessionCrop: function(imagem, width, height) {
		if (this.session != 'fotos')
			return false;

		// Tracker de CROP
		GA.track('/site/promo/quero_participar/crop_foto');
		
		if (!this.cropImage) {
			this.cropDivImage = new Element('div').setStyle({
				border: 'medium none',
				margin: '0',
				padding: '0',
				visibility: 'visible',
				position: 'absolute',
				zIndex: '1002',
				top: '0',
				left: '0'
			});
			this.cropMovimento = new Element('div').setStyle({
				border: 'medium none',
				margin: '0',
				padding: '0',
				visibility: 'visible',
				position: 'absolute',
				zIndex: '1004',
				cursor:'pointer',
				background: '#000',
				opacity: '0'
			});
			this.cropImage = new Element('img').setStyle({position: 'absolute', zIndex: '1003'});
			$('imagem').insert({bottom: this.cropDivImage});
			this.cropDivImage.insert({bottom: this.cropImage});
			this.cropDivImage.insert({bottom: this.cropMovimento});
		} else {
			this.cropDivImage.setStyle({top: '0', left: '0'});
		}
		
		$$('.fotos-cadastro').first().setStyle({display:'none'});
		$$('.crop').first().setStyle({display:'block'});
		this.cropImage.onload = function() {
			var dimensions = $(this).getDimensions();
			Look.cropMovimento.setStyle({
				width: dimensions.width + 'px',
				height: dimensions.height + 'px'
			});
		}
		this.cropImage.src = 'arquivos/tmp/' + imagem;
		this.session = 'crop';

		this.cropMovimento.onmousedown = function(e) {
			e = e || event;
			initialX = Event.pointerX(e) - parseInt($(this.parentNode).getStyle('left'));
			initialY = Event.pointerY(e) - parseInt($(this.parentNode).getStyle('top'));

			$(this).setStyle({display: 'none'});
			activeMove = true;
		};
		
		this.cropImage.onmouseup = function() {
			activeMove = false;
			initialX = 0;
			initialY = 0;
			Look.cropMovimento.setStyle({display: ''});
		};
		
		this.cropImage.onmouseout = function() {
			activeMove = false;
			initialX = 0;
			initialY = 0;
			Look.cropMovimento.setStyle({display: ''});
		};
		
		this.cropImage.onmousemove = function(e) {
			if (activeMove) {
				e = e || event;
				var dimensions = $(this).getDimensions();

				x = Event.pointerX(e) - initialX;
				y = Event.pointerY(e) - initialY;

				if (y < 0 && y + dimensions.height > 255)
					$(this.parentNode).setStyle({top: y+'px'});
				
				if (x < 0  && x + dimensions.width > 263)
					$(this.parentNode).setStyle({left: x+'px'});
			}
		};
	},
	sessionTermos: function() {
		this.modal('termos');
		this.session = 'termos';
	},
	sessionConfirmacao: function() {
		this.modal('cadastro_confirmacao');
		this.session = 'confirmacao';
	},
	sessionRegulamento: function(termos) {
		
		if (termos) {
			setTimeout(function() {
				if ($(termos).checked == false) {
					$(termos).checked = true;
					$(termos).parentNode.className = 'termos checked';
				} else {
					$(termos).checked = false;
					$(termos).parentNode.className = 'termos';
				}
			}, 500);
		}

		this.regulamento();
		this.session = 'regulamento';
	},
	
	cadastro: function(form) {
		if (!$('termos').checked) {
			alert('Li e concordo com os termos e condições de uso desta promoção. deve ser selecionado.');
		} else if (!Estados.include($('uf').getValue().toUpperCase())) {
			alert('O estado deve ser válido.');
		} else {
			new Ajax.Request('cadastro_verifica_email.php', {
				method: 'post',
				parameters: {email: $('email').getValue()},
				onComplete: function(transport) {
					if (transport.responseText == '1') {
						Look.info = form.serialize(true);
						Look.startSession('fotos');
					} else if (transport.responseText == '2') {
						alert('E-mail já utilizado por outro usuário.');
					} else {
						alert('E-mail inválido.');
					}
				}
			})
		}

		return false;
	},
	
	cadastroFotos: function() {
		this.info['fotos[]'] = $$('.crop-image-info').map(Form.Element.getValue).without("");

		$('concluir').className = 'desabilitado';
		$('concluir').onclick = function() { }

		new Ajax.Request('cadastro_envia.php', {
			method: 'post',
			parameters: this.info,
			onComplete: function(transport) {
				if (parseInt(transport.responseText) > 0) {
					Look.startSession('confirmacao');
				} else {
					alert('Ocorreu um erro no cadastro. Favor tenta novamente.');
				}
			}
		})
	},
	
	regulamento: function() {

		// Tracker de Regulamento
		GA.track('/site/promo/regulamento');

		this.sessionStatus = this.modalContent.getStyle('display');
		this.locker.show();
		this.modalBody.show();
		this.modalContent.hide();
		$('_banner-swf').setStyle({visibility:'hidden'});
		this.modalRegulamento.setStyle({display: 'block'});

		if (!this.modalRegulamentoLoaded) {
			new Ajax.Request('regulamento.html', {
				onComplete: function(transport) {
					this.modalRegulamentoLoaded = true;
					this.modalRegulamento.update(transport.responseText);
				}.bind(this)
			});
		}
	},
	
	regulamentoClose: function() {
		this.modalRegulamento.hide();
		
		if (this.sessionStatus == 'none') {
			this.locker.hide();
			this.modalBody.hide();
			$('_banner-swf').setStyle({visibility:'visible'});
		} else {
			this.modalContent.show();
		}
		this.sessionStatus = 'none';
	},

	modal: function(file) {
		new Ajax.Request(file+'.html', {
			onCreate: function() {
				this.modalContent.update();
				this.modalShow();
			}.bind(this),
			onComplete: function(transport) {
				this.modalContent.className = modalContentClassName + ' ' + this.session;
				this.modalContent.update(transport.responseText);
			}.bind(this)
		});
	},

	faleConosco: function() {
		window.open('http://www.rexona.com.br/site/content/contato/contato_popup.php?origem=DANCE','','width=475,height=435');
	},

	crop: {
		diferenca: 10,
		_zoom: function(valor) {
			if (!Look.cropImage) return false;
			var dimensions = Look.cropImage.getDimensions();
			Look.cropImage.setStyle({width: (dimensions.width + valor) + 'px'});
			var dimensions = Look.cropImage.getDimensions();
			Look.cropMovimento.setStyle({
				width: (dimensions.width) + 'px',
				height: (dimensions.height) + 'px'
			});
		},
		zoomIn: function() {
			this._zoom(this.diferenca);
		},
		zoomOut: function() {
			var dimensions = Look.cropImage.getDimensions();
			var left = parseInt($(Look.cropImage.parentNode).getStyle('left'));
			var top = parseInt($(Look.cropImage.parentNode).getStyle('top'));

			if (dimensions.width + left > 255 + this.diferenca &&
				dimensions.height + top > 255 + this.diferenca) {
				this._zoom(- this.diferenca - 15);
			}
		},
		loader: function() {
			var cropImages = $$('.crop-image');
			var image = cropImages[Look.numberCropImages];
			image.src = 'media/images/loading_foto_arrasa_look.gif';
		},
		save: function() {
			/* save width, height, top, left of image */
			var imageInfo = {
				file: Look.cropImage.src.split('\/').last(),
				dimensions: Look.cropImage.getDimensions(),
				positions: {
					top: Math.abs(parseInt($(Look.cropImage.parentNode).getStyle('top'))),
					left: Math.abs(parseInt($(Look.cropImage.parentNode).getStyle('left')))
				}
			};

			$$('.fotos-cadastro').first().setStyle({display:'block'});
			$$('.crop').first().setStyle({display:'none'});

			if (Look.numberCropImages == 0) {
				$('concluir').className = '';
				$('concluir').onclick = function() {
					Look.cadastroFotos();
				}
			}

			var cropImages = $$('.crop-image'),
				cropInputs = $$('.input'),
				cropColuna = $$('.coluna'),
				cropInputsHidden = $$('.crop-image-info');

			var image = cropImages[Look.numberCropImages],
				inputIframe = cropInputs[Look.numberCropImages],
				coluna = cropColuna[Look.numberCropImages],
				inputHidden = cropInputsHidden[Look.numberCropImages];

			var proporcao = function(valor) {
				return 81 * valor / 255;
			};

			var cropImageWidth = proporcao(imageInfo.dimensions.width),
				cropImageHeight = proporcao(imageInfo.dimensions.height),
				cropImageTop = proporcao(- imageInfo.positions.top),
				cropImageLeft = proporcao(- imageInfo.positions.left);

			image.setStyle({
				width: cropImageWidth + 'px',
				height: cropImageHeight + 'px',
				top: cropImageTop + 'px',
				left: cropImageLeft + 'px', position: 'relative'
			});
			image.src = Look.cropImage.src;

			inputHidden.value = Object.toJSON(imageInfo);

			if (Look.numberCropImages < 2) {
				var nextInputIframe = cropInputs[Look.numberCropImages + 1],
					nextColuna = cropColuna[Look.numberCropImages + 1];

				nextColuna.className = 'coluna';
				nextInputIframe.update(inputIframe.innerHTML);
			}

			coluna.className = 'coluna desabilitada';
			inputIframe.update();

			Look.numberCropImages++;
			Look.session = 'fotos';
			Look.cropImage.src = '';
			Look.cropImage.setStyle({width: '', height: ''});
		}
	}
};