function SessionVerlaengern(duration)
{
	remain = duration;
	document.getElementById('minutes').innerHTML = remain;
	new Ajax.Request("/ajax/sessionverlaengern.php");
}

function save_pos(obj, user)
{
  var x = $("matchings_" + obj).style.left;
  var y = $("matchings_" + obj).style.top;  
  
  new Ajax.Request("/ajax/windows/window_save_pos.php",{method:"post",parameters:"posx="+x+"&posy="+y+"&obj="+obj+"&user="+user});

  showz(obj);
}

function save_pos_start(x,y, obj)
{
   offx[obj] = x - posx[obj];
   offy[obj] = y - posy[obj];
   posx[obj] = x;
   posy[obj] = y;
  
   //var zi = $("matchings_" + obj).style.zIndex;
   
   zi = zi + 5;
   
   $("matchings_" + obj).style.zIndex = zi;
   
   showz(obj);
   //alert (zi);
   
  // posy[obj] = $("matchings_" + obj).style.top;
}

function Hide(wind)
{
  if(!$("matchings_" + wind))
	return false;
  $("matchings_" + wind).style.display="none";
  new Ajax.Request("/ajax/windows/window_hide.php", {method:"post",parameters:"obj="+wind});
}
var count = 1;
function Show(wind)
{
	new Ajax.Request("/ajax/windows/window_hide.php", {method:"post",parameters:{obj:wind,on:1}});
	if($("matchings_" + wind))
	{
		$("matchings_" + wind).style.display="block";
	}
	else
	{
		var obj = document.getElementsByTagName('body')[0];
		var node = document.createElement('div');
		node.setAttribute('style','height:0px;width:0px;position:absolute;top:0;left:0');
		node.setAttribute('id','WindowLoad'+count);
		obj.appendChild(node);
		/* new Ajax.Request("/ajax/windows/window_load.php", {method:"post",evalScripts:true,parameters:{id:wind},onSuccess:function(t){
			document.getElementsByTagName('div')[document.getElementsByTagName('div').length-1].innerHTML = t.responseText;
			new Draggable("matchings_"+wind, {ghosting:false, revert:false,handle:"titel2"})
		}});	 */
		new Ajax.Updater('WindowLoad'+count,"/ajax/windows/window_load.php",{method:"post",evalScripts:true,insertion:Insertion.bottom,parameters:{id:wind}});
		count++;
	}
}

function minimize(obj)
{
  var bl;

  stat = $("fmain_" + obj).style.display;

  if (stat == "none")
  {
    $("fmain_" + obj).style.display="block";
    bl = 0;
  }
  else
  {
    $("fmain_" + obj).style.display="none";
    bl = 1;
  }
  
  new Ajax.Request("/ajax/windows/window_minimize.php", {method:"post",parameters:"ob="+obj+"&stat="+bl});
}

function showz(obj)
{
  //z1 = $("matchings_" + obj).style.zIndex;
  //$("f1").innerHTML = z1;
}

function Create(bname)
{
	Sortable.create(bname,
  {
    tag:'fieldset',
    overlap:'vertical',
    constraint:false,
    handle:'handlepoint',
    onUpdate:function()
    { 
      Update(Sortable.serialize(bname) + "&vnam="+bname); 
    }
  })
}

function Create2(bname)
{
	Sortable.create(bname,
  {
    tag:'fieldset',
    overlap:'horizontal',
    constraint:false,
    handle:'handlepoint',
    onUpdate:function()
    { 
      Update(Sortable.serialize(bname) + "&vnam="+bname); 
    }
  })
}

function Update(parameters)
{
	new Ajax.Request('/eros/ajax/start_boxen.php',{method:'post',parameters:parameters});
}

function test()
{
  alert("klappt");
}



posx = new Array();
posy = new Array();
offx = new Array();
offy = new Array();

var zi = 1000; 



if(!Nikmedia) var Nikmedia = {};

Nikmedia.TableSearch = Class.create({
    initialize: function(element, options) {
        this.element = element = $(element);
        this.options = {
            useTHead: true,
            elements: null,
            indicate: true,
            inputStyle: {
                width: '100%'
            },
            startSearch: function() {},
            endSearch: function() {},
            updateSearch: function() {},
            editTitle: function() {}
        };
        Object.extend(this.options, options || {});

        this.boundOnUpdate = this.onUpdate.bind(this);
        this.boundOnShow = this.onShow.bind(this);
        this.boundOnAbort = this.onAbort.bind(this);

        if(element.tagName.toLowerCase() != 'table') throw 'element must be a table';
        var grp = (this.options.useTHead) ? 'thead' : 'tbody';
        this.editors = [];
        element.select(grp)[0].down().childElements().each(function(elem, index) {
            if(this.options.elements == null || this.options.elements.include(index)) {
                var style = Object.clone(this.options.inputStyle);
                if(style.width == '100%') {
                    //style.width = elem.getWidth()+'px';
                }
                this.options.editTitle(elem, this);
                this.editors.push(new Nikmedia.InlineEditor(elem, {
                    inputStyle: style,
                    onUpdate: this.boundOnUpdate,
                    onShow: this.boundOnShow,
                    onAbort: this.boundOnAbort,
                    onAccept: function() { return false }
                }));
            }
        }.bind(this));
        this.threadWorker = new Nikmedia.ThreadWorker();
        if(this.options.indicate) {
            this._indicate();
        }
        this.stats = {};
    },
    _indicate: function() {
        this._getRows().each(function(elem) {
            this.threadWorker.addWorker(function(element) {
                element.setStyle({
                    display: ''
                });
                element.childElements().each(function(element, index) {
                    if(!this.options.elements.include(index)) {
                        return;
                    }
                    while(element && element.down && element.down()) {
                        element = element.down();
                    }
                }.bind(this));
            }.bind(this, elem));
        }.bind(this));
        this.threadWorker.start();
    },
    onUpdate: function(editor) {
        editor.value = editor.input.value;
        this._search();
    },
    onShow: function(editor) {
        if(Object.isUndefined(editor.value)) return;
        editor.setValue(editor.value);
    },
    onAbort: function(editor) {
        editor.value = '';
        this._search();
    },
    _search: function() {
        this.threadWorker.stop();
        this.threadWorker.removeAllWorker();

        var regex = this._getRegex();
        this.options.startSearch(this);

        var worker = [];
        worker.push(function() {
            this.stats.searched = 0;
            this.stats.total = this._getRows().length;
        }.bind(this));
        this._getRows().each(function(elem) {
            worker.push(function(elem, regex) {
                var i = 0;
                elem.setStyle({
                    display: ''
                });
                elem.childElements().each(function(element, index) {
                    if(!this.options.elements.include(index)) {
                        return;
                    }
                    while(element && element.down && element.down()) {
                        element = element.down();
                    }
                    if(!regex[i].match(element.innerHTML)) {
                        elem.setStyle({
                            display: 'none'
                        });
                    }
                    i++;
                }.bind(this));
                ++this.stats.searched;
                this.options.updateSearch(this);
            }.bind(this, elem, regex));
        }.bind(this));
        worker.push(this.options.endSearch.bind(this, this));
        
        this.threadWorker.addWorker(worker);
        this.threadWorker.start();
        /*this._getRows().each(function(elem) {
            var i = 0;
            elem.setStyle({
                display: ''
            });
            elem.childElements().each(function(element, index) {
                if(!this.options.elements.include(index)) {
                    return;
                }
                while(element && element.down && element.down()) {
                    element = element.down();
                }
                if(!regex[i].match(element.innerHTML)) {
                    elem.setStyle({
                        display: 'none'
                    });
                }
                i++;
            }.bind(this));
        }.bind(this));*/
        //this.options.endSearch(this);
    },
    _getRows: function() {
        var grp = (this.options.useTHead) ? 'thead' : 'tbody', rows = this.element.select(grp)[0].childElements();
        if(grp == 'tbody') {
            rows.shift();
        }
        return rows;
    },
    _getRegex: function() {
        var regex = [];
        this.editors.each(function(editor) {
            regex.push(new RegExp("^"+RegExp.escape(editor.value || '').replace(/\\\*/, '.+')));
        }.bind(this));
        return regex;
    }
});

Nikmedia.InlineEditor = Class.create({
    initialize: function(element,options) {
        this.element = $(element);

        this.options = {
            filter: new RegExp(''),
            inputStyle: {
                width: '150px'
            },
            onShow: function() {},
            onAccept: function() {},
            onCancel: function() {},
            onAbort: function() {},
            onUpdate: function() {}
        };

        this.tmpText = '';

        Object.extend(this.options, options || {});

        this.element.observe("click", this.actionPerformed.bindAsEventListener(this));

        this.input = null;
    },
    actionPerformed: function(e) {
        var event = Event.extend(e);
        if(event.element() == this.element && event.type == "click") {
            this.tmpText = this.element.innerHTML;
            this.element.innerHTML = '';

            this.input = new Element("input")
                            .setStyle(this.options.inputStyle)
                            //.observe("keypress",this.actionPerformed.bindAsEventListener(this))
                            .observe("keydown",this.actionPerformed.bindAsEventListener(this));

            this.element.insert(this.input);
            this.input.focus();

            this.input.observe("blur", this.actionPerformed.bind(this));
            this.options.onShow(this);
        } else if(event.element() == this.input && event.type == "keydown") {
            if(event.keyCode == Event.KEY_ESC) {
                this.element.innerHTML = this.tmpText;
                this.options.onUpdate(this);
                this.options.onCancel(this);
                this.options.onAbort(this);
            } else if(event.keyCode == Event.KEY_RETURN) {
                if(this.options.onAccept(this) !== false) {
                    this.element.innerHTML = this.input.value;
                }
            } else {
                window.setTimeout(function(){
                    this.input.value = this.input.value.replace(this.options.filter,'');
                    this.options.onUpdate(this);
                }.bind(this),10);
            }
        } else if(event.element() == this.input && event.type == "blur") {
            this.element.innerHTML = this.tmpText;
            this.options.onCancel(this);
        }
    },
    setValue: function(value) {
        this.input.value = value;
    }
});

Nikmedia.ThreadWorker = Class.create({
    initialize: function(worker, options) {
        this.options = {
            numberOfThreads: 5
        };
        Object.extend(this.options, options);
        this.worker = $A(worker || []);
        this.running = false;
        this.working = 0;
    },
    addWorker: function(worker) {
        if(Object.isArray(worker)) {
            this.worker = [this.worker, $A(worker)].flatten();
        } else {
            this.worker.push(worker);
        }
        this._startWorker();
    },
    removeAllWorker: function() {
        if(this.running) {
            throw "worker can't remove while running";
        }
        this.worker = [];
    },
    start: function() {
        this.running = true;
        this.working = 0;
        this._startWorker();
    },
    stop: function() {
        this.running = false;
    },
    _startWorker: function() {
        if(!this.running || this.working >= this.options.numberOfThreads) {
            return;
        }
        for(var i=this.working;i<this.options.numberOfThreads;++i) {
            var worker = this.worker.shift();
            if(!worker) {
                return;
            }
            ++this.working;
            this._run.bind(this, worker).defer();
        }
    },
    _run: function(worker) {
        worker();
        --this.working;
        this._startWorker();
    }
});

Nikmedia.Benchmark = Class.create({
    initialize: function() {
        this.start = this._getMilliseconds();
        this.last = this.start;
    },
    getDiff: function(inSeconds) {
        var div = (inSeconds || false) ? 1000 : 1;
        return (this._getMilliseconds() - this.start) / div;
    },
    getDiffToLast: function(inSeconds) {
        var div = (inSeconds || false) ? 1000 : 1;
        var millis = (this._getMilliseconds() - this.last) / div;
        this.last = this._getMilliseconds();
        return millis;
    },
    _getMilliseconds: function() {
        var date = new Date(), millis = Date.parse(date);
        if(millis % 1000 == 0) {
            millis += date.getMilliseconds();
        }
        return millis;
    }
});

Element.addMethods({
    removeAll: function(element) {
        element = $(element);
        element.childElements().invoke('remove');
    },
    fireNativeEvent: function(element, eventType, eventArgs) {
        element = $(element);
        var event;
        if (document.createEvent) {
            event = document.createEvent("HTMLEvents");
            event.initEvent(eventType, true, true);
        } else {
            event = document.createEventObject();
            event.eventType = 'on'+eventType;
        }
        Object.extend(event, eventArgs || {});
        if (document.createEvent) {
            element.dispatchEvent(event);
        } else {
            element.fireEvent(event.eventType, event);
        }
    }
});


Nikmedia.AjaxTableDataSource = {}
Nikmedia.AjaxTableDataSource.JSON = Class.create({
    initialize: function(url, options) {
        this.url = url;
        this.page = 1;
        this.cache = [];
        this.options = Object.extend({
            onAjaxStart: function() {},
            onAjaxEnd: function() {},
            onPageUpdate: function() {}
        }, options || {});
    },
    getData: function() {
        if(!this.cache[this.page]) {
            this.options.onAjaxStart(this);
            new Ajax.Request(this.url, {
                asynchronous: false,
                parameters: {
                    page: this.page
                },
                onSuccess: function(t) {
                    this.cache[this.page] = t.responseJSON;
                }.bind(this)
            });
            this.options.onAjaxEnd(this);
        }
        return this.cache[this.page];
    },
    setPage: function(page) {
        var meta = this.getMeta(), max = Math.ceil(meta.total/meta.eps);
        if(page < 1)
            page = 1;
        if(page > max)
            page = max;
        this.page = page;
        this.options.onPageUpdate(this);
    },
    getPage: function() {
        return this.page;
    },
    getMeta: function() {
        return this.getData().meta;
    }
});

Nikmedia.AjaxTable = Class.create({
    initialize: function(element, options) {
        this.element = element = $(element);

        if(element.tagName.toLowerCase() != 'table') throw 'element must be a table';

        this.options = {
            dataSource: null,
            navPrev: null,
            navNext: null,
            styles: [],
            attributes: [],
            onInit: function() {},
            onBuild: function() {}
        };
        Object.extend(this.options, options);

        if(Object.isElement(this.options.navPrev)) {
            this.options.navPrev.observe('click', this.navigate.bind(this, -1));
        }
        if(Object.isElement(this.options.navNext)) {
            this.options.navNext.observe('click', this.navigate.bind(this, 1));
        }

        this._init();
    },
    _init: function() {
        this.element.down().show();
        this.element.down().removeAll();
        this.options.dataSource.getData().data.each(this._addRow.bind(this));
        this.navigate(0);
        this.options.onInit(this);
    },
    build: function() {
        this.options.dataSource.getData.bind(this.options.dataSource).defer();
        this.element.hide();
        this.element.down().removeAll();
        this.options.dataSource.getData().data.each(this._addRow.bind(this));
        this.element.appear({
            duration: 0.25,
            queue: 'end',
            afterFinish: function() {
                this.options.onBuild(this);
            }.bind(this)
        });
    },
    _addRow: function(row) {
        var tr = new Element('tr');
        row.each(function(cell, i) {
            var td = new Element('td');
            if(Object.isString(cell)) {
                td.update(cell)
                  .setStyle(this.options.styles[i] || {})
                  .writeAttribute(this.options.attributes[i] || {});
            } else {
                td.update(cell.data)
                  .setStyle(Object.extend(this.options.styles[i] || {}, cell.style || {}))
                  .writeAttribute(Object.extend(this.options.attributes[i] || {}, cell.attributes || {}));
            }
            tr.insert(td);
        }.bind(this));
        this.element.down().insert(tr);
    },
    navigate: function(align) {
        this.options.dataSource.setPage(this.options.dataSource.getPage()+align);
        if(Object.isElement(this.options.navPrev)) {
            this.options.navPrev.setStyle({
                visibility: (this.options.dataSource.getPage() == 1) ? 'hidden' : 'visible'
            })
        }
        if(Object.isElement(this.options.navNext)) {
            var meta = this.options.dataSource.getMeta();
            this.options.navNext.setStyle({
                visibility: (this.options.dataSource.getPage() == Math.ceil(meta.total/meta.eps)) ? 'hidden' : 'visible'
            })
        }
        if(align != 0)
            this.build();
    }
});
function deaktiviere(item)
{	  
	  var but = "but" + item;
	  var myform = document.getElementById("form" + item);
	  document.getElementById(but).value = "Bitte warten....";	
      document.getElementById(but).disabled = true;
      myform.submit();
      return false;
	 
}
