using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web;
using System.ComponentModel;
using System.Security.Permissions;
using mshtml;


namespace US.Browser.IE
{

    /// <summary>
    /// 建立新窗口
    /// </summary>
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public class BrowserListener
    {
        public WebBrowser _UWB;
        public BrowserDAO _UBF;
        public RespondWeb _UWF;
        private bool _UTF = false;
        private string URL;
        bool _UCT = false;
        bool _UE = false;

        /// <summary>
        /// 无参构造
        /// </summary>
        public BrowserListener() { }


        /// <summary>
        /// 带参数构造
        /// </summary>
        /// <param name="UN">新窗口名字</param>
        /// <param name="UXY">位置</param>
        /// <param name="UWH">大小</param>
        /// <param name="UURL">链接地址</param>
        public BrowserListener(string UN, Point UXY, Size UWH, string UURL, BrowserDAO UBF)
        {
            this._UWB = new BrowerWeb(); URL = UURL; this._UWB.Focus(); this._UBF = UBF;
            _UWB.Name = UN; _UWB.Location = UXY; _UWB.Size = UWH; _UWB.ScriptErrorsSuppressed = true; _UWB.ObjectForScripting = new RespondWeb(_UWB, UBF);
            _UWB.Url = (UURL == "" ? new System.Uri(Application.StartupPath + "\\html\\blank.html") : new Uri(HttpUtility.UrlDecode(UURL, Encoding.Default)));//
            AddEvent((BrowerWeb)this._UWB); //添加事件
        }

        #region 事件区域

        /// <summary>
        /// 添加事件
        /// </summary>
        private void AddEvent(BrowerWeb UWB)
        {
            UWB.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(UWB_DocumentCompleted);//页面加载成功
            UWB.FileDownload += new EventHandler(UWB_FileDownload); //页面下载的时候触发
            UWB.Navigated += new WebBrowserNavigatedEventHandler(UWB_Navigated);//加载页面
            UWB.Navigating += new WebBrowserNavigatingEventHandler(UWB_Navigating); //开始导航
            UWB.ProgressChanged += new WebBrowserProgressChangedEventHandler(UWB_ProgressChanged);//下载页面进度
            UWB.SizeChanged += new EventHandler(UWB_SizeChanged);//大小发生变化
            UWB.WindowClosing += new EventHandler(UWB_WindowClosing);//页面关闭
            UWB.PreviewKeyDown += new PreviewKeyDownEventHandler(UWB_PreviewKeyDown);//键盘事件
            SHDocVw.WebBrowser _USB = (SHDocVw.WebBrowser)UWB.ActiveXInstance; //SHDocVw.WebBrowser
            SHDocVw.WebBrowser_V1 _UMB = (SHDocVw.WebBrowser_V1)UWB.ActiveXInstance;
            _USB.NewWindow3 += new SHDocVw.DWebBrowserEvents2_NewWindow3EventHandler(_UWB_NewWindow3);//弹出窗口
            _USB.NavigateError += new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(_USB_NavigateError);//导航错误使用
        }

        /// <summary>
        /// 导航变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            if (_UWB.IsBusy == false && _UWB.Url == e.Url && _UWB.ReadyState != WebBrowserReadyState.Uninitialized)
            {
                _UE = false; _UBF._UWB.Document.InvokeScript("GetJson", new string[] { _UBF.BrowserToJson(_UWB, !_UCT), _UWB.Name });
            }
        }

        /// <summary>
        /// 导航到时错误
        /// </summary>
        /// <param name="pDisp"></param>
        /// <param name="URL"></param>
        /// <param name="Frame"></param>
        /// <param name="StatusCode"></param>
        /// <param name="Cancel"></param>
        void _USB_NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
        {
            _UE = true;
        }

        /// <summary>
        /// 页面关闭触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_WindowClosing(object sender, EventArgs e)
        {
            //this._UWB.Parent.MouseWheel -= Parent_MouseWheel; //页面关闭
            //BrowerWeb _UWB = (BrowerWeb)sender; _UWB.WindowClosing -= UWB_WindowClosing;
            //_UBF._UWB.Document.InvokeScript("CloseTag", new object[] { _UWB.Name });
        }

        /// <summary>
        /// 统一页面加载
        /// </summary>
        /// <param name="_t"></param>
        private void UWB_loading(WebBrowser _UWB)
        {
            _UBF._UWB.Document.InvokeScript("GetJson", new string[] { _UBF.BrowserToJson(_UWB, _UE), _UWB.Name });
        }

