/**
 * @namespace Namespace que contém os widgets do TeContei
 */
TeContei.Widgets = {};
TeContei.Widgets.Termometro = Class.create(
/** @lends TeContei.Widgets.Termometro.prototype */
{
	/**
	 * Widget do termômetro
	 *
	 * @param {Element} el O container do termometro
	 * @constructs
	 */
	initialize: function(el) {
		this.el = el;
		this.quesitos = [];
		this.totalInput = this.el.down('input[name="termometro_nota_final"]');

		var temp = this.el.select('div.termometro_quesito');

		for(var i = 0, len = temp.length ; i < len ; i++) {
			this.quesitos.push({
				label: temp[i].down('div.quesito_label'),
				input: temp[i].down('div.quesito_input input'),
				slider: temp[i].down('div.slider'),
				handle: temp[i].down('div.handle')
			});
			this.quesitos[i].handle.setStyle({
				left: Math.round(parseFloat(this.quesitos[i].input.value)*10)+'%'
			})
		}

		if(this.el.down('div.submit_container') != null) {
			this.generateSliders();
		}
		else {
			Event.observe(el,'click',this.showPopup.bindAsEventListener(this));
		}
		this.updateTotal();
	},
	/** @private */
	generateSliders: function() {
		var instance = this;
		for(var i=0, len=this.quesitos.length ; i < len ; i++) {
			this.quesitos[i].sliderControl = new Control.Slider(this.quesitos[i].handle, this.quesitos[i].slider, {
				increment: 0.1,
				range: $R(0, 10.0),
				sliderValue: parseFloat(this.quesitos[i].input.value),
				termometro: this,
				quesito: this.quesitos[i],
				onSlide: function(value) {
					this.quesito.input.value = Math.round(value*10)/10;
				},
				onChange: function(value) {
					this.quesito.input.value = Math.round(value*10)/10;
					instance.updateTotal();
				}
			});
		}
	},
	/** @private */
	updateTotal: function() {
		var soma = 0;
		var len = this.quesitos.length;
		for(var i=0 ; i < len ; i++) {
			nota = this.quesitos[i].input.value;
			nota = nota.replace(',','.');
			soma += eval(nota);
		}
		this.totalInput.value = Math.round((soma/len)*100)/100;
	},
	/** @private */
	showPopup: function(event) {
		var elem = Event.element(event);
		if(elem.hasClassName('slider')) {
			var parameters = {
				content: TeContei.Dicionario.Termometro.Alertas.Login,
				style: {
					height: '100px',
					width: '400px'
				}
			}
			TeContei.Widgets.ModalDialog.Show(parameters);
		}
	}
});
TeContei.Widgets.Galeria = Class.create(
/** @lends TeContei.Widgets.Galeria.prototype */
{
	/**
	 * Widget da galeria de fotos
	 *
	 * @param {Element} el O container da galeria
	 * @constructs
	 */
	initialize: function(el, selected_pic) {
		this.el = $(el);
		this.selected_pic = selected_pic || 1;

		this.scrollWidth = 99;

		this.Buttons = {
			Next: this.el.down('div.seta_dir img'),
			Prev: this.el.down('div.seta_esq img')
		};

		this.Containers = {
			Controles: this.el.down('div.galeria_controles'),
			Fotos: this.el.down('div.fotos div')
		};

		var scroll = (this.scrollWidth * this.selected_pic) - this.scrollWidth;
		JSTweener.addTween(this.Containers.Fotos, {
			time: 0,
			transition: 'easeoutquad',
			scrollLeft: this.Containers.Fotos.scrollLeft+scroll
		});

		Event.observe(this.Containers.Controles, 'click', this.handleClick.bindAsEventListener(this));
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		var scroll = 0;
		if(elem == this.Buttons.Next) {
			scroll += this.scrollWidth;
		}
		else if (elem == this.Buttons.Prev) {
			scroll -= this.scrollWidth;
		}
		JSTweener.addTween(this.Containers.Fotos, {
			time: 0.3,
			transition: 'easeoutquad',
			scrollLeft: this.Containers.Fotos.scrollLeft+scroll
		});
	}
});
TeContei.Widgets.Calculadora = Class.create(
/** @lends TeContei.Widgets.Calculadora.prototype */
{
	/**
	 * Widget da calculadora do amor
	 *
	 * @param {Element} el O container da calculadora
	 * @constructs
	 */
	initialize: function(el) {
		this.nome1Input = el.down('input[name="calculadora_nome1"]');
		this.nome2Input = el.down('input[name="calculadora_nome2"]');
		this.calcButton = el.down('input[name="calculadora_calc"]');
		this.progressBar = el.down('div.barra_porcentagem');
		this.progressLabel = el.down('div.label_porcentagem');
		this.fraseContainer = el.down('div.frase');

		this.CurrentResult = 0;

		Event.observe(this.calcButton, 'click', this.calculate.bindAsEventListener(this));
	},
	/** @private */
	calculate: function(event) {
		Event.stop(event);
		this.progressBar.setStyle({
			width: '0%'
		});
		this.progressLabel.innerHTML = '';
		this.fraseContainer.innerHTML = '';
		if(this.nome1Input.value.empty() || this.nome2Input.value.empty()) {
			this.fraseContainer.innerHTML = TeContei.Dicionario.Calculadora.Frases.Empty;
			return;
		}
		var tempNome1 = this.nome1Input.value.toLowerCase();
		var tempNome2 = this.nome2Input.value.toLowerCase();

		var soma1 = 0;
		var soma2 = 0;

		for(var i=0, len=tempNome1.length ; i < len ; i++) {
			soma1 += tempNome1.charCodeAt(i)/(i+1);
		}

		for(var i=0, len=tempNome2.length ; i < len ; i++) {
			soma2 += tempNome2.charCodeAt(i)/(i+1);
		}

		this.CurrentResult = parseInt(((soma1+soma2)/((Math.abs(soma1-soma2))+1)*1000).toString().substr(2,2));

		JSTweener.addTween(this.progressBar.style, {
			time: 1,
			transition: 'easeoutquad',
			onUpdateParams: [this],
			onUpdate: function() {
				this.progressLabel.innerHTML = parseInt(this.progressBar.style.width)+'%';
			}.bind(this),
			onComplete: function() {
				var conjFrases;
				if(this.CurrentResult < 33) {
					conjFrases = TeContei.Dicionario.Calculadora.Frases.Baixa;
				}
				else if(this.CurrentResult < 66) {
					conjFrases = TeContei.Dicionario.Calculadora.Frases.Media;
				}
				else {
					conjFrases = TeContei.Dicionario.Calculadora.Frases.Alta;
				}
				this.fraseContainer.innerHTML = '"'+conjFrases[Math.floor((Math.random()*conjFrases.length))]+'"';
			}.bind(this),
			width: this.CurrentResult,
			suffix: {
				width: '%'
			}
		});
	}
});
TeContei.Widgets.Toolbox = Class.create(
/** @lends TeContei.Widgets.Toolbox.prototype */
{
	/**
	 * Widget do toolbox
	 *
	 * @constructs
	 * @param {Element} el O container do toolbox
	 * @requires TeContei.Favorito
	 */
	initialize: function(el) {
		this.el = $(el);

		this.Buttons = {
			Indique: $('toolbox_indique'),
			Favorita: $('toolbox_favorita_button')
		}

		this.HasVinculo = this.Buttons.Favorita.hasClassName('invertido');

		this.Favorito = {
			Id: el.down('input').value,
			Tipo: TeContei.Favorito.Tipos[$('favtype').value]
		}

		this.ShareOptions = {};
		this.ShareOptions[TeContei.IMG_SERVER+'toolbox/share/facebook.gif'] = {
			name: 'Facebook',
			url:'http://www.facebook.com/sharer.php?',
			args: {
				url: 'u=',
				title: 't='
			}
		};
		this.ShareOptions[TeContei.IMG_SERVER+'toolbox/share/delicious.gif'] = {
			name: 'Del.icio.us',
			url: 'http://del.icio.us/post?',
			args: {
				url: 'url=',
				title: 'title='
			}
		},
		this.ShareOptions['http://favorites.live.com/favicon.ico'] = {
			name: 'LiveSpaces',
			url: 'https://favorites.live.com/quickadd.aspx?',
			insert: 'marklet=1&mkt=en-us&top=0',
			args: {
				url: 'url=',
				title: 'title='
			}
		}

		Event.observe(this.el,'click',this.handleClick.bindAsEventListener(this));
		document.observe('favoritos:added',this.favoritoAdded.bindAsEventListener(this));
		document.observe('favoritos:removed',this.favoritoRemoved.bindAsEventListener(this));
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		if(elem.hasClassName('disabled')) {
			Event.stop(event);
		}
		else if(elem == this.Buttons.Favorita) { // Favorita
			var url = TeContei.URL+'proxy/favoritos/';
			if(this.HasVinculo) {
				TeContei.Favorito.Remove(this.Favorito);
			}
			else {
				TeContei.Favorito.Add(this.Favorito);
			}
			Event.stop(event);
		}
		else if(elem.tagName == 'IMG') { // Social Bookmarking
			window.open(this.assembleURL(this.ShareOptions[Event.element(event).src]));
			Event.stop(event);
		}
		else if(elem == this.Buttons.Indique) {
			Event.stop(event);
			var url = elem.href.split('#');
			var urlinfo = url[url.length-1].split("=");
			window.location.href = TeContei.URL + 'indique/?' + 'p=' + urlinfo[0] + '&v=' + urlinfo[1] + '&url=' + window.location.href;
		}
	},
	/** @private */
	favoritoAdded: function(event) {
		this.Buttons.Favorita.addClassName('invertido');
		this.Buttons.Favorita.innerHTML = ' '+TeContei.Dicionario.Toolbox.Labels.SouFa;
		this.HasVinculo = true;
	},
	/** @private */
	favoritoRemoved: function(event) {
		this.Buttons.Favorita.removeClassName('invertido');
		this.Buttons.Favorita.innerHTML = ' '+TeContei.Dicionario.Toolbox.Labels.Favorita;
		this.HasVinculo = false;
	},
	/** @private */
	assembleURL: function(service) {
		var url = service.url;
		if(typeof(service.insert) !== 'undefined') {
			url += service.insert+'&';
		}
		url += service.args.url+encodeURI(window.location.href);
		url += '&'+service.args.title+encodeURI(document.title);
		return url;
	}
});
TeContei.Widgets.Resumos = Class.create(
/** @lends TeContei.Widgets.Resumos.prototype */
{
	/**
	 * Widget de resumos de novela
	 *
	 * @param {Element} el O container dos resumos
	 * @constructs Widget dos resumos de novela
	 */
	initialize: function(el) {
		this.el = $(el);

		this.Buttons = {
			Prev: this.el.down('a.seta_esq'),
			Next: this.el.down('a.seta_dir')
		}

		Event.observe(this.el, 'click', this.handleClick.bindAsEventListener(this));
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		if(elem.hasClassName('inactive')) {
			Event.stop(event);
		}
		else if(elem.tagName == 'SPAN') {
			if(elem.parentNode.hasClassName('inactive')) {
				Event.stop(event);
			}
		}
		else if(elem == this.Buttons.Next) {
			Event.stop(event);
			elem.up('form').submit();
		}
		else if(elem == this.Buttons.Prev) {
			Event.stop(event);
			elem.up('form').submit();
		}
	}
});
TeContei.Widgets.Quiz = Class.create(
/** @lends TeContei.Widgets.Quiz.prototype */
{
	/**
	 * Widget do Quiz
	 *
	 * @param {Element} el O container do quiz
	 * @constructs
	 */
	initialize: function(el) {
		this.url = TeContei.URL+'proxy/quiz/';
		this.el = $(el);
		this.quizObj = {};

		this.Labels = {
			CurrentPergunta: $('quiz_navegacao_current_pergunta'),
			NumeroPerguntas: $('quiz_navegacao_numero_perguntas'),
			Pergunta: $('quiz_pergunta')
		}
		this.Containers = {
			Confirma: $('confirma_container'),
			CurrentPergunta: $('quiz_current_pergunta'),
			Loading: this.el.down('div.loading'),
			Opcoes: $('quiz_opcoes_container'),
			Quiz: this.el.down('div.quiz')
		}
		this.Buttons = {
			Previous: $('quiz_previous_button'),
			Next: $('quiz_next_button'),
			Confirm: $('quiz_confirma_button')
		}

		this.respostasHidden = $('quiz_respostas_hidden');

		this.currentPage = 1;
		this.currentPergunta = 1;

		Event.observe(document,'quiz:loaded',this.quizLoaded.bindAsEventListener(this));
		Event.observe(document,'quiz:loadError',this.quizLoadErrorHandler.bindAsEventListener(this));

		TeContei.Quiz.Load(this.el.down('input[name="quiz_id"]').value);

	},
	/** @private */
	quizLoaded: function(event) {
		this.quizObj = event.memo;
		this.numeroPerguntas = this.quizObj.perguntas.length;
		this.Labels.NumeroPerguntas.innerHTML = this.numeroPerguntas;

		this.changePergunta(this.currentPergunta);

		if(this.currentPergunta == this.numeroPerguntas) {
			this.Containers.Confirma.show();
		}
		else {
			this.Containers.Confirma.hide();
		}
		this.Containers.Loading.hide();
		Event.observe(this.Containers.Quiz,'click', this.handleClick.bindAsEventListener(this));
	},
	/** @private */
	quizLoadErrorHandler: function(event) {
		this.Containers.Loading.innerHTML = 'Erro ao carregar o Quiz';
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		if(elem == this.Buttons.Previous) {
			this.previousPergunta(event);
		}
		else if(elem == this.Buttons.Next) {
			this.nextPergunta(event);
		}
		else if(elem == this.Buttons.Confirm) {
			this.submitQuiz(event);
		}
		else if(elem.tagName == 'INPUT') {
			this.quizObj.perguntas[this.currentPergunta-1].selectedValue = elem.value;
			this.highlightContainer(Event.findElement(event,'li'));
		}
	},
	/** @private */
	highlightContainer: function(container) {
		var opcoes = this.Containers.Opcoes.select('li');
		for(var i = 0, len = opcoes.length ; i < len ; i++) {
			if(opcoes[i] == container) {
				opcoes[i].setStyle({
					background: 'url('+TeContei.IMG_SERVER+'40p.scale.fix.png)'
				});
			}
			else {
				opcoes[i].setStyle({
					background: 'url('+TeContei.IMG_SERVER+'20p.scale.fix.png)'
				});
			}
		}
	},
	/** @private */
	nextPergunta: function(event) {
		if(this.currentPergunta < this.numeroPerguntas) {
			if(this.currentPergunta == this.numeroPerguntas-1) {
				this.Containers.Confirma.show();
				this.Buttons.Next.hide();

			}
			this.changePergunta(this.currentPergunta+1);
		}
		Event.stop(event);
	},
	/** @private */
	previousPergunta: function(event) {
		if(this.currentPergunta > 1) {
			if(this.currentPergunta == this.numeroPerguntas) {
				this.Containers.Confirma.hide();
				this.Buttons.Next.show();
			}
			this.changePergunta(this.currentPergunta-1);
		}
		Event.stop(event);
	},
	/** @private */
	changePergunta: function(pergunta) {
		this.currentPergunta = pergunta;
		this.perguntaChanged();
	},
	/** @private */
	submitQuiz: function(event) {
		var nulo = this.quizObj.perguntas.find(function(pergunta){return pergunta.selectedValue==null});
		if(nulo) {
			var parameters = {
				content: TeContei.Dicionario.Quiz.Alertas.Incompleto,
				style: {
					height: '100px',
					width: '400px'
				}
			}
			TeContei.Widgets.ModalDialog.Show(parameters);
			Event.stop(event);
		}
		else {
			for(var i = 0, len = this.quizObj.perguntas.length ; i < len ; i++) {
				var elem = document.createElement('input');
				Element.writeAttribute(elem, {
					type: 'hidden',
					name: 'perguntas['+this.quizObj.perguntas[i].id+']',
					value: this.quizObj.perguntas[i].selectedValue
				});
				this.Containers.Quiz.appendChild(elem);
			}
		}
	},
	/** @private */
	perguntaChanged: function() {
		this.Containers.CurrentPergunta.innerHTML = this.currentPergunta;
		this.Labels.CurrentPergunta.innerHTML = this.currentPergunta;
		this.buildPergunta(this.currentPergunta);
		this.Labels.Pergunta.innerHTML = this.quizObj.perguntas[this.currentPergunta-1].titulo;
	},
	/** @private */
	buildPergunta: function(numero) {
		var opcoesArr = this.quizObj.perguntas[numero-1].opcoes;
		var len = opcoesArr.length;
		var hasSelected = false;
		var newHTML = '';
		for(var i = 0 ; i < len ; i++) {
			if(this.quizObj.perguntas[numero-1].selectedValue == opcoesArr[i].id) {
				newHTML += this.buildOpcao(opcoesArr[i],true);
				hasSelected = true;
			}
			else {
				newHTML += this.buildOpcao(opcoesArr[i],false);
			}
		}
		this.Containers.Opcoes.innerHTML = newHTML;
		if(hasSelected) {
			this.highlightContainer(this.Containers.Opcoes.down('input[checked]').up('li'));
		}
	},
	/** @private */
	buildOpcao: function(opcao,checked) {
		var opcaoHTML = '<li class="transp_20p"><div class="opcao"><div class="outer">';
		opcaoHTML += '<div class="middle"><div class="inner"><input name="opcao" type="radio" value="';
		opcaoHTML += opcao.id+'" '+(checked?'checked':'')+' /></div></div></div></div>';
		opcaoHTML += '<div class="resposta outer"><div class="middle"><div class="inner opcaoTexto">';
		opcaoHTML += opcao.texto;
		opcaoHTML += '</div></div></div></li>';
		return opcaoHTML;
	}
});

