/*
 * InPlaceEditor extension that adds a 'click to edit' text when the field is
 * empty.
 */
Ajax.InPlaceEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
Ajax.InPlaceEditor.prototype.__editField = Ajax.InPlaceEditor.prototype.editField;
Ajax.InPlaceEditor.prototype.__okButtonElement = Ajax.InPlaceEditor.prototype.okButtonElement;
Ajax.InPlaceEditor.prototype.__getText = Ajax.InPlaceEditor.prototype.getText;
Ajax.InPlaceEditor.prototype.__onComplete = Ajax.InPlaceEditor.prototype.onComplete;
Ajax.InPlaceEditor.prototype.__createForm = Ajax.InPlaceEditor.prototype.createForm;
Ajax.InPlaceEditor.prototype.__dispose = Ajax.InPlaceEditor.prototype.dispose;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {

    initialize: function(element, url, options){
        this.__initialize(element,url,options)
        this.setOptions(options);
        this._checkEmpty();
        this.counterLabel = Builder.node('span');
        this.counterContainer = Builder.node('span');
        this.counterValue = this.options.counter;
    },

    setOptions: function(options){
        this.options = Object.extend(Object.extend(this.options,{
            emptyText: 'click to edit...',
            emptyClassName: 'inplaceeditor-empty',
            counter: 0,
            counterText: 'characters left:'
        }),options||{});
    },

    _checkEmpty: function(){
        if( this.element.innerHTML.length == 0 ){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
        }
    },

    getText: function(){
        document.getElementsByClassName(this.options.emptyClassName,this.element).each(function(child){
            this.element.removeChild(child);
        }.bind(this));
        return this.__getText()
    },

    onComplete: function(transport){
        if (Element.visible('redbox')) Element.hide('redbox');
        if (Element.visible('greenbox')) Element.hide('greenbox');
        if(transport) {
            //var resp = eval(transport.getResponseHeader('X-JSON'));
            var resp = eval('('+transport.responseText+')');
	    // update error
            if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); window.scrollTo(0,0); }
            if (resp.infoMsg.length != 0) { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); window.scrollTo(0,0); }
	    // as header() can not send us real newlines, we have to replace %0A to <br>
	    //var content_repl = resp.content;
	    //var neu = content_repl.replace(/%0D%0A/ig, "<br />\n").replace(/%0A/ig, "<br />\n");
            Element.update(this.element, unescape(resp.content));
        }
        this._checkEmpty();
        this.__onComplete(transport);
    },

    createForm: function() {
        this.__createForm();
        if (this.options.counter > 0) {
            Element.update(this.counterLabel, this.options.counterText);
            this.form.appendChild(this.counterLabel);

            this.counterValue = this.options.counter - this.editField.value.length;
            Element.update(this.counterContainer, ''+this.counterValue);
            this.keyupListener = this.updateCounter.bindAsEventListener(this);
            Event.observe(this.editField, 'keyup', this.keyupListener);
            this.form.appendChild(this.counterContainer);
        }
    },

    updateCounter: function(Evt) {
        this.counterValue = this.options.counter - this.editField.value.length;
        if (this.counterValue >= 0) {
            Element.update(this.counterContainer, ''+this.counterValue);
            this.okButtonElement.disabled = false;
        }
        else {
            //this.editField.disabled = true;
            this.okButtonElement.disabled = true;
            Element.update(this.counterContainer, '<span style="color:#FF0000;">'+this.counterValue+'</span>');
        }
    },

    dispose: function() {
        Event.stopObserving(this.element, 'keyup', this.keyupListener);
        __dispose();
    }

});

/* InPlaceSelect extension */

