$(function() {
	function runEffect(){
		var selectedEffect = 'scale';
		var options = {};
		if(selectedEffect == 'scale'){  options = {percent: 100}; }
		else if(selectedEffect == 'transfer'){ options = { to: "#button", className: 'ui-effects-transfer' }; }
		else if(selectedEffect == 'size'){ options = { to: {width: 280,height: 185} }; }
		$("#effect").show(selectedEffect,options,500,callback);
	};
	$("#button").click(function() {
		runEffect();
			return false;
	});
		
});




$(document).ready(function() {
	$(".news_column").sortable({
		connectWith: [".news_column"],
		containment: 'document',
		opacity: 0.8,
		forcePlaceholderSize: true,
		tolerance: "pointer",
		handle: ".portlet-header",
		revert: true,
		update: function(e, ui){
			if ($(this).attr('id') == ui.item.context.parentNode.id) {
				var movedFeed = ui.item.context;
				var feedId = movedFeed.id;
				var preFeed = $(movedFeed).prev();	
				if(undefined === preFeed[0])
				{
					preFeed = this;
				}
				var preFeedId = $(preFeed).attr('id');
				var sessionId=ReadCookie('_cuba');
				$.getJSON("http://cuba.lu/ajax/move/session/"+sessionId+"/feed/"+feedId+"/position/"+preFeedId+"/format/json", function(data){});					
			}
		}
	});

	$(".portlet-header .ui-icon-refresh").click(function() {
		var id = $(this).parent().parent().attr('id');
		var sessionId=ReadCookie('_cuba');
			
		$.getJSON("http://cuba.lu/ajax/refresh/session/"+sessionId+"/feed/"+id+"/format/json", function(data){
		    $('#' + id + ' ul').empty();
		    $.each(data.news, function(i,item){
	            	a = "<li class=\"bubbleInfo\"><a href=\"" + item.link + "\" class= \"item trigger\" target='_blank' id=\"" + item.entry_id + "\">" + item.title + "</a></li>";
		    	$('#' + id + ' ul').prepend(a);
		    });
		    $('#' + id + ' ul .item').each(function () {
                        if ($(this).parent().hasClass("bubbleInfo")) {
         	            var id = $(this).attr('id');
        	            var parent = $(this).parent();
        	            createBubble(parent, id);
			}
		    });
		});
	});
	
        $(".portlet-header .ui-icon-carat-2-n-s").click(function() {
		var id = $(this).parent().parent().attr('id');
		var sessionId=ReadCookie('_cuba');
			
		$.getJSON("http://cuba.lu/ajax/expand/session/"+sessionId+"/feed/"+id+"/format/json", function(data){
		    $('#' + id + ' ul').empty();
		    $.each(data.news, function(i,item){
	            	a = "<li class=\"bubbleInfo\"><a href=\"" + item.link + "\" class= \"item trigger\" target='_blank' id=\"" + item.entry_id + "\">" + item.title + "</a></li>";
		    	$('#' + id + ' ul').prepend(a);
		    });
		    $('#' + id + ' ul .item').each(function () {
                        if ($(this).parent().hasClass("bubbleInfo")) {
         	            var id = $(this).attr('id');
        	            var parent = $(this).parent();
        	            createBubble(parent, id);
			}
		    });
		});

	});
	$(".portlet-header .ui-icon-closethick").click(function() {	
		var container = $(this).parents(".portlet:first");
		var containerId = $(container).attr('id');
		$(container).hide("scale", {percent:0}, 750, function() {
			window.setTimeout(function() {
				$(container).remove();
			},750);
		});
		var sessionId=ReadCookie('_cuba');
		$.getJSON("http://cuba.lu/ajax/remove/session/"+sessionId+"/feed/"+containerId+"/format/json", function(data){});		
	});
	
    $("a.item").each(function () {
        if ($(this).parent().hasClass("bubbleInfo")) {
        	var id = $(this).attr('id');
        	var parent = $(this).parent();
        	var parentId = $(this).parent().parent().parent().parent().attr('id');
        	createBubble(parent,id);
        }
    });

    $("a.item").mouseup(function () {
        var id = $(this).attr('id');
        var sessionId=ReadCookie('_cuba');
        $.getJSON("http://cuba.lu/ajax/clicked/session/"+sessionId+"/item/"+id+"/format/json", function(data){});
        return false;
    });
    
    $("h2.portlet-headline > a").mouseover(function () {
        var id = $(this).parent().parent().parent().attr('id');
        var sessionId=ReadCookie('_cuba');
        $.getJSON("http://cuba.lu/ajax/hlmo/session/"+sessionId+"/item/"+id+"/format/json", function(data){});
        return false;
    });

    function createBubble(element, id)
    {
    	$(element).append($("<table class=\"popup\"></table>"));
    	var sessionId=ReadCookie('_cuba');
        var distance = 10;
        var time = 250;
        var showDelay = 500;
        var hideDelay = 500;
        var showDelayTimer = null;
        var hideDelayTimer = null;
        var beingShown = false;
        var shown = false;
        var trigger = $('.trigger', element);
        var popup = $('.popup', element).css('opacity', 100);      
        $([trigger.get(0), popup.get(0)]).mouseover(function () {
        	if (hideDelayTimer) clearTimeout(hideDelayTimer);
        	if (beingShown || shown) {
        		return;
        	}

           	showDelayTimer = setTimeout(function(){
           		 	showDelayTimer = null;
        			if (0 == $(popup).children().length) {
        			  	$(popup).append($("<tbody><tr><td id=\"topleft\" class=\"corner\"></td><td class=\"top\"></td><td id=\"topright\" class=\"corner\"></td></tr>" +
        			  		    "<tr><td class=\"left\"></td><td><table class=\"popup-contents\"><tbody><tr><td>" + "<img src=\"/styles/images/ajax-loader.gif\" class=\"image_load\" />" + "</td></tr></tbody></table>" +
        			  	  		"</td><td class=\"right\"></td></tr><tr><td class=\"corner\" id=\"bottomleft\"></td><td class=\"bottom\"></td><td id=\"bottomright\" class=\"corner\"></td></tr></tbody>"));
        			
           			  	$.getJSON("http://cuba.lu/ajax/previewopened/session/"+sessionId+"/item/"+id+"/format/json", function(data){
           			  		var token = data["data"]["token"];
            			  	var timestamp = data["data"]["timestamp"];
           			  		var text = data["data"]["text"];
           			  		$(popup).find("tbody.bubbleInfo").attr("id", token);
                			$(popup).contents().find("img").replaceWith(text);
            		  		if ("" != timestamp) {
            		  			$(popup).find("table").append("<tr class=\"message-timestamp\"><td><div>" + timestamp + "</div></td></tr></tbody>");
            		  		}
               			});
        			
        			}
        			beingShown = true;

        	        var sideLeft = -280;
        	        var sideRight = 260;
        	        var side = sideRight;
        	        if ($(element).parent().parent().parent().parent().next().attr("id") == "footer") {
        	        	side = sideLeft;
        	        }
        			popup.css({
        				'z-index': 150,
        				top:  $(element).parent().parent().get(0).offsetTop,
        				left: side, // (-250)
        				width: 290,
        				display: 'block'	// brings the popup back tin to view
        			})
        			.animate({
        				top: '-=' + distance + 'px',
        				opacity: 1
        			}, time, 'swing', function() {
        				//once the animaiton is complete, set the tracker variables
        				beingShown = false;
        				shown = true;
        			});
        		}, showDelay);
        }).mouseout(function () {
        	if (showDelayTimer) clearTimeout(showDelayTimer);
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                popup.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    popup.css('display', 'none');
                });
        		$.get("http://cuba.lu/ajax/previewclosed/session/"+sessionId+"/item/"+id+"/format/json", function(data){});
            }, hideDelay);
            return false;
        });
    };
    function ReadCookie(cookieName) {
    	var theCookie=""+document.cookie;
    	var ind=theCookie.indexOf(cookieName);
    	if (ind==-1 || cookieName=="") return ""; 
    	var ind1=theCookie.indexOf(';',ind);
    	if (ind1==-1) ind1=theCookie.length; 
    	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
    };
});


