using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using Orciid.Core;

namespace Orciid.PageTemplate
{

	public class OrciidPage: LocalPage, IPostBackDataHandler
	{
		private PageHeader pageheader = null;
		private PageFooter pagefooter = null;
		private PageMenu pagemenu = null;

		// use double curly brackets in here, since it will be run through String.Format !!
		const string headertags = @"
<LINK REL='stylesheet' HREF='PageTemplate/stylesheet.aspx?bg={0}&fs={1}' TYPE='text/css'>
<script language='JavaScript' type='text/javascript'><!--
		function clickButton(e, buttonid)
		{{ 
			var bt = document.getElementById(buttonid); 
			if (typeof bt == 'object')
			{{ 
				if (navigator.appName.indexOf('Netscape') > -1)
				{{
					if (e.keyCode == 13)
					{{ 
						bt.click(); 
                        return false; 
					}} 
				}} 
				if (navigator.appName.indexOf('Microsoft Internet Explorer') > -1)
				{{ 
					if (event.keyCode == 13)
					{{ 
                        bt.click(); 
                        return false; 
					}} 
				}} 
			}}
		}}
		//-->
		</script>
";

		public bool UserCanBuildSlideshows = false;

		private void Page_Load(object sender, System.EventArgs e)
		{
		}

		private void UpdateHeaders()
		{
			// find the literal control with HTML header information
			// and add tags to it
			for (int i = 0; i < Controls.Count; i++)
				if (Controls[i] is LiteralControl)
				{
					LiteralControl c = Controls[i] as LiteralControl;
					// insert additional header tags
					int p = c.Text.ToLower().IndexOf("<head>");
					if (p >= 0)
					{
						string fontsize = Session["FontSize"] as string;
						if (fontsize == null)
						{
							Orciid.Core.User user = Orciid.Core.User.CurrentUser();
							if (user != null)
							{
								Properties props = Properties.GetProperties(user);
								fontsize = props.Get("uifontsize", "N");
								Session["FontSize"] = fontsize;
							}
							else
								fontsize = "N";
						}
						c.Text = c.Text.Insert(p + 6, 
							String.Format(headertags, HasLeftMenu() ? "menu" : "nomenu", fontsize));
					}
				}
		}

		private PlaceHolder ErrorMessagesPlaceholder = new PlaceHolder();

		private void InsertTemplateElements()
		{

			// find the form control on the current page
			// and insert page controls in form to create template
			HtmlForm form = null;
			for (int i = 0; i < Controls.Count; i++)
				if (Controls[i] is HtmlForm)
				{
					form = Controls[i] as HtmlForm;
					break;
				}
			if (form != null)
			{
// Don't jump out of frames by default:
//				form.Target = "_top";
// Instead, add target to pages that have a name ending in _top, which are the ones
// in framesets.  Set the target to "_parent", so they only close their own frameset
// but leave other surrounding framesets alone:
				if (Request.FilePath.ToLower().EndsWith("_top.aspx"))
					form.Target = "_parent";

				// insert at top of page
				int p = 0;
				if (HasPageHeader())
					form.Controls.AddAt(p++, pageheader);
				form.Controls.AddAt(p++, new LiteralControl("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>"));
				form.Controls.AddAt(p++, new LiteralControl("<td valign=\"top\">"));
				if (HasLeftMenu())
					form.Controls.AddAt(p++, pagemenu);
				else
				{
					form.Controls.AddAt(p++, new LiteralControl("<img src=\"images/spacer.gif\" width=\"15\" height=\"9\"><img src=\"images/upper_left_corner.gif\">"));
				}
				form.Controls.AddAt(p++, new LiteralControl("</td>"));
				form.Controls.AddAt(p++, new LiteralControl("<td valign=\"top\" style=\"padding: 5px;\"><a name=\"content\"></a>"));
				if (HasSelectionStatus())
					form.Controls.AddAt(p++, LoadControl("PageTemplate/SelectionStatus.ascx"));
				form.Controls.AddAt(p++, ErrorMessagesPlaceholder);
				form.Controls.Add(new LiteralControl("</td></tr></table>"));
				if (HasPageFooter())
					form.Controls.Add(pagefooter);
			}
		}

