var requests = [];

/**
 * Constants.
 */
var ELEMENT_NODE                = 1;
var ATTRIBUTE_NODE              = 2;
var TEXT_NODE                   = 3;
var CDATA_SECTION_NODE          = 4;
var ENTITY_REFERENCE_NODE       = 5;
var ENTITY_NODE                 = 6;
var PROCESSING_INSTRUCTION_NODE = 7;
var COMMENT_NODE                = 8;
var DOCUMENT_NODE               = 9;
var DOCUMENT_TYPE_NODE          = 10;
var DOCUMENT_FRAGMENT_NODE      = 11;
var NOTATION_NODE               = 12;

/**
 * Array methods.
 */
// IE<6 check
if (!Array.prototype.push)
{
    Array.prototype.push = function()
    {
        var thisLen = this.length;
        var argLen  = arguments.length;
        for(var i=0; i<argLen; i++)
        {
            this[thisLen+i] = arguments[i];
        }
        return this.length;
    };
}

Array.prototype.indexOf = function(needle)
    {
        var thisLen = this.length;
        for (var i=0; i<thisLen; i++)
        {
            if (this[i] == needle)
            {
                return i;
            }
        }
        return -1;
    };

Array.prototype.insert = function(item, before)
    {
        if (before && before < 0)
        {
            before += this.length;
        }

        if (!before || before >= this.length)
        {
            this.push(item);
        }
        else if (before === 0)
        {
            this.unshift(item);
        }
        else if (before > 0)
        {
            var tmp = this.slice(before); // copy the remainder of the items
            this.splice(before, tmp.length); // remove them from `this`
            this.push(item);
            for (var i=0; i<tmp.length; i++)
            {
                this.push(tmp[i]);
            }
        }
        else // if (before < 0)
        {
            return null;
        }
    };

/**
 * Utility functions.
 */

function copyXml(src, dst)
{
    if (!src || !dst)
    {
        return;
    }

    var node = null;

    switch (src.nodeType)
    {
    case ELEMENT_NODE: //xml element
        // Create the node
        //var node = document.createElement(src.childNodes[elem].nodeName);
        node = document.createElement(src.nodeName);
        // Copy the attributes
        //for (var attrIndex=0; attrIndex<src.childNodes[elem].attributes.length; attrIndex++)
        for (var attrIndex=0; attrIndex<src.attributes.length; attrIndex++)
        {
            //var attr = src.childNodes[elem].attributes[attrIndex];
            var attr = src.attributes[attrIndex];
            if (attr.name.substring(0, 2).toLowerCase() == "on" && node.attachEvent)
            {
                var fncBody = attr.value.replace("javascript:", "");
                fncBody = fncBody.replace("return", "");
                node.attachEvent(attr.name.toLowerCase(), function(){eval(fncBody);});
                //node.setAttribute(attr.name.toLowerCase(), fncBody);
            }
            else
            {
                node.setAttribute(attr.name, attr.value);
            }
        }
        // Check for any children to be copied
        for (var elem=0; elem<src.childNodes.length; elem++)
        {
            copyXml(src.childNodes[elem], node);
        }
        break;
    case TEXT_NODE: //text element
        var value = src.nodeValue;
        value = value.replace(/[\t\n ]*/, "");
        if (value !== "")
        {
            node = document.createTextNode(src.nodeValue);
        }
        break;
    case PROCESSING_INSTRUCTION_NODE: // <?xml ... ?>
        break; // do nothing
    default:
        //alert("No handler defined for this type of data: " + src.childNodes[elem].nodeType + "\n" + src.childNodes[elem].nodeValue);
        window.alert("No handler defined for this type of data: " + src.nodeType + "\n" + src.nodeValue);
        break;
    }

    // Add it to the tree
    if (node)
    {
        dst.appendChild(node);
    }
    return node;
}

function removeAllChilds(node)
{
    while (node.childNodes.length > 0)
    {
        node.removeChild(node.firstChild);
    }
}

/**
 * Page population functions.
 */
function default_content(elem, text)
{
    if (typeof(text) == "object")
    {
        removeAllChilds(elem);
        var doc = 0;
        while (text.childNodes[doc].nodeType != ELEMENT_NODE) 
        {
            doc++;
        }
        for (var i=0; i<text.childNodes[doc].childNodes.length; i++)
        {
            copyXml(text.childNodes[doc].childNodes[i], elem);
        }
    }
    else
    {
        elem.innerHTML = text;
    }
}

function populate_complete(text)
{
    if (requests.length > 0)
    {
        var obj = requests.shift();
        if (typeof(obj.callback) == "function")
        {
            obj.callback(obj.element, text);
        }
        else
        {
            default_content(obj.element, text);
        }
    }
    else
    {
        // raise an error here
        window.alert("Got a response for a request that I didn't make!");
    }

    if (requests.length > 0)
    {
        sendRequest(requests[0].source);
    }
}

function populate_error(text)
{
    var obj  = requests.shift();
    var elem = obj.element;

    removeAllChilds(elem);
    
    var err  = document.createElement("DIV");
    err.setAttribute("class", "error");
    err.appendChild( document.createTextNode(text) );
    elem.appendChild(err);
    //var img = elem.getElementsByTagName("IMG")[0];
    //img.parentNode.replaceChild(err, img);

    err = document.createElement("A");
    err.setAttribute("href", obj.source);
    err.appendChild( document.createTextNode("details") );
    elem.appendChild(err);

    if (requests.length > 0)
    {
        sendRequest(requests[0].source);
    }
}

function populate(elem, url, callback)
{
    removeAllChilds(elem);

    if (elem.nodeName == "DIV")
    {
        var div = document.createElement("DIV");
        div.setAttribute("class", "progressIndicator");
        var img = document.createElement("IMG");
        img.setAttribute("src", "script/images/loading.gif");
        div.appendChild(document.createTextNode("Fetching content..."));
        div.appendChild(document.createElement("br"));
        div.appendChild(img);
        elem.appendChild(div); 
    } 
    else if (elem.nodeName == "SELECT")
    {
        var option = document.createElement("OPTION");
        option.selected = true;
        option.setAttribute("class", "progressIndicator");
        option.appendChild( document.createTextNode("Fetching content...") );
        elem.appendChild(option);
        elem.selectedIndex = 0;
    }
    if (elem.nodeName == "TR")
    {
        var td = document.createElement("TD");
        td.setAttribute("colspan", "99");
        td.setAttribute("class", "progressIndicator");
        img = document.createElement("IMG");
        img.setAttribute("src", "script/images/loading.gif");
        td.appendChild(document.createTextNode("Fetching content..."));
        td.appendChild(document.createElement("br"));
        td.appendChild(img);
        elem.appendChild(td);
    } 

    var o = {element:  elem,
             source:   url,
             callback: callback};
    requests.push(o);
    onComplete = populate_complete;
    onError    = populate_error;
    if (requests.length == 1)
    {
        sendRequest(url);
    }
}

