/*
    contact.js      2007-02-16  (c) e.sens.e GmbH
*/

function elementIsClass(e, className)
{
    if (e.className)
        return (e.className.search(
            new RegExp("\\b" + className + "\\b")) != -1);
    return false;
}

function elementAddClass(e, className)
{
    if (!elementIsClass(e, className))
        e.className += (" " + className);
}

function elementRemoveClass(e, className)
{
    e.className = e.className.replace(new RegExp("(\\b|\\s+)" + className +
        "(\\b|\\s+)"), "");
}

function elementGetChildNodesByClassName(e, className)
{
    var children = Array();
    for (i = 0; i < e.childNodes.length; i++)
        if (elementIsClass(e.childNodes[i], className))
            children[children.length] = e.childNodes[i];
    return children;
}

var INPUT_TEXT =        "text";
var INPUT_DROPDOWN =    "dropdown";
var INPUT_RADIO =       "radio";
var INPUT_CHECKBOX =    "checkbox";
var INPUT_SUBMIT =      "submit";
var FORMAT_EMAIL =      1;
//var FORMAT_PHONE =      2;

function ContactBox(id)
{
    this.idPrefix = "contactbox_";
    this.id = id;
    this.title = "";
    this.inputs = new Array();
    this.openedClassName = "opened";
    this.hiddenClassName = "hidden";
    this.getRowId = ContactBox_getRowId;
    this.getHTML = ContactBox_getHTML;
    this.getElement = ContactBox_getElement;
    this.init = ContactBox_init;
    this.open = ContactBox_open;
    this.close = ContactBox_close;
    this.isOpened = ContactBox_isOpened;
    this.show = ContactBox_show;
    this.hide = ContactBox_hide;
    this.isVisible = ContactBox_isVisible;
    this.setNumber = ContactBox_setNumber;
    this.setTitle = ContactBox_setTitle;
    this.showInput = ContactBox_showInput;
    this.hideInput = ContactBox_hideInput;
    this.isInputVisible = ContactBox_isInputVisible;
    this.setInputFocus = ContactBox_setInputFocus;
    this.setInputRequired = ContactBox_setInputRequired;
    this.getInputIndexByName = ContactBox_getInputIndexByName;
    this.getInputFieldIndexByValue = ContactBox_getInputFieldIndexByValue;
    this.isInputEmpty = ContactBox_isInputEmpty;
    this.isInputValid = ContactBox_isInputValid;
    this.checkRequired = ContactBox_checkRequired;
    this.getNext = ContactBox_getNext;
}

function ContactBox_getRowId(i, j)
{
    while (this.inputs[i].sameRow && (i > 0))
        i--;
    switch (this.inputs[i].type)
    {
        case INPUT_RADIO:
        case INPUT_CHECKBOX:
            return "row_" + this.inputs[i].name + "_" +
                ((ContactBox_getRowId.arguments.length > 1) ? j :
                (this.inputs[i].fields.length - 1));
        default:
            return "row_" + this.inputs[i].name;
    }
}

