var xpto;


$(function(){
	post.likes();
	post.switches();
	post.report();
	post.answers();
	post.init();
	favorite.init();
	favorite.events();
	
	if (typeof sortFilter !== 'undefined') {
		$('.sort option[value=' + sortFilter + ']').attr('selected', 'selected');
	}
	
	$('.answer textarea').focus(function(){
		$(this).next().children().show();
	});	
	
	
	$('.sort select').change(function(){
		
		 if ($(this).find('option:selected').val() === '') {
			return;
		}
		
		$('.sort').submit();
	});
	
	$('.remove').live('click', function(){
		
		var aHref = $(this),
				post_id = aHref.attr('data-post-id'),
				modal = $('#removeModal'),
				text = aHref.parent().prev().find('.original').html(),	
				author = aHref.parent().prev().find('cite a').text(),
				src = aHref.parent().prev().prev().find('img').attr('src');
				
		modal.find('p').html(text);
		modal.find('#author').text(author);				
		modal.find('#avatar').attr('src', src);

		modal.data('overlay').load();
		
		modal.find('.btn').unbind('click').click(function(){
			
			$.getJSON('/services/post/remove_post', {'post_id': post_id}, function(json){
				
				if (json.success === true) {
					$('#messageModal').removeClass('interactModal');
					cqlook.showMessageModal('O comentário foi excluído com sucesso!', 'ok', function(){
						window.location.href = window.location.pathname;
					});
				}
			});
		});
	});
	
	$('.went a').live('click', function(){
		var went = $(this),
				textarea = went.parent().parent().parent().find('textarea');
		
		went.toggleClass('active');
		textarea.data('placeholder', null);
		
		/*/console.log(textarea.text());
		
		if (went.hasClass('active')) {
			if(textarea.text() == 'escreva sua resposta...')
				textarea.text('escreva como você foi...');
		}
		else {
			if(textarea.text() == 'escreva como você foi...')
				textarea.text('escreva sua resposta...');
		}
		
		//textarea.inputPlaceHolder();*/
	});
	
	PrepareMedia.init();
	moreAnswers();
});


var moreAnswers = function() {

	$('.moreAnswers').each(function(){
		
		var moreAnswers = $(this),
			questionLi = moreAnswers.parent(),
		    postId = questionLi.find('div.question').attr('data-post-id'),
		    answers = questionLi.find('.answers>li'),
		    total = answers.length;
		
		if (total <= 3)
		    return;

		moreAnswers.click(function(e){
		    
		    e.preventDefault();
		    answers.slideDown()
		    moreAnswers.hide()
			moreAnswers.next().show();
		}).show();	
	});
};

var PrepareMedia =   {
	
	type: null,
	
	go: function() {
			$.getJSON('/services/post/prepare_media');
	},
	
	getType: function() {
		return type;
	},
	
	init: function() {
		
		$('#doubt .sendChoices li a').click(function(){
		
			if (PrepareMedia.type === 'question') return;
			
			tabs.chosenFiles.init()
			PrepareMedia.type = 'question';
			PrepareMedia.go();
		});
	}

};	

var favorite = function() {
	
	var modal, populate = function(data) {
		
		modal.find('#avatar').attr('src', data.avatar_uri);
		modal.find('#author').text(data.author);
		modal.find('#description').html(data.description);
		
		modal.data('overlay').load();
	};				
	
	return {
		init: function() {
			modal = $('#favoriteModal');
			
		},
		events: function(){
			$('.favorite').live('click', function(){
				var favorite = $(this), data = {
					avatar_uri: favorite.parent().prev().find('img').attr('src'),
					author: favorite.next().text(),
					description: favorite.next().next().html(),
					comment_id: post.getPostId(favorite)
				};
				
				if (favorite.hasClass('favorited'))
					return;
				
				populate(data);
				
				modal.find('.btn').unbind('click').click(function(){
					
					modal.data('overlay').close();
					cqlook.loader.show();
					
					$.getJSON('/services/post/set_favorite', {comment_id: data.comment_id}, function(json){
						
						cqlook.loader.hide();
						
						if (json.success === true) {
							favorite.unbind('click').addClass('favorited');
							$('.favorite').not('.favorited').remove();
							$('#messageModal').removeClass('interactModal');
							cqlook.showMessageModal('O comentário foi favoritado com sucesso!', 'ok');	
							return;
						}
						$('#messageModal').removeClass('interactModal');
						cqlook.showMessageModal('Ocorreu um erro', 'error');
					})
				});
			});
		}
	}					
}();
			
