using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Data;
using System.Xml;
using System.Web;
using System.Threading;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Security.Principal;
using SK.MemberBLL;

namespace SK.MemberWeb
{
	/// <summary>
	/// BaseControl 的摘要说明。
	/// </summary>
	public class BaseControl : System.Web.UI.UserControl
	{
		public BaseControl()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
			this.Load += new EventHandler(SorkeSite_Load);
		}
		private void SorkeSite_Load(object sender,EventArgs e) 
		{
			for(int i =0;i<this.Controls.Count;i++)
			{
				if(this.Controls[i].GetType()==typeof(SK.MemberWeb.Controls.ControlHolder))
				{
					string PlaceHolderName = ((SK.MemberWeb.Controls.ControlHolder)this.Controls[i]).Src;
					System.Web.UI.Control hdrCtl = null;
					hdrCtl = LoadControl(TemplatePath+PlaceHolderName+".ascx");
					if (hdrCtl != null)
					{
						this.Controls[i].Controls.Add(hdrCtl);
					}
				}
			}
		}
		/*private void LoadUserControl(string PlaceHolderName)
		{
			LoadUserControl(PlaceHolderName,TemplatePath+PlaceHolderName+".ascx");
		}
		private void LoadUserControl(string PlaceHolderName,string ascxaddress)
		{
			PlaceHolder ph = (PlaceHolder)this.FindControl(PlaceHolderName);
			if(ph!=null)
			{
				System.Web.UI.Control hdrCtl = null;
				hdrCtl = LoadControl(ascxaddress);
				if (hdrCtl != null)
				{
					ph.Controls.Add(hdrCtl);
				}
			}
		}
		private void LoadControlHolder(string ControlHolderName)
		{
			LoadControlHolder(ControlHolderName,TemplatePath+ControlHolderName+".ascx");
		}
		private void LoadControlHolder(string ControlHolderName,string ascxaddress)
		{
			SK.MemberWeb.Controls.ControlHolder ph = (SK.MemberWeb.Controls.ControlHolder)this.FindControl(ControlHolderName);
			if(ph!=null)
			{
				System.Web.UI.Control hdrCtl = null;
				hdrCtl = LoadControl(ascxaddress);
				if (hdrCtl != null)
				{
					ph.Controls.Add(hdrCtl);
				}
			}
		}*/
		public void DisplayAlert (string message)
		{
			base.Page.RegisterClientScriptBlock(Guid.NewGuid().ToString(), "<script language=\"JavaScript\">" + GetAlertScript(message) + "</script>");
		}
		
		public string GetAlertScript(string message)
		{
			return "alert('" + message.Replace("'", "\\'") + "');";
		}
		
		public void GiveFocus (Control c)
		{
			base.Page.RegisterClientScriptBlock("CSP-focus-function", "<script language=\"JavaScript\">" + "\n" + "function CSP_focus(id) {" + "  var o = document.getElementById(id); if (o != null) o.focus(); " + "}" + "\n" + "</script>");
			
			base.Page.RegisterStartupScript("CSP-focus", "<script language=\"JavaScript\">CSP_focus('" + c.ClientID + "');</script>");
		}
		public string GetFocusScript(Control c)
		{
			base.Page.RegisterClientScriptBlock("CSP-focus-function", "<script language=\"JavaScript\">" + "\n" + "function CSP_focus(id) {" + "  var o = document.getElementById(id); if (o != null) o.focus(); " + "}" + "\n" + "</script>");
			return "CSP_focus('"+c.ClientID+"');";
		}
		public void DisabledControl (Control c)
		{
			base.Page.RegisterClientScriptBlock("CSP-disabled-function", "<script language=\"JavaScript\">" + "\n" + "function CSP_disabled(id) {" + "  var o = document.getElementById(id); if (o != null) o.disabled=true; " + "}" + "\n" + "</script>");
			
			base.Page.RegisterStartupScript("CSP-disabled", "<script language=\"JavaScript\">CSP_disabled('" + c.ClientID + "');</script>");
		}
		public string GetDisabledControlScript (Control c)
		{
			//base.Page.RegisterClientScriptBlock("CSP-disabled-function", "<script language=\"JavaScript\">" + "\n" + "function CSP_disabled(id) {" + "  var o = document.getElementById(id); if (o != null) o.disabled=true; " + "}" + "\n" + "</script>");
			
			//base.Page.RegisterStartupScript("CSP-disabled", "<script language=\"JavaScript\">CSP_disabled('" + c.ClientID + "');</script>");
			return "var o = document.getElementById("+c.ClientID+"); if (o != null) o.disabled=true;";
		}
		public void ExecuteControl (Control c)
		{
			base.Page.RegisterClientScriptBlock("CSP-execute-function", "<script language=\"JavaScript\">" + "\n" + "function CSP_execute(id) {" + "  var o = document.getElementById(id); if(event.keyCode == 13) o.onclick(); " + "}" + "\n" + "</script>");
			
			//base.Page.RegisterStartupScript("CSP-execute", "<script language=\"JavaScript\">CSP_execute('" + c.ClientID + "');</script>");
		}
		public string GetExecuteControlScript (Control c)
		{
			//return "function CSP_execute(id) {" + "  var o = document.getElementById(id); if(event.keyCode == 13) o.onclick(); " + "}" + "\n" + "</script>");
			base.Page.RegisterClientScriptBlock("CSP-execute-function", "<script language=\"JavaScript\">" + "\n" + "function CSP_execute(id) {" + "  var o = document.getElementById(id); if(event.keyCode == 13){event.keyCode=9; event.returnValue = false;o.click();} " + "}" + "\n" + "</script>");
			return "CSP_execute('"+c.ClientID+"');";
			
			
		}
		public void DisplayPopup (string url, string options)
		{
			base.Page.RegisterStartupScript(Guid.NewGuid().ToString(), "<script language=\"JavaScript\">" + GetPopupScript(url, options) + "</script>");
		}
		