function ContactBox_getHTML()
{
    var i, j, html = "", s, islast;
    html += "<div class=\"contactbox " + this.hiddenClassName +
            "\" id=\"" + this.idPrefix + this.id + "\">\n";
    html += "<div class=\"head\" onclick=\"selectContactBox('" + this.id +
            "')\">\n";
    html += "<a href=\"javascript:selectContactBox('" + this.id + "')\">" +
            "<img src=\"../img/arrow_down.gif\" width=\"7\" height=\"7\"" +
            " alt=\"open\" title=\"open\" /></a>\n";
    html += "<div class=\"number\"></div>\n";
    html += "<div class=\"title\">" + this.title + "</div>\n";
    html += "</div>\n";
    html += "<div class=\"body\">\n";
    islast = false;
    for (i = 0; i < this.inputs.length; i++)
        switch (this.inputs[i].type)
        {
            case INPUT_TEXT:
                if (!this.inputs[i].sameRow)
                    html += "<div class=\"row\" id=\"row_" +
                            this.inputs[i].name + "\"" +
                            " onclick=\"setFocus(document." + contactFormName +
                            "." + this.inputs[i].name + ")\"" +
                            ">";
                if (this.inputs[i].title)
                    html += ("<span class=\"inputtitle" +
                            (this.inputs[i].required ? " required" : "") +
                            "\">" + this.inputs[i].title + "</span>");
                if (this.inputs[i].rows)
                {
                    html += "<textarea name=\"" + this.inputs[i].name + "\"";
                    if (this.inputs[i].size)
                        html += " cols=\"" + this.inputs[i].size + "\"";
                    html += " rows=\"" + this.inputs[i].rows + "\"";
                }
                else
                {
                    html += "<input type=\"text\" size=\"" +
                            (this.inputs[i].size ? this.inputs[i].size : 30) +
                            "\" name=\"" + this.inputs[i].name + "\"";
                    if (this.inputs[i].hint)
                        html += " value=\"" + this.inputs[i].hint + "\"";
                    if (this.inputs[i].maxLength)
                        html += " maxlength=\"" + this.inputs[i].maxLength +
                        "\"";
                }
                html += " onfocus=\"contactSetHint('" + this.id + "'," + i +
                        ",false);lastFocusName=this.name;contactFocusRow('" +
                        this.getRowId(i) + "')\"" +
                        " onblur=\"contactSetHint('" + this.id + "'," + i +
                        ",true);contactUpdateRequired('" + this.id + "'," + i +
                        ");lastFocusName='';contactBlurRow('" +
                        this.getRowId(i) + "')\"" +
                        " onclick=\"setFocusLock++\"" +
                        " />";
                if (this.inputs[i].rows)
                    html += "</textarea>\n";
                if (!(this.inputs[i + 1] && this.inputs[i + 1].sameRow))
                    html += "</div>\n";
                break;
            case INPUT_DROPDOWN:
                if (!this.inputs[i].sameRow)
                    html += "<div class=\"row\" id=\"row_" +
                            this.inputs[i].name + "\"" +
                            " onclick=\"setFocus(document." + contactFormName +
                            "." + this.inputs[i].name + ")\"" +
                            ">\n";
                if (this.inputs[i].title)
                    html += ("<span class=\"inputtitle" +
                            (this.inputs[i].required ? " required" : "") +
                            "\">" + this.inputs[i].title + "</span>");
                html += "<select name=\"" + this.inputs[i].name +
                        "\" size=\"1\"" +
                        " onfocus=\"lastFocusName=this.name;contactFocusRow('" +
                        this.getRowId(i) + "')\"" +
                        " onblur=\"contactUpdateRequired('" + this.id + "'," +
                        i + ");lastFocusName='';contactBlurRow('" +
                        this.getRowId(i) + "')\"" +
                        ">\n";
                for (j = 0; j < this.inputs[i].fields.length; j++)
                {
                    html += "<option";
                    html += " value=\"" + this.inputs[i].fields[j].value + "\"";
                    html += ">" + this.inputs[i].fields[j].text +
                            "</option>\n";
                }
                html += "</select>\n";
                if (!(this.inputs[i + 1] && this.inputs[i + 1].sameRow))
                    html += "</div>\n";
                break;
            case INPUT_RADIO:
                for (j = 0; j < this.inputs[i].fields.length; j++)
                {
                    html += "<div class=\"row\" id=\"row_" +
                            this.inputs[i].name + "_" + j + "\"" +
                            " onclick=\"document." + contactFormName + "." +
                            this.inputs[i].name +
                            "[" + j + "].checked=true\"" +
                            ">";
                    html += "<input class=\"radio\" type=\"radio\"" +
                            " name=\"" + this.inputs[i].name + "\"" +
                            " value=\"" +  this.inputs[i].fields[j].value +
                            "\"" +
                            " onfocus=\"lastFocusName=this.name\"" +
                            " onblur=\"lastFocusName=''\"" +
                            "/>" + this.inputs[i].fields[j].text;
                    if (!( (j == (this.inputs[i].fields.length - 1)) &&
                        this.inputs[i + 1] && this.inputs[i + 1].sameRow))
                        html += "</div>\n";
                }
                break;
            case INPUT_CHECKBOX:
                //TODO support for more than two columns
                if (this.inputs[i].columns > 1)
                    html += "<div class=\"col0\">\n";
                for (j = 0; j < this.inputs[i].fields.length; j++)
                {
                    html += "<div class=\"row\" id=\"row_" +
                            this.inputs[i].name + "_" + j + "\"" +
                            " onclick=\"toggleCheckbox(document." +
                            contactFormName + ".elements['" +
                            this.inputs[i].name + "']" +
                            ((this.inputs[i].fields.length > 1) ?
                            ("[" + j + "]") : "") + ")\">";
                    html += "<input class=\"checkbox\" type=\"checkbox\"" +
                            " name=\"" + this.inputs[i].name + "\" value=\"" + 
                            (this.inputs[i].fields[j].value ?
                            this.inputs[i].fields[j].value :
                            this.inputs[i].fields[j].text) + "\"" +
                            " onfocus=\"lastFocusName=this.name\"" +
                            " onblur=\"lastFocusName=''\"" +
                            " onclick=\"toggleCheckboxLock++\"" +
                            " />";
                    html += this.inputs[i].fields[j].text;
                    html += "</div>\n";
                    if ((this.inputs[i].columns > 1) && !((j + 1) %
                        Math.ceil(this.inputs[i].fields.length /
                        this.inputs[i].columns)))
                        html += "</div>\n<div class=\"col1\">\n";
                }
                if (this.inputs[i].columns > 1)
                    html += "</div>\n";
                break;
            case INPUT_SUBMIT:
                html += "<p class=\"next\">";
                html += "<input type=\"submit\" name=\"" +
                        this.inputs[i].name + "\" value=\"" +
                        this.inputs[i].value + "\"" +
                        " onfocus=\"lastFocusName=this.name\"" +
                        " onblur=\"lastFocusName=''\"" +
                        " />";
                html += "</p>\n";
                islast = true;
                break;
        }
    if (!islast)
        html += "<p class=\"next\"><a href=\"javascript:nextContactBox('" +
                this.id + "')\">Weiter...</a></p>\n";
    html += "</div>\n";
    html += "<div class=\"foot\"></div>\n";
    html += "</div>\n";
    return html;
}

