function toggleDisplay(id){
    if(document.getElementById(id).style.display == 'none')
    {
        document.getElementById(id).style.display = 'block';
    }
    else
    {
        document.getElementById(id).style.display = 'none';
    }
}

/* */
function SetCookie(sName, sValue)
{
    document.cookie = sName + "=" + escape(sValue);
}

/* */
function GetCookie(sName)
{
    var aCookie = document.cookie.split("; ");
    for (var i=0; i < aCookie.length; i++)
    {
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0]) {
            if (aCrumb.length == 2) {
                return unescape(aCrumb[1]);
            } else {
                return null;
            }
        }
    }
    return null;
}

function GetProdukt(identifer)
{
    var produkt = produkt_liste[identifer];
    if (produkt == null) {
        alert("Error: Couldn't find id: '" + identifer + "' ");
    }
    return produkt;
}

function AddOrUpdateWarenkorb(identifer)
{
    if (document.getElementById('menge_' + identifer)) {
        AddWarenkorb(parseInt(document.getElementById('menge_' + identifer).value), identifer); 
    } else { // FIXME: Somewhat ugly
        AddWarenkorb(1, identifer); 
    }
    window.location.href='warenkorb.html';
}

function Bestellung(menge, id)
{
    var obj = new Object;
    obj.menge = menge;
    obj.id    = id;
    return obj;
}

function Produkt(id, bezeichnung, preis, bild, beschreibung)
{
    var obj = new Object;
    obj.id = id;
    obj.bezeichnung = bezeichnung;
    obj.preis = preis;
    obj.beschreibung = beschreibung;
    return obj;
}

function TestJavaScript()
{
    var doc = window.open('', 'Warenkorb', "status=0,toolbar=0,location=0,width=640,height=480").document;
    doc.write("Test JavaScript:<br>");
    doc.write(document.cookie);
    doc.write("<BR>")
    doc.write("Cookie: " + unescape(GetCookie('warenkorb')));
    doc.write("<BR>")

    var cookie = unescape(GetCookie('warenkorb'));

    if (cookie) {
        var lst = cookie.split('|');
        if (lst) {
            var warenkorb = [];
            doc.write("List leer: ");
            doc.write(unescape(null));
            doc.write("<BR>");

            doc.write("List null: ");
            doc.write(null);
            doc.write("<BR>");

            doc.write("List Komplete: ");
            doc.write(lst);
            doc.write("<BR>");
            
            for (var i = 0; i < lst.length; ++i) {
                doc.write("List Item: ");
                doc.write(lst[i]);
                doc.write("<BR>");
            }
        } else {
            doc.write("EMPTY!!!!!!<BR>");
        }

    } else {

    }
}

function ShowWarenkorb_test()
{
    var doc = window.open('', 'Warenkorb', "status=0,toolbar=0,location=0,width=640,height=480").document;
    doc.write("Cookie: ");
    doc.write(GetCookie('warenkorb'));
    doc.write("<BR>")

    var warenkorb = ReadWarenkorb();
    doc.write("Length: ");
    doc.write(warenkorb.length);
    doc.write("<BR>")

    for(var i = 0; i < warenkorb.length; ++i)
    {
        doc.write(warenkorb[i]);
        doc.write(" - ")
        doc.write(warenkorb[i].menge);
        doc.write(" - ")
        doc.write(warenkorb[i].id);
        doc.write("<BR>")
    }

    doc.close()
}

function FormatPreis(preis)
{
    var str = String(preis);
    var euro = str.substring(0, str.length-2);
    var cent = str.substring(str.length-2);

    if (euro == "") {
        euro = "0";
    }

    return euro + "," + cent + " €";
}

function FormatValue(value, width, align)
{
    var str = String(value);

    if (align == 'right') {
        for(var i = str.length; i < width; ++i)
            str = " " + str;
    } else {
        for(var i = str.length; i < width; ++i)
            str = str + " ";
    }

    //  if (str.length != width) { // FIXME
    //      alert("Error: " + str.length + " != " + width);
    //  }

    return str;
}

function escapeBezeichnung(str)
{
    str = str.replace(/\n/g, ", ");
    str = str.replace(/<br\/>/g, ", ");

    // FIXME: Umlauts (do we need this, does this even work?)
    str = str.replace(/ä/g, "ae");
    str = str.replace(/ö/g, "oe");
    str = str.replace(/ü/g, "ue");
    str = str.replace(/Ä/g, "Ae");
    str = str.replace(/Ö/g, "Oe");
    str = str.replace(/Ü/g, "Ue");
    str = str.replace(/ß/g, "ss");

    str = str.replace(/ +/g, " ");

    return str;
}