function requestIndexOf(url)
{
    for (var i=0; i<requests.length; i++)
    {
        var o = requests[i];
        if (o.source == url) 
        {
            return i;
        }
    }
    return -1;
}

function cancelRequest(urlOrIndex)
{
    var i;
    if (typeof urlOrIndex == "string")
    {
        i = requestIndexOf(urlOrIndex);
    }
    else if (typeof urlOrIndex == "number")
    {
        i = urlOrIndex;
    }
    if (i < requests.length)
    {
        requests.splice(i, 1);
    }
}

/**
 * Dialog functions.
 */
function show_dialog(url, title, toolwin, callback)
{
    if (typeof(title) == "undefined") 
    { 
        title = "thewindow"; 
    }
    if (typeof(toolwin) == "undefined") 
    { 
        toolwin = true; 
    }
    if (typeof(callback) == "undefined")
    {
        callback = null;
    }

    var dlg  = document.getElementById("dialogContent");
    var mdlg = document.getElementById("modalDialog");

    document.getElementById("overlay").style.display = "block";
    mdlg.style.display = "block";

    var src = "index.asp";
    switch (url)
    {
    case "print_options":
    case "help":
    case "load":
        src += "?part=" + url;
        mdlg.className = url;
        break;
    default:
        if (toolwin) 
        {
            mdlg.className = "toolwin";
        }
        break;
    }
    /*if (url == "print_options" || url == "help" || url == "load")
    {
        src += "?part=" + url;
    }
    switch (url)
    {
    case "print_options":
        mdlg.style.width  = "495px";
        mdlg.style.margin = "auto -247px";
        break;
    case "help":
        mdlg.style.width   = "725px";
        mdlg.style.margin  = "auto -362px";
        dlg.style.overflow = "auto";
        break;
    case "load":
        mdlg.style.width  = "379px";
        mdlg.style.height = "330px";
        mdlg.style.margin = "auto -190px";
        break;
    default:
        mdlg.style.width  = (toolwin ? "725" : "379") + "px";
        mdlg.style.height = (toolwin ? "580" : "330") + "px";
        mdlg.style.margin = "auto -" + (toolwin ? "362" : "290") + "px";
        break;
    }*/
    populate(dlg, src, callback);
}

function closeDialog(dlg, event)
{
    document.getElementById("overlay").style.display = "none";
    document.getElementById("modalDialog").style.display = "none";

    //if (typeof(dlg) == "undefined")
    //{
        dlg = document.getElementById("dialogContent");
    //}
    removeAllChilds(dlg);
    if (dlg.detachEvent)
    {
        dlg.detachEvent("onclick", closeDialog);
    }
    else
    {
        dlg.setAttribute("onclick", "");
        dlg.setAttribute("onclick", null);
        dlg.removeAttribute("onclick");
    }
    dlg.style.width  = "";
    dlg.style.height = "";
    dlg.style.overflow = "";

    return false;
}


/**
 * Code handling routines
 */
function get_current_code_div_ids()
{
    var result = [];
    var codes_div = document.getElementById("code_list");
    var divs = codes_div.getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
    for (var div=0; div<divs.length; div++)
    {
        var id = divs[div].id;
        if (id && id !== "" && id.substr(0, 5) != "code_")
        {
            result.push(id);
        }
    }
    return result;
}

function parse_code_label(div, xml)
{
    removeAllChilds(div);

    var show_title            = (getMultiValue("opticonfigure", "chapter",     "") !== "");
    var show_description      = true; //(getMultiValue("opticonfigure", "showtext",    "") !== "");
    var show_codes            = true; // TODO: mix with the bar code style for 2D config labels
    var show_serial           = (getMultiValue("opticonfigure", "serial",      "") !== "");
    var show_software_version = (getMultiValue("opticonfigure", "softversion", "") !== "");
    var show_delete           = true; // show always
    
    if (show_title || show_description) 
    {
        var divTexts = document.createElement("TD");
        divTexts.setAttribute("class", "descriptions");
        if (show_title) 
        {
            var divTitle = document.createElement("DIV");
            divTitle.setAttribute("class", "title");
            if ((xml.getElementsByTagName("title").length > 0) &&
                (xml.getElementsByTagName("title")[0].childNodes.length > 0))
            {
                divTitle.appendChild(document.createTextNode(xml.getElementsByTagName("title")[0].childNodes[0].nodeValue));
            }
            divTexts.appendChild(divTitle);
        }
        if (show_description) 
        {
            var divDescription = document.createElement("DIV");
            divDescription.setAttribute("class", "description");
            if ((xml.getElementsByTagName("description").length > 0) &&
                (xml.getElementsByTagName("description")[0].childNodes.length > 0))
            {
                divDescription.appendChild(document.createTextNode(xml.getElementsByTagName("description")[0].childNodes[0].nodeValue));
            }
            divTexts.appendChild(divDescription);
        }
        div.appendChild(divTexts);
    }

    if (show_codes) 
    {
        var divCode = document.createElement("TD");
        divCode.setAttribute("class", "code");
        var imgCode = document.createElement("IMG");
        if ((xml.getElementsByTagName("code").length > 0) &&
            (xml.getElementsByTagName("code")[0].childNodes.length > 0))
        {
            imgCode.setAttribute("title", xml.getElementsByTagName("code")[0].childNodes[0].nodeValue);
            var value = xml.getElementsByTagName("code")[0].childNodes[0].nodeValue;
            while (value != value.replace("+", "%2b"))
            {
                value = value.replace("+", "%2b");
            }
            imgCode.setAttribute("src", "/image.asp?data="+value);
        }
        divCode.appendChild(imgCode);
        div.appendChild(divCode);
        // TODO:
        // Insert a div with "Please wait one second" between this and the previous, if
        //  the ?data=value is the same for the previous entry and this one, and
        //   there are C39 labels used
        var divs = div.parentNode.getElementsByTagName("TR");
        for (var i = 0; i<divs.length; i++)
        {
            if (div == divs[i])
            {
                break;
            }
        }
        var iDiv = 1;
        //if (show_software_version) { iDiv++; }
        //if (show_serial) { iDiv++; }
        if (i > 1) // skip if this is the first DIV in the list
        {
            var otherImg = divs[i-iDiv].getElementsByTagName("IMG")[0]; // get the only image of the previous div
            if (otherImg && (imgCode.getAttribute("src") == otherImg.getAttribute("src")))
            {
                var divWait = document.createElement("TR");
                divWait.className = "please_wait";
                divWaitCell = document.createElement("TD");
                divWaitCell.setAttribute("colspan", "99");
                divWait.appendChild(divWaitCell);
                div.parentNode.insertBefore(divWait, div);
                div.parentNode.insertBefore(document.createTextNode("\n"), div);
                populate(divWaitCell, "index.asp?part=please_wait");
            }
        }
    }

    if (show_serial)
    {
        var divSerial = document.createElement("TD");
        divSerial.setAttribute("class", "serial");
        if ((xml.getElementsByTagName("code").length > 0) &&
            (xml.getElementsByTagName("code")[0].childNodes.length > 0))
        {
            divSerial.appendChild(document.createTextNode(xml.getElementsByTagName("code")[0].childNodes[0].nodeValue));
        }
        div.appendChild(divSerial);
    }
    
    if (show_software_version) 
    {
        var divSoftware = document.createElement("TD");
        if ((xml.getElementsByTagName("software").length > 0) &&
            (xml.getElementsByTagName("software")[0].childNodes.length > 0))
        {
            divSoftware.appendChild(document.createTextNode(xml.getElementsByTagName("software")[0].childNodes[0].nodeValue));
        }
        div.appendChild(divSoftware);
    }

    var isDefault = xml.getElementsByTagName("default");
    if (isDefault.length > 0) 
    {
        isDefault = isDefault[0];
        if (isDefault.childNodes.length > 0)
        {
            isDefault = isDefault.childNodes[0].nodeValue.substring(0, 1);
            isDefault = (isDefault == "y" || isDefault == "t" || isDefault == "1");
        }
        else
        {
            isDefault = true;
        }
    }
    else
    {
        isDefault = false;
    }
    if (isDefault)
    {
        div.setAttribute("class", div.getAttribute("class") + " default");
    }

    if (show_delete) // warning: contant expression
    {
        var divControl = document.createElement("TD");
        divControl.setAttribute("class", "control");
        var inpDelete   = document.createElement("INPUT");
        inpDelete.setAttribute("name",  "Delete");
        inpDelete.setAttribute("type",  "Checkbox");
        inpDelete.setAttribute("id",    "chkbx_"+div.getAttribute("id"));
        inpDelete.setAttribute("value", div.getAttribute("id"));
        divControl.appendChild(inpDelete);
        div.appendChild(divControl);
    }
}

