/*
var windowW_multiplier = 1.5;
var windowH_multiplier = 1.3;
function doPreviewSize()
{
   // put all your jQuery goodness in here.
   	var windowW = getWindowWidth();
	var windowH = getWindowHeight();
	
   	$("#drop-holder").width(windowW / windowW_multiplier);
   	$("#drop-holder").height(windowH / windowH_multiplier);
	$("#background-spacer").width(windowW/windowW_multiplier);
	$("#background-spacer").height(windowH/windowH_multiplier);
   	$("#drop-table-spacer").height((windowH-210) / windowH_multiplier);
   	$("#drop-table-holder").height("auto");
   	$("#drop-table-holder").width("auto");
   	$("#drop-table-holder").css({ position: "relative" });
   	$("#drop-table-holder").css({ top: windowH / 9 });

	//$("#page-spacer").height($("#drop-table-holder").height() + 300);

   	$(".widget-holder").height(windowH / 10);
   	$(".widget-holder").width(windowW / 10);
   	$(".widget-holder").attr("originalWidth", $(".widget-holder").width());
   	$(".widget-holder").attr("originalHeight", $(".widget-holder").height());
   	
   	fixLayout();
}
*/
/**
 * Not really called becauses it messes up stuff
function adjustBackgroundSize()
{
	var windowH = getWindowHeight();
	
	$("#page-spacer").height($("#drop-table-holder").height() + 300);

	var h1 = windowH/windowH_multiplier - 155;
	var h2 = $("#drop-table-holder").height();
	$("#background-spacer").height(Math.max(h1, h2));
}
 */

/*
function initLayout(num_widgets, num_cells)
{
   // put all your jQuery goodness in here.
   	var windowW = getWindowWidth();
	var windowH = getWindowHeight();
	//$("#background-image").append("<img src='http://static.dreamer.me/img/widgets/dreamer-bg-top.png' width='" + (windowW/windowW_multiplier) + "' height='92'/>");
	//$("#background-image").append("<img id='background-spacer' src='http://static.dreamer.me/img/widgets/dreamer-bg-middle.png' width='" + (windowW/windowW_multiplier) + "' height='" + (windowH/windowH_multiplier) + "'/>");
	//$("#background-image").append("<img src='http://static.dreamer.me/img/widgets/dreamer-bg-bottom.png' width='" + (windowW/windowW_multiplier) + "' height='63'/>");
	$("#background-image").append("<img id='background-spacer' src='http://static.dreamer.me/img/widgets/dreamer-bg.png' width='" + (windowW/windowW_multiplier) + "' height='" + (windowH/windowH_multiplier) + "'/>");
 	doPreviewSize();

	for (i = 1; i <= num_widgets; i++)
	{
		$("#draggable" + i).draggable({ 
			revert: 'invalid',
			start: function() {
				startDrag($(this));
			},
			stop : function() {
				stopDrag($(this));
			}
		});
	}
		
	// this loop is different because we need to include the 
	// drop source (at droppable0)
	for (i = 0; i <= num_cells; i++)
		{
		$("#droppable" + i).droppable({
			hoverClass: 'widget-holder-state-hover',
			activeClass: 'widget-holder-state-active',
			drop: function(event, ui) {
				handleDrop($(this), ui);
			}
		});
	}
}
*/
function stopDrag(jquery)
{
	var dropped = jquery.attr("dropped");
	if (dropped != undefined)
		jquery.css({ position : "static"});
	//if (dropped != undefined && dropped != "droppable0") 
	//	autoSize($("#" + jquery.attr("dropped")));
    //$("#" + jquery.attr("droptarget")).droppable("enable");
    $("[dropdisabled='true']").each (function () {
    	$(this).attr("dropdisabled", "false");
    	$(this).droppable("enable");
    });

	if (jquery.attr("permanent") != "true")
	{
		jquery.removeClass("widget-edit-over");
		jquery.addClass("widget-edit-out");
		jquery.find(".widget-editbox").css({ visibility: 'hidden' });
	}
	
	$(".droppable-widget").each(function () {
		autoSize($(this));
		$(this).removeClass("hilight-droptarget");
	});
		
	in_drag = null;
	disable_dialogs = false;
}
function startDrag(jquery)
{
	in_drag = jquery;
	disable_dialogs = true;
	drag_w = jquery.width();
	drag_h = jquery.height();
	
	$(".droppable-widget").each(function () {
		$(this).addClass("hilight-droptarget");
	});
	/*
	$(".droppable").each(function () {
		$(this).width(jquery.width());
		$(this).height(jquery.height());
	});
	*/
	
	jquery.prev().attr("dropdisabled", "true");
	jquery.prev().droppable("disable");
	jquery.prev().attr("dropdisabled", "true");
	jquery.next().droppable("disable");
    //$("#" + jquery.attr("droptarget")).droppable("disable");
	//$("#droppable0").droppable("enable");
	// disable dropping on our source for certain dudes
	//if (jquery.attr("nosource") == "true")
	//	$("#droppable0").droppable("disable");

	var dropped = jquery.attr("dropped");
	if (dropped != undefined)
	{
		jquery.css({ position : "absolute"});
	}	
	
	fixLayout();
}

