using System;
using System.Globalization;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Net;
using System.Runtime.InteropServices;
using System.IO;
using System.IO.Compression;
using System.Web;


namespace DSTool
{


    public partial class FrmMain : Form
    {
        //ArrayList Villages = new ArrayList();
        List<Village> Villages = new List<Village>();
        ArrayList Groups = new ArrayList();
        static String Cookies = "";
        String GMKey = "";
        ListViewItem.ListViewSubItem GMLastSel = null;
        ListViewGroup GMGLastSel = null;
        int TimerSecCnt = 0;
        StatistikDaten StatData = new StatistikDaten();

        public FrmMain()
        {
            InitializeComponent();
            InitializeListViews();
            System.Net.ServicePointManager.Expect100Continue = false;
            pnlWait.BringToFront();

            tabCMain.SelectedTab = tabLogin;
            tabCMain.TabPages.Remove(tabDEBUG);
        }

        private int GMgetVillages()
        {
            this.Enabled = false;
            String webDaten = "";
            int posA = 0;
            int posB = 0;
            int posC = 0;
            Village tmpVillage;
            String tmpStr = "";
            ListViewItem tmpItem;
            //String Doerfer = "";

            GMList.Items.Clear();
            GMList.Groups.Clear();
            Villages.Clear();
            Groups.Clear();

            if (File.Exists("DSTool.ini"))
            {
                //String AktGrp = "";
                //String tmpStr = "";

                //FileStream fs = new FileStream("DSTool.ini", FileAccess.Read);
                //StreamReader reader = new StreamReader(fs);
                String[] ini = File.ReadAllLines("DSTool.ini", Encoding.Default);
                for (int q = 0; q < ini.Count(); q++)
                {
                    ini[q] = ini[q].Trim(" \t\n\r\0".ToCharArray());
                    if (ini[q] != "")
                    {
                        if (ini[q].StartsWith("[") && ini[q].EndsWith("]"))
                        {
                            Groups.Add(ini[q].Substring(1, ini[q].Length - 2));
                            Groups.Add(new ArrayList());
                            GMList.Groups.Add(new ListViewGroup(ini[q].Substring(1, ini[q].Length - 2)));
                        }
                        else
                            if (ini[q].StartsWith(";"))
                            {
                            }
                            else
                            {
                                if (ini[q] != "")
                                {
                                    try
                                    {
                                        if (ini[q].IndexOf(';') > 0) ini[q] = ini[q].Remove(ini[q].IndexOf(';')).Trim(" \t\n\r\0".ToCharArray());
                                        ((ArrayList)Groups[Groups.Count - 1]).Add(Convert.ToInt32(ini[q]));
                                    }
                                    catch
                                    {
                                    }
                                }
                                else
                                {
                                }
                            }
                    }
                }
            }

            GMList.Groups.Add(new ListViewGroup("Dörfer, in denen jetzt zu Betracht gezogen werden könnte militärische Einheiten zu produzieren"));
            GMList.Groups.Add(new ListViewGroup("Andere"));

            webDaten = getFromHTTP("http://de22.die-staemme.de/game.php?screen=overview_villages&mode=prod&page=-1");
            txtDEBUG.Text = webDaten;
            Clipboard.SetText(webDaten);

            posA = webDaten.IndexOf("<tr><th>Dorf</th><th>Punkte</th><th>Rohstoffe</th><th>Speicher</th>", posA);
            if (posA > 0) posA += 67;
            else
            {
                MessageBox.Show("Fehler beim Einlesen der Truppeninformationen");
                return 1;
            }


            while (true)
            {
                posA = webDaten.IndexOf("<a href=\"/game.php?village=", posA);
                if (posA <= 0) break;
                tmpVillage = new Village();
                posA += 27;
                posB = webDaten.IndexOf("&amp;", posA);
                //MessageBox.Show(webDaten.Substring(posA, posB - posA));
                tmpVillage.ID = Convert.ToInt32(webDaten.Substring(posA, posB - posA));
                tmpStr = "<span id=\"label_text_" + webDaten.Substring(posA, posB - posA) + "\">";
                posC = webDaten.IndexOf(tmpStr) + tmpStr.Length;
                posB = webDaten.IndexOf("</span>", posC);
                tmpVillage.Name = webDaten.Substring(posC, posB - posC);
                //MessageBox.Show(tmpVillage.Name);
                posB = webDaten.IndexOf("<td>", posA)+4;
                posC = webDaten.IndexOf("</td>", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                tmpVillage.Punkte = Convert.ToInt32(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                posB = webDaten.IndexOf("title=\"Holz\" alt=\"\" />", posB)+22;
                posC = webDaten.IndexOf(" <img", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                tmpVillage.Holz = Convert.ToInt32(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                posB = webDaten.IndexOf("title=\"Lehm\" alt=\"\" />", posB) + 22;
                posC = webDaten.IndexOf(" <img", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                tmpVillage.Lehm = Convert.ToInt32(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                posB = webDaten.IndexOf("title=\"Eisen\" alt=\"\" />", posB) + 23;
                posC = webDaten.IndexOf(" </td>", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                tmpVillage.Eisen = Convert.ToInt32(webDaten.Substring(posB, posC - posB).Replace("<span class=\"grey\">.</span>", "").Replace("<span class=\"warn\">", "").Replace("</span>", ""));
                posB = webDaten.IndexOf("<td>", posB) + 4;
                posC = webDaten.IndexOf("</td>", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB));
                tmpVillage.Speicher = Convert.ToInt32(webDaten.Substring(posB, posC - posB));
                posB = webDaten.IndexOf("<td>", posB) + 4;
                posB = webDaten.IndexOf("\">", posB) + 2;
                posC = webDaten.IndexOf("</a>", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB));
                tmpVillage.Haendler = webDaten.Substring(posB, posC - posB);
                posB = webDaten.IndexOf("<td>", posB) + 4;
                posC = webDaten.IndexOf("</td>", posB);
                //MessageBox.Show(webDaten.Substring(posB, posC - posB));
                tmpVillage.Bauernhof = webDaten.Substring(posB, posC - posB);
                posA = posC;
                Villages.Add(tmpVillage);

                //Doerfer += tmpVillage.ID.ToString() + "\t;" + tmpVillage.Name + Environment.NewLine;

                GMList.Items.Add(tmpVillage.Name);
                tmpItem = GMList.Items[GMList.Items.Count - 1];
                for (int q = 0; q < Groups.Count/2; q++)
                    if (((ArrayList)Groups[q * 2 + 1]).Contains(tmpVillage.ID)) tmpItem.Group = GMList.Groups[q];
                if (tmpItem.Group == null) tmpItem.Group = GMList.Groups[GMList.Groups.Count - 1];
                tmpItem.UseItemStyleForSubItems = false;
                tmpItem.SubItems.Add(tmpVillage.Punkte.ToString());
                tmpItem.SubItems.Add(tmpVillage.Holz.ToString());
                if (tmpVillage.Holz >= tmpVillage.Speicher) tmpItem.SubItems[tmpItem.SubItems.Count-1].BackColor = Color.FromArgb(255, 200, 200);
                if (tmpVillage.Holz >= tmpVillage.Speicher) tmpItem.SubItems[tmpItem.SubItems.Count - 1].ForeColor = Color.Red;
                tmpItem.SubItems.Add(tmpVillage.Lehm.ToString());
                if (tmpVillage.Lehm >= tmpVillage.Speicher) tmpItem.SubItems[tmpItem.SubItems.Count - 1].BackColor = Color.FromArgb(255, 200, 200);
                if (tmpVillage.Lehm >= tmpVillage.Speicher) tmpItem.SubItems[tmpItem.SubItems.Count - 1].ForeColor = Color.Red;
                tmpItem.SubItems.Add(tmpVillage.Eisen.ToString());
                if (tmpVillage.Eisen >= tmpVillage.Speicher) tmpItem.SubItems[tmpItem.SubItems.Count - 1].BackColor = Color.FromArgb(255, 200, 200);
                if (tmpVillage.Eisen >= tmpVillage.Speicher) tmpItem.SubItems[tmpItem.SubItems.Count - 1].ForeColor = Color.Red;
                tmpItem.SubItems.Add(tmpVillage.Speicher.ToString());
                tmpItem.SubItems.Add(tmpVillage.Bauernhof);
                posB = tmpVillage.Bauernhof.IndexOf('/');
                if (tmpVillage.Bauernhof.Substring(0, posB) != tmpVillage.Bauernhof.Substring(posB + 1))
                {
                    tmpItem.Group = GMList.Groups[GMList.Groups.Count - 2];
                    tmpItem.SubItems[tmpItem.SubItems.Count - 1].BackColor = Color.LightGoldenrodYellow;
                    tmpItem.SubItems[tmpItem.SubItems.Count - 1].ForeColor = Color.Orange;
                }
                tmpItem.SubItems.Add("0");
                tmpItem.SubItems.Add(tmpVillage.ID.ToString());
                //MessageBox.Show(tmpVillage.ID.ToString() + " " + tmpVillage.Name + ", " + tmpVillage.Punkte.ToString() + ", " + tmpVillage.Holz.ToString() + ", " + tmpVillage.Lehm.ToString() + ", " + tmpVillage.Eisen.ToString() + ", " + tmpVillage.Speicher + ", " + tmpVillage.Bauernhof);
            }

            //Clipboard.SetText(Doerfer);

            GMgetKey();

            this.Enabled = true;
            return 0;
        }

        private void GMgetKey()
        {
            String webDaten = "";
            int posA = 0;
            if (Villages.Count > 0)
            {
                for (int q = 0; q < Villages.Count; q++)
                {
                    webDaten = getFromHTTP("http://de22.die-staemme.de/game.php?village=" + Villages[q].ID.ToString() + "&screen=snob");
                    //Clipboard.SetText(webDaten);
                    if (webDaten.IndexOf("<th>Prägen</th>") <= 0) return;
                    posA = webDaten.IndexOf("action=coin&amp;h="); //18
                    if (posA > 0)
                    {
                        posA += 18;
                        GMKey = webDaten.Substring(posA, 4);
                        return;
                    }
                }
            }
        }

        private void TRgetTruppen()
        {
            String webDaten = "";
            String cmdDaten = "";
            int posA = 0;
            int posB = 0;
            int posC = 0;
            String TRurl = "";
            //String TRid = "";
            Truppen TR;
            ListViewItem tmpItem = null;
            List<String> TRid = new List<String>();

            TRList.Items.Clear();
            TRList.Groups.Clear();
            TRList.Groups.Add("Unt", "Unterstützung");
            TRList.Groups.Add("Ang", "Angriffe");
            TRList.Groups.Add("Zur", "Zurückgeschickt");
            TRList.Groups.Add("Rue", "Rückkehr");
            TRList.Groups.Add("Ruz", "Rückzug");
            TRList.Groups.Add("Abg", "Abgebrochene Befehle");
            TRList.Groups.Add("And", "Andere");

            pnlWait.Visible = true;
            pbWait.Value = 0;
            lblWaitMsg.Text = "Prüfe Dörfer"+Environment.NewLine;
            lblWaitProgress.Text = "0%";

            for (int q = 0; q < Villages.Count; q++)
            {
                pbWait.Value = q*100/Villages.Count;
                lblWaitMsg.Text = "Prüfe Dörfer" + Environment.NewLine + Villages[q].Name;
                lblWaitProgress.Text = (q*100/Villages.Count).ToString() + "%";
                webDaten = getFromHTTP("http://de22.die-staemme.de/game.php?village=" + Villages[q].ID.ToString() + "&screen=place");
                posA = 0;
                this.Enabled = true;
                while(true)
                {
                    Application.DoEvents();
                    posA = webDaten.IndexOf("/game.php?village=" + Villages[q].ID.ToString() + "&amp;screen=info_command", posA);
                    if (posA <= 0) break;
                    //if (posA <= 0)
                    //{
                    //    if (MessageBox.Show("Fehler beim Prüfen der Dörfer. Weiterhin versuchen?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2) == DialogResult.Yes) break;
                    //    pnlWait.Visible = false;
                    //    return;
                    //}
                    posB = webDaten.IndexOf("\"><img src", posA);
                    if (posB <= 0) break;
                    TRurl = "http://de22.die-staemme.de" + webDaten.Substring(posA, posB-posA).Replace("&amp;", "&");
                    posA += ("/game.php?village=" + Villages[q].ID.ToString() + "&amp;screen=info_command").Length+8;
                    posB = webDaten.IndexOf("&amp;type", posA);
                    if (posB <= 0) break;
                    if (TRid.Contains(webDaten.Substring(posA, posB - posA))) continue;
                    TRid.Add(webDaten.Substring(posA, posB - posA));
                    cmdDaten = getFromHTTP(TRurl);
                    //Clipboard.SetText(cmdDaten);
                    posB = cmdDaten.IndexOf("<h2>");
                    if (posB <= 0) continue;
                    posB += 4;
                    TR = new Truppen();
                    TR.ID = Convert.ToInt32(TRid[TRid.Count - 1]);
                    if (cmdDaten.Substring(posB, "Unterstützung".Length) == "Unterstützung") TR.Typ = "Unterstützung";
                    if (cmdDaten.Substring(posB, "Angriff".Length) == "Angriff") TR.Typ = "Angriff";
                    if (cmdDaten.Substring(posB, "Zurückgeschickt".Length) == "Zurückgeschickt") TR.Typ = "Zurückgeschickt";
                    if (cmdDaten.Substring(posB, "Rückkehr".Length) == "Rückkehr") TR.Typ = "Rückkehr";
                    if (cmdDaten.Substring(posB, "Rückzug".Length) == "Rückzug") TR.Typ = "Rückzug";
                    if (cmdDaten.Substring(posB, "Abgebrochener Befehl".Length) == "Abgebrochener Befehl") TR.Typ = "Abgebrochener Befehl";
                    if (TR.Typ == "") TR.Typ = "Unbekannt";
                    posB = cmdDaten.IndexOf(">", cmdDaten.IndexOf("Herkunft<td>Spieler:</td><td>")+29)+1;
                    posC = cmdDaten.IndexOf("</a></td>", posB);
                    if (posB <= 0 || posC <= 0) continue;
                    TR.HerkunftSpieler = HttpUtility.UrlDecode(cmdDaten.Substring(posB, posC - posB));
                    posB = cmdDaten.IndexOf(">", cmdDaten.IndexOf("Dorf:</td><td><a href", posB) + 21) + 1;
                    posC = cmdDaten.IndexOf("</a></td>", posB);
                    if (posB <= 0 || posC <= 0) continue;
                    TR.Herkunft = HttpUtility.UrlDecode(cmdDaten.Substring(posB, posC - posB));
                    posB = cmdDaten.IndexOf(">", cmdDaten.IndexOf("Ziel</td><td>Spieler:</td><td>") + 30) + 1;
                    posC = cmdDaten.IndexOf("</a></td>", posB);
                    if (posB <= 0 || posC <= 0) continue;
                    TR.ZielSpieler = HttpUtility.UrlDecode(cmdDaten.Substring(posB, posC - posB));
                    posB = cmdDaten.IndexOf(">", cmdDaten.IndexOf("Dorf:</td><td><a href", posB) + 21) + 1;
                    posC = cmdDaten.IndexOf("</a></td>", posB);
                    if (posB <= 0 || posC <= 0) continue;
                    TR.Ziel = HttpUtility.UrlDecode(cmdDaten.Substring(posB, posC - posB));
                    posB = cmdDaten.IndexOf("Ankunft in:</td><td><span class=\"timer\">");
                    if (posB <= 0) continue;
                    posB += 40;
                    posC = cmdDaten.IndexOf("</span>", posB);
                    if (posC <= 0) continue;
                    TR.Ankunft = HttpUtility.UrlDecode(cmdDaten.Substring(posB, posC - posB));
                    posB = cmdDaten.IndexOf("title=\"Adelsgeschlecht\" alt=\"\" /></th></tr>");

                    //MessageBox.Show(TR.Typ + " (" + TR.ID + ") von " + TR.Herkunft + " (" + TR.HerkunftSpieler + ") nach " + TR.Ziel + " (" + TR.ZielSpieler + ") in " + TR.Ankunft);

                    if (posB > 0)
                    {
                        posB += 43;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        //MessageBox.Show(cmdDaten.Substring(posB, posC - posB));
                        TR.Speertraeger = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Schwertkaempfer = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Axtkaempfer = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Bogenschuetze = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Spaeher = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.LeichteKavallerie = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.BerittenerBogenschuetze = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.SchwereKavallerie = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Rammbock = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Katapult = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Paladin = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                        posB = posC + 1;
                        posB = cmdDaten.IndexOf("<td", posB);
                        if (posB <= 0) continue;
                        posB = cmdDaten.IndexOf(">", posB);
                        if (posB <= 0) continue; else posB += 1;
                        posC = cmdDaten.IndexOf("</td>", posB);
                        if (posC <= 0) continue;
                        TR.Adelsgeschlecht = Convert.ToInt32(cmdDaten.Substring(posB, posC - posB));
                    }

                    TRList.Items.Add(TR.Herkunft);
                    tmpItem = TRList.Items[TRList.Items.Count - 1];
                    if (TR.Typ == "Unterstützung") tmpItem.Group = TRList.Groups["Unt"];
                    if (TR.Typ == "Angriff") tmpItem.Group = TRList.Groups["Ang"];
                    if (TR.Typ == "Zurückgeschickt") tmpItem.Group = TRList.Groups["Zur"];
                    if (TR.Typ == "Rückkehr") tmpItem.Group = TRList.Groups["Rue"];
                    if (TR.Typ == "Rückzug") tmpItem.Group = TRList.Groups["Ruz"];
                    if (TR.Typ == "Abgebrochener Befehl") tmpItem.Group = TRList.Groups["Abg"]; 
                    if (TR.Typ == "Unbekannt") tmpItem.Group = TRList.Groups["And"];
                    tmpItem.SubItems.Add(TR.Ziel);
                    tmpItem.SubItems.Add(TR.HerkunftSpieler);
                    tmpItem.SubItems.Add(TR.ZielSpieler);
                    tmpItem.SubItems.Add(TR.Ankunft);

                    tmpItem.SubItems.Add(TR.Speertraeger.ToString());
                    tmpItem.SubItems.Add(TR.Schwertkaempfer.ToString());
                    tmpItem.SubItems.Add(TR.Axtkaempfer.ToString());
                    tmpItem.SubItems.Add(TR.Bogenschuetze.ToString());
                    tmpItem.SubItems.Add(TR.Spaeher.ToString());
                    tmpItem.SubItems.Add(TR.LeichteKavallerie.ToString());
                    tmpItem.SubItems.Add(TR.BerittenerBogenschuetze.ToString());
                    tmpItem.SubItems.Add(TR.SchwereKavallerie.ToString());
                    tmpItem.SubItems.Add(TR.Rammbock.ToString());
                    tmpItem.SubItems.Add(TR.Katapult.ToString());
                    tmpItem.SubItems.Add(TR.Paladin.ToString());
                    tmpItem.SubItems.Add(TR.Adelsgeschlecht.ToString());
                }

            }

            pnlWait.Visible = false;

        }


        private void STgetData()
        {

            STDoerfer.VirtualListSize = 0;
            STSpieler.VirtualListSize = 0;
            STStaemme.VirtualListSize = 0;

            StatData.Ally.Clear();
            StatData.Conquer.Clear();
            StatData.Player.Clear();
            StatData.Profile.Clear();
            StatData.Village.Clear();

            pnlWait.Visible = true;
            WebClient wc;
            Stream webstream;
            GZipStream decompress;
            StreamReader sr;
            int cnt;

            // Dörfer
            pbWait.Value = 0;
            lblWaitProgress.Text = "0%";
            lblWaitMsg.Text = "Empfange Dörfer ...";
            Application.DoEvents();

            wc = new WebClient();
            webstream = wc.OpenRead("http://de22.die-staemme.de/map/village.txt.gz");
            decompress = new GZipStream(webstream, CompressionMode.Decompress);
            sr = new StreamReader(decompress);
            cnt = 0;
            while (!sr.EndOfStream)
            {
                string ln = sr.ReadLine();
                string[] dat = ln.Split(',');
                for (int q = 0; q < dat.Length; q++)
                    dat[q] = HttpUtility.UrlDecode(dat[q]);
                StatData.Village.Add(new StatistikDaten.VillageDaten(Convert.ToInt32(dat[0]), dat[1], Convert.ToInt32(dat[2]), Convert.ToInt32(dat[3]), Convert.ToInt32(dat[4]), Convert.ToInt32(dat[5]), Convert.ToInt32(dat[6])));
                if (cnt % 200 == 0)
                {
                    pbWait.Value = Math.Min(100, Math.Max(0, cnt*8/35000));
                    lblWaitProgress.Text = pbWait.Value.ToString()+"%";
                    lblWaitMsg.Text = "Empfange Dörfer ..." + System.Environment.NewLine + cnt.ToString();
                    Application.DoEvents();
                }
                cnt++;
                //if (cnt > 10000) break;    // Zum Testen
            }
            sr.Close();
            decompress.Close();
            webstream.Close();


            // Spieler
            pbWait.Value = 85;
            lblWaitProgress.Text = "85%";
            lblWaitMsg.Text = "Empfange Spieler ...";
            Application.DoEvents();

            wc = new WebClient();
            webstream = wc.OpenRead("http://de22.die-staemme.de/map/player.txt.gz");
            decompress = new GZipStream(webstream, CompressionMode.Decompress);
            sr = new StreamReader(decompress);
            cnt = 0;
            while (!sr.EndOfStream)
            {
                string ln = sr.ReadLine();
                string[] dat = ln.Split(',');
                for (int q = 0; q < dat.Length; q++)
                    dat[q] = HttpUtility.UrlDecode(dat[q]);
                StatData.Player.Add(new StatistikDaten.PlayerDaten(Convert.ToInt32(dat[0]), dat[1], Convert.ToInt32(dat[2]), Convert.ToInt32(dat[3]), Convert.ToInt32(dat[4]), Convert.ToInt32(dat[5])));
                if (cnt % 50 == 0)
                {
                    lblWaitMsg.Text = "Empfange Spieler ..." + System.Environment.NewLine + cnt.ToString();
                    Application.DoEvents();
                }
                cnt++;
            }
            sr.Close();
            decompress.Close();
            webstream.Close();


            // Stämme
            pbWait.Value = 90;
            lblWaitProgress.Text = "90%";
            lblWaitMsg.Text = "Empfange Stämme ...";
            Application.DoEvents();

            wc = new WebClient();
            webstream = wc.OpenRead("http://de22.die-staemme.de/map/ally.txt.gz");
            decompress = new GZipStream(webstream, CompressionMode.Decompress);
            sr = new StreamReader(decompress);
            cnt = 0;
            while (!sr.EndOfStream)
            {
                string ln = sr.ReadLine();
                string[] dat = ln.Split(',');
                for (int q = 0; q < dat.Length; q++)
                    dat[q] = HttpUtility.UrlDecode(dat[q]);
                StatData.Ally.Add(new StatistikDaten.AllyDaten(Convert.ToInt32(dat[0]), dat[1], dat[2], Convert.ToInt32(dat[3]), Convert.ToInt32(dat[4]), Convert.ToInt32(dat[5]), Convert.ToInt32(dat[6]), Convert.ToInt32(dat[7])));
                if (cnt % 20 == 0)
                {
                    lblWaitMsg.Text = "Empfange Stämme ..." + System.Environment.NewLine + cnt.ToString();
                    Application.DoEvents();
                }
                cnt++;
            }
            sr.Close();
            decompress.Close();
            webstream.Close();



            // Profile
            pbWait.Value = 95;
            lblWaitProgress.Text = "95%";
            lblWaitMsg.Text = "Empfange Profile ...";
            Application.DoEvents();

            wc = new WebClient();
            webstream = wc.OpenRead("http://de22.die-staemme.de/map/profile.txt.gz");
            decompress = new GZipStream(webstream, CompressionMode.Decompress);
            sr = new StreamReader(decompress);
            cnt = 0;
            while (!sr.EndOfStream)
            {
                string ln = sr.ReadLine();
                string[] dat = ln.Split(',');
                for (int q = 0; q < dat.Length; q++)
                    dat[q] = HttpUtility.UrlDecode(dat[q]);
                StatData.Profile.Add(new StatistikDaten.ProfileDaten(Convert.ToInt32(dat[0]), dat[1], dat[2], dat[3], "", ""));
                if (cnt % 50 == 0)
                {
                    lblWaitMsg.Text = "Empfange Profile ..." + System.Environment.NewLine + cnt.ToString();
                    Application.DoEvents();
                }
                cnt++;
            }
            sr.Close();
            decompress.Close();
            webstream.Close();




                        
            STDoerfer.VirtualListSize = StatData.Village.Count;
            STSpieler.VirtualListSize = StatData.Player.Count;
            STStaemme.VirtualListSize = StatData.Ally.Count;

            pnlWait.Visible = false;



        }




        private void btnAkt_Click(object sender, EventArgs e)
        {
            if (tabCMain.SelectedTab == tabGM) GMgetVillages();
            if (tabCMain.SelectedTab == tabTruppen) TRgetTruppen();
            if (tabCMain.SelectedTab == tabStats) STgetData();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            webBrowser.GoBack();
        }

        private void btnFwd_Click(object sender, EventArgs e)
        {
            webBrowser.GoForward();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            webBrowser.Stop();
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            webBrowser.Refresh();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            String tmpURL = txtURL.Text;
            //if (!tmpURL.StartsWith("www.")) tmpURL = "www." + tmpURL;
            if (!tmpURL.StartsWith("http://")) tmpURL = "http://" + tmpURL;
            Uri tmpUri = new Uri(tmpURL);
            webBrowser.Url = tmpUri;
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            txtURL.Text = webBrowser.Url.ToString();
        }


        static private String getFromHTTP(String WebAddress)
        {

            // used to build entire input
            StringBuilder sb = new StringBuilder();
            HttpWebResponse response = null;

            // used on each read operation
            byte[] buf = new byte[8192];

            try
            {
                // prepare the web page we will be asking for
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(WebAddress);
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
                request.KeepAlive = true;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers["Cookie"] = Cookies;
                request.Expect = "";

                // execute the request
                response = (HttpWebResponse)request.GetResponse();

                // we will read data via the response stream
                Stream resStream = response.GetResponseStream();
                
                string tempString = null;
                int count = 0;

                do
                {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to default //ASCII text
                        tempString = Encoding.UTF8.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?
                response.Close();
            }
            catch (Exception ex)
            {
                if (response != null) response.Close();
                MessageBox.Show(ex.Message);
                return "";
            }

            // print out page source
            return sb.ToString();

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            if (Cookies == "")
            {
                Cookies = doLogin(txtUsername.Text, txtPassword.Text);
                //webBrowser.Document.Cookie = Cookies;
                if (Cookies == "")
                {
                    MessageBox.Show("Fehler beim Login!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {
                    pnlLogin.Enabled = false;
                    btnLogin.Text = "Logout";
                    GMgetVillages();
                    tabCMain.SelectedTab = tabGM;
                }
            }
            else
            {
                pnlLogin.Enabled = true;
                Cookies = "";
                GMKey = "";
                btnLogin.Text = "Login";
            }
            this.Enabled = true;
        }


        static private String doLogin(String Username, String Password)
        {

            String tmpStr = "";

            try
            {
                // prepare the web page we will be asking for
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.die-staemme.de/index.php?action=login");
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
                request.KeepAlive = true;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Expect = "";
                request.Referer = "http://www.die-staemme.de/";
                request.AllowAutoRedirect = false;

                string lcPostData = "user=" + HttpUtility.UrlEncode(Username) +
                   "&clear=true&password=" + HttpUtility.UrlEncode(Password) + "&server=de22";
                request.Method = "POST";
                byte[] lbPostBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(lcPostData);
                request.ContentLength = lbPostBuffer.Length;
                request.ContentType = "application/x-www-form-urlencoded";
                Stream loPostData = request.GetRequestStream();
                loPostData.Write(lbPostBuffer, 0, lbPostBuffer.Length);
                loPostData.Close();

                // execute the request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Close();

                if (response.Headers["Location"] == null) return "";

                request = (HttpWebRequest)WebRequest.Create(response.Headers["Location"]);
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
                request.KeepAlive = true;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Expect = "";
                request.Referer = "http://www.die-staemme.de/index.php";
                request.AllowAutoRedirect = false;


                // execute the request
                response = (HttpWebResponse)request.GetResponse();
                response.Close();

                if (response.Headers["Location"] == null) return "";

                request = (HttpWebRequest)WebRequest.Create("http://de22.die-staemme.de/" + response.Headers["Location"]);
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
                request.KeepAlive = true;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                tmpStr = response.Headers["Set-Cookie"];
                tmpStr = tmpStr.Replace("httponly,", "");
                tmpStr = tmpStr.Remove(tmpStr.IndexOf("expires") - 2);
                request.Headers["Cookie"] = tmpStr;
                request.Expect = "";
                request.Referer = "http://www.die-staemme.de/index.php";
                request.AllowAutoRedirect = false;

                // execute the request
                response = (HttpWebResponse)request.GetResponse();

                response.Close();
                return tmpStr;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Unerwarteter Fehler beim Login (" + ex.Message + ")");
                return "";
            }

        }

        private void GMList_FloatPositionChanged(object sender, EventArgs e)
        {
            SetFloatCbPosition();
        }

        private void SetFloatCbPosition()
        {
            //ListViewItem tmpItem;
            ListViewItem.ListViewSubItem tmpItem;
            ListViewItem tmpItemGroup = null;
            if (GMList.SelectedItems.Count == 1)
            {
                //tmpItem = GMList.SelectedItems[0]; //.SubItems[GMList.SelectedItems[0].SubItems.Count - 2];
                tmpItem = GMList.SelectedItems[0].SubItems[GMList.SelectedItems[0].SubItems.Count - 2];
                for (int q = 0; q < GMList.Items.Count; q++)
                    if (GMList.Items[q].Group == GMList.SelectedItems[0].Group) { tmpItemGroup = GMList.Items[q]; break; }
                GMedit.Location = new Point(GMList.Bounds.Location.X + tmpItem.Bounds.Location.X + GMList.Margin.Left, GMList.Bounds.Location.Y + tmpItem.Bounds.Location.Y);
                GMedit.Width = tmpItem.Bounds.Width;
                GMedit.Height = tmpItem.Bounds.Height;
                if (GMLastSel != tmpItem)
                {
                    GMedit.Visible = true;
                    GMedit.Show();
                    GMedit.BringToFront();
                    GMedit.Update();
                    GMedit.Text = tmpItem.Text;
                    //GMedit.Focus();
                    //GMedit.SelectAll();
                    GMLastSel = tmpItem;
                }

                if (tmpItemGroup != null)
                {
                    GMGedit.Location = new Point(GMList.Bounds.Location.X + tmpItem.Bounds.Location.X + GMList.Margin.Left, GMList.Bounds.Location.Y + tmpItemGroup.Bounds.Location.Y - 25);
                    GMGedit.Width = tmpItem.Bounds.Width;
                    GMGedit.Height = tmpItem.Bounds.Height;
                    if (GMGLastSel != tmpItemGroup.Group)
                    {
                        GMGedit.Text = "";
                        GMGedit.Visible = true;
                        GMGedit.Show();
                        GMGedit.BringToFront();
                        GMGedit.Update();
                        GMGLastSel = tmpItemGroup.Group;
                    }
                }
            }
            else
            {
                if (GMLastSel != null)
                {
                    GMedit.Visible = false;
                    GMedit.Hide();
                    GMLastSel = null;
                }
                if (GMGLastSel != null)
                {
                    GMGedit.Visible = false;
                    GMGedit.Hide();
                    GMGLastSel = null;
                }
                //try { GMList.Focus(); }
                //catch { }
            }

        }

        private void GMList_FloatPositionChanged(object sender, ColumnReorderedEventArgs e)
        {
            SetFloatCbPosition();
        }

        private void GMList_FloatPositionChanged(object sender, ColumnWidthChangedEventArgs e)
        {
            SetFloatCbPosition();
        }

        private void GMList_FloatPositionChanged(object sender, ColumnWidthChangingEventArgs e)
        {
            SetFloatCbPosition();
        }

        private void GMedit_TextChanged(object sender, EventArgs e)
        {
            ListViewItem.ListViewSubItem tmpItem;
            if (GMList.SelectedItems.Count == 1)
            {
                tmpItem = GMList.SelectedItems[0].SubItems[GMList.SelectedItems[0].SubItems.Count - 2];
                try
                {
                    if (Convert.ToInt32(GMedit.Text) < 0) throw new Exception();
                    tmpItem.Text = (GMedit.Text == "" ? "0" : Convert.ToInt32(GMedit.Text).ToString());
                }
                catch
                {
                    tmpItem.Text = "0";
                }
                if (tmpItem.Text != "0")
                {
                    try
                    {
                        //MessageBox.Show(GMList.SelectedItems[0].SubItems[0].Text);
                        if (Convert.ToInt32(GMList.SelectedItems[0].SubItems[2].Text) < 28000 | Convert.ToInt32(GMList.SelectedItems[0].SubItems[3].Text) < 30000 | Convert.ToInt32(GMList.SelectedItems[0].SubItems[4].Text) < 25000)
                            tmpItem.BackColor = Color.FromArgb(255, 192, 192);
                        else
                        {
                            if (28000 * Convert.ToInt32(tmpItem.Text) < 0 || 30000 * Convert.ToInt32(tmpItem.Text) < 0 || 25000 * Convert.ToInt32(tmpItem.Text) < 0) throw new Exception();
                            if (Convert.ToInt32(GMList.SelectedItems[0].SubItems[2].Text) < (28000 * Convert.ToInt32(tmpItem.Text)) | Convert.ToInt32(GMList.SelectedItems[0].SubItems[3].Text) < (30000 * Convert.ToInt32(tmpItem.Text)) | Convert.ToInt32(GMList.SelectedItems[0].SubItems[4].Text) < (25000 * Convert.ToInt32(tmpItem.Text)))
                                tmpItem.BackColor = Color.FromArgb(255, 255, 128); //Color.FromArgb(255, 192, 128);
                            else
                                tmpItem.BackColor = Color.LightGreen;
                        }
                    }
                    catch
                    {
                        tmpItem.BackColor = Color.Red;
                    }
                }
                else tmpItem.BackColor = SystemColors.Window;
            }
        }

        private void GMGedit_TextChanged(object sender, EventArgs e)
        {
            ListViewItem.ListViewSubItem tmpItem;
            ListViewItem.ListViewSubItem tmpItemGroup = null;
            if (GMList.SelectedItems.Count == 1)
            {
                tmpItem = GMList.SelectedItems[0].SubItems[GMList.SelectedItems[0].SubItems.Count - 2];
                try
                {
                    if (Convert.ToInt32(GMGedit.Text) < 0) throw new Exception();  //Fehler bei ungültiger Eingabe erzeugen
                    for (int q = 0; q < GMList.Items.Count; q++)
                        if (GMList.Items[q].Group == GMList.SelectedItems[0].Group)
                        {
                            tmpItemGroup = GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 2];
                            tmpItemGroup.Text = Convert.ToInt32(GMGedit.Text).ToString();
                            if (tmpItemGroup.Text != "0")
                            {
                                try
                                {
                                    if (Convert.ToInt32(GMList.Items[q].SubItems[2].Text) < 28000 || Convert.ToInt32(GMList.Items[q].SubItems[3].Text) < 30000 || Convert.ToInt32(GMList.Items[q].SubItems[4].Text) < 25000)
                                        tmpItemGroup.BackColor = Color.FromArgb(255, 192, 192);
                                    else
                                    {
                                        if (28000 * Convert.ToInt32(tmpItemGroup.Text) < 0 || 30000 * Convert.ToInt32(tmpItemGroup.Text) < 0 || 25000 * Convert.ToInt32(tmpItemGroup.Text) < 0) throw new Exception();
                                        if (Convert.ToInt32(GMList.Items[q].SubItems[2].Text) < (28000 * Convert.ToInt32(tmpItemGroup.Text)) || Convert.ToInt32(GMList.Items[q].SubItems[3].Text) < (30000 * Convert.ToInt32(tmpItemGroup.Text)) || Convert.ToInt32(GMList.Items[q].SubItems[4].Text) < (25000 * Convert.ToInt32(tmpItemGroup.Text)))
                                            tmpItemGroup.BackColor = Color.FromArgb(255, 255, 128);
                                        else
                                            tmpItemGroup.BackColor = Color.LightGreen;
                                    }
                                }
                                catch
                                {
                                    tmpItemGroup.BackColor = Color.Red;
                                }
                            }
                            else tmpItemGroup.BackColor = SystemColors.Window;
                        }
                    GMedit.Text = GMGedit.Text;
                }
                catch
                {
                }
            }
        }

        private void txtURL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnGo_Click(sender, e);
                e.Handled = true;
            }
        }

        private void btnGMPraegen_Click(object sender, EventArgs e)
        {
            int ges = 0;
            int akt = 0;
            int akt2 = 0;
            int pos = 0;
            String webDaten;

            if (GMKey == "") GMgetKey();
            if (GMKey == "") { MessageBox.Show("Fehler beim Prägen"); return; }

            for (int q = 0; q < GMList.Items.Count; q++)
                ges += Convert.ToInt32(GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 2].Text);
            if (ges > 0)
            {
                pnlWait.Visible = true;
                pbWait.Value = 0;
                lblWaitProgress.Text = "0%";
                Application.DoEvents();
                for (int q = 0; q < GMList.Items.Count; q++)
                {
                    akt2 += Convert.ToInt32(GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 2].Text);
                    for (int w = 1; w <= Convert.ToInt32(GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 2].Text); w++)
                    {
                        akt++;
                        lblWaitMsg.Text = "Präge Goldmünzen" + Environment.NewLine + Environment.NewLine + "Aktuelles Dorf: " + GMList.Items[q].SubItems[0].Text;
                        Application.DoEvents();
                        if (Convert.ToInt32(GMList.Items[q].SubItems[2].Text) >= 28000 && Convert.ToInt32(GMList.Items[q].SubItems[3].Text) >= 30000 && Convert.ToInt32(GMList.Items[q].SubItems[4].Text) >= 25000)
                        {
                            webDaten = getFromHTTP("http://de22.die-staemme.de/game.php?village=" + GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 1].Text + "&screen=snob&action=coin&h=" + GMKey);
                            pos = webDaten.IndexOf("<th>Prägen</th");
                            if (pos <= 0)
                            {
                                if (MessageBox.Show("Fehler beim Prägen. Weiter versuchen?", "Fehler", MessageBoxButtons.YesNo, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2) != DialogResult.Yes) { pnlWait.Visible = false; return; }
                            }
                            else
                            {
                                if (webDaten.IndexOf("Rohstoffe verfügbar", pos) > 0) break;
                                GMList.Items[q].SubItems[2].Text = (Convert.ToInt32(GMList.Items[q].SubItems[2].Text) - 28000).ToString();
                                GMList.Items[q].SubItems[3].Text = (Convert.ToInt32(GMList.Items[q].SubItems[3].Text) - 30000).ToString();
                                GMList.Items[q].SubItems[4].Text = (Convert.ToInt32(GMList.Items[q].SubItems[4].Text) - 25000).ToString();
                            }
                        }
                        else break;
                        pbWait.Value = akt * 100 / ges;
                        lblWaitProgress.Text = (akt * 100 / ges).ToString() + "%";
                        Application.DoEvents();
                        //MessageBox.Show(webDaten);
                    }
                    akt = akt2;
                    pbWait.Value = akt * 100 / ges;
                    lblWaitProgress.Text = (akt * 100 / ges).ToString() + "%";
                    Application.DoEvents();
                    GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 2].Text = "0";
                    GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 2].BackColor = SystemColors.Window;
                }
                pnlWait.Visible = false;
            }
            SetFloatCbPosition();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            SetFloatCbPosition();

            TimerSecCnt++;
            if (TimerSecCnt >= 10)
            {
                TimerSecCnt = 0;
                //DateTime time;
                //for (int q = 0; q < TRList.Items.Count; q++)
                //{
                //    DateTime.TryParse(TRList.Items[q].SubItems[4].Text, out time);
                //    try {time.AddSeconds(-1);}
                //    catch {}
                //    TRList.Items[q].SubItems[4].Text = time.ToString("hhhh:mm:ss");
                //}
                string[] time;
                string tmpswap;
                for (int q = 0; q < TRList.Items.Count; q++)
                {
                    time = TRList.Items[q].SubItems[4].Text.Split(':');

                    if (time.Count() > 0)
                    {
                        if (time.Count() == 2) { tmpswap = time[0]; time[0] = time[1]; time[1] = tmpswap; }
                        if (time.Count() == 3) { tmpswap = time[0]; time[0] = time[2]; time[2] = tmpswap; }
                        if (Convert.ToInt32(time[0]) > 0) time[0] = (Convert.ToInt32(time[0]) - 1).ToString();
                        else
                            if (time.Count() > 1)
                                if (Convert.ToInt32(time[1]) > 0) { time[1] = (Convert.ToInt32(time[1]) - 1).ToString(); time[0] = "59"; }
                                else
                                    if (time.Count() > 2)
                                        if (Convert.ToInt32(time[2]) > 0) { time[2] = (Convert.ToInt32(time[2]) - 1).ToString(); time[1] = "59"; time[0] = "59"; }
                                
                        tmpswap = "";
                        if (time.Count() == 1) { tmpswap = time[0].PadLeft(2, '0'); }
                        if (time.Count() == 2) { tmpswap = time[1].PadLeft(2, '0') + ":" + time[0].PadLeft(2, '0'); }
                        if (time.Count() == 3) { tmpswap = time[2].PadLeft(2, '0') + ":" + time[1].PadLeft(2, '0') + ":" + time[0].PadLeft(2, '0'); }
                        TRList.Items[q].SubItems[4].Text = tmpswap;
                    }
                }
            }

        }

        private void alleDörferKopierenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String Doerfer = "";
            for (int q = 0; q < GMList.Items.Count; q++)
            {
                Doerfer += GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 1].Text + "\t;" + GMList.Items[q].Text + Environment.NewLine;
            }
            if (Doerfer != "") Clipboard.SetText(Doerfer);
        }

        private void ausgewähltesDorfKopierenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String Dorf = "";
            if (GMList.SelectedItems.Count > 0)
            {
                Dorf = GMList.SelectedItems[0].SubItems[GMList.SelectedItems[0].SubItems.Count-1].Text + "\t;" + GMList.SelectedItems[0].Text + Environment.NewLine;
                if (Dorf != "") Clipboard.SetText(Dorf);
            }
        }

        private void aktuelleGruppeKopierenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String Doerfer = "";
            if (GMList.SelectedItems.Count > 0)
            {
                for (int q = 0; q < GMList.Items.Count; q++)
                {
                    if (GMList.SelectedItems[0].Group == GMList.Items[q].Group)
                        Doerfer += GMList.Items[q].SubItems[GMList.Items[q].SubItems.Count - 1].Text + "\t;" + GMList.Items[q].Text + Environment.NewLine;
                }
                if (Doerfer != "") Clipboard.SetText(Doerfer);
            }
        }

        private void GMcontext_Opening(object sender, CancelEventArgs e)
        {
            if (GMList.SelectedItems.Count > 0)
            {
                aktuelleGruppeKopierenToolStripMenuItem.Enabled = true;
                ausgewähltesDorfKopierenToolStripMenuItem.Enabled = true;
            }
            else
            {
                aktuelleGruppeKopierenToolStripMenuItem.Enabled = false;
                ausgewähltesDorfKopierenToolStripMenuItem.Enabled = false;
            }
        }

        private void TRList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TRList.SelectedItems.Count > 0)
            {
                TRSpeertraeger.Text = TRList.SelectedItems[0].SubItems[5].Text;
                TRSchwertkaempfer.Text = TRList.SelectedItems[0].SubItems[6].Text;
                TRAxtkaempfer.Text = TRList.SelectedItems[0].SubItems[7].Text;
                TRBogenschuetze.Text = TRList.SelectedItems[0].SubItems[8].Text;
                TRSpaeher.Text = TRList.SelectedItems[0].SubItems[9].Text;
                TRLeichteKavallerie.Text = TRList.SelectedItems[0].SubItems[10].Text;
                TRBerittenerBogenschuetze.Text = TRList.SelectedItems[0].SubItems[11].Text;
                TRSchwereKavallerie.Text = TRList.SelectedItems[0].SubItems[12].Text;
                TRRammbock.Text = TRList.SelectedItems[0].SubItems[13].Text;
                TRKatapult.Text = TRList.SelectedItems[0].SubItems[14].Text;
                TRPaladin.Text = TRList.SelectedItems[0].SubItems[15].Text;
                TRAdelsgeschlecht.Text = TRList.SelectedItems[0].SubItems[16].Text;
            }
            else
            {
                TRSpeertraeger.Text = "";
                TRSchwertkaempfer.Text = "";
                TRAxtkaempfer.Text = "";
                TRBogenschuetze.Text = "";
                TRSpaeher.Text = "";
                TRLeichteKavallerie.Text = "";
                TRBerittenerBogenschuetze.Text = "";
                TRSchwereKavallerie.Text = "";
                TRRammbock.Text = "";
                TRKatapult.Text = "";
                TRPaladin.Text = "";
                TRAdelsgeschlecht.Text = "";
            }
        }



        public static string DecompressString(string compressedText)
        {
            byte[] gZipBuffer = Convert.FromBase64String(compressedText);
            using (var memoryStream = new MemoryStream())
            {
                int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
                memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

                var buffer = new byte[dataLength];

                memoryStream.Position = 0;
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    gZipStream.Read(buffer, 0, buffer.Length);
                }

                return Encoding.UTF8.GetString(buffer);
            }
        }

        private void STDoerfer_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {

            if (e.ItemIndex >= 0 && e.ItemIndex < StatData.Village.Count)
            {
                e.Item = new ListViewItem(StatData.Village[e.ItemIndex].name);
                StatistikDaten.PlayerDaten tmpPlayer = StatData.Player.Find(delegate(StatistikDaten.PlayerDaten player) { return player.id == StatData.Village[e.ItemIndex].player; });
                if (tmpPlayer == null) e.Item.SubItems.Add(StatData.Village[e.ItemIndex].player.ToString());
                else e.Item.SubItems.Add(tmpPlayer.name);
                e.Item.SubItems.Add(StatData.Village[e.ItemIndex].points.ToString());
                e.Item.SubItems.Add(StatData.Village[e.ItemIndex].x.ToString());
                e.Item.SubItems.Add(StatData.Village[e.ItemIndex].y.ToString());
                e.Item.SubItems.Add(StatData.Village[e.ItemIndex].rank.ToString());
                e.Item.SubItems.Add(StatData.Village[e.ItemIndex].id.ToString());
            }
        }

        private void STSpieler_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            if (e.ItemIndex >= 0 && e.ItemIndex < StatData.Player.Count)
            {
                e.Item = new ListViewItem(StatData.Player[e.ItemIndex].name);
                StatistikDaten.AllyDaten tmpAlly = StatData.Ally.Find(delegate(StatistikDaten.AllyDaten ally) { return ally.id == StatData.Player[e.ItemIndex].ally; });
                if (tmpAlly == null) e.Item.SubItems.Add(StatData.Player[e.ItemIndex].ally.ToString());
                else e.Item.SubItems.Add(tmpAlly.name);
                e.Item.SubItems.Add(StatData.Player[e.ItemIndex].villages.ToString());
                e.Item.SubItems.Add(StatData.Player[e.ItemIndex].points.ToString());
                e.Item.SubItems.Add(StatData.Player[e.ItemIndex].rank.ToString());
                StatistikDaten.ProfileDaten tmpProfile = StatData.Profile.Find(delegate(StatistikDaten.ProfileDaten profile) { return profile.player_id == StatData.Player[e.ItemIndex].id; });
                if (tmpProfile == null)
                {
                    e.Item.SubItems.Add("[unbekannt]");
                    e.Item.SubItems.Add("[unbekannt]");
                    e.Item.SubItems.Add("[unbekannt]");
                }
                else
                {
                    //if (tmpProfile.Geburtstag == "0000-00-00") e.Item.SubItems.Add("[unbekannt]"); else e.Item.SubItems.Add(tmpProfile.Geburtstag);
                    //if (tmpProfile.Geschlecht == "") e.Item.SubItems.Add("[unbekannt]"); else e.Item.SubItems.Add(tmpProfile.Geschlecht);
                    //if (tmpProfile.Wohnort == "") e.Item.SubItems.Add("[unbekannt]"); else e.Item.SubItems.Add(tmpProfile.Wohnort);

                    if (tmpProfile.Geburtstag == "0000-00-00") e.Item.SubItems.Add(""); else e.Item.SubItems.Add(tmpProfile.Geburtstag);
                    e.Item.SubItems.Add(tmpProfile.Geschlecht);
                    e.Item.SubItems.Add(tmpProfile.Wohnort);
                }
                e.Item.SubItems.Add(StatData.Player[e.ItemIndex].id.ToString());
            }
        }

        private void STStaemme_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            if (e.ItemIndex >= 0 && e.ItemIndex < StatData.Ally.Count)
            {
                e.Item = new ListViewItem(StatData.Ally[e.ItemIndex].name);
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].tag);
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].member.ToString());
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].villages.ToString());
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].points.ToString());
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].all_points.ToString());
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].rank.ToString());
                e.Item.SubItems.Add(StatData.Ally[e.ItemIndex].id.ToString());
            }
        }


        //private const int WM_HSCROLL = 0x114;
        //private const int WM_VSCROLL = 0x115;

        //protected override void WndProc(ref Message msg)
        //{
        //    if ((msg.Msg == WM_VSCROLL) || (msg.Msg == WM_HSCROLL))
        //    {
        //        MessageBox.Show("Hallo");
        //        SetFloatCbPosition();
        //    }
        //    base.WndProc(ref msg);
        //}

    }

    public class Village
    {
        public int ID = 0;
        public String Name = "";
        public int Punkte = 0;
        public int Holz = 0;
        public int Lehm = 0;
        public int Eisen = 0;
        public int Speicher = 0;
        public String Haendler = "";
        public String Bauernhof = "";
    }

    public class Truppen
    {
        public String Typ = "";
        public int ID = 0;
        public int HerkunftID = 0;
        public String Herkunft = "";
        public String HerkunftSpieler = "";
        public int ZielID = 0;
        public String Ziel = "";
        public String ZielSpieler = "";
        public String Ankunft = "";

        public int Speertraeger = 0;
        public int Schwertkaempfer = 0;
        public int Axtkaempfer = 0;
        public int Bogenschuetze = 0;
        public int Spaeher = 0;
        public int LeichteKavallerie = 0;
        public int BerittenerBogenschuetze = 0;
        public int SchwereKavallerie = 0;
        public int Rammbock = 0;
        public int Katapult = 0;
        public int Paladin = 0;
        public int Adelsgeschlecht = 0;

    }


    class StatistikDaten
    {

        public List<VillageDaten> Village = new List<VillageDaten>();
        public List<PlayerDaten> Player = new List<PlayerDaten>();
        public List<AllyDaten> Ally = new List<AllyDaten>();
        public List<ConquerDaten> Conquer = new List<ConquerDaten>();
        public List<ProfileDaten> Profile = new List<ProfileDaten>();

        public class VillageDaten
        {
            public int id = 0;
            public string name = "";
            public int x = 0;
            public int y = 0;
            public int player = 0;
            public int points = 0;
            public int rank = 0;

            public VillageDaten() {}
            public VillageDaten(int _id, string _name, int _x, int _y, int _player, int _points, int _rank)
            {
                id = _id;
                name = _name;
                x = _x;
                y = _y;
                player = _player;
                points = _points;
                rank = _rank;
            }


            public override bool Equals(Object obj)
            {
                // If parameter is null return false.
                if (obj == null)
                {
                    return false;
                }

                // If parameter cannot be cast to Point return false.
                VillageDaten o = obj as VillageDaten;
                if ((Object)o == null)
                {
                    return false;
                }

                // Return true if the fields match:
                return (id == o.id);
            }

            public bool Equals(VillageDaten o)
            {
                // If parameter is null return false:
                if ((object)o == null)
                {
                    return false;
                }

                // Return true if the fields match:
                return (id == o.id);
            }

            public override int GetHashCode()
            {
                return id;
            }

        }

        public class PlayerDaten
        {
            public int id = 0;
            public string name = "";
            public int ally = 0;
            public int villages = 0;
            public int points = 0;
            public int rank = 0;

            public PlayerDaten() {}
            public PlayerDaten(int _id, string _name, int _ally, int _villages, int _points, int _rank)
            {
                id = _id;
                name = _name;
                ally = _ally;
                villages = _villages;
                points = _points;
                rank = _rank;
            }
        }

        public class AllyDaten
        {
            public int id = 0;
            public string name = "";
            public string tag = "";
            public int member = 0;
            public int villages = 0;
            public int points = 0;
            public int all_points = 0;
            public int rank = 0;

            public AllyDaten() { }
            public AllyDaten(int _id, string _name, string _tag, int _member, int _villages, int _points, int _all_points, int _rank)
            {
                id = _id;
                name = _name;
                tag = _tag;
                member = _member;
                villages = _villages;
                points = _points;
                all_points = _all_points;
                rank = _rank;
            }
        }

        public class ConquerDaten
        {
            public int village_id = 0;
            public int unix_timestamp = 0;
            public int new_owner = 0;
            public int old_owner = 0;

            public ConquerDaten() { }
            public ConquerDaten(int _village_id, int _unix_timestamp, int _new_owner, int _old_owner)
            {
                village_id = _village_id;
                unix_timestamp = _unix_timestamp;
                new_owner = _new_owner;
                old_owner = _old_owner;
            }
        }

        public class ProfileDaten
        {
            public int player_id = 0;
            public string Geburtstag = "";
            public string Geschlecht = "";
            public string Wohnort = "";
            public string Profiltext = "";
            public string Profilbild = "";

            public ProfileDaten() { }
            public ProfileDaten(int _player_id, string _Geburtstag, string _Geschlecht, string _Wohnort, string _Profiltext, string _Profilbild)
            {
                player_id = _player_id;
                Geburtstag = _Geburtstag;
                Geschlecht = _Geschlecht;
                Wohnort = _Wohnort;
                Profiltext = _Profiltext;
                Profilbild = _Profilbild;
            }

            public override bool Equals(Object obj)
            {
                // If parameter is null return false.
                if (obj == null)
                {
                    return false;
                }

                // If parameter cannot be cast to Point return false.
                ProfileDaten o = obj as ProfileDaten;
                if ((Object)o == null)
                {
                    return false;
                }

                // Return true if the fields match:
                return (player_id == o.player_id);
            }

            public bool Equals(ProfileDaten o)
            {
                // If parameter is null return false:
                if ((object)o == null)
                {
                    return false;
                }

                // Return true if the fields match:
                return (player_id == o.player_id);
            }
            
            public override int GetHashCode()
            {
                return player_id;
            }
        }

    }

}