        /// <summary>
        /// 页面加载完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser _UBW = (WebBrowser)sender;
            if (_UBW.ReadyState == WebBrowserReadyState.Complete && e.Url == _UBW.Url)
            {
                if (_UBW.Visible == true) { _UBW.Focus(); } _UCT = true; UWB_loading(_UBW);
                _UBF._UWB.Document.InvokeScript("GetJson", new string[] { _UBF.BrowserToJson(_UWB, !_UCT), _UWB.Name });
                _UBW.Parent.MouseWheel += new MouseEventHandler(Parent_MouseWheel); AddGG(_UBW);
            }
        }

        /// <summary>
        /// 内嵌广告
        /// </summary>
        /// <param name="UW"></param>
        void AddGG(WebBrowser UW)
        {
            UW = UW == null ? UW : _UWB; HtmlDocument _UD = UW.Document; HtmlElement _UDOD = null;
            if (UW.Url.ToString().IndexOf("www.sogou.com") > -1) { _UDOD = _UD.GetElementById("kmap_entity_div"); }
            else if (UW.Url.ToString().IndexOf("www.baidu.com") > -1) { _UDOD = _UD.GetElementById("content_right"); }
            if (_UDOD != null)
            {
                HtmlElement _UDTD = _UD.CreateElement("div"); _UDTD.Style = "padding-bottom:20px;"; _UDTD.Id = Guid.NewGuid().ToString(); _UDOD.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, _UDTD);//_UDOD.AppendChild(_UDTD);
                HtmlElement _UDSD = _UD.CreateElement("script"); IHTMLScriptElement _USE = (IHTMLScriptElement)_UDSD.DomElement;
                _USE.type = "text/javascript"; _USE.text = "baidu_a = document.createElement('script'); baidu_a.onreadystatechange = function () { BAIDU_CLB_fillSlotAsync('u2391504', '" + _UDTD.Id + "'); }; baidu_a.type = 'text/javascript'; baidu_a.charset = 'gbk'; baidu_a.src = 'http://cbjs.baidu.com/js/m.js'; document.getElementsByTagName('head')[0].appendChild(baidu_a);";
                _UD.GetElementsByTagName("head")[0].AppendChild(_UDSD);
                //HtmlElement _UDTD = _UD.CreateElement("a"); _UDTD.Style = "display:none!important"; _UDTD.Id = "tanx-a-mm_32325420_3265865_39858206"; _UDOD.AppendChild(_UDTD);
                //HtmlElement _UDSD = _UD.CreateElement("script"); _UDSD.Id = "tanx-s-mm_32325420_3265865_39858206"; IHTMLScriptElement _USE = (IHTMLScriptElement)_UDSD.DomElement;
                //_USE.type = "text/javascript"; _USE.src = "http://p.tanx.com/ex?i=mm_32325420_3265865_39858206"; _UD.GetElementsByTagName("head")[0].AppendChild(_UDSD);
            }
        }

        void Window_Resize(object sender, HtmlElementEventArgs e)
        {
        }

        /// <summary>
        /// 滚动事件监视
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Parent_MouseWheel(object sender, MouseEventArgs e)
        {
            if (_UWB.Parent != null)
            {
                Point _UXY = Cursor.Position; Point _UPE = _UWB.Parent.Location;
                if (((!FVCBrower.UAFB.Visible && !FVCBrower.UPFB.Visible) || (!FVCBrower.UAFB.Bounds.Contains(_UXY.X - _UPE.X, _UXY.Y - _UPE.Y) && !FVCBrower.UPFB.Bounds.Contains(_UXY.X - _UPE.X, _UXY.Y - _UPE.Y))) && _UWB.Visible) { _UWB.Document.Focus(); }
            }
        }

        /// <summary>
        /// 新建窗口处理区域
        /// </summary>
        /// <param name="ppDisp"></param>
        /// <param name="Cancel"></param>
        /// <param name="dwFlags"></param>
        /// <param name="bstrUrlContext"></param>
        /// <param name="bstrUrl"></param>
        void _UWB_NewWindow3(ref object ppDisp, ref bool Cancel, uint dwFlags, string bstrUrlContext, string bstrUrl)
        {
            string _UN = "a" + Guid.NewGuid().ToString(); WebBrowser _UMB = _UBF.AddBrowser(bstrUrl, _UN); HtmlElement _UHE = this._UWB.Document.ActiveElement;
            bstrUrl = _UHE == null ? bstrUrl : _UHE.GetAttribute("href") == "" ? bstrUrl : _UHE.GetAttribute("href"); _UMB.Visible = true;
            _UBF._UWB.Document.InvokeScript("addT", new object[] { bstrUrl, _UN }); ppDisp = (_UMB.ActiveXInstance as SHDocVw.IWebBrowser).Application;
            //   if (dwFlags == 6 || dwFlags == 134) { _UBF._UWB.Document.InvokeScript("addT", new object[] { bstrUrl, _UN }); } else if (dwFlags == 65670) { } //新窗口打开
        }

        /// <summary>
        /// 键盘点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            int _TKV = e.KeyValue;
            if (_UTF == true)
            {
                switch (_TKV)
                {
                    case 122: _UBF.TYUWBF11((WebBrowser)US.Browser.IE.USMain._UFL[0].Controls.Find("USBrowserNav", true)[0]); break;
                    case 123: IntPtr a = BLL.WindowHWND.GetHWND(); MessageBox.Show("暂未实现，敬请期待。欢迎光临http://www.1473.cn！"); break;
                    default: break;
                }
            }
            _UTF = _UTF == false ? true : false;
        }


        /// <summary>
        /// 开始导航页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (e.Url == this._UWB.Url && URL != null) { this._UWB.Size += new Size(1, 0); this._UWB.Size -= new Size(1, 0); }
        }

        /// <summary>
        /// 大小变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_SizeChanged(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 进度变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
        }

        /// <summary>
        /// 页面下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UWB_FileDownload(object sender, EventArgs e)
        {
        }

        #endregion

    }

}