function handleDrop(jquery, ui, in_handleDrop)
{
    if (!in_handleDrop)
    	fixLayout();
    	
	//ui.draggable.css({ margin: '5px' });
	//if (jquery.attr("id") != "droppable0")
	//	autoSize(jquery);
	autoSize(jquery);

	//jquery.addClass('widget-holder-state-highlight');//.find('p').html(status);
	//jquery.find("div").append(ui.draggable);
	jquery.after($("<center>").append(ui.draggable));
	//jquery.append("<br/>");
	ui.draggable.css({ position: 'static' });
	//ui.draggable.draggable('destroy');
	ui.draggable.attr("dropped", jquery.attr("id"));
	
	//resizeDropArea();
	//adjustBackgroundSize();
	
    ui.draggable.addClass("draggable-widget");
    
    // remove our old box from the dom
    $("#" + ui.draggable.attr("droptarget")).remove();
    // then add a new one after us
	ui.draggable.attr("droptarget", "droppable" + drop_target_count);
	//jquery.droppable("disable");
	//jquery.removeClass("droppable-widget");
	ui.draggable.after("<div id='droppable" + (drop_target_count) + "' class='droppable-widget widget-holderW'></div>");
	$("#droppable" + drop_target_count).droppable({
		hoverClass: 'widget-holder-state-hover',
		activeClass: 'widget-holder-state-active',
		drop: function(event, ui) {
			handleDrop($(this), ui);
		}
	});
	drop_target_count++
    
    if (ui.draggable.attr("autosave") == "true") saveLayout();
}

var drop_target_count = 1;
function createDropTargets()
{
    $(".drop-column").each(function () {
    	$(this).prepend("<div id='droppable" + (drop_target_count++) + "' class='droppable-widget widget-holderW'></div>");
    });
    $(".draggable-widget").each(function () {
    	$(this).attr("droptarget", "droppable" + drop_target_count);
    	$(this).after("<div id='droppable" + (drop_target_count++) + "' class='droppable-widget widget-holderW'></div>");
    });
}

/**
 * Fixes a problem where as soon as you start dragging or when you dropped the drop area you just left would re-align everything
 */
function fixLayout()
{
	if (true) return;
	$(".draggable-widget").each(function() {
		handleDrop( $("#" + $(this).attr("dropped")) , { draggable: $(this) }, true);
	});
}

function autoSize(jquery)
{
	jquery.width("auto");
	jquery.height("auto");
}
function originalSize(jquery)
{
	jquery.width(jquery.attr("originalWidth"));
	jquery.height(jquery.attr("originalHeight"));
}

	
var in_drag = null;
var drag_w = 0;
var drag_h = 0;


/*
var mouseover_widget = null;
var mouseover_instance = null;
*/

function widget_mouseover(widget, instance)
{
	if (!dreamer.edit_on) return;
	if (in_drag != null) return;
	
/*	mouseover_widget = widget;
	mouseover_instance = instance;
	setTimeout("widget_really_mouseover(" + widget + "," + instance + ")", 500);
}

function widget_really_mouseover(widget,instance)
{
	if (widget != mouseover_widget || instance != mouseover_instance) return;
*/
	$("#widget_" + widget + "_" + instance).draggable("enable");
	$("#widget_" + widget + "_" + instance).removeClass("widget-edit-out");
	$("#widget_" + widget + "_" + instance).addClass("widget-edit-over");
	$("#edit_" + widget + "_" + instance).css({ visibility: 'visible' });
}

function widget_mouseout(widget, instance)
{
	if (in_drag != null) return;
	
	mouseover_widget = null;
	mouseover_instance = null;
	
	if ($("#widget_" + widget + "_" + instance).length > 0) {
		$("#widget_" + widget + "_" + instance).draggable("disable");
		$("#widget_" + widget + "_" + instance).removeClass("widget-edit-over");
		$("#widget_" + widget + "_" + instance).addClass("widget-edit-out");
		$("#edit_" + widget + "_" + instance).css({ visibility: 'hidden' });
	}
}

