var Dependencies = new Object();
var Dependencies_By_Namespace = new Object();
var Focused_Action_Namespace = "";
var LastURL = "";
var Last_Path_Item_Namespace;

function Load_Video(Container_ID, URL)
{
	$(Container_ID + "_Player").Load_Video(URL);
}

function Play_Video(Container_ID)
{
	$(Container_ID + "_Player").Play_Video();
}

function Stop_Video(Container_ID)
{
	$(Container_ID + "_Player").Stop_Video();
}

function Create_Video_Player(Container_ID, Width, Height)
{
	var Jelly_Flash_Video_Player_Writer = new SWFObject("/jelly/Flash/Jelly_Flash_Video_Player.swf", Container_ID + "_Player", Width, Height, "9");
	Jelly_Flash_Video_Player_Writer.addVariable("wmode", "transparent");
	Jelly_Flash_Video_Player_Writer.write(Container_ID);
}

function Video_Update(Player_ID, Update_Type, Update_Description, Bytes_Loaded, Bytes_Total)
{
	switch (Update_Type)
	{
		case "Play":
			break;
		case "Stop":
			break;
		case "Complete":
			break;
		case "Progress":
			break;
		case "Error":
			document.title = "Player error: " + Update_Description;
			break;
	}
}
					
var Directory;
var Directory_Set = false;
function Start_Jelly(New_Directory)
{
	Directory = New_Directory;
	Directory_Set = true;
//	alert("DIR: " + Directory);
//	console.log(Directory);
	//document.addEventListener("keydown", Open_Interface,true);
	
	document.addEventListener('click', Document_Click, true);
	
	// Watch address bar
	setInterval("Watch_Address_Bar();", 100);
	
	// Write Flash
	Flash_Container_Item = document.createElement("div");
	Flash_Container_Item.id = "Jelly_Flash_Extras_Container";
	Flash_Container_Item.style.position = "absolute";
	Flash_Container_Item.style.left = "0px";
	Flash_Container_Item.style.top = "0px";
	Flash_Container_Item.style.width = "5px";
	Flash_Container_Item.style.height = "5px";
	Body_Item = $("Body");
	Body_Item.appendChild(Flash_Container_Item);
	var Jelly_Flash_Extras_Writer = new SWFObject("/jelly/Flash/Jelly_Flash_Extras.swf", "Jelly_Flash_Extras", "1", "1", "9");
	Jelly_Flash_Extras_Writer.addVariable("wmode", "transparent");
	Jelly_Flash_Extras_Writer.write("Jelly_Flash_Extras_Container");
}

function Execute_Action(Namespace)
{
	var Parameters = new Object();
	Parameters["Parameters"] = new Object();
	
	// Add regular inputs
	var Inputs = document.getElementsByTagName("input");
	for (InputIndex = 0; InputIndex < Inputs.length; InputIndex++)
	{
		if (Inputs[InputIndex].id.substring(0, Namespace.length) == Namespace)
		{
			if (Inputs[InputIndex].type == "checkbox")
			{
				if (Inputs[InputIndex].checked)
					Parameters["Parameters"][Inputs[InputIndex].name] = "1";
				else
					Parameters["Parameters"][Inputs[InputIndex].name] = "0";
			}
			else
				Parameters["Parameters"][Inputs[InputIndex].name] = $F(Inputs[InputIndex]);
		}
	}
	
	// Add select menu inputs
	var Inputs = document.getElementsByTagName("select");
	for (InputIndex = 0; InputIndex < Inputs.length; InputIndex++)
		if (Inputs[InputIndex].id.substring(0, Namespace.length) == Namespace)
			Parameters["Parameters"][Inputs[InputIndex].name] = $F(Inputs[InputIndex]);
	
	// Add textarea inputs
	var Inputs = document.getElementsByTagName("textarea");
	for (InputIndex = 0; InputIndex < Inputs.length; InputIndex++)
		if (Inputs[InputIndex].id.substring(0, Namespace.length) == Namespace)
			Parameters["Parameters"][Inputs[InputIndex].name] = $F(Inputs[InputIndex]);
	
	Parameters["Namespace"] = Namespace;
	Parameters["Action"] = $F(Namespace + "_Action");
	
	Execute_Action_With_Parameters(Parameters);
}

