(function($) {
    $.fn.markItUp = function(settings, extraSettings) {
        var method, params, options, ctrlKey, shiftKey, altKey; ctrlKey = shiftKey = altKey = false;

        if (typeof settings == 'string') {
            method = settings;
            params = extraSettings;
        }

        options = {	id:						'',
            nameSpace:				'',
            root:					'',
            previewHandler:			false,
            previewInWindow:		'', // 'width=800, height=600, resizable=yes, scrollbars=yes'
            previewInElement:		'',
            previewAutoRefresh:		true,
            previewPosition:		'after',
            previewTemplatePath:	'~/templates/preview.html',
            previewParser:			false,
            previewParserPath:		'',
            previewParserVar:		'data',
            resizeHandle:			true,
            beforeInsert:			'',
            afterInsert:			'',
            onEnter:				{},
            onShiftEnter:			{},
            onCtrlEnter:			{},
            onTab:					{},
            markupSet:			[	{ /* set */ } ]
        };
        $.extend(options, settings, extraSettings);

        // compute markItUp! path
        if (!options.root) {
            $('script').each(function(a, tag) {
                miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/);
                if (miuScript !== null) {
                    options.root = miuScript[1];
                }
            });
        }

        // Quick patch to keep compatibility with jQuery 1.9
        var uaMatch = function(ua) {
            ua = ua.toLowerCase();

            var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
                /(webkit)[ \/]([\w.]+)/.exec(ua) ||
                /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
                /(msie) ([\w.]+)/.exec(ua) ||
                ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
                [];

            return {
                browser: match[ 1 ] || "",
                version: match[ 2 ] || "0"
            };
        };
        var matched = uaMatch( navigator.userAgent );
        var browser = {};

        if (matched.browser) {
            browser[matched.browser] = true;
            browser.version = matched.version;
        }
        if (browser.chrome) {
            browser.webkit = true;
        } else if (browser.webkit) {
            browser.safari = true;
        }

        return this.each(function() {
            var $$, textarea, levels, scrollPosition, caretPosition, caretOffset,
                clicked, hash, header, footer, previewWindow, template, iFrame, abort;
            $$ = $(this);
            textarea = this;
            levels = [];
            abort = false;
            scrollPosition = caretPosition = 0;
            caretOffset = -1;

            $(".form-bbcode-button").click(function() {
                refreshPreview();
                preview();
            });

            options.previewParserPath = localize(options.previewParserPath);
            options.previewTemplatePath = localize(options.previewTemplatePath);

            if (method) {
                switch(method) {
                    case 'remove':
                        remove();
                        break;
                    case 'insert':
                        markup(params);
                        break;
                    default:
                        $.error('Method ' +  method + ' does not exist on jQuery.markItUp');
                }
                return;
            }

            // apply the computed path to ~/
            function localize(data, inText) {
                if (inText) {
                    return 	data.replace(/("|')~\//g, "$1"+options.root);
                }
                return 	data.replace(/^~\//, options.root);
            }

            // init and build editor
            function init() {
                id = ''; nameSpace = '';
                if (options.id) {
                    id = 'id="'+options.id+'"';
                } else if ($$.attr("id")) {
                    id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"';

                }
                if (options.nameSpace) {
                    nameSpace = 'class="'+options.nameSpace+'"';
                }
                $$.wrap('<div '+nameSpace+'></div>');
                $$.wrap('<div '+id+' class="markItUp"></div>');
                $$.wrap('<div class="markItUpContainer"></div>');
                $$.addClass("markItUpEditor");

                // add the header before the textarea
                header = $('<div class="markItUpHeader"></div>').insertBefore($$);
                $(dropMenus(options.markupSet)).appendTo(header);

                // add the footer after the textarea
                footer = $('<div class="markItUpFooter"></div>').insertAfter($$);

                // add the resize handle after textarea
                if (options.resizeHandle === true && browser.safari !== true) {
                    resizeHandle = $('<div class="markItUpResizeHandle"></div>')
                        .insertAfter($$)
                        .bind("mousedown.markItUp", function(e) {
                            var h = $$.height(), y = e.clientY, mouseMove, mouseUp;
                            mouseMove = function(e) {
                                $$.css("height", Math.max(20, e.clientY+h-y)+"px");
                                return false;
                            };
                            mouseUp = function(e) {
                                $("html").unbind("mousemove.markItUp", mouseMove).unbind("mouseup.markItUp", mouseUp);
                                return false;
                            };
                            $("html").bind("mousemove.markItUp", mouseMove).bind("mouseup.markItUp", mouseUp);
                        });
                    footer.append(resizeHandle);
                }

                // listen key events
                $$.bind('keydown.markItUp', keyPressed).bind('keyup', keyPressed);

                // bind an event to catch external calls
                $$.bind("insertion.markItUp", function(e, settings) {
                    if (settings.target !== false) {
                        get();
                    }
                    if (textarea === $.markItUp.focused) {
                        markup(settings);
                    }
                });

                // remember the last focus
                $$.bind('focus.markItUp', function() {
                    $.markItUp.focused = this;
                });

                if (options.previewInElement) {
                    refreshPreview();
                }
            }

            // recursively build header with dropMenus from markupset
            function dropMenus(markupSet) {
                var ul = $('<ul></ul>'), i = 0;
                $('li:hover > ul', ul).css('display', 'block');
                $.each(markupSet, function() {
                    var button = this, t = '', title, li, j;
                    title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||'');
                    key   = (button.key) ? 'accesskey="'+button.key+'"' : '';
                    if (button.separator) {
                        li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul);
                    } else {
                        i++;
                        for (j = levels.length -1; j >= 0; j--) {
                            t += levels[j]+"-";
                        }
                        li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>')
                            .bind("contextmenu.markItUp", function() { // prevent contextmenu on mac and allow ctrl+click
                                return false;
                            }).bind('click.markItUp', function(e) {
                                e.preventDefault();
                            }).bind("focusin.markItUp", function(){
                                $$.focus();
                            }).bind('mouseup', function(e) {
                                if (button.call) {
                                    eval(button.call)(e);
                                }
                                setTimeout(function() { markup(button) },1);
                                return false;
                            }).bind('mouseenter.markItUp', function() {
                                $('> ul', this).show();
                                $(document).one('click', function() { // close dropmenu if click outside
                                        $('ul ul', header).hide();
                                    }
                                );
                            }).bind('mouseleave.markItUp', function() {
                                $('> ul', this).hide();
                            }).appendTo(ul);
                        if (button.dropMenu) {
                            levels.push(i);
                            $(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu));
                        }
                    }
                });
                levels.pop();
                return ul;
            }

            // markItUp! markups
            function magicMarkups(string) {
                if (string) {
                    string = string.toString();
                    string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g,
                        function(x, a) {
                            var b = a.split('|!|');
                            if (altKey === true) {
                                return (b[1] !== undefined) ? b[1] : b[0];
                            } else {
                                return (b[1] === undefined) ? "" : b[0];
                            }
                        }
                    );
                    // [![prompt]!], [![prompt:!:value]!]
                    string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g,
                        function(x, a) {
                            var b = a.split(':!:');
                            if (abort === true) {
                                return false;
                            }
                            value = prompt(b[0], (b[1]) ? b[1] : '');
                            if (value === null) {
                                abort = true;
                            } else {
                                if ($.isFunction(clicked.checkValue)) {
                                    value = clicked.checkValue(value);
                                }
                            }
                            return value;
                        }
                    );
                    return string;
                }
                return "";
            }

            // prepare action
            function prepare(action) {
                if ($.isFunction(action)) {
                    action = action(hash);
                }
                return magicMarkups(action);
            }

            // build block to insert
            function build(string) {
                var openWith 			= prepare(clicked.openWith);
                var placeHolder 		= prepare(clicked.placeHolder);
                var replaceWith 		= prepare(clicked.replaceWith);
                var closeWith 			= prepare(clicked.closeWith);
                var openBlockWith 		= prepare(clicked.openBlockWith);
                var closeBlockWith 		= prepare(clicked.closeBlockWith);
                var multiline 			= clicked.multiline;

                if (replaceWith !== "") {
                    block = openWith + replaceWith + closeWith;
                } else if (selection === '' && placeHolder !== '') {
                    block = openWith + placeHolder + closeWith;
                } else {
                    string = string || selection;

                    var lines = [string], blocks = [];

                    if (multiline === true) {
                        lines = string.split(/\r?\n/);
                    }

                    for (var l = 0; l < lines.length; l++) {
                        line = lines[l];
                        var trailingSpaces;
                        if (trailingSpaces = line.match(/ *$/)) {
                            blocks.push(openWith + line.replace(/ *$/g, '') + closeWith + trailingSpaces);
                        } else {
                            blocks.push(openWith + line + closeWith);
                        }
                    }

                    block = blocks.join("\n");
                }

                block = openBlockWith + block + closeBlockWith;

                return {	block:block,
                    openBlockWith:openBlockWith,
                    openWith:openWith,
                    replaceWith:replaceWith,
                    placeHolder:placeHolder,
                    closeWith:closeWith,
                    closeBlockWith:closeBlockWith
                };
            }

            // define markup to insert
            function markup(button) {
                var len, j, n, i;
                hash = clicked = button;
                get();
                $.extend(hash, {	line:"",
                        root:options.root,
                        textarea:textarea,
                        selection:(selection||''),
                        caretPosition:caretPosition,
                        ctrlKey:ctrlKey,
                        shiftKey:shiftKey,
                        altKey:altKey
                    }
                );
                // callbacks before insertion
                prepare(options.beforeInsert);
                prepare(clicked.beforeInsert);
                if ((ctrlKey === true && shiftKey === true) || button.multiline === true) {
                    prepare(clicked.beforeMultiInsert);
                }
                $.extend(hash, { line:1 });

                if ((ctrlKey === true && shiftKey === true)) {
                    lines = selection.split(/\r?\n/);
                    for (j = 0, n = lines.length, i = 0; i < n; i++) {
                        if ($.trim(lines[i]) !== '') {
                            $.extend(hash, { line:++j, selection:lines[i] } );
                            lines[i] = build(lines[i]).block;
                        } else {
                            lines[i] = "";
                        }
                    }

                    string = { block:lines.join('\n')};
                    start = caretPosition;
                    len = string.block.length + ((browser.opera) ? n-1 : 0);
                } else if (ctrlKey === true) {
                    string = build(selection);
                    start = caretPosition + string.openWith.length;
                    len = string.block.length - string.openWith.length - string.closeWith.length;
                    len = len - (string.block.match(/ $/) ? 1 : 0);
                    len -= fixIeBug(string.block);
                } else if (shiftKey === true) {
                    string = build(selection);
                    start = caretPosition;
                    len = string.block.length;
                    len -= fixIeBug(string.block);
                } else {
                    string = build(selection);
                    start = caretPosition + string.block.length ;
                    len = 0;
                    start -= fixIeBug(string.block);
                }
                if ((selection === '' && string.replaceWith === '')) {
                    caretOffset += fixOperaBug(string.block);

                    start = caretPosition + string.openBlockWith.length + string.openWith.length;
                    len = string.block.length - string.openBlockWith.length - string.openWith.length - string.closeWith.length - string.closeBlockWith.length;

                    caretOffset = $$.val().substring(caretPosition,  $$.val().length).length;
                    caretOffset -= fixOperaBug($$.val().substring(0, caretPosition));
                }
                $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } );

                if (string.block !== selection && abort === false) {
                    insert(string.block);
                    set(start, len);
                } else {
                    caretOffset = -1;
                }
                get();

                $.extend(hash, { line:'', selection:selection });

                // callbacks after insertion
                if ((ctrlKey === true && shiftKey === true) || button.multiline === true) {
                    prepare(clicked.afterMultiInsert);
                }
                prepare(clicked.afterInsert);
                prepare(options.afterInsert);

                // refresh preview if opened
                if (previewWindow && options.previewAutoRefresh) {
                    refreshPreview();
                }

                // reinit keyevent
                shiftKey = altKey = ctrlKey = abort = false;
            }

            // Substract linefeed in Opera
            function fixOperaBug(string) {
                if (browser.opera) {
                    return string.length - string.replace(/\n*/g, '').length;
                }
                return 0;
            }
            // Substract linefeed in IE
            function fixIeBug(string) {
                if (browser.msie) {
                    return string.length - string.replace(/\r*/g, '').length;
                }
                return 0;
            }

            // add markup
            function insert(block) {
                if (document.selection) {
                    var newSelection = document.selection.createRange();
                    newSelection.text = block;
                } else {
                    textarea.value =  textarea.value.substring(0, caretPosition)  + block + textarea.value.substring(caretPosition + selection.length, textarea.value.length);
                }
            }

            // set a selection
            function set(start, len) {
                if (textarea.createTextRange){
                    // quick fix to make it work on Opera 9.5
                    if (browser.opera && browser.version >= 9.5 && len == 0) {
                        return false;
                    }
                    range = textarea.createTextRange();
                    range.collapse(true);
                    range.moveStart('character', start);
                    range.moveEnd('character', len);
                    range.select();
                } else if (textarea.setSelectionRange ){
                    textarea.setSelectionRange(start, start + len);
                }
                textarea.scrollTop = scrollPosition;
                textarea.focus();
            }

            // get the selection
            function get() {
                textarea.focus();

                scrollPosition = textarea.scrollTop;
                if (document.selection) {
                    selection = document.selection.createRange().text;
                    if (browser.msie) { // ie
                        var range = document.selection.createRange(), rangeCopy = range.duplicate();
                        rangeCopy.moveToElementText(textarea);
                        caretPosition = -1;
                        while(rangeCopy.inRange(range)) {
                            rangeCopy.moveStart('character');
                            caretPosition ++;
                        }
                    } else { // opera
                        caretPosition = textarea.selectionStart;
                    }
                } else { // gecko & webkit
                    caretPosition = textarea.selectionStart;

                    selection = textarea.value.substring(caretPosition, textarea.selectionEnd);
                }
                return selection;
            }

            // open preview window
            function preview(e) {
                var altKeyPressed = false;
                if (e != undefined) {
                    altKeyPressed = e.altKey;
                }

                if (typeof options.previewHandler === 'function') {
                    previewWindow = true;
                } else if (options.previewInElement) {
                    previewWindow = $(options.previewInElement);
                } else if (!previewWindow || previewWindow.closed) {
                    if (options.previewInWindow) {
                        previewWindow = window.open('', 'preview', options.previewInWindow);
                        $(window).unload(function() {
                            previewWindow.close();
                        });
                    } else {
                        iFrame = $('<div class="markItUpPreviewFrame"></div>');
                        if (options.previewPosition == 'after') {
                            iFrame.insertAfter(footer);
                        } else {
                            iFrame.insertBefore(header);
                        }
                        previewWindow = iFrame;
                        previewWindow.animate({
                            height: '+=300px'
                        }, 1000);
                    }
                } else if (altKeyPressed === true) {
                    if (iFrame) {
                        iFrame.remove();
                    } else {
                        previewWindow.close();
                    }
                    previewWindow = iFrame = false;
                }
                if (!options.previewAutoRefresh) {
                    refreshPreview();
                }
                if (options.previewInWindow) {
                    previewWindow.focus();
                }
            }

            // refresh Preview window
            function refreshPreview() {
                renderPreview();
            }

            function renderPreview() {
                var phtml;
                if (options.previewHandler && typeof options.previewHandler === 'function') {
                    options.previewHandler( $$.val() );
                } else if (options.previewParser && typeof options.previewParser === 'function') {
                    var data = options.previewParser( $$.val() );
                    writeInPreview(localize(data, 1) );
                } else if (options.previewParserPath !== '') {
                    $.ajax({
                        type: 'POST',
                        dataType: 'text',
                        global: false,
                        url: options.previewParserPath,
                        data: options.previewParserVar+'='+encodeURIComponent($$.val()),
                        success: function(data) {
                            writeInPreview( localize(data, 1) );
                        }
                    });
                } else {
                    if (!template) {
                        $.ajax({
                            url: options.previewTemplatePath,
                            dataType: 'text',
                            global: false,
                            success: function(data) {
                                writeInPreview( localize(data, 1).replace(/<!-- content -->/g, $$.val()) );
                            }
                        });
                    }
                }
                return false;
            }

            function writeInPreview(data) {
                if (options.previewInElement) {
                    $(options.previewInElement).html(data);
                } else if (previewWindow) {
                    try {
                        sp = previewWindow.get().scrollTop
                    } catch(e) {
                        sp = 0;
                    }
                    previewWindow.html(data);
                    previewWindow.get().scrollTop = sp;
                }
            }

            // set keys pressed
            function keyPressed(e) {
                shiftKey = e.shiftKey;
                altKey = e.altKey;
                ctrlKey = (!(e.altKey && e.ctrlKey)) ? (e.ctrlKey || e.metaKey) : false;

                if (e.type === 'keydown') {
                    if (ctrlKey === true) {
                        li = $('a[accesskey="'+((e.keyCode == 13) ? '\\n' : String.fromCharCode(e.keyCode))+'"]', header).parent('li');
                        if (li.length !== 0) {
                            ctrlKey = false;
                            setTimeout(function() {
                                li.triggerHandler('mouseup');
                            },1);
                            return false;
                        }
                    }
                    if (e.keyCode === 13 || e.keyCode === 10) { // Enter key
                        if (ctrlKey === true) {  // Enter + Ctrl
                            ctrlKey = false;
                            markup(options.onCtrlEnter);
                            return options.onCtrlEnter.keepDefault;
                        } else if (shiftKey === true) { // Enter + Shift
                            shiftKey = false;
                            markup(options.onShiftEnter);
                            return options.onShiftEnter.keepDefault;
                        } else { // only Enter
                            markup(options.onEnter);
                            return options.onEnter.keepDefault;
                        }
                    }
                    if (e.keyCode === 9) { // Tab key
                        if (shiftKey == true || ctrlKey == true || altKey == true) {
                            return false;
                        }
                        if (caretOffset !== -1) {
                            get();
                            caretOffset = $$.val().length - caretOffset;
                            set(caretOffset, 0);
                            caretOffset = -1;
                            return false;
                        } else {
                            markup(options.onTab);
                            return options.onTab.keepDefault;
                        }
                    }
                }
            }

            function remove() {
                $$.unbind(".markItUp").removeClass('markItUpEditor');
                $$.parent('div').parent('div.markItUp').parent('div').replaceWith($$);

                var relativeRef = $$.parent('div').parent('div.markItUp').parent('div');
                if (relativeRef.length) {
                    relativeRef.replaceWith($$);
                }

                $$.data('markItUp', null);
            }

            init();
        });
    };

    $.fn.markItUpRemove = function() {
        return this.each(function() {
                $(this).markItUp('remove');
            }
        );
    };

    $.markItUp = function(settings) {
        var options = { target:false };
        $.extend(options, settings);
        if (options.target) {
            return $(options.target).each(function() {
                $(this).focus();
                $(this).trigger('insertion', [options]);
            });
        } else {
            $('textarea').trigger('insertion', [options]);
        }
    };
})(jQuery);

