/// <summary>
 ///     Initializes a new instance of this class.
 /// </summary>
 /// <param name="name">Name of file to download.</param>
 /// <param name="url">URL of file to download.</param>
 /// <param name="type">Type of file being downloaded.</param>
 /// <param name="description">Description of game being downloaded.</param>
 public DownloadItem(string name, string url, DownloadType type, GameDescription description)
 {
     _name = name;
     _gameDescription = description;
     _downloadType = type;
     _downloader = new FileDownloader(url);
     _downloader.Start();
 }
        /// <summary>
        ///     Invoked when the login button is clicked.
        /// </summary>
        /// <param name="sender">Object that caused this event to be triggered.</param>
        /// <param name="e">Arguments explaining why this event occured.</param>
        private void loginButton_Click(object sender, EventArgs e)
        {
            string password = passwordTextBox.Text;
            string username = usernameTextBox.Text;
            if (password == null || password.Length < 6 ||
                username == null || username.Length < 6)
            {
                MessageBox.Show("A password and username must be entered. Both must be equal to or longer than 6 characters", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                ProgressWindow progressWindow = new ProgressWindow("Logging in", "Verifying login");
                progressWindow.Marquee = true;
                progressWindow.Show();
                this.Enabled = false;

                FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionverifylogin&username="******"&password="******"")
                    {
                        MessageBox.Show("An error occured while connecting to the server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    Application.DoEvents();
                }

                this.Enabled = true;
                progressWindow.Dispose();

                ASCIIEncoding encoding = new ASCIIEncoding();
                string response = encoding.GetString(downloader.FileData);
                if (response.ToLower() == "invalid")
                    MessageBox.Show("The login given was invalid. If you have lost your password please click the password reset link.", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else if (response.ToLower() == "valid")
                {
                    MessageBox.Show("Your login was successfull.", "Valid Login", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // Place the password / username in the config file if we are to remember them.
                    Fusion.GlobalInstance.CurrentUsername = username;
                    Fusion.GlobalInstance.CurrentPassword = password;
                    Fusion.GlobalInstance.RememberUser = rememberMeCheckBox.Checked;

                    Close();
                }
                else
                    MessageBox.Show("Unexpected value returned from server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        ///     Invoked when the reset button is clicked.
        /// </summary>
        /// <param name="sender">Object that caused this event to be triggered.</param>
        /// <param name="e">Arguments explaining why this event occured.</param>
        private void resetButton_Click(object sender, EventArgs e)
        {
            string email = emailTextBox.Text;
            if (email == null || !email.Contains("@"))
            {
                MessageBox.Show("A valid email must be entered.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                ProgressWindow progressWindow = new ProgressWindow("Reseting Password", "Contacting server");
                progressWindow.Marquee = true;
                progressWindow.Show();
                this.Enabled = false;

                FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionresetpassword&email=" + System.Web.HttpUtility.UrlEncode(email));
                downloader.Start();
                while (downloader.Complete == false)
                {
                    if (downloader.Error != "")
                    {
                        MessageBox.Show("An error occured while connecting to the server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    Application.DoEvents();
                }

                this.Enabled = true;
                progressWindow.Dispose();

                ASCIIEncoding encoding = new ASCIIEncoding();
                string response = encoding.GetString(downloader.FileData);
                if (response.ToLower() == "noaccount")
                    MessageBox.Show("No account exists with the email that your provided.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else if (response.ToLower() == "invalid")
                    MessageBox.Show("The email you provided was invalid.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else if (response.ToLower() == "valid")
                {
                    MessageBox.Show("An email has been sent to the email account we have in our database. It contains a link to a webpage you can reset your password at.", "Password Reset", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DialogResult = DialogResult.OK;
                    Close();
                    return;
                }
                else
                    MessageBox.Show("Unexpected value returned from server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            DialogResult = DialogResult.Cancel;
            Close();
        }
        /// <summary>
        ///     Downloads the games library from the central server.
        /// </summary>
        private void LoadGamesLibrary()
        {
            // Make sure we are logged in.
            if (Fusion.GlobalInstance.CurrentUsername == "" || Fusion.GlobalInstance.CurrentPassword == "")
                return;

            // See if we can connect to the internet.
            FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusiongameslist&username="******"&password="******"Downloading Games Library ...";
                statusToolStripStatusLabel.Text = "Downloading Games Library ...";
                statusToolStripProgressBar.Style = ProgressBarStyle.Marquee;

                while (downloader.Complete == false)
                {
                    if (downloader.Error != "")
                        throw new Exception("An error occured while connecting to the server.");
                    Application.DoEvents();
                }

                statusToolStripProgressBar.Style = ProgressBarStyle.Continuous;
                statusToolStripStatusLabel.Text = "Downloaded Games Library.";

                // Get the data.
                ASCIIEncoding encoding = new ASCIIEncoding();
                string data = encoding.GetString(downloader.FileData);

                // Clear up.
                _gamesLibrary.Clear();
                _gamesLibraryImageList.Images.Clear();
                _gamesLibraryImageList.ColorDepth = ColorDepth.Depth32Bit;
                _gamesLibraryImageList.ImageSize = new Size(48, 48);

                // Ok now parse the data.
                if (data.Length != 4 && data.ToLower() != "none")
                {
            #if RELEASE || PROFILE
                    try
                    {
            #endif
                        XmlDocument document = new XmlDocument();
                        document.LoadXml(data);

                        if (document["games"] != null)
                        {
                            for (int i = 0; i < document["games"].ChildNodes.Count; i++)
                            {
                                string title = document["games"].ChildNodes[i]["title"].InnerText;
                                string version = document["games"].ChildNodes[i]["version"].InnerText;
                                string language = document["games"].ChildNodes[i]["language"].InnerText;
                                string shortdescription = document["games"].ChildNodes[i]["shortdescription"].InnerText;
                                string description = document["games"].ChildNodes[i]["description"].InnerText;
                                string rating = document["games"].ChildNodes[i]["rating"].InnerText;
                                string players = document["games"].ChildNodes[i]["players"].InnerText;
                                string requirements = document["games"].ChildNodes[i]["requirements"].InnerText;
                                string publisher = document["games"].ChildNodes[i]["publisher"].InnerText;

                                // Download the icon.
                                FileDownloader iconDownloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusiongamedownload&username="******"&password="******"&game=" + System.Web.HttpUtility.UrlEncode(title) + "&file=0");
                                try
                                {
                                    iconDownloader.Start();
                                    while (iconDownloader.Complete == false)
                                    {
                                        if (iconDownloader.Error != "")
                                            break; // Not important enough for an error message.
                                        Application.DoEvents();
                                    }
                                }
                                catch {}

                                Stream iconDataStream = new MemoryStream(iconDownloader.FileData);
                                Image iconImage = Image.FromStream(iconDataStream);
                                //iconDataStream.Close();

                                GameDescription gameDescription = new GameDescription("", title, description, shortdescription, rating, language, requirements, players, version, publisher);
                                gameDescription.Icon = iconImage;
                                _gamesLibrary.Add(gameDescription);

                                _gamesLibraryImageList.Images.Add(iconImage);
                            }
                            SyncronizeWindow();
                            statusToolStripStatusLabel.Text = "Idle.";
                        }
            #if RELEASE || PROFILE
                    }
                    catch (Exception)
                    {
                        BinaryPhoenix.Fusion.Runtime.Debug.DebugLogger.WriteLog("Unable to parse game library XML, the root node dosen't exist.");
                        statusToolStripStatusLabel.Text = "An error occured while parsing game library XML.";
                    }
            #endif
                }
            #if RELEASE || PROFILE
            }
            catch (Exception)
            {
                _connectedToNet = false;
            }
            #endif

            // Is there an update available for any of our games?
            foreach (GameDescription myGameDescription in _myGames)
                foreach (GameDescription gamesLibraryDescription in _gamesLibrary)
                    if (gamesLibraryDescription.Name == myGameDescription.Name && float.Parse(gamesLibraryDescription.Version) > float.Parse(myGameDescription.Version))
                        if (MessageBox.Show("There are updates available for "+myGameDescription.Name+", would you like to download the updates now?", "Updates Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            gamesLibraryDescription.Downloading = true;
                            AddDownload(gamesLibraryDescription.Name + " (Version " + gamesLibraryDescription.Version + ")", "http://www.binaryphoenix.com/index.php?action=fusiongamedownload&username="******"&password="******"&game=" + System.Web.HttpUtility.UrlEncode(gamesLibraryDescription.Name) + "&file=1", DownloadType.Game, gamesLibraryDescription);
                        }
        }
        /// <summary>
        ///     Checks for new updates with the central server.
        /// </summary>
        private void CheckForUpdates()
        {
            // Wrok out the major / minor versions.
            string version = Engine.GlobalInstance.EngineConfigFile["version", "1.0"];
            int radixIndex = version.IndexOf('.');
            string majorVersion = radixIndex == -1 ? "1" : version.Substring(0, radixIndex);
            string minorVersion = radixIndex == -1 ? "0" : version.Substring(radixIndex + 1);

            // See if we can connect to the internet.
            FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionupdates&mjrver="+majorVersion+"&minver="+minorVersion);
            try
            {
                downloader.Start();
                statusToolStripStatusLabel.Text = "Checking for updates.";
                statusToolStripProgressBar.Style = ProgressBarStyle.Marquee;

                while (downloader.Complete == false)
                {
                    if (downloader.Error != "")
                        throw new Exception("An error occured while connecting to the server.");
                    Application.DoEvents();
                }

                statusToolStripProgressBar.Style = ProgressBarStyle.Continuous;
                statusToolStripStatusLabel.Text = "Downloaded updates.";

                // Get the data.
                ASCIIEncoding encoding = new ASCIIEncoding();
                string data = encoding.GetString(downloader.FileData);

                // Ok now parse the data.
                if (data.Length != 4 && data.ToLower() != "none")
                {
                    try
                    {
                        XmlDocument document = new XmlDocument();
                        document.LoadXml(data);

                        if (document["updates"] != null)
                        {
                            if (MessageBox.Show("There are updates available for the Fusion Game Engine, would you like to download the updates now?", "Updates Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            {
                                for (int i = 0; i < document["updates"].ChildNodes.Count; i++)
                                {
                                    string name = document["updates"].ChildNodes[i]["name"].InnerText;
                                    string file = document["updates"].ChildNodes[i]["file"].InnerText;
                                    AddDownload(name, file, DownloadType.FusionUpdate, null);
                                }
                                SyncronizeWindow();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        BinaryPhoenix.Fusion.Runtime.Debug.DebugLogger.WriteLog("Unable to parse updates XML, the root node dosen't exist.");
                        statusToolStripStatusLabel.Text = "An error occured while parsing updates XML.";
                    }
                }

                statusToolStripStatusLabel.Text = "Idle.";
            }
            catch (Exception)
            {
                _connectedToNet = false;
            }
        }
        /// <summary>
        ///     Validates the current username and password.
        /// </summary>
        /// <returns>True if login is valid, else false.</returns>
        private bool ValidateLogin()
        {
            // See if we can connect to the internet.
            FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionverifylogin&username="******"&password="******"Validating login.";
                statusToolStripProgressBar.Style = ProgressBarStyle.Marquee;

                while (downloader.Complete == false)
                {
                    if (downloader.Error != "")
                        throw new Exception("An error occured while connecting to the server.");
                    Application.DoEvents();
                }

                statusToolStripProgressBar.Style = ProgressBarStyle.Continuous;
                statusToolStripStatusLabel.Text = "Validating login.";

                // Get the data.
                ASCIIEncoding encoding = new ASCIIEncoding();
                string response = encoding.GetString(downloader.FileData);

                if (response.ToLower() == "invalid")
                {
                    Fusion.GlobalInstance.CurrentPassword = "";
                    Fusion.GlobalInstance.CurrentUsername = "";
                    return false;
                }
                else if (response.ToLower() == "valid")
                    return true;
                else
                    MessageBox.Show("Unexpected value returned from server. Please login manually.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                statusToolStripStatusLabel.Text = "Idle.";
            }
            catch (Exception)
            {
                _connectedToNet = false;
            }

            return false;
        }
        /// <summary>
        ///     Refreshs the new tab by downloading news ite from the
        ///     central server.
        /// </summary>
        private void RefreshNews()
        {
            // See if we can connect to the internet.
            FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionnews");
            try
            {
                downloader.Start();
                statusToolStripStatusLabel.Text = "Downloading news.";
                statusToolStripProgressBar.Style = ProgressBarStyle.Marquee;

                while (downloader.Complete == false)
                {
                    if (downloader.Error != "")
                        throw new Exception("An error occured while connecting to the server.");
                    Application.DoEvents();
                }

                statusToolStripProgressBar.Style = ProgressBarStyle.Continuous;
                statusToolStripStatusLabel.Text = "Downloaded news.";

                // Get the data.
                ASCIIEncoding encoding = new ASCIIEncoding();
                string data = encoding.GetString(downloader.FileData);

                // Ok now parse the data.
                if (data.Length != 4 && data.ToLower() != "none")
                {
                    XmlDocument document = new XmlDocument();
                    document.LoadXml(data);
                    if (document["news"] != null)
                    {
                        int y = 15;
                        for (int i = 0; i < document["news"].ChildNodes.Count; i++)
                        {
                            string title = document["news"].ChildNodes[i]["title"].InnerText;
                            string author = document["news"].ChildNodes[i]["author"].InnerText;
                            string date = document["news"].ChildNodes[i]["date"].InnerText;
                            string body = document["news"].ChildNodes[i]["body"].InnerText;

                            NewsItem item = new NewsItem(title, "written by " + author + " on " + date, body, recentNewsTabPage);
                            item.NewsPanel.Location = new Point(15, y);
                            _newsItems.Add(item);

                            y += item.NewsPanel.Height + 15;
                        }

                        statusToolStripStatusLabel.Text = "Idle.";
                        newDownloadLabel.Visible = false;
                    }
                    else
                    {
                        BinaryPhoenix.Fusion.Runtime.Debug.DebugLogger.WriteLog("Unable to parse news XML, the root node dosen't exist.");
                        statusToolStripStatusLabel.Text = "An error occured while parsing news XML.";
                        newDownloadLabel.Text = "Unable to download.";
                    }
                }
            }
            catch (Exception)
            {
                _connectedToNet = false;
            }
        }
        /// <summary>
        ///     Invoked when the register button is clicked.
        /// </summary>
        /// <param name="sender">Object that caused this event to be triggered.</param>
        /// <param name="e">Arguments explaining why this event occured.</param>
        private void registerButton_Click(object sender, EventArgs e)
        {
            string email = emailTextBox.Text;
            string displayName = displaynameTextBox.Text;
            string username = usernameTextBox.Text;
            string password = passwordTextBox.Text;
            string confirmPassword = confirmPasswordTextBox.Text;

            if (email == null || !email.Contains("@"))
            {
                MessageBox.Show("A valid email must be entered.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (username == null || username.Length < 6)
            {
                MessageBox.Show("A valid username must be entered.", "Invalid Username", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (password.ToLower() != confirmPassword.ToLower())
            {
                MessageBox.Show("Your passwords do not match.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (password.Length < 6)
            {
                MessageBox.Show("A valid password must be entered.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                ProgressWindow progressWindow = new ProgressWindow("Registering", "Contacting server");
                progressWindow.Marquee = true;
                progressWindow.Show();
                this.Enabled = false;

                FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionregister&email=" + System.Web.HttpUtility.UrlEncode(email) + "&username="******"&password="******"" ? ("&displayname=" + System.Web.HttpUtility.UrlEncode(displayName)) : ""));
                downloader.Start();
                while (downloader.Complete == false)
                {
                    if (downloader.Error != "")
                    {
                        MessageBox.Show("An error occured while connecting to the server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    Application.DoEvents();
                }

                this.Enabled = true;
                progressWindow.Dispose();

                ASCIIEncoding encoding = new ASCIIEncoding();
                string response = encoding.GetString(downloader.FileData);
                if (response.ToLower() == "usernameinuse")
                    MessageBox.Show("An account already exists with the username that your provided.", "Invalid Register", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else if (response.ToLower() == "emailinuse")
                    MessageBox.Show("An account already exists with the email that your provided.", "Invalid Register", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else if (response.ToLower() == "valid")
                {
                    MessageBox.Show("Your account has successfully been registered with the server and you have been logged in. We hope you like being a member of Binary Phoenix's community.", "Registration Successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DialogResult = DialogResult.OK;
                    Close();
                    Fusion.GlobalInstance.CurrentUsername = username;
                    Fusion.GlobalInstance.CurrentPassword = password;
                    return;
                }
                else
                    MessageBox.Show("Unexpected value returned from server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }