﻿DropDownControlArray = new Array();

function DropDownControl(titleTxt, titlePanel, itemsBox, className) {

    this.title = titleTxt;
    this.titlePanel = document.getElementById(titlePanel);
    this.itemsBox = document.getElementById(itemsBox);
    this.className = className;
    this.items = new Array();

    this.onloaddelegate = function() {
        this.items = this.titlePanel.value.split(", ");
        if (this.items.contains(this.title) > -1)
            this.items.splice(this.items.contains(this.title), 1);
    }

    this.init = function() {

        DropDownControlArray[DropDownControlArray.length] = this;

        Array.prototype.contains = function(needle) {
            for (i = 0; i < this.length; i++) {
                if (this[i] == needle)
                    return i;
            }
            return -1;
        }

        document.onload = this.onloaddelegate();

        return this;
    }

    this.Toggle = function() {
        this.itemsBox.style.display = (this.itemsBox.style.display == 'block') ? 'none' : 'block';
    }

    this.Close = function() {
        this.itemsBox.style.display = 'none';
    }

    this.AddTitle = function(obj) {
        if (obj.checked) {
            if (this.items.contains(obj.parentNode.childNodes[1].innerHTML) < 0)
                this.items[this.items.length] = obj.parentNode.childNodes[1].innerHTML;
        } else {
            this.items.splice(this.items.contains(obj.parentNode.childNodes[1].innerHTML), 1);
        }
        FillTitles(this.title, this.titlePanel, this.items);
    }

    function FillTitles(titleStr, titlePanelObj, itemsObj) {
        titlePanelObj.value = (itemsObj.length == 0) ? titleStr : "";
        for (i = 0; i < itemsObj.length; i++) {
            if (itemsObj[i] != null)
                titlePanelObj.value += (i == 0) ? itemsObj[i] : ", " + itemsObj[i];
        }
    }
}

window.onload = function() {
    document.onclick = function(e) {
        e = e || event;
        var target = e.srcElement || e.target;
        for (i = 0; i < DropDownControlArray.length; i++) {
            if (target.parentNode.className != DropDownControlArray[i].className)
                DropDownControlArray[i].Close();
                }
        }
}