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;

   zi = zi + 5;
   
   $("matchings_" + obj).style.zIndex = zi;
   
   showz(obj);
}

function HideOnly(wind)
{
	if($("matchings_"+wind))
	{
		var body = $("matchings_"+wind).parentNode;
		for(var i=0;i<body.childNodes.length;i++)
		{
			if(body.childNodes[i].id == "matchings_"+wind)
				body.removeChild(body.childNodes[i]);
		}
	}
}
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"})
//		}});
		window.setTimeout("new Ajax.Updater('WindowLoad'+"+count+",'/ajax/windows/window_load.php',{method:'post',evalScripts:true,insertion:Insertion.bottom,parameters:{id:"+wind+"}});",250);
		count++;
	}
}
function ShowOnly(wind,sessid)
{
	if($("matchings_" + wind))
	{
		$("matchings_" + wind).style.display="block";
	}
	else
	{
        var body = $$('body').first();
        if(body) {
            body.insert({bottom:new Element('div', {
                id: 'WindowLoad'+count
            }).setStyle({
                height: 0,
                width: 0,
                position: 'absolute',
                top: 0,
                left: 0
            })});
        }
//		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.Request('/ajax/windows/window_load.php?PHPSESSID='+sessid, {
            method: 'post',
            parameters: {
                id: wind
            },
            onSuccess: function(element, t) {
                element.insert(t.responseText);
                t.responseText.evalScripts();
            }.bind(null, $('WindowLoad'+count))
        })
		//window.setTimeout("new Ajax.Updater('WindowLoad'+"+count+",'/ajax/windows/window_load.php?PHPSESSID="+sessid+"',{method:'post',evalScripts:true,insertion:Insertion.bottom,parameters:{id:"+wind+"}});",250);
		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; 

var Obm = {
    savePerson: function() {
        var data = $('obm-person-form').serialize(true);
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=savePerson', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveEducation: function(certificate, other, year) {
        var data = {
            'certificate' : certificate,
            'other'       : other,
            'year'        : year
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveEducation', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    removeEducation: function(certificate, other) {
        var data = {
            'certificate' : certificate,
            'other'       : other
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=removeEducation', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveApprenticeship: function(job, start, end, exam, employer, city, branch, branchOther) {
        var data = {
            'job'       : job,
            'start'     : start,
            'end'       : end,
            'exam'      : exam,
            'employer'  : employer,
            'city'      : city,
            'branch'    : branch,
            'branchOther' : branchOther
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveApprenticeship', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    removeApprenticeship: function(job, employer) {
        var data = {
            'job' : job,
            'employer' : employer
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=removeApprenticeship', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveStudy: function(program, branch, university, start, end, exam) {
        var data = {
            'program'   : program,
            'start'     : start,
            'end'       : end,
            'exam'      : exam,
            'branch'    : branch,
            'university' : university
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveStudy', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    removeStudy: function(program, branch, university) {
        var data = {
            'program' : program,
            'branch'  : branch,
            'university' : university
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=removeStudy', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveWork: function(start, end, employer, city, branch, branchOther, position, activities) {
        var data = {
            'position'  : position,
            'activities': activities,
            'employer'  : employer,
            'start'     : start,
            'end'       : end,
            'city'      : city,
            'branch'    : branch,
            'branchOther' : branchOther
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveWork', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    removeWork: function(position, activities, employer) {
        var data = {
            'position'  : position,
            'activities': activities,
            'employer'  : employer
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=removeWork', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveCertificate: function(certificate, date) {
        var data = {
            'certificate'  : certificate,
            'date'         : date
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveCertificate', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    removeCertificate: function(certificate) {
        var data = {
            'certificate'  : certificate
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=removeCertificate', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    setDone: function(step, done) {
        if(Object.isUndefined(done)) {
            done = true;
        } else {
            done = !!done;
        }
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=setDone', {
            method: 'post',
            asynchronous: false,
            parameters: {'step':step,'done':done ? 1 : 0},
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    removeAttachment: function(name) {
        var data = {
            'name'  : name
        };
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=removeAttachment', {
            method: 'post',
            asynchronous: false,
            parameters: data,
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    setNoOne: function(type, val) {
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=setNoOne', {
            method: 'post',
            asynchronous: false,
            parameters: {
                'type': type,
                'val' : val
            },
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveSkill: function(skill, points) {
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveSkill', {
            method: 'post',
            asynchronous: false,
            parameters: {
                'skill': skill,
                'points' : points
            },
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveSkillFreetext: function(skill, value) {
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveSkillFreetext', {
            method: 'post',
            asynchronous: false,
            parameters: {
                'skill': skill,
                'value' : value
            },
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveIntent: function(intent, intentOther) {
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveIntent', {
            method: 'post',
            asynchronous: false,
            parameters: {
                'intent': intent,
                'intentOther' : intentOther
            },
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    saveFocus: function(focus) {
        var success = false;
        new Ajax.Request('/ajax/obm.php?action=saveFocus', {
            method: 'post',
            asynchronous: false,
            parameters: {
                'focus': focus
            },
            onSuccess: function(t){
                success = true;
            }
        });

        return success;
    },
    warning: function(text) {
        alert(text);
    },
    info: function(text) {
        alert(text);
    },
    error: function(text) {
        alert(text);
    }
};


Obm.Uploader = Class.create({
    initialize: function(options) {
        this.options = options;

        this.form = this.options.form; //$('attachments-form');
        if(this.form.tagName.toLowerCase() != 'form') {
            throw 'element must be a form';
        }
        this.boundOnSubmit = this.onSubmit.bindAsEventListener(this);
        this.boundOnLoad   = this.onLoad.bindAsEventListener(this);
        this.boundOnClick  = function(event) {
            event.stop();
            this.form.upload();
        }.bind(this);

        this.form.observe('submit', this.boundOnSubmit);

        var name = this.buildIFrame();
        this.form.writeAttribute('target', name);

        this.form.upload = function() {
            this.onSubmit();
        }.bind(this);


        this.form.select('a.attachments-save').invoke('observe', 'click', this.boundOnClick);

        this.running = false;
    },
    buildIFrame: function() {
        this.iFrame = new Element('iframe', {
            name: 'obm-uploader-' + Obm.Uploader.index++,
            src: 'javascript:void(0);',
            style: 'display: none'
        });
        this.iFrame.observe('load', this.boundOnLoad);
        $$('body')[0].insert(this.iFrame);
        return this.iFrame.readAttribute('name');
    },
    onSubmit: function() {
        this.form.select('input').invoke('setStyle', {
            borderColor: '',
            backgroundColor: ''
        });
        if(!this.check()) {
            this.form.select('input').invoke('setStyle', {
                            borderColor: 'red',
                            backgroundColor: '#ffaaaa'
                        });
            Obm.error('Es wurden nicht alle Felder ausgefüllt');
            return;
        }
        this.insertRow();
        this.form.stopObserving('submit', this.boundOnSubmit);
        this.form.select('a.attachments-save').invoke('stopObserving', 'click', this.boundOnClick);
        this.startUploading();
        this.form.submit();
        new Obm.Uploader(this.options);
        this.form.reset();
    },
    onLoad: function(event) {
        var text = this.iFrame.contentDocument.body.innerHTML;
        if(/Dateiupload fehlgeschlagen/i.match(text)) {
            /*window.setTimeout(function() {
                this.row.fade({
                    afterFinish: function(effect) {
                        effect.element.remove();
                    }
                });
            }.bind(this), 5000);*/
        } else {
            this.row.down('td', 2).insert(new Element('a', {
                href: '#'
            }).update('Entfernen').observe('click', removeAttachment));
        }
        this.row.down('td', 1).update(text);
        this.stopUploading();
    },
    check: function() {
        /*var name = $$('input[name="name"]')[0].getValue(),
            type = $$('select[name="type"]')[0].getValue(),
            file = $$('input[name="file"]')[0].getValue();*/
        var data = this.form.serialize(true),
            /*name = data.name,
            type = data.type,*/
            file = this.form.select('input[type="file"]')[0].getValue();
        /*if(name == "Anhangname" || name == '') {
            return false;
        }
        if(type == '' || type == 0) {
            return false;
        }*/
        if(Object.isUndefined(file) || file == '') {
            return false;
        }
        return true;
    },
    insertRow: function() {
        var name = this.form.select('input[name="file"]')[0].getValue().replace(/^.*(?:\\|\/)([^\\/]+)$/, '$1'),
            type = this.form.select('input[name="type"]')[0].getValue();

        this.row = new Element('tr', {
            className: 'attachment-row ' + this.form.up('tr').readAttribute('rel')
        });
        this.row.addClassName('attachment-row ' + this.form.up('tr').readAttribute('rel'));
        this.row.insert(new Element('td').update(name));
        //this.row.insert(new Element('td').update(type));
        this.row.insert(new Element('td').update('Upload wird gestartet.'));
        this.row.insert(new Element('td'));

        var opt = {};
        opt[this.options.insert.position] = this.row;

        this.options.insert.element.insert(opt);
        /*$$('.attachments.master')[0].insert({
            before: this.row
        });*/
    },
    startUploading: function() {
        this.row.down('td', 1).addClassName('loading');
        this.running = true;
        this.i = 0;
        this.interval = window.setInterval(function() {
            if(!this.running) {
                return this;
            }
            this.row.down('td', 1).update('Uploading' + ('.'.times(this.i++%4)));
            return this;
        }.bind(this), 250);
    },
    stopUploading: function() {
        this.row.down('td', 1).removeClassName('loading');
        this.running = false;
        window.clearInterval(this.interval);
    }
});

Obm.Uploader.index = 0;

Element.addMethods('input', {
    inlineTitle: function(element, title) {
        title = title || element.value;
        var t = title;
        element.observe('click', function(event) {
            var e = event.element();
            if(e.value == t)
                e.value = '';
        }).observe('blur', function(event) {
            var e = event.element();
            if(e.value == '') {
                e.value = t;
            }
        });
        return element;
    }
});

Element.addMethods({
    fireNative: 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);
        }
    }
});

Element.addMethods('select', {
    getText: function(element) {
        var index = element.selectedIndex;
        return index >= 0 ? element.options[index].text : null;
    }
});

Element.addMethods('input', {
    'dateField': function(element, options) {
        options = Object.extend({
            classNames: ''
        }, options || {});
        var dayField, monthField, yearField, i, o, values;

        values = element.getValue().split(/\./);

        dayField = new Element('select', {
            className: options.classNames
        });
        //dayField.insert(new Element('option', {value: '00'}).update('TT'));
        for(i=1;i<=31;i++) {
            o = new Element('option', {value: i<10 ? "0" + i : i}).update(i<10 ? "0" + i : i);
            if(i == values[0]) {
                o.selected = true;
            }
            dayField.insert(o);
        }
        monthField = new Element('select', {
            className: options.classNames
        });
        //monthField.insert(new Element('option', {value: '00'}).update('MM'));
        for(i=1;i<=12;i++) {
            o = new Element('option', {value: i<10 ? "0" + i : i}).update(i<10 ? "0" + i : i);
            if(i == values[1]) {
                o.selected = true;
            }
            monthField.insert(o);
        }
        yearField = new Element('select', {
            className: options.classNames
        });
        //yearField.insert(new Element('option', {value: "0000"}).update("JJJJ"));
        for(i=(new Date()).getFullYear()-15;i>=(new Date()).getFullYear()-70;i--) {
            o = new Element('option', {value: i}).update(i);
            if(i == values[2]) {
                o.selected = true;
            }
            yearField.insert(o);
        }

        dayField.style.width = 'auto';
        monthField.style.width = 'auto';
        yearField.style.width = 'auto';

        element.insert({before:dayField}).insert({before:monthField}).insert({before:yearField}).hide();

        var change = function() {
            element.value = [dayField, monthField, yearField].invoke('getValue').join('.');
        };

        dayField.observe('change', change);
        monthField.observe('change', change);
        yearField.observe('change', change);

        change();
    }
});

Array.prototype.sum = function() {
    return (! this.length) ? 0 : this.slice(1).sum() +
      ((typeof this[0] == 'number') ? this[0] : 0);
};


/*var a = new Date();
a = new Date(a.getTime() +1000*60*60*24*365);
var json = Object.toJSON({namespace:{key1:'val1',key2:'val2'}});
document.cookie = 'cookieNamespace=' + escape(json) + '; expires='+a.toGMTString()+';';*/


var CookieNamespace = {
    _getObject: function() {
        if(Object.isUndefined(CookieNamespace._values)) {
            if(!document.cookie) {
                CookieNamespace._values = {};
            } else {
                var val = /cookieNamespace=([^;]+);/.exec(document.cookie);
                if(!val || val.length < 2) {
                    CookieNamespace._values = {};
                } else {
                    CookieNamespace._values = unescape(val[1]).evalJSON();
                }
            }
        }
        return CookieNamespace._values;
    },
    getNamespace: function(name) {
        var ns = CookieNamespace._getObject();
        if(Object.isUndefined(ns[name])) {
            return null;
        } else {
            return ns[name];
        }
    },
    setNamespace: function(namespace, values) {
        this._getObject();
        this._values[namespace] = values;
        this._save();
    },
    deleteNamespace: function(namespace) {
        this._getObject();
        delete this._values[namespace];
        this._save();
    },
    _save: function() {
        document.cookie = 'cookieNamespace=' + escape(Object.toJSON(this._getObject()))
                        + '; expires=' + (new Date((new Date()).getTime() +1000*60*60*24*365)).toGMTString() + ';';
    }
};


function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        radioGroup = $(el).name;
        el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
    var checked = (el ? $(el).getInputs('radio', radioGroup) : $$('input[name="' + radioGroup + '"]')).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

