var oBBCode = new function()
{
    var _aVideoServices = [
        [
            /<object width="(.*?)" height="(.*?)">.*?<param.+?name="movie".+?value="(http:\/\/www\.youtube\.com.*?)">.*?<\/object>/ig,
            '[youtube src="$3" width="$1" height="$2"]',
            'YouTube'
        ],
        [
            /<embed.+?src="(http:\/\/www\.metacafe\.com.*?)".+?width="(.*?)".+?height="(.*?)".*?<\/font>/ig,
            '[metacafe src="$1" width="$2" height="$3"]',
            'metacafe'
        ],
        [
            /<object.+?width="(.*?)".+?height="(.*?)".*?>.*?<embed.+?src="(http:\/\/[\w\-\.]*?patrz\.pl\/.*?)".*?<\/embed><\/object>/ig,
            '[patrz src="$3" width="$1" height="$2"]',
            'patrz.pl'
        ],
        [
            /<script type="text\/javascript" src="(http:\/\/www\.wrzuta\.pl\/embed_video.js.*?width=([0-9]+)&height=([0-9]+).*)"><\/script>/ig,
            '[wrzuta src="$1" width="$2" height="$3"]',
            'wrzuta.pl'
        ],
        [
            //<div style="width:425px;text-align:left" id="__ss_2211180"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/gerardodada/find-the-risk-vs-reward-balance-in-social-media" title="Find the Risk vs. Reward Balance in Social Media">Find the Risk vs. Reward Balance in Social Media</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=riskrewardssocialmediafinal2007-091013132216-phpapp01&stripped_title=find-the-risk-vs-reward-balance-in-social-media" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=riskrewardssocialmediafinal2007-091013132216-phpapp01&stripped_title=find-the-risk-vs-reward-balance-in-social-media" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object><div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/gerardodada">Gerardo Dadadada</a>.</div></div>
            /<div.*?<a.*?<embed.+?src="(http:\/\/[\w\-\.]*?slideshare[\w\-]*?\.(?:com|net).*?)".+?width="([0-9]+)".+?height="([0-9]+)".*?<\/div><\/div>.*?/ig,
            '[slideshare src="$1" width="$2" height="$3"]',
            'slideshare'
        ],
        [
            /<object.+?width="(.*?)".+?height="(.*?)".+?(data|value)="(http:\/\/vimeo\.com.*?)".*?<a href="http:\/\/vimeo\.com">Vimeo<\/a>\.<\/p>.*?/ig,
            '[vimeo src="$4" width="$1" height="$2"]',
            'vimeo'
        ],
        [
            /<div><a.*?>.*?<\/a><div><object.+?width="([0-9]+)".+?height="([0-9]+)".*?FlashVars="(.*?)".*?<\/embed><\/object><\/div><\/div>/ig,
            '[videogazetapl src="$3" width="$1" height="$2"]',
            'Gazeta.pl Plej'
        ],
        [
            /<script.*?src='(http:\/\/filmownia.org\/.*?)'>.*?<\/script>/ig,
            '[filmownia src="$1"]',
            'Filmownia.org'
        ],
        [
            /<embed.*?src="(http:\/\/blip\.tv\/.*?)".*?width="(.*?)".*?height="(.*?)".*?<\/embed>/ig,
            '[bliptv src="$1" width="$2" height="$3"]',
            'blip.tv'
        ],
        [
            /<script\s+type="text\/javascript"\s+src="(http:\/\/[\w\-\.]*?interia\.pl\/.*?),([0-9]+),([0-9]+)"><\/script>/ig,
            '[video_interia src="$1" width="$2" height="$3"]',
            'interia.pl'
        ],
        [
            //<a href="http://video.msn.com/video.aspx?mkt=pl-PL&vid=5e797d0b-6ca3-4cc5-9303-eaf3a86ce49a" target="_new" title="Palikot: Schetyna popełnił błąd pychy"><img src="http://img3.catalog.video.msn.com/Image.aspx?uuid=5e797d0b-6ca3-4cc5-9303-eaf3a86ce49a&w=112&h=84" border=0 alt="Palikot: Schetyna popełnił błąd pychy" width=112 height=84><br />Palikot: Schetyna popełnił błąd pychy</a>
            /<a href="(http:\/\/video\.msn\.com\/.*?)".+?title="(.*?)".*?<img.+?src="(.*?)".+?width=([0-9]+).+?height=([0-9]+).+?<\/a>/ig,
            '[msn src="$1" title="$2" img="$3" width="$4" height="$5"]',
            'MSN Video'
        ],
        [
            /<embed src='http:\/\/krak\.tv\/.*?'\s+height='(.*?)'\s+width='(.*?)'.+?flashvars='(.*?)'.*?\/>/ig,
            '[kraktv src="$3" width="$2" height="$1"]',
            'krak.tv'
        ],
        [
            /<object\s+width="(.*?)"\s+height="(.*?)".+?<param\s+name="flashvars"\s+value="(.*?=http:\/\/[\w\.]*?beeatwork\.(com\.)?pl\/.*?)".+?<\/embed><\/object>/ig,
            '[beeatwork src="$3" width="$1" height="$2"]',
            'beeatwork.pl'
        ]
    ];

    this.getVideoServicesNames = function()
    {
        var aServicesNames = [];
        for (var i in _aVideoServices) {
            aServicesNames.push(_aVideoServices[i][2]);
        }
        return aServicesNames;
    };


    this.translateVideoObjects = function(sCode, bReturnFalseOnFail)
    {
        var bDetected = false;

        for (var i in _aVideoServices)
        {
            if (sCode.match(_aVideoServices[i][0])) {
                bDetected = true;
                sCode = sCode.replace(_aVideoServices[i][0], _aVideoServices[i][1]);
            }
        }

        if (bDetected || !bReturnFalseOnFail) {
            return sCode;
        }
        return false;
    };


    this.translateTextAreaVideoObjects = function(xTextArea)
    {
        oTextArea = $(xTextArea);
        oTextArea.val(this.translateVideoObjects(oTextArea.val()));
    };


    this.insertBBCode = function(sStartTag, sEndTag, xInput, bIgnoreSelection)
    {
        var oInput = $(xInput).get(0),
            jInput = $(oInput);
        try {
            if (document.selection)
            {
                var sSelectedText = document.selection.createRange().text;
                oInput.focus();
                var oSelectionRange = document.selection.createRange();
                oSelectionRange.text = sStartTag + (bIgnoreSelection ? '' : sSelectedText) + sEndTag;
            }
            else
            {
                var iSelectionLength = oInput.textLength,
                    iSelectionStart = oInput.selectionStart,
                    iSelectionEnd = oInput.selectionEnd,
                    sBeforeText = jInput.val().substring(0, iSelectionStart),
                    sSelectedText = jInput.val().substring(iSelectionStart, iSelectionEnd),
                    sAfterText = jInput.val().substring(iSelectionEnd, iSelectionLength);

                jInput.val(sBeforeText + sStartTag + (bIgnoreSelection ? '' : sSelectedText) + sEndTag + sAfterText);
                oInput.selectionStart = jInput.val().length - sAfterText.length;
                oInput.selectionEnd = jInput.val().length - sAfterText.length;
            }
        }
        finally {
            oInput.focus();
        }
    };


    this.insertText = function(sText, xInput)
    {
        var oInput = $(xInput).get(0),
            jInput = $(oInput);
        try {
            if (document.selection)
            {
                oInput.focus();
                (document.selection.createRange()).text = sText;
            }
            else
            {
                var iSelectionLength = oInput.textLength,
                    iSelectionStart = oInput.selectionStart,
                    iSelectionEnd = oInput.selectionEnd,
                    sBeforeText = jInput.val().substring(0, iSelectionStart),
                    sAfterText = jInput.val().substring(iSelectionEnd, iSelectionLength);

                jInput.val(sBeforeText + sText + sAfterText);
                oInput.selectionStart = jInput.val().length - sAfterText.length;
                oInput.selectionEnd = jInput.val().length - sAfterText.length;
            }
        }
        finally {
            oInput.focus();
        }
    };


    this.insertLink = function(xInput)
    {
        var sURL = prompt(GetTranslation('Podaj link do strony www:'));
        if (sURL) {
            this.insertBBCode('[url=' + oUtils.makeHTTP(sURL) + ']', '[/url]', xInput);
        }
    };


    this.markAsCite = function(xInput)
    {
        var sAuthor = prompt(GetTranslation('Podaj nazwisko autora komentarza'), '');
        if (sAuthor) {
            this.insertBBCode('[cite author="' + sAuthor + '"]', '[/cite]', xInput);
        }
    };


    this.insertImage = function(sURL, xInput, bNoAutoHTTP)
    {
        if (sURL.trim().length) {
            this.insertBBCode('[img]' + (bNoAutoHTTP ? sURL : oUtils.makeHTTP(sURL)), '[/img]', xInput, true);
        }
    };


    this.insertVideo = function(sCode, xInput)
    {
        if (sCode.trim().length) {
            sCode = this.translateVideoObjects(sCode, true);
            if (sCode !== false) {
                this.insertText(sCode, xInput);
            }
        }
    };
};

