//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using CA = ComponentArt.Web.UI;
using CommunityServer.Components;

namespace CommunityServer.Controls
{
	/// <summary>
	/// Summary description for ContextMenu.
	/// </summary>
	public class ContextMenu : TabDrivenTemplatedWebControl
	{
		#region Child Controls

		private CA.Menu _menu;
		private CSContext _csContext = CSContext.Current;

		#endregion
		
		#region Public Properties

		public CA.Menu Menu
		{
			get
			{
				EnsureChildControls();
				return _menu;
			}
		}

		public string OnMenuOpenScript
		{
			get
			{
				string state = (string) ViewState["OnMenuOpenScript"];
				if (state == null)
					return String.Empty;
				else
					return state;
			}
			set
			{
				ViewState["OnMenuOpenScript"] = value;
			}
		}

		public string OnMenuCloseScript
		{
			get
			{
				string state = (string) ViewState["OnMenuCloseScript"];
				if (state == null)
					return String.Empty;
				else
					return state;
			}
			set
			{
				ViewState["OnMenuCloseScript"] = value;
			}
		}

		#endregion

		#region Skin
                
		protected override void AttachChildControls() 
		{
			_menu = (CA.Menu) FindControl("Menu");   
		}

		#endregion

		#region Event Handlers

		protected override void OnLoad(EventArgs e) 
		{
			base.OnLoad(e);

			DataBind();
		}

		protected override void OnPreRender(System.EventArgs e)
		{
			string script = @"
<script language=javascript>
function ContextMenu (name, contextMenu, onMenuOpen, onMenuClose)
{
	this.Name = name;
	this.ContextMenuHandle = contextMenu;
	this.OnMenuClose = onMenuClose;
	this.OnMenuOpen = onMenuOpen;
	this.Element = null;
	this.LastElement = null;

	this.ContextMenuOpened = function()
	{
		if (this.OnMenuOpen != '')
			eval(this.OnMenuOpen);
	}

	this.ContextMenuClosed = function()
	{
		var element = this.Element;
		if (this.LastElement)
		{
			this.Element = this.LastElement;
		}
	
		if (this.OnMenuClose != '')
			eval(this.OnMenuClose);

		if (this.LastElement)
		{			
			this.LastElement = null;
			this.Element = element;
		}
		else
			this.Element = null;
	}

	this.ShowContextMenu = function()
	{
		var parameters = new Array();
		var i;
		for (i = 2; i < arguments.length; i++)
		{
			parameters[i - 2] = arguments[i];
		}

		this.LastElement = this.Element;
		this.Element = arguments[0];

		this.UpdateMenuItems(this.ContextMenuHandle.Items(), parameters);
		this.ContextMenuHandle.ShowContextMenu(arguments[1], new ContextMenuData(this, parameters));
	}

	this.UpdateMenuItems = function (items, parameters)
	{
		var i, subItems;
		for (i = 0; i < items.length; i++)
		{
			if (!items[i].OriginalText)
				items[i].OriginalText = items[i].Text;

			items[i].Text = this.Format(items[i].OriginalText, parameters);

			subItems = items[i].Items();
			if (subItems && subItems.length > 0)
				this.UpdateMenuItems(items[i].Items(), parameters);
		}
	}

	this.Format = function(text, parameters)
	{
		var i;
		for (i = 0; i < parameters.length; i++)
		{
			text = text.replace('{' + i + '}', parameters[i]);
		}

		return text;
	}
}

function ContextMenuData (contextMenu, parameters)
{
	this.Parameters = parameters;
	this.ContextMenu = contextMenu;

	this.NavigateToUrl = function(url)
	{
		this.ContextMenu.ContextMenuClosed();
		window.location = this.Format(url);
	}

	this.OpenModal = function(url, width, height, callback)
	{
		this.ContextMenu.ContextMenuClosed();
		window.Telligent_Modal.Open(this.Format(url), width, height, callback);
	}

	this.ExecuteScript = function (script)
	{
		this.ContextMenu.ContextMenuClosed();
		eval(this.Format(script));
	}

	this.Format = function(text)
	{
		var i;
		for (i = 0; i < this.Parameters.length; i++)
		{
			text = text.replace('{' + i + '}', this.Parameters[i]);
		}

		return text;
	}
}
</script>";

			if (!Page.IsClientScriptBlockRegistered(this.GetType().FullName))
				Page.RegisterClientScriptBlock(this.GetType().FullName, script);

			if (!Page.IsClientScriptBlockRegistered(this.ClientID))
				Page.RegisterStartupScript(this.ClientID, String.Format("<script language=javascript>window.{0} = new ContextMenu('{0}', window.{1}, '{2}', '{3}');</script>", this.ClientID, this._menu.ClientID, this.OnMenuOpenScript.Replace("'", "\\'"), this.OnMenuCloseScript.Replace("'", "\\'")));

			base.OnPreRender(e);
		}

		#endregion

		#region DataBind

		public override void DataBind() 
		{
			base.DataBind();

			_menu.Items.Clear();
			_menu.ClientSideOnContextMenuShow = "new Function(\"eval('window." + this.ClientID + ".ContextMenuOpened();')\")";
			_menu.ClientSideOnContextMenuHide = "new Function(\"eval('window." + this.ClientID + ".ContextMenuClosed();');\")";

			TabCollection tc = GetTabs();
			AddMenuItems(tc.Tabs, _menu.Items);
		}

		#region Databinding Helpers

		protected void AddMenuItems(Tab[] tabs, CA.MenuItemCollection items)
		{
			CA.MenuItem item;

			foreach(Tab tab in tabs)
			{
				if(tab.IsValid(Context))
				{
					item = new CA.MenuItem();
					item.Text = GetText(tab);
					item.ClientSideCommand = FormatClientSideCommand(tab);
					items.Add(item);

					if(tab.HasChildren)
						AddMenuItems(tab.Children, item.Items);
				}
			}
		}

		public static readonly string ModalClientSideCommand = "{0}.ContextData.OpenModal('{1}', {2}, {3}, {4});";
		public static readonly string UrlClientSideCommand = "{0}.ContextData.NavigateToUrl('{1}');";
		public static readonly string JavaScriptClientSideCommand = "{0}.ContextData.ExecuteScript('{1}');";

		protected string FormatClientSideCommand(Tab tab)
		{
			string url = FormatLink(tab);

			if (tab.IsJavaScript)
				return FormatJavaScriptClientSideCommand(tab.JavaScript);
			else if (Globals.IsNullorEmpty(url))
				return "";
			else if (tab.IsModal)
				return FormatModalLinkClientSideCommand(url, tab.ModalWidth, tab.ModalHeight, tab.ModalCallback);
			else
				return FormatNavigateUrlClientSideCommand(url);
		}

		protected string FormatJavaScriptClientSideCommand(string script)
		{
			return String.Format(ContextMenu.JavaScriptClientSideCommand, this._menu.ClientID, script.Replace("'", "\\'"));
		}

		protected string FormatNavigateUrlClientSideCommand(string url)
		{
			return String.Format(ContextMenu.UrlClientSideCommand, this._menu.ClientID, url);
		}

		protected string FormatModalLinkClientSideCommand(string url, string width, string height, string callbackScript)
		{
			return String.Format(ContextMenu.ModalClientSideCommand, this._menu.ClientID, url, width, height, Globals.IsNullorEmpty(callbackScript) ? "null" : callbackScript);
		}

		#endregion
		
		#endregion		
	}
}