var post = {
	
	Tabs: null,
	
	init: function() {
		
		post.Tabs = new Tabs('#mediaModal');
		post.Tabs.swfCallBackName = 'post.Tabs.endSwf';
		post.Tabs.inModal = true;
		post.Tabs.init();
		post.Tabs.chosenFiles.init();
		
		$('#mediaModal a.close').click(function(){
    	PrepareMedia.go();
			post.Tabs.init();
			post.Tabs.chosenFiles.init();
		});
		
		$('li.what p').each(function (i) {
			var cont =  $(this).find('span').text()
			if(cont.length >20){
			$(this).find('span').text(cont.substr(0,20)+'...')
			}
		});

		
		
	},
  
	switches: function(){
    
		$('.private a').bind('click.liked', function(){
      
			var aHref = $(this),
          id = post.getPostId(aHref),
					text = 'Deseja ocultar esta pergunta?';
					
			if (aHref.hasClass('active')) {
				text = 'Deseja mostrar esta pergunta para todos?';
			}
			$('#messageModal').removeClass('interactModal');
			var modalContainer = cqlook.showMessageModal(text + '<ul id="privateConfirm"><li id="yes" class="btn">sim</li><li id="no" class="btn">não</li></ul>', 'warning'),
					modal = modalContainer.data('overlay');
					
				modal.onClose = function() {
					modalContainer.find('ul').remove();
				};
				
				modalContainer.find('#yes').click(function(){
					$.getJSON('/services/post/switch_privacy', {post_id: id}, function(json){
		        if (json.data.is_private) {
		          aHref.addClass('active');
		        }
		        else {
		          aHref.removeClass('active');
		        }
						modal.close();
		      });						
				});
				
				modalContainer.find('#no').click(function(){
					modal.close();
				});
    }); 
		
		$('.finish a').bind('click.liked', function(){
      
			var aHref = $(this),
					id = post.getPostId(aHref),
          text;
					
			if (aHref.hasClass('not-mine')) {
				return;
			}
					
      if (aHref.hasClass('active')) {
        text = 'Deseja reabrir as respostas?';
      }
			else {
				text = 'Deseja encerrar as respostas?'
			}
			$('#messageModal').removeClass('interactModal');
			var modalContainer = cqlook.showMessageModal(text + '<ul id="privateConfirm"><li id="yes" class="btn">sim</li><li id="no" class="btn">não</li></ul>', 'warning'),
			    modal = modalContainer.data('overlay')					
			
			modal.onClose = function() {
				modalContainer.find('ul').remove();
			};
			
			modalContainer.find('#yes').click(function(){
				
				$.getJSON('/services/post/close_post', {post_id: id}, function(json){
	      
					modal.close();
					window.location.href = window.location.pathname;
	      });
			});
			
			modalContainer.find('#no').click(function(){
				modal.close();
			});
    });
		
  },  	
	likes: function(){
		// like comments
		$('.likeIt').live('click', function(){
		
			var thumb = $(this),
					id = $(this).attr('data-post-id');
					
			if (thumb.hasClass('liked'))
				return;
			
			$.getJSON('/services/post/add_user_like', {post_id: id}, function(json){
		
				thumb.addClass('liked').unbind('click.liked');
				thumb.next().find('span').text(addZero(json.data.thumbs_up));
			});
		});	

		// like questions
		$('.manyLiked').live('click', function(){
		
			var thumb = $(this),
					id = $(this).attr('data-post-id');
					
			if (thumb.hasClass('.manyLikedBlocked'))
				return;
			
			$.getJSON('/services/post/add_user_like', {post_id: id}, function(json){
		
				thumb.empty().text(addZero(json.data.thumbs_up));
				thumb.addClass('hasLikes').addClass('manyLikedBlocked').unbind('click.manyLiked');
				Cufon.refresh();
			});
		});
	},
	
	report: function(){
		$('.report').live('click', function(e){
			var clickE = 1;
			var primeiroThis = this;
			var thumb = $(this),
					id = $(this).attr('data-post-id'),
					msg;

			if (thumb.hasClass('reported'))
				return;
					
			if (thumb.hasClass('answerReport')) {
				msg = thumb.prev().html();
			}	
			else {
				msg = $(this).parents('.pergunta').find('div.questionDescription').html();
			}
			$('#messageModal #txtMessageModal').removeClass('error', 'ok');
			cqlook.showModal('<div id="report-text"></div>');
						
			$('#report-text').html('<div class="original">"'+msg+'"</div><p>Achou o conteúdo inapropriado? Então escreva para o moderador Com que look eu vou?</p><textarea name="reportDescription" id="reportDescription"></textarea><p class="right"><a class="btn">Enviar</a></p>');
			
			if ($('#report-text .original').html().indexOf('class="full"')>0){
				$('#report-text .original .summary').hide();
				$('#report-text .original .full').show();
			}

			Cufon.refresh();
			
			$('#report-text .btn').click(function(){
				if ($('#reportDescription').val() != '') {
					$.getJSON('/services/post/add_denounce', {post_id: id, description: $('#reportDescription').val()}, function(json){
						thumb.html('reportado').addClass('reported').addClass('reportBlocked').unbind('click.report');
						$('#messageModal .close').click();
						$('#messageModal').removeClass('interactModal');
					});
				} else {
					clickE = 2;
					$('#messageModal').removeClass('interactModal');
					cqlook.showMessageModal('Escreva uma mensagem para o moderador Com que look eu vou?', 'error');
					$('#messageModal .close').click(function() {
						if (clickE == 2) {
							$(primeiroThis).click();
							clickE = 1;
						}
					});
				}
			});
			
			window.location = window.location.pathname + '#topo';
		});
	},
	
	getPostId: function(element) {
		return element.parents().find('[data-post-id]').attr('data-post-id');
	},
	getPostType: function(element) {
		
		if (element.parent().prev().find('a').hasClass('active')) {
			return 'look';
		}
		return 'comment';
	},
	
	answers: function(){
  
		var openModal = function() {	 		
			var aHref = $(this);
			/*				
			if (aHref.hasClass('videoModal')) {
				$('.tab_video a').click();
			} 
			else {
				$('.tab_photo a').click();
			}
			*/
			$('#infoPhotoVideo').show();
			$('#mediaModal').data('overlay').load();			
		};
		
		var prepareMedia = function() {
			
			if (PrepareMedia.type === 'other') return;
			if ($('#doubt').length) tabs.close();
			
			PrepareMedia.type = 'other';				
			PrepareMedia.go();			
		};	
		
  	
  	var isPostingReply = false;
  	
  	var postReply = function() {
		
		if (isPostingReply) {
			return;
		}
		
		
		isPostingReply = true;
		
		
		var reply = $(this), 
			postId = post.getPostId(reply),
			postId = reply.attr('data-post-id'),
			type = post.getPostType(reply),
			textarea = reply.parent().parent().prev();
			//alert(textarea);
		post.Tabs.chosenFiles.setPostId(postId);
			
  		if (textarea.val() == 'escreva sua resposta...') {
			$('#messageModal').removeClass('interactModal');
  			cqlook.showMessageModal('Por favor, preencha primeiramente sua resposta', 'error');
			isPostingReply = false;
			
			window.location = window.location.pathname + '#topo';
			
			$('#messageModal .close').click(function (){
				window.location = window.location.pathname + '#' + postId;
			});
			
  			return;
  		}
  		
  		
  		$.post('/services/post/save_post', {
			'post': JSON.stringify({
				description: textarea.val(),
				'type': type,
				parent_id: postId
			})
		},function(result){
			
			isPostingReply = false;
			
			var json = $.parseJSON(result);
			if (json.success === true) {
				window.location = window.location.pathname + '#' + postId;
				window.location.reload();
				return false;
			}
			window.location = window.location.pathname + '#topo';
			$('#messageModal').removeClass('interactModal');
			cqlook.showMessageModal('Ocorreu um erro', 'error');
			});
			return false;

		};		
			
		$('.photoModal, .videoModal').live('click', function(e) {		
			e.preventDefault();
			
			postId = $(this).parent().find('.reply a').attr('data-post-id');

			openModal();
			prepareMedia();
			
			window.location = window.location.pathname + '#topo';
			
			$('#mediaModal .close').unbind('click');
			
			$('#mediaModal .close').click(function (){
				$('#mediaModal').data('overlay').close();
				window.location = window.location.pathname + '#' + postId;
			});
		});

		$('.went').live('click', prepareMedia);		
		
		$('.reply a').live('click', postReply);  	
			
		$('#attach').click(function(){
			$('#mediaModal').data('overlay').close();	
		});
		
		$('#mediaModal .close').click(function(){
			$('#mediaModal').data('overlay').close();	
		});

  	$('.firstLevelAction').click(function(){
  	
  		var aHref = $(this);
  		var toShow = aHref.next().next();
			aHref.remove();
			toShow.show();
  	});
  }
};

