var LastWindowIndex = 1;
var Loaded = false;
var OpenActions = new Array();
var CancelButtonReloads = false;
var OpenTextArea = "";
var AJAXNamespace = "";
//window.onload = LoadState;

var windowsInternetExplorer = false;

function detectBrowser()
{
	// Cute comment
    windowsInternetExplorer = false;
    var appVersion = navigator.appVersion;
    if ((appVersion.indexOf("MSIE") != -1) &&
        (appVersion.indexOf("Macintosh") == -1))
    {
        windowsInternetExplorer = true;
    }
}
detectBrowser();

//For debug purpose.
function Store(Name, Type)
{
	if (!SmailPound[Type])
		SmailPound[Type] = new Array();
	
	SmailPound[Type].push(Name);
}

function SetupPage()
{
	SetupRollovers();
	SetupPNGs();
}

function SetupRollovers()
{
	if (!document.images) return;
	if (!document.getElementById) return;

	var PreloadArray = new Array();
	var ImageArray = document.getElementsByTagName('img');

	
	for (var i = 0; i < ImageArray.length; i++)
	{
		var ImageObject = ImageArray[i];
		
		if (ImageObject.src.indexOf("Off.") != -1)
		{
			var OffSource = ImageObject.src;
			var OnSource = ImageObject.src.replace('Off.', 'On.');

			ImageObject.OffSource = OffSource;
			ImageObject.OnSource = OnSource;

			PreloadArray[i] = new NewImage(OnSource);
	
			if (ImageObject.className != "CustomRollover")
			{
				ImageArray[i].onmouseover = function()
				{
					this.src = this.OnSource;
				}
	
				ImageArray[i].onmouseout = function()
				{
					this.src = this.OffSource;
				}
			}
		}
	}
	Loaded = true;
}

function NewImage(arg)
{
	if (document.images)
	{
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function GenerateAction(OpenAction)
{	
	
	// Show loading status
	ShowWindow("Loading");
	
	// Push action
	OpenActions.push(OpenAction);
	
	// Get action information
	Namespace = OpenAction["Namespace"];
	DefaultValues = OpenAction["Default_Values"];
	Temporary = OpenAction["Temporary"];
	URL = OpenAction["URL"];
	
	// Create window if necessary
	var WindowElement = document.getElementById(Namespace + "-Window")
	if (!WindowElement)	
	{
		var SpanElement = document.createElement("span");
		
		// Make IE use "absolute" rather than default to "static"
		if (BrowserDetect.browser == "Explorer")
		{
			SpanElement.innerHTML = "<div id=\"" + Namespace + "-Window"+ "\" class=\"DynamicSite DynamicSite_Window\" style=\"position:absolute\"></div>";
		}
		else
		{
			SpanElement.innerHTML = "<div id=\"" + Namespace + "-Window"+ "\" class=\"DynamicSite DynamicSite_Window\"></div>";
		}
		ExternalElement = document.getElementById("ExternalHTML");
		ExternalElement.appendChild(SpanElement);	
		WindowElement = SpanElement.lastChild;
	}
	
	// Write response function	
	Response = function () {	
		// Hide status
		HideWindow("Loading");
		
		//Get action information
		OpenAction = OpenActions[OpenActions.length-1];
		Namespace = OpenAction["Namespace"];
		DefaultValues = OpenAction["Default_Values"];
		Temporary = OpenAction["Temporary"];
		URL = OpenAction["URL"];
		
		//Populate window
		UpdateValues(DefaultValues, Namespace);
		if (Temporary)
			UpdateValues("Temporary=1", Namespace);
		
		//Show window
		ShowWindow(Namespace);
	};
	
	//Fill window with a URL and response function
	Fill(WindowElement, URL, Response);	
}

function Remove(Type, Alias, DefaultValues)
{
	// Process
	Namespace = "Remove-" + Type + "-" + Alias;
	URL = "/Type/" + Type + "/" + Alias + "/Remove/Raw";	
	OpenAction = new Array();
	OpenAction["Namespace"] = Namespace;
	OpenAction["Default_Values"] = DefaultValues;
	OpenAction["URL"] = URL;
		
	// Generate window
	GenerateAction(OpenAction);
}

function Edit(Type, Alias, Temporary)
{
	// Process
	Namespace = "Edit-" + Type + "-" + Alias;
	URL = "/Type/" + Type + "/" + Alias + "/Edit/Raw";
	OpenAction = new Array();
	OpenAction["Namespace"] = Namespace;
	OpenAction["URL"] = URL;
	if (Temporary)
		OpenAction["Temporary"] = 1;
		
	// Generate window
	GenerateAction(OpenAction);
}


function SetInputValues(Namespace)
{	
	for (i = 1; i < SetInputValues.arguments.length; i++)
	{	
		Argument = arguments[i].split("=");
		Input = document.DynamicForm[Namespace + "-" +Argument[0]];
		if (Input != null)
		{
			Input.value = Argument[1];
			var Success = "Yay";
		}
	}
}

function ShowWindow(Namespace)
{		
	var BackgroundElement = document.getElementById("DynamicSite_Lightbox");
	BackgroundElement.style.zIndex = LastWindowIndex;
	BackgroundElement.style.display = "block";
	LastWindowIndex++;
	
	var WindowElement = document.getElementById(Namespace + "-Window");
	WindowElement.style.zIndex = LastWindowIndex;
	LastWindowIndex++;
	RepositionWindow(WindowElement);
	WindowElement.style.visibility = "visible";
	WindowElement.focus();
//	FadeIn( Namespace + "-Window", 0);
}

//function FadeIn(Name, LastPercent)
//{
//	SetOpacity(document.getElementById(Name), 100);
//	return; 
//	
//	NewPercent = LastPercent + 25;
//	SetOpacity(document.getElementById(Name), NewPercent);
//	if (NewPercent < 100)
//		setTimeout("FadeIn(\"" + Name + "\", " + NewPercent + ")", 70);
//}



function RepositionWindow(WindowElement)
{
	//Todo: BrowserCheck and IE code.
	ElementWidth  = WindowElement.offsetWidth;
	ElementHeight = WindowElement.offsetHeight;
	
	CalculatedLeft = Math.floor((950 - ElementWidth) / 2);
	CalculatedTop = Math.floor((480 + 130 - ElementHeight) / 2);
	WindowElement.style.left =  CalculatedLeft + "px";
	WindowElement.style.top =  CalculatedTop + "px";	
}

function SetOpacity(Element, Opacity)
{
	if (Opacity == 100)
		Opacity = "1.0";
	else
		Opacity = Opacity / 100;
	// IE/Win
//	Element.style.filter = "alpha(opacity:" + (Opacity * 100) + ")";
	// Safari<1.2, Konqueror
//	Element.style.KHTMLOpacity = Opacity;

	// Older Mozilla and Firefox
//	Element.style.MozOpacity = Opacity;

	// Safari 1.2, newer Firefox and Mozilla, CSS3
	Element.style.opacity = Opacity;
}

function RefreshWindow()
{
	// gets the name , regenerates action.
}

//{Name:String = Name of Window,  RemoveWindow:Boolean  = Remove Window from DOM } 
function HideWindow(Name, RemoveWindow)
{
	LastWindowIndex -= 2;
	var BackgroundElement = document.getElementById("DynamicSite_Lightbox");
	BackgroundElement.style.zIndex = LastWindowIndex - 2;
	if (LastWindowIndex == 1)
		BackgroundElement.style.display = "none";
		
	var WindowElement = document.getElementById(Name + "-Window");
	
//	SetOpacity(Element, 0);
	WindowElement.style.visibility = "hidden";
	WindowElement.style.top = "-1000px";		
	if (RemoveWindow)
	{
		WindowElement.parentNode.removeChild(WindowElement);
	}


//	FadeOut( Name + "-Window", 100, RemoveWindow);
}

/*function FadeOut(Name, LastPercent, RemoveWindow)
{
	Element = document.getElementById(Name);
	
//	SetOpacity(Element, 0);
	Element.style.visibility = "hidden";
	Element.style.top = "-1000px";		
	if (RemoveWindow)
	{
		Element.parentNode.removeChild(Element);
	}
	return false; 
	
	NewPercent = LastPercent - 25;
	Element.style.opacity = NewPercent / 100;
	if (NewPercent > 0)
	{
		var TimeOutString = "FadeOut(\"" + Name + "\", " + NewPercent + "," + RemoveWindow +")";
//		Debug(TimeOutString);
		setTimeout(TimeOutString, 10);
	}
	else
	{
		Element.style.visibility = "hidden";
		Element.style.top = "-1000px";		
		
		if (RemoveWindow)
		{
			Element.parentNode.removeChild(Element);
		}
	}
}
*/

function SelectImage(Name, Value, ThumbnailFile)
{
	document.DynamicForm[Name].value = Value;
	Preview = document.getElementById(Name + "-Preview");
	if (Preview)
		Preview.src = ThumbnailFile;
	HideWindow(Name);
}

function SubmitAsynchronousFile(Name)
{
	//process 
	document.DynamicForm.target ="DynamicSite_File";
    UpdateValue(document.DynamicForm["HandleFile"], Name);
	document.DynamicForm.submit();

	// set loading status
	UpdateValueById("Loading-Text", "Uploading File");
	ShowWindow("Loading");
	
	//clean up
	document.DynamicForm.target ="";
    UpdateValue(document.DynamicForm["HandleFile"], "");	
}

function SubmitAsynchronousFileResponse(Name, Value)
{
	// remove loading status
	HideWindow("Loading");
			
	// set path
	UpdateValueById(Name + "-Path", Value);
}

function SubmitAsynchronousGlobalAction()
{
	SubmitAsynchronousAction(document.DynamicForm["Submit_Action"].value, document.DynamicForm["Submit_Namespace"].value, true);
}


function SubmitAsynchronousAction(Action, Namespace, UseAJAX)
{
	document.getElementById("Submit_Action").value = Action;
	document.getElementById("Submit_Namespace").value = Namespace;
	
	if (UseAJAX)
	{
		// Set target and submit method
		document.DynamicForm.target = "";
		document.getElementById("Submit_Method").value = "AJAX";
		AJAXNamespace = Namespace;
		
		// Prepare POST parameters
		var Parameters = "";
		var Inputs = document.getElementsByTagName("input");
		for (InputIndex = 0; InputIndex < Inputs.length; InputIndex++)
		{
			if (Inputs[InputIndex].type == "checkbox")
			{
				if (Inputs[InputIndex].checked)
					Parameters += "&" + Inputs[InputIndex].name + "=" + "1";
				else
					Parameters += "&" + Inputs[InputIndex].name + "=" + "0";
			}
			else
				Parameters += "&" + Inputs[InputIndex].name + "=" + escape($F(Inputs[InputIndex]));
		}
			
		var Inputs = document.getElementsByTagName("select");
		for (InputIndex = 0; InputIndex < Inputs.length; InputIndex++)
			Parameters += "&" + Inputs[InputIndex].name + "=" + escape($F(Inputs[InputIndex]));
			
		var Inputs = document.getElementsByTagName("textarea");
		for (InputIndex = 0; InputIndex < Inputs.length; InputIndex++)
			Parameters += "&" + Inputs[InputIndex].name + "=" + escape($F(Inputs[InputIndex]));
		
		// Submit
		var ActionAjax = new Ajax.Request(
			"/",
			{
				method: 'post',
				parameters: Parameters,
				onComplete: AsynchronousActionResponse
			});
	}
	else
	{
		// Set target and submit method
		document.DynamicForm.target ="DynamicSite_Frame";
		//document.DynamicForm.target ="DynamicSite_Frame";
		document.getElementById("Submit_Method").value = "Form";
		
		// Submit
		document.DynamicForm.submit();
	
		// Show loading window
		UpdateValueById("Loading-Text", "Uploading File");
		ShowWindow("Loading");
	}
	
	// Show spinning loading icon
	var LoadingElement = document.getElementById(Namespace + "-Loading");
	if (LoadingElement)
		LoadingElement.style.display = "inline";
}

function AsynchronousActionResponse(OriginalRequest)
{
	Debug(OriginalRequest.responseText);
	//get namespace
	Namespace = AJAXNamespace;
	AJAXNamespace = "";
	
	var Result = OriginalRequest.responseText.substring(OriginalRequest.responseText.indexOf("<Result>"), OriginalRequest.responseText.length);
	Result = Result.substring(0, Result.indexOf("</Result>") + 9);
	InnerResult = Result.substring(8, Result.length - 9);
	Debug(InnerResult);
	eval(InnerResult);
	
	//set display status
	var LoadingElement = document.getElementById(Namespace + "-Loading");
	if (LoadingElement)
		LoadingElement.style.display = "none";
}

function SubmitFormWithAction(Action,Namespace)
{
	document.getElementById("Submit_Method").value = "NonAJAX";
	SetFormAction(Namespace, Action);
	document.DynamicForm.submit();
}

function UpdateValues(Values, Namespace)
{	
	if (Values)
	{
		// tentative function with tentative format:  ElementName=ElementValue, ElementName2=ElementValue2, ...		
		Pairs = Values.split(",");
		for (PairIndex = 0; PairIndex < Pairs.length; PairIndex++)
		{
			PairParts = Pairs[PairIndex].split("=");
			ElementName = Namespace + "-" + PairParts[0];
			ElementValue = PairParts[1];
			var UpdateElement =  null;
			UpdateElement = document.getElementById(ElementName);
//			alert("" + ElementName + " = " + ElementValue);
			
			//if visible, set its value
			if (UpdateElement)
			{
				Debug(" Found.")
				UpdateValue(UpdateElement, ElementValue);
			}
				
			//if not visible, add as a hidden input
			else 
			{
				Debug(" Did Not Found.!!!")
				NewElement = document.createElement("span");
				NewElement.innerHTML = "<input type=\"hidden\" class=\"DynamicSite_Input\" name=\"" + ElementName +"\" id=\"" + ElementName +"\" value=\"" + ElementValue +"\">";
				document.DynamicForm.appendChild(NewElement);
			}
		}
	}
}


function UpdateValueById(ContainerID, NewContent)
{
	UpdateElement = document.getElementById(ContainerID);
	if (UpdateElement)
		UpdateValue(UpdateElement, NewContent);
}

function UpdateValue(ContainerElement, NewContent)
{
	Debug ( "SETTING '" + ContainerElement.toString() + "' TO '" +  NewContent + "'");
	TagName = ContainerElement.tagName.toLowerCase();
	Debug( TagName);
	switch (TagName)
	{
		case "textarea":
		case "span":
//			Debug("Setting!!!");
	    	ContainerElement.innerHTML = NewContent;
	    	break;
	    case "select":
	    	ElementOptions = ContainerElement.options;
	    	OptionIndex = 0;
	    	OptionFound =  false;
	    	while ( OptionIndex < ElementOptions.length && !OptionFound)
	    	{
				OptionValue =	ElementOptions[OptionIndex].value
	    		Debug ( "'" + OptionValue +"' =='"+ NewContent +"' ?");
	    		if (OptionValue == NewContent)
	    			OptionFound = true;
	    		else
		    		OptionIndex++;
	    	}
	    	if (OptionFound)
		    	ContainerElement.selectedIndex = OptionIndex;
		    break;
		case "input":
	   		if (ContainerElement.type == "checkbox")
	   		{
	   			if (NewContent == 1)
	   				ContainerElement.checked = true;
	   			else
	   				ContainerElement.checked = false;
	   		}
		   	else 	
		   		ContainerElement.value = NewContent; 
		   	break;
	    
	}
}

function UpdateElementWithSwipe(ContainerElement, NewContent)
{
	if (ContainerElement.innerHTML == NewContent)
		return;
	var OriginalHeight = Element.getDimensions(ContainerElement).height;
	ContainerElement.style.display = "none";
	ContainerElement.style.height = "";
	ContainerElement.innerHTML = NewContent;
	var TargetHeight = Element.getDimensions(ContainerElement).height;
	ContainerElement.style.height = OriginalHeight + "px";
	ContainerElement.style.overflow = "hidden";
	ContainerElement.style.display = "block";
//	Debug(Dimensions.height);
	setTimeout("UpdateElementWithSwipePartial('" + ContainerElement.id + "', " + OriginalHeight + ", " + TargetHeight + ", 0, 10);", 10);
}

function UpdateElementWithSwipePartial(ElementID, OriginalHeight, TargetHeight, CurrentStep, TotalSteps)
{
	var CurrentElement = document.getElementById(ElementID);
	var NewHeight = Math.floor(OriginalHeight + (TargetHeight - OriginalHeight) * CurrentStep / TotalSteps);
	CurrentElement.style.height = NewHeight + "px";
	CurrentStep++;
//	Debug (NewHeight);
	if (CurrentStep < TotalSteps)
		setTimeout("UpdateElementWithSwipePartial('" + ElementID + "', " + OriginalHeight + ", " + TargetHeight + ", " + CurrentStep + ", " + TotalSteps + ");", 10);
}

function SetFormAction(Namespace, Action)
{
	document.DynamicForm["Submit_Action"].value = Action;
	document.DynamicForm["Submit_Namespace"].value = Namespace;	
}

function SubmitFormWithData(Name, HiddenName, HiddenValue)
{
	Name = Name  + "-Form";	
	var form = document.getElementById(Name);
	form.innerHTML += "<input type=\"hidden\" name=\"" + HiddenName + "\" value=\"" + HiddenValue + "\" />";
	form.submit();
}

function SubmitForm(Name)
{
	Name = Name  + "-Form";
	document.getElementById(Name).submit();
}

function SubmitAJAXForm(FormID)
{
	var ajax = new Ajax.Updater(
		{success: 'AJAXResponse'},
		"/test.asp",
		{
			method: 'get',
			parameters: Form.serialize(FormID),
			evalScripts: true
		}
	);
}

function insertAtCursor(TextArea, Value) 	// from phpMyAdmin
{
	//IE
	if (document.selection) 
	{
		TextArea.focus();
		sel = document.selection.createRange();
		sel.text = Value;
	}
	
	//MOZILLA/NETSCAPE
	else if (TextArea.selectionStart || TextArea.selectionStart == '0')
	{

		var startPos = TextArea.selectionStart;
		var endPos = TextArea.selectionEnd;
		var cursorPos = Value.length + startPos;
		
		TextArea.value = TextArea.value.substring(0, startPos)
		+ Value
		+ TextArea.value.substring(endPos, TextArea.value.length);
		
		TextArea.selectionStart = cursorPos;
		TextArea.selectionEnd = cursorPos;
	} 
	else {
		TextArea.value += Value;
	}
}

function HandleTextKeyPress(e, Element)
{
//	Debug("hey");
	return false;
}

function ToggleTextArea(Element)
{	
	if (OpenTextArea == "")
	{
		TextArea  = $('DynamicSite-Data_Input-TextArea');
		TextArea.value = Element.value;
		OpenTextArea = Element.id;
		ShowWindow("DynamicSite-Data_Input");
	}
	else
	{
		TextArea  = document.getElementById(OpenTextArea);
		TextArea.value = Element.value;
		OpenTextArea = "";
		HideWindow("DynamicSite-Data_Input");
	}
}


function HandleTextAreaKeyPress(e, Element)
{
	// Mozilla only.
	// TODO: Back bracket doesn't work at  top line, neither bracket works when cursor is at end of line.
	var OpenBracket = 27;
	var CloseBracket = 29;	
	var ToggleWindow = 112; // ctrl + P
	var SafariToggleWindow = 16; // ctrl + P
	var EscapeKey = 27;
	
	// Show/Hide zoomed text area when Control-P is pressed
	if ((e.which == ToggleWindow || e.which == SafariToggleWindow) && e.ctrlKey)
	{
		ToggleTextArea(Element);
		return false;
	}
	
	//TODO: same fucking code as open bracket!!!
	// to support safari just use .keycode to avoid conflicts (e.which = mozillacode... || e.keycode = safaricode...)

	// Hide zoomed text area when Escape is pressed
//	if (e.which == EscapeKey && OpenTextArea != "")
//	{
//		ToggleTextArea(Element);
//		return false;
//	}


	// TODO: this doesn't really belong in handle text area, does it? 
	// Cancel top window if Escape is pressed
//	if (e.which == EscapeKey)
//	{
//		HideTopWindow();
//		return false;
//	}
	
	if (e.which == CloseBracket && e.ctrlKey)
	{		
		// Indent lines
		if (Element.selectionStart || Element.selectionStart == 0)
		{
		    ScrollPosition = Element.scrollTop;	
			StartPosition = Element.selectionStart;
			EndPosition = Element.selectionEnd;
			Affected = 0;
			
			LastNewLinePosition = Element.value.substring(0,StartPosition).lastIndexOf("\n");		
			if (LastNewLinePosition < 0)
			{
				Element.value = String.fromCharCode(9) +  Element.value;
				LastNewLinePosition = 0;
				Affected ++;
			}
			ReplaceArea = Element.value.substring(LastNewLinePosition, EndPosition);
			Matches = ReplaceArea.match(/\n/g);
			if (Matches)
				Affected += Matches.length;
			ReplaceArea = ReplaceArea.replace(/\n/g, "\n" + String.fromCharCode(9));
			ReplaceValue = Element.value.substring(0,LastNewLinePosition) + ReplaceArea + Element.value.substring(EndPosition);			
			Element.value = ReplaceValue;	
			
			EndPosition += Affected;
			NextNewLinePosition = EndPosition +  Element.value.substring(EndPosition).indexOf("\n");
			if (NextNewLinePosition < 0)
				NextNewLinePosition = Element.value.length-1;
			Element.selectionStart = LastNewLinePosition + 1;
			Element.selectionEnd = NextNewLinePosition;			
			Element.scrollTop = ScrollPosition;
		}
		return false;
	}
	
	if (e.which == OpenBracket && e.ctrlKey)
	{
		// unindent lines.	
		    ScrollPosition = Element.scrollTop;
			StartPosition = Element.selectionStart;
			EndPosition = Element.selectionEnd;
			Affected = 0;
			
			LastNewLinePosition = Element.value.substring(0,StartPosition).lastIndexOf("\n");		
			if (LastNewLinePosition < 0)
			{
				Element.value = Element.value.replace("\n\t", "\n");
				LastNewLinePosition = 0;
				Affected ++;
			}			
			ReplaceArea = Element.value.substring(LastNewLinePosition, EndPosition);
			Matches = ReplaceArea.match(/\n\t/g);
			if (Matches)
				Affected += Matches.length;
			ReplaceArea = ReplaceArea.replace(/\n\t/g, "\n");
			ReplaceValue = Element.value.substring(0,LastNewLinePosition) + ReplaceArea + Element.value.substring(EndPosition);			
			Element.value = ReplaceValue;	
			
			EndPosition -= Affected;
			NextNewLinePosition = EndPosition +  Element.value.substring(EndPosition).indexOf("\n");
			if (NextNewLinePosition < 0)
				NextNewLinePosition = Element.value.length-1;
			Element.selectionStart = LastNewLinePosition+ 1;
			Element.selectionEnd = NextNewLinePosition;			
			Element.scrollTop = ScrollPosition;
		return false;
	}

}

function HandleTextAreaFocus(Element)
{
	Element.rows = "15";
}

function HandleTextAreaBlur(Element)
{
		Element.rows  = "2";
}

function ProcessTab(ElementID)
{
	insertAtCursor(document.getElementById(ElementID), String.fromCharCode(9));
	setTimeout("SetFocus('" + Element.id + "')", 20);
}

function SetFocus(ElementID)
{
	document.getElementById(ElementID).focus();
}

function ItemChanged()
{
//	TODO: If you want to be more specific , 
//add/edit/remove -property: 
//    add/rename/remove property in property list of edit-type-itemtype
//    add/rename/remove input in property list of edit-itemtype, add-itemtype
//
// add/edit - type
//    adds/renames/removes type to type dropdowns
//    adds/renames/removes type to page.
//   
//   
//add - item:
//    adds item to dropdowns of properties of item type and single 
//    
//edit/remove -item
//   removes/renames item in dropdowns of propertties of item type and single
//   removes/renames item in binidng lists of properties of item type and multiple


	// Hides the top window and refreshes the window behind it.
	OpenActionsCount = OpenActions.length;
	if (OpenActionsCount <= 1)
	{
		//HideWindow(OpenAction["Namespace"], true);
		ReloadPage();
	}
	else
	{
		OpenAction = OpenActions.pop();
		HideWindow(OpenAction["Namespace"], true);
		
		//TODO: Should be a more refresh window function
		OpenAction = OpenActions.pop();
		GenerateAction( OpenAction);
	}
	
	// TODO: repopulate all the open windows at once.
	// Oh boy, now when you close a window it regets the one behind it.
	CancelButtonReloads = true;
}

function ReloadPage()
{
	var CurrentURL = window.location.href;
	var PoundPosition = CurrentURL.indexOf("#");
	if (PoundPosition != -1)
	{
		CurrentURL = "/" + CurrentURL.substring(PoundPosition + 1);
		document.location = CurrentURL;
	}
	else
		document.location = document.location;
}

function HideTopWindow()
{
	OpenAction = OpenActions.pop();
	SubmitAsynchronousAction("Cancel", OpenAction["Namespace"], true);
	HideWindow(OpenAction["Namespace"], true);	
	if (CancelButtonReloads)
	{
		//TODO: Should be a more refresh window function
		OpenAction = OpenActions.pop();
		if (OpenAction != null)
			GenerateAction( OpenAction);
		else
			ReloadPage();	
	}
}

function Debug(DebugString)
{
	return;
	DebugDiv = document.getElementById("Debug");
	if (DebugDiv)
	{
		DebugString = DebugString.replace(/>/g,"&#62;");
		DebugString = DebugString.replace(/</g,"&#60;");
		DebugString = DebugString.replace(/\//g,"&#47;");
		DebugString = DebugString.replace(/\n/g,"<br/>");
		DebugDiv.style.display = "block";
		DebugDiv.innerHTML += DebugString + "<br/>";
		
		LightboxElement = $("DynamicSite_Lightbox");
		LightboxElement.style.top = DebugDiv.offsetHeight + "px";
	}
}

function NameChanged(Namespace, Name)
{
	UpdateValueById(Namespace + "-Alias", NameAsAlias(Name));
}

function AliasChanged(ID)
{
	//mark this field as edited, which should override the automatic functionality...
}

function NameAsAlias(Name)
{	
	var Alias = Name.replace(/[( )\\/_.-]+/g, "_");
//	Debug(Alias);	
	Alias = Alias.replace(/^_[0-9A-Za-z]/g, "");
//	Debug(Alias);
	return Alias;
}

function Fill(ElementID, URL, Response, Show_Loading_Icon)
{	
	//TODO : Get rid of AJAX Updater so that Element.update is not a function error doesn't happen SOMETIMES.
	// Just fo' the record, it only happens AFTER you call Add Property and Add Inline Item .... FUCKOING CCRAZY RIGHT ?
	var Current_Element = document.getElementById(ElementID);
	if (Show_Loading_Icon)
//		Current_Element.innerHTML = "<img src=\"/jelly/images/loading.gif\" alt=\"Loading\"/>";
		Current_Element.innerHTML = "&nbsp;&nbsp;&nbsp;Loading...";
	var myAjax = new Ajax.Updater(
	ElementID, 
	URL,
	{
		method: 'post', 
		onComplete: Response,
		onException: function (request, exception) { }
	});	
}

var LastURL = "";
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 != LastURL)
	{
		LastURL = CurrentURL;
		CurrentURL = CurrentURL.replace(/\/*$/g, "");
	
		// Set loading status.
		LoadingIndicator = $('Last_Path_Item-Loading');
		if (LoadingIndicator)
			LoadingIndicator.style.display = "block";	
		
		if (CurrentURL == "")
			var RequestURL = "/" + "Site/Default_Page" + "/Raw";
		else
			var RequestURL = "/" + CurrentURL + "/Raw";
		
		//Remove loading status
		Response = function()
		{
			LoadingIndicator = $('Last_Path_Item-Loading');
			if (LoadingIndicator)
				LoadingIndicator.style.display = "none";
		};
		
		Fill("Last_Path_Item", RequestURL, Response);
	}
}

function Start_Dynamic_Site()
{
	// Watch address bar
	setInterval("Watch_Address_Bar();", 100);
}

function SetLocation(NewLocation)
{
	// Set loading status.
	LoadingIndicator = $('Last_Path_Item-Loading');
	if (LoadingIndicator)
		LoadingIndicator.style.display = "block";
	
	// etc....
	var CurrentURL = document.location.href;
	var PoundPosition = CurrentURL.indexOf("#");
	if (PoundPosition != -1)
		CurrentURL = CurrentURL.substring(PoundPosition + 1);
	else
		CurrentURL = "Site/Default_Page";

	var PoundPosition = NewLocation.indexOf("#");
	if (PoundPosition != -1)
		NewLocation = NewLocation.substring(PoundPosition + 1);		
		
	//Remove loading status
	Response = function()
	{
		LoadingIndicator = $('Last_Path_Item-Loading');
		if (LoadingIndicator)
			LoadingIndicator.style.display = "none";
	};

	if (CurrentURL == NewLocation)
	{
		Fill("Last_Path_Item", "/" + CurrentURL + "/Raw", Response);
	}
	else
	{
		// Hacked redirect for Safari supresses the infinite spinning loading icon
		if (BrowserDetect.browser == "Safari")
		{
			var Redirect_Form = document.getElementById("Redirect_Form");
			if (!Redirect_Form)
			{
				// Create redirect form
				var Body_Element = document.getElementsByTagName('body')[0];
				var Redirect_Form = document.createElement("form");
				Redirect_Form.setAttribute("id", "Redirect_Form");
				Redirect_Form.setAttribute("name", "Redirect_Form");
				Redirect_Form.setAttribute("action", "");
				Redirect_Form.setAttribute("method", "get");
				Body_Element.appendChild(Redirect_Form);
			}
			Redirect_Form.action = "#" + NewLocation;
			Redirect_Form.submit();
		}
		else
			document.location.href = "#" + NewLocation;
	}
}