function Execute_Action_With_Parameters(Parameters)
{
	if (Parameters["Namespace"])
		Namespace = Parameters["Namespace"];
	else
		Namespace = "Action";
	
	// Prepare POST parameters
	var Post_Parameters = "";
	Post_Parameters += "&" + "Submit_Action" + "=" + Parameters["Action"];
	Post_Parameters += "&" + "Submit_Namespace" + "=" + Namespace;
	Post_Parameters += "&" + "Submit_Method" + "=" + "AJAX";
	
	// Add parameters
	for (Parameter_Index in Parameters["Parameters"])
	{
		Post_Parameters += "&" + (Namespace + "_" + Parameter_Index) + "=" + encodeURIComponent(Parameters["Parameters"][Parameter_Index]);
		Post_Parameters = Post_Parameters.replace("+", "%2B");
	}
	
	// Show spinning loading icon
	var LoadingElement = $(Namespace + "_Loading");
	if (LoadingElement)
		LoadingElement.style.display = "inline";
	
	// Submit
	var ActionAjax = new Ajax.Request(
		Directory + "/",
		{
			method: 'post',
			parameters: Post_Parameters,
			onComplete: function (OriginalRequest)
				{
					var Result = OriginalRequest.responseText;
//					alert(Result);
					Result.extractScripts().map(eval);
					
					var Result_Div = $(Namespace + "_Result");
					if (Result_Div)
						Result_Div.innerHTML = Result;
					
					//set display status
					var LoadingElement = $(Namespace + "_Loading");
					if (LoadingElement)
						LoadingElement.style.display = "none";
					
					Refresh_Fills();
				}
		});
}

function Fill(Parameters)
{
	if (Parameters["Element"])
		var Target_Element = Parameters["Element"];
	else
		var Target_Element = document.getElementById(Parameters["ID"]);
	
	var Loading_Element = $(Target_Element.id + "_Loading");
	
	var Destination_URL = Parameters["URL"];
	if (!Parameters["Not_From_Last_Path_Item"])
	{
		if (Destination_URL.indexOf(":") == -1)
			Destination_URL += ":From_Last_Path_Item=1";
		else
			Destination_URL += ",From_Last_Path_Item=1";
	}
	
//	console.log("FILLING: " + Target_Element.id + " :::: WITH ::: " + Destination_URL);
	
	Add_Dependency({"Namespace": Target_Element.id, "URL": Destination_URL});
	
	if (!Loading_Element)
	{
		Loading_Element = document.createElement("div");
		Loading_Element.id = Target_Element.id + "_Loading";
		Loading_Element.className = "Loading";
		Loading_Element.innerHTML = "<div style=\"height: 10px; position: relative; top: 50%; margin-top: -5px;\"><img src=\"" + Directory + "/jelly/images/loading.gif\" alt=\"Loading\" align=\"absmiddle\" /> Loading</div>";
		
		if (Parameters["Transition"] != "None")
		{
//			if (Target_Element.offsetWidth == 0)
//				Parameters["Transition"] = "None";
		}
		if (Parameters["Transition"] != "None")
		{
			var Original_Display = Target_Element.style.display;
			Target_Element.style.display = "block";
			
			var Start_Width = Target_Element.offsetWidth;
			var Start_Height = Target_Element.offsetHeight;
			
			var Original_Overflow = Target_Element.style.overflow;
			Target_Element.style.overflow = "hidden";
			var Original_Height = Target_Element.style.height;
			Target_Element.style.height = Start_Height + "px";
			
			var Destination_Element = document.createElement("div");
			Destination_Element.id = Target_Element.id + "_Content";
			Destination_Element.style.position = "absolute";
			Destination_Element.style.visibility = "hidden";
			Destination_Element.style.width = Target_Element.offsetWidth + "px";
			Target_Element.parentNode.insertBefore(Destination_Element, Target_Element);
		}
	}
	Loading_Element.style.width = Math.max(Target_Element.scrollWidth, 10) + "px";
	Loading_Element.style.height = Math.max(Target_Element.scrollHeight, 10) + "px";
	Target_Element.parentNode.insertBefore(Loading_Element, Target_Element);
	
	var Filling_Ajax = new Ajax.Request(
		Destination_URL,
		{
			method: 'post',
			onComplete: function (OriginalRequest)
				{
					var Result = OriginalRequest.responseText;
					
					Loading_Element.parentNode.removeChild(Loading_Element);
					Target_Element.innerHTML = Result;
					
					if (Parameters["Transition"] != "None")
					{
						Destination_Element.style.width = Target_Element.offsetWidth + "px";
						Destination_Element.innerHTML = Result;
						var End_Width = Destination_Element.offsetWidth;
						var End_Height = Destination_Element.offsetHeight;
//						alert(Original_Overflow + ":" + Original_Display + ":" + Original_Height);
//			alert(Start_Height + ":" + End_Height);
						Destination_Element.parentNode.removeChild(Destination_Element);
						
						Ramp_Value({"Command": "$('" + Target_Element.id + "').style.height = VALUE + 'px';", "Start_Value": Start_Height, "End_Value": End_Height, "On_Complete": function () {Target_Element.style.overflow = Original_Overflow; Target_Element.style.height = Original_Height; Target_Element.style.display = Original_Display;}});
					}
//					console.log(Result);
//					console.log("EVVVVVV");
					Result.extractScripts().map(eval);
//					console.log(Result.extractScripts());
					
					if (Parameters["Response"])
						Parameters["Response"].call();
				}
		});	
}

