﻿var currentresize = null;

(function($) {
    $.fn.document = function() {
        var element = this.get(0);
        if (element.nodeName.toLowerCase() == 'iframe')
            return element.contentWindow.document;
        return this;
    };

    $.fn.documentSelection = function() {
        var element = this.get(0);

        if (element.contentWindow.document.selection)
            return element.contentWindow.document.selection.createRange().text;
        else
            return element.contentWindow.getSelection().toString();
    };

    $.fn.wysiwyg = function(options) {
        if (arguments.length > 0 && arguments[0].constructor == String) {
            var action = arguments[0].toString();
            var params = [];

            for (var i = 1; i < arguments.length; i++)
                params[i - 1] = arguments[i];

            if (action in Wysiwyg) {
                return this.each(function() {
                    $.data(this, 'wysiwyg')
                     .designMode();

                    Wysiwyg[action].apply(this, params);
                });
            }
            else return this;
        }

        var controls = {};

        if (options && options.controls) {
            var controls = options.controls;
            delete options.controls;
        }

        options = $.extend({
            html: '<' + '?xml version="1.0" encoding="UTF-8"?' + '><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">STYLE_SHEET<style>p, br, div, ul, li, ol, hr {clear:both;} object, embed{width:400px;height:300px;clear:both;} img{float:left;margin:5px;max-width:100%;}</style></head><body style="margin: 5px;">INITIAL_CONTENT</body></html>',
            css: {},
            debug: false,
            autoSave: true,
            rmUnwantedBr: false,
            brIE: true,
            controls: {},
            messages: {}
        }, options);

        options.messages = $.extend(true, options.messages, Wysiwyg.MSGS_EN);
        options.controls = $.extend(true, options.controls, Wysiwyg.TOOLBAR);

        for (var control in controls) {
            if (control in options.controls)
                $.extend(options.controls[control], controls[control]);
            else
                options.controls[control] = controls[control];
        }

        return this.each(function() {
            Wysiwyg(this, options);
        });
    };

    function Wysiwyg(element, options) {
        return this instanceof Wysiwyg
            ? this.init(element, options)
            : new Wysiwyg(element, options);
    }

    $.extend(Wysiwyg, {
        createLink: function(szURL) {
            var self = $.data(this, 'wysiwyg');

            if (self.constructor == Wysiwyg && szURL && szURL.length > 0) {
                var selection = $(self.editor).documentSelection();

                if (selection.length > 0) {
                    if ($.browser.msie) self.focus();
                    self.editorDoc.execCommand('unlink', false, []);
                    self.editorDoc.execCommand('createLink', false, szURL);
                }
                else if (self.options.messages.nonSelection)
                    alert(self.options.messages.nonSelection);
            }
        },

        insertHtml: function(szHTML) {
            var self = $.data(this, 'wysiwyg');

            if (self.constructor == Wysiwyg && szHTML && szHTML.length > 0) {
                if ($.browser.msie) {
                    self.focus();
                    self.editorDoc.execCommand('insertImage', false, '#jwysiwyg#');
                    var img = self.getElementByAttributeValue('img', 'src', '#jwysiwyg#');
                    if (img) {
                        $(img).replaceWith(szHTML);
                    }
                }
                else {
                    self.editorDoc.execCommand('insertHTML', false, szHTML);
                }
            }
        },

        setContent: function(newContent) {
            var self = $.data(this, 'wysiwyg');
            self.setContent(newContent);
            self.saveContent();
        },

        clear: function() {
            var self = $.data(this, 'wysiwyg');
            self.setContent('');
            self.saveContent();
        },

        MSGS_EN: {
            nonSelection: 'select the text you wish to link'
        },

        TOOLBAR: {

            separator00: { visible: true, separator: true },

            bold: { visible: false, tags: ['b', 'strong'], css: { fontWeight: 'bold' }, tooltip: "Bold" },
            italic: { visible: true, tags: ['i', 'em'], css: { fontStyle: 'italic' }, tooltip: "Italic" },
            strikeThrough: { visible: true, tags: ['s', 'strike'], css: { textDecoration: 'line-through' }, tooltip: "Strike-through" },

            separator01: { visible: true, separator: true },

            insertOrderedList: { visible: true, tags: ['ol'], tooltip: "Insert Ordered List" },
            insertUnorderedList: { visible: true, tags: ['ul'], tooltip: "Insert Unordered List" },

            separator02: { visible: true, separator: true },

            createLink: {
                visible: true,
                exec: function() {
                    var selection = $(this.editor).documentSelection();

                    if (selection.length > 0) {
                        if ($.browser.msie) {
                            this.focus();
                            this.editorDoc.execCommand('createLink', true, null);
                        }
                        else {
                            var szURL = prompt('URL', 'http://');

                            if (szURL && szURL.length > 0) {
                                this.editorDoc.execCommand('unlink', false, []);
                                this.editorDoc.execCommand('createLink', false, szURL);
                            }
                        }
                    }
                    else if (this.options.messages.nonSelection)
                        alert(this.options.messages.nonSelection);
                },

                tags: ['a'],
                tooltip: "Create link"
            },

            removeFormat: {
                visible: true,
                exec: function() {
                    if ($.browser.msie) this.focus();
                    this.editorDoc.execCommand('removeFormat', false, []);
                    this.editorDoc.execCommand('unlink', false, []);
                },
                tooltip: "Remove formatting"
            },

            separator03: { visible: true, separator: true },


            insertImage: {
                visible: true,
                tags: ['img'],
                tooltip: "Insert image"
            },

            insertVideo: {
                visible: false,
                tags: ['object'],
                tooltip: "Insert video"
            },

            insertCode: {
                visible: true,
                exec: function() {
                    $(this.insertCodeB).find("textarea").val("");
                    $(this.insertCodeB).css("display", "block");
                },

                tags: ['object'],
                tooltip: "Insert Code"
            },

            forumCut: {
                visible: true,
                tags: ['hr'],
                exec: function() {
                    var selection = $(this.editor).documentSelection();
                    document.title = selection;

                    this.editorDoc.body.innerHTML += "<hr />";
                },
                tooltip: "Forum Cut"
            },

            html: {
                visible: false,
                exec: function() {
                    if (this.viewHTML) {
                        this.setContent($(this.original).val());
                        $(this.editor).height($(this.original).height());
                        $(this.original).hide();
                        $(this.editor).show();
                        $(this.panel).find(".html").parent().removeClass("active");
                    }
                    else {
                        this.saveContent();
                        $(this.original).height($(this.editor).height());
                        $(this.original).show();
                        $(this.editor).hide();
                        $(this.panel).find(".html").parent().addClass("active");
                    }

                    this.viewHTML = !(this.viewHTML);
                },
                tooltip: "View source code"
            }
        }
    });

    $.extend(Wysiwyg.prototype,
    {
        original: null,
        options: {},

        element: null,
        editor: null,
        insertCodeB: null,

        flashButton: function() {
            var editorid = $(this.original).attr('id');
            return '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="24" height="24" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + BaseURL + 'Sources/wysiwyg/Editor.Image.Upload.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="FlashVars" value="Url=' + BaseURL + 'Editor/UploadImage&Editor=' + editorid + '&CallBack=wysiwygImageUploadComplete" /><embed src="' + BaseURL + 'Sources/wysiwyg/Editor.Image.Upload.swf" quality="high" bgcolor="#ffffff" width="24" height="24" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" FlashVars="Url=' + BaseURL + 'Editor/UploadImage&Editor=' + editorid + '&CallBack=wysiwygImageUploadComplete" /></object>';
        },

        focus: function() {
            $(this.editorDoc.body).focus();
        },

        init: function(element, options) {
            var self = this;

            this.editor = element;
            this.options = options || {};

            $.data(element, 'wysiwyg', this);

            var newX = element.width || element.clientWidth;
            var newY = element.height || element.clientHeight;

            if (element.nodeName.toLowerCase() == 'textarea') {
                this.original = element;

                if (newX == 0 && element.cols)
                    newX = (element.cols * 8) + 21;

                if (newY == 0 && element.rows)
                    newY = (element.rows * 16) + 16;


                var editor = this.editor = $('<iframe src="javascript:false;"></iframe>').css({
                    width: '100%', height: '150px'
                }).attr('id', $(element).attr('id') + 'IFrame').attr('name', $(element).attr('id') + 'IFrame')
                .attr('frameborder', '0');

                this.editor.attr('tabindex', $(element).attr('tabindex'));

                if ($.browser.msie) {
                    this.editor
                        .css('height', '150px');
                }
            }

            var panel = this.panel = $('<ul role="menu" class="panel" onmousedown="return false;"></ul>');

            var insertCodeB = this.insertCodeB = $('<div style="top: 0px;display:none;" class="vs_cod"><div class="t"><div class="crn lt"></div><div class="crn rt"></div><div class="tt"></div><div class="tt2"></div></div><div class="l"></div><div class="r"></div><div align="center" class="c"><div class="h">вставить код</div><div class="inp1"><div><textarea></textarea></div></div><a href="javascript:void(0);" onclick="wysiwygInsertCode(\'' + $(this.original).attr("id") + '\',$(this).parent().parent().parent().find(\'textarea\').val());"><img src="' + BaseURL + 'Sources/images/btns/paste_code.gif"></a></div><div class="b"><div class="crn lb"></div><div class="crn rb"></div><div class="bb"></div></div></div>');

            this.appendControls();
            this.element = $('<div></div>').css({
                width: '100%'
            }).addClass('wysiwyg')
                .append(panel)
                .append($('<div><!-- --></div>').css({ clear: 'both' }))
                .append(editor)
                .append('<div class="iframeresize"></div>');
            ;

            $(element)
                .hide()
                .before(this.element)
			;

            this.viewHTML = false;
            this.initialHeight = 150;

            this.initialContent = $(element).val();
            this.initFrame();

            if (this.initialContent.length == 0)
                this.setContent('');

            var form = $(element).closest('form');

            if (this.options.autoSave) {
                form.submit(function() { self.saveContent(); });
            }

            form.bind('reset', function() {
                self.setContent(self.initialContent);
                self.saveContent();
            });

            //$(this.original).insertAfter($(this.editor));

            $(this.editor).parent().before(insertCodeB);

            $(this.editor).next().mousedown(function() {
                currentresize = self.editor;
                $(currentresize).css("visibility", "hidden");
                return false;
            });

            $(window).mousemove(function(e) {
                if (currentresize != null) {
                    $(currentresize).height(e.pageY - $(currentresize).offset().top);
                }
            });

            $(window).mouseup(function(e) {
                $(currentresize).css("visibility", "visible");
                currentresize = null;
            });
        },

        initFrame: function() {
            var self = this;
            var style = '';

            if (this.options.css && this.options.css.constructor == String) {
                style = '<link rel="stylesheet" type="text/css" media="screen" href="' + this.options.css + '" />';
            }

            this.editorDoc = $(this.editor).document();
            this.editorDoc_designMode = false;

            try {
                this.editorDoc.designMode = 'on';
                this.editorDoc_designMode = true;
            } catch (e) {
                $(this.editorDoc).focus(function() {
                    self.designMode();
                });
            }

            this.editorDoc.open();
            this.editorDoc.write(
                this.options.html

					.replace(/INITIAL_CONTENT/, function() { return self.initialContent; })
                    .replace(/STYLE_SHEET/, function() { return style; })
            );
            this.editorDoc.close();

            this.editorDoc.contentEditable = 'true';

            this.editorDoc.body.style.margin = '0px';
            //this.editorDoc.body.innerHTML = "1234";//this.original.value;

            if ($.browser.msie) {
                setTimeout(function() { $(self.editorDoc.body).css('border', 'none'); }, 0);
            }

            $(this.editorDoc).click(function(event) {
                self.checkTargets(event.target ? event.target : event.srcElement);
            });

            $(this.original).focus(function() {
                if (!$.browser.msie) {
                    self.focus();
                }
            });

            if (this.options.autoSave) {
                $(this.editorDoc).keydown(function() { self.saveContent(); })
                                 .keyup(function() { self.saveContent(); })
                                 .mousedown(function() { self.saveContent(); });
            }

            if (this.options.css) {
                setTimeout(function() {
                    if (self.options.css.constructor == String) {

                    }
                    else
                        $(self.editorDoc).find('body').css(self.options.css);
                }, 0);
            }

            $(this.editorDoc).keydown(function(event) {
                if ($.browser.msie && self.options.brIE && event.keyCode == 13) {
                    var rng = self.getRange();
                    rng.pasteHTML('<br/>');
                    rng.collapse(false);
                    rng.select();
                    return false;
                }

                return true;
            });

            $(this.editorDoc).keyup(function(event) {
                //if(self.editorDoc.body.clientHeight > self.editor.height())
                //	self.editor.height(self.editorDoc.body.clientHeight);

                if ((event.keyCode == 86) && (event.ctrlKey == true)) {
                    var body = self.editorDoc.body.innerHTML;
                    body = body.replace(/<script[^>]*>.*<\/script>/g, "");
                    body = body.replace(/(?!<[\/]{0,1}(a|ul|ol|li|i|object|embed|img|p|br|span)(\s|>)[^>]*>)<[^>]*>|(\s{2})|(\t)/g, "");
                    self.editorDoc.body.innerHTML = body;
                }
            });
        },

        designMode: function() {
            if (!(this.editorDoc_designMode)) {
                try {
                    this.editorDoc.designMode = 'on';
                    this.editorDoc_designMode = true;
                } catch (e) { }
            }
        },

        getSelection: function() {
            return (window.getSelection) ? window.getSelection() : document.selection;
        },

        getRange: function() {
            var selection = this.getSelection();

            if (!(selection))
                return null;

            return (selection.rangeCount > 0) ? selection.getRangeAt(0) : selection.createRange();
        },

        getContent: function() {
            return $($(this.editor).document()).find('body').html();
        },

        setContent: function(newContent) {
            $($(this.editor).document()).find('body').html(newContent);
        },

        saveContent: function() {
            if (this.original) {
                var content = this.getContent();

                if (this.options.rmUnwantedBr) {
                    content = (content.substr(-4) == '<br>') ? content.substr(0, content.length - 4) : content;
                }

                $(this.original).val(content);
            }
        },

        withoutCss: function() {
            if ($.browser.mozilla) {
                try {
                    this.editorDoc.execCommand('styleWithCSS', false, false);
                }
                catch (e) {
                    try {
                        this.editorDoc.execCommand('useCSS', false, true);
                    }
                    catch (e) {
                    }
                }
            }
        },

        appendMenu: function(cmd, args, className, fn, tooltip) {
            var self = this;
            args = args || [];
            switch (cmd) {
                case "insertImage":
                    button = '<iframe style="display:none;" name="imageUpload"></iframe><form action="' + BaseURL + 'Editor/UploadImage/" method="post" enctype="multipart/form-data" style="position:relative;" target="imageUpload" id="wysiwygUploadForm"><input type="hidden" name="Editor" value="' + $(this.original).attr("id") + '"><a class="insertImage"></a><input name="Image" type="file" style="position:absolute;left:-175px;top:0px;opacity:0;height:24px;cursor:pointer;filter:alpha(opacity=0);" onchange="wysiwygImageUpload();" /></form>">';
                    $('<li></li>').css({ position: "relative", width: "24px", height: "24px", overflow: "hidden" }).append(button).appendTo(this.panel);
                    break;
                case "insertVideo":
                    $('<li></li>').append(self.flashButton()).appendTo(this.panel);
                    break;
                default:
                    $('<li></li>').append(
						$('<a role="menuitem" href="javascript:;">' + (className || cmd) + '</a>')
							.addClass(className || cmd)
							.addClass(cmd == "html" ? "html" : "")
							.attr('title', tooltip)
					).click(function() {
					    if (fn) fn.apply(self); else {
					        self.withoutCss();
					        self.editorDoc.execCommand(cmd, false, args);
					    }
					    if (self.options.autoSave) self.saveContent();
					}).appendTo(this.panel);
                    break;
            }
            if (cmd == "insertImage") {

            } else {

            }
        },

        appendMenuSeparator: function() {
            $('<li role="separator" class="separator"></li>').appendTo(this.panel);
        },

        appendControls: function() {
            for (var name in this.options.controls) {
                var control = this.options.controls[name];

                if (control.separator) {
                    if (control.visible !== false)
                        this.appendMenuSeparator();
                }
                else if (control.visible) {
                    this.appendMenu(
                        control.command || name, control.arguments || [],
                        control.className || control.command || name || 'empty', control.exec,
                        control.tooltip || control.command || name || ''
                    );
                }
            }
        },

        checkTargets: function(element) {
            for (var name in this.options.controls) {
                var control = this.options.controls[name];
                var className = control.className || control.command || name || 'empty';

                $('.' + className, this.panel).parent().removeClass('active');

                if (control.tags) {
                    var elm = element;

                    do {
                        if (elm.nodeType != 1)
                            break;

                        if ($.inArray(elm.tagName.toLowerCase(), control.tags) != -1)
                            $('.' + className, this.panel).parent().addClass('active');
                    } while ((elm = elm.parentNode));
                }

                if (control.css) {
                    var elm = $(element);

                    do {
                        if (elm[0].nodeType != 1)
                            break;

                        for (var cssProperty in control.css)
                            if (elm.css(cssProperty).toString().toLowerCase() == control.css[cssProperty])
                            $('.' + className, this.panel).addClass('active');
                    } while ((elm = elm.parent()));
                }
            }
        },

        getElementByAttributeValue: function(tagName, attributeName, attributeValue) {
            var elements = this.editorDoc.getElementsByTagName(tagName);

            for (var i = 0; i < elements.length; i++) {
                var value = elements[i].getAttribute(attributeName);

                if ($.browser.msie) {
                    value = value.substr(value.length - attributeValue.length);
                }

                if (value == attributeValue)
                    return elements[i];
            }

            return false;
        }
    });
})(jQuery);

function wysiwygImageUploadComplete(editor, status, result) {
    if (status == 1) {
        var NewImg = "<a href='" + result + "'><img align='left' vspace='10' hspace='10' src='" + result.replace(/\/original/g, "") + "' /></a>";
        $("#" + editor).wysiwyg("setContent", $("#" + editor).val() + NewImg);

    } else
        alert(status + ": " + result);
}

function wysiwygImageUpload() {
    $("#wysiwygUploadForm").submit();
}

function wysiwygInsertCode(editor, Code) {
    $("#" + editor).wysiwyg("setContent", $("#" + editor).val() + Code);
    $(".vs_cod").css("display", "none");
}