/**
 * WYSIWYG - jQuery plugin 0.5
 *
 * Copyright (c) 2008-2009 Juan M Martinez
 * http://plugins.jquery.com/project/jWYSIWYG 
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Id: $
 */
(function( $ )
{
    $.fn.document = function()
    {
        var element = this[0];

        if ( element.nodeName.toLowerCase() == 'iframe' && element.contentWindow )
            return element.contentWindow.document;
            /*
            return ( $.browser.msie )
                ? document.frames[element.id].document
                : element.contentWindow.document // contentDocument;
             */
        else
            return $(this);
    };

    $.fn.documentSelection = function()
    {
        var element = this[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 the user set custom controls, we catch it, and merge with the
         * defaults controls later.
         */
        if ( options && options.controls )
        {
            var controls = options.controls;
            delete options.controls;
        }

        var 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</head><body>INITIAL_CONTENT</body></html>',
            css  : {},

            debug        : false,

            autoSave     : true,  // http://code.google.com/p/jwysiwyg/issues/detail?id=11
            rmUnwantedBr : true,  // http://code.google.com/p/jwysiwyg/issues/detail?id=15
            brIE         : true,

            controls : {},
            messages : {}
        }, options);

		try {
			if (typeof options.lang == 'undefined') throw '1';
			var lang = 'MSGS_' + options.lang.toUpperCase();
			if (typeof Wysiwyg[lang] == 'undefined') throw '2';
			options.messages = $.extend(true, options.messages, Wysiwyg[lang]);
		} catch ( ex ) {
			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];
        }

        // not break the chain
        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, {
        insertImage : function( szURL, attributes )
        {
            var self = $.data(this, 'wysiwyg');

            if ( self.constructor == Wysiwyg && szURL && szURL.length > 0 )
            {
				self.reFocus();
                if ( attributes )
                {
                    self.editorDoc.execCommand('insertImage', false, '#jwysiwyg#');
                    var img = self.getElementByAttributeValue('img', 'src', '#jwysiwyg#');

                    if ( img )
                    {
                        img.src = szURL;

                        for ( var attribute in attributes )
                        {
                            $(img).attr(attribute, attributes[attribute]);
                        }
                    }
                }
                else
                {
                    self.editorDoc.execCommand('insertImage', false, szURL);
                }
            }
        },

        createLink : function( szURL, attributes )
        {
            var self = $.data(this, 'wysiwyg');

            if ( self.constructor == Wysiwyg && szURL && szURL.length > 0 )
            {
                var selection = $(self.editor).documentSelection();

                if ( selection.length > 0 )
                {
                    self.editorDoc.execCommand('unlink', false, []);
					
					if ( attributes ) {
						self.editorDoc.execCommand('createLink', false, '#jwysiwyg#');
						var anchor = self.getElementByAttributeValue('a', 'href', '#jwysiwyg#');

						if ( anchor )
						{
							anchor.href = szURL;

							for ( var attribute in attributes )
							{
								$(anchor).attr(attribute, attributes[attribute]);
							}
						}
					} else {
						self.editorDoc.execCommand('createLink', false, szURL);
					}
                }
                else if ( self.options.messages.nonSelection )
                    alert(self.options.messages.nonSelection);
            }
        },

        setContent : function( newContent )
        {
            var self = $.data(this, 'wysiwyg');
                self.setContent( newContent );
                self.saveContent();
        },

        clear : function()
        {
            var self = $.data(this, 'wysiwyg');
                self.setContent('<br />');
                self.saveContent();
        },

        MSGS_EN : {
            nonSelection : 'select the text you wish to link'
        },
        MSGS_RU : {
            nonSelection : 'select the text you wish to link'
        },

        TOOLBAR : {
		
		
		
            bold          : { visible : true, tags : ['b', 'strong'], css : { fontWeight : 'bold' } },
            italic        : { visible : true, tags : ['i', 'em'], css : { fontStyle : 'italic' } },
            strikeThrough : { visible : true, tags : ['s', 'strike'], css : { textDecoration : 'line-through' } },
            underline     : { visible : true, tags : ['u'], css : { textDecoration : 'underline' } },

            separator00 : { visible : true, separator : true },
			
            subscript   : { visible : true, tags : ['sub'] },
            superscript : { visible : true, tags : ['sup'] },

            separator03 : { visible : true, separator : true },

            justifyLeft   : { visible : true, extended : true, css : { textAlign : 'left' } },
            justifyCenter : { visible : true, extended : true, tags : ['center'], css : { textAlign : 'center' } },
            justifyRight  : { visible : true, extended : true, css : { textAlign : 'right' } },
            justifyFull   : { visible : false, extended : true, css : { textAlign : 'justify' } },

            separator01 : { visible : true, extended : true, separator : true },

            indent  : { visible : true, extended : true },
            outdent : { visible : true, extended : true },

            separator02 : { visible : true, extended : true, separator : true },
			
            insertOrderedList    : { visible : true, extended : true, tags : ['ol'] },
            insertUnorderedList  : { visible : true, extended : true, tags : ['ul'] },
            insertHorizontalRule : { visible : true, extended : true, tags : ['hr'] },

            separator05 : { visible: true, extended : true, separator : true },
			
            createLink : {
                visible : true,
				extended : true,
                exec    : function()
                {
                    var selection = $(this.editor).documentSelection();

                    if ( selection.length > 0 )
                    {
                        if ( $.browser.msie )
                            this.editorDoc.execCommand('createLink', true, null);
                        else
                        {
                            var szURL = prompt('URL', 'http://');

                            if ( szURL && szURL.length > 0 )
                            {
								//var target = confirm(typeof settings['open_in_new_window'] != 'undefined' ? settings['open_in_new_window'] : 'Open in New Window?');
								var target = true;
								$( this.original ).wysiwyg('createLink', szURL, { 'target': target ? '_blank' : '_self' });
                                //this.editorDoc.execCommand('unlink', false, []);
                                //this.editorDoc.execCommand('createLink', false, szURL);
                            }
                        }
                    }
                    else if ( this.options.messages.nonSelection )
                        alert(this.options.messages.nonSelection);
                },

                tags : ['a']
            },
			
            insertImage : {
                visible : true,
				extended : false,
                exec    : function()
                {
					//setAction(settings.url + '/photo/wysiwyg/');
                    if ( $.browser.msie )
                        this.editorDoc.execCommand('insertImage', true, null);
                    else
                    {
                        var szURL = prompt('URL', 'http://');

                        if ( szURL && szURL.length > 0 )
                            this.editorDoc.execCommand('insertImage', false, szURL);
                    }
                },

                tags : ['img']
            },
			uploadImage : {
				visible : false,
				exec 	: function() 
				{
					var self = this;
					var pathVal = 'YToxOntpOjA7YToxOntTOjU6ImxhYmVsIjtTOjEzOiJ3eXNpd3lnX2ltYWdlIjt9fQ'; // PATH 0 => array('label' => 'wysiwyg_image');
					if (!$('#' + this.editor.attr('ID') + 'ImageUploader').length) {
						var uploadLayer = $('<div></div>')
							.attr({
								'ID' : this.editor.attr('ID') + 'ImageUploader'
							})
							.css({
								'position' : 'absolute',
								'border' : '1px solid #898989',
								'background' : '#fff',
								'padding' : '3px 5px',
								'display' : 'none',
								'z-index' : 1000
							});
						var uploadForm = $('<form></form>')
							.attr({
								'target' : 'postFrame',
								'method' : 'post',
								'enctype' : 'multipart/form-data',
								'encoding' : 'multipart/form-data',
								'action' : ''
							})
							.append('<input type="hidden" name="PATH" value='+pathVal+' />')
							.append('<div><input type="file" name="src" /></div>')
							.append('<div><input type="submit" value="Upload & Add" /></div>')
							.bind('submit', function( event ) {
								$(this).unbind('submit');
								setAction('?ACTION=WYSIWYGIMAGE', this, true, function( content ) {
									self.uploadImageSuccess( content );
									uploadLayer.fadeOut('fast');
								});
								return false;
							}).appendTo( uploadLayer );
						$('<input type="button" value="close" />')
							.bind('click', function() {
								uploadLayer.fadeOut('fast');
								//$(this).parents('form:first').trigger('reset');
							})
							.appendTo( uploadForm );
						uploadLayer.prependTo( this.panel.find('a.uploadImage').parent() ).fadeIn('fast');						
					} else {
						$('#' + this.editor.attr('ID') + 'ImageUploader').fadeIn('fast');
					}
				}
			},
			
            insertObject : {
                visible : true,
                exec    : function()
                {
					var szHTML = prompt('Embed Code', '');

					if ( szHTML && szHTML.length > 0 ) {
						this.editorDoc.execCommand('insertHTML', false, szHTML);
						this.saveContent();
						this.setContent( $(this.original).val() );
					}
                },

                tags : ['object']
            },
			
            separator06 : { visible : false, extended: true, separator : true },
			
			newline01 : { visible : true, extended : true, newline : true },

            undo : { visible : false },
            redo : { visible : false },

            separator04 : { visible: true, separator : true },

            h1mozilla : { visible : false && $.browser.mozilla, className : 'h1', command : 'heading', arguments : ['h1'], tags : ['h1'] },
            h2mozilla : { visible : false && $.browser.mozilla, className : 'h2', command : 'heading', arguments : ['h2'], tags : ['h2'] },
            h3mozilla : { visible : false && $.browser.mozilla, className : 'h3', command : 'heading', arguments : ['h3'], tags : ['h3'] },

            h1 : { visible : false && !( $.browser.mozilla ), className : 'h1', command : 'formatBlock', arguments : ['Heading 1'], tags : ['h1'] },
            h2 : { visible : false && !( $.browser.mozilla ), className : 'h2', command : 'formatBlock', arguments : ['Heading 2'], tags : ['h2'] },
            h3 : { visible : false && !( $.browser.mozilla ), className : 'h3', command : 'formatBlock', arguments : ['Heading 3'], tags : ['h3'] },

            separator07 : { visible : false, separator : true },

            cut   : { visible : false },
            copy  : { visible : false },
            paste : { visible : false },

            separator08 : { separator : false && !( $.browser.msie ) },

            increaseFontSize : { visible : true && !( $.browser.msie ), tags : ['big'] },
            decreaseFontSize : { visible : true && !( $.browser.msie ), tags : ['small'] },

            separator09 : { separator : true },

            removeFormat : {
                visible : true,
                exec    : function()
                {
                    this.editorDoc.execCommand('removeFormat', false, []);
                    this.editorDoc.execCommand('unlink', false, []);
                }
            },
			
			separator10 : { separator : false },
			
            html : {
                visible : true,
				inHTML	: true,
                exec    : function()
                {
                    if ( this.viewHTML ) {
					
                        this.setContent( $(this.original).val() );
						$(this.element).removeClass('whtml');
                        $(this.original).parent().hide();
                        $(this.editor).show();
						this.updateHeight();
						
                    } else {
					
						var self = this;
                        this.saveContent();
						$(this.element).addClass('whtml');
                        $(this.original).parent().show();
                        $(this.editor).hide();
						this.clearPanelTimeout();
						if (this.panel.position().top) {
							this.panel.animate( { 'top' : 0 }, 'fast', function() {
								self.panel.show();
							});
						}
						
                    }

                    this.viewHTML = !( this.viewHTML );
                }
            }

        }
    })

    $.extend(Wysiwyg.prototype,
    {
        original : null,
        options  : {},

        element  : null,
        editor   : null,
		
		objects  : {},
		counter	 : 0,

        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></iframe>').css({
                    height : ( newY - 6 ).toString() + 'px',
                    width     : '100%'//( newX - 8 ).toString() + 'px'
                }).attr('id', $(element).attr('id') + 'IFrame');
				
				// set height to textarea
				$(this.original).css({height : ( newY - 6 ).toString() + 'px'});

                if ( $.browser.msie )
                {
                    this.editor
                        .css('height', ( newY ).toString() + 'px');

                    /**
                    var editor = $('<span></span>').css({
                        width     : ( newX - 6 ).toString() + 'px',
                        height    : ( newY - 8 ).toString() + 'px'
                    }).attr('id', $(element).attr('id') + 'IFrame');

                    editor.outerHTML = this.editor.outerHTML;
                     */
                }
            }

            var panel = this.panel = $('<ul></ul>').addClass('panel').css({ top: 0 });
			
			this.panel
				.mouseover(function() {
					self.clearPanelTimeout(); 
				})
				.mouseout(function() {
					self.setPanelTimeout();
				});
			
            this.appendControls();
            this.element = $('<div></div>').css({
                width : ( newX > 0 && false ) ? ( newX ).toString() + 'px' : 'auto'
            }).addClass('wysiwyg')
              .append( panel )
              .append( $('<div><!-- --></div>').css({ clear : 'both' }) );
            
			$("<div></div>").addClass('iframe').append( editor ).appendTo( this.element );			

            $(element)
            // .css('display', 'none')
            // .hide()
            .before(this.element);
			
			// move textarea into wysiwyg div
			$("<div></div>").addClass('textarea').append( this.original ).appendTo( this.element ).hide();

            this.viewHTML = false;

            this.initialHeight = newY - 6;

            /**
             * @link http://code.google.com/p/jwysiwyg/issues/detail?id=52
             */
            this.initialContent = $(element).val();
			
            this.initFrame();

			/*
            if ( this.initialContent.length == 0 ) {
                this.setContent('<br />');
			}
			*/
			this.setContent( this.initialContent.length == 0 ? '<br />' : this.initialContent );

            if ( this.options.autoSave )
                $(element).parents('form:first').submit(function() { if (!self.viewHTML) self.saveContent(); });

            $(element).parents('form:first').bind('reset', function() {
                self.setContent( self.initialContent );
                self.saveContent();
            });
        },

        initFrame : function()
        {
            var self = this;
            var style = '';

            /**
             * @link http://code.google.com/p/jwysiwyg/issues/detail?id=14
             */
            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.editorWin = $(this.editor)[0].contentWindow || $(this.editor)[0].iframe.window;
            this.editorDoc_designMode = false;

            try {
                this.editorDoc.designMode = 'on';
                this.editorDoc_designMode = true;
            } catch ( e ) {
                // Will fail on Gecko if the editor is placed in an hidden container element
                // The design mode will be set ones the editor is focused

                $(this.editorDoc).focus(function()
                {
                    self.designMode();
                });
            }

            this.editorDoc.open();
            this.editorDoc.write(
                this.options.html
                    .replace(/INITIAL_CONTENT/, '' /*this.initialContent*/) //need to use setContent function
                    .replace(/STYLE_SHEET/, style)
            );
            this.editorDoc.close();
            this.editorDoc.contentEditable = 'true';

            if ( $.browser.msie )
            {
                /**
                 * Remove the horrible border it has on IE.
                 */
                setTimeout(function() { $(self.editorDoc.body).css('border', 'none'); }, 0);
            }

            $(this.editorDoc)
				.click(function( event ) {
					if ($.browser.msie && $.browser.version > 6) {
						self.checkTargets( event.target ? event.target : event.srcElement);
					}
					self.updateHeight();
				})
				.mouseup( function( e ) {
					self.clearPanelTimeout();
					if (e.clientY > 200) {
						self.panel.addClass('active');
						self.panel.animate( { 'top' : e.clientY - 30/*, 'left': round(($(self.editorDoc.body).width() - self.panel.width()) / 2)*/ }, 'fast', function() {
							self.setPanelTimeout();
						});
						
					} else if (self.panel.position().top) {
						self.panel.animate( { 'top' : 0, 'left' : 0 }, 'fast', function() {
							self.panel.removeClass('active');
						});
					}
				});

            /**
             * @link http://code.google.com/p/jwysiwyg/issues/detail?id=20
             */
            $(this.original)	
				.focus(function() {
					$(self.editorDoc.body).focus();
				});

            if ( this.options.autoSave )
            {
                /**
                 * @link http://code.google.com/p/jwysiwyg/issues/detail?id=11
                 */
                $(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 )
                    {
                        /**
                         * $(self.editorDoc)
                         * .find('head')
                         * .append(
                         *     $('<link rel="stylesheet" type="text/css" media="screen" />')
                         *     .attr('href', self.options.css)
                         * );
                         */
                    }
                    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;
					}
				})
				.keyup(function() {
					self.updateHeight();
				});
        },
		
		clearPanelTimeout : function() {
			clearTimeout( this.panel.positionTimeout );
			this.panel.positionTimeout = false;
		},
		
		setPanelTimeout : function() {
			var top = parseInt(this.panel.css('top').replace('px',''));
			if (!top) return false;
			var self = this;
			this.clearPanelTimeout();
			this.panel.positionTimeout = setTimeout(function() { self.panelFade() }, 10000);			
		},
		
		panelFade : function() {
			var top = this.panel.css('top').replace('px','');
			if (!top) {
				clearTimeout(this.panel.positionTimeout);
				this.panel.positionTimeout = false;
				return;
			}
			var self = this;
			this.panel.fadeOut('slow', function() {
				self.panel.hide();
				self.panel.css({'top': 0, 'left' : 0});
				self.panel.removeClass('active');
				self.panel.show();
			});
		},

        designMode : function()
        {
            if ( !( this.editorDoc_designMode ) )
            {
                try {
                    this.editorDoc.designMode = 'on';
                    this.editorDoc_designMode = true;
                } catch ( e ) {}
            }
        },
		
        getSelection : function()
        {
            return ( this.editorWin.getSelection ) ? this.editorWin.getSelection() : this.editorDoc.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 )
        {
			var self = this;
			var content = $('<div></div>').html( newContent );
			content.find('object').each(function( i ) {
				var nm = self.counter++;
				self.objects[ 'o' + nm ] = this.outerHTML || $('<div></div>').html( this.cloneNode( true ) ).html();
				$('<img class="object" id="im-'+nm+'" src="'+settings.url+'/images/i/blank.gif" />')
					.attr({ 'width' : this.width, 'height' : this.height })
					.insertBefore( this );
				$(this).remove();
			});
            $( $(this.editor).document() ).find('body').html( content.html() );
			//this.updateHeight();
			
        },

        saveContent : function()
        {
            if ( this.original )
            {
				//$( $(this.editor).document() ).find('body object img ').remove();
				var self = this;
				var iHTML = $('<div></div>').html( this.getContent() );
				iHTML.find('img.object').each(function() {
					if ( this.id ) {
						var r = this.id.match(/^im-(.*)$/);
						var nm = parseInt(r[1]);
						$( self.objects[ 'o' + nm ] ).insertBefore( this );
					}
					$( this ).remove();
				});
                var content = iHTML.html();

                if ( this.options.rmUnwantedBr )
                    content = ( content.substr(-4).toLowerCase() == '<br>' ) ? content.substr(0, content.length - 4) : content;
				content = content.replace(/<br>/ig, '<br />');
				self.getRange();
                $(this.original).val(content);
            }
        },
		
		updateHeight : function() {

			//OLD var newHeight = $.browser.msie ? this.editorDoc.body.scrollHeight : $('body', this.editorDoc).height();
			var newHeight = $.browser.msie ? this.editorDoc.body.scrollHeight : this.editorDoc.documentElement.offsetHeight;
			newHeight += 20;
			if (newHeight >= this.initialHeight) {
				this.editor.css({
					height : newHeight + 'px'
				});
				$(this.original).css({
					height : newHeight + 'px'
				});
			}
		},
		
		saveFocus : function() {

			this.editorWin.focus();
			this.range = null;
			this.range = this.getRange();
			
		},
		
		reFocus : function() {
			
			this.editorWin.focus();
			if ($.browser.msie && this.range) {
				var self = this;
				setTimeout(function() {
					self.range.collapse(false);
					self.range.select();
				}, 0);
			}
			
		},

        appendMenu : function( cmd, args, className, fn, inHTML )
        {
            var self = this;
            var args = args || [];

            $('<li></li>').append(
                $('<a><span></span></a>').addClass(className || cmd)
            ).appendTo( this.panel )
			.find('a:first')
			.mousedown(function( e ) {
				
				if (self.viewHTML && !inHTML) return false;
				self.saveFocus();
                if ( fn ) fn.apply( self ); 
				else {
					self.editorDoc.execCommand(cmd, false, args);
				}
                if ( self.options.autoSave ) self.saveContent();
				self.reFocus();
				
            }).click(function() {
				//alert('a');
			});
        },

        appendMenuSeparator : function()
        {
            $('<li class="separator"></li>').appendTo( this.panel );
        },
        appendMenuBreak : function()
        {
            $('<li class="break"></li>').appendTo( this.panel );
        },
        appendMenuClear : function()
        {
            $('<li class="clear"></li>').appendTo( this.panel );
        },

        appendControls : function()
        {
            for ( var name in this.options.controls )
            {
                var control = this.options.controls[name];

				if ( control.newline ) {
                    if ( control.visible !== false || ( this.options.extended && control.extended ) )
                        this.appendMenuBreak();
				} 
				else if ( control.separator )
                {
                    if ( control.visible !== false || ( this.options.extended && control.extended ) )
                        this.appendMenuSeparator();
                }
                else if ( control.visible || ( this.options.extended && control.extended ) )
                {
                    this.appendMenu(
                        control.command || name, 
						control.arguments || [],
                        control.className || control.command || name || 'empty', 
						control.exec,
						control.inHTML
                    );
                }
            }
			this.appendMenuClear();
        },

        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).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).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 )
                {
                    /** IE add full path, so I check by the last chars. */
                    value = value.substr(value.length - attributeValue.length);
                }

                if ( value == attributeValue )
                    return elements[i];
            }

            return false;
        },
		
		uploadImageSuccess : function( html ) {
			$(this.original).wysiwyg('insertImage', html, { alt: '' });
			ajaxLoader( false );
		}
		
    });
})(jQuery);