var openQuestionModal = function(post_id, index) {
		
	var navigator;
			
	if (typeof homeMedias === 'undefined') {
		navigator = medias; // estamos na interna
	}
	else {
		navigator = homeMedias[post_id];
	}			
	openModalMedia(post_id, index, navigator.getMedias());
		
};

var openModalMedia = function(post_id, index, medias) {

	var modal = $('#fullMediaModal'),
			scrollable;
	
	scrollable = getScrollable(medias, index);
	
	modal.find('div').remove();
	modal.append(scrollable);
	
	index = parseInt(index, 10);
	
	if (index === 0) {
		$('.prev').addClass('disabled');
	}
		
	if (index === medias.length	 - 1) {
		$('.next').addClass('disabled');
	}
	
	modal.data('overlay').onLoad = function() {
		$('.mediaDetail').children().hide();
		scrollable.data('scrollable').seekTo(index, 1);
		modal.data('overlay').onLoad = function() {};
	};
	
	modal.data('overlay').onClose = function() {
		$('.mediaDetail').children().show();
	};
	
	modal.data('overlay').load();	

	window.location = window.location.pathname + '#fullMediaModalAnc';
};
	
	var getScrollable = function(medias, index) {
		
		var scrollable = $("<div class='modalScrollable' />"),
				items = scrollable.append('<div class="items" />').find('.items'),
				mediasNumber = medias.length;
				
		for (var i = 0; i < mediasNumber; i++) {
			items.append(getScrollableItem(medias[i]));
		}
		
		scrollable.append(items);
		
		if (mediasNumber > 1) {
			scrollable.prepend("<a class='prev' />");
			scrollable.append("<a class='next' />");	
		}
		
		scrollable.scrollable({circular: false, speed: 900});
		
		scrollable.find('.next').click(function(){
			
			var aHref = $(this);
			
			if (aHref.hasClass('disabled')) {
				return;
			}
			
			$('.prev').removeClass('disabled');
			index++;
			scrollable.data('scrollable').next();
			
			if (index === mediasNumber - 1) {
				aHref.addClass('disabled');
			}
		});
		
		scrollable.find('.prev').click(function(){
			
			var aHref = $(this);
			
			if (aHref.hasClass('disabled')) {
				return;
			}
			
			$('.next').removeClass('disabled');
			index--;
			scrollable.data('scrollable').prev();
			
			if (index === 0) {
				aHref.addClass('disabled');
			}
		});
		
		return scrollable;
	};
	
	var getScrollableItem = function(data) {
		
		var item = $("<div class='item' />");
		
		if (data.is_image) {
			var img = item.append('<img src="" alt="" />').find('img');
					img.attr('src', '/media/images/normal/' 
										+ data.uri + '?' 
										+ new Date().getTime()); // para o IE ignorar o cache e disparar o onLoad
					
			img.load(function(){
				img.css('margin-top', (img.height() / 2) *-1 -12);
				img.css('margin-left', (img.width() / 2) *-1 -60);
				img.show();
			});
		}
		else {
			item.append("<div class='swf' />").find('.swf').flashembed("/swf/playback.swf", {
				MEDIA_SOURCE: data.source_type,
				VIDEO_URL: data.uri,
				THUMBNAIL: 'false'
			});    
		}
		
		return item;
	};

var answerMediaList = function() {

	$('.answerMediaList img').unbind('click').click(function(){
		
		var img = $(this),
				post_id = post.getPostId(img),
				index = img.index('.answerMediaList[data-post-id=' + post_id + '] li img'),
				navigator;
				
		$.getJSON('/services/post/get_media_navigator_json', {'post_id': post_id}, function(json){
				
				var medias = $.parseJSON(json.data);
				openModalMedia(post_id, index, medias);
				
		});
	});
};


$(function(){

	answerMediaList();
					
	$('#fullMediaModal').overlay({
		
		closeOnClick: true, 
		mask: { color: '#000000', loadSpeed: 1100, opacity: 0.7}
	});				
	
	$('.mediaDetail img').live('click', function(){
		
		var img = $(this),
				post_id = post.getPostId(img),
				index = $('.media[data-post-id=' + post_id + ']').attr('data-index');
				
		openQuestionModal(post_id, index);
	});
});				
	