		public string GetPopupScript(string url, string options)
		{
			return "var w = window.open(\"" + url + "\", null, \"" + options + "\");";
		}
		public void ShowDialog (string url, string options,bool refresh)
		{
			base.Page.RegisterStartupScript(Guid.NewGuid().ToString(), "<script language=\"JavaScript\">" + GetDialogScript(url, options,refresh) + "</script>");
		}
		public string GetDialogScript(string url, string options,bool refresh)
		{
			string script ="";
			if(url.IndexOf("?")>-1)
				url += "&rnd="+System.Guid.NewGuid().ToString();
			else
				url += "?rnd="+System.Guid.NewGuid().ToString();
			script = "var w=window.showModalDialog(\""+ url +"\",null,\"" + options + "\");";
			if(refresh)
				script += "if (w!=null) window.location.reload();";
			script += "return false;";
			return script;
		}
		public string GetDialogScript(string url, string options,string control)
		{
			string script = "";
			if(url.IndexOf("?")>-1)
				url += "&rnd="+System.Guid.NewGuid().ToString();
			else
				url += "?rnd="+System.Guid.NewGuid().ToString();
			script += "var w=window.showModalDialog(\""+ url +"\",null,\"" + options + "\");";
			script += "if (w!=null) document.all('"+control+"').value=w;";
			return script;
		}
		public void CloseWindow (bool refreshParent)
		{
			base.Page.RegisterClientScriptBlock("CSP-close-popup", "<script language=\"JavaScript\">" + GetCloseWindowScript(refreshParent) + "</script>");
		}
		public void AlertAndCloseWindow (string msg)
		{
			base.Page.RegisterClientScriptBlock("CSP-close-popup", "<script language=\"JavaScript\">" +this.GetAlertScript(msg)+ GetCloseWindowScript(false) + "</script>");
		}


		public string GetCloseWindowScript(bool refreshParent)
		{
			string script="";
			if (refreshParent)
			{
				script += "window.opener.location.reload();";
			}
			
			return script+"self.close();";
		}

		public void CloseDialog (bool refreshParent)
		{
			base.Page.RegisterClientScriptBlock("CSP-close-dialog", "<script language=\"JavaScript\">" + GetCloseDialogScript(refreshParent) + "</script>");
		}
		public string GetCloseDialogScript(bool refreshParent)
		{
			string script="";
			if (refreshParent)
			{
				script += "window.returnValue='ok';";
			}
			
			return script+"self.close();";
		}
		protected void RegisterOnchangeScript ()
		{
			if (! base.Page.IsClientScriptBlockRegistered("CSP-onchange-function"))
			{
				base.Page.RegisterClientScriptBlock("CSP-onchange-function", "<script language=\"JavaScript\">" + "var isDirty= false;" + "\n" + "function CSP_checkForChange(msg) {" + "\n" + "  if (isDirty) return confirm(msg); else return true;" + "\n" + "}" + "\n" + "</script>");
			}
		}
		
		public void MonitorChanges (WebControl c)
		{
			RegisterOnchangeScript();
			if (c is CheckBox | c is CheckBoxList | c is RadioButtonList)
			{
				c.Attributes["onclick"] = "isDirty = true;";
			}
			else
			{
				c.Attributes["onchange"] = "isDirty = true;";
			}
		}
		
		public void ConfirmOnExit (WebControl c, string message)
		{
			RegisterOnchangeScript();
			c.Attributes["onclick"] = "return CSP_checkForChange('" + message.Replace("'", "\\'") + "');";
		}
		