function parse_setend_label(div, xml)
{
    removeAllChilds(div);

    var imgCode = document.createElement("IMG");
    if ((xml.getElementsByTagName("code").length > 0) &&
        (xml.getElementsByTagName("code")[0].childNodes.length > 0))
    {
        var value = xml.getElementsByTagName("code")[0].childNodes[0].nodeValue;
        while (value != value.replace("+", "%2b"))
        {
            value = value.replace("+", "%2b");
        }
        imgCode.setAttribute("src", "/image.asp?data="+value);
    }
    div.appendChild(imgCode);
}

function confirmDelete(elem, event) 
{
    var selected = getCheckedCodes();

    if (selected.length == 0)
    {
        return;
    }

    var msg = (selected.length == 1) ?
              "Are you sure you want to delete this option?" :
              "Are you sure you want to delete these options?";

    if (window.confirm(msg)) 
    {
        var url = "index.asp?part=delete_code";
        for (var i=0; i<selected.length; i++)
        {
            url += "&" + selected[i].name + "=" + selected[i].value;
        }
        var o = {element:  document.getElementById("codesContent"),
                 source:   url,
                 callback: refresh_code};
        requests.push(o);
        onComplete = populate_complete;
        onError    = populate_error;

        document.getElementById("btnSelectAll").checked = false;

        return form_onsubmit(document.getElementById("codesContent"), event, url);
    }
}

function selectAllCodes(select)
{
    var inputs = document.getElementById("codesContent").getElementsByTagName("INPUT");
    for (var i=0; i<inputs.length; i++)
    {
        if (inputs[i].type == "checkbox")
        {
            inputs[i].checked = select;
        }
    }
}

function create_options_header()
{
    var res = document.createElement("TR");
    res.setAttribute("id", "code_header");
    var show_title            = (getMultiValue("opticonfigure", "chapter",     "") !== "");
    var show_description      = true; //(getMultiValue("opticonfigure", "showtext",    "") !== "");
    var show_codes            = true; // TODO: mix with the bar code style for 2D config labels
    var show_serial           = (getMultiValue("opticonfigure", "serial",      "") !== "");
    var show_software_version = (getMultiValue("opticonfigure", "softversion", "") !== "");
    var show_delete           = true;
    if (show_title || show_description)
    {
        var divDescr = document.createElement("TH");
        divDescr.setAttribute("class", "descriptions");
        divDescr.appendChild( document.createTextNode("Description") );
        res.appendChild(divDescr);
    }
    if (show_codes)
    {
        var divCode = document.createElement("TH");
        divCode.setAttribute("class", "code");
        divCode.appendChild( document.createTextNode("Barcode") );
        res.appendChild(divCode);
    }
    if (show_serial)
    {
        var divSerial = document.createElement("TH");
        divSerial.setAttribute("class", "serial");
        divSerial.appendChild( document.createTextNode("Serial") );
        res.appendChild(divSerial);
    }
    if (show_software_version)
    {
        var divSoftware = document.createElement("TH");
        divSoftware.setAttribute("class", "software");
        divSoftware.appendChild( document.createTextNode("Software") );
        res.appendChild(divSoftware);
    }
    if (show_delete)
    {
        var divControl = document.createElement("TH");
        divControl.setAttribute("class", "control");
        var inpDeleteBtn = document.createElement("BUTTON");
        //inpDeleteBtn.setAttribute("type",    "submit");
        //inpDeleteBtn.setAttribute("id",      "btnDelete");
        //inpDeleteBtn.setAttribute("name",    "btnDelete");
        //inpDeleteBtn.setAttribute("value",   "Delete");
        inpDeleteBtn.appendChild( document.createTextNode("Delete") );
        if (inpDeleteBtn.attachEvent)
        {
            inpDeleteBtn.attachEvent("onclick", confirmDelete);
        }
        else
        {
            inpDeleteBtn.setAttribute("onclick", "javascript:return confirmDelete(this, event);");
        }
        divControl.appendChild(inpDeleteBtn);
        var inpDelete = document.createElement("INPUT");
        inpDelete.setAttribute("type", "checkbox");
        inpDelete.setAttribute("name", "SelectAll");
        inpDelete.setAttribute("id",   "btnSelectAll");
        if (inpDelete.attachEvent)
        {
            inpDelete.attachEvent("onclick", function(event){return selectAllCodes(event.srcElement.checked);});
        }
        else
        {
            inpDelete.setAttribute("onclick", "javascript:return selectAllCodes(this.checked)");
        }
        divControl.appendChild(inpDelete);
        res.appendChild(divControl);
    }

    var head = document.createElement("THEAD");
    head.appendChild( document.createTextNode("\n") );
    head.appendChild(res);
    return head;
}