Ajax.InPlaceSelect = Class.create();
Ajax.InPlaceSelect.prototype = {
  initialize:function(element,url,selectname,values,labels,options) {
    this.element = $(element);
    this.url = url;
    this.selectname = selectname;
    this.values = values;
    this.labels = labels;

    this.options = Object.extend({
      paramName: 'selected',
      highlightcolor: "#eabd36",
      highlightendcolor: "#D4DDE4",
      onFailure: function(transport) {
        alert("Error: " + transport.responseText.stripTags());
      },
      savingText: "Saving...",
      savingClassName: 'inplaceeditor-saving',
      clickToEditText: "Double-click to edit",
      cancelText: "cancel"
    }, options || {} );

    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }

    this.element.title = this.options.clickToEditText;

    this.ondblclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);

    Event.observe(this.element, 'click', this.ondblclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.ondblclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }

  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    Element.hide(this.element);
    Element.hide(this.options.externalControl);
    this.createControls();
    this.element.parentNode.insertBefore(this.menu, this.element);
    this.element.parentNode.insertBefore(this.cancelButton, this.element);
    return false;
  },
  createControls: function() {
    var options = new Array();
    for (var i=0;i<this.values.length;i++)
        options[i] = Builder.node('option', {value:this.values[i]}, this.labels[i]);
    this.menu = Builder.node('select', options);
    this.menu.onchange = this.onChange.bind(this);

//    this.menu.onblur = this.onCancel.bind(this);
//    this.menu.onmouseout = this.onCancel.bind(this);

    for (var i=0;i<this.values.length;i++)
      if (this.labels[i]==this.element.innerHTML) {
        this.menu.selectedIndex=i;
        continue;
      }
    this.cancelButton = Builder.node('button', { type:'button' }, this.options.cancelText);
    Element.addClassName(this.cancelButton, 'editor_cancel_button');
    this.cancelButton.onclick = this.onCancel.bind(this);
/*
    this.cancelButton = Builder.node('a', {href:"#"},this.options.cancelText);
    this.cancelButton.onclick = this.onCancel.bind(this);
*/
  },
  onCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onChange: function() {
    if (this.options.parameters) {
        var params = this.options.parameters + "&" + 'value' + "=" + this.values[this.menu.selectedIndex];
    }
    else {
        var params = 'value' + "=" + this.values[this.menu.selectedIndex];
    }
    this.onLoading();
//    new Ajax.Updater({success:this.element}, this.url, {parameters: params,
//      onComplete: this.onComplete.bind(this), onFailure: this.onFailure.bind(this)});
    new Ajax.Request(this.url, Object.extend({ parameters: params, onComplete: this.onComplete.bind(this), onFailure: this.onFailure.bind(this)}));
  },
  onLoading: function() {
    this.saving = true;
    this.removeControls();
    this.leaveHover();
    this.showSaving();
  },
  removeControls:function() {
    if(this.menu) {
      if (this.menu.parentNode) Element.remove(this.menu);
      this.menu = null;
    }
    if (this.cancelButton) {
      if (this.cancelButton.parentNode) Element.remove(this.cancelButton);
      this.cancelButton = null;
    }
  },
  showSaving:function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  onComplete: function(transport) {
    if (Element.visible('redbox')) Element.hide('redbox');
    if(transport) {
       //var resp = eval(transport.getResponseHeader('X-JSON'));
       var resp = eval('('+transport.responseText+')');
       if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); }
       Element.update(this.element, resp.content);
    }
    this.leaveEditMode();
    new Effect.Highlight(this.element, {startcolor: this.options.highlightcolor});
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  enterHover: function() {
    if (this.saving) return;
    this.element.style.backgroundColor = this.options.highlightcolor;
    if (this.effect) { this.effect.cancel(); }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    if (this.options.backgroundColor) {
      this.element.style.backgroundColor = this.oldBackground;
    }
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
    this.effect = new Effect.Highlight(this.element, {
      startcolor: this.options.highlightcolor,
      endcolor: this.options.highlightendcolor,
      restorecolor: this.originalBackground
    });
  },
  leaveEditMode:function(transport) {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeControls();
    this.leaveHover();
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
    Element.show(this.options.externalControl);
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
  }
}

/* Adding tag to list of tags */

function appendToTags(id) {
    var newid;
    var newLI = Builder.node('li');
    var delbtn = Builder.node('img', { src:'files/img/delete_button.gif'} );
    var tag = document.getElementById('newTag').value;
    delbtn.setAttribute('title', document.getElementsByTagName('li')[0].getAttribute('title'));

    if (tag != '') {

        document.getElementById('newTag').value = '';
        // inserte mit Ajax
        new Ajax.Request(
            'index.php',
            {
                asynchronous: true,
                post: true,
                postBody: 'ebdAction=ajaxAction&aAction=newEntryTag&ebdEntryID='+id+'&ebdTag='+escape(tag),
                onSuccess: function(t) {
                    //var resp = eval(t.getResponseHeader('X-JSON'));
                    var resp = eval('('+t.responseText+')');
                    if (resp.infoMsg.length != 0) { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); }
                    if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); window.scrollTo(0,0); }
                    else {
                        newid = resp.content;
                        newLI.setAttribute('id', 'tag_'+newid);
                        delbtn.setAttribute('onclick' , "removeTag('" + newid + "', '" + id + "')");

                        // baue knoten
                        var tagtext = Builder._text(' '+tag);
                        newLI.appendChild(delbtn, newLI);
                        newLI.appendChild(tagtext);
                        // haenge an
                        document.getElementById('tagList').appendChild(newLI);
                        // baue neu auf
                        Sortable.create(
                            'tagList',
                            {
                                onUpdate: function() {
                                    new Ajax.Request(
                                        'index.php',
                                        {
                                            asynchronous: true,
                                            post:true,
                                            postBody:'ebdAction=ajaxAction&aAction=updateEntryTags&ebdEntryID=<?=$ebdEntry->getID(); ?>&'+Sortable.serialize('tagList', { tag:'li', name:'tagList' })
                                        }
                                     );
                                }
                            }
                        );
                    }
                }
            }
        );

    }
}

function removeTag(value, id) {
    new Ajax.Request(
        'index.php',
        {
            asynchronous:true,
            post:true,
            postBody:'ebdAction=ajaxAction&aAction=removeEntryTag&ebdTagID='+escape(value),
            onSuccess: function(t) { }
        }
    );
    document.getElementById('tagList').removeChild(document.getElementById('tag_'+value));
        Sortable.create(
            'tagList',
            {
                onUpdate: function() {
                    new Ajax.Request(
                        'index.php',
                        {
                            asynchronous: true,
                            post:true,
                            postBody:'ebdAction=ajaxAction&aAction=updateEntryTags&ebdEntryID='+id+'&'+Sortable.serialize('tagList', { tag:'li', name:'tagList' })
                        }
                     );
                }
            }
        );
}

function passwordChange() {
    Element.hide('redbox');
    Element.hide('greenbox');
    var opw = document.getElementById('oldEbdPassword').value;
    var opwn = document.getElementById('oldEbdPassword').name;
    var npw = document.getElementById('newEbdPassword').value;
    var npwn = document.getElementById('newEbdPassword').name;
    var npw2 = document.getElementById('newEbdPasswordConfirm').value;
    var npwn2 = document.getElementById('newEbdPasswordConfirm').name;
    var pwdata = escape(opwn) + '=' + escape(opw) +'&' + escape(npwn) + '=' + escape(npw) +'&' + escape(npwn2) + '=' + escape(npw2);
    var postData = 'ebdAction=ajaxAction&aAction=changePassword&'+pwdata;
    new Ajax.Request(
        'index.php',
        {
            asynchronous:true,
            post:true,
            postBody:postData,
            onSuccess: function(t) {
                //var resp = eval(t.getResponseHeader('X-JSON'));
                var resp = eval('('+t.responseText+')');
                if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); }
                else { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); }
                document.getElementById('oldEbdPassword').value = '';
                document.getElementById('newEbdPassword').value = '';
                document.getElementById('newEbdPasswordConfirm').value = '';
                window.scrollTo(0,0);
            }
        }
    );
}

function confirmContact(contact_id) {
    Element.hide('redbox');
    Element.hide('greenbox');
    new Ajax.Request(
        'index.php',
        {
            asynchronous:true,
            post:true,
            postBody:'ebdAction=ajaxAction&aAction=contactsData&do=confirm&ebdContactId='+escape(contact_id),
            onSuccess: function(t) {
                //var resp = eval(t.getResponseHeader('X-JSON'));
                var resp = eval('('+t.responseText+')');
                if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); }
                else { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); }
                Element.hide('confirmButton_'+ contact_id);
                Element.update('contact_status_'+contact_id, resp.content);
                Element.show('contactPublic'+contact_id);
                window.scrollTo(0,0);
            }
        }
    );
}

function rejectContact(contact_id) {
    Element.hide('greenbox');
    Element.hide('redbox');
    new Ajax.Request(
        'index.php',
        {
            asynchronous:true,
            post:true,
            postBody:'ebdAction=ajaxAction&aAction=contactsData&do=reject&ebdContactId='+escape(contact_id),
            onSuccess: function(t) {
                //var resp = eval(t.getResponseHeader('X-JSON'));
                var resp = eval('('+t.responseText+')');
                if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); }
                else { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); }
                Element.remove('contacts'+contact_id);
            }
        }
    );
}

function contactTogglePublic(cid, eid) {
    Element.hide('greenbox');
    Element.hide('redbox');
    new Ajax.Request(
        'index.php',
        {
            asynchronous:true,
            post:true,
            postBody:'ebdAction=ajaxAction&aAction=contactsData&do=togglePublic&ebdContactId='+escape(cid)+'&entryNumber='+escape(eid),
            onSuccess: function(t) {
                //var resp = eval(t.getResponseHeader('X-JSON'));
                var resp = eval(t.responseText);
                if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); }
                else { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); }
            }
        }
    );
}

Ajax.InPlacePhoneEditor = Class.create();
Ajax.InPlacePhoneEditor.defaultHighlightColor = "#eabd36";
Ajax.InPlacePhoneEditor.prototype = {
  initialize: function(element, url, options) {
    this.url = url;
    this.element = $(element);

    this.options = Object.extend({
      okButton: true,
      okText: "ok",
      cancelLink: true,
      cancelText: "cancel",
      savingText: "Saving...",
      clickToEditText: "Click to edit",
      okText: "ok",
      onComplete: function(transport, element) {
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      },
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      loadingText: 'Loading...',
      savingClassName: 'inplaceeditor-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'inplaceeditor-form',
      highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
      highlightendcolor: "#D4DDE4",
      externalControl: null,
      submitOnBlur: false,
      ajaxOptions: {},
      evalScripts: false
    }, options || {});

    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplaceeditor";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }

    if (this.options.externalControl) {
      this.options.externalControl = $(this.options.externalControl);
    }

    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }

    this.element.title = this.options.clickToEditText;

    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'click', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    if (this.options.externalControl) {
      Element.hide(this.options.externalControl);
    }
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField3);
    // stop the event to avoid a page refresh in Safari
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createEditField();

    if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }

    if (this.options.okButton) {

      okButton = Builder.node('button', { type:'submit' }, this.options.okText);
      Element.addClassName(okButton, 'editor_ok_button');
      okButton.onclick = this.onSubmit.bind(this);
      this.form.appendChild(okButton);
    }

    if (this.options.cancelLink) {
      cancelLink = Builder.node('button', { type:'button' }, this.options.cancelText);
      Element.addClassName(cancelLink, 'editor_cancel_button');
      cancelLink.onclick = this.onclickCancel.bind(this);
      this.form.appendChild(cancelLink);
    }
  },
  hasHTMLLineBreaks: function(string) {
    if (!this.options.handleLineBreaks) return false;
    return string.match(/<br/i) || string.match(/<p>/i);
  },
  convertHTMLLineBreaks: function(string) {
    return string.replace(/<br>/gi, "").replace(/<br\/>/gi, "").replace(/<\/p>/gi, "").replace(/<p>/gi, "");
  },
  createEditField: function() {
    var text;
    if(this.options.loadTextURL) {
      text = this.options.loadingText;
    } else {
      text = this.getText();
    }

    var obj = this;

    if (!this.hasHTMLLineBreaks(text)) {
        var parts = Array();
        if (text == '') {
            parts[0] = '';
            parts[1] = '';
            parts[2] = '';
        }
        else {
            parts = text.split('-');
        }

        var plus = Builder._text('+');
        var minus = Builder._text(' - ');
        var minus2 = Builder._text(' - ');

        var textField1 = Builder.node('input', { type:'text', name:'value1', value:parts[0].substr(1) });
        Element.addClassName(textField1, 'phonefax1');
        textField1.style.backgroundColor = this.options.highlightcolor;
        var textField2 = Builder.node('input', { type:'text', name:'value2', value:parts[1] } );
        Element.addClassName(textField2, 'phonefax2');
        textField2.style.backgroundColor = this.options.highlightcolor;
        var textField3 = Builder.node('input', { type:'text', name:'value3', value:parts[2] } );
        Element.addClassName(textField3, 'phonefax3');
        textField3.style.backgroundColor = this.options.highlightcolor;


      if (this.options.submitOnBlur) {
        textField1.onblur = this.onSubmit.bind(this);
        textField2.onblur = this.onSubmit.bind(this);
        textField3.onblur = this.onSubmit.bind(this);
        }
      this.editField1 = textField1;
      this.editField2 = textField2;
      this.editField3 = textField3;

    if(this.options.loadTextURL) {
      this.loadExternalText();
    }
    this.form.appendChild(plus);
    this.form.appendChild(this.editField1);
    this.form.appendChild(minus);
    this.form.appendChild(this.editField2);
    this.form.appendChild(minus2);
    this.form.appendChild(this.editField3);
    }

  },
  getText: function() {
    return this.element.innerHTML;
  },
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onLoadedExternalText: function(transport) {
    Element.removeClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = false;
    this.editField.value = transport.responseText.stripTags();
    Field.scrollFreeActivate(this.editField);
  },
  onclickCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    var form = this.form;
    var value1 = this.editField1.value;
    var value2 = this.editField2.value;
    var value3 = this.editField3.value;


    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();

    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value1, value2, value3),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true,
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null },
        this.url, Object.extend({
          parameters: this.options.callback(form, value1, value2, value3),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    this.element.style.backgroundColor = this.options.highlightcolor;
    if (this.effect) {
      this.effect.cancel();
    }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    if (this.options.backgroundColor) {
      this.element.style.backgroundColor = this.oldBackground;
    }
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
    this.effect = new Effect.Highlight(this.element, {
      startcolor: this.options.highlightcolor,
      endcolor: this.options.highlightendcolor,
      restorecolor: this.originalBackground
    });
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
    if (this.options.externalControl) {
      Element.show(this.options.externalControl);
    }
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
    this.onLeaveEditMode();
  },
  onComplete: function(transport) {
    this.leaveEditMode();
    this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {},
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    Event.stopObserving(this.element, 'click', this.onclickListener);
    Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};

Ajax.InPlacePhoneEditor.prototype.__initialize = Ajax.InPlacePhoneEditor.prototype.initialize;
Ajax.InPlacePhoneEditor.prototype.__getText = Ajax.InPlacePhoneEditor.prototype.getText;
Ajax.InPlacePhoneEditor.prototype.__onComplete = Ajax.InPlacePhoneEditor.prototype.onComplete;
Ajax.InPlacePhoneEditor.prototype = Object.extend(Ajax.InPlacePhoneEditor.prototype, {

    initialize: function(element, url, options){
        this.__initialize(element,url,options)
        this.setOptions(options);
        this._checkEmpty();
    },

    setOptions: function(options){
        this.options = Object.extend(Object.extend(this.options,{
            emptyText: 'click to edit...',
            emptyClassName: 'inplaceeditor-empty'
        }),options||{});
    },

    _checkEmpty: function(){
        if( this.element.innerHTML.length == 0 ){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
        }
    },

    getText: function(){
        document.getElementsByClassName(this.options.emptyClassName,this.element).each(function(child){
            this.element.removeChild(child);
        }.bind(this));
        return this.__getText();
    },

    onComplete: function(transport){
        if (Element.visible('redbox')) Element.hide('redbox');
        if (Element.visible('greenbox')) Element.hide('greenbox');
        if(transport) {
            //var resp = eval(transport.getResponseHeader('X-JSON'));
            var resp = eval('('+transport.responseText+')');
	    // update error
            if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); window.scrollTo(0,0); }
            if (resp.infoMsg.length != 0) { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); window.scrollTo(0,0); }
	    // as header() can not send us real newlines, we have to replace %0A to <br>
	    var content_repl = resp.content;
	    var neu = content_repl.replace(/%0A/ig, "<br>\n");
            Element.update(this.element, neu);
        }
        this._checkEmpty();
        this.__onComplete(transport);
    }
});



