/**
 * GSB-specific AJAX classes and functions
 * @version $Id: ajax_gsb.js,v 1.1.2.4 2006/09/06 08:52:55 kruithof Exp $
 */

var currentHrefPrefix;
var containerDiv;
var parentContainerDiv;
var statusBox;
var containers = new Array();
var selectTexts = new Array();
var defaultSelectText;
var defaultWaitText;

/**
 * Creates nested div and select box
 * @param DOMNode parentDiv the div to append child div to
 * @param string path the path used as div id
 * @return void
 */
function createChildSelectDiv(parentDiv, path)
{
    var selectText;

    while (parentDiv.childNodes.length > 1) parentDiv.removeChild(parentDiv.lastChild);

    var div = document.createElement('div');
    div.setAttribute('id', getPathId(path));

    var select = document.createElement('select');
    select.style.display = 'none';

    if (selectTexts.length > 0) {
        selectText = selectTexts.shift();
    } else {
        selectText = defaultSelectText;
    }
    select.setAttribute('selecttext', selectText);
    select.onchange = processSelectChange;

    div.appendChild(select);
    parentDiv.appendChild(div);

    if (containers[path]) {
        processContainer(containers[path], path);
    } else {
        loadContainer(path);
    }
}

/**
 * Creates nested div for page data
 * @param DOMNode parentDiv the div to append child div to
 * @param string path the path used as div id
 * @return void
 */
function createChildPageDiv(parentDiv, path)
{
    while (parentDiv.childNodes.length > 1) parentDiv.removeChild(parentDiv.lastChild);

    div = document.createElement('div');
    div.setAttribute('id', getPathId(path));
    parentDiv.appendChild(div);

    if (containers[path]) {
        processContainer(containers[path], path);
    } else {
        loadContainer(path);
    }
}

/**
 * Returns a full path (with first div's prefix) for a given container path
 * @param string path The container's path (e.g. /boetebase/drugs/)
 * @return string The full path
 */
function getPathId(path_id)
{
    var path = containerDiv.getAttribute('id') + path_id;
    return path;
}

/**
 * Resets select boxes to initial state
 */
function startOver()
{
    createChildSelectDiv(containerDiv, currentHrefPrefix, '');
}

/**
 * Gets content array for a given level
 * @access public
 * @param string path The path to get content for. Must begin and end with forward slash.
 * @return Array an array holding content and children for the requested level
 */
function loadContainer(path)
{
    AjaxRequest.get(
        {
          'url':path + '?output=xml',
          'generateUniqueUrl':false,
          'onSuccess':processContentContainerRequest
        }
      );
}

/**
 * Processes XML response for a container
 * @param AjaxRequest The request object. See AjaxRequest.js for details.
 * @return void
 */
function processContentContainerRequest(req)
{
    var doc = req.responseXML.documentElement;
    var path = doc.getAttribute('path');
    var container = new ContentContainer(doc, path);
    containers[path] = container;
    processContainer(container);
}

/**
 * Processes Container, applies data where necessary.
 * @param ContentContainer container The container to process.
 * @return void
 */
function processContainer(container)
{
    if (container.type == 'menu') {
        populateBox(container);
    } else if (container.type == 'page') {
        populatePageDiv(container);
    } else if (container.type == 'dossier') {
        populateDossierDiv(container);
    }
}

/**
 * OnChange handler for select boxes
 * @param Event e The onchange event object
 * @return void
 */
function processSelectChange(e)
{
    if (!e) e = window.event;
    element = e.target || e.srcElement;

    var selectedPath = element.options[element.selectedIndex].value;

    if (element.options[0].value == '') element.options[0] = null;

    if (selectedPath != '') {

//        statusBox.setStatus('busy');
//        statusBox.setText(defaultWaitText);

        var parentPath = element.parentNode.getAttribute('id').substring(containerDiv.getAttribute('id').length);
        var selectedType = containers[parentPath].children[selectedPath].container_type;

        if (selectedType == 'menu') {
            createChildSelectDiv(element.parentNode, parentPath + selectedPath + '/');
        } else if (selectedType == 'dossier') {
            createChildPageDiv(element.parentNode, parentPath + selectedPath + '/');
        }
    }
}


/**
 * Populates select box with container's sections as options
 * @param ContentContainer container The container
 * @return void
 */
function populateBox(container)
{
    var path = container.path;
    var children = container.children;
    var select, el, firstOption, newOption;

    el = document.getElementById(getPathId(path));

    try {
        if (el) {
            select = el.firstChild;
            if (select) {
                while (select.firstChild) select.removeChild(select.firstChild);

                firstOption = document.createElement('option');
                addTextNode(firstOption, select.getAttribute('selecttext'));
                select.appendChild(firstOption);

                for (var i in children) {

                    // only add objects, since there can be variables and functions too
                    if (typeof(children[i]) == 'object') {
                        newOption = document.createElement('option');
                        newOption.setAttribute('value', children[i].name);
                        addTextNode(newOption, children[i].title);
                        select.appendChild(newOption);
                    }
                }
            }
            select.style.display = 'block';
        }
//        statusBox.setStatus('idle');
    } catch (e) {
//        statusBox.reportError(e);
    }
}

/**
 * Populates a div with page data.
 * Currently, only page type 'penalty' is implemented
 * @param ContentContainer container The contentcontainer
 * @return void
 */
function populatePageDiv(container)
{
    var path = container.path;

    el = document.getElementById(getPathId(path));

    try {
        if (el) {
            while (el.childNodes.length > 0) el.removeChild(el.firstChild);

        }
//        statusBox.setStatus('idle');
    } catch (e) {
//        statusBox.reportError(e);
    }
}

/**
 * Populates a div with dossier data.
 * @param ContentContainer container The contentcontainer
 * @return void
 */
function populateDossierDiv(container)
{
    var path = container.path;
    var tr, th, td, a, img;

    el = document.getElementById(getPathId(path));

    try {
        if (el) {

            while (el.childNodes.length > 0) el.removeChild(el.firstChild);

            // start creating table elements
            var table = document.createElement('table');
            var thead = document.createElement('thead');
            var tbody = document.createElement('tbody');
            var tfoot = document.createElement('tfoot');

            table.setAttribute('id', 'dossiers');

            // fill table head

            tr = document.createElement('tr');
            th = document.createElement('th');
            addTextNode(th, getText('DossierDate'));
            tr.appendChild(th);

            th = document.createElement('th');
            addTextNode(th, getText('DossierTitle'));
            tr.appendChild(th);

            th = document.createElement('th');
            addTextNode(th, getText('DossierInstrument'));
            tr.appendChild(th);

            //th = document.createElement('th');
            //addTextNode(th, getText('DossierStage'));
            //tr.appendChild(th);

            th = document.createElement('th');
            addTextNode(th, getText('DossierDossiertype'));
            tr.appendChild(th);

            th = document.createElement('th');
            addTextNode(th, getText('DossierRead'));
            tr.appendChild(th);

            thead.appendChild(tr);
            table.appendChild(thead);
            table.appendChild(tbody);
            el.appendChild(table);

            // see if children are available, and fill tbody
            if (container.children == undefined) {
                // give notice that no children are available
                tr = document.createElement('tr');
                td = document.createElement('td');
                td.setAttribute('colspan', '5');
                addTextNode(td, 'Er zijn geen dossiers weer te geven');
                tr.appendChild(td);
                tbody.appendChild(tr);
            } else {
                for (var a in container.children) {
                    if (typeof(container.children[a]) == 'object') {

                        tr = document.createElement('tr');
                        tr.setAttribute('id', a);

                        td = document.createElement('td');
                        addTextNode(td, container.children[a].datetime_dossier);
                        tr.appendChild(td);

                        td = document.createElement('td');
                        addTextNode(td, container.children[a].title);
                        tr.appendChild(td);

                        td = document.createElement('td');
                        addTextNode(td, container.children[a].instrument);
                        tr.appendChild(td);

                        //td = document.createElement('td');
                        //addTextNode(td, container.children[a].stage);
                        //tr.appendChild(td);

                        td = document.createElement('td');
                        addTextNode(td, container.children[a].dossiertype);
                        tr.appendChild(td);

                        td = document.createElement('td');
                        link = document.createElement('a');
                        img = document.createElement('img');

                        link.setAttribute('href', container.children[a].url);
                        link.setAttribute('title', 'Lezen (' + container.children[a].extension + ')');
                        img.setAttribute('src', '/images/ico_' + container.children[a].extension + '.gif');
                        img.setAttribute('alt', container.children[a].extension.toUpperCase());

                        link.appendChild(img);
                        td.appendChild(link);
                        tr.appendChild(td);

                        tbody.appendChild(tr);
                    }
                }
            }
            new Effect.Highlight('dossiers', {startcolor:'#fcf2e8',endcolor:'#ffffff'});
        }
//        statusBox.setStatus('idle');
    } catch (e) {
//        statusBox.reportError(e);
    }
}

/**
 * Initializes AJAX menu. Sets global variables and creates first select box.
 * @param string boxDivId The Id for the first div
 * @param string hrefprefix The path for first div
 * @param string waitText The 'loading data' message text
 * @param string selectText The 'make a selection' message text
 * @param string currencySign The (probably euro) currency sign
 * @return void
 */
function initBoxTree(parentId, containerId, statusBoxId, hrefprefix, waitText, selectText)
{
    // fill selecttexts array
    defaultSelectText = selectText;
    if (arguments.length > 5) {
        for (var i = 6; i < arguments.length; i++) {
            selectTexts.push(arguments[i]);
        }
    }

    currentHrefPrefix = hrefprefix;
    defaultWaitText = waitText;
    containerDiv = document.getElementById(containerId);
    parentContainerDiv = document.getElementById(parentId);
//    statusBox = new StatusBox(document.getElementById(statusBoxId));

    if (!containerDiv) {
        containerDiv = document.createElement('div');
        containerDiv.setAttribute('id', containerId);
        parentContainerDiv.appendChild(containerDiv);
    }

//    statusBox.setStatus('busy');
//    statusBox.setText(waitText);
    createChildSelectDiv(containerDiv, currentHrefPrefix);
}