  //***********************************************************************************
    // Konfiguration
  //***********************************************************************************

    // Name des Cookies
    var $cookiename = "zrrtd";

    // Maximale Anzahl von zu speichernden Zeitreihen
  var $maxentries = 25;

  // Trennzeichen fuer Zeitreihen im Cookie
  var $separator = "#";

  // Name der Checkboxes
  var $cbname = "cb";


  //***********************************************************************************
    // Globale Variablen
  //***********************************************************************************

    // Inhalt eines Eingabefeldes im Downloadformular vor der Aenderung
    var $oldcontent = "";


  //***********************************************************************************
    // Start
  //***********************************************************************************
    flavor = navigator.appName.toLowerCase()
    ver = parseFloat(navigator.appVersion)
    ie4 = (flavor.indexOf("microsoft") != -1 && ver >= 4)
    ns4 = (flavor.indexOf("netscape") != -1 && ver >= 4.01)
    works = (ie4 || ns4)
    ns4Problem=(ns4&&ver<4.06)


  //***********************************************************************************
    // function isEntry
  // Ueberprueft, ob Eintrag $id bereits im Cookie vorhanden ist
  // Input: $id = Eintrag, der ueberprueft werden soll
  // Returnwert: True = bereits im Cookie enthalten
  //             False = nicht enthalten
  //***********************************************************************************
    function isEntry ($id) {
        var $s = "";
        var $gotit = false;

        $s = $separator + ReadCookieValue($cookiename) + $separator;
        if ($s.indexOf($separator + $id + $separator) != -1) {
            $gotit = true;
        }
        return $gotit;
    }


  //***********************************************************************************
  // function removeEntry
  // Loescht Eintrag $id aus dem Cookie
  // Input: $id = Eintrag der geloescht werden soll
  // Returnwert: -
  //***********************************************************************************
  function removeEntry ($id) {
        var $s = "";
        var $x = -1;

        $s = $separator + ReadCookieValue($cookiename) + $separator;
        $x = $s.indexOf($separator + $id + $separator)
        if ($x != -1) {
            $s = $s.substring(0, $x) + $s.substring($x + $id.length + 1, $s.length);
        }
        if ($s.substring(0, 1) == $separator) {
            $s = $s.substring(1, $s.length);
        }
        if ($s.substring($s.length - 1, $s.length) == $separator) {
            $s = $s.substring(0, $s.length - 1);
        }
        window.document.cookie = $cookiename + "=" + $s + "; path=/";
  }


  //***********************************************************************************
  // function removeAllEntries
  // Loescht Alle Eintraege aus dem Cookie loeschen
  // Input: -
  // Returnwert: -
  //***********************************************************************************
  function removeAllEntries () {
      var $i;

      // alert("removeallentries start");
      // alert(window.document.cookie);
      $entrieslist = ReadCookieValue($cookiename);
      $entries = $entrieslist.split('#');
      for ($i=0; $i<$entries.length; $i++) {
          removeEntry($entries[$i]);
      }
  }


  //***********************************************************************************
  // function addEntry
  // Fuegt Eintrag $id an das Ende des Cookies an
  // Ein evtl. bereits enthaltener alter Eintrag wird vorher entfernt
  // Input: $id = Eintrag, der hinzugefuegt werden soll
  // Returnwert: true = Cookie wurde gesetzt (genauer: Cookie enthaelt irgendwas)
  //             false = Cookie ist leer bzw. Cookie gibt es nicht
  //***********************************************************************************
  function addEntry ($id, $lang) {
    var $s = "";
    var $z = 0;
    var $x = 0;

    removeEntry($id);
    $s = ReadCookieValue($cookiename);

        // Trennzeichen zaehlen, zur Ueberpruefung der maximalen Eintragsanzahl
        while ($x < $s.length && $x != -1) {
            $x = $s.indexOf($separator, $x);
            if ($x != -1) {
                $z++;
                $x++;
            }
        }

        // Cookie setzen bzw. Meldung ausgeben
        if ($z > $maxentries - 2) {
            if ( $lang == 'en' )
            {
                alert("Download can only contain up to " + $maxentries + " time series.");
            }
            else
            {
                alert("Es können maximal " + $maxentries + " Zeitreihen in die Download-Liste übernommen werden.");
            }
            preselectCheckboxes(document.form);
        }
        else {
            if ($s == "") {
                $s = $s + $id;
            }
            else {
              $s = $s + $separator + $id;
             }
          window.document.cookie = $cookiename + "=" + $s + "; path=/";
        }

        // Test, ob Cookie gesetzt
        if (window.document.cookie == '') {
        return false;
    }
    else {
      return true;
    }

    }


  //***********************************************************************************
    // function buyAndSell
  // Schreibt wenn noch nicht vorhanden Eintrag $id in Cookie bzw.
  // loescht wenn bereits vorhanden Eintrag $id aus dem Cookie
    // Input: $id = Eintrag, der gesetzt bzw. geloescht werden soll
  // Returnwert: -
  //***********************************************************************************
  function buyAndSell ($id) {
      // alert("buyandsell start");

    if (isEntry($id)) {
      removeEntry($id);
    }
    else {
      if (addEntry($id) == false) {
        alert("Ihr Browser muss f�r diese Funktion COOKIES akzeptieren.\n\nVerwenden Sie einen Browser, der Cookies unterst�tzt\nbzw. aktivieren Sie die entsprechende Option.");
        preselectCheckboxes(document.form);
      }
    }
      // alert("buyandsell ende");
  }


  //***********************************************************************************
    // function preselectCheckboxes
  // Belegt je nach Cookiezustand die Checkboxes der Seite vor
  // Returnwert: -
  //***********************************************************************************
  function preselectCheckboxes(frm) {
    var $i;
    for ($i=0; $i < frm.length; $i++) {
      if (frm.elements[$i].name == $cbname) {
        if (isEntry(frm.elements[$i].value)) {
          frm.elements[$i].checked=true;
        }
          else {
          frm.elements[$i].checked=false;
        }
      }
    }
  }


  //***********************************************************************************
  // function ReadCookieValue
  // Gibt (Browser-unabhaengig) den reinen Cookie-Wert (ohne Namen) zurueck
  // Input: $cookiename = Name des Cookies
  // Returnwert: Wert des Cookies
  //***********************************************************************************
  function ReadCookieValue ($cookiename) {
        var parts;
        var parts2;
        var ret = '';

        if (document.cookie != "") {
            parts = document.cookie.split(";");
            for (var i=0; i<parts.length; i++) {
                parts2 = parts[i].split("=");
                if (trim(parts2[0]) == $cookiename && parts2.length==2) {
                    ret = trim(parts2[1]);
                    break;
                }
            }
        }
        return ret;
  }


  //***********************************************************************************
  // function WriteCookieValue
  // schreibt ein Cookie mit einem best. Namen, legt es wenn notwendig an
  // Input: $cookiename = Name des Cookies
    //        $value = Wert des Cookies
  // Returnwert: Wert des Cookies
  //***********************************************************************************
    function WriteCookieValue($cookiename, $value) {
        document.cookie = $cookiename+"="+$value;
        return;

        var parts = document.cookie.split(";");
        var newcookie = "";
        for (var i=0; i<parts.length; i++) {
            if (parts[i] != "" && parts[i].indexOf($cookiename + "=") == -1) {
//                newcookie = newcookie + parts[i] + "; ";
//document.cookie = parts[i];
            }
        }
//        newcookie = newcookie + $cookiename + "=" + $value + "; path=/";
        document.cookie = "";
        document.cookie = newcookie;
    }


  //***********************************************************************************
    // function StoreInputfieldContent
    // Merkt sich den Inhalt eines Textfeldes des Downloadformulars vor einer Aenderung
    // Input: $text = Text
    // Returnwert: -
  //***********************************************************************************
    function StoreInputfieldContent ($text) {
        $oldcontent = $text;
    }


    //***********************************************************************************
    // function UpdateCookieForInputfield
    // Aendert den Cookieinhalt gemaess einer Aenderung in einem Textfeld des
    // Downloadformulars unter zu Hilfenahme von $oldcontent
    // Input: $text = Text
    // Returnwert: -
  //***********************************************************************************
    function UpdateCookieForInputfield ($text) {
        if ($oldcontent != $text) {
            if ($oldcontent != "") {
                removeEntry ($oldcontent);
            }
            if ($text != "") {
                addEntry ($text);
            }
        }
    }


    //***********************************************************************************
    // function CheckDate
    // Ueberprueft einen Datumsstring auf Gueltigkeit
    // Gueltige Formate: MM.JHJJ oder JHJJ
    // Fuehrende und abschliessende Blanks werden nicht beruecksichtigt
    // Input: $date = Datum
    // Returnwert: 1 = Datum gueltig
    //             0 = Datum nicht gueltig
  //***********************************************************************************
    function CheckDate ($date) {
        var $error = 0;
        var $month;
        var $year;

        $date = trim($date);
        if ($date.length == 4) {
            $year = parseFloat($date);
            if ($year < 1800 || $year > 2100 || isNaN($year) == true) {
                $error = 1;
            }
        }
        else if ($date.length == 7) {
            $month = parseFloat($date.substr(0, $date.indexOf('.')));
            $year = parseFloat($date.substr($date.indexOf('.') + 1));
            if ($month < 1 || $month > 12 || isNaN($month) == true || $year < 1800 || $year > 2100 || isNaN($year) == true) {
                $error = 1;
            }
        }
        else if ($date != '') {
            $error = 1;
        }
        return $error;
    }


    //***********************************************************************************
    // function trim
    // Entfernt von einem String fuehrende und abschliessende Blanks
    // Input: $string = String;
    // Returnwert: bereinigter String
    //***********************************************************************************
    function trim ($string) {
        while ($string.substr(0, 1) == ' ') {
            $string = $string.substr(1, $string.length - 1);
        }
        while ($string.substr($string.length - 1, 1) == ' ') {
            $string = $string.substr(0, $string.length - 1);
        }
        return $string;
    }

    //***********************************************************************************
    // function checkIfCookieSet
    // Gibt Alert aus, wenn keine Zeitreihen ausgewaehlt sind
    // Input: keiner
    // Returnwert: true/false
    //***********************************************************************************
    function checkIfCookieSet () {
        if (ReadCookieValue($cookiename) == "") {
            alert("Sie haben noch keine Zeitreihen ausgew�hlt.");
            return false;
        }
        else {
            return true;
        }
    }

    //***********************************************************************************
    // function clearAll
    // Loescht alle Eingabefelder fuer Zeitreihenschluessel
    // Input: form-Objekt
    // Returnwert: keiner
    //***********************************************************************************
    function clearAll(form) {
        var elems = form.elements;
        for (i=0; i<elems.length; i++) {
            if (elems[i].name.search(/^tr_(\w+\_){7}\w+$/) != -1) {
                if (elems[i].type == 'checkbox') {
                    $cookie_ts_handler.deleteTsKey(elems[i].value);
                    //removeEntry(elems[i].value);
                    elems[i].value = "";
                }
            }
        }
        form.func_form.click();
    }

    //***********************************************************************************
    // function clearChecked
    // Loescht alle markierten Eingabefelder fuer Zeitreihenschluessel
    // Input: form-Objekt
    // Returnwert: keiner
    //***********************************************************************************
    function clearChecked(form) {
        var elems = form.elements;
        for (i=0; i<elems.length; i++) {
            if (elems[i].name.search(/^tr_(\w+\_){7}\w+$/) != -1) {
                if ((elems[i].type == 'checkbox') && (elems[i].checked == true)) {
                    $cookie_ts_handler.deleteTsKey(elems[i].value);
                    elems[i].value = "";
                }
            }
        }
        form.func_form.click();
    }

    //Cookie.options.extend({'encode': false});
    Cookie.options = Cookie.options + {'encode': false};

    Cookie.set = function(key, value, options){
        options = $merge(this.options, options);
        if (true === this.options.encode)
        {
            value = encodeURIComponent(value);
        }
        if (options.domain) value += '; domain=' + options.domain;
        if (options.path) value += '; path=' + options.path;
        if (options.duration) {
            var date = new Date();
            date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);
            value += '; expires=' + date.toGMTString();
        }
        if (options.secure) value += '; secure';
        document.cookie = key + '=' + value;
        return $extend(options, {'key': key, 'value': value});
    }

    var CookieTsKeyHandler = new Class({

        options:
        {
            cookie_name:    'zrrtd',
            separator:      '#',
            max_entries:    25,

            cookie:         null
        },

        initialize: function ($cookie_name, $separator)
        {
            var options = { cookie_name:    $cookie_name,
                            seperator:      $separator,
                            cookie:         ''
                            }
            this.setOptions(options);

            this.initializeCookie();
        },

        initializeCookie: function()
        {
            var cookie_str = Cookie.get(this.options.cookie_name);
            if (cookie_str == false)
            {
                cookie_str = '';
            }
            this.deserialize(cookie_str);
        },

        rewriteCookie: function()
        {
            var cookie_str = this.serialize();
            if (cookie_str !== false)
            {
                Cookie.set(this.options.cookie_name, cookie_str, {path: '/'});
            }
        },

        serialize: function()
        {
            var cookie_str = '';
			run = 0;
            this.options.cookie.each(function(element, i) {
                if (element != '') {
                    if (run > 0)
                    {
                        cookie_str = cookie_str + this.options.separator;
                    }
                    cookie_str = cookie_str + element;
                    run = 1;
                }
            }.bind(this));

            return cookie_str;
        },

        deserialize: function(cookie_value)
        {
            var cookie_arr = cookie_value.split(this.options.separator)

            this.options.cookie = $H();
            for (var i = 0; i < cookie_arr.length; i++)
            {
                if (cookie_arr[i] != '') {
                    this.options.cookie.set(i, cookie_arr[i]);
                }
            }
        },

        getCookieStr: function()
        {
            return this.serialize();
        },

        appendTsKey: function(key)
        {
            next_id = this.options.cookie.values().length;
            this.options.cookie.set(next_id, key);
        },

        getIndex: function(ts_key)
        {
            for (var i = 0; i < this.options.cookie.values().length; i++)
            {
                if (this.options.cookie.get(i) == ts_key) return i;
            }

            return false;
        },

        moveUpTsKey: function(key)
        {
            var index_old = this.getIndex(key);

            if ((false === index_old) || (index_old == 0)) return;

            var index_new = index_old - 1;

            var tmp = this.options.cookie.get(index_new);
            this.options.cookie.set(index_new, key);
            this.options.cookie.set(index_old, tmp);

            this.rewriteCookie();
        },

        moveDownTsKey: function(key)
        {
            var index_old = this.getIndex(key);

            if ((false === index_old) || (index_old == (this.options.cookie.values().length - 1))) return;

            var index_old = this.getIndex(key);
            var index_new = index_old + 1;

            var tmp = this.options.cookie.get(index_new);
            this.options.cookie.set(index_new, key);
            this.options.cookie.set(index_old, tmp);

            this.rewriteCookie();
        },

        deleteTsKey: function(key)
        {
            var index = this.getIndex(key);

            this.options.cookie.remove(index);

            this.rewriteCookie();
        },

        deleteAll: function()
        {
            this.options.cookie.empty();

            this.rewriteCookie();
        },

        deleteSelected: function(form)
        {
        	elems = form.elements;
	        for (i = 0; i < elems.length; i++)
	        {
				if (elems[i].checked)
				{
					this.deleteTsKey(elems[i].value);
					if(this.serialize()) {
    					this.deserialize(Cookie.get(this.options.cookie_name));
    				}
					elems[i].checked = false;
				}
	        }
        }

    });
    CookieTsKeyHandler.implement(new Options());

var DownloadProgress = new Class({

    ajax_obj:   null,

    options:
    {
        progress_image:    null,
        download_link:    null,
        download_text:    null,
        download_url:    '',
        generate_url:    ''
    },

    initialize: function (options) {
        this.options = options;
    },

    request: function () {
        // show progress image
        this.options.progress_image.setStyle('display', 'inline');

        this.ajax_obj = new Ajax(this.options.generate_url, {
            method:     'get',
            onComplete: this.onComplete.bind(this),
            update:     this.options.download_error
        }).request();
    },

    onComplete: function () {
        // change the link location
        this.options.download_link.href = this.options.download_url;
        this.options.download_link.setStyle('display', 'inline');
        this.options.download_text.setStyle('display', 'none');

        // hide progress image
        this.options.progress_image.setStyle('display', 'none');
    }

});


