/**
 * editoR for BBCode
 * 
 * @package Ideo.Edito
 * @author Marcin Gil
 * @copyright Copyright (c) 2007
 * @version 0.1
 **/
 
 
Ext.editoR = function(elToolbar, elArea, config)
{
	this.elToolbar = Ext.get(elToolbar);
	this.elArea = Ext.get(elArea);

	this.html = this.elArea.dom;
	this.html.focus();
	
	this.actions = [];
	this.i = 0;

	if(config) Ext.apply(this, config);
	this.init();
	this.storeCaret();
}

Ext.editoR.prototype =
{
    init: function()
	{
		Ext.EventManager.addListener(this.html, 'click', this.storeCaret.createDelegate(this));
		Ext.EventManager.addListener(this.html, 'select', this.storeCaret.createDelegate(this));
		Ext.EventManager.addListener(this.html, 'keyup', this.storeCaret.createDelegate(this));
	
        this.toolWidth = this.elArea.getWidth() || 350;

        this.elArea.setWidth(this.toolWidth);
        this.createToolBar();
    },
    
	createToolBar: function()
	{
	    var fontFaceMenu = new Ext.menu.Menu(
        {
			items:
            [
                {text: '<span style="font-family: arial;">Arial</span>', handler: this.wrapSelection.createDelegate(this, ['[font=arial]', '[/font]'])},
                {text: '<span style="font-family: courier new;">Courier New</span>', handler: this.wrapSelection.createDelegate(this, ['[font=courier new]', '[/font]'])},
                {text: '<span style="font-family: georgia;">Georgia</span>', handler: this.wrapSelection.createDelegate(this, ['[font=georgia]', '[/font]'])},
                {text: '<span style="font-family: times new roman;">Times New Roman</span>', handler: this.wrapSelection.createDelegate(this, ['[font=times new roman]', '[/font]'])}
               
            ]
        });
	    var fontSizeMenu = new Ext.menu.Menu(
        {
		    items:[
                {text: '<span style="font-size: 9px;">'+ editoRLang.fontSmall +'</span>', handler: this.wrapSelection.createDelegate(this, ['[size=9]', '[/size]'])},
                {text: '<span style="font-size: 12px;">'+ editoRLang.fontNormal +'</span>', handler: this.wrapSelection.createDelegate(this, ['[size=12]', '[/size]'])},
                {text: '<span style="font-size: 15px;">'+ editoRLang.fontLarge +'</span>', handler: this.wrapSelection.createDelegate(this, ['[size=15]', '[/size]'])},
                {text: '<span style="font-size: 18px;">'+ editoRLang.fontHuge +'</span>', handler: this.wrapSelection.createDelegate(this, ['[size=18]', '[/size]'])}
        	]
        }); 
	   	var emoMenu = new Ext.menu.Menu(
        {
			items:
            [
                {text: '<img src="images/forum/editor/emoticon_smile.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :smile: '])},
                {text: '<img src="images/forum/editor/emoticon_grin.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :grin: '])},
                {text: '<img src="images/forum/editor/emoticon_tongue.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :tongue: '])},
                {text: '<img src="images/forum/editor/emoticon_waii.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :waii: '])},
            	{text: '<img src="images/forum/editor/emoticon_evilgrin.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :evilgrin: '])},
                {text: '<img src="images/forum/editor/emoticon_happy.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :happy: '])},
                {text: '<img src="images/forum/editor/emoticon_surprised.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :suprised: '])},
                {text: '<img src="images/forum/editor/emoticon_unhappy.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :unhappy: '])},   
                {text: '<img src="images/forum/editor/emoticon_wink.png" alt="" />', handler: this.wrapSelection.createDelegate(this, ['', ' :wink: '])} 
			]
        });
        
	    var tb = new Ext.Toolbar(this.elToolbar);
	    tb.add(
			{
	            cls: 'x-btn-icon btnUndo',
	            tooltip: editoRLang.undo,
			    handler: this.undo.createDelegate(this)
	       
	        },
	        {
	            cls: 'x-btn-icon btnRedo',
	            tooltip: editoRLang.redo,				
	            handler: this.redo.createDelegate(this)
	        },
			'-',
	        {
	            cls: 'x-btn-icon btnBold',
	            tooltip: editoRLang.bold,
	            handler: this.wrapSelection.createDelegate(this, ['[b]', '[/b]'])
	       
	        },
	        {
	            cls: 'x-btn-icon btnItalic',
	            tooltip: editoRLang.italic,
	            handler: this.wrapSelection.createDelegate(this, ['[i]', '[/i]'])
	       
	        },
	        {
	            cls: 'x-btn-icon btnUnderline',
	            tooltip: editoRLang.underline,
	            handler: this.wrapSelection.createDelegate(this, ['[u]', '[/u]'])
	       
	        },
	        '-',
	        {
	            cls: 'x-btn-icon btnFont',
	            tooltip: editoRLang.fontFace,
			    menu: fontFaceMenu
	       
	        },
	        {
	            cls: 'x-btn-icon btnFontSize',
	            tooltip: editoRLang.fontSize,				
	            menu: fontSizeMenu
	        },
	        {
	            cls: 'x-btn-icon btnForeColor',
	            tooltip: editoRLang.colour,
			    menu: {items:[new Ext.menu.ColorItem({id: 'forecolor', selectHandler: this.colorSelected, scope:this})]}
	        },
	        '-',
	        {
	            cls: 'x-btn-icon btnLink',
	            tooltip: editoRLang.link,
	            handler: this.showLinkPrompt.createDelegate(this)
	        },
	        {
	            cls: 'x-btn-icon btnImg',
	            tooltip: editoRLang.image,
	            handler: this.showImagePrompt.createDelegate(this)
	        },
	        {
	            cls: 'x-btn-icon btnEmo',
	            tooltip: editoRLang.emoticons,				
	            menu: emoMenu
	        }
	     );
	},
    
    showImagePrompt: function()
	{
		var editoR = this;
        Ext.MessageBox.prompt(editoRLang.image, editoRLang.enterImageURL, function(btn, url)
		{
		    if(btn == 'ok' && url != '')
			{
	            editoR.wrapSelection('', '[img]'+ url +'[/img]');
	        }
		});
    },
    
    showLinkPrompt: function()
	{
		var editoR = this;
        Ext.MessageBox.prompt(editoRLang.link, editoRLang.enterURL, function(btn, url)
		{
		    if(btn == 'ok' && url != '')
			{
				if(editoR.isSelectedText())
				{
					editoR.wrapSelection('[url='+url+']', '[/url]');
				}
				else
				{
					Ext.MessageBox.prompt(editoRLang.link, editoRLang.enterURLDesc, function(btn, urlDesc)
					{
					    if(btn == 'ok' && urlDesc != '')
						{
				            editoR.wrapSelection('', '[url='+ url +']'+ urlDesc +'[/url]');
				        }
				        else
				        {
	
				        	editoR.wrapSelection('', '[url]'+ url +'[/url]');
				        }
					});
				}
	        }
		});
    },

    colorSelected: function(cp, color)
	{
		this.wrapSelection('[color=#'+ color +']', '[/color]');
    },
    
	undo: function()
	{
	    if(this.actions[this.i-1] != null) {
	        this.html.value = this.actions[this.i-1];
	        this.i--;
	    }
	},

	redo: function()
	{
	    if(this.actions[this.i+1] != null)
		 {
	    	this.i++;
	    	this.html.value = this.actions[this.i];
	    }
	},
	
	storeCaret: function()
	{
	    if(this.html.createTextRange)
	    {
	        this.html.caretPos = document.selection.createRange().duplicate();
	    }
	},
	
	mozWrap: function(lft, rgt)
	{
		var selLength = this.html.textLength;
		var selStart = this.html.selectionStart;
		var selEnd = this.html.selectionEnd;
		var selScroll = this.html.scrollTop;
		if (selEnd == 1 || selEnd == 2) selEnd=selLength;
		var s1 = (this.html.value).substring(0, selStart);
		var s2 = (this.html.value).substring(selStart, selEnd)
		var s3 = (this.html.value).substring(selEnd, selLength);
		var str = lft + s2 + rgt;
		this.html.value = s1 + lft + s2 + rgt + s3;
		this.html.selectionStart = s1 + (str.length);
	    this.html.selectionEnd = s1 + (str.length);
	    this.html.scrollTop = selScroll;
	},

	isSelectedText: function()
	{
		if(Ext.isIE)
		{
			return this.html.createTextRange && this.html.caretPos.text != '';
		}
		else
		{
			return this.html.selectionStart < this.html.selectionEnd;
		}
	},

	IEWrapCaret: function(lft, rgt)
	{
	    if(this.html.createTextRange && this.html.caretPos)
		{
	         var caretPos = this.html.caretPos;
	         var txt = lft + caretPos.text + rgt;
	         caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? txt + ' ' : txt;
		}
		else
		{
	        this.html.value = this.html.value + txt;
	    }
	},
	
	wrapSelection: function(lft, rgt)
	{
	    this.actions[this.i] = this.html.value;
	    this.i++;
	
		if(Ext.isIE)
		{
			this.IEWrapCaret(lft, rgt);
		}
		else if(document.getElementById)
		{
			this.mozWrap(lft, rgt);
		}
	
		this.actions[this.i] = this.html.value;
		
		for(j = this.actions.length - 1; j > this.i; j--)
		{
	        if(this.actions[j] != null)
	        {
	            this.actions.pop();
	        }
	    }
	}
}