TeContei.Widgets.Enquete = Class.create({
	initialize: function(frm_el, enq_id) {
		this.el = $(frm_el);
		this.enquete_id = enq_id;
		var btn_votar = this.el.down('input.enquete-votar');
		if (btn_votar) {
			btn_votar.observe('click', this.votar.bind(this));
		}
	},

	getSelectedOpc: function(){
		var opcs = this.el.select('input[type=radio].enquete-opcao');
		for (var i = opcs.length-1; i >= 0; i--) {
			if (opcs[i].checked == true) {
				return opcs[i].value;
			}
		}
	},

	votar: function(evn) {
		Event.stop(evn);
		var selected_opc = this.getSelectedOpc();

		// Nenhuma opção selecionada
		if (Object.isUndefined(selected_opc)) {
			return;
		}

		var opcs = this.el.select('input[type=radio].enquete-opcao');
		var btn_votar = this.el.down('input.enquete-votar');

		var url = '/enquete/votar';
		new Ajax.Request(url, {
			method: 'post',
			parameters: 'enquete_id=' + this.enquete_id + '&opcao=' + selected_opc,
			evalJSON: true,
			onSuccess: function(transport) {
				var opcoes = transport.responseJSON;

				for (var index in opcoes) {
					var votos = opcoes[index].voto;
					opcs[index-1].up().update(opcoes[index].votos);
				}

				btn_votar.up().update();
			}
		});
	}
});