Effect.BlindUpDown = function(elementName) {

    element = $(elementName);
    if (element.style.display != 'none')
    {
      Element.hide(element); //new Effect.Shrink(element);
      Element.hide(elementName+'TipHide');
      Element.show(elementName+'TipShow');
    }
    else
    {
      Element.show(element); //new Effect.Grow(element);
      Element.show(elementName+'TipHide');
      Element.hide(elementName+'TipShow');
    }
}


Ajax.InPlaceCheckbox = Class.create();
Ajax.InPlaceCheckbox.defaultHighlightColor = "#eabd36";
Ajax.InPlaceCheckbox.prototype = {
  initialize: function(element, url, options, values, labels) {
    this.url = url;
    this.element = $(element);
    this.values = values;
    this.labels = labels;

    this.options = Object.extend({
      okButton: true,
      okText: "ok",
      cancelLink: true,
      cancelText: "cancel",
      savingText: "Saving...",
      clickToEditText: "Click to edit",
      okText: "ok",
      onComplete: function(transport, element) {
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      },
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      loadingText: 'Loading...',
      savingClassName: 'inplaceeditor-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'inplaceeditor-form',
      highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
      highlightendcolor: "#D4DDE4",
      externalControl: null,
      submitOnBlur: false,
      ajaxOptions: {},
      evalScripts: false
    }, options || {});

    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplacecheckbox";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }

    if (this.options.externalControl) {
      this.options.externalControl = $(this.options.externalControl);
    }

    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }

    this.element.title = this.options.clickToEditText;

    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'click', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    if (this.options.externalControl) {
      Element.hide(this.options.externalControl);
    }
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    // stop the event to avoid a page refresh in Safari
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createCheckboxes();
    var br = document.createElement("br");
    this.form.appendChild(br);

    if (this.options.okButton) {

      okButton = Builder.node('button', { type:'button' }, this.options.okText);
      Element.addClassName(okButton, 'editor_ok_button');
      okButton.onclick = this.onSubmit.bind(this);
      this.form.appendChild(okButton);
    }

    if (this.options.cancelLink) {
      cancelLink = Builder.node('button', { type:'button' }, this.options.cancelText);
      Element.addClassName(cancelLink, 'editor_cancel_button');
      cancelLink.onclick = this.onclickCancel.bind(this);
      this.form.appendChild(cancelLink);
    }
  },
  createCheckboxes: function() {
    _text = this.getText();
    var parts = Array();
    if (_text == '') parts[0] = '';
    else parts = _text.split(', ');

    /*var table = document.createElement('table'); //Builder.node('table');

    for (var i = 0; i < this.values.length; i++) {
        if (i % 3 == 0) {
            var tr = Builder.node('tr');
        }
        td = Builder.node('td');
        tmp = document.createElement('input');
        tmp.type = 'checkbox';
        tmp.name = 'ebdCountriesIn[]';
        tmp.value = this.values[i];
        tmp.className = 'inputcheckbox';
        tmp = Builder.node('input', {className: 'inputcheckbox', type:'checkbox', name:'ebdCountriesIn[]', value:this.values[i] });
        //tmp.addClassName('inputcheckbox');
        //tmp2 = document.createTextNode(' '+this.labels[i]);
        tmp2 = Builder._text(' '+this.labels[i]);
        for (var j = 0; j < parts.length; j++) {
            if (parts[j] == this.labels[i]) tmp.checked = true;
        }
        td.appendChild(tmp);
        td.appendChild(tmp2);
        tr.appendChild(td);
        if (i % 3 == 0) {
            table.appendChild(tr);
        }
    }*/

    for (var i = 0; i < this.values.length; i++) {

        var check = false;
        for (var j = 0; j < parts.length; j++) {
            if (parts[j] == this.labels[i]) {
                check = true;
            }
        }
        if (check) this.form.appendChild(Builder.node('input', {className: 'inputcheckbox', type:'checkbox', name:'ebdCountriesIn[]', value:this.values[i], checked:true }));
        else this.form.appendChild(Builder.node('input', {className: 'inputcheckbox', type:'checkbox', name:'ebdCountriesIn[]', value:this.values[i] }));
        this.form.appendChild(Builder._text(' '+this.labels[i]));
        this.form.appendChild(document.createElement('br'));
    }

    /*this.form.appendChild(table);
    if (this.form.hasChildNodes()) {
        var nodes = this.form.childNodes;
        alert(nodes[0].nodeName);
        alert(nodes[0].firstChild.firstChild.firstChild.getAttribute('className'));
    }*/
  },
  getText: function() {
    return this.element.innerHTML;
  },
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onLoadedExternalText: function(transport) {
    Element.removeClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = false;
    this.editField.value = transport.responseText.stripTags();
    Field.scrollFreeActivate(this.editField);
  },
  onclickCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    var formToDo = this.form;
    var value = this.form.ebdCountriesIn;
    query = this.options.callback(formToDo);

    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();

    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: query,
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true,
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null },
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    this.element.style.backgroundColor = this.options.highlightcolor;
    if (this.effect) {
      this.effect.cancel();
    }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    if (this.options.backgroundColor) {
      this.element.style.backgroundColor = this.oldBackground;
    }
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
    this.effect = new Effect.Highlight(this.element, {
      startcolor: this.options.highlightcolor,
      endcolor: this.options.highlightendcolor,
      restorecolor: this.originalBackground
    });
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
    if (this.options.externalControl) {
      Element.show(this.options.externalControl);
    }
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
    this.onLeaveEditMode();
  },
  onComplete: function(transport) {
    this.leaveEditMode();
    this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {},
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    Event.stopObserving(this.element, 'click', this.onclickListener);
    Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};