function oBBCodeToolbar(xContainer, xInput)
{
    var _iRequestCount = 0,
        _oResponse = false,
        _jBlocker,
        _jBlockerLoader,
        _aThreads = [];

    var _prepareAjaxOptions = function(oOptions)
    {
        oOptions.async = typeof oOptions.async == 'undefined' ? true : oOptions.async;
        oOptions.beforeSend = _onRequestBegin;
        oOptions.complete = _onRequestEnd;
        oOptions.success = _onRequestSuccess;
        oOptions.error = oOptions.timeout = _onRequestError;
        oOptions.dataType = typeof oOptions.dataType == 'undefined' ? 'json' : oOptions.dataType;
        oOptions.type = typeof oOptions.type == 'undefined' ? 'GET' : oOptions.type;
        return oOptions;
    };


    var _onRequestBegin = function(oXHR)
    {
        _oResponse = false;
        if (_iRequestCount == 0 ) {
            if (oPopupWindow.isVisible()) {
                oPopupWindow.showWndBlocker();
            }
            //_jContent.slideUp();
        }
        _iRequestCount++;
    };


    var _onRequestEnd = function()
    {
        _iRequestCount--;
        if (_iRequestCount == 0) {
            oPopupWindow.hideWndBlocker();
            //_jContent.slideDown();
        } else {
            _jBlocker.height(_jBlocker.parent().outerHeight() + 'px');
        }
    };


    var _onRequestSuccess = function(oData)
    {
        _oResponse = oData;
    };


    var _onRequestError = function()
    {

    };


    var _sliceArguments = function(aArguments, iStart, iLength)
    {
        iLength = ((!iLength || iLength > aArguments.length) ? aArguments.length - iStart : iLength) + iStart;
        aResult = [];
        for (var i = iStart; i < iLength; i++) {
            aResult.push(aArguments[i]);
        }
        return aResult;
    };


    var _ajax = function(oOptions, fCallback, aArguments)
    {
        if (_iRequestCount) return;
        oOptions = _prepareAjaxOptions(oOptions);
        oOptions.complete = function(oData) {
            if (typeof fCallback == 'function') {
                fCallback(oData, aArguments);
            }
            $('.ui-tabsdiv').tabs();
            $("textarea[maxlength]").each(function() { $(this).maxLength(this.getAttribute('maxlength')); });
            $('a.thickbox').lightBox(oLightboxDefaultOptions);
            _onRequestEnd();
        }
        $.ajax(oOptions);
    };


    var _ajaxForm = function(oForm, fCallback)
    {
        var aArguments = _sliceArguments(arguments, 2);
        _ajax({
            url : $(oForm).attr('action'),
            data : $(oForm).serialize(),
            type : $(oForm).attr('method')
        },
        fCallback, aArguments);
    };


    var _ajaxFormWithFiles = function(oForm, fCallback)
    {
        var aArguments = _sliceArguments(arguments, 2);
        _onRequestBegin();
        oIFrameAjax.sendForm(oForm, $(oForm).attr('action'), $(oForm).attr('method'), function(sResponse){
            try {
                _oResponse = eval('_oResponse = ' + sResponse);
                if (typeof fCallback == 'function') {
                    fCallback();
                }
                _setContent();
                $('.ui-tabsdiv').tabs();
                $("textarea[maxlength]").each(function() { $(this).maxLength(this.getAttribute('maxlength')); });
                $('a.thickbox').lightBox(oLightboxDefaultOptions);
            }
            finally {
                _onRequestEnd();
            }
        }, aArguments);
    };


    var _setContent = function()
    {
        oPopupWindow.setWindowContent(_oResponse.content);
    };


    var _loadContent = function(oOptions, fCallback)
    {
        var aArguments = _sliceArguments(arguments, 2);
        _ajax(oOptions, function(oResponse, aArguments) {
            _setContent();
            if (typeof fCallback == 'function') {
                fCallback();
            }
        }, aArguments);

    };


    this.loadPage = function(sURL)
    {
        _loadContent({ url : sURL }, function() {
            oPopupWindow.showWindow('500px', null);
        });
    };

    this.togglePanel = function(sPanelName)
    {
        var jPanels = _jContainer.find('.panels'),
            jPanel = jPanels.find('.panel.'+sPanelName);
        if (jPanel.is(':visible')) {
            jPanels.find('.panel').hide();
        } else {
            jPanels.find('.panel').hide();
            jPanel.show();
        }
        return false;
    };


    this.insertBBCode = function(sStartTag, sEndTag, bIgnoreSelection)
    {
        oBBCode.insertBBCode(sStartTag, sEndTag, _jInput, bIgnoreSelection);
    };


    this.insertText = function(sText)
    {
        oBBCode.insertText(sText, _jInput);
    };


    this.insertLink = function()
    {
        oBBCode.insertLink(_jInput);
    };


    this.markAsCite = function()
    {
        oBBCode.markAsCite(_jInput);
    };


    this.insertImage = function(sURL, bNoAutoHTTP)
    {
        oBBCode.insertImage(sURL, _jInput, bNoAutoHTTP);
    };


    this.insertVideo = function(sCode)
    {
        oBBCode.insertVideo(sCode, _jInput);
    };


    this.insertImageFromInput = function(xInput)
    {
        oBBCode.insertImage($(xInput).val(), _jInput);
        $(xInput).val('');
    };


    this.insertVideoFromInput = function(xInput)
    {
        oBBCode.insertVideo($(xInput).val(), _jInput);
        $(xInput).val('');
    };

    var _that = this,
        _jContainer = $(xContainer),
        _jInput = $(xInput);

    _jContainer.get(0)._oBBCT = _that;
    _jContainer.find('*').each(function() { this._oBBCT = _that; });
    this.oContainer = _jContainer;

    _jContainer.find('.bbcCtrlBold').click(function(){ oBBCode.insertBBCode('[b]', '[/b]', _jInput); return false; });
    _jContainer.find('.bbcCtrlItalic').click(function(){ oBBCode.insertBBCode('[i]', '[/i]', _jInput); return false; });
    _jContainer.find('.bbcCtrlUnderline').click(function(){ oBBCode.insertBBCode('[u]', '[/u]', _jInput); return false; });
    _jContainer.find('.bbcCtrlLink').click(function(){ oBBCode.insertLink(_jInput); return false; });
    _jContainer.find('.bbcCtrlCite').click(function(){ oBBCode.markAsCite(_jInput); return false; });
    _jContainer.find('.bbcCtrlVideo').click(function(){ _that.togglePanel('video'); return false; });
    _jContainer.find('.bbcCtrlPicture').click(function(){ _that.togglePanel('picture'); return false; });

    _jContainer.find('.bbctAvailableServices').html(oBBCode.getVideoServicesNames().join(', '));

};