TeContei.Widgets.Video = Class.create(
/** @lends TeContei.Widgets.Video.prototype */
{
	/**
	 * Widget de controles do Video
	 *
	 * @param {Element} el O container do video
	 * @constructs
	 */
	initialize: function(el) {
		this.el = el;

		this.Avaliacao = {
			OpcaoId: el.down('input[name="opcao_id"]').value,
			JaVotou: el.down('input[name="ja_votou"]').value == 'true'
		}

		this.MediaNotas = $('video_nota').value;

		this.Video = {
			Id: el.down('input[name="video_id"]').value
		}

		this.Favorito = {
			Id: this.Video.Id,
			Tipo: TeContei.Favorito.Tipos[TeContei.View.Controller]
		}

		this.Buttons = {
			Estrelas: this.el.select('div.rating a.estrela'),
			Favorita: this.el.down('a.favorito'),
			Video: $('video_favorita_button')
		}

		for(var i=this.MediaNotas ; i > 0 ; i--) {
			this.Buttons.Estrelas[i-1].setStyle({backgroundPosition: '0px 0px'});
		}

		this.HasVinculo = this.Buttons.Favorita.hasClassName('invertido');

		if(this.Buttons.Favorita.hasClassName('disabled')) {
			return;
		}

		Event.observe(this.el, 'click', this.handleClick.bindAsEventListener(this));
		document.observe('favoritos:added',this.favoritoAdded.bindAsEventListener(this));
		document.observe('favoritos:removed',this.favoritoRemoved.bindAsEventListener(this));

		if(this.Avaliacao.JaVotou) {
			return;
		}

		Event.observe(this.el, 'mouseover', this.handleMouseOver.bindAsEventListener(this));
		document.observe('avaliacao:made',this.avaliacaoMade.bindAsEventListener(this));
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		if(elem == this.Buttons.Favorita) {
			if(!this.HasVinculo) {
				TeContei.Favorito.Add(this.Favorito);
			}
			else {
				TeContei.Favorito.Remove(this.Favorito);
			}
			Event.stop(event);
		}
		else if(elem.hasClassName('estrela') && !this.Avaliacao.JaVotou) {
			var avaliacao = {
				obj_id: this.Video.Id,
				obj_tipo: TeContei.Avaliacao.Tipos['video']
			}
			avaliacao['opcoes['+this.Avaliacao.OpcaoId+']'] = this.Buttons.Estrelas.indexOf(elem)+1,
			TeContei.Avaliacao.Make(avaliacao);
			Event.stop(event);
		}
	},
	/** @private */
	handleMouseOver: function(event) {
		var elem = Event.element(event);
		if(elem.hasClassName('estrela')) {
			var nota = this.Buttons.Estrelas.indexOf(elem)+1;
			for(var i=this.Buttons.Estrelas.length ; i > 0 ; i--) {
				if(i > nota) {
					this.Buttons.Estrelas[i-1].setStyle({backgroundPosition: '85px 0px'});
				}
				else {
					this.Buttons.Estrelas[i-1].setStyle({backgroundPosition: '0px 0px'});
				}
			}
			Event.stop(event);
		}
	},
	/** @private */
	favoritoAdded: function(event) {
		this.Buttons.Video.addClassName('invertido');
		this.Buttons.Video.innerHTML = ' '+TeContei.Dicionario.Toolbox.Labels.SouFa;
		this.HasVinculo = true;
	},
	/** @private */
	favoritoRemoved: function(event) {
		this.Buttons.Video.removeClassName('invertido');
		this.Buttons.Video.innerHTML = ' '+TeContei.Dicionario.Toolbox.Labels.Favorita;
		this.HasVinculo = false;
	},
	/** @private */
	avaliacaoMade: function(event) {
		this.Avaliacao.JaVotou = true;
		Event.stopObserving(this.el,'mouseover');
	}
});
/** @namespace */
TeContei.Widgets.ModalDialog = {
	Container: null,
	Box: null,
	/** @private */
	quickHide: true,
	/** @private */
	cachedClickHandler: null,
	/** @prviate */
	middle: false,
	Hide: function() {
		this.Container.hide();
		document.fire('modaldialog:hidden');
		Event.stopObserving(this.Container,'click',this.cachedClickHandler);
		Event.stopObserving(document,'modaldialog:trigger');
		if(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 7) {
			TeContei.Util.IE6Fix.UnregisterElement(this.Box);
		}
	},
	Show: function(parameters) {
		if(typeof(parameters) !== 'undefined') {
			if(typeof(parameters.style) !== 'undefined') {
				this.Box.setStyle(parameters.style);
			}
			if(typeof(parameters.content) !== 'undefined') {
				if(typeof(parameters.middle) !== 'undefined' && parameters.middle == true) {
					this.Box.down('div.conteudo').hide();
					this.Box.down('div.conteudo_middle').innerHTML = parameters.content;
					this.Box.down('div.outer').show();
				}
				else {
					this.Box.down('div.outer').hide();
					this.Box.down('div.conteudo').innerHTML = parameters.content;
					this.Box.down('div.conteudo').show();
				}
			}
			if(typeof(parameters.quickHide) !== 'undefined') {
				this.quickHide = parameters.quickHide;
			}
			if(typeof(parameters.title) !== 'undefined') {
				this.Box.down('span.title').innerHTML = parameters.title;
			}
		}
		this.Container.show();
		this.Box.down('div.outer').setStyle({height:this.Box.getHeight()+'px'});
		if(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 7) {
			var x = parseInt(document.viewport.getWidth()/2)-parseInt(this.Box.getWidth()/2);
			var y = parseInt(document.viewport.getHeight()/2)-parseInt(this.Box.getHeight()/2);
			this.Box.setStyle({top:y+'px',left:x+'px'});
			TeContei.Util.IE6Fix.RegisterElement(this.Box,x,y);
			this.Container.setStyle({height:$('wrapper').getHeight()+'px'});
		}
		else {
			this.Box.setStyle({
				marginLeft: -parseInt(this.Box.getWidth()/2)+'px',
				marginTop: -parseInt(this.Box.getHeight()/2)+'px'
			})
		}
		if(this.cachedClickHandler === null) {
			this.cachedClickHandler = this.handleClick.bind(this);
		}
		Event.observe(this.Container,'click',this.cachedClickHandler);
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		if(elem != this.Box) {
			if(elem.match('.modal_close_button') || elem.match('.close_button')) {
				this.Hide();
			}
			else if(this.quickHide && !elem.descendantOf(this.Box)) {
				this.Hide();
			}
			else if(elem.match('.modal_trigger')) {
				document.fire('modaldialog:trigger',elem);
			}
		}
	}
}
TeContei.Widgets.Indique = {
	Container: null,
	Services: {},
	Inputs: {},
	/** @private */
	isBusy: false,
	Initialize: function(el) {
		this.Container = el;

		this.Inputs.Destinatarios = el.down('textarea[name="destinatarios"]');
		this.Inputs.Mensagem = el.down('textarea[name="mensagem"]');
		this.Inputs.Url = el.down('input[name="url"]');

		Event.observe(el,'click',this.handleClick.bindAsEventListener(this));
		Event.observe(document,'indique:sent',this.sent.bindAsEventListener(this));
	},
	/** @private */
	handleClick: function(event) {
		var elem = Event.element(event);
		if(elem.match('input[name="enviar"]')) {
			Event.stop();
			this.enviar();
		}
		else if(elem.match('input[name="limpar"]')) {
			Event.stop();
			this.Container.down('form').reset();
		}
		else if(elem.match('.indique_button')) {
			var service_name = '';
			if(elem.hasClassName('indique_button_hotmail')) {
				service_name = 'hotmail';
			}
			else if(elem.hasClassName('indique_button_gmail')) {
				service_name = 'gmail';
			}
			else if(elem.hasClassName('indique_button_yahoo')) {
				service_name = 'yahoo';
			}
			else if(elem.hasClassName('indique_button_orkut')) {
				service_name = 'orkut';
			}
			else if(elem.hasClassName('indique_button_msn')) {
				service_name = 'msn';
			}
			this.Container.down('input[name="indique_service_name"]').value = service_name;
			var parameters = {
				style: {
					height: '300px',
					width: '500px'
				},
				title: TeContei.Dicionario.Indique.Alertas.Importar,
				content: this.Container.down('div.indique_login_screen').innerHTML,
				quickHide: false,
				middle: true
			}
			if(typeof(this.cachedLoginHandler) === 'undefined') {
				this.cachedLoginHandler = this.handleLogin.bindAsEventListener(this);
			}
			Event.observe(document,'modaldialog:trigger',this.cachedLoginHandler);
			TeContei.Widgets.ModalDialog.Show(parameters);
		}
	},
	handleLogin: function(event) {
		Event.stopObserving(document,'modaldialog:trigger',this.cachedLoginHandler);
		var elem = event.memo;
		var form = $(elem.form)
		if (!this.isBusy) {
			this.isBusy = true;
			new Ajax.Request(TeContei.URL+'proxy/importar_indique/',{
				method: 'post',
				parameters: {
					service_u: form.down('input[name="indique_login"]').value,
					service_p: form.down('input[name="indique_password"]').value,
					service: form.down('input[name="indique_service_name"]').value
				},
				onCreate: function() {
					var content = '<img src="'+TeContei.IMG_SERVER+'ajax_loading.gif" />';
					content += '<br />'+TeContei.Dicionario.Indique.Alertas.Aguarde;
					var parameters = {
						content: content,
						middle: true
					}
					TeContei.Widgets.ModalDialog.Show(parameters);
				},
				onSuccess: function(response) {
					var response = response.responseJSON;
					if(typeof(response.error) !== 'undefined') {
						this.handleImportError(response.error);
					}
					else {
						this.handleImportComplete(response);
					}
				}.bind(this),
				onComplete: function() {
					this.isBusy = false;
				}.bind(this)
			});
		}
	},
	/** @private */
	enviar: function() {
		if (!this.isBusy) {
			this.isBusy = true;
			new Ajax.Request(TeContei.URL+'proxy/indique/',{
				method: 'post',
				parameters: {
					destinatarios: this.Inputs.Destinatarios,
					mensagem: this.Inputs.Mensagem,
					url: this.Inputs.Url
				},
				onSuccess: function(response) {
					var response = response.responseJSON;
					document.fire('indique:sent', response);
				},
				onComplete: function() {
					this.isBusy = false;
				}.bind(this)
			});
		}
	},
	/** @private */
	sent: function() {

	},
	/** @private */
	handleImportError: function (errorMsg) {
		var parameters = {
			title: 'Erro',
			content: errorMsg,
			middle: true
		}
		TeContei.Widgets.ModalDialog.Show(parameters);
	},
	/** @private */
	handleImportComplete: function (contacts) {
		if(contacts.length == 0) {
			var parameters = {
				content: TeContei.Dicionario.Indique.Alertas.NenhumContato,
				middle: true
			}
			TeContei.Widgets.ModalDialog.Show(parameters);
			return;
		}
		var html = '';
		for(var i=0,len=contacts.length ; i < len ; i++) {
			html += '<tr>';
			html += '<td><input type="checkbox" name="email_'+i+'" /></td>';
			html += '<td>'+contacts[i].email+'</td>';
			html += '<td>'+contacts[i].name+'</td>';
			html += '</tr>';
		}
		this.Container.down('div.indique_contacts_table table tbody').update(html);
		var parameters = {
			style: {
				height: '300px',
				width: '500px'
			},
			title: TeContei.Dicionario.Indique.Alertas.Escolha,
			content: this.Container.down('div.indique_contacts_table').innerHTML
		}
		if(typeof(this.cachedSelectedHandler) === 'undefined') {
			this.cachedSelectedHandler = this.handleContactsSelected.bindAsEventListener(this);
		}
		Event.observe(document,'modaldialog:trigger',this.cachedSelectedHandler);
		TeContei.Widgets.ModalDialog.Show(parameters);
	},
	handleContactsSelected: function(event) {
		var inputs = $(event.memo).up().previous().down().select('input[type="checkbox"]').findAll(function(cb){return cb.checked});
		this.Inputs.Destinatarios.value.strip();
		for(var i=0,len=inputs.length ; i < len ; i++) {
			if(i != 0 || this.Inputs.Destinatarios.value != '') {
				this.Inputs.Destinatarios.value += ', '
			}
			this.Inputs.Destinatarios.value += inputs[i].up().next().innerHTML;
		}
		TeContei.Widgets.ModalDialog.Hide();
	}
};

