/**
 * @author MARTINSP <paulo.martins@wunderman.com>
 */

var promotion = {
	all: '',
	active: '',
	current: '',
	cultural_frase: '',
	cultural_ca1: '',
	cultural_ca2: '',
	options: {},
	type: ''
};

var frases = {
	participe : {
		foto: "Concorra a uma camisa oficial da Sele��o Brasileira autografada pelos jogadores. Para participar, envie uma foto, entre os dias 31/05 e 08/06, que demonstre a sua paix�o pela Sele��o. Ser�o dois vencedores, portanto, participe! Clique no bot�o abaixo, leia o regulamento e envie a sua foto.",
		video: "",
		concurso: "",
		quiz: "Suas chances de ganhar s�o proporcionais ao seu conhecimento. Boa sorte!",
		participacao: ""
	},
	especificacoes: {
		video: "<label>M&aacute;ximo:</label> 5120 kb (5MB) | <label>Extens&otilde;es:</label> mov, avi, mpeg, wmv, mpg",
		imagem: "<label>M&aacute;ximo:</label> 1024 kb (1MB) | <label>Extens&otilde;es:</label> jpg, jpge, gif, png, bmp, tif, tiff"
	}
};

var promotypes = {
	init: function(tp,options) {
		promotion.options = options;
		frases.participacao = options.participacao;
		
		var frase_participe = null,
			types = tp ? tp : '';
		
		if (types.indexOf('F') != -1) {
			frase_participe = frases.participe.foto;
			promotion.active = 'foto';
		}
		else {
			if (types.indexOf('V') != -1) {
				frase_participe = frases.participe.video;
				promotion.active = 'video';
			}
			else {
				if (types.indexOf('C') != -1) { 
					frase_participe = frases.participe.concurso;
					promotion.active = 'concurso';
				}
				else {
					if (types.indexOf('Q') != -1) { 
						frase_participe = frases.participe.quiz;
						promotion.active = 'quiz';
					}
					else {
						if (types.indexOf('P') != -1) {
							promotion.active = 'fim';
						}
						else {
							$('div#promoEnrollment p').html('Promo&ccedil;&atilde;o inv&aacute;lida!');
							return;
						}
					}
				}
			}
		}
		
		promotion.all = types;
		isLogged();
		//$('div#promoEnrollment span').html(frase_participe).css('display','block');
	}
};

var isLogged = function() {
	$.getJSON('../../promotypes/php/services.php', {cmd: 'isLogged'}, function(json){
		if (json === 'ok') {
			$.getJSON('../../promotypes/php/services.php', {cmd: 'firstEnrollment'}, function(json){
				if (json === 'ok') {
					$('#enrollmentInfo').empty();
					$('#enrollment').css('display', 'block').click(function(e){
						$('#promoEnrollment, div.promo_descr').remove();
						ext = '.html';
						e.preventDefault();
						$.get(
							'../../promotypes/templates/' + promotion.active + ext,
							function(data) {
								$('#promoWrapper').html(data).show();
								$('#promoWrapper div:eq(0)').show();
								$('#promoWrapper p#promoTxt').html(frases.participacao);
								
								if(promotion.active == 'quiz') {
									//e.preventDefault();
									startQuiz();
								}
								if(promotion.active == 'foto') {
									var promoarea = location.href,
										promodir = '';
									
									if(promoarea.indexOf('interno') != -1 || promoarea.indexOf('trade') != -1) {
										promodir = '../';
									}
									
									foto();
									$("#snapShotLink").fancybox({
										'padding'			: 0,
										'autoScale'			: false,
										'transitionIn'		: 'none',
										'transitionOut'		: 'none',
										'width'				: 548,
										'height'			: 507,
										'swf': {wmode: 'transparent', flashvars: 'service_link='+promodir+'promotypes/php/webcam.php'}
									});		
								}
								if(promotion.active == 'concurso') {
									$('em#valor').html(promotion.options.tamanho_texto);
									
									if(promotion.options.campo_adicional_1 && promotion.options.campo_adicional_1 != '') {
										$('p#ca1').show();
										$('p#ca1 label').html(promotion.options.campo_adicional_1);
									}
									if(promotion.options.campo_adicional_2 && promotion.options.campo_adicional_2 != '') {
										$('p#ca2').show();
										$('p#ca2 label').html(promotion.options.campo_adicional_2);
									}
									if(promotion.options.label_textarea != '') {
										$('p#ta label').html(promotion.options.label_textarea);
									}
									startConcurso();
								}
								if(promotion.active == 'video') {
									startVideo();
								}
								if(promotion.active == 'fim') {
									finishPromotion();
								}
							}
						);
						
					});
				}
				else {
					$('#enrollmentInfo').html('Voc&ecirc; j&aacute; participou desta promo&ccedil;&atilde;o.');	
				}
			});			
		}
		else {
			$('#enrollmentInfo').html('Para participar, efetue seu login ou fa&ccedil;a seu cadastro.');
		}		
	});
};

