/*
 * InPlaceEditor extensions.
 */

Ajax.InPlaceEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
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.__leaveEditMode = Ajax.InPlaceEditor.prototype.leaveEditMode;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {
    initialize: function(element, url, options){
        this.__initialize(element,url,options);
        this.setOptions(options);
        this._checkEmpty();
        var self = this;
        this.element.click_from_outer_content = function(){
            self.enterEditMode(window.event);
        };
        if(this.options.default_opened_with){
            this.flag = {};
            this.flag.fld_focused = false;
            this.defaultOpened();
        }
    },
    defaultOpened: function(){
        this.enterEditMode(window.event);
        this._controls.editor.blur();
        this._controls.editor.value = this.options.default_opened_with;
        this._controls.editor.style.fontSize = '12px';
        this._controls.editor.style.color = '#ccc';
        var self = this;
        this._controls.editor.onfocus = function(){
            self._controls.editor.value = '';
            self._controls.editor.style.color = '#000';
            self.flag.fld_focused = true;
            self._controls.editor.onfocus = null;
        }
        Event.observe(this._controls['ok'], 'click', function(){
            if(!self.flag.fld_focused)
                self._controls.editor.value = '';
        });
    },
    setOptions: function(options){
        this.options = Object.extend(Object.extend(this.options,{
            emptyText: 'クリックして編集',
            emptyClassName: 'inplaceeditor-empty'
        }),options||{});
        // 以下は拡張前に初期化されちゃうので、再度やる感じ
        if (this.options.externalControl)
            this.options.externalControl = $(this.options.externalControl);
        if (!this.options.externalControl)
            this.options.externalControlOnly = false;
        this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
    },
    _checkEmpty: function(){
        if(this.element.innerHTML.length == 0){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},[ Builder.node('img',{ src:"/images/partial/edit.gif" }), this.options.emptyText]));
            this._oldInnerHTML = this.element.innerHTML;
        }
    },
    leaveEditMode: function(){
        //ほんとはonLeaveEditModeでやりたかった。。
        this.__leaveEditMode();
        this._checkEmpty();
    },
    getText: function(){
//        var empty_childs = this.element.getElementsByClassName(this.options.emptyClassName);
        // Safari3, Fx3, NodeList -> Array
        var empty_childs = $A(this.element.getElementsByClassName(this.options.emptyClassName));
        if(empty_childs && empty_childs.length > 0){
            empty_childs.each(function(child){
                this.element.removeChild(child);
            }.bind(this));
        }
        if(this.options.replaceBr){
            return this.__getText().replace(/<(?:br|BR) ?\/?>/g, "\n");
        }else{
            return this.__getText();
        }
    },
    createEditField: function() {
        var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
        var fld;

        if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
            fld = document.createElement('input');
            fld.type = 'text';
            var size = this.options.size || this.options.cols || 0;
            if (0 < size) fld.size = size;
        } else {
            fld = document.createElement('textarea');
            fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
            fld.cols = this.options.cols || 40;
        }
        fld.name = this.options.paramName;
        fld.value = text; // No HTML breaks conversion anymorebr
        fld.className = 'editor_field';
        if (this.options.submitOnBlur)
            fld.onblur = this._boundSubmitHandler;
        // text length limit description
        if (this.options.limit) {
            var word_num = (this.options.limit == fld.value.length) ? '0' : this.options.limit - fld.value.length
            var limit_container = Builder.node('p',{ id:'text-size-limit-container' },[ 'あと', Builder.node('span',{ id:"text-size-limit" }, word_num), '文字']);
            this._form.appendChild(limit_container);
            var limit = this.options.limit;
            var self = this;
            Event.observe(fld, 'keyup', function(){
                $('text-size-limit').innerHTML = limit - fld.value.length;
                if( (limit - fld.value.length) < 0 ){
                    $('text-size-limit').style.color = "red";
                } else {
                    $('text-size-limit').style.color = "#666";
                }
            }, 'false')
        }
        // tabkeyが押された後にクリック
        if(this.options.click_after_tabbed_with){
            Event.observe(fld, 'keydown', function(e){
                if(e.keyCode == 9){
                    e.returnValue = false;
                    if(e.preventDefault)
                        e.preventDefault();
                    $(self.options.click_after_tabbed_with).click_from_outer_content();
                    return false;
                }
            }, 'false');
            Event.observe(fld, 'keypress', function(e){
                if(e.keyCode == 9){
                    e.returnValue = false;
                    if(e.preventDefault)
                        e.preventDefault();
                    return false;
                }
            }, 'false');
        }
        this._controls.editor = fld;
        if (this.options.loadTextURL)
            this.loadExternalText();
        this._form.appendChild(this._controls.editor);
    },
    createForm: function(){
        // 一ページには一つしかin_place_editorを出現させないようにする
        $$('input.editor_ok_button').each(function(obj){obj.click()});
        if($$('.editor_ok_button').length > 0){
            this.__leaveEditMode();
            return false;
        }
        this.__createForm();
    },
    createControl: function(mode, handler, extraClasses) {
        var control = this.options[mode + 'Control'];
        var text = this.options[mode + 'Text'];
        if ('button' == control) {
            var btn = document.createElement('input');
            btn.type = 'submit';
            btn.value = text;
            btn.className = 'editor_' + mode + '_button';
            if ('cancel' == mode){
                btn.onclick = this._boundCancelHandler;
            }else{
                if(this.options.limit){
                    var self = this;
                    btn.onclick = function(){
                        if(self._controls.editor.value.length > self.options.limit){
                            alert('入力内容が' + self.options.limit + '文字を超えています');
                            return false;
                        }
                    }
                }else{
                    var self = this;
                    btn.onclick = function(){
                        if(self.options.click_after_submit_with){
                            self._form.removeChild(self._controls[mode]);
                            $(self.options.click_after_submit_with).click_from_outer_content();
                            self.handleFormSubmission();
                        }
                    }
                }
            }
            this._form.appendChild(btn);
            this._controls[mode] = btn;
        } else if ('link' == control) {
            var link = document.createElement('a');
            //# -> javascript:void(0);
            link.href = 'javascript:void(0);';
            link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
            link.appendChild(document.createTextNode(text));
            link.className = 'editor_' + mode + '_link';
            if (extraClasses)
                link.className += ' ' + extraClasses;
            this._form.appendChild(link);
            this._controls[mode] = link;
        }
    }

});

Object.extend(Ajax.InPlaceEditor, {
    DefaultOptions: {
        ajaxOptions: { },
        autoRows: 3,                                // Use when multi-line w/ rows == 1
        cancelControl: 'link',                      // 'link'|'button'|false
        cancelText: '取消',
        clickToEditText: 'クリックして編集',
        externalControl: null,                      // id|elt
        externalControlOnly: false,
        fieldPostCreation: 'activate',              // 'activate'|'focus'|false
        formClassName: 'inplaceeditor-form',
        formId: null,                               // id|elt
        highlightColor: '#ffff99',
        highlightEndColor: '#ffffff',
        hoverClassName: '',
        htmlResponse: true,
        loadingClassName: 'inplaceeditor-loading',
        loadingText: 'Loading...',
        okControl: 'button',                        // 'link'|'button'|false
        okText: '保存',
        paramName: 'value',
        rows: 1,                                    // If 1 and multi-line, uses autoRows
        savingClassName: 'inplaceeditor-saving',
        savingText: '<img src="/images/shared/indicator.gif">',
        size: 0,
        stripLoadedTextTags: false,
        submitOnBlur: false,
        textAfterControls: '',
        textBeforeControls: '',
        textBetweenControls: '',
        replaceBr: true
    }
});