function Watch_Address_Bar()
{
	var CurrentURL = document.location.href;
	var PoundPosition = CurrentURL.indexOf("#");
	if (PoundPosition != -1)
		CurrentURL = CurrentURL.substring(PoundPosition + 1);
	else
		CurrentURL = "Site/Default_Page";
	if (CurrentURL == "")
		CurrentURL = "Site/Default_Page";
	
	if (CurrentURL != LastURL)
	{
//	alert(CurrentURL + ":" + LastURL);
		LastURL = CurrentURL;
		CurrentURL = CurrentURL.replace(/\/*$/g, "");
		
		if (CurrentURL == "")
			var Request_URL = "Site/Default_Page";
		else
			var Request_URL = CurrentURL;
		
		Item_Changed("Last_Path_Item");
		Refresh_Fills();
	}
}

function Set_Location(NewLocation)
{
	// etc....
	CurrentURL = document.location.href;
	var PoundPosition = CurrentURL.indexOf("#");
	if (PoundPosition != -1)
		CurrentURL = CurrentURL.substring(PoundPosition + 1);
	else
		CurrentURL = "Page/Home";

	var PoundPosition = NewLocation.indexOf("#");
	if (PoundPosition != -1)
		NewLocation = NewLocation.substring(PoundPosition + 1);		
	
	document.location.href = "#" + NewLocation;
}

function Add_Dependency(Dependency)
{
//	console.log(Dependency);
//	console.log("NEW: " + Dependency["ID"]);
	// Store dependency by its ID
	if (!Dependencies[Dependency["ID"]])
		Dependencies[Dependency["ID"]] = new Array();
	Dependencies[Dependency["ID"]].push(Dependency);
	
	// Store dependency by its namespace so parent lookups can be easily found
	if (Dependency["Namespace"])
		Dependencies_By_Namespace[Dependency["Namespace"]] = Dependency;
	
	if (Dependency["ID"] == "Last_Path_Item" && Directory_Set)
	{
//		console.log(LastURL);
//		alert("/" + LastURL + "/" + Dependency["Template"] + "/" + "Raw" + ":" + "Namespace" + "=" + Dependency["Namespace"] + ",From_Last_Path_Item=1");
		Fill({"ID": Dependency["Namespace"], "URL": Directory + "/" + LastURL + "/" + "Raw" + ":" + "Namespace" + "=" + Dependency["Namespace"] + ",From_Last_Path_Item=1"});
	}
}

var Fills = new Object();
function Item_Changed(Item_ID)
{
	var Dependency;
//	console.log("Changed: " + Item_ID);
	if (Dependencies[Item_ID])
	{
		for (Item_Index in Dependencies[Item_ID])
		{
			Dependency = Dependencies[Item_ID][Item_Index];
			if (Dependency["Namespace"])
			{
//				console.log("Starting at: " + Dependency["Namespace"]);
				while (Dependency)
				{
					if (Dependency["URL"] || Dependency["Template"])
					{
//						console.log("Fill: " + Dependency["Namespace"]);
						Dependency_Element = $(Dependency["Namespace"]);
						if (Dependency_Element)
							Fills[Dependency["Namespace"]] = Dependency;
//						else
//							console.log("Not found: " + Dependency["Namespace"]);
						Dependency = null;
					}
					else
					{
						if (Dependency["Parent_Namespace"])
							Dependency = Dependencies_By_Namespace[Dependency["Parent_Namespace"]];
						else
							Dependency = null;
					}
				}
			}
		}
	}
}

function Refresh_Fills()
{
	for (Fill_Index in Fills)
	{
		var Updates = "";
		Fill_Element = Fills[Fill_Index];
		
		var Dependency = Fill_Element;
		var Already = false;
		while (Dependency)
		{
			if (Dependency["Parent_Namespace"])
			{
//				console.log(Dependency["Parent_Namespace"]);
				Dependency = Dependencies_By_Namespace[Dependency["Parent_Namespace"]];
			}
			else
				Dependency = null;
			
			if (Dependency)
			{
				for (Second_Fill_Index in Fills)
				{
					if (Fills[Second_Fill_Index]["Namespace"] == Dependency["Namespace"])
					{
						var Already = true;
						break;
					}
				}
			}
		}
		
		if (!Already)
		{
//			console.log("FILL: " + Fill_Element["Namespace"]);
			if (Fill_Element["URL"])
			{
//				console.log(Fill_Element["URL"]);
				Fill({"ID": Fill_Element["Namespace"], "URL": Fill_Element["URL"], "Not_From_Last_Path_Item": true});
				Updates += Fill_Element["Namespace"] + " >>> " + Fill_Element["URL"] + "\n\n";
			}
			else
			{
				Fill({"ID": Fill_Element["Namespace"], "URL": Directory + "/" + LastURL + "/" + "Raw" + ":" + "Namespace" + "=" + Fill_Element["Namespace"] + ",From_Last_Path_Item=1"});
			}
			
			/*
			
				if (Dependency["Template"] != "HTML")
					Fill({"ID": Dependency["Namespace"], "URL": Request_URL + "/" + Dependency["Template"] + "/" + "Raw" + ":" + "Namespace" + "=" + Dependency["Namespace"]});
				else
					Fill({"ID": Dependency["Namespace"], "URL": Request_URL + "/" + "Raw" + ":" + "Namespace" + "=" + Dependency["Namespace"]});
			*/
		}
	}
	
	Fills = new Object();
}