function show_print_preview()
{
    /*var url = window.location.href;
    if (url.lastIndexOf("?") > 0)
    {
        url = url.substr(0, url.lastIndexOf("?"));
    }
    if (url.lastIndexOf("#") > 0)
    {
        url = url.substr(0, url.lastIndexOf("#"));
    }*/
    var url = "/print.asp";
    window.open(url + "?skin=" + skin + "&view=print");
}

function create_options_footer()
{
    var res = document.createElement("TH");
    res.setAttribute("colspan", "99");

    var btnPrintPreview = document.createElement("BUTTON");
    btnPrintPreview.appendChild( document.createTextNode("Print Preview") );
    if (btnPrintPreview.attachEvent)
    {
        btnPrintPreview.attachEvent("onclick", show_print_preview);
    }
    else
    {
        btnPrintPreview.setAttribute("onclick", "javascript:return show_print_preview(event);");
    }
    res.appendChild(btnPrintPreview);

    /* var btnSaveCodes = document.createElement("BUTTON");
     */

    var foot = document.createElement("TFOOT");
    foot.appendChild( document.createTextNode("\n") );
    var row = document.createElement("TR");
    row.setAttribute("id", "code_footer");
    row.appendChild( document.createTextNode("\n") );
    row.appendChild( res );
    foot.appendChild(row);
    return foot;
}

function create_setend_label(labelText)
{
    var div;
    var show_serial = (getMultiValue("opticonfigure", "serial", "") !== "");
    
    div = document.createElement("TR");
    div.setAttribute("id", "code_" + labelText);
    div.className = "code_label";
    
    var divDescrs = document.createElement("TD");
    divDescrs.className = "descriptions";
    var divDescr = document.createElement("DIV");
    divDescr.className = "description";
    divDescr.appendChild( document.createTextNode(labelText) );
    divDescrs.appendChild(divDescr);
    div.appendChild(divDescrs);
    
    var divCode = document.createElement("TD");
    divCode.className = "code";
    if (show_serial)
    {
        divCode.setAttribute("colspan", "2");
    }
    div.appendChild(divCode);

    div.appendChild(document.createTextNode("\n"));

    populate(divCode, "index.asp?part=setend_label", parse_setend_label);

    return div;
}

function refresh_code(code_div)
{
    //debugger;
    var cookie = getCookie("cookie");

    if (typeof cookie == "string" && cookie !== "" && cookie !== ";")
    {
        cookie = decodeURIComponent(cookie);
        if (cookie.substring(cookie.length-1, 1) == ";")
        {
            cookie = cookie.substring(0, cookie.length-1); // remove the trailing ;
        }
        var codes_div = document.getElementById("code_list");
        if (codes_div === null)
        {
            // Create the list holder
            codes_div = document.createElement("TABLE");
            codes_div.setAttribute("id", "code_list");
            codes_div.appendChild(document.createTextNode("\n"));
            code_div.appendChild(codes_div);

            // Create the header
            var divHeader = create_options_header();
            codes_div.appendChild(divHeader);

            var divFooter = create_options_footer();
            codes_div.appendChild(divFooter);

            var tbody = document.createElement("TBODY");
            codes_div.appendChild(tbody);

            var divSetLabel = create_setend_label("SET");
            tbody.appendChild(divSetLabel);

            var divEndLabel = create_setend_label("END");
            tbody.appendChild(divEndLabel);
        }
        else
        {   // make sure that the delete button is enabled
            enable_submits(code_div, true);
        }
        codes_div = codes_div.getElementsByTagName("TBODY")[0];
        var crumbles    = cookie.split(";");
        var current_div = 0;

        // check if there are divs in 'code_list' that are removed from the 'crumbles'
        var ids = get_current_code_div_ids();
        for (var id=0; id<ids.length; id++)
        {
            if (crumbles.indexOf(ids[id]) == -1) // id not in crumbles
            {
                var removeDiv = document.getElementById(ids[id]);
                codes_div.removeChild(removeDiv);
            }
        }
        
        // Process the cookie
        for (var crumble=0; crumble<crumbles.length; crumble++)
        {
            if (crumbles[crumble] !== "") // is there an option to show?
            {
                var elem = document.getElementById(crumbles[crumble]);
                var divs = get_current_code_div_ids();

                if (elem) // does the option already exist?
                {
                    // Possible bug in DataWizard. When two DirectInput characters are present as an
                    //  argument, they end up with the same ID.
                    if (crumbles[crumble-1] == crumbles[crumble])
                    {
                        elem = document.createElement("TR");
                        elem.setAttribute("id", crumbles[crumble] + "-1");
                        elem.setAttribute("class", "code_label");
                    }
                    else
                    {
                        // check if the 'crumble' is at the same position as the div in the 'code_list'
                        var div = document.getElementById(divs[current_div]);
                        if (div != elem)
                        {
                            // TODO
                            //debugger;
                        }
                    }
                    current_div++;
                }
                else
                {
                    // insert it at the right position in 'code_list'
                    elem = document.createElement("TR");
                    elem.setAttribute("id", crumbles[crumble]);
                    elem.setAttribute("class", "code_label");

                    var position = document.getElementById("code_END"); // set to append
                    if (divs.length > 0)
                    {
                        if (divs.length > crumble)
                        {
                            position = document.getElementById(divs[current_div++]); // in front of this one
                        }
                    }
                    codes_div.insertBefore(elem, position);
                    codes_div.insertBefore(document.createTextNode("\n"), position);
                    populate(elem, "index.asp?part=code_label&id=" + crumbles[crumble], parse_code_label);
                }
            }
        }
    }
    else
    {
        removeAllChilds(code_div);
    }
    // update the menu
    updateMenu();
}

function getCheckedCodes()
{
    var res    = [];
    var inputs = document.getElementById("codesContent").getElementsByTagName("INPUT");
    for (var i=0; i<inputs.length; i++)
    {
        if (inputs[i].type == "checkbox" && inputs[i].name != "SelectAll")
        {
            if (inputs[i].checked)
            {
                res.push(inputs[i]);
            }
        }
    }
    return res;
}


/**
 * Options handling routines 
 */

function label_clicked(event)
{
    var evt     = event ? event : window.event;
    var target  = evt.srcElement ? evt.srcElement : evt.target;
    var forId   = target.getAttribute("for");
    var forElem = forId == "" ? null : document.getElementById(forId);
    if (forElem)
    {
        forElem.click();
    }
}

function copyOptionsFromXml(xml, elem)
{
    var child;
    
    if (!xml || !elem)
    {
        return;
    }

    if (xml.nodeName)
    {
        switch (xml.nodeName.toLowerCase())
        {
        case 'options':
            if ((xml.getElementsByTagName("option").length > 0) ||
                (xml.getElementsByTagName("Select").length > 0))
            {
                var form = document.createElement("FORM");
                form.setAttribute("id", "formOptions");
                if (form.attachEvent)
                {
                    form.attachEvent("onsubmit", options_onsubmit);
                }
                else
                {
                    form.setAttribute("onsubmit", "javascript:return options_onsubmit(this, event);");
                }
                elem.appendChild(form);
                copyOptionsFromXml(xml.childNodes, form);
                var smt = document.createElement("INPUT");
                smt.setAttribute("type",  "submit");
                smt.setAttribute("value", "Add option(s)");
                form.appendChild(smt);
            }
            else
            {
                copyOptionsFromXml(xml.childNodes, elem);
            }
            return; // the childNodes are processed already
        case 'title':
            child = document.createElement("H1");
            child.appendChild( document.createTextNode(xml.childNodes[0].nodeValue) );
            elem.appendChild( child );
            return; // there are no childNodes
        case 'p':
            child = document.createElement("P");
            child.appendChild( document.createTextNode(xml.childNodes[0].nodeValue) );
            elem.appendChild( child );
            return;
        case 'form':
        case 'table':
        case 'tr':
        case 'td':
            copyOptionsFromXml(xml.childNodes, elem);
            return;
        case 'group':
            var d = document.createElement("DIV");
            d.className = "optiongroup";
            elem.appendChild(d);
            copyOptionsFromXml(xml.childNodes, d);
            return; // the childNodes are processed already
        case 'option':
            var div = document.createElement("DIV");
            var lbl = document.createElement("LABEL");
            var v   = xml.getElementsByTagName("value")[0].childNodes[0].nodeValue;
            var t   = xml.getElementsByTagName("type")[0].childNodes[0].nodeValue;
            var n   = xml.getElementsByTagName("name")[0].childNodes[0].nodeValue;
            var isD = xml.getElementsByTagName("default").length > 0;
            var isC = xml.getElementsByTagName("checked").length > 0;
            var optId = t + "_" + v;
            var inp;
            if (isD) { div.className = "bold"; }
            if (navigator.userAgent.indexOf("MSIE") >= 0)
            {
               inp = document.createElement("<INPUT " + 
                       "type='"  + t + "' " +
                       "name='"  + n + "' " +
                       "value='" + v + "' " +
                       "id='"    + optId + "'" + 
                       (isC ? " checked='true'" : "") +
                       ">");
            }
            else
            {
                inp = document.createElement("INPUT");
                inp.setAttribute("id",    optId);
                inp.setAttribute("value", v);
                inp.setAttribute("name",  n);
                inp.setAttribute("type",  t);
                if (isC) { inp.setAttribute("checked", true); }
            }
            lbl.appendChild( document.createTextNode(xml.getElementsByTagName("description")[0].childNodes[0].nodeValue) );
            lbl.setAttribute("for", optId);
            if (navigator.userAgent.indexOf("MSIE") > 0)
            {   // make the labels clickable in IE
                if (lbl.attachEvent)
                {
                    lbl.attachEvent("onclick", label_clicked);
                }
                else
                {
                    lbl.setAttribute("onclick", "javascript:return label_clicked(event)");
                }
            }
            div.appendChild(inp);
            div.appendChild(lbl);
            if (xml.getElementsByTagName("information").length > 0)
            {
                var img = document.createElement("IMG");
                img.setAttribute("src",   "skins/" + skin + "/images/info.png");
                img.setAttribute("alt",   "info");
                img.setAttribute("title", "info");
                if (img.attachEvent)
                {
                    img.attachEvent("onmouseover", show_option_info);
                }
                else
                {
                    img.setAttribute("onmouseover", "javascript:return show_option_info(event);");
                }
                div.appendChild(img);
            }
            elem.appendChild(div);
            return; // the childNodes are processed
        case 'select':
            copyXml(xml, elem);
            elem.appendChild( document.createElement("BR") );
            elem.appendChild( document.createTextNode("\n") );
            return; // the childNodes are processed
        case 'input':
            if (xml.getAttribute('Type').toLowerCase() == 'hidden')
            {
                if (navigator.userAgent.indexOf("MSIE") >= 0)
                {
                    n = xml.getAttribute('Name');
                    v = xml.getAttribute('Value');
                    inp = document.createElement("<INPUT " + 
                       "type='hidden' " +
                       "name='"  + n + "' " +
                       "value='" + v + "'" +
                       ">");
                    elem.appendChild(inp);
                }
                else
                {
                    copyXml(xml, elem);
                }
            }
            break;
        default:
            break;
        }
    }
    
    if (xml.nodeType != TEXT_NODE && xml.length)
    {
        for (child=0; child<xml.length; child++)
        {
            copyOptionsFromXml(xml[child], elem);
        }
        return;
    }
}
        
function parse_options(options_div, text)
{
    removeAllChilds(options_div);

    if (typeof(text) == "string")
    {
        return;
    }

    if (text.getElementsByTagName("options").length > 0)
    {
        copyOptionsFromXml(text.getElementsByTagName("options"), options_div);
    }
    else if (text.getElementsByTagName("parsererror").length > 0)
    {
        handle_parsererror(text.getElementsByTagName("parsererror")[0], options_div);
    }
    else
    {
        copyXml(text.childNodes[0], options_div);
    }
    
/*
    options_div.innerHTML = text;
    
    var forms = options_div.getElementsByTagName("FORM");
    if (forms.length > 0)
    {
        options_div.innerHTML = forms[0].parentNode.innerHTML;
    }
    
    var images = options_div.getElementsByTagName("IMG");
    for (var i=0; i<images.length; i++)
    {
        var img = images[i];
        img.setAttribute("src", img.getAttribute("src").replace("plaatjes", "images"));
    }
    
    forms = options_div.getElementsByTagName("FORM");
    var target;
    for (i=0; i<forms.length; i++)
    {
        target = forms[i].getAttribute("action");
        forms[i].setAttribute("onsubmit", "javascript:return options_onsubmit(this, event, '" + target + "');");
        // forms[i].removeAttribute("action");
        // forms[i].removeAttribute("method");
        forms[i].setAttribute("action", "");
        forms[i].setAttribute("method", "POST");
    }
    
    var anchors = options_div.getElementsByTagName("A");
    for (i=0; i<anchors.length; i++)
    {
        if (anchors[i].getAttribute("href").indexOf("javascript:openWin") === 0)
        {
            var id = anchors[i].getAttribute("href").match(/ID=(\d+)&/);
            if (id) 
            {
                anchors[i].setAttribute("onclick", "javascript:return show_help_for('" + id[1] + "');");
                anchors[i].setAttribute("onmouseover", "javascript:balloon.showTooltip(event, '<iframe src=\"/popup2.asp?ID=" + id[1] + "\">There should be help text here.</iframe>');");
                anchors[i].setAttribute("href", "#");
            }
            id = anchors[i].getAttribute("href").match(/chapter=([0-9.]+)&/);
            if (id) 
            {
                anchors[i].setAttribute("onmouseover", "javascript:balloon.showTooltip(event, '<iframe src=\"/popup3.asp?chapter=" + id[1] + "\">There should be help text here.</iframe>');");
                anchors[i].setAttribute("href", "#");
            }
        }
    }
*/
}