TeContei.Widgets.TesteLux = Class.create({
	initialize: function(el) {
		this.container = $(el);
		this.pontuacao = 0;
		this.total_perguntas = 5;
		this.pergunta_atual = 1;
		this.url = TeContei.URL + 'testeperfil/get_opcoes/';

		this.getOpcoes(this.pergunta_atual);
	},

	clickHandler: function(i) {
		this.opcaoSelected(i);
		return false;
	},

	opcaoSelected: function(value) {
		this.pontuacao += parseInt(value);
		if (this.pergunta_atual < this.total_perguntas) {
			this.getOpcoes(this.pergunta_atual+1);
		}
		else {
			var url = TeContei.URL + 'testeperfil/resultado/' + this.pontuacao;
			window.location.assign(url);
		}
	},

	getOpcoes: function(pergunta_id) {
		/*var html = '<p style="padding-top: 140px;">';
		html += '<img src="http://img.estatico.bolsademulher.com/ajax_loading_ffffff_ff0099.gif" /><br />';
		html += 'Carregando, por favor aguarde...';
		html += '</p>';*/

		this.pergunta_atual = parseInt($F('pergunta_atual')) + 1;
		$('pergunta_atual').value = this.pergunta_atual;
		new Ajax.Request(this.url + pergunta_id, {
			method: 'get',
			onSuccess: function(transport) {
				var perg = transport.responseJSON;
				var pergunta_atual = $F('pergunta_atual');

				$('tc-testeperfillux').down('span.passo').innerHTML = pergunta_atual;
				$('tc-testeperfillux').down('div.tc-teste-pergunta').innerHTML = perg.pergunta;

				var resp = perg.respostas.toArray();

				var html = '';
				for (var i=0,len = resp.length ; i < len ; i++) {
					html += '<a href="#" onclick="javascript:return TeContei.Containers.TesteLux.clickHandler('+resp[i].pontos+');" class="tc-teste-opc">';
					html += '<img src="' + TeContei.IMG_SERVER + 'testelux/' + resp[i].img + '" height="150" width="150" style="display: block;float:left;margin: 5px;" />';
					html += '<input type="hidden" name="resposta['+resp[i].id+']" value="' + resp[i].pontos + '" />';
					html += '</a>';
				}
				html += '<div class="cleaner"></div>';
				$('tc-teste-imgs').update(html);
			}
		});
	}
});

