/**
 * Pwr-on Co.
 *
 * @package    Pwron_Blog
 * @copyright  Copyright (c) 2011 Pwron Co.
 * @license    http://pwr-on.com/license.txt
 * @demo       http://pwr-on.com/blog 
 * @mail       info@pwr-on.com 
 */
Validation.addAllThese(
    [
    ['validate-tag', 'Please use letters, spase and comma.', function (v) {
        return Validation.get('IsEmpty').test(v) ||  /^[a-zA-ZА-Яа-яіїєІЇЄ0-9\ \,\-]+$/.test(v)
    }],
    ],
    [
    ['validate-urn', 'Please use letters, numbers and "-".', function (v) {
        return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z0-9\-]+$/.test(v)
    }],
    ]
    );        
        

/**
 * PwronLinkForm
 **/
PwronLinkForm = Class.create();
PwronLinkForm.prototype = new VarienForm();

PwronLinkForm.prototype.initialize = (function(super_initialize) {
    return function(formId, editor) {
        super_initialize.call(this, formId, false);
        this.editor=editor;
        if (this.form) {
            this.errorElement   = null;
            this.successElement = null;
            this.form.observe('submit', this.submit.bindAsEventListener(this))
        }
    };
})(VarienForm.prototype.initialize);

PwronLinkForm.prototype.setDefault = function(value) {
    $('link_description').setValue(value);
}
PwronLinkForm.prototype.clear = function() {
    if (this.errorElement) {
        var messageBox = this.form.select('ul.form-list')[0].previous('ul.messages');
        messageBox.remove();
        this.errorElement = null;
    }
    this.form.reset();//select('post_image_file')[0].value.empty();
}
PwronLinkForm.prototype.submit = function(e) {
    if(this.validator && this.validator.validate()) {
        var link = $('link_link').getValue();
        var desc = $('link_description').getValue();
        this.editor.editorPanel.insertLinkUrl(link, desc);
        this.editor.closeLinkDialog();
    }
    Event.stop(e);
    return false;
};


/**
 * PwronVideoForm
 **/
PwronVideoForm = Class.create();
PwronVideoForm.prototype = new VarienForm();

PwronVideoForm.prototype.initialize = (function(super_initialize) {
    return function(formId, editor) {
        super_initialize.call(this, formId, false);
        this.editor=editor;
        if (this.form) {
            this.errorElement   = null;
            this.successElement = null;
            this.form.observe('submit', this.submit.bindAsEventListener(this))
        }
    };
})(VarienForm.prototype.initialize);


PwronVideoForm.prototype.clear = function() {
    if (this.errorElement) {
        var messageBox = this.form.select('ul.form-list')[0].previous('ul.messages');
        messageBox.remove();
        this.errorElement = null;
    }
    this.form.reset();//select('post_image_file')[0].value.empty();
}
PwronVideoForm.prototype.submit = function(e) {
    if(this.validator && this.validator.validate()) {
        var link = $('video_link').getValue();
        this.editor.editorPanel.insertVideoUrl(link);
        this.editor.closeVideoDialog();
    }
    Event.stop(e);
    return false;
};

/**
 * PwronImageForm
 **/
PwronImageForm = Class.create();
PwronImageForm.prototype = new VarienForm();

PwronImageForm.prototype.initialize = (function(super_initialize) {
    return function(formId, editor) {
        super_initialize.call(this, formId, false);
        this.editor=editor;
        if (this.form) {
            this.errorElement   = null;
            this.successElement = null;
            this.form.observe('submit', this.submit.bindAsEventListener(this))
        }
    };
})(VarienForm.prototype.initialize);