function Ramp_Value(Parameters)
{
	// Parameters: Command, Start_Value (default: 0), End_Value (default: 1), Duration (milliseconds, default: 500), Start_Time (default: now)
	
	var d = new Date();
	var Current_Time = d.getTime();
	if (!Parameters["Duration"])
		Parameters["Duration"] = 500;
	if (!Parameters["Start_Time"])
		Parameters["Start_Time"] = Current_Time;
	if (!Parameters["Start_Value"])
		Parameters["Start_Value"] = 0;
	if (!Parameters["End_Value"])
		Parameters["End_Value"] = 1;
	
	var Ramp_Value_Recursive = function()
	{
		var d = new Date();
		var Current_Time = d.getTime();
		
		var Partial = (Current_Time - Parameters["Start_Time"]) / Parameters["Duration"];
		if (Partial > 1)
			Partial = 1;
		Partial = (1 - Math.pow((1 - Partial), 4));
		
		var Value = Parameters["Start_Value"] + (Parameters["End_Value"] - Parameters["Start_Value"]) * Partial;
		
		var Command = Parameters["Command"];
		Command = Command.replace(/VALUE/g, Value);
		try
		{
			eval(Command);
		}
		catch(Error)
		{
		}
		
		if (Partial < 1)
			setTimeout(Ramp_Value_Recursive, 0);
		else
			if (Parameters["On_Complete"])
				Parameters["On_Complete"]();
	}
	
	setTimeout(Ramp_Value_Recursive, 0);
}