function html2text(str)
{
    return str.replace(/<br *\/>/g, "\n").replace(/<.*>/g, "").replace(/ +/g, " ").replace(/\n */, "\n").replace(/^ */g, "").replace(/ *$/g, "");
}

function Stream()
{
    this.text = "";
}

Stream.prototype.write = function(text)
{
    this.text += text;
}

Stream.prototype.writeln = function(text)
{
    this.text += text + "\n";
}

Stream.prototype.getText = function()
{
    return this.text;
}

function splitLines(str)
{
    var lst = []
    var line = "";
    for(var i = 0; i < str.length; ++i)
    {
        if (str.charAt(i) == "\n") {
            lst.push(line);
            line = "";
        } else {
            line += str.charAt(i);
        }
    }
    lst.push(line);
    return lst;
}

function ShowWarenkorbAsText()
{       
    // Bezahlung auf Rechnung!

    // <INPUT TYPE="HIDDEN" NAME="recipient" VALUE="shop@hv-ravensberg.de">
    // <INPUT TYPE="HIDDEN" NAME="subject" VALUE="Online Bestellung">
    // <INPUT TYPE="HIDDEN" NAME="title" VALUE="Vielen Dank fÃ¼r Ihre E-mail">

    // Bestelldatum               : 10.01.2006                                        
    // 
    // Lieferanschrift:
    // ================
    // Name                       : Milli Mustermann
    // Einrichtung                : -
    // Strasse                    : Am Musterhof 45
    // Ort                        : 11020 Musterdorf
    // Email                      : muster@mann.de                                    
    // Telefon                    : 01002 / 110055
    // Telefax                    : - 
    //
    // Hiermit bestelle ich folgende Waren:
    //
    // Menge   Bezeichnung                              Einzelpreis  Gesamtpreis
    // -------------------------------------------------------------------------
    //     2   eaeu                                        10,00EUR     20,00EUR 
    // 
    // Versandkosten: ...
    // Versicherung: ...
    // -------------------------------------------------------------------------
    // Gesamtpreis:                                                     20,00EUR
    //                                                                  ========
    //

    stream = new Stream;

    /*    stream.writeln("Bestelldatum               : 10.01.2006");
    stream.writeln("");
    stream.writeln("Lieferanschrift:");
    stream.writeln("================");
    stream.writeln("Name                       : Milli Mustermann");
    stream.writeln("Einrichtung                : -");
    stream.writeln("Strasse                    : Am Musterhof 45");
    stream.writeln("Ort                        : 11020 Musterdorf");
    stream.writeln("Email                      : muster@mann.de");                                    
    stream.writeln("Telefon                    : 01002 / 110055");
    stream.writeln("Telefax                    : - ");
    stream.writeln("");
    stream.writeln("");
*/
    var warenkorb = ReadWarenkorb();
    
    /*    stream.writeln("Hiermit bestelle ich folgende Artikel:");
    stream.writeln("");*/

    stream.writeln("Menge  Bezeichnung                                        Einzelpreis  Insgesamt");
    stream.writeln("--------------------------------------------------------------------------------");
    stream.writeln('');
    for(var i = 0; i < warenkorb.length; ++i)
    {
        var produkt = GetProdukt(warenkorb[i].id);

        var lines = splitLines(html2text(produkt.bezeichnung))

        stream.write(FormatValue(warenkorb[i].menge, 5, 'right'));
        stream.write('  ');      
        stream.write(FormatValue(lines[0], 52, 'left'));
        stream.write('  ');
        stream.write(FormatValue(FormatPreis(produkt.preis), 8, 'right'));
        stream.write('  ');
        stream.write(FormatValue(FormatPreis(produkt.preis * warenkorb[i].menge), 9, 'right'));
        stream.writeln('');

        for(var j = 1; j < lines.length; ++j)
        {
            stream.write(FormatValue("", 5, 'right'));
            stream.write('  ');
            stream.write(FormatValue(lines[j], 52, 'left'));
            stream.write('  ');
            stream.write("", 8, 'right');
            stream.write('  ');
            stream.write("", 9, 'right');
            stream.writeln('');
        }
        stream.writeln('');
    }
    stream.writeln("--------------------------------------------------------------------------------");
    stream.writeln("Insgesamt:" + FormatValue(FormatPreis(GetGesamtPreis(warenkorb)), 70, 'right'));
    stream.writeln("Zuzüglich Porto und Verpackung                                          ========");

    return stream.getText()
}

function GetGesamtPreis(warenkorb)
{
    var komplett_preis = 0;
    for(var i = 0; i < warenkorb.length; ++i)
    {
        var produkt = GetProdukt(warenkorb[i].id);   
        komplett_preis += warenkorb[i].menge * produkt.preis;
    }
    return komplett_preis;
}

function WarenkorbEmpty()
{
    var warenkorb = ReadWarenkorb();
    return (warenkorb.length == 0);
}

function ShowWarenkorb()
{
    // document.write("Cookie: ");
    // document.write(GetCookie('warenkorb'));
    // document.write("<BR>")

    var warenkorb = ReadWarenkorb();
    
    // document.write("Length: ");
    // document.write(warenkorb.length);
    // document.write("<BR>")

    if (warenkorb.length == 0) {
        document.writeln("<p class=\"komplettpreis\">Ihr Warenkorb ist leer.</p>");
    } else {
        document.writeln("<table class=\"produkt\" width=\"100%\">");

        document.writeln("<tr><th>Entfernen</th><th width=\"100%\">Bezeichnung</th><th>Menge</th><th>Einzelpreis</th><th>Insgesamt</th></tr>");
        for(var i = 0; i < warenkorb.length; ++i)
        {
            var produkt = GetProdukt(warenkorb[i].id);
            if ((i % 2) == 0) {
                document.writeln("<tr class=\"produkt-even\">");
            } else {                
                document.writeln("<tr class=\"produkt-odd\">");
            }

            // Entfernen
            document.writeln("<td align=\"center\">");
            document.writeln("<a href=\"javascript:DeleteFromWarenkorb('" 
                             + warenkorb[i].id + "');window.location.reload()\">");
            document.write("<img alt=\"Entfernen\" title=\"Entfernen\" style=\"vertical-align: middle\" border=\"0\" src=\"images/papierkorb_small.png\" />");
            //document.write("Entfernen");
            document.write("</a>");
            document.writeln("</td>");

            // Bezeichnung/Beschreibung
            document.writeln("<td>");
            //document.write("<input type=\"hidden\" name=\"id_" + warenkorb[i].id + "\" " +
            //               "value=\"" + warenkorb[i].id + "\" />");


            document.writeln("<b><a href=\"javascript:toggleDisplay('beschreibung_" + produkt.id + "')\">" + produkt.bezeichnung+ "</a></b>");
            document.writeln("<div style=\"display: none; margin-top: 1em;\" id=\"beschreibung_" + produkt.id + "\">");

            // Bild: <a href="images/{bild}.jpg"><img style="padding: 0.5em;" src="images/{bild}_thumb.jpg" alt="Bild der Buch Vorderseite" align="right" border="0" /></a>
            
            document.writeln(produkt.beschreibung);
            document.writeln("<br clear=\"all\" />");
            document.writeln("</div>");

            //document.write("<b>");
            //document.write(produkt.bezeichnung);
            //document.write("</b>");

            document.writeln("</td>");

            document.writeln("<td align=\"right\">");
            document.write("<input onChange=\"AddOrUpdateWarenkorb('" + warenkorb[i].id + "')\" " +
                           "style=\"text-align: right;\" " + 
                           "size=\"4\" type=\"text\" " + 
                           "id=\"menge_" + warenkorb[i].id + "\" " + 
                           "value=\"" + warenkorb[i].menge + "\" />");
            document.writeln("</td>");

            document.writeln("<td nowrap=\"1\" align=\"right\">");
            document.writeln(FormatPreis(produkt.preis));
            document.writeln("</td>");

            document.writeln("<td nowrap=\"1\" align=\"right\">");
            document.writeln(FormatPreis(produkt.preis * warenkorb[i].menge));
            document.writeln("</td>");

            document.writeln("</tr>");
        }
        document.writeln("</table>");

        var komplett_preis = 0;
        for(var i = 0; i < warenkorb.length; ++i)
        {
            var produkt = GetProdukt(warenkorb[i].id);   
            komplett_preis += warenkorb[i].menge * produkt.preis;
        }
        document.writeln("<p class=\"komplettpreis\">Komplett Preis: " + FormatPreis(komplett_preis) + "</p>");
    }
}


function ReadWarenkorb()
{
    var cookie = GetCookie('warenkorb');

    if (cookie) {
        var lst = unescape(cookie).split('|');
        var warenkorb = [];
        for (var i = 0; i < lst.length; ++i) {
            if (lst[i]) {
                var bestellung = lst[i].split(',');
                warenkorb.push(Bestellung(parseInt(bestellung[0]), bestellung[1]));
            }
        }
        return warenkorb;
    } else {
        return [];
    }
}

function WriteWarenkorb(warenkorb)
{
    var cookie = "";
    for(var i = 0; i < warenkorb.length; ++i)
    {
        cookie += String(warenkorb[i].menge);
        cookie += ","
        cookie += warenkorb[i].id;
        cookie += "|"
    }
    
    SetCookie('warenkorb', escape(cookie));
}

function ClearWarenkorb()
{
    SetCookie('warenkorb', '');
}

function AddWarenkorb(menge, id)
{
    if (menge == 0) {
        DeleteFromWarenkorb(id);
    } else {
        var warenkorb = ReadWarenkorb();

        for(var i = 0; i < warenkorb.length; ++i)
        {
            if (warenkorb[i].id == id) {
                warenkorb[i].menge = menge; // FIXME
                WriteWarenkorb(warenkorb);
                return;
            }
        }
        warenkorb.push(Bestellung(menge, id));
        WriteWarenkorb(warenkorb);
    }
}

function DeleteFromWarenkorb(id)
{
    var warenkorb = ReadWarenkorb();
    
    for(var i = 0; i < warenkorb.length; ++i)
    {
        if (warenkorb[i].id == id) {
            warenkorb.splice(i, 1);
            break;
        } 
    }

    WriteWarenkorb(warenkorb);
}

function UnicodeToAscii(text)
{
    var i;
    var out = "";
    for (i=0; i < text.length; i++) {
       var c = text.charAt(i);
       if (c == "Ä") {
           out += "Ae";         
       } else if (c == "ä") {
           out += "ae";
       } else if (c == "Ö") {
           out += "Oe";
       } else if (c == "ö") {
           out += "oe";
       } else if (c == "Ü") {
           out += "Ue";
       } else if (c == "ü") {
           out += "ue";
       } else if (c == "ß") {
           out += "ss";
       } else if (c == " ") {
           out += " ";
       } else if (c == "€") {
           out += "EUR";
       } else {
           out += c;
       }
    }
    return out
}

function BestellFormularCheckAndSend()
{
    var missing="";

    if (window.document.Feedback.Name.value == "") {
        missing += "  * Name\n"
    }

    if (window.document.Feedback.Strasse.value == "") {
        missing += "  * Strasse\n"
    }

    if (window.document.Feedback.PLZ.value == "") {
        missing += "  * Postleitzahl\n"
    }

    if (window.document.Feedback.Ort.value == "") {
        missing += "  * Ort\n"
    }    

    if (window.document.Feedback.email.value == "") {
        missing += "  * E-Mail\n"
    }    
    
    if (missing == "") {
        window.document.Feedback.Nachricht.value = UnicodeToAscii(window.document.Feedback.Nachricht.value)
        window.document.Feedback.submit();
    } else {
        alert("Fehler: Folgende Felder muessen noch ausgefuellt werden:\n\n" + missing + "\n");
    }
}

/** Check if all fields in kontakt.xml are properly filled */
function KontaktFormularCheck()
{
    var missing="";
    if (window.document.Feedback.Name.value == "") {
        missing += "  * Name\n";
    }

    if (window.document.Feedback.Strasse.value == "") {
        missing += "  * Strasse\n";
    }
    
    if (window.document.Feedback.Telefon.value == "") {
        missing += "  * Telefon\n";
    }
    
    if (window.document.Feedback.email.value == "") {
        missing += "  * EMail\n";
    }
    
    if(window.document.Feedback.Ort.value == "") {
        missing += "  * Ort\n";
    }

    if(window.document.Feedback.Nachricht.value == "") {
        missing += "  * Nachricht\n";
    }

    if (missing == "") {
        window.document.Feedback.subject.value = "[hvrinfo] " + window.document.Feedback.subject.value
        window.document.Feedback.submit();
    } else {
        alert("Fehler: Folgende Felder muessen noch ausgefuellt werden:\n\n" + missing + "\n");
    }
}

function MitgliedschaftFormularCheck()
{
    var i;
    var error=0;
    
    for (i=0; i < window.document.Feedback.elements.length; ++i)
    { 
        if(window.document.Feedback.elements[i].value == "") {
            error = 1;
            break;
        }
    }
    if (error == 0) {
        window.document.Feedback.submit();
    } else {
        alert('Fehler: Alle Felder muessen ausgefuellt werden');
    }
}

function CheckCookie()
{
    SetCookie('cookietest', 'vorhanden');
    //document.writeln('cookietest: ' + GetCookie('cookietest') + '<br>');
    //document.writeln('warenkorb: '  + GetCookie('warenkorb')  + '<br>');

    if (GetCookie('cookietest') != 'vorhanden') {
        document.writeln("<p>Die Nutzung des Wahrenkorbs erfordert das Cookies eingeschaltet sind.</p>");    
    }
}

function CalculateMaxLength(str)
{
    var result = new Object();
    result.cols = 1;
    result.rows = 1;

    var col = 1;

    for (var i=0; i < str.length; ++i)
    {
        col += 1;
        if (str.charAt(i) == "\n")
        {
            result.cols = Math.max(result.cols, col);
            result.rows = result.rows + 1;
            col = 1;
        }
    }

    return result;
}

/* EOF */
