/**
 * 
 */

Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}


var _portlet_height = 0,
    _doc_height = 0,
    _header_height = 0,
    _footer_height = 0;


function objHasData(o, key) {
	_n = "o";
	try {
		_n = o.id;
		if (_n == undefined) throw 0;
		_n = "'#" + _n + "'";
	}
	catch (e) {
		try {
			_n = "'#" + o.attr("id") + "'";
		}
		catch (e) {
			// nop
		}
	}
	
	try {
		_d = o.data(key);
	}
	catch (e) {
		try {
			_d = $(o).data(key);
		}
		catch (e) {
			log("objHasData(" + _n + ", '" + key + "'): invalid o");
			return false;
		}
	}
	if (_d == null) {
		log("objHasData(" + _n + ", '" + key + "'): nope - is: null");
		return false;
	}
	if (_d == undefined) {
		log("objHasData(" + _n + ", '" + key + "'): nope - is: undefined");
		return false;
	}
	if (_d == "") {
		log("objHasData(" + _n + ", '" + key + "'): nope - is: empty string");
		return false;
	}
	log("objHasData(" + _n + ", '" + key + "'): yeah, is: '" + _d + "'");
	return true;
}


function createPortletInsertionHelper(draggable, above) {
	container = draggable.data("currentContainer");
	
	_id = "ins_helper_" + $.now();
    _n = $("<div id='" + _id + "' class='portletInsertionHelper'>&nbsp;</div>");
	if (above.id != "__bottom__")
        _n.insertBefore($(above));
	else
    	_n.appendTo(draggable.data("currentContainer"));
	
    newhelper = $("#" + _id);
    draggable.data("insertionHelper", newhelper);
    initialHeight = draggable.data("initialHelperHeight");
    if (initialHeight) {
    	newhelper.css({height: initialHeight});
    	draggable.removeData("initialHelperHeight");
    }
    
    newhelper.animate({height: '50px', marginBottom: '.9em'}, 500);
}


function deletePortletInsertionHelper(draggable) {
	var helper = draggable.data("insertionHelper");
	draggable.removeData("insertionHelper");
	helper.animate({height: '0px'}, 500, function() {
    	helper.remove();
	});
}


function removePortletInsertionHelper(draggable) {
    above = draggable.data("currentAbove");
	container = draggable.data("currentContainer");
	
	if (above == undefined)
		above = "?";
	
    s = "now OUT";
    if (above != "?") {
        s += " (was '" + above.id + "')";
    }
    else {
        s += " (was undefined)";
    }
    logToPage(s);
    
    if (objHasData(draggable, "insertionHelper"))
    	deletePortletInsertionHelper(draggable);
    
	draggable.data("currentAbove", "?");
}


function updatePortletInsertionHelper(draggable, lastAbove, above) {
	s = "";
	if (above.id != "__bottom__")
	    s += "now ABOVE '" + above.id + "'";
	else
		s += "now at BOTTOM";
    
    if (lastAbove != "?") {
    	s += " (was '" + lastAbove.id + "')";
    }
    else {
    	s += " (was undefined)";
    }
    
    var helper = draggable.data("insertionHelper");
    if (helper == undefined) {
    	createPortletInsertionHelper(draggable, above);
    }
    else {
    	deletePortletInsertionHelper(draggable);
    	createPortletInsertionHelper(draggable, above);
    }
    
	logToPage(s);
    
	draggable.data("currentAbove", above);
}


function applyPortletDrop(draggable) {
    /* make the helper as large as the dragged portlet, when finished: delete helper and replace with dragged */
    var thePortlet = draggable;
    var helper = draggable.data("insertionHelper");
    
    h = thePortlet.outerHeight(true); /* full height incl margins */
    
    logToPage("--- applying portlet move [height of .portlet: " + h + ", in: " + $(helper).closest(".portletContainer")[0].id + "] ---");
    
    helper.html("");
    draggable.clone(false).show().appendTo(helper);
    
 	helper = $(helper);
    draggable.removeData("insertionHelper");
    
    helper.find(".portlet").animate({opacity: 1.0}, 500);
    helper.animate({height: h}, 500, function() {
        draggable.insertBefore(helper);
        helper.remove();
        draggable.show();
    });
	
	draggable.data("currentAbove", "?");
	fixPortletContainerHeights();
}


function revertPortletDrop(draggable) {
	var thePortlet = draggable;
	var helper = draggable.data("insertionHelper");
	
    removePortletInsertionHelper(draggable);
    draggable.show();
    
    fixPortletContainerHeights();
}


function fixPortletContainerHeights() {
	var header_height = $("#mainHeader").height();
	var maxHeight = 0;
	
	$.each($(".portal"), function(i, portal) {
		portal = $(portal);
		
		$.each(portal.find(".portletContainer"), function (j, container) {
			all = $(container).find('.portlet:visible[id!="__helper__"]');
			lowest = $(all.filter(':last'));
			if (lowest.length == 0) {
				return false; // continue
			}
			
			_top = lowest.position().top - header_height;
			_hig = lowest.outerHeight(true);
			_bot = _top + _hig;
			
			$.each(all, function (i,o) {
				var pc = $(o).find(".portletContent")[0];
				var lc = $(pc).find(".loadedContent");
				if (lc && lc.length > 0) {
					var h = $(pc).height();
					var ch = $(lc).height() || 0;
					if (h - ch >= -2) {
						$(pc).css({overflow: 'hidden'});
					}
					else {
						$(pc).css({overflow: 'auto'});
					}
				}
			})
			
			//logToPage("" + i + ": " + container.id + " bottom at " + _bot + " (lowest portlet: " + lowest[0].id + ")");
			
			if (_bot > maxHeight)
				maxHeight = _bot;
		});
		
		portal.find(".portletContainer").height(maxHeight);

        //var lowest = portal.find('.portletArea .column75 .portlet:visible[id!="__helper__"]:last');
        //_top = lowest.position().top - header_height;
        //_hig = lowest.outerHeight(true);
        //_bot = _top + _hig;
        var _bot = $(document).height() - 64;
        $("#mainFooter").offset({right:$("#mainFooter").offset().right, top:_bot});
	});
}


$(function() {
    _doc_height = $(window).height();
    _header_height = $("#mainHeader").height();
    _footer_height = $("#mainFooter").height();
    _portlet_height = _doc_height - _header_height - _footer_height;
    
    $(".portlet:not(.fixed)").draggable({
    	helper: "clone",
    	handle: ".portletTitleBar",
    	distance: 10,
    	opacity: 0.7,
    	scroll: false,
        start: function(e, ui) {
        	$(this).css({opacity: 0.3});
        	$(ui.helper).width($(this).width());
        	ui.helper[0].id = "__helper__";
        	
        	h = $(this).outerHeight(true); /* full height incl margins */
        	$(this).data("initialHelperHeight", h);
        	$(this).data("currentAbove", "?");
        	$(this).hide();
        	
//        	$(this).data("tasks", []);
        },
        drag: function(e, ui) {
        	var x = e.pageX;
        	var y = e.pageY;
        	
        	var lastAbove = $(this).data("currentAbove");
        	var container = $(this).data("currentContainer");
        	
        	cp = $(container).position();
        	
        	if (cp == null) {
        		//logToPage("cp is null for container: " + container);
        	}
        	else
	        	if (x < cp.left || x > cp.left + $(container).width()) {
	        		if (lastAbove != "?") {
	        			removePortletInsertionHelper($(this));
	        		}
	        		return;
	        	}
        	
        	var above = undefined;
        	
        	$.each($(container).find(".portlet:visible"), function(i, o) {
        		if (o.id != "__helper__") {
        			_o = $(o);
            		_o_p = _o.position();
            		_o_h = _o.height();
            		if (y < _o_p.top + (_o_h / 2)) {
            			above = o;
            			return false; /* break */
            		}
        		}
        	});
        	
        	if (above != undefined) {
        		if (lastAbove != above) {
	            	updatePortletInsertionHelper($(this), lastAbove, above);
        		}
        	}
        	else {
        		if (lastAbove.id != "__bottom__") {
        			updatePortletInsertionHelper($(this), lastAbove, {id: "__bottom__"});
        		}
        	}
        },
        stop: function(e, ui) {
            $(this).css({opacity: 1.0});
        },
        revert: function(droppable) {
            if ($(this).data("currentAbove") != "?") {
                applyPortletDrop($(this));
                return false;
            }
            logToPage("--- revert! ---");
            revertPortletDrop($(this));
            return true;
        }
    });
    
    $(".portlet:not(.fixed):not(.fixedSize) .portletContent").resizable({
        handles: "s",
        stop: fixPortletContainerHeights
    });
    
    $(".portletContainer").droppable({
        hoverClass: "portletContainerOver",
        tolerance: "pointer",
        accept: ".portlet",
        over: function(e, ui) {
        	if (ui.draggable.data("currentAbove") != "?") {
        		logToPage("--- entering another container ---");
        		removePortletInsertionHelper($(this));
        	}
        	ui.draggable.data("currentContainer", this);
        	ui.draggable.data("currentAbove", "?");
        },
    });
    
    /* hover alpha effect for portlet toolbar buttons */
    defAlpha = 0.2;
    $(".portletTitleBar > .portletToolbarBtn").css({opacity: defAlpha}).hover(
        function(){ 
            $(this).css({opacity: 1.0});
        },
        function(){ 
        	$(this).css({opacity: defAlpha});
        }
    );
    
    /* specific portlet toolbar button functionalities */
    $(".portletTitleBar .portletEditBtn").click(function() {
        alertFancy("settings...");
    });
    
    $(".portletTitleBar .portletCloseBtn").click(function() {
    	p = $(this).closest(".portlet");
    	p.fadeOut();
    });
    
    $(".portletTitleBar .portletMaxBtn").click(function() {
    	var self = $(this).closest(".portlet");
    	var portal = $(this).closest(".portal");
        var tempCo = portal.find(".tempContainer");
        var myArea = portal.find(".portletArea");
        var maximizedArea = portal.find(".maximizedPortletArea");
    	
    	$(this).css({opacity: defAlpha});
    	
    	if ($(this).hasClass("ui-icon-arrow-4-diag")) {
        	/* to maximize: first reparent to the full portal area; but put it into a temporary container first
        	   lest it gets hidden, too, when the portletArea is. */
        	
            var parent = self.closest(".portletContainer");
            
        	self.draggable('option', 'handle', '.closeBtn');
        	self.find(".portletTitleBar").css({cursor: "auto"});
        	
        	newdiv = $("<div class='portlet ui-widget'></div>");
        	newdiv.height(self.height());
        	newdiv.insertBefore(self);
        	self.data("tempPortletPlaceholder", newdiv);
        	self.appendTo(tempCo);
        	
        	$(this).switchClass("ui-icon-arrow-4-diag", "ui-icon-newwin", 0);
        	self.find(".portletCollapseBtn").hide();
        	self.find(".portletCloseBtn").hide();
        	
            myArea.hide("fade", 500);
            maximizedArea.find(".portletContainer").append(self);
            maximizedArea.show("fade", 0);
    	}
    	else {
    		$(this).switchClass("ui-icon-newwin", "ui-icon-arrow-4-diag", 0);
            self.find(".portletCollapseBtn").show();
            self.find(".portletCloseBtn").show();
            
            self.draggable('option', 'handle', '.portletTitleBar');
            self.find(".portletTitleBar").css({cursor: "move"});
            
            tempPortletPlaceholder = self.data("tempPortletPlaceholder");
            
            maximizedArea.hide("fade", 500);
            self.insertBefore(tempPortletPlaceholder);
            tempPortletPlaceholder.remove();
            tempCo.remove("div");
            myArea.show("fade", 0);
    	}
    });
    
    $(".portletTitleBar .portletCollapseBtn").click(function() {
    	var titlebar = $(this).closest(".portletTitleBar");
    	
    	/* toggle icon for collapse/expand button */
    	if ($(this).hasClass("ui-icon-arrowthickstop-1-n")) {
        	$(this).switchClass("ui-icon-arrowthickstop-1-n", "ui-icon-arrowthick-1-s", 0);
        	$(this).closest(".portlet").find(".portletContent").hide("slide", {direction: "up"}, 500);
        	titlebar.switchClass("ui-corner-top", "ui-corner-all", 500);
        	titlebar.find(".portletMaxBtn").hide();
        	setTimeout(fixPortletContainerHeights, 500);
    	}
        else {
        	$(this).switchClass("ui-icon-arrowthick-1-s", "ui-icon-arrowthickstop-1-n", 0);
            $(this).closest(".portlet").find(".portletContent").show("slide", {direction: "up"}, 500);            	
            titlebar.switchClass("ui-corner-all", "ui-corner-top", 500);
            titlebar.find(".portletMaxBtn").show();
            setTimeout(fixPortletContainerHeights, 500);
        }
    });
    
    
    /* splitter functionality */
    $(".portletHSplitter").draggable({
    	revert: true,
    	drag: function(e, ui) {
    		
    	}
    }).hover(
        function() {
        	$(this).find(".ui-icon").show();
        },
        function() {
        	$(this).find(".ui-icon").hide();
        }
    ).find(".ui-icon").hide();
    
    
    /* POC: dynamically load content */
    // $("#Persons .portletContent .loadedContent").remove();
    // divcode = "<div class='loadedContent'></div>";
    // $(divcode).appendTo($("#Persons .portletContent")).load("/persons?portlet", function(r, s)
    // {
        // if (s == "error") logToPage("errör!");
    	// fixPortletContainerHeights();
    // });
    
    // $("#Employees .portletContent .loadedContent").remove();
    // $(divcode).appendTo($("#Employees .portletContent")).load("/employees?portlet", function(r, s) {
    	// fixPortletContainerHeights();
    // });
    
//    $("#Timeline .portletContent .loadedContent").remove();
//    $(divcode).appendTo($("#Timeline .portletContent:first")).load("/timeline?portlet", function(r, s) {
//    	fixPortletContainerHeights();
//    });
    
    // $("#Hoo .portletContent .loadedContent").remove();
    // $(divcode).appendTo($("#Hoo .portletContent")).load("/static/css/datatables.css", function(r, s) {
    	// // fixPortletHeight(0, $(this).closest(".portlet"));
    	// fixPortletContainerHeights();
    // });
    
    $(".portletChildTabs_Container").tabs({
    	tabTemplate: "<li><a href='#{href}'>#{label}</a><div class='ui-icon ui-icon-close'></div></li>",
    	panelTemplate: '<div class="portletChildTabs_TabContent ui-corner-top"><div class="portletContent"></div></div>',
    	add: function(event, ui) {
    		//log("tab.add: ui = ", ui);
    		//log(ui.panel.id);
    		$(this).tabs('select', '#' + ui.panel.id);
    		
    		var tab_content = $(this).find("#" + ui.panel.id);
    		var tab_bg_obj = $(this).find(".portletChildTabs_TabBackground");
    		
    		tab_bg_obj.height(tab_content.height());
    		
    		log("tab-content object:", $(this).find("#" + ui.panel.id));
    		log("tab-background object:", $(this).find(".portletChildTabs_TabBackground"));
    	},
//    	remove: function(event, ui) {
//    		var tab_content = $(this).find("#" + ui.panel.id);
//    		tab_content.hide("fade", "slow");
//    	},
    }).find(".ui-tabs-nav").sortable({axis: "x"});
    
    fixPortletContainerHeights();
    
    /* make the maximized-area exactly overlap the normal area */
    $.each($(".portal"), function(i, p) {
    	// p = $(p);
    	// var minArea = p.find(".portletArea");
    	// var maxArea = p.find(".maximizedPortletArea");
    	// maxArea.offset(minArea.offset());
    });
    /* -------------------------------------------------------------------------------------------------------- */
    
    $( ".portletChildTabs_TabBar > li > div.ui-icon-close" ).live( "click", function() {
		var index = $(".portletChildTabs_Container > ul > li").index($(this).parent());
		$(".portletChildTabs_Container").tabs("remove", index);
	});    
});


function addMdiTab(title, obj_id) {
	var tab = $(".portletChildTabs_Container").tabs("add", "#"+obj_id);
	log("addMdiTab('" + title + "', '" + obj_id + "'): tab is: ", tab);
	$(tab).find('a[href="#' + obj_id + '"]').html(title);
	return tab;
}