function initializeDragAndDrop()
{
	// initialize draggable
	$(".draggable-widget").each( function () {
		$(this).draggable({ 
			revert: 'invalid',
			start: function() {
				startDrag($(this));
			},
			stop : function() {
				stopDrag($(this));
			}
		});
		$(this).draggable("disable");
	});

	// initialize droppable
	createDropTargets();
	$(".droppable-widget").each( function () {
		$(this).droppable({
			hoverClass: 'widget-holder-state-hover',
			activeClass: 'widget-holder-state-active',
			drop: function(event, ui) {
				handleDrop($(this), ui);
			}
		});
		
	});
	
	// initialize mouse movement capturing thing
	$("body").mousemove( function (event) {

		if (Math.abs(event.pageX - last_mouse_x) < 10 && Math.abs(event.pageY - last_mouse_y) < 10) return;
		last_mouse_x = event.pageX;
		last_mouse_y = event.pageY;
		if (in_drag != null)
		{
			var closest = null;
			var dist = 100000000;
			$(".droppable-widget").each( function () {
				//if (in_drag.attr("droptarget") == $(this).attr("id")) return;
				if ($(this).attr("dropdisabled") == "true") return;
				var current = distance($(this), event.pageX, event.pageY);
				if (closest == null || current < dist)
				{
					closest = $(this);
					dist = current;
				}
			});
			$(".droppable-widget").each( function () {
				if (closest == null) return;
				if ($(this).attr('id') == closest.attr('id'))
				{
					// little hack to make sure the ddmanager has the right size for our closest friend
					$.ui.ddmanager.prepareOffsets($.ui.ddmanager.current,null); 
					$(this).width(drag_w);
					$(this).height(drag_h);
					$(this).removeClass("widget-holder-state-inactive");
					//$(this).proportions.width = drag_w;
					//$(this).proportions.height = drag_h;
				}
				else
				{
					$(this).width("auto");
					$(this).height("auto");
					$(this).addClass("widget-holder-state-inactive");
				}
			});
		}
	});
}
var last_mouse_x = 0;
var last_mouse_y = 0;

function distance(jquery, x, y)
{
	var center_x = jquery.position().left + jquery.width()/2;
	var center_y = jquery.position().top + jquery.height()/2;
	
	var dist = Math.round( (x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) );
	return dist;
}

function widget_moveable(widget, instance)
{
	if (in_drag == null)
		$("#widget_" + widget + "_" + instance).draggable('enable'); 
}
function widget_unmoveable(widget, instance)
{
	if (in_drag == null)
		$("#widget_" + widget + "_" + instance).draggable('disable'); 
}	
function removeWidget(widget, instance)
{
	if (confirm("Are you sure you want to do that?"))
	{
		var wdiv = $("#widget_" + widget + "_" + instance);
		$("#" + wdiv.attr("droptarget")).remove();
		wdiv.remove();
		$("<div/>").load("/serv?c=remove-user-widget&raw=true&id=" + widget + "&instance=" + instance);
	}
}

function saveLayout()
{
	if (!dreamer.logged_in) 
	{
		$("#login_dialog").dialog({
			closeOnEscape: false
		});
		return;
	}

	var page = $("#page_layout").attr("page");
	var theme = $("#page_layout").attr("theme");
	var url = "/serv?c=save-layout&page=" + page + "&theme=" + theme + "&";
	for (cell = 1; cell <= 4; cell++)
	{
		$("#cell_" + cell + " .save-widget").each( function () {
			var widget = $(this).attr("widget");
			var instance = $(this).attr("instance");
			url += "widget_id=" + widget + "-" + instance + "&";
			url += "cell_id=" + cell + "&"; 
		});
	}
	// ok.. now we really save the layout
	attempt(url, 
		function () {
			if (theme) {
				// do nothing
				$("#page_message").html("changes saved");
				clearPageMessage();
			}
		},
		function (error) {
			$("#page_message").html("Unable to save " + error);
			clearPageMessage();
		}
	);
}

function show_editors()
{
	$(".draggable-widget").each(function () {
		$(this).addClass("widget-edit-over");
		$(this).removeClass("widget-edit-out");
		$(this).find(".widget-editbox").css({ visibility: 'visible' });
		$(this).draggable("disable");
	});
}		
function hide_editors()
{
	$(".draggable-widget").each(function () {
		$(this).removeClass("widget-edit-over");
		$(this).addClass("widget-edit-out");
		$(this).find(".widget-editbox").css({ visibility: 'hidden' });
		$(this).draggable("enable");
	});
}		


function clearPageMessage()
{
	setTimeout('$("#page_message").html("")', 4000);
}