function show_option_info(event)
{
    var evt = event ? event : window.event;
    var elem = evt.srcElement ? evt.srcElement : evt.target;
    var id = elem.parentNode.childNodes[0].getAttribute("value");
    balloon.showTooltip(evt, '<iframe src=\"/popup2.asp?ID=' + id + '\">There should be help text here.</iframe>');
}

function parse_submit_response(option_div, text)
{
    removeAllChilds(option_div);
    refresh_code(document.getElementById("codesContent"));
}

function options_onsubmit(source, event)
{
    var evt = event ? event : window.event;
    var form = source;
    if (form.nodeName != "FORM") 
    {
        if (source.srcElement) // IE7 style
        {
            form = source.srcElement;
        }
        else // workaround
        {
            form = document.getElementById("formOptions");
        }
    }

    var chptr = currentOpenMenu[currentOpenMenu.length-1].getAttribute("id");
    chptr = chptr.replace("chapter_", "");
    while (chptr != chptr.replace("_", "."))
    {
        chptr = chptr.replace("_", ".");
    }
    var o = {element:  document.getElementById("optionsContent"),
             source:   "submit.asp?chapter=" + chptr,
             callback: parse_submit_response};
    requests.push(o);
    onComplete = populate_complete;
    onError    = populate_error;

    return form_onsubmit(form, evt, o.source);
}


/**
 * Menu handling routines 
 */
var currentOpenMenu = [];

function updateMenu()
{
    // get all chapters used by 'cookie'
    var cookie = getCookie("cookie");
    var chapter;
    var chapters = []; //new Array();

    if (typeof cookie == "string") // && cookie !== "")
    {
        cookie = decodeURIComponent(cookie);
        if (cookie.charAt(cookie.length-1) == ";")
        {
            cookie = cookie.substring(0, cookie.length-1); // remove the trailing ;
        }
        
        // Create a list of chapters, as defined by 'cookie'
        var crumbles = cookie.split(";");
        for (var crumble=0; crumble<crumbles.length; crumble++)
        {
            var thisChapter = crumbles[crumble].split("-")[0];
            if (chapters.indexOf(thisChapter) == -1)
            {
                chapters.push(thisChapter);
            }
        }

        // Make sure that the parent chapters are present
        var fHaveInserted;
        do
        {
            fHaveInserted = false;
            for (chapter=0; chapter<chapters.length; chapter++)
            {
                thisChapter = chapters[chapter];
                thisChapter = thisChapter.substring(0, thisChapter.length-1); // remove trailing dot
                if (thisChapter.lastIndexOf(".") != -1)
                {
                    var parentChapter = thisChapter.substring(0, thisChapter.lastIndexOf(".")+1); // including '.'
                    if (chapters.indexOf(parentChapter) == -1)
                    {
                        chapters.insert(parentChapter, chapter);
                        fHaveInserted = true;
                    }
                }
            }
        } 
        while (fHaveInserted);
    }

    // Reassign classes to all menu-items
    var menu_div = document.getElementById("menuContent");
    var items = menu_div.getElementsByTagName("LI");
    var currentActive = currentOpenMenu[currentOpenMenu.length-1];

    for (var elem = 0; elem < items.length; elem++)
    {
        var item = items[elem];
        var classes = [];
        chapter = item.id.replace("chapter_", "");
        while (chapter != chapter.replace("_", "."))
        {
            chapter = chapter.replace("_", ".");
        }
        classes.push( ((chapters.indexOf(chapter) == -1) ? "un" : "") + "changed" );
        if (currentOpenMenu.indexOf(item) != -1)
        {
            classes.push("opened");
            if (item == currentActive)
            {
                classes.push("active");
            }
        }
        item.className = classes.join(" ");
    }
}

function setup_menu(menu_div, text)
{
    var doc = text.getElementsByTagName("menu")[0];
    //menu_div.innerHTML = text;
    removeAllChilds(menu_div);
    copyXml(doc.getElementsByTagName("ul")[0],    menu_div);
    copyXml(doc.getElementsByTagName("Table")[0], menu_div); 
    var lastActiveID = getCookie("selectedChapter", "");
    var lastActiveElem = document.getElementById(lastActiveID);
    if (lastActiveElem)
    {
        var rootMenu = document.getElementById("menuContent").getElementsByTagName("UL")[0];
        currentOpenMenu = _makeTreeUpto(lastActiveElem, rootMenu);
        var i = requestIndexOf("?part=options");
        if (i != -1)
        {
            cancelRequest(i);
            var chapter = lastActiveID.substring(8);
            while (chapter != chapter.replace("_", "."))
            {
                chapter = chapter.replace("_", ".");
            }
            populate(document.getElementById("optionsContent"), "index.asp?part=options&chapter=" + chapter, parse_options);
        }
    }
    updateMenu();
}

function _makeTreeUpto(elem, root)
{ // elem is a HTMLLIElement
  // root is a HTMLULElement
    var result = []; //new Array();
    for (;;)
    {
        result.unshift(elem);
        if (elem.parentNode == root)
        {
            return result;
        }
        else
        {
            if (elem.parentNode.parentNode.nodeName == "LI")
            {
                elem = elem.parentNode.parentNode;
            }
            else
            {
                // this cannot happen
                alert("Denkfout!");
                return result;
            }
        }
    }
}

