var Tabs = function(selector) {
	
	var that = this;
	
	this.root = $(selector);
	
	this.chosenFiles = new ChosenFiles(this);
	
	this.currentArea = '';
	this.ajaxUploader = false;
	this.isBusy = false;
	this.doubtId = false;
	this.inModal = false;	
	this.swfCallBackName = false;
	
	this.init = function() {

		this.root.find('.linkUrl').inputPlaceHolder();
		
		this.root.find('.tabs a').unbind('click');
		
		this.onClick();
		this.onSend();
		
		this.events.upload();
		this.events.link();
		this.events.webcam();
	};
	
	this.close = function() {
		that.currentArea = '';
		that.chosenFiles.init();
		that.root.find('.tabs a').removeClass('active');
		that.root.find('.info').hide();
	};
	
	this.showArea = {
	
		photo: function(){
			
			that.root.find('.infoPhotoVideo').removeClass('video').addClass(that.currentArea).show();
			that.ajaxUploader.setParams({
				'source_type': 'upload', 'media_type': 'image'
			});
			that.root.find('.sendButtons li').hide();
			that.root.find('.sendMethods label').hide();
			that.root.find('.sendMethods ul li a').removeClass('active');
			that.root.find('.snapshot').show();
			that.root.find('.record').hide();
			that.root.find('.sendMethods .msg').hide();
			that.root.find('.sendMethods .obs').html('Máximo de 5MB. Formatos: JPG, GIF ou PNG.');
		
		},
		video: function(){
			
			that.root.find('.infoPhotoVideo').removeClass('photo').addClass(that.currentArea).show();
			that.ajaxUploader.setParams({
					'source_type': 'video_upload', 'media_type': 'video'
			});
			that.root.find('.sendButtons li').hide();
			that.root.find('.sendMethods label').hide();
			that.root.find('.sendMethods ul li a').removeClass('active');
			that.root.find('.snapshot').hide();
			that.root.find('.record').show();
			that.root.find('.sendMethods .msg').hide();
			that.root.find('.sendMethods .obs').html('Máximo de 5MB ou 30s.');
					
		},
		voce: function(){
			
			that.root.find('.infoVoce').show();
		},
		evento: function(){
			
			that.root.find('.infoEvento').show();
		}
	};
	
	this.showSendLoader = function(){
			that.root.find('.linkUrl, addFile_webcam, .addFile_link, .addFile_upload').hide();
			that.root.find('.sendLoader').show();
			that.isBusy = true;
	};
	
	this.hideSendLoader = function(){
			that.root.find('.linkUrl, addFile_webcam, .addFile_link, .addFile_upload').show();
			that.root.find('.sendLoader').hide();
			that.isBusy = false;
	};
	
	this.onClick = function(){
	
		that.root.find('.tabs a').click(function(e){
		
			e.preventDefault();
			var clickedArea = $(this).parent().attr('data-area');
			that.root.find('.tabs a').removeClass('active');
			that.root.find('.info').removeClass('bgActive');
			
			if ( ! that.inModal && clickedArea === that.currentArea) {
				that.root.find('.info').hide();
				that.currentArea = '';
				return;
			}
			
			that.root.find('.info').hide();
			that.root.find('.info').addClass('bgActive');
			$(this).addClass('active');
			that.currentArea = clickedArea;
			that.showArea[that.currentArea]();
		});
	};
	
	this.onSend = function(){
		
		that.root.find('.sendChoices li').click(function(e){
			
			that.root.find('.sendMethods ul li a').removeClass('active');

			$(this).find('a').addClass('active');
			var sendButtons = that.root.find('.sendButtons li.action').hide();
					index = $(this).index('#' + that.root.attr('id') + ' .sendChoices li'); // todo: muito ruim
					$(sendButtons[index]).show();
					
					
		});
	};
	
	this.checkSuccess = function(json){
	
			that.hideSendLoader();
			
			var errorCodes = {
					'default': 'Erro no envio do arquivo. Por favor, tente novamente',
					'format': 'O arquivo não é uma imagem válida. Formatos aceitos: JPG, GIF e PNG',
					'size': 'O arquivo enviado é grande demais.',
					'duration': 'O vídeo enviado é longo demais.'
					}, 
					errorMsg = errorCodes['default'];
					
			if (that.currentArea === 'video') {
				errorCodes.format = 'O vídeo não tem um formato válido. Por favor, tente um outro tipo de arquivo';
			}
			
			if (!json || json.success === false) {
					
					if (json && json.error_code) {
						errorMsg = errorCodes[json.error_code];
					}
					
					var onClose = function() {};
					if (that.inModal) {
						onClose = function() {
							$('#mediaModal').data('overlay').load();
							$('#messageModal').data('overlay').onClose = function() {};
						};
					}
					
					cqlook.showMessageModal(errorMsg, 'error', onClose);
					return;
			}
			
			that.chosenFiles.addFile(json.data);
	};
	
	this.events = {

		upload: function(){
		
			that.ajaxUploader = new qq.FileUploader({
				element: that.root.find('.addFile_upload')[0],
				action: '/services/media/add_post_media',
				params: {
						source_type: 'upload',
						media_type: 'image'
				},
				onSubmit: function() { that.showSendLoader();},
				onComplete: function(id, fileName, json){
						that.checkSuccess(json);
				}
			});
			
		},
		
		link: function(){
		
			that.root.find('.addFile_link').unbind('click.send').bind('click.send', function(e){
			
				e.preventDefault();
				
				that.showSendLoader();
				
				var	data = {
					source_type: 'link',
					'link': that.root.find('.linkUrl').val(),
					media_type: function() {
						if (that.currentArea === 'photo') {
							return 'image';
						}
						return 'video';	
					}()
				};
						
				$.ajax({
					type: "POST",
					dataType: 'json',
					url: '/services/media/add_post_media',
					'data': data,
					timeout: 50000,
					error: function() {
						that.checkSuccess({success: false})
					},
					success: function(json) {
						that.root.find('.linkUrl').data('placeholder').resetOriginal();
						that.checkSuccess(json);
					}
				});
			});
		},
		
		webcam: function(){
		
				that.root.find('.addFile_webcam').unbind('click.send').bind('click.send', function(e){
				
					e.preventDefault();
					var swfFile;
					
					if (that.currentArea === 'photo') {
						swfFile = 'snapshot.swf';
					}
					else {
						swfFile = 'record.swf';
					}
					
					var embedFlash = function() {

						that.embedDoubtId(function(doubt_id){
					
							$("#swfModal").empty().append("<div id='swf' />").data("overlay").load();
							
							$("#swf").flashembed({
								src: "/swf/" + swfFile,
								wmode: 'window'
							}, {
								DOUBT_ID: doubt_id,
								SERVICE_URL: '/services/media/add_post_media',
								CALLBACK: that.swfCallBackName
							});
						});								
					};
					
					if (that.inModal) {
						
						var mediaModal = $('#mediaModal').data('overlay'),
								swfModal = $('#swfModal').data('overlay');
								
						mediaModal.onClose = embedFlash;
						
						swfModal.onClose = function(){
							mediaModal.load();
							mediaModal.onClose = function() {};
						};
						
						mediaModal.close();
					}
					else {
						embedFlash();	
					}
			});
		}
	};
	
	this.endSwf = function(json){
  
  	if (json) {
  		if (typeof json === 'string') {
  			json = $.parseJSON(json);
  		}
  		
  		that.chosenFiles.addFile(json.data);
	}
  	
  	var swfModal = $("#swfModal").data("overlay");
  	
		if (that.inModal) {
  		swfModal.onClose = function(){
				$('#mediaModal').data('overlay').load().onClose = function() {};
				swfModal.onClose = function() {};
	  	}
  	}
  	else {
  		swfModal.onClose = function() {};
		}
  
		swfModal.close();
	};
	
	this.embedDoubtId = function(fn){

		if (that.doubtId) {
			fn(that.doubtId);
			return;
		}
		
		that.doubtId = 0;
		fn(0);
	};	
};

