Plugin = Class.extend({
    w: 0,
    path: '',
    icon: null,
    iframe: null,
    window: null,
    document: null,
    body: null,
    content: null,
    helpers: [],

    init: function() {
        this.name = this.path.match(/\/(.*)$/)[1].toString();
        this.Name = this.name.charAt(0).toUpperCase() + this.name.substr(1);
        var $this = this;
        $('.PE_toolbar span.tool[rel=' + this.name + ']').each(function(i, tool) {
            var rel = $(tool).closest('div.PE_wrapper').attr('rel');
            $this.refreshHelpers(rel);
            if($this.icon != null) {
                $(tool).append($this.icon(rel));
            } else {
                $(tool).append($('<a>')
                    .addClass('img')
                    .html('&nbsp;')
                    .attr({ href: 'javascript: void(0)', onClick: $this.Name + '.executeOn("' + rel + '")' })
                    .css('background-image', 'url(/plugins/editor/wysiwyg/plugins/' + $this.path + '/' + $this.name + '.png)'))
            }
        });
    },

    executeOn: function(id, params) {
        this.iframe = $('iframe[rel=' + id + ']');
        this.window = this.iframe[0].contentWindow;
        this.document = this.iframe.contents();
        this.body = this.document.find('body');
        this.content = this.body.html();
        this.range = this.window.getSelection().rangeCount ? this.window.getSelection().getRangeAt(0) : null;

        this.execute(params);
    },

    popup: function(url, params, width, height) {
        var query = '?';
        if(typeof(width) == 'undefined') width = 800;
        if(typeof(height) == 'undefined') height = 640;
        if(typeof(params) != 'undefined') {
            $.each(params, function(key, value) {
                query += key + '=' + value + '&';
            });
        }
        window.open('/plugins/editor/wysiwyg/' + 'plugins/' + this.path + '/' + url + query.replace(/[\?&]$/, ''), 'RTE_popup' + this.w++, 'width=' + width + ',height=' + height + ',resizable=no,location=no,status=no');
    },

    show: function(url, params, width, height) {
        var query = '?';
        if(typeof(width) == 'undefined') width = 800;
        if(typeof(height) == 'undefined') height = 640;
        if(typeof(params) != 'undefined') {
            $.each(params, function(key, value) {
                query += key + '=' + value + '&';
            });
        }
        $.get(
            '/plugins/editor/wysiwyg/' + 'plugins/' + this.path + '/' + url + query.replace(/[\?&]$/, ''),
            null,
            function(response) {
                var wrapper = $('<div>').addClass('submenu').html(response); }
        );
    },

    execCommand: function(command, value, more) {
        if(typeof more == 'undefined') more = false;
        this.window.focus();
        this.document[0].execCommand(command, more, value);
        this.window.focus();
    },

    insert: function(content) {
        var sel, range, html, wrapper;
        if(this.window.getSelection) {
            sel = this.window.getSelection();
            if(sel.getRangeAt && sel.rangeCount) {
                var temp = document.createElement('div');
                temp.innerHTML = content;
                sel.getRangeAt(0).deleteContents();
                sel.getRangeAt(0).insertNode(temp.firstChild);
            }
        } else if(document.selection && document.selection.createRange) {
            range = this.document.selection.createRange();
            range.pasteHTML(content);
        }
        this.refreshHelpers();
    },

    clear: function() {
        var content = this.content.replace(/\>\s*/g, ">\n");
        this.body.html(content);
    },

    helper: function(content, element, iframe) {
        if($('div.PE_helper').length > 0) {
            var helper = $('div.PE_helper');
        } else {
            var close = $('<a>').addClass('PE_helper-close').attr({ href: "javascript: void(0)", title: 'Close box' }).click(function() { $(this).closest('div.PE_helper').hide(); });
            var inner = $('<div>').addClass('PE_helper-inner');
            var helper = $('<div class="PE_helper">').append(close).append(inner);
            $('body').append(helper);
        }
        var left = iframe.offset().left + element.offset().left;
        var top = -window.pageYOffset + iframe.offset().top + element.offset().top + element.outerHeight() + 3;
        helper.children('.PE_helper-inner').html(content);
        helper.css({ left: left, top: top }).show();
    },

    refreshHelpers: function(id) {
        var $this = this;
        var $iframe = typeof(id) == undefined ? $this.iframe : $('iframe[rel=' + id + ']');
        var $window = typeof(id) == undefined ? $this.window : $iframe[0].contentWindow;
        $.each(this.helpers, function(i, helper) {
            $window.select(helper.selector).click(function() { $this.helper(helper.action($(this)), $(this), $iframe); });
        });
    }
});