Set_Window_Item = null;

function Hide_Set_Window()
{	
	Set_Window_Item.style.display = "none";
}

function Show_Set_Window()
{
	if (!Set_Window_Item)
		Set_Window('Set_Window_Type_Type','/Type/Type/Browse/Raw');
	else
		Set_Window_Item.style.display = "block";		
}

function Set_Window(Namespace, URL)
{
	if (!Set_Window_Item)
	{
		Set_Window_Item = document.createElement("div");
		Set_Window_Item.id = "Set_Window";
		Set_Window_Item.style.position = "absolute";
		Set_Window_Item.style.left = "0px";
		Set_Window_Item.style.top = "0px";
		Set_Window_Item.style.width = "100%";
		Set_Window_Item.style.height = "100%";
		Body_Item = $("Body");
		Body_Item.appendChild(Set_Window_Item);
	}
	Set_Window_Item.innerHTML = "<table id=\"Set_Window_Outer\" width=\"100%\" height=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td align=\"center\" valign=\"middle\" width=\"100%\" height=\"100%\" style=\"text-align:center;\"><center><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"background-color: white; border-style: solid; border-width: 1px; border-color: #cccccc; padding: 10px;\"><tr><td><div id=\"" + Namespace + "\" style=\"\"></div></td></tr></table></center></td></tr></table>";	
	Set_Window_Item.style.zIndex = 500;
	
	$('Set_Window_Outer').addEventListener('click', function (e)
		{
			Hide_Set_Window();
		},
		false);
	
	$(Namespace).addEventListener('click', function (e)
		{
			if (!e) var e = window.event;
			e.cancelBubble = true;
			if (e.stopPropagation) e.stopPropagation();
		},
		false);
			
	Fill({"ID": Namespace, "URL":URL});
	Add_Dependency({"ID": "", "Namespace":Namespace, "URL":URL});
}

var Windows = new Array();
function Add_Window(Namespace, URL)
{
	console.log(Namespace);
	console.log(URL);
	
	Clear_Menus();
	
	var Window_Item = $(Namespace);
	if (!Window_Item)
	{
		Window_Item = document.createElement("div");
		Window_Item.id = Namespace + "_Window";
		Window_Item.style.position = "fixed";
		Window_Item.style.left = "0px";
		Window_Item.style.top = "0px";
		Window_Item.style.width = "100%";
		Window_Item.style.height = "100%";
		Window_Item.innerHTML = "<table width=\"100%\" height=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td align=\"center\" valign=\"middle\"><center><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"background-color: white; border-style: solid; border-width: 1px; border-color: #cccccc; padding: 10px;\"><tr><td><div id=\"" + Namespace + "\" style=\"\"></div></td></tr></table></center></td></tr></table>";
		Body_Item = $("Body");
		Body_Item.appendChild(Window_Item);
		Windows.push(Window_Item);
	}
	Window_Item.style.zIndex = 500 + Windows.length * 2 + 1;
	
	Light_Box();
	
	Fill({"ID": Namespace, "URL": URL});
	Add_Dependency({"ID": "", "Namespace": Namespace, "URL": URL});
}

function Close_Top_Window()
{
	// Remove top window if it exists
	if (Windows.length)
	{
		var Window_Item = Windows.pop();
		Window_Item.parentNode.removeChild(Window_Item);
		
		// Move lightbox backwards
		var Lightbox_Item = $("Lightbox");
		Lightbox_Item.style.zIndex = 500 + Windows.length * 2;
		if (Windows.length == 0)
			Lightbox_Item.style.display = "none";
		
		Edit_Item = null;
	}
	
	// Or remove inline property windows
	else
	{
		Editable_Item.parentNode.removeChild(Editable_Item);
		Edit_Item.style.display = Edit_Item_Display;
		Edit_Item = null;
		Editable_Item = null;
		Edit_Item_Style = null;
		Edit_Item_Display = null;
		
		$("Lightbox_Left").style.display = "none";
		$("Lightbox_Right").style.display = "none";
		$("Lightbox_Top").style.display = "none";
		$("Lightbox_Bottom").style.display = "none";
		
		Remove_Highlight();
	}
	
	// Hide Toolbar
//	Hide_Toolbar();
	

}

function Upload_File(File_Type, Input_ID)
{
	var Jelly_Flash_Extras = $("Jelly_Flash_Extras");
	if (!Jelly_Flash_Extras)
	{
		Upload_Update("Error", "No uploader present.");
		return;
	}
	Jelly_Flash_Extras.Upload_File("/", File_Type, Input_ID);
//	$("Loading-Text").innerHTML = "Uploading";
//	ShowWindow("Loading");
}

function Upload_Update(Update_Type, Update_Description, Bytes_Loaded, Bytes_Total, Result)
{
	switch (Update_Type)
	{
		case "Update":
//			document.title = "update";
			break;
		case "Complete":
//			document.title = "Complete";
			console.log(Result);
//			alert(Result);
			eval(Result);
//			HideWindow("Loading");
			break;
		case "Progress":
//			document.title = "progress";
			break;
			if (Bytes_Loaded == Bytes_Total)
			$("Loading-Text").innerHTML = "Uploading (please wait)" + "<div style=\"width: 202px; height: 1px;\">&nbsp;</div><div style=\"position: absolute; z-index: 200; width: 200px; height: 16px; border-style: solid; border-width: 1px; border-color: #FC7C00; background-color: white;\"><div style=\"overflow: hidden; width: " +  Math.floor((Bytes_Loaded / Bytes_Total) * 200) + "px; height: 16px; background-color: #FC7C00;\">&nbsp;</div></div>";
			else
			$("Loading-Text").innerHTML = "Uploading (" + Math.floor((Bytes_Loaded / Bytes_Total) * 100) + "%)" + "<div style=\"width: 202px; height: 1px;\">&nbsp;</div><div style=\"position: absolute; z-index: 200; width: 200px; height: 16px; border-style: solid; border-width: 1px; border-color: #FC7C00; background-color: white;\"><div style=\"overflow: hidden; width: " +  Math.floor((Bytes_Loaded / Bytes_Total) * 200) + "px; height: 16px; background-color: #FC7C00;\">&nbsp;</div></div>";
			break;
		case "Error":
			alert("Error: " + Update_Description);
//			HideWindow("Loading");
			break;
	}
}

function Handle_Input_Key_Down(e)
{
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);
	if (code == 13)
	{
		Execute_Focused_Action();
		return false;
	}
	return true;
}

function Set_Focused_Action_Namespace(Namespace)
{
	Focused_Action_Namespace = Namespace;
}

function Execute_Focused_Action()
{
	Execute_Action(Focused_Action_Namespace);
}

function Clean_HTML(Text)
{
	Text = Text.replace(" class=\"Apple-style-span\"", "");
	return Text;
}