/** @ignore */
Event.observe(window, 'load', function() {
	TeContei.Widgets.ModalDialog.Container = $('modal_container');
	TeContei.Widgets.ModalDialog.Box = $('modal_box');

	var galeria = $('galeria');
	if(galeria != null) {
		TeContei.Containers.Galeria = new TeContei.Widgets.Galeria(galeria, $F('tc-galeria-foto-idx'));
	}
	var quiz = $('quiz_container');
	if(quiz != null) {
		TeContei.Containers.Quiz = new TeContei.Widgets.Quiz(quiz);
	}
	var video = $('video_controles');
	if(video != null) {
		TeContei.Containers.Video = new TeContei.Widgets.Video(video);
	}
	var indique = $('indique');
	if(indique != null) {
		TeContei.Widgets.Indique.Initialize(indique);
	}
	var testelux = $('tc-testeperfillux');
	if (testelux != null) {
		TeContei.Containers.TesteLux = new TeContei.Widgets.TesteLux(testelux);
	}
	var newsbutton = $('sidebar_newsletter_button');
	if(newsbutton != null) {
		Event.observe(newsbutton,'click',function(event) {
			var email = $('sidebar_newsletter_input').value;
			window.location.href = 'http://www.bolsademulher.com/cadastro/?frm_email='+email;
			Event.stop(event);
		});
	}
});