function ContactBox_getElement()
{
    return document.getElementById(this.idPrefix + this.id);
}

function ContactBox_init()
{
    var i;
    for (i = 0; i < this.inputs.length; i++)
    {
        switch (this.inputs[i].type)
        {
            case INPUT_TEXT:
                elementRemoveClass(document.getElementById(this.getRowId(i)),
                    "alert");
                contactSetHint(this.id, i, false);
                this.inputs[i].hint = this.inputs[i].required ?
                    "(Bitte ausfüllen!)" : "";
                contactSetHint(this.id, i, true);
                break;
        }
    }
    return true;
}

function ContactBox_open()
{
    elementAddClass(this.getElement(), this.openedClassName);
}

function ContactBox_close()
{
    elementRemoveClass(this.getElement(), this.openedClassName);
}

function ContactBox_isOpened()
{
    return elementIsClass(this.getElement(), this.openedClassName);
}

function ContactBox_show()
{
    elementRemoveClass(this.getElement(), this.hiddenClassName);
}

function ContactBox_hide()
{
    elementAddClass(this.getElement(), this.hiddenClassName);
}

function ContactBox_isVisible()
{
    return !elementIsClass(this.getElement(), this.hiddenClassName);
}

function ContactBox_setNumber(number)
{
    elementGetChildNodesByClassName(
        elementGetChildNodesByClassName(this.getElement(), "head")[0],
        "number")[0].innerHTML = number;
}

function ContactBox_setTitle(title)
{
    elementGetChildNodesByClassName(
        elementGetChildNodesByClassName(this.getElement(), "head")[0],
        "title")[0].innerHTML = title;
}