PwronImageForm.prototype.clear = function() {
    if (this.errorElement) {
        var messageBox = this.form.select('ul.form-list')[0].previous('ul.messages');
        messageBox.remove();
        this.errorElement = null;
    }
    this.form.reset();//select('post_image_file')[0].value.empty();
}
PwronImageForm.prototype.submit = function(e) {
    if(this.validator && this.validator.validate()) {
        var url = this.form.getAttribute('action');
        var desc = $('image_description').getValue();
        var align = $('image_align').getValue();
        var req = new JsHttpRequest();
        var that = this;
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                if (req.responseJS.imgurl) {
                    that.editor.editorPanel.insertImageUrl(req.responseJS.imgurl, desc, align);
                    that.editor.closeImageDialog();
                } else {				
                    if (!that.errorElement) {
                        var fields = that.form.select('ul.form-list')[0];
                        Element.insert(fields, {
                            before: '<ul class="messages"><li class="error-msg"><ul><li><span></span></li></ul></li></ul>'
                        });
                        that.errorElement = fields.previous('ul.messages').select('span')[0];
                    }
                    that.errorElement.update(req.responseJS.error.join ? req.responseJS.error.join("<br />") : req.responseJS.error);
                }
            }
        }
        req.open(null, url, true);
        req.send( {
            value: document.getElementById('form-image')
        } );
    }
    Event.stop(e);
    return false;
};

/* 
 * ControlTextArea
 */
ControlTextArea = Class.create({
    initialize: function(textarea){
        this.onChangeTimeout = false;
        this.element = $(textarea);
    },
    doOnChange: function(event){
    },
    saveRange: function(){
        this.range = document.selection.createRange();
    },
    getValue: function(){
        return this.element.value;
    },
    getSelection: function(){
        if(!!document.selection) {
            return document.selection.createRange().text;
        }
        else if(!!this.element.setSelectionRange) {
            return this.element.value.substring(this.element.selectionStart,this.element.selectionEnd);
        }
        else {
            return false;
        }
    },
    replaceSelection: function(text){
        var scroll_top = this.element.scrollTop;
        if(!!document.selection){
            this.element.focus();
            var range = (this.range) ? this.range : document.selection.createRange();
            range.text = text;
            range.select();
        }else if(!!this.element.setSelectionRange){
            var selection_start = this.element.selectionStart;
            this.element.value = this.element.value.substring(0,selection_start) + text + this.element.value.substring(this.element.selectionEnd);
            this.element.setSelectionRange(selection_start + text.length,selection_start + text.length);
        }
        this.doOnChange();
        this.element.focus();
        this.element.scrollTop = scroll_top;
    },
    wrapSelection: function(before,after){
        var sel = this.getSelection();
        // Remove the wrapping if the selection has the same before/after
        if (sel.indexOf(before) === 0 &&
            sel.lastIndexOf(after) === (sel.length - after.length)) {
            this.replaceSelection(sel.substring(before.length,
                sel.length - after.length));
        } else {
            this.replaceSelection(before + sel + after);
        }
    },
    insertBeforeSelection: function(text){
        this.replaceSelection(text + this.getSelection());
    },
    insertAfterSelection: function(text){
        this.replaceSelection(this.getSelection() + text);
    },
    collectFromEachSelectedLine: function(callback,before,after){
        this.replaceSelection((before || '') + $A(this.getSelection().split("\n")).collect(callback).join("\n") + (after || ''));
    },
    insertBeforeEachSelectedLine: function(text,before,after){
        this.collectFromEachSelectedLine(function(line){
            },before,after);
    }
});

/**
 * PwronEditorPanel
 **/
var PwronEditorPanel = Class.create();
PwronEditorPanel.prototype = Object.extend(new ControlTextArea(), {
    wrapSelectionTag: function(tag){
        this.wrapSelection ('<'+tag+'>', '</'+tag+'>');
    },
    insertLinkUrl: function(url, txt) {
        //var seltxt=this.getSelection();
        this.replaceSelection('<a href="'+url+'">'+txt+'</a>');
    }, 
    insertVideoUrl: function(url) {
        this.replaceSelection('<video>'+url+'</video>');
    }, 
    
    insertImageUrl: function(url, desc, align){
        if (url) {
            var s_align = align ? 'align="'+align+'"'              : '';
            var s_desc   = desc   ? 'title="'+desc+'" alt="'+desc+'"'  : '';
            this.insertAfterSelection('<img src="'+url+'" '+s_align+' '+s_desc+'>');
        }
    },
    
    insertTitle: function (select) {
        var tag=select.getValue()
        if (tag) {
            this.wrapSelection ('<'+tag+'>', '</'+tag+'>');
        }
        select.options[0].selected=true;
    },
    
    insertList: function (select) {
        var tp=select.getValue();
        var prefix='';
        if (this.getValue()!=''){
            prefix = "\n";
        }
        if (tp=='ul') {
            this.wrapSelection(prefix+"<ul>\n\t<li>","</li>\n</ul>");
        }
        if (tp=='ol') {
            this.wrapSelection(prefix+"<ol>\n\t<li>","</li>\n</ol>");
        }
        select.options[0].selected=true;
    },
    
    wrapSelectionColor: function (select){
            var color=select.getValue();
            this.wrapSelection ('<font color="'+color+'">', '</font>');
            select.options[0].selected=true;
    },
    
    wrapSelectionFontSize: function (select){
            var size=select.getValue();
            this.wrapSelection ('<font size="'+size+'">', '</font>');
            select.options[0].selected=true;
    }
    
});

/**
 * PwronEditorForm
 **/
var PwronEditorForm = Class.create();
PwronEditorForm.prototype = new VarienForm();


PwronEditorForm.prototype.initialize = (function(super_initialize) {
    return function(formId, previewContainer,  previewURL) {
        super_initialize.call(this, formId, false);
        
        this.form = $(formId);
        this.editElement   = $('description');
        this.panelContainer= $('panel-container');
        
        this.previewContainer=previewContainer;
        this.previewURL=previewURL;
        
        this.editorPanel = new PwronEditorPanel(this.editElement, this.previewURL)
        this.formImage = new PwronImageForm('form-image', this);
        this.formLink  = new PwronLinkForm('form-link', this);
        this.formVideo  = new PwronVideoForm('form-video', this);
        
        $(this.panelContainer).appendChild($('editor-panel')).show();
        $(this.panelContainer).show()
        this.preview();
    };
})(VarienForm.prototype.initialize);


PwronEditorForm.prototype.upPreview = function(txt){
    if (txt) {
        $(this.previewContainer).setStyle({
            display:'block'
        });
        $(this.previewContainer).update ( txt );
    } else {
        $(this.previewContainer).setStyle({
            display:'none'
        });
    }
}

PwronEditorForm.prototype.preview = function(){
    var that = this;
    new Ajax.Request(this.previewURL, {
        parameters: {
            text: this.editorPanel.getValue()
        },            
        onSuccess: function(transport) {
            try {
                var jsonResponse=transport.responseText.evalJSON();
                if(jsonResponse.error){
                    alert(jsonResponse.errorTxt);
                    return false;
                }
                that.upPreview(jsonResponse.text);
            } catch(e) {
                console.log(e.message);
            }
        }.bind(this)
    });        
};


PwronEditorForm.prototype.showDialog = function(elm) {
    this.formImage.clear();
    this.formLink.clear();
    this.formVideo.clear();
    var scnW;
    var scnH;
    if (self.innerHeight) { // all except Explorer
        scnW = self.innerWidth;
        scnH = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        scnW = document.documentElement.clientWidth;
        scnH = document.documentElement.clientHeight;
    }
    else if (document.body) {// other Explorers
        scnW = document.body.clientWidth;
        scnH = document.body.clientHeight;
    }        
    var w = $(elm).getWidth();
    var h = $(elm).getHeight();
    $(elm).setStyle({
        display:'block',
        left: (scnW-w)/2+'px',
        top: (scnH-h)/2+'px'
    });
    $('form-popup-overlay').setStyle({
        display:'block'
    });
}

PwronEditorForm.prototype.showImageDialog = function() {
    this.showDialog('form-image-wrap');
};

PwronEditorForm.prototype.showVideoDialog = function() {
    this.showDialog('form-video-wrap');
    this.formVideo.setDefault(this.editorPanel.getSelection());
};

PwronEditorForm.prototype.showLinkDialog = function() {
    this.showDialog('form-link-wrap');
    this.formLink.setDefault(this.editorPanel.getSelection());
};


PwronEditorForm.prototype.closeImageDialog = function(){
    $('form-image-wrap').setStyle({
        display:'none'
    });
    $('form-popup-overlay').setStyle({
        display:'none'
    });
};


PwronEditorForm.prototype.closeLinkDialog = function(){
    $('form-link-wrap').setStyle({
        display:'none'
    });
    $('form-popup-overlay').setStyle({
        display:'none'
    });
};


PwronEditorForm.prototype.closeVideoDialog = function(){
    $('form-video-wrap').setStyle({
        display:'none'
    });
    $('form-popup-overlay').setStyle({
        display:'none'
    });
};

PwronAutocompleter = Class.create(Autocompleter.Base, {
    initialize: function(element, update, url, options) {
        this.baseInitialize(element, update, options);
        this.options.asynchronous  = true;
        this.options.onComplete    = this.onComplete.bind(this);
        this.options.onSuccess     = this.onSuccess.bind(this);
        this.options.defaultParams = this.options.parameters || null;
        this.url                   = url;
    },

    getUpdatedChoices: function() {
        this.startIndicator();

        var entry = encodeURIComponent(this.options.paramName) + '=' +
        encodeURIComponent(this.getToken());

        this.options.parameters = this.options.callback ?
        this.options.callback(this.element, entry) : entry;

        if(this.options.defaultParams)
            this.options.parameters += '&' + this.options.defaultParams;

        new Ajax.Request(this.url, this.options);
    },
  
    onSuccess: function(request) {
        if ($('loading-mask')){
            Element.hide('loading-mask');
        }
        this.stopIndicator();
    },
  
    onComplete: function(request) {
        /*if ($('loading-mask')){Element.hide('loading-mask');}*/
        this.updateChoices(request.responseText);
    }
});

/**
 * PwronEditorForm
 **/
PwronTagForm = Class.create();
PwronTagForm.prototype = {
    initialize : function(field, emptyText, indicator){
        this.field = $(field);
        this.indicator = indicator;
        this.emptyText = emptyText;
        Event.observe(this.field, 'focus', this.focus.bind(this));
        Event.observe(this.field, 'blur', this.blur.bind(this));
        this.blur();
    }, 
    focus : function(event){
        if(this.field.value==this.emptyText){
            this.field.value='';
        }
    }, 
    blur : function(event){
        if(this.field.value==''){
            this.field.value=this.emptyText;
        }
    }, 
    initAutocomplete : function(url, destinationElement){
        new PwronAutocompleter(this.field, destinationElement, url, {
            paramName: 'tag', 
            method: 'get',
            minChars: 2,
            tokens: ',',
            indicator: this.indicator,
            afterUpdateElement: this._afterUpdateElement.bind(this), 
            //callback: this._callback.bind(this),
            onShow : function(element, update) {
                if(!update.style.position || update.style.position=='absolute') {
                    update.style.position = 'absolute';
                    Position.clone(element, update, {
                        setHeight: false, 
                        offsetTop: element.offsetHeight
                    });
                }
                Effect.Appear(update,{
                    duration:0
                });
            }
        });
    }, 
    _afterUpdateElement : function(element){
        this.field.value = this.field.value + ', ';
    //if ($('loading-mask')){$('loading-mask').hide();}
    }
}