		public void ConfirmOnChange (DropDownList ddl, string message)
		{
			//Register the script block
			if (! base.Page.IsStartupScriptRegistered("CSP-ddl-onchange"))
			{
				base.Page.RegisterStartupScript("CSP-ddl-onchange", "<script language=\"JavaScript\">" + "var CSP_savedDDLID = document.getElementById('" + ddl.ClientID + "').value;" + "\n" + "function resetDDLIndex() {" + "\n" + "   document.getElementById('" + ddl.ClientID + "').value = CSP_savedDDLID;" + "\n" + "}" + "\n" + "</script>");
			}
			
			ddl.Attributes["onchange"] = "if (!confirm('" + message.Replace("'", "\\'") + "')) resetDDLIndex(); else ";
		}
		public bool IsDateTime(object datetime)
		{
			try
			{
				DateTime.Parse(String.Format("{0:yyyy-MM-dd}",datetime));
				return true;
			}
			catch
			{
				return false;
			}
		}
		//IPrincipal cp = HttpContext.Current.User;
		
		public object CurrentMemberID
		{
			get
			{
				if(HttpContext.Current.User.Identity.IsAuthenticated)
				{
					string[] parts = HttpContext.Current.User.Identity.Name.Split(';');
					return Convert.ToInt32(parts[0]);
				}
				else
					return null;
			}
		}
		public object CurrentMemberName
		{
			get
			{
				if(HttpContext.Current.User.Identity.IsAuthenticated)
				{
					string[] parts = HttpContext.Current.User.Identity.Name.Split(';');
					return parts[1];
				}
				else
					return null;
			}
		}
		public string FormatScript(string str)
		{
			return str.Replace("\r\n","\\r\\n").Replace("'", "\\'").Replace("\\", "\\\\");
		}
		public void AlertAndRedir (string message,string url)
		{
			base.Page.RegisterClientScriptBlock(Guid.NewGuid().ToString(), "<script language=\"JavaScript\">" + GetAlertScript(message) + "window.location.href =\""+url+"\"; " + "</script>");
		}
		public string Root
		{
			get 
			{
				try
				{
					///return Config.ConfigSection["root"];
					string path = HttpContext.Current.Request.ApplicationPath;
					if(!path.EndsWith("/")) path += "/";


					return path;
				}
				catch(Exception)
				{
					return "/";
				}
			}
		}
		public string TemplateName
		{
			get{return Main.GetValue("TemplateName").ToString();}
		}
		public string TemplatePath
		{
			get{return Root+"templates/"+TemplateName+"/";}
		}
		public string ImagesFolder
		{
			get{return Root+"templates/"+Main.GetValue("TemplateName").ToString()+"/images/";}
		}
		/*public static string CheckImageUrl(object Url,object NullUrl)
		{
			if(Url == null)
				return Main.TemplateFolder+NullUrl;
			if(Url.ToString() == "")
				return Main.TemplateFolder+NullUrl;
			return Url.ToString();
		}
		public static string CheckImageUrl_Small(object Url)
		{
			if(Url == null)
				return Main.ImagesFolder+"noimg.gif";
			if(Url.ToString() == "")
				return Main.ImagesFolder+"noimg.gif";
			return Url.ToString();
		}
		public static string CheckImageUrl_Medium(object Url)
		{
			if(Url == null)
				return Main.ImagesFolder+"noimg.gif";
			if(Url.ToString() == "")
				return Main.ImagesFolder+"noimg.gif";
			return Url.ToString();
		}
		public static string CheckImageUrl_Large(object Url)
		{
			if(Url == null)
				return Main.ImagesFolder+"noimg.gif";
			if(Url.ToString() == "")
				return Main.ImagesFolder+"noimg.gif";
			return Url.ToString();
		}*/
		public static string TextToHtml(object str)
		{
			return str.ToString().Replace("\n","<br>").Replace(" ","&nbsp;").Replace("　","&nbsp;&nbsp;");
		}
		public static string Space(object str,object Num)
		{
			int num = Convert.ToInt32(Num);
			string va="";
			for(int i=0;i<num;i++)
			{
				va+=str.ToString();
			}
			return va;
		}
		public static string ShowTitle(object str)
		{
			return "<title>"+str.ToString()+"</title>";
		}
		public static string MonthAndDay(object datetime)
		{
			DateTime t = Convert.ToDateTime(datetime);
			return String.Format("{0}-{1}",t.Month,t.Day);
		}
		public static string MonthDayTime(object datetime)
		{
			DateTime t = Convert.ToDateTime(datetime);
			return String.Format("{0}-{1} {2}:{3}",t.Month,t.Day,t.Hour,t.Minute );
		}
		public static string GetCustomText(object CustomName)
		{
			CustomTextSystem txt = new CustomTextSystem();
			return txt.GetContent(CustomName);
		}
		public static string GetValue(object Name)
		{
			return Main.GetValue(Name.ToString()).ToString();
		}
		public string Domain
		{
			get
			{
				return System.Configuration.ConfigurationSettings.AppSettings["Domain"].ToString();
			}
		}
	}
}