		override protected void LoadViewState(object savedState)
		{
			base.LoadViewState(savedState);
		}

		override protected void OnInit(EventArgs e)
		{
			string requiressl = Configuration.Instance.ContainsKey("ui.requiressl") ?
				Configuration.Instance.GetString("ui.requiressl") :
				"false";
			if (!Request.IsSecureConnection)
			{
				if (requiressl == "true" ||
					(requiressl == "login" && this is _default))
				{
					Response.Redirect("https://" + Request.Url.Host + Request.RawUrl);
				}
			}
			else
			{
				if (requiressl == "login" && !(this is _default))
				{
					Response.Redirect("http://" + Request.Url.Host + Request.RawUrl);
				}
			}

			Orciid.Core.User user = Session["CurrentUser"] as Orciid.Core.User;
			// New test code for WebAuth CM 3-10-06
			if (user == null)
			{
			    string username = Request.ServerVariables["HTTP_WEBAUTH_USER"];
			    if (username != "" && username != null) // wrapper required to deal with access attempts that don't come through SUWA
			    {
			        user = Orciid.Core.User.GetByLogin(username,"password_will_be_ignored");
			        Session["CurrentUser"] = user;
			    }
			}
			// End of new code for WebAuth
			if (user != null)
				UserCanBuildSlideshows =
					Orciid.Core.User.HasPrivilege(Privilege.CreateSlideshow, user) ||
					Orciid.Core.User.HasPrivilegeOnAny('S', user, Privilege.ModifySlideshow, 
					Privilege.DeleteSlideshow, Privilege.ModifyACL);
			if (user != null)
				user.Activate(Request.UserHostAddress);
			if (!CheckUserPrivileges(user))
				Response.Redirect("insufficientprivileges.aspx"); 
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new EventHandler(OrciidPage_PreRender);
			base.OnInit(e);
			// pageheader is loaded here because other methods need to have access to it later
			pageheader = (PageHeader)LoadControl("PageTemplate/PageHeader.ascx");
			pagefooter = (PageFooter)LoadControl("PageTemplate/PageFooter.ascx");
			pagemenu = (PageMenu)LoadControl("PageTemplate/PageMenu.ascx");
			CreateChildControls();
			Response.Expires = 0;
		}

		override protected void OnUnload(EventArgs e)
		{
		}

		protected override void CreateChildControls() 
		{
			base.CreateChildControls();
			InsertTemplateElements();
			ChildControlsCreated = true;
		}

		/// <summary>
		/// Highlighted Menu Item
		/// </summary>
		/// <remarks>
		/// Override this method to select the menu item that will be highlighted for
		/// the overriding page.
		/// </remarks>
		/// <returns>The string identifier of the menu item to be highlighted, or <c>null</c>
		/// if no item should be highlighted.</returns>
		public virtual string GetHighlightedMenuItem()
		{
			return null;
		}

		/// <summary>
		/// Check User Privileges
		/// </summary>
		/// <remarks>
		/// This method must check if the current user has sufficient privileges to view
		/// the current page. If this method returns <c>false</c>, the client will be redirected
		/// to another page. 
		/// </remarks>
		/// <param name="user">The user to check privileges for. This parameter may be <c>null</c>
		/// if there is no current active user.</param>
		/// <returns><c>true</c> if the user has sufficient privileges, <c>false</c> otherwise.</returns>
		protected virtual bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return false;
		}

		/// <summary>
		/// Control left menu
		/// </summary>
		/// <remarks>
		/// Override this method for pages that do not have a left menu
		/// </remarks>
		/// <returns><c>true</c></returns>
		public virtual bool HasLeftMenu()
		{
			return true;
		}

		/// <summary>
		/// Control page footer
		/// </summary>
		/// <remarks>
		/// Override this method for pages that do not have a page footer
		/// </remarks>
		/// <returns><c>true</c></returns>
		protected virtual bool HasPageFooter()
		{
			return true;
		}

		protected virtual bool HasPageHeader()
		{
			return true;
		}

		protected virtual bool HasSelectionStatus()
		{
			return true;
		}

		public void AddPageHeaderMenuItem(string title, string href, string id)
		{
			if (pageheader != null)
				pageheader.AddMenuItem(title, href, id);
			else
				throw new Exception("Could not add menu item to page header");
		}

		#region IPostBackDataHandler Members

		public void RaisePostDataChangedEvent()
		{
		}

		public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
		{
			//			InsertTemplateElements();
			return false;
		}

		#endregion

		private struct ErrorMessage
		{
			public string message;
			public int severe;
		}

		private ArrayList errormessages = null;

		private void AddErrorMessage(string msg, int sev)
		{
			if (errormessages == null)
				errormessages = new ArrayList();
			ErrorMessage e;
			e.message = msg;
			e.severe = sev;
			errormessages.Add(e);
		}

		public void ShowInformation(string msg)
		{
			AddErrorMessage(msg, 0);
		}

		public void ShowWarning(string msg)
		{
			AddErrorMessage(msg, 1);
		}

		public void ShowError(string msg)
		{
			AddErrorMessage(msg, 2);
		}

		private void OrciidPage_PreRender(object sender, EventArgs e)
		{
			string[] images = { "info", "warning", "error" };
			string[] alt = { "Information", "Warning", "Error" };
			UpdateHeaders();
			ErrorMessagesPlaceholder.EnableViewState = false;
			if (errormessages != null)
			{
				ErrorMessagesPlaceholder.Controls.Add(new LiteralControl(
					"<div style='border:red 2px solid;padding:3px;margin-top:15px;margin-bottom:5px;font-weight:bold;'>"));
				foreach (ErrorMessage em in errormessages)
				{
					System.Web.UI.WebControls.Image icon = new System.Web.UI.WebControls.Image();
					icon.ImageUrl = "images/" + images[em.severe] + ".gif";
					icon.Width = 16;
					icon.Height = 16;
					icon.Attributes["vspace"] = "2";
					icon.AlternateText = alt[em.severe];
					icon.ImageAlign = ImageAlign.AbsMiddle;
                    ErrorMessagesPlaceholder.Controls.Add(icon);
					ErrorMessagesPlaceholder.Controls.Add(new LiteralControl(" " + em.message + "<br />"));
				}
				ErrorMessagesPlaceholder.Controls.Add(new LiteralControl(
					"</div>"));
			}
			else
				ErrorMessagesPlaceholder.Visible = false;

			Localize();
		}


		protected void DisableButtonOnClick(System.Web.UI.WebControls.Button button, string newlabel)
		{
			if (!IsClientScriptBlockRegistered("disablebuttononclick"))
				RegisterClientScriptBlock("disablebuttononclick",@"
<script language='JavaScript' type='text/javascript'><!--
function __disablebuttononclick(button,newlabel) {
if (typeof(Page_ClientValidate)=='function'){if (Page_ClientValidate()==false){return false;}}
button.value=newlabel;button.disabled=true;
" + GetPostBackEventReference(button) + @";
}
//-->
</script>");
		
			button.Attributes["onclick"] = "__disablebuttononclick(this,'" + EncodeJavaScriptString(newlabel) + "');";
		}


		public static string EncodeJavaScriptString(string s)
		{
			return s.Replace(@"\", @"\\").Replace(@"'", @"\'");
		}

		public void RegisterTempSessionFile(string tempfile)
		{
			ArrayList tempfiles = Session["TemporarySessionFiles"] as ArrayList;
			if (tempfiles == null)
				tempfiles = new ArrayList();
			tempfiles.Add(tempfile);
			Session["TemporarySessionFiles"] = tempfiles;
		}

	}
}