Ajax.InPlaceCheckbox.prototype.__initialize = Ajax.InPlaceCheckbox.prototype.initialize;
Ajax.InPlaceCheckbox.prototype.__getText = Ajax.InPlaceCheckbox.prototype.getText;
Ajax.InPlaceCheckbox.prototype.__onComplete = Ajax.InPlaceCheckbox.prototype.onComplete;
Ajax.InPlaceCheckbox.prototype = Object.extend(Ajax.InPlaceCheckbox.prototype, {

    initialize: function(element, url, options, values, labels){
        this.__initialize(element,url,options, values, labels)
        this.setOptions(options);
        this._checkEmpty();
    },

    setOptions: function(options){
        this.options = Object.extend(Object.extend(this.options,{
            emptyText: 'click to edit...',
            emptyClassName: 'inplaceeditor-empty'
        }),options||{});
    },

    _checkEmpty: function(){
        if( this.element.innerHTML.length == 0 ){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
        }
    },

    getText: function(){
        document.getElementsByClassName(this.options.emptyClassName,this.element).each(function(child){
            this.element.removeChild(child);
        }.bind(this));
        return this.__getText();
    },

    onComplete: function(transport){
        if (Element.visible('redbox')) Element.hide('redbox');
        if (Element.visible('greenbox')) Element.hide('greenbox');
        if(transport) {
            //var resp = eval(transport.getResponseHeader('X-JSON'));
            var resp = eval('('+transport.responseText+')');
	    // update error
            if (resp.errorMsg.length != 0) { Element.update('errorMessageContainer', resp.errorMsg); Element.show('redbox'); window.scrollTo(0,0); }
            if (resp.infoMsg.length != 0) { Element.update('infoMessageContainer', resp.infoMsg); Element.show('greenbox'); window.scrollTo(0,0); }
	    // as header() can not send us real newlines, we have to replace %0A to <br>
	    var content_repl = resp.content;
	    var neu = content_repl.replace(/%0A/ig, "<br>\n");
            Element.update(this.element, neu);
        }
        this._checkEmpty();
        this.__onComplete(transport);
    }
});

function textChange(toID) {
    var langDivs = document.getElementsByClassName('entrytextdiv');
    for (var i = 0; i < langDivs.length; i++) {
        if (langDivs[i].id == toID) Element.show(langDivs[i].id);
        else Element.hide(langDivs[i].id);
    }
}