function checkVideoLink(v) {
    var l = v.toLowerCase();
    if (l.indexOf("youtube.com") >= 0) {
        v = v.replace(/[^\.]*\.*youtube\.com\/watch\?v=([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*youtube\.com\/watch\?[^?]+&v=([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*youtube\.com\/embed\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("youtu.be") >= 0) {
        v = v.replace(/[^\.]*\.*youtu\.be\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("vimeo.com") >= 0) {
        v = v.replace(/[^\.]*\.*vimeo\.com\/video\/([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*vimeo\.com\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("liveleak.com") >= 0) {
        v = v.replace(/[^\.]*\.*liveleak\.com\/view\?i=([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*liveleak\.com\/e\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("veoh.com") >= 0) {
        v = v.replace(/[^\.]*\.*veoh\.com\/swf\/webplayer\/WebPlayer\.swf\?[^\n]*permalinkId=([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*veoh\.com\/watch\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("dailymotion.com") >= 0) {
        v = v.replace(/[^\.]*\.*dailymotion\.com\/video\/([^\/&#_]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*dailymotion\.com\/embed\/video\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("dai.ly") >= 0) {
        v = v.replace(/[^\.]*\.*dai\.ly\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("myspace.com") >= 0) {
        v = v.replace(/[^\.]*\.*myspace\.com\/services\/media\/[^\n]*[^a-z]m=([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*myspace\.com\/[^\n]*\/([^\/]+)/ig, "$1");
    } else if (l.indexOf("wegame.com") >= 0) {
        v = v.replace(/[^\.]*\.*wegame\.com\/static\/flash\/[^\n]*\/video\/([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*wegame\.com\/watch\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("collegehumor.com") >= 0) {
        v = v.replace(/[^\.]*\.*collegehumor\.com\/e\/([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*collegehumor\.com\/video\/([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("vevo.com") >= 0) {
        v = v.replace(/[^\.]*\.*vevo\.com\/embed\/[^\n]*videoId=([^\/&#]+)[^\n]*/ig, "$1");
    } else if (l.indexOf("funnyordie.com") >= 0) {
        v = v.replace(/[^\.]*\.*funnyordie\.com\/videos\/([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*funnyordie\.com\/embed\/([^\/&#]+)[^\n]*/ig, "$1");
        v = v.replace(/[^\.]*\.*funnyordie\.com\/m\/([^\/&#]+)[^\n]*/ig, "$1");
    }
    return v;
}

var bbcodeSettings = {
    nameSpace:          "bbcode", // Useful to prevent multi-instances CSS conflict
    previewParserPath:  "/bbcode/preview",
    markupSet: [
        {name:'Жирный', key:'B', openWith:'[b]', closeWith:'[/b]'},
        {name:'Курсив', key:'I', openWith:'[i]', closeWith:'[/i]'},
        {name:'Подчеркнутый', key:'U', openWith:'[u]', closeWith:'[/u]'},
        {name:'Зачеркнутый', openWith:'[s]', closeWith:'[/s]'},
        {separator:'---------------' },
        {name:'Рисунок', key:'P', replaceWith:'[img][![Url]!][/img]'},
//        {name:'Видео', dropMenu: [
//            {name:'Youtube', openWith:'[video="youtube"][![Введите ссылку на видео или его ID]!][/video]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Vimeo', openWith:'[vimeo][![Введите ссылку на видео или его ID]!][/vimeo]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Liveleak', openWith:'[liveleak][![Введите ссылку на видео или его ID]!][/liveleak]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Veoh', openWith:'[veoh][![Введите ссылку на видео или его ID]!][/veoh]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Dailymotion', openWith:'[dailymotion][![Введите ссылку на видео или его ID]!][/dailymotion]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'MySpace', openWith:'[myspace][![Введите ссылку на видео или его ID]!][/myspace]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Wegame', openWith:'[wegame][![Введите ссылку на видео или его ID]!][/wegame]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Collegehumor', openWith:'[collegehumor][![Введите ссылку на видео или его ID]!][/collegehumor]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Vevo', openWith:'[vevo][![Введите ссылку на видео или его ID]!][/vevo]', checkValue: function(v) { return checkVideoLink(v); } },
//            {name:'Funnyordie', openWith:'[funnyordie][![Введите ссылку на видео или его ID]!][/funnyordie]', checkValue: function(v) { return checkVideoLink(v); } }
//        ]},
        {name:'Письмо', openWith:'[email="[![Email]!]"]', closeWith:'[/email]', placeHolder:'Send to...'},
        {name:'Ссылка', key:'L', openWith:'[url="[![Url]!]"]', closeWith:'[/url]', placeHolder:'Your text to link here...'},
        {separator:'---------------' },
        {name:'Заголовок', dropMenu: [
            {name:'Заголовок 1', openWith:'[h1]', closeWith:'[/h1]' },
            {name:'Заголовок 2', openWith:'[h2]', closeWith:'[/h2]' },
            {name:'Заголовок 3', openWith:'[h3]', closeWith:'[/h3]' },
            {name:'Заголовок 4', openWith:'[h4]', closeWith:'[/h4]' },
            {name:'Заголовок 5', openWith:'[h5]', closeWith:'[/h5]' },
            {name:'Заголовок 6', openWith:'[h6]', closeWith:'[/h6]' }
        ]},
        {name:'Цвета', openWith:'[color="[![Color]!]"]', closeWith:'[/color]', dropMenu: [
            {name:'Желтый', openWith:'[color="yellow"]', closeWith:'[/color]', className:"col1-1" },
            {name:'Оранжевый', openWith:'[color="orange"]', closeWith:'[/color]', className:"col1-2" },
            {name:'Красный', openWith:'[color="red"]', closeWith:'[/color]', className:"col1-3" },
            {name:'Синий', openWith:'[color="blue"]', closeWith:'[/color]', className:"col2-1" },
            {name:'Пурпурный', openWith:'[color="purple"]', closeWith:'[/color]', className:"col2-2" },
            {name:'Зеленый', openWith:'[color="green"]', closeWith:'[/color]', className:"col2-3" },
            {name:'Фиолетовый', openWith:'[color="magenta"]', closeWith:'[/color]', className:"col3-1" },
            {name:'Серый', openWith:'[color="gray"]', closeWith:'[/color]', className:"col3-2" },
            {name:'Черный', openWith:'[color="black"]', closeWith:'[/color]', className:"col3-3" }
        ]},
        {name:'Размер шрифта', key:'S', dropMenu :[
            {name:'Крупный', openWith:'[big]', closeWith:'[/big]' },
            {name:'Маленький', openWith:'[small]', closeWith:'[/small]' },
            {name:'Подстрочный', openWith:'[sub]', closeWith:'[/sub]', className:"sub" },
            {name:'Надстрочный', openWith:'[sup]', closeWith:'[/sup]', className:"sup" }
        ]},
        {name:'По центру', openWith:'[center]', closeWith:'[/center]', dropMenu :[
            {name:'По левому краю', openWith:'[left]', closeWith:'[/left]', className:"left" },
            {name:'По ширине', openWith:'[justify]', closeWith:'[/justify]', className:"justify" },
            {name:'По правому краю', openWith:'[right]', closeWith:'[/right]', className:"right" }
        ]},
        {separator:'---------------' },
        {name:'Таблица', openWith:'[table]\n  [tr]\n    [td]', closeWith:'[/td]\n  [/tr]\n[/table]', dropMenu: [
            {name:'Table', openWith:'[table]', closeWith:'[/table]'},
            {name:'THead', openWith:'[thead]', closeWith:'[/thead]'},
            {name:'TBody', openWith:'[tbody]', closeWith:'[/tbody]'},
            {name:'TFoot', openWith:'[tfoot]', closeWith:'[/tfoot]'},
            {name:'TH', openWith:'[th]', closeWith:'[/th]'},
            {name:'TR', openWith:'[tr]', closeWith:'[/tr]'},
            {name:'TD', openWith:'[td]', closeWith:'[/td]'}
        ]},
        {name:'Список', openWith:'[list]\n[*]', closeWith:'\n[/list]'},
        {name:'Пронумерованный список', openWith:'[list=1]\n[*]', closeWith:'\n[/list]'},
        {name:'Элемент списка', openWith:'[*]'},
        {name:'Разрыв строки', openWith:'[br]'},
        {separator:'---------------' },
        {name:'Цитата', openWith:'[quote]', closeWith:'[/quote]'},
        {separator:'---------------' },
        {name:'Эмоции', openWith:'[![Emotion]!]', dropMenu: [
            /*
             {name:'Счастливый', openWith:' :) ', className:"col1-1" },
             {name:'Восторженный', openWith:' :D ', className:"col1-2" },
             {name:'Хм', openWith:' :/ ', className:"col1-3" },
             {name:'Злой', openWith:' >[ ', className:"col1-4" },
             {name:'Язык', openWith:' :p ', className:"col2-1" },
             {name:'Что', openWith:' :? ', className:"col2-2" },
             {name:'Апатия', openWith:' :| ', className:"col2-3" },
             {name:'Раздражение', openWith:' :aw: ', className:"col2-4" },
             {name:'Круто', openWith:' 8) ', className:"col3-1" },
             {name:'Яростный', openWith:' >< ', className:"col3-2" },
             {name:'Аааа!', openWith:' :O ', className:"col3-3" },
             {name:'Сердце', openWith:' <3 ', className:"col3-4" },
             {name:'Поцелуй', openWith:' :3 ', className:"col4-1" },
             {name:'Молчок', openWith:' :x ', className:"col4-2" },
             {name:'Печальный', openWith:' :( ', className:"col4-3" },
             {name:'Подмигивание', openWith:' ;) ', className:"col4-4" }
             */
            {name:'Улыбка', openWith:' :) ', className:"col1-1" },
            {name:'Подмигивание', openWith:' ;) ', className:"col1-2" },
            {name:'Смех', openWith:' :D ', className:"col1-3" },
            {name:'Ржач', openWith:' :-D ', className:"col1-4" },
            {name:'LOL', openWith:' :lol: ', className:"col2-1" },
            {name:'Язык', openWith:' :P ', className:"col2-2" },
            {name:'Злорадный', openWith:' :malicious: ', className:"col2-3" },
            {name:'Грустный', openWith:' :( ', className:"col2-4" },
            {name:'Плачет', openWith:' :cry: ', className:"col3-1" },
            {name:'Хм', openWith:' 8| ', className:"col3-2" },
            {name:'Злобный', openWith:' :angry: ', className:"col3-3" },
            {name:'Ругается', openWith:' :0 ', className:"col3-4" },
            {name:'Фингал', openWith:' :fingal: ', className:"col4-1" },
            {name:'Восклицание', openWith:' :!: ', className:"col4-2" },
            {name:'Вопрос', openWith:' :?: ', className:"col4-3" },
            {name:'Сердце', openWith:' :heart: ', className:"col4-4" },
            {name:'Поцелуй', openWith:' :kiss: ', className:"col5-1" },
            {name:'Палец вверх', openWith:' :thumbs_up: ', className:"col5-2" },
            {name:'Палец вниз', openWith:' :thumbs_down: ', className:"col5-3" },
            {name:'Пальцы веером', openWith:' :fingers_fan: ', className:"col5-4" },
        ]},
        {separator:'---------------' },
        {name:'Очистить', className:"clean", replaceWith:function(h) { return h.selection.replace(/\[(.*?)\]/g, "") } },
        {name:'Предпросмотр (Нажмите с Alt чтобы закрыть)', className:"preview", call:'preview' }
    ]
}

$(document).ready(function()	{
    $('.bbcode').markItUp(bbcodeSettings);
});