function menuchapter_onclick(event, chapter)
{
    var evt = event ? event : window.event;
    var elem = evt.target ? evt.target : evt.srcElement;
    var thisMenu = elem.parentNode;
    
    var rootMenu = document.getElementById("menuContent").getElementsByTagName("UL")[0];
    var newOpenMenu = _makeTreeUpto(thisMenu, rootMenu);
    
    var subMenu, subMenuHolder;

    var l = currentOpenMenu.length < newOpenMenu.length ? currentOpenMenu.length : newOpenMenu.length;
    for (var i=0; i<l; i++)
    {
        if (currentOpenMenu[i] != newOpenMenu[i])
        {
            break;
        }
    }
    if (i == l && newOpenMenu.length >= currentOpenMenu.length) // submenu or the same menu is choosen
    {
        currentOpenMenu = newOpenMenu;
    }
    else 
    {
        while (i < currentOpenMenu.length)
        {
            subMenu = currentOpenMenu.pop();
            //if ( (" " + subMenu.className).indexOf("active") > 0)
            //    subMenu.className.replace("active", "");
            subMenu.className = subMenu.className.replace("opened", "");
            subMenuHolder = subMenu.getElementsByTagName("UL");
            if (subMenuHolder.length > 0)
            {
                //subMenuHolder[0].style.display = "none";
                subMenuHolder[0].className = subMenuHolder[0].className.replace("opened", "");
            }
        }
        
        currentOpenMenu = newOpenMenu;
    }
    setCookie("selectedChapter", currentOpenMenu[currentOpenMenu.length-1].id);
        
/*    if (thisMenu.className.indexOf("opened") == -1)
            thisMenu.className += " opened";
    subMenuHolder = thisMenu.getElementsByTagName("UL");
    if (subMenuHolder.length > 0)
    {
        subMenu = subMenuHolder[0];
        //subMenu.style.display = (subMenu.style.display == 'none') ? // collapsed?
        //                        'block' :
        //                        'none'  ;
        if (subMenu.className.indexOf("opened") == -1)
            subMenu.className += " opened";
    }
    //if (typeof thisMenu.className == "string" && thisMenu.className.length > 0)
    //    thisMenu.className += " active"
    //else
    //    thisMenu.className = "active"
*/
    populate(document.getElementById("optionsContent"), "index.asp?part=options&chapter=" + chapter, parse_options);

    updateMenu();
    
    return false;
}


/**
 * UI callback functions.
 */
function handle_parsererror(xmlError, elem)
{
    var div=null, pre=null;

    switch(xmlError.nodeName.toLowerCase())
    {
    case 'parsererror':
        removeAllChilds(elem);
        div = document.createElement("div");
        div.className = "error";
        elem.appendChild(div);
        break;
    case 'sourcetext':
        pre = document.createElement("pre");
        elem.appendChild(pre);
        break;
    case '#text':
        elem.appendChild( document.createTextNode(xmlError.nodeValue) );
        break;
    }

    if (xmlError.childNodes.length)
    {
        for (var child=0; child<xmlError.childNodes.length; child++)
        {
            handle_parsererror(xmlError.childNodes[child], div?div:(pre?pre:elem));
        }
    }
}

function create_dialog_from_xml(dlg_elem, xml, formAttributes)
{
    if (typeof(formAttributes) == "undefined") 
    {
        formAttributes = {};
    }

    for (var i=0; i<xml.length; i++)
    {
        switch(xml[i].nodeName.toLowerCase())
        {
        case 'parsererror':
            handle_parsererror(xml[i], dlg_elem);
            break;
        case 'dialog':
            removeAllChilds(dlg_elem);
            create_dialog_from_xml(dlg_elem, xml[i].childNodes, formAttributes);
            break;
        case 'title':
            var title = document.createElement("H1");
            title.appendChild( document.createTextNode(xml[i].childNodes[0].nodeValue) );
            dlg_elem.appendChild(title);
            break;
        case 'message':
            var form = document.createElement("FORM");
            for (var attr in formAttributes)
            {
                if (attr.substring(0, 2).toLowerCase() == "on" && form.attachEvent)
                {
                    var fncBody = formAttributes[attr].replace("javascript:", "");
                    fncBody = fncBody.replace("return", "");
                    form.attachEvent(attr.toLowerCase(), function(){eval(fncBody); return false;});
                }
                else
                {
                    form.setAttribute(attr, formAttributes[attr]);
                }
            }
            create_dialog_from_xml(form, xml[i].childNodes, formAttributes);
            dlg_elem.appendChild(form);
            break;
        case 'text':
            dlg_elem.appendChild( document.createTextNode(typeof(xml[i].text) == "undefined" ? xml[i].childNodes[0].nodeValue : xml[i].text) );
            // FALL THROUGH
        case 'br':
            dlg_elem.appendChild( document.createElement("BR") );
            dlg_elem.appendChild( document.createTextNode("\n") );
            break;
        case 'input':
            copyXml(xml[i], dlg_elem);
            break;
        case 'label':
            var lbl = copyXml(xml[i], dlg_elem);
            if (isIE)
            {
                if (lbl.attachEvent)
                {
                    lbl.attachEvent("onclick", label_clicked);
                }
                else
                {
                    lbl.setAttribute("onclick", "javascript:return label_clicked(event);");
                }
            }
            break;
        case 'table':
            copyXml(xml[i], dlg_elem);
            break;
        default:
            break; // ignore
        }
    }

/*    var body = text.getElementsByTagName("BODY")[0];
        for (var elem = 0; elem < body.childNodes.length; elem++)
        {
            if (body.childNodes[elem].nodeName == "FORM")
            {
                body.childNodes[elem].setAttribute("onsubmit", "javascript:return onsubmit_print_options(this, event);");
                body.childNodes[elem].setAttribute("action", "index.asp?part=print_options_sub");
            }
            if (body.childNodes[elem].nodeName != "FONT")
            {
                dlg.appendChild(body.childNodes[elem]);
            }
        }
*/
}

/** 
 * Configuration dialog 
 */
function parse_load_config_dialog(dlg, text)
{
        var iBegin = text.indexOf("<Body");
        iBegin = text.indexOf(">", iBegin);
        var iEnd   = text.indexOf("</Body>");
        text = text.substring(iBegin+">".length, iEnd);
        var iFormBegin = text.indexOf("<Form ");
        var iFormEnd   = text.indexOf(">", iFormBegin);
        text = text.substring(0, iFormBegin) + 
               "<Form" + 
               " Method=\"Post\"" + 
               " Action=\"/opticonnect/loadcodes2.asp\"" +
               " onsubmit=\"javascript:return onsubmit_load_config(this, event);\"" + 
               text.substr(iFormEnd);
        dlg.innerHTML = text;
}

function load_config(elem, event)
{
    show_dialog("load", "OptiConnect", true, parse_load_config_dialog);
}

function onsubmit_load_config(elem, event)
{
    var o = {element:  document.getElementById("codesContent"),
             source:   elem.getAttribute("Action"),
             callback: refresh_code};
    requests.push(o);
    onComplete = populate_complete;
    onError    = populate_error;
    
    return true;
}

/**
 * Start over question box
 */
function start_over(elem, event)
{
    if (confirm("Clear the current configuration and\nstart over?"))
    {
        clearCookie("cookie");
        currentOpenMenu = [];
        clearCookie("selectedChapter");
        // Clear all non-print options
        setMultiValue("opticonfigure", "reader",      "");
        setMultiValue("opticonfigure", "readersoft",  "");
        setMultiValue("opticonfigure", "rom",         "");
        setMultiValue("opticonfigure", "typeRom",     "");
        setMultiValue("opticonfigure", "FLASH",       "");
        setMultiValue("opticonfigure", "typeFlash",   "");
        setMultiValue("opticonfigure", "DMC",         "");
        setMultiValue("opticonfigure", "typeDmc",     "");
        setMultiValue("opticonfigure", "opto",        "");
        removeAllChilds(document.getElementById("optionsContent"));
        refresh_code(document.getElementById("codesContent"));
        updateMenu();
    }
}

/**
 * Print options dialog
 */
function process_print_options()
{
    var elem, i;

    // Update the header and footer elements 
    for (i=1; i<=3; i++)
    {
        elem = document.getElementById("header" + i);
        removeAllChilds(elem);
        elem.appendChild( document.createTextNode(getMultiValue("opticonfigure", "hd"+i, "")) );
    }
    for (i=1; i<=3; i++)
    {
        elem = document.getElementById("footer" + i);
        removeAllChilds(elem);
        elem.appendChild( document.createTextNode(getMultiValue("opticonfigure", "ft"+i, "")) );
    }

    //removeAllChilds(document.getElementById("codesContent"));
    refresh_code(document.getElementById("codesContent"));
}

function parse_print_options_dialog(dlg, text)
{
    if (typeof(text) == "object")
    {
        create_dialog_from_xml(dlg, text.childNodes, {action:"index.asp?part=print_options_sub", onsubmit:"javascript:return onsubmit_print_options(this, event);"});
    }
    else
    {
        var iBegin = text.indexOf("<Body>");
        var iEnd   = text.indexOf("</Body>");
        text = text.substr(iBegin+"<Body>".length, iEnd);

        var iFormBegin = text.indexOf("<Form ", iBegin);
        var iFormEnd   = text.indexOf(">", iFormBegin);
        text = text.substr(0, iFormBegin) + 
               "<Form Method=\"Post\" Action=\"index.asp?part=print_options_sub\" onsubmit=\"javascript:return onsubmit_print_options(this, event);\"" + 
               text.substr(iFormEnd);

        dlg.innerHTML = text;
    }
    //init_scripts();
}

function show_print_options(elem, event)
{
    show_dialog("print_options", "Print Options", false, parse_print_options_dialog);
}

function onsubmit_print_options(elem, event)
{
    var evt = event ? event : window.event;
    var form = elem;
    if (form.nodeName != "FORM")
    {
        form = evt.srcElement;
    }
    var data = form_gather_data(form, null, true);
    var options = data.split("&");
    for (var option = 0; option < options.length; option++)
    {
        var param = options[option].split("=");
        var name  = param[0];
        var value = param[1];
        switch (name)
        {
            case "chapter":
            case "serial":
            case "output":
            case "extra":
            case "softversion":
            case "showtext":
            case "hd1":
            case "hd2":
            case "hd3":
            case "ft1":
            case "ft2":
            case "ft3":
            case "nopicture":
                setMultiValue("opticonfigure", name, value);
                break;

            //case "link": // Keep JSLint.com happy
            default:
                break;
        }
    }
    
    process_print_options();
    return closeDialog();
}

function changeHeaderFooterText(event)
{
    var evt  = event ? event : window.event;
    var elem = evt.srcElement ? evt.srcElement : evt.target;
    var id   = elem.getAttribute("id");
    var text = elem.childNodes[0].nodeValue;
    var response = window.prompt("Please enter new text for the " + id.substr(0, 6).toLowerCase(), text);
    if (response && response != text)
    {
        node = document.createTextNode(response);
        elem.replaceChild(node, elem.childNodes[0]);
        setMultiValue("opticonfigure", ((id.substr(0, 6).toLowerCase() == "header") ? "hd" : "ft") + id.substr(6), response);
    }
}
    
/**
 * Help dialog
 */
function parse_help_dialog(dlg, text)
{
    removeAllChilds(dlg);

    if (typeof text == "object")
    {
        var table = text.getElementsByTagName("TABLE")[0];
        for (var elem = 0; elem < table.childNodes.length; elem++)
        {
            dlg.appendChild(table.childNodes[elem]);
        }
    }
    else
    {
        var iBegin = text.indexOf("<Table>");
        var iEnd   = text.indexOf("</TABLE>");
        text = text.substr(iBegin+"<Table>".length, iEnd);
        dlg.innerHTML = "\n<h1>Help</h1>" + text;
    }
    if (dlg.attachEvent)
    {
        dlg.attachEvent("onclick", closeDialog);
    }
    else
    {
        dlg.setAttribute("onclick", "javascript:return closeDialog(this, event);");
    }
}

function show_help()
{
    show_dialog("help", "Help", true, parse_help_dialog);
}

/*
function show_help_for(id)
{
    show_dialog("/popup2.asp?ID=" + id);
}
*/

/**
 * Page initialization
 */
function populate_page()
{
	populate(document.getElementById("contactmenu"),    "index.asp?part=contactmenu");
	populate(document.getElementById("mainmenu"),       "index.asp?part=mainmenu");
	populate(document.getElementById("menuContent"),    "index.asp?part=menu",    setup_menu);
	populate(document.getElementById("optionsContent"), "index.asp?part=options", parse_options);
    refresh_code(document.getElementById("codesContent"));
}

function bind_listeners()
{
    var types = ["header", "footer"];
    for (var elemType=0; elemType<types.length; elemType++)
    {
        for (var i=1; i<=3; i++)
        {
            var elem = document.getElementById(types[elemType] + i);
            if (elem.attachEvent)
            {
                elem.attachEvent("ondblclick", changeHeaderFooterText);
            }
            else
            {
                elem.setAttribute("ondblclick", "javascript:return changeHeaderFooterText(event);");
            }
        }
    }
}

function opticonfigure_initialize()
{
    // Check for cookie existance, create if not present
    if (!getCookie("opticonfigure"))
    {
        setMultiValue("opticonfigure", "showtext", "yes");
    }

    process_print_options();
    populate_page();
    bind_listeners();
}

// vim: expandtab cindent:

