function getTinyURL(longURL, success){
	var API = 'http://json-tinyurl.appspot.com/?url=', URL = API + encodeURIComponent(longURL) + '&callback=?';

	
	$.getJSON(URL, function(data){
		success && success(data.tinyurl);
	});
}

$(document).ready(function() {
	var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
	po.src = 'https://apis.google.com/js/plusone.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
});
function liveDisplayShare(){
	$(".share-options").each(function(){
		$("#"+$(this).attr("id")).dialog({autoOpen: false,  closeOnEscape: true, resizable: false, draggable:false, modal:true, width:400});
	});

	$(".display-share").click(function(e){
		e.preventDefault();
		var shareElement = $("#"+$(this).attr("rel"));
		shareElement.dialog('open');
		gapi.plusone.go();
		return false;
	});
	$(".share-options input").click(function(){
		$(this).select();
	});
}

function liveWriteCommentAction(){
	
	$(".write-comment-action.external").click(function(e){
		return writeCommentActionHandler(e, $(this));
	});
}

function liveViewMore(){
	$(".view-more").click(function(e){
		e.preventDefault();
		loadStreamPage($(this).attr("rel"));
		$(this).remove();
		return false;
	});
}

function liveFilters() {
	$("#feed-filter li a").click(function (e) {
		e.preventDefault();
		loadStreamPage($(this).attr("href"), null, false);
		return false;
	});
}

function liveFormType() {
	$('.add-post form').hide();
	var txtarea = $('.add-post form:first').show().find("textarea");
	if (txtarea.length > 0) {
		txtarea.placeholder();
	}
	$("#activity-form-type li:first").addClass("active");

	$("#activity-form-type li a").click(function (e) {
		e.preventDefault();
		$(this).parents("ul").find("li").removeClass("active");
		$(this).parent().addClass("active");
		$('.add-post form').hide();
		var txtarea = $('.add-post form.' + $(this).parent().attr('title')).show().find("textarea");
		if (txtarea.lenght > 0) {
			txtarea.placeholder();
		}
		return false;
	});
}

function liveFormSubmit() {
	$('.add-post form').submit(function (e) {
		e.preventDefault();
		var form = $(this);
		$.ajax({
            type: "POST",
            data: form.serialize(),
            url: form.attr("action"),
            cache: false,
            dataType: "html",
            success: function(html, textStatus) {
				loadStreamPage(
					$("#feed-filter li.first a").attr("href"),
					function () {
						$(".add-post .response").html("");
						form.find("textarea").val("");
						form.find("input[type='submit']").attr("disabled", true);
						form.find("input[type='submit']").addClass("disabled");
					},
					false
					);
            },
            error: function (html) {
            	$('.add-post .response').html(html.response);
            }
        });
		return false;

	});
}

function loadStreamPage(url, callback, append) {
	if (typeof append == "undefined") {
		append = true;
	}
	if (!append) {
		$(".activity-list").html("");
	}
	$(".activity-list").next('img.stream-preloading').show();
	$.get(url, function(data) {
		$(".activity-list").append(data);
		$("ul.comment-list").each(function(){
			addCommentListener($(this).attr("id"));
		})
		triggerEvents();
		if (typeof callback == "function") {
			callback();
		}
		$(".activity-list").next('img.stream-preloading').hide();
		$(".videoactivity iframe").each(function () {
			var ifr_source = $(this).attr('src');
			if (ifr_source.match(/^http:\/\/www\.youtube\.com\/embed\/\w+(?!\?wmode=transparent)$/)) {
				var wmode = "?wmode=transparent";
				$(this).attr('src',ifr_source+wmode);
			}
		});
		$(".photoactivity p.content a").click(function() {
			var link = $(this);
			var img_src = link.find('img').attr("src");
			var i = new Image();
			i.src = img_src;
			$(i).load(function () {
				var ww = $(window).width() - 30;
				var wh = $(window).height() - 30;
				var w = i.width;
				var h = i.height;
				if (w > ww || h > wh) {
					var r = w / h;
					var wr = ww / wh;
					if (r > wr) {
						w = ww;
						h = w / r;
					} else {
						h = wh;
						w = h * r;
					}
				}

				klightbox(link.html(), w, h);
			});
			return false;
		});
	});
}

function liveReadMore(){
	$(".read-more").click(function(e){
		e.preventDefault();
		$(this).hide();
		var container = $(this).parents(".content");
		container.children(".complete").addClass("hidden-visible");
		container.children(".partial").remove();
		$(this).remove();
		return false;
	});
}

function triggerEvents(){
	liveWriteCommentAction();
	liveDisplayShare();
	liveViewMore();
	liveReadMore();
	$(".delete-activity").submit(function(e){
		e.preventDefault();
		var form = $(this);
		$.ajax({
            type: "POST",
            data: form.serialize(),
            url: form.attr("action"),
            cache: false,
            dataType: "html",
            success: function(html, textStatus) {
				var container = form.parents("li");
				container.prev(".grouper").remove();
				container.hide();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            	
            }
        });
		return false;
	});
	$(".activity-list li").hover(function(){
		$(this).find(".delete-activity").removeClass("invisible");
	},function(){
		$(this).find(".delete-activity").addClass("invisible");
	});
	
	$(".activity-list li .delete-activity button").click(function(e){
		e.preventDefault();
		
		var deleteForm = $(this).parent(".delete-activity");
		
		var banForm = deleteForm.next(".ban-form");
		
		var del = gettext("Delete content");
		var ban = gettext("Delete content and block user");
		var buttons = new Object();
		buttons[del] = function() {
			deleteForm.submit();
			$("#dialog_loading").dialog("open");
			$("#delete_stream_dialog").dialog("destroy");
		}

		if (banForm.length == 1) {
			buttons[ban] = function() {
				deleteForm.ajaxComplete(function(){
					banForm.submit();
				});
				deleteForm.submit(); 
				$("#delete_stream_dialog").dialog("destroy");
			}
		}
		$("#delete_stream_dialog").dialog({
			dialogClass: "delete_stream_dialog",
			modal:true,
			buttons: buttons,
			closeOnEscape: true,
			resizable: false,
			draggable:false
		});

		return false;
	});
}

function loadModerationHelper(){
	function getCheckedRows(){
		return $("input[name='check']:checked");
	}
	
	function resetCheck(){
		$(".approve input, .delete input").attr("checked", false);
	}
	$("input[name='check-all']").click(function() {
		$("input[name='check']").attr("checked", $(this).attr("checked"));
	});
	
	$(".btn").click(function(e){
		e.preventDefault();
		var action = $(this).attr("name");
		var checked = getCheckedRows();
		resetCheck();
		checked.each(function(){
			$(this).parent().nextAll("."+action).children("input").attr("checked", true);
		});
		$(this).parent("form").submit();
	})
}

$(document).ready(function(){
	loadModerationHelper();    
	triggerEvents();

	liveFilters();
	liveFormType();
	liveFormSubmit();
	
	if (!allarga_actived) {
		$(".add-post textarea").each(function(){
			allarga($(this), false);
		});
	}
	
	

	var close = gettext("Close");
	var buttons = new Object();
	buttons[close] = function() {
		$("#dialog_follow").dialog("close");
	}
	$("#dialog_follow").dialog({
		autoOpen: false,
		dialogClass: "follow_dialog",
		modal:true,
		buttons: buttons,
		closeOnEscape: true,
		resizable: false,
		draggable:false,
		width: '400px'
	});
	
	$(".follow-button-action").click(function(e){
		e.preventDefault();
		$("#dialog_follow").dialog("open");
		return false;
	});
	
	$(".add-post form textarea").keyup(function(){
		if ($(this).val() == ""){
			var button = $(this).nextAll(".send");
			button.addClass("disabled");
			button.attr("disabled", true);
		} else {
			var button = $(this).nextAll(".send");
			button.removeClass("disabled");
			button.attr("disabled", false);
		}
	});
	
	$(document).ajaxStop(function(){
		$("#dialog_loading").dialog('close');
	});
})


