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

using System;
using CommunityServer.Components;
using CommunityServer.Controls;
using TWC = Telligent.Web.UI;

namespace CommunityServer.ControlPanel.Controls
{

	/// <summary>
	/// Renders a Tab + Submenus based on the tab configuration file.
	/// </summary>
	public class ControlPanelTabStrip : ControlPanelTabDrivenTemplatedWebControl
	{
		public ControlPanelTabStrip() : base()
		{
		}

		#region Private Members
		
		private TWC.TabSet _tabStrip;

		#endregion

		#region Skin Methods

		protected override void AttachChildControls()
		{
			_tabStrip = (TWC.TabSet) FindControl("TabStrip");
		}

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

			EnsureChildControls();
			if (_tabStrip != null)
				BuildTabs();
		}


		/// <summary>
		/// Creates the markup for the current TabCollection
		/// </summary>
		/// <returns></returns>
		protected void BuildTabs()
		{
			_tabStrip.Tabs.Clear();
			TWC.TabSetTab parentTab;

			//Get the tab data
			TabCollection tc = GetTabs();
			String url;
			
			//Walk the parents
			foreach(Tab parent in tc.Tabs)
			{
				//Is this parent enabled? Check Permissions
				if(parent.IsValid(Context))
				{
					parentTab = new TWC.TabSetTab();
					parentTab.Text = GetText(parent);
					
					url = FormatLink(parent);
					if (parent.IsJavaScript)
						parentTab.OnClickClientFunction = parent.JavaScript;
					else if (!Globals.IsNullorEmpty(url))
					{
						if (parent.IsModal)
							parentTab.OnClickClientFunction = String.Format("new Function(\"Telligent_Modal.Open('{0}', {1}, {2}, {3});\")", url, parent.ModalWidth, parent.ModalHeight, Globals.IsNullorEmpty(parent.ModalCallback) ? "null" : parent.ModalCallback);
						else
							parentTab.NavigateUrl = url;

						parentTab.Text = GetText(parent, url);
					}

					_tabStrip.Tabs.Add(parentTab);

					//Check to see if/how this is tab is selected
					if (GetState(parent) == SelectedState.Selected)
						_tabStrip.SelectedTab = parentTab;
				}
			}
		}

		#endregion

		#region Public Properties

		private string _selected = null;
		public override string Selected
		{
			get
			{
				if(_selected == null)
					_selected = Context.Items["ControlPanelSelectedTab"] as string;

				return _selected;
			}
			set
			{
				_selected = value;
			}
		}

		#endregion

	}
}
