var setting_sections = new Array();
setting_sections[0] = 'work';
setting_sections[1] = 'leisure';
//setting_sections[2] = 'sleep';
setting_sections[2] = 'sport';

var setting_total_id = 'total';

var global_table_handler = null;

var max_fields = new Array();
max_fields['work'] = 5;
max_fields['leisure'] = 2;
max_fields['sport'] = 4;

function nrj_init() {
    global_table_handler = new Table_handler();
    for (var i = 0; i < setting_sections.length; ++i) {
        var t = new Row_handler();
        t.set_name(setting_sections[i]);
        global_table_handler.add_row(t);
    }
    check_hour_input();
}

function delete_row(ele) {
    global_table_handler.delete_row(ele);
    check_hour_input();
}

function check_input(ele) {
    global_table_handler.check_input(ele);
    check_hour_input();
}

function check_hour_input(ele) {
    var total = 0;
    var tmp;
    var inputs = document.getElementsByTagName('INPUT');

    for (var i = 0; i < inputs.length; ++i) {
        if (inputs[i].id.search(/[.]*_h/) != -1) {
            if (!isNaN(parseFloat(inputs[i].value))) {
                total += parseFloat(inputs[i].value);
            }
        }
    }

    total = total.toFixed(2);
    if (total == 0.00) total = '';
    $(setting_total_id).value = total;
}

function Table_handler() {
    this.rows_ = new Array();

    this.add_row = function(row) {
        this.rows_.push(row);
    };
    this.delete_row = function(ele) {
        for (var i = 0; i < this.rows_.length; ++i) {
            if (this.rows_[i].delete_row(ele)) {
                return true;
            }
        }
        return false;
    };
    this.check_input = function(ele) {
        for (var i = 0; i < this.rows_.length; ++i) {
            if (this.rows_[i].check_input(ele)) {
                return true;
            }
        }
        return false;
    };
}

function Row_handler() {
    this.rows_ = new Array();
    this.name_ = null;

    this.init = function() {
        for (
            var i = 0;
            document.getElementById(this.name_ + '_' + i) != null;
            ++i
            ) {
            var t = new Input_ele();
            t.set_name(this.name_ + '_' + i);
            this.rows_[i] = t;
        }
    };
    this.set_name = function(name) {
        this.name_ = name;
        this.init();
    };
    this.is_here = function(ele) {
        if (ele.id.search(this.name_) != -1) {
            return true;
        }
        return false;
    };

    this.array_remove_ele = function(container,ele_id) {
        var t = new Array();
        for (var i = 0; i < container.length; ++i) {
            if (container[i].get_name() != ele_id) {
                t.push(container[i]);
            }
        }
        return t;
    }
    this.delete_row = function(ele) {
        if (!this.is_here(ele)) return false;

        if (this.rows_.length > 1) {
            var tr = parent_by_tag(ele,'TR');
            // check if we need to keep first content of td
            if ( // at least 1 html tag
                isset(tr.cells[0].innerHTML) &&
                tr.cells[0].innerHTML != '' &&
                tr.cells[0].innerHTML.search(/(<.*>)+[^<]*(<.*>)+.*/i) != -1
                ) {
                var table = parent_by_tag(tr,'TABLE');
                if (
                    isset(table.rows[(tr.rowIndex + 1)].cells[0]) &&
                    table.rows[(tr.rowIndex + 1)]
                    .cells[0].innerHTML.search(/(<.*>)+[^<]*(<.*>)+.*/i) == -1
                    ) {
                    table.rows[(tr.rowIndex + 1)].cells[0].innerHTML =
                        tr.cells[0].innerHTML;
                }
            }
            remove_all_childs(tr);
            tr.parentNode.removeChild(tr);
            this.rows_ = this.array_remove_ele(
                this.rows_,
                ele.id.replace(/delete_/i,'')
                );
            // hide delete if needed
            if (this.rows_.length <= 1) {
                var i   = this.get_first_num();
                var ele = $(this.name_ + '_' + i);
                if (ele.value == '-1') {
                    $('delete_' + this.name_ + '_' + i).className = "hidden";
                }
            }
        } else {
            var t = ele.id.replace(/delete_/i,'');
            // first element reset it
            $(t).selectedIndex = 0;
            $(t + '_h').value  = '';
            ele.className = "hidden";
        }
        return true;
    };
    this.check_input = function(ele) {
        if (!this.is_here(ele)) return false;

        // + 1 cause the '_'
        var ele_num = ele.id.slice((this.name_.length + 1));
        var ele_cnt = this.rows_.length;

        if (
            (this.get_last_num()) != ele_num ||
            ele_cnt >= max_fields[this.name_]
            ) {
            // ele is here but no need to append new element
            // cause its not the last one of our list
            return true;
        }

        if (isset(ele.value) && ele.value != '' && ele.value != '-1') {
            // append new one
            this.append_row();
            // show delete image
            $('delete_' + this.name_ + '_' + ele_num).className = "";
        } else {
            // remove old one? => atm not :-)
        }
        return true;
    };
    this.append_row = function() {
        var first_num = this.get_first_num();
        var copy   = null;
        var select = document.getElementById(this.name_ + '_' + first_num);
        var tr     = parent_by_tag(select,'TR');
        var table  = parent_by_tag(tr,'TABLE');

        var new_tr = table.insertRow(tr.rowIndex + (this.rows_.length));
        var cell   = new_tr.insertCell(-1);
        cell.innerHTML = '&nbsp;';

        cell = new_tr.insertCell(-1);
        Move.element(select,cell,'copy');
        copy = document.getElementById(select.id + '-copy');
        copy.id = this.name_ + '_' + this.get_next_num();
        copy.name = this.name_ + '_' + this.get_next_num();
        copy.selectedIndex = 0;

        cell = new_tr.insertCell(-1);
        Move.element('delete_' + this.name_ + '_' + first_num,cell,'copy');
        copy = document.getElementById(
            'delete_' + this.name_ + '_' + first_num + '-copy'
            );
        cell.className = "del_img";
        copy.id = 'delete_' + this.name_ + '_' + this.get_next_num();
        copy.name = 'delete_' + this.name_ + '_' + this.get_next_num();
        copy.className = "hidden";

        cell = new_tr.insertCell(-1);
        Move.element(this.name_ + "_" + first_num + "_h",cell,'copy');
        copy = document.getElementById(this.name_ + "_" + first_num + "_h-copy");
        copy.id = this.name_ + '_' + this.get_next_num() + '_h';
        copy.name = this.name_ + '_' + this.get_next_num() + '_h';
        copy.value = '';

        cell = new_tr.insertCell(-1);
        cell.className = "form_unit";

        var t = getElementsByClassName("form_unit");
        if (t.length > 0) {
            for (var i = 0; i < t.length; ++i) {
                if (t[i] != '') {
                    cell.innerHTML = t[i].innerHTML;
                    break;
                }
            }
        }
        if (cell.innerHTML == '') {
            cell.innerHTML = 'Stunde/n';
        }

        var t = new Input_ele();
        t.set_name(this.name_ + '_' + this.get_next_num());
        this.rows_.push(t);
    };
    this.get_first_num = function() {
        var t = this.rows_[0].get_name();
        t = t.replace(this.name_,'');
        t = t.replace(/_/g,'');
        t = t.replace(/[a-z]/ig,'');
        return parseFloat(t);
    };
    this.get_last_num = function() {
        var t = this.rows_[(this.rows_.length - 1)].get_name();
        t = t.replace(this.name_,'');
        t = t.replace(/_/g,'');
        t = t.replace(/[a-z]/ig,'');
        return parseFloat(t);
    };
    this.get_next_num = function() {
        return this.get_last_num() + 1;
    };
}

function Input_ele() {
    this.name_ = null;
    this.ele_  = null;

    this.set_name = function(name) {
        this.name_ = name;
        this.ele_  = document.getElementById(name);
        this.set_event();
    };
    this.get_del_button = function() {
        return document.getElementById('delete_' + this.name_);
    };
    this.get_hour_input = function() {
        return document.getElementById(this.name_ + '_h');
    };
    this.get_name = function() {
        return this.name_;
    };
    this.set_event = function() {
        this.ele_.onchange = new Function("check_input(this)");

        this.get_del_button().onclick = new Function(
            "delete_row(this)"
            );

        this.get_hour_input().onkeyup = new Function(
            "check_hour_input(this)"
            );
    };
}

function isset(v) {
    if (
        v == null ||
        typeof v == 'undefined'
        ) {
        return false;
    }
    return true;
}

function parent_by_tag(child,tag) {
    var parent = child.parentNode;
    while (parent.tagName != tag && parent.tagName != 'BODY') {
        parent = parent.parentNode;
    }

    if (parent.tagName != tag) return null;
    return parent;
}

function remove_all_childs(parent) {
    while (parent.childNodes.length >= 1) {
        parent.removeChild(parent.firstChild);
    }
}

/*
  This script is copyright (c) 2006 Elliot Swan under the
  Creative Commons Attribution-ShareAlike 2.5 license:
  http://creativecommons.org/licenses/by-sa/2.5/

  More information on this script can be found at:
  http://www.elliotswan.com/2006/04/12/move-and-copy/
*/
var Move =  {
copy: function(e, target) {
        var eId      = $(e);
        var copyE    = eId.cloneNode(true);
        var cLength  = copyE.childNodes.length -1;
        copyE.id     = $(e).id + '-copy';

        for(var i = 0; cLength >= i;  i++)  {
            if(copyE.childNodes[i].id) {
                var cNode   = copyE.childNodes[i];
                var firstId = cNode.id;
                cNode.id    = firstId+'-copy'; }
        }
        $(target).appendChild(copyE);
    },

element: function(e, target, type) {
        var eId =  $(e);
        if(type == 'move') {
            $(target).appendChild(eId);
        }
        else if(type == 'copy') {
            this.copy(e, target);
        }
    }
}

/* This script and many more are available free online at
   The JavaScript Source :: http://javascript.internet.com
   Created by: Dustin Diaz :: http://www.dustindiaz.com/ */
    function $() {
        var elements = new Array();
        for (var i = 0; i < arguments.length; i++) {
            var element = arguments[i];
            if (typeof element == 'string')
                element = document.getElementById(element);
            if (arguments.length == 1)
                return element;
            elements.push(element);
        }
        return elements;
    }

function debug(v) {
    //document.getElementById('debug').innerHTML += v + '<br />';
}

/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};