function ContactBox_showInput(i, j)
{
    if (ContactBox_showInput.arguments.length > 1)
        elementRemoveClass(document.getElementById(this.getRowId(i, j)), "hidden");
    else
        elementRemoveClass(document.getElementById(this.getRowId(i)), "hidden");
}

function ContactBox_hideInput(i, j)
{
    if (ContactBox_hideInput.arguments.length > 1)
        elementAddClass(document.getElementById(this.getRowId(i, j)), "hidden");
    else
        elementAddClass(document.getElementById(this.getRowId(i)), "hidden");
}

function ContactBox_isInputVisible(i, j)
{
    if (ContactBox_isInputVisible.arguments.length > 1)
        return !elementIsClass(document.getElementById(this.getRowId(i, j)), "hidden");
    else
        return !elementIsClass(document.getElementById(this.getRowId(i)), "hidden");
}

function ContactBox_setInputFocus(i, f)
{
    var j, k, found = false;
    switch (ContactBox_setInputFocus.arguments.length)
    {
        case 0:
            for (j = 0; j < this.inputs.length; j++)
            {
                switch (this.inputs[j].type)
                {
                    case INPUT_RADIO:
                    case INPUT_CHECKBOX:
                        for (k = 0; k < this.inputs[j].fields.length; k++)
                            if (this.isInputVisible(j, k))
                            {
                                this.setInputFocus(j, k);
                                found = true;
                            }
                        break;
                    default:
                        if (this.isInputVisible(j))
                        {
                            this.setInputFocus(j);
                            found = true;
                        }
                }
                if (found)
                    break;
            }
            break;
        case 1:
            setFocus(document.forms[contactFormName].elements[this.inputs[i].name]);
            break;
        default:
            setFocus(document.forms[contactFormName].elements[this.inputs[i].name][f]);
    }
}

function ContactBox_setInputRequired(i, required)
{
    var e;
    this.inputs[i].required = required;
    switch (this.inputs[i].type)
    {
        case INPUT_TEXT:
            e = elementGetChildNodesByClassName(
                document.getElementById(this.getRowId(i)), "inputtitle")[0];
            if (required)
                elementAddClass(e, "required");
            else
                elementRemoveClass(e, "required");
            break;
    }
}

function ContactBox_getInputIndexByName(name)
{
    for (i = 0; i < this.inputs.length; i++)
        if (this.inputs[i].name == name)
            return i;
    return -1;
}

function ContactBox_getInputFieldIndexByValue(i, value)
{
    var j, e = document.forms[contactFormName].elements[this.inputs[i].name];
    for (j = 0; j < this.inputs[i].fields.length; j++)
        if (e[j].value == value)
            return j;
    return -1;
}

function ContactBox_isInputEmpty(i)
{
    var e = document.forms[contactFormName].elements[this.inputs[i].name];
    switch (this.inputs[i].type)
    {
        case INPUT_TEXT:
            return ((e.value == "") || (e.value == this.inputs[i].hint));
        case INPUT_DROPDOWN:
            return (getSelectValue(e) == "");
        case INPUT_RADIO:
            return (getRadioValue(e) == "");
    }
    return false;
}

function ContactBox_isInputValid(i)
{
    e = document.forms[contactFormName].elements[this.inputs[i].name];
    switch (this.inputs[i].checkFormat)
    {
        case FORMAT_EMAIL:
            return validEmail(e.value);
            break;
        //case FORMAT_PHONE:
        //    break;
    }
    return true;
}

function ContactBox_checkRequired()
{
    var i, e, invalid = Array(), msg = "";
    for (i = 0; i < this.inputs.length; i++)
    {
        e = document.forms[contactFormName].elements[this.inputs[i].name];
        if (this.inputs[i].required && this.isInputEmpty(i))
        {
            switch (this.inputs[i].type)
            {
                case INPUT_TEXT:
                case INPUT_DROPDOWN:
                    elementAddClass(document.getElementById("row_" + e.name),
                        "alert");
                    break;
            }
            if (!invalid.length)
                switch (this.inputs[i].type)
                {
                    case INPUT_RADIO:
                        msg = "Bitte wählen Sie eines der Felder aus!";
                        break;
                    default:
                        msg = "Bitte füllen Sie die fehlenden Felder aus!";
                }
            invalid[invalid.length] = i;
        }
        if (this.inputs[i].checkFormat && !this.isInputEmpty(i) &&
            !this.isInputValid(i))
        {
            elementAddClass(document.getElementById("row_" + e.name), "alert");
            if (!invalid.length)
                switch (this.inputs[i].checkFormat)
                {
                    case FORMAT_EMAIL:
                        msg = "Bitte geben Sie eine gültige E-Mail-Adresse an!";
                        break;
                    //case FORMAT_PHONE:
                    //    break;
                    default:
                        msg = "Bitte geben Sie einen gültigen Wert ein!";
                }
            invalid[invalid.length] = i;
        }
    }
    if (invalid.length)
    {
        alert(msg);
        this.setInputFocus(invalid[0]);
        return false;
    }
    return true;
}

function ContactBox_getNext()
{
    var i, j, e;
    if (this.defaultSetTitle)
        this.setTitle(this.defaultSetTitle);
    for (i = 0; i < this.inputs.length; i++)
        switch (this.inputs[i].type)
        {
            case INPUT_RADIO:
                e = document.getElementsByName(this.inputs[i].name);
                for (j = 0; j < e.length; j++)
                    if (e[j].checked)
                    {
                        if (this.inputs[i].fields[j].setTitle)
                            this.setTitle(this.inputs[i].fields[j].setTitle);
                        if (this.inputs[i].fields[j].nextBox)
                            return this.inputs[i].fields[j].nextBox;
                    }
                break;
        }
    return this.defaultNextBox;
}

function getContactBoxIndexById(id)
{
    var i;
    for (i = 0; i < contactForm.length; i++)
        if (contactForm[i].id == id)
            return i;
    return -1;
}

function getContactBoxById(id)
{
    var box;
    box = getContactBoxIndexById(id);
    if (box != -1)
        return (contactForm[box]);
    else
        return false;
}

function selectContactBox(id)
{
    var i, e, j;
    box = getContactBoxIndexById(id);
    if (box == -1)
    {
        alert("Error: unknown id (" + id + ")");
        return;
    }
    for (i = 0; i < contactForm.length; i++)
        if (i == box)
        {
            if (contactForm[i].init())
            {
                contactForm[i].setTitle(contactForm[i].title);
                contactForm[i].open();
                contactForm[i].show();
                contactForm[i].setInputFocus();
            }
            else
                break;
        }
        else
        {
            contactForm[i].close();
            if (i > box)
                contactForm[i].hide();
        }
    updateContactBoxNumbers();
}

function updateContactBoxNumbers()
{
    var i, n = 0;
    for (i = 0; i < contactForm.length; i++)
        if (contactForm[i].isVisible())
            contactForm[i].setNumber(++n);
}

function nextContactBox(id)
{
    box = getContactBoxById(id)
    if (box)
        if (box.checkRequired())
            selectContactBox(box.getNext());
}

function contactCheckSubmit()
{
    if (contactForm[contactForm.length - 1].isVisible())
        return contactForm[contactForm.length - 1].checkRequired();
    for (i = (contactForm.length - 1); i; i--)
        if (contactForm[i].isVisible())
        {
            nextContactBox(contactForm[i].id);
            break;
        }
    return false;
}

function contactFocusRow(id)
{
    elementAddClass(document.getElementById(id), "focused");
}

function contactBlurRow(id)
{
    elementRemoveClass(document.getElementById(id), "focused");
}

function contactUpdateRequired(id, i)
{
    var box = getContactBoxById(id);
    if (!((box.inputs[i].required && box.isInputEmpty(i)) ||
        (box.inputs[i].checkFormat && !box.isInputEmpty(i) &&
            !box.isInputValid(i))))
        elementRemoveClass(document.getElementById(box.getRowId(i)), "alert");
//FIXME fehler bei title2
}

function contactSetHint(id, i, bSet)
{
    var box, e, hint = "";
    box = getContactBoxById(id);
    e = document.forms[contactFormName].elements[box.inputs[i].name];
    if (box.inputs[i].hint)
        hint = box.inputs[i].hint;
    if (bSet)
    {
        if ((e.value == "") &&
            ((e.maxLength <= 0) || (e.maxLength >= hint.length)))
            e.value = hint;
    }
    else
    {
        if (e.value == hint)
            e.value = "";
    }
}

function contactInit()
{
    var i;
    for (i = 0; i < contactForm.length; i++)
        document.write(contactForm[i].getHTML());
    selectContactBox(contactForm[0].id);
}

function validEmail(email)
{
    //TESTME regexp ok?
    //var user = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
    var user = "[a-zA-Z0-9][a-zA-Z0-9_.-]*";
    var domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]+\\.[a-zA-Z]{2,}";
    var r = new RegExp("^" + user + "\@" + domain + "$");
    return r.exec(email);
}

function getSelectValue(e)
{
    var i;
    for (i = 0; i < e.options.length; i++)
        if (e.options[i].selected)
            return e.options[i].value /*? e.options[i].value : e.options[i].text*/;
    return "";
}

function getRadioValue(e)
{
    var i;
    for (i = 0; i < e.length; i++)
        if (e[i].checked)
            return e[i].value;
    return "";
}

var toggleCheckboxLock = 0;

function toggleCheckbox(e)
{
    if (toggleCheckboxLock > 0)
    {
        toggleCheckboxLock--;
        return;
    }
    e.checked = e.checked ? false : true;
}

var setFocusLock = 0;
var lastFocusName = "";

function setFocus(e)
{
    if (setFocusLock > 0)
    {
        setFocusLock--;
        return;
    }
    if (e.name != lastFocusName)
    {
        lastFocusName = e.name;
        e.focus();
    }
}

function decodeURL(str) { return unescape(str.replace(/\+/g, "%20")); }

function getQuery()
{
    var query, pairs, ret, i, pair;
    ret = new Object();
    pos = document.URL.indexOf("?");
    if (pos != -1 || (defaultQuery))
    {
        if (pos != -1)
            query = document.URL.substr(pos + 1);
        else
            query = defaultQuery;
        pairs = query.split("&");
        for (i = 0; i < pairs.length; i++)
            if (pairs[i])
            {
                pair = pairs[i].split("=", 2);
                ret[decodeURL(pair[0])] = decodeURL(pair[1]);
            }
    }
    return ret;
}

function contactSetDefaults()
{
    var i, j, e, f, box;
    for (i = 0; i < contactForm.length; i++)
        for (j = 0; j < contactForm[i].inputs.length; j++)
        {
            if (GET[contactForm[i].inputs[j].name])
            {
                e = document.forms[contactFormName].elements[contactForm[i].
                    inputs[j].name];
                switch (contactForm[i].inputs[j].type)
                {
                    case INPUT_TEXT:
                        e.value = GET[contactForm[i].inputs[j].name];
                        break;
                    case INPUT_DROPDOWN:
                        //TODO
                        break;
                    case INPUT_CHECKBOX:
                        if (!e.length)
                        {
                            e.checked = true;
                            break;
                        }
                    case INPUT_RADIO:
                        for (f = 0; f < contactForm[i].inputs[j].fields.length;
                            f++)
                            if (e[f].value == GET[contactForm[i].inputs[j].name])
                            {
                                e[f].checked = true;
                                if (contactForm[i].inputs[j].fields[f].setTitle)
                                    contactForm[i].setTitle(contactForm[i].
                                        inputs[j].fields[f].setTitle);
                                break;
                            }
                        break;
                }
            }
            if (GET[contactForm[i].inputs[j].name + "_settitle"])
                contactForm[i].defaultSetTitle =
                    GET[contactForm[i].inputs[j].name + "_settitle"];
        }
    if (GET["contactbox"])
        for (box = contactForm[0]; box; box = getContactBoxById(box.getNext()))
        {
            selectContactBox(box.id);
            if (box.id == GET["contactbox"])
                break;
        }
}