var Quiz = function(servicePath) {
	this.servicePath = servicePath;
	this.data = null;
	this.questionCount = 0;
	this.currentQuestion  = 0;
	this.nextButton = $('#nextQuestion');
	this.prevButton = $('#prevQuestion');
	this.finishButton = $('#finish');
	this.acceptButton = $('#accept');
	this.answers = [];
};

var startQuiz = function(tp) {
	var qsa = new Quiz('/promotypes/php/services.php');
	qsa.getData(function() {
		$('#quizEnrollment').remove();
		$('#quizWrapper').show();
		qsa.changeQuestion(0);
		qsa.eventNextButton();
		qsa.eventPrevButton();
		qsa.eventFinish(tp);
	});
};

Quiz.prototype = {
	
	getData: function(cb) {
		
		var cb = cb || function() {};
		var that = this;
		
		$.getJSON(this.servicePath, {cmd: 'getQuizData', id: this.id}, function(json){
			
			that.data = json;
			that.questionCount = json.length;
			cb();
		});	
	},
	
	populateGrid: function(questionNumber) {
		
		var data = this.data[questionNumber];
		
		$('dt').empty().html('<em>' + (questionNumber + 1) + '.</em> ' + data.description);
		
		var ulElement = $('dl dd ul').empty();
		
		for (var i = 0; i < data.answers.length; i++) {
			
			ulElement.append(
				'<li>' + 
				"<input type='radio' name='answer' />" + '<div>' +  
					data.answers[i].description 
				+ '</div></li>'
			);
		}		
	},
	
	isLastQuestion: function() {
		return (this.currentQuestion === this.questionCount - 1);
	},
	
	changeQuestion: function(questionNumber) {
		
		this.populateGrid(questionNumber);
		
		this.eventSelectAnswer();
		
		this.hideNextButton();
		this.hideFinishButton();
		this.hideAcceptButton();
		
		if (this.currentQuestion > 0) {
			this.showPrevButton();
		}
		
		if (this.currentQuestion == 0) {
			this.hidePrevButton();
		}
		
		if (typeof this.answers[questionNumber] === 'number') {
			$($('dd input')[this.answers[questionNumber]]).attr('checked', 'checked');
			if (!this.isLastQuestion()) {
				this.showNextButton();	
			}
			else {
				this.showFinishButton();
				this.showAcceptButton();
			}
		}
	},
	
	eventSelectAnswer: function() {
		
		var checks = $('dd input'), that = this;
		
		checks.click(function(){
			that.showNextButton();
			var indexResponse = $('dd input').index($('dd input:checked'));
			that.answers[that.currentQuestion] = indexResponse;
			
			that.hideFinishButton();
			
			if (that.currentQuestion === that.questionCount - 1) {
				that.hideNextButton();
				that.showFinishButton();
				//that.showAcceptButton();
			}
		});
	},
	
	eventNextButton: function() {
		
		var that = this;
		
		this.nextButton.click(function(e){
			
			e.preventDefault();
			that.currentQuestion++;
			that.changeQuestion(that.currentQuestion);
		});
	},
	
	eventPrevButton: function() {
		
		var that = this;
		
		this.prevButton.click(function(e){
			e.preventDefault();
			that.currentQuestion--;
			that.changeQuestion(that.currentQuestion);
		});
	},
	
	eventFinish: function(tp) {
		
		var that = this;
		
		this.finishButton.click(function(e){

			e.preventDefault();
			
			$('div#wrapper').empty();
			
			$.getJSON(that.servicePath, {
				cmd: 'saveQuiz',
				data: that.enrichData()
			}, function(json){
				
				if(json === 'ok') {
					if (promotion.all.indexOf(type(tp)) != -1 ) {
						loadNextPromoType();
						$('a#nextType').click();
					} else {
						finishPromotion();
						$("a#finishPromotion").click();
					}
					return					
				}
				
				alert('Ocorreu um erro. Por favor, tente novamente'); 
			});
		});
	},
	
	enrichData: function() {
		
		var data = [];
		
		for (var i = 0; i < this.answers.length; i++) {
			
			data.push({
				'question_id': this.data[i].question_id,
				'answer_id': this.data[i].answers[this.answers[i]].answer_id
			});	
		}
		return JSON.stringify(data);
	},
	
	showSucces: function() {},
	
	showNextButton: function() {
		this.nextButton.css('display','block');
	},
	
	hideNextButton: function() {
		this.nextButton.hide();
	},
	
	showPrevButton: function() {
		this.prevButton.css('display','block');
	},
	
	hidePrevButton: function() {
		this.prevButton.hide();
	},
	
	showFinishButton : function() {
		this.finishButton.css('display','block');
	},
	
	hideFinishButton : function() {
		this.finishButton.hide();
	},
	
	showAcceptButton : function() {
		this.acceptButton.css('display','block');
	},
	
	hideAcceptButton : function() {
		this.acceptButton.hide();
	}
	
};

var prepareUpload = function(type, tp) {
	promotion.type = type;
	type = type ? '?type=' + type : '';
	new AjaxUpload('uploadButton', {
		action: '/promotypes/php/upload.php' + type,
		name: 'userfile',
		data: {
			promoid: $("input[name='promoid']").val(),
			promoarea: $("input[name='promoarea']").val()
		},
		autoSubmit: true,
		responseType: false,
		onChange: function(file, extension){
			$('span#file_name').text(file).css('background','#ffffff url(../../promotypes/img/loader.gif) no-repeat 315px center');
			$('p#uploadInfo').removeClass('error').html('Aguarde! Verificando arquivo.');
			$('a#uploadButton').hide();
		},
		onSubmit: function(file, extension) {},
		onComplete: function(file, response) {
			$('span#file_name').css('background','#ffffff');
			$('a#uploadButton').show();
			if (response === 'success') {
				if(promotion.type == 'videos'){$('p#uploadInfo').removeClass('error').html(frases.especificacoes.video);}
				else{$('p#uploadInfo').removeClass('error').html(frases.especificacoes.imagem);}
				$('a#sendButton').show();
				
				$('a#sendButton').unbind('click');
				$('a#sendButton').bind('click', function(){
					$('#uploadContainer').hide();
					if (promotion.type == 'videos') {
						$('#success').addClass('video').show();
					} else {
						$('#success').show();
					}
					
					if (promotion.all.indexOf(type(tp)) != -1 ) {
						$('#nextType').css('display', 'block');
						
						if (promotion.type == 'videos') {
							if (promotion.all.indexOf('C') != -1) {
								loadNextPromoType('concurso');
							}
							else {
								if (promotion.all.indexOf('Q') != -1) {
									loadNextPromoType('quiz');
								}
								else {
									loadNextPromoType();
								}
							}
						}
						else {
							if (promotion.all.indexOf('V') != -1) {
								loadNextPromoType('video');
							}
							else {
								if (promotion.all.indexOf('C') != -1) {
									loadNextPromoType('concurso');
								}
								else {
									if (promotion.all.indexOf('Q') != -1) {
										loadNextPromoType('quiz');
									}
									else {
										loadNextPromoType();
									}
								}
							}
						}
					} else {
						finishPromotion();
						$("div#fimWrapper").css('display','block');
					}
					
				return false;
				});
				return;
			}
			
			if (response === 'not-image')
			{
				$('a#sendButton').hide();
				$('p#uploadInfo').addClass('error').html('O arquivo enviado n&atilde;o &eacute; uma imagem v&aacute;lida! Tente novamente.');
				return;
			}
			
			if (response === 'big')
			{
				$('a#sendButton').hide();
				$('p#uploadInfo').addClass('error').html('Arquivo muito <strong>grande</strong>, tamanho m&aacute;ximo 1024 kb');
				return;
			}
			
			if (response === 'not-video')
			{
				$('a#sendButton').hide();
				$('p#uploadInfo').addClass('error').html('O arquivo enviado n&atilde;o &eacute; um v&iacute;deo v&aacute;lido! Tente novamente.');
				return;
			}
			
			if (response === 'big-video')
			{
				$('a#sendButton').hide();
				$('p#uploadInfo').addClass('error').html('Arquivo muito <strong>grande</strong>, tamanho m&aacute;ximo 5120 kb');
				return;
			}
			
			$('a#sendButton').hide();
			alert('Ocorreu um erro, tente novamente mais tarde!');
		}
	});
};

var foto = function() {
	$('#photo').click(function(e){
		e.preventDefault();
		
		$('#sendMethods').hide();
		$('#uploadContainer').show();
		
		prepareUpload();
	});
	
	$('#uploadCancel').click(function(e){
		e.preventDefault();
		
		$('#sendMethods').show();
		$('#uploadContainer').hide();
	});
};

var closeWebcam = function() {
	$.fancybox.close();
	$('#sendMethods').hide();
	$('#success').show();
	$('#nextType').css('display','block');
	loadNextPromoType('video');
	return;
};

var startConcurso = function(tp) {
	$("textarea[name='textoCultural']").keyup(function(){
		if($(this).val()){
			if (promotion.all.indexOf(type(tp)) != -1 ) {
				$("a#nextType").css('display','block');
			} else {
				finishPromotion();
				$("div#fimWrapper").css('display','block');
			}
		}
		else {
			if (promotion.all.indexOf(type(tp)) != -1 ) {
				alert("F");
				$("a#nextType").css('display','none');
			} else {
				$("div#fimWrapper").css('display','none');
			}
		}
});
	
	$("textarea[name='textoCultural']").blur(function(){
		
		if (promotion.all.indexOf('Q') != -1) {
			loadNextPromoType('quiz','concurso');
		}
		else {
			loadNextPromoType(null,'concurso');
		}
	});
};

var loadNextPromoType = function(tp,pmt) {
	if(pmt=='concurso') {
		promotion.cultural_frase = $("textarea[name='textoCultural']").val();
		promotion.cultural_ca1 = $("input[name='campo_adicional_1']").val();
		promotion.cultural_ca2 = $("input[name='campo_adicional_2']").val();
	}
	$('a#nextType').unbind('click');
	$('a#nextType').bind('click', function(){
		$('div#promoWrapper').html('');
		
		if (promotion.all.indexOf(type(tp)) != -1 ) {
			$.get('/promotypes/templates/' + tp + '.html', function(data){
				$('div#promoWrapper').html(data);
				$('#promoWrapper div:eq(0)').show();
				if (tp == 'quiz') {
					startQuiz(tp);
				}
				if (tp == 'concurso') {
					$('em#valor').html(promotion.options.tamanho_texto);
									
					if(promotion.options.campo_adicional_1 && promotion.options.campo_adicional_1 != '') {
						$('p#ca1').show();
						$('p#ca1 label').html(promotion.options.campo_adicional_1);
					}
					if(promotion.options.campo_adicional_2 && promotion.options.campo_adicional_2 != '') {
						$('p#ca2').show();
						$('p#ca2 label').html(promotion.options.campo_adicional_2);
					}
					if(promotion.options.label_textarea != '') {
						$('p#ta label').html(promotion.options.label_textarea);
					}
					
					startConcurso(tp);
				}
				if (tp == 'video') {
					startVideo(tp);
				}
			});
		}
		else {
			$.get('/promotypes/templates/fim.html', function(data){
				//$('div#fimWrapper').html(data);
				//$('a#nextType').css('display','none');
				//finishPromotion();
			});
		}
	return false;
	});
};

var preparaConcurso = function() {
	$.getJSON('/promotypes/php/services.php',
		{
			cmd: 'saveCultural',
			frase: promotion.cultural_frase,
			ca1: promotion.cultural_ca1,
			ca2: promotion.cultural_ca2
		},
		function(json){}
	);
};

var preparaParticipe = function() {
	$.getJSON('/promotypes/php/services.php',
		{
			cmd: 'saveParticipe',
			frase: promotion.cultural_frase,
			ca1: promotion.cultural_ca1,
			ca2: promotion.cultural_ca2
		},
		function(json){}
	);
};

var finishPromotion = function() {
	$('a#finishPromotion').css('display','block');
	$('label#accept').show();
	$('a#finishPromotion').click(function(){
		var vl = false;
		
		if ($('label#accept input:checked').length < 1) {
			alert('Por favor, aceite os termos');
			return false;
		}
		
		if(promotion.all.indexOf('C') != -1) {
			preparaConcurso();
		}
		
		if(promotion.all.indexOf('P') != -1) {
			preparaParticipe();
		}
		
		if(promotion.active == 'quiz') {
			$('div#fimWrapper').prev().toggle();
			$('div#fimWrapper').prev().prev().toggle();
			$('div#fimWrapper').prev().prev().prev().toggle();
			$('div#fimWrapper').prev().prev().prev().prev().toggle();
		}
		
		$('div#fimWrapper').html("<p class='txt'>Obrigado por participar da promo&ccedil;&atilde;o. Seus dados foram enviados com sucesso.</p>").show();
		return false;
	});
};

var type = function(t) {
	switch(t)
	{
		case 'foto':
			return 'F';
			break;
		
		case 'video':
			return 'V';
			break;
				
		case 'concurso':
			return 'C';
			break;
			
		case 'quiz':
			return 'Q';
			break;
			
		default:
			return null;
	}
};

startVideo = function(tp) {
	$('li#photo').click(function(){
		$(this).parent().hide();
		$('div#uploadContainer').css('display','block');
	});
	
	prepareUpload('videos', tp);
};
