 var textEditor = function (options) 
{
	var domain = window.location;
	var protocol = domain.protocol;
	var host = isBrowser.IE || isBrowser.SF ? domain.host: domain.hostname;
	var pathname = domain.pathname;
	var URL = protocol +'//'+ host + pathname ;
	if(!/js\/editor\//.test(URL))URL = DOMAIN + 'js/editor/';
	this.URL = URL;
	this.options =
	{	
		imagesPath		 : options.imgPath || URL + 'img/',
		includesPath	 : options.incPath || URL +'includes/',
		cssFile			 : options.cssPath || URL + 'css/editor.css',
		fieldName		 : options.fieldName || 'text-edit',
		html			 : options.html || '',
		width			 : options.width || 400,
		height			 : options.height || 200,
		buttons			 : options.buttons || 'null',
		readOnly		 : options.readOnly || false,
		textarea		 : options.textArea_id || false,
		emoticonsPath	 : options.emoticonsPath || URL + 'img/emoticons/',
		emoticons		 : options.emoticons ||  false,
		fontsPanel		 : options.fonts_panel || false,
		on_close		 : options.on_close || false,
		on_getHTML		 : options.on_getHTML || false	
	};
	this.stockBlocks =  new Array();
	if (this.options.buttons)
	{

		if (this.options.buttons == 'null'|| ! /(minimum|full|normal)/.test(this.options.buttons))
		{
			this.options.buttons = false;
			/*[
				['rte-toggle-html','rte-toggle-html.gif','ver codigo html']
			];*/
			this.options.emoticons = false;
			this.options.fontsPanel = false;
			this.options.fontsColor = false;
			this.options.fontsSize = false;
			this.options.putVideo = false;
		}
		if (this.options.buttons == 'minimum')
		{
			this.options.buttons = 
			[
				
				['rte-toggle-html','rte-toggle-html.gif','ver codigo html'],
				['bold','bold.png','negrita'],
				['italic','italic.png','cursiva'],
				['insertorderedlist','insertorderedlist.gif','lista viņetas'],
				['insertunorderedlist','insertunorderedlist.gif','lista numerada'],
				['insertlink','insertlink.png','enlace'],
				['addimage','addimage.png','imagen']
			];
			this.options.emoticons = true;
		}

		var normal = false;
		this.full = false;
		if(this.options.buttons == 'full' )this.full = true;
		if (this.options.buttons == 'full' || this.options.buttons == 'normal')
		{
			normal = this.options.buttons== 'normal' ? true : false;
			this.options.buttons =
			[
				
				['rte-toggle-html','rte-toggle-html.gif','ver codigo html'] ,
				['bold','bold.png','negrita'],
				['italic','italic.png','cursiva'],
				['underline','underline.png','subrayado'],
				['justifyleft','justifyleft.png','izquierda'],
				['justifycenter','justifycenter.png','centro'],
				['justifyright','justifyright.png','derecha'],
				['outdent','outdent.gif','disminuir sangria'],
				['indent','indent.gif','aumentar sangria'],
				['insertorderedlist','insertorderedlist.gif','lista viņetas'],
				['insertunorderedlist','insertunorderedlist.gif','lista numerada'],
				['insertlink','insertlink.png','enlace'],
				['addimage','addimage.png','imagen']// boton para poder ver el source html
			];
			this.options.emoticons = true;
			this.options.fontsPanel = true;
			this.options.fontsColor = true;
			this.options.fontsSize = true;
			this.options.putVideo = true;
		}
		if (normal)
		{
			this.options.fontsPanel = false;
		}
		
		
	}
	var fontStyles = 
	[
		"Arial",
		"Arial Black",
		"Arial Narrow",
		"Book Antiqua",
		"Century Gothic",
		"Comic Sans MS",
		"Courier New",
		"Franklin Gothic Medium",
		"Garamond",
		"Georgia",
		"Impact",
		"Lucida Console",
		"Lucida Sans Unicode",
		"Microsoft Sans Serif",
		"Palatino Linotype",
		"Tahoma",
		"Times New Roman",
		"Trebuchet MS",
		"Verdana"	
	];
	
	this.emoticonsMSN =
	[
		[':)',':smile:'],
		[':D',':shiny:'],
		[':(',':sad:'],
		[':\'(',':cry:'],
		[':P',':tongue:']
	];
	
	this.fontStyles = fontStyles;
	this.options.fieldName = this.options.textarea+'_editor';
	this.isRichText = false;
	this.rng = '';
	var currentRTE;
	var allRTEs = "";
	if (document.getElementById && document.designMode && !isBrowser.SF && !isBrowser.KQ) this.isRichText = true;
	//try{if(this.isRichText)document.writeln('<link rel="stylesheet" type="text/css" href="'+this.options.cssFile+'">');}catch(e){}
	if(document.createStyleSheet) 
	{
		document.createStyleSheet(this.options.cssFile);
	}
	else 
	{
		var styles = "@import url(' "+this.options.cssFile+" ');";
		var newSS=document.createElement('link');
		newSS.rel='stylesheet';
		newSS.href='data:text/css,'+escape(styles);
		document.getElementsByTagName("head")[0].appendChild(newSS);
	}
};

textEditor.prototype.stripSpecificTags = function (str)
{
	str = str.replace(/<(tr|td|table|tbody|thead|div)[^>]*>/gi,'');
	str = str.replace(/<\/(tr|td|table|tbody|thead|div)>/gi,'');
	return str;
}

textEditor.prototype.start = function()
{
	this.write();
	/* fix IE */
	runCommand(this.iframeEl.id,null,null);
};
textEditor.prototype.write = function()
{
	var _this = this;
	this.iframeID = this.options.fieldName +'edit_iframe';
    var div = document.createElement('div');
    div.id =  this.options.fieldName + '_blog_editor';
	this.container = div;
	var height;
	var marginTop;
	var marginLeft;
	var marginRight;
	var marginBottom;
	if(this.options.textarea)
	{ 
		try
		{
			var textarea = $(this.options.textarea);
			width  = getStyle(textarea,'width');
			this.container.style.width = width;//
			height = getStyle(textarea,'height');
			this.container.style.height = height - 25;//
			
			marginTop= getStyle(textarea,'margin-top');
			div.style.marginTop = marginTop; 
			marginLeft = getStyle(textarea,'margin-left');
			div.style.marginLeft = marginLeft;
			marginRight= getStyle(textarea,'margin-right');
			div.style.marginRight = marginRight; 
			marginBottom  = getStyle(textarea,'margin-bottom');
			div.style.marginBottom = marginBottom;
		}catch(e){};
		
	}
	var html = '';
	html += '<div unselectable="on" class="main_wrapper" style="'+ ((this.options.fontsSize||this.options.fontsPanel||this.options.fontsColor)?'background-image:url('+this.options.imagesPath+'rte_tile.gif);':'')+'height:'+height+';maring-top:'+marginTop+';margin-left:'+marginLeft+';margin-right:'+marginRight+';margin-bottom:'+marginBottom+';">\
	             <div class="control_panel">';
	if(this.options.fontsSize)
	html +='<div id="'+this.options.fieldName+'panel_1" style="height: 26px; padding-top: 2px; padding-left: 4px;">\
					 <div style="float:left" unselectable="on">\
				      <div unselectable="on" class="font_size menu_editor menu_clicker" style="width: 105px; cursor: pointer;">\
					   <table unselectable="on" >\
					    <tr>\
						 <td unselectable="on" >\
						  <div unselectable="on" class="menu_clicker" style="width: 80px;" onclick="getFontSizePanel(\'' + this.options.fieldName + '_size_panel\',\''+this.iframeID+'\');">Tama&ntilde;o</div>\
					     </td>\
						 <td>\
						  <div onclick="getFontSizePanel(\'' + this.options.fieldName + '_size_panel\',\''+this.iframeID+'\');" class="drop_down_editor menu_clicker" unselectable="on" />\
						 </td>\
						</tr>\
					   </table>\
					  </div>'+this.getFontSizePanel()+'\
					 </div>';
	if(this.options.fontsPanel)		 
	html +=  '<div style="float:left" unselectable="on">\
			  <div unselectable="on" class="font_size menu_editor menu_clicker" style="width: 105px; cursor: pointer;">\
			   <table unselectable="on" >\
				<tr>\
				 <td unselectable="on" >\
				  <div unselectable="on" class="menu_clicker" style="width: 80px;" onclick="getFontPanel(\'' + this.options.fieldName + '_font_panel\',\''+this.iframeID+'\');">Fuentes</div>\
				 </td>\
				 <td>\
				  <div onclick="getFontPanel(\'' + this.options.fieldName + '_font_panel\',\''+this.iframeID+'\');" class="drop_down_editor menu_clicker" unselectable="on" />\
				 </td>\
				</tr>\
			   </table>\
			  </div>'+this.getFontStylePanel()+'</div>';	  
		 
	if(this.options.fontsColor) 
	html += '<div style="float:left" unselectable="on">\
					   <div class="font_color menu_editor menu_clicker" style="width: 105px; cursor: pointer;" unselectable="on">\
					    <table unselectable="on">\
						 <tr>\
						  <td unselectable="on">\
						   <div class="menu_clicker" style="width: 80px;" unselectable="on" onclick="getForeColorPallete(\''+this.options.fieldName+'_palette_wrapper\',\''+this.iframeID+'\');">Color<div>\
						  </td>\
						  <td>\
						   <div class="drop_down_editor menu_clicker" unselectable="on" onclick="getForeColorPallete(\''+this.options.fieldName+'_palette_wrapper\',\''+this.iframeID+'\');">\
						   </div>\
						  </td>\
						 </tr>\
						</table>\
					   </div>'+this.getPalletePanel()+'\
					  </div>\
			       </div>';
	html += '<div id="'+this.options.fieldName+'panel_2" style="height: 26px; padding-top: 2px; padding-left: 4px;">';
	html += this.createButtons();
	if(this.options.emoticons)html +='<div style="float: left; height: 23px; width: 51px;"><div id="'+this.options.fieldName+'popup_emoticons" unselectable="on" class="rte-normal-menubutton" style="margin-right: 4px; cursor: pointer; border-top-width: 1px;margin-top:1px; padding-top: 0px; padding-bottom: 0px; height: 20px; width: 44px;" title="Emoticones"><table style="margin-top: -3px;" unselectable="on"><tr unselectable="on"><td unselectable="on"><img onclick="getEmoticonPanel(\'' + this.options.fieldName + '_emoticon_panel\',\''+this.iframeID+'\');" unselectable="on" src="'+this.options.emoticonsPath+'happy.gif" /></td><td><img onclick="getEmoticonPanel(\'' + this.options.fieldName + '_emoticon_panel\',\''+this.iframeID+'\');" class="ipd" border="0" alt="" src="'+this.options.imagesPath+'icon_open.gif"/></td></tr></table></div>' + this.getEmoticonsPanel() + '</div>';
	if(this.options.putVideo)html +='<div class="video_wrap">\
				<div id="'+this.options.fieldName+'video_button" unselectable="on" onclick="putVideo(\''+this.iframeID+'\')" class="rte-normal-menubutton" style="padding: 4px; float: left; width: 33px; cursor: pointer; border-bottom-width: 1px; margin-left: 1px; height: 12px;margin-top:1px;" >Video</div>\
			</div>';
	html +='</div><div class="word-area" style="padding-top:0px;"id="'+this.options.fieldName +'_word_area">';
	var heightPlus = 90;
	if (!(this.options.fontsPanel||this.options.fontsPanel||this.options.fontsColor)){heightPlus =heightPlus-29;}
	html +='   <iframe  id="'+ this.options.fieldName +'edit_iframe" name="' + this.options.fieldName  + '" style="width:99%;height:'+(parseInt(height.replace('px',''))-heightPlus)+'px;margin-left:1px;"  class="edit_iframe" ></iframe>';
	html +='  </div>';
	//html +='<div class="word-area2" id="' + this.options.fieldName +'_work_area" style="display:none"><textarea style="width:98%;height:' + this.options.height + 'px;"></textarea><div><input class="rte-menu-button" type="button" value=" Save HTML " onclick="switchToIframe(\''+this.iframeID+'\',\'save\');" /><input class="rte-menu-button" type="button" value=" CANCEL " onclick="switchToIframe(\''+this.iframeID+'\',\'cancel\');" /></div></div>';
	html +='<div class="word-area2" id="' + this.options.fieldName +'_work_area" style="display:none"><textarea style="width:98%;height:'+(parseInt(height.replace('px',''))-90)+'px;"></textarea><div></div></div>';
	html += '</div></div>';
	div.innerHTML+= html;
	if(this.options.textarea)
	{
		try{
			var textarea = $(this.options.textarea);
			textarea.style.display = 'none';
			insertAfter(div, textarea)
		/*	if(textarea.value != '')
			{*/
				if(!this.full) this.options.html = this.stripSpecificTags(textarea.value);
				else this.options.html = textarea.value;
			//}
			var form = findParentNode("form", textarea );
			//console.log(form);
			var submit = function ()
			{
				textarea.value = _this.getHTML();
				if(_this.emoticonsIMG.length>0)
				{
					var x =_this.emoticonsIMG;
					for(var i=0;i<x.length;i++)
					{
					/*	var textToReplace = '<'+(isBrowser.IE?'IMG':'img')+' src="'+x[i]+'">';
						var arra = (x[i].replace(/(.gif|.png)/g,'')).split('/');
						var sus = ' :'+arra[arra.length-1]+': ';
						textarea.value= textarea.value.replace(textToReplace,sus);				*/	
					}
				}
			}
			if(form)
			addEvent(form,'submit',submit);
		}catch(e){}
	}
	
	var iframe = $(this.iframeID);
	this.iframeEl = iframe;
	iframe.editor = this;
	this.enableDesignMode();
	//event setup
	      
	/*---------------------------------------------*/
    this.events = new Array(); //event register
    if(this.options.fontsPanel||this.options.fontsColor||this.options.fontsSize)
	{
		var hideMenus = [!isBrowser.IE?window:window.document,'click',function(e){_this.hideMenus(e);}];
		addEvent(hideMenus[0],hideMenus[1],hideMenus[2]);
		this.events.push(hideMenus);
	
		var hideMenus1 = [!isBrowser.IE?iframe.contentWindow:iframe.contentWindow.window.document,'click',function(){_this.hideMenus();}];
		addEvent(hideMenus1[0],hideMenus1[1],hideMenus1[2]);
		this.events.push(hideMenus);
	}
	if (this.options.emoticons) {
		var checktags = [!isBrowser.IE ? iframe.contentWindow : iframe.contentWindow.window.document,'keypress',function(e){_this.chekTags(e);}];
		addEvent(checktags[0],checktags[1],checktags[2], false);
		this.events.push(hideMenus);
	}
	

	//addEvent(iframe,'')
	/*---------------------------------------------*/

	if(this.options.fontsColor)
	{
		this.palettePanel = $(this.options.fieldName+'_palette');
		this.palettePanel_wrapper =  $(this.options.fieldName+'_palette_wrapper');
		this.setPaletteEvents();
	}

	if (this.options.fontsPanel) {

		this.fontStylePanel = $(this.options.fieldName + '_font_panel');
		this.setFontStyleEvents();
	}
	if(this.options.fontsSize )
	{
		this.fontSizePanel = $(this.options.fieldName + '_size_panel');
		this.setFontSizeEvents();
	}
	
	this.word_area =  $(this.options.fieldName +'_word_area');
	if(this.options.fontsPanel||this.options.fontsColor||this.options.fontsSize)this.panel_1 = $(this.options.fieldName+'panel_1');
	this.panel_2 = $(this.options.fieldName+'panel_2');
	if(this.options.emoticons)this.emoticonsPanel = $(this.options.fieldName + '_emoticon_panel');
	
	//tag cheker vars
	this.tagStarted = false;
	this.tagFinished = false;
	this.cacheTag = '';
	
	if(this.options.emoticons)
	{
		this.emoticonsIMG = new Array();
		this.emoticonsDrop = $(this.options.fieldName+'popup_emoticons');
	}
	this.nodes = new Array();
	
	//this.disableOnHtmlSource = false;
	if(this.options.putVideo)
	{
		this.videoTags =
		{
			'youtube':['<object width="425" height="344"><param name="movie" value="$1"></param><param name="allowFullScreen" value="true"></param><embed wmode="transparent" src="$1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>','http://www.youtube.com/watch?v=','http://www.youtube.com/v/',false],
			'google':['<embed wmode="transparent" id="VideoPlayback" style="width:400px;height:326px" allowFullScreen="true" src="http://video.google.com/googleplayer.swf?docid=$1&fs=true" type="application/x-shockwave-flash"> </embed>','http://video.google.com/videoplay?docid=','',false],
			'myspace':['<object width="425px" height="360px" ><param name="allowFullScreen" value="true"/><param name="movie" value="http://mediaservices.myspace.com/services/media/embed.aspx/m=$1,t=1,mt=video"/><embed wmode="transparent" src="http://mediaservices.myspace.com/services/media/embed.aspx/m=$1,t=1,mt=video" width="425" height="360" allowFullScreen="true" type="application/x-shockwave-flash"></embed></object>','http://vids.myspace.com/index.cfm?fuseaction=vids.individual&videoid=','',false],
			'levelup':['<embed wmode="transparent" id="mymovie" width="410" height="310" flashvars="origSize=true&imagePath=http://imagenes.levelup.com.mx/files/thumbs/file_thumb_$1.jpg&videoPath=http://archivos.levelup.com.mx/files/video/files_video_$1.flv&autoStart=false&volAudio=40&xmlFile=http%3A%2F%2Fwww%2Elevelup%2Ecom%2Emx%2F%3Fseccion%3Darchivos%26accion%3Dvideo%5Fxml&videoTitle=Evolution Trailer&embedURL=http%3A%2F%2Fwww%2Elevelup%2Ecom%2Emx%2F%3Fseccion%3Darchivos%26accion%3Ddetalle%5Farchivos%26id%5Farchivo%3D$1&embedPlayer='+EMBED_PLAYER+'" allowscriptaccess="always" allowFullScreen="true" quality="high" name="mymovie" style="" src="'+EMBED_PLAYER+'" type="application/x-shockwave-flash"/>','http://www.levelup.com.mx/?seccion=archivos&accion=detalle_archivos&id_archivo=','',
			function(str,replaceTXT,currentHTML)
			{
				str= str.replace('http://www.levelup.com.mx/?seccion=archivos&accion=detalle_archivos&id_archivo=','');
				//var strC = '[levelup]http://www.levelup.com.mx/?seccion=archivos&accion=detalle_archivos&id_archivo=' + str +'[/levelup]';
			    var html='<embed id="mymovie" width="410" height="310" flashvars="origSize=true&imagePath=http://imagenes.levelup.com.mx/files/thumbs/file_thumb_'+str+'.jpg&videoPath=http://archivos.levelup.com.mx/files/video/files_video_'+str+'.flv&autoStart=false&volAudio=40&xmlFile=http%3A%2F%2Fwww%2Elevelup%2Ecom%2Emx%2F%3Fseccion%3Darchivos%26accion%3Dvideo%5Fxml&videoTitle=Evolution Trailer&embedURL=http%3A%2F%2Fwww%2Elevelup%2Ecom%2Emx%2F%3Fseccion%3Darchivos%26accion%3Ddetalle%5Farchivos%26id%5Farchivo%3D'+str+'&embedPlayer='+EMBED_PLAYER+'" allowscriptaccess="always" allowFullScreen="true" quality="high" name="mymovie" style="" src="'+EMBED_PLAYER+'" type="application/x-shockwave-flash"/>';
				return html;
			}],
			'metatube':['','','',
			function(str,replaceTXT,currentHTML)
			{
				var url= str;
				var id = str.replace('http://www.metatube.com/play/','').split('/')[0];
				var html='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="480" height="400"><param name="movie" value="http://www.metatube.com/flvplayer2.swf?id='+id+'&video='+url+'&site=http://www.metatube.com/&pic=http://www.metatube.com/uploads/pic_1194991154.jpg" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><embed src="http://www.metatube.com/flvplayer2.swf?id='+id+'&video=http://www.metatube.com/play/5563/Horn-Dog-Spike-and-Mike-Sick-and-Twisted.html&site=http://www.metatube.com/&pic=http://www.metatube.com/uploads/pic_1194991154.jpg" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" ></embed></object>';
			}
			]
		};
		this.videoInsertedTags = new Array();
		this.videoButton = $(this.options.fieldName+'video_button');
	}
	if(!_this.full)
	{
		setInterval
		(
			function () {_this.textEditorBlockTables(_this)},
			1
		);
	}
};
textEditor.prototype.textEditorBlockTables = function (obj)
{
	try
	{
		var html = $(obj.iframeID).contentWindow.document.body.innerHTML;
		if(/(<table|<tr|<td|<tbody)/.test(html.toLowerCase()))runCommand(obj.iframeID,'Undo','');
	}catch(e){}
}

textEditor.prototype.enableDesignMode = function ()
{
	var _this = this;
	var iframe = this.iframeEl;
	var frameHtml = this.getFrameHTML();
	if (document.all) 
	{
		var iframe = frames[this.iframeID].document;
		iframe.open();
		iframe.write(frameHtml);
		iframe.close();
		if (!this.options.readOnly) iframe.designMode = "On";
	}	
	else
	{
		try 
		{
			if (!this.options.readOnly) 
			{
				try{iframe.contentDocument.designMode = "on";}catch(e){}
				try{iframe.contentWindow.document.designMode = "on";}catch(e){}
				try{$( this.iframeID).contentDocument.designMode = "on";}catch(e){if (isBrowser.OP)setTimeout(function (){_this.enableDesignMode();},10);}
			}
			try 
			{
				var iframe = iframe.contentWindow.document;
				iframe.open();
				iframe.write(frameHtml);
				iframe.close();
				//if (isBrowser.GK && !this.options.readOnly) addEvent(iframe,"keypress", kb_handler, true);
				
			} catch (e){}
		} 
		catch (e) 
		{
			if (isBrowser.GK||isBrowser.OP) 
			{
				setTimeout(function (){_this.enableDesignMode();},10);
			} else 
			{
				try{return false;}catch(e){}
			}
		}
	}
};
textEditor.prototype.getFrameHTML = function ()
{
	return "<html id=\"" + this.options.fieldName +'edit_iframe'+"\">\n<head>\n" + ((this.options.cssFile.length > 0) ? "<link media=\"all\" type=\"text/css\" href=\"" + this.options.cssFile + "\" rel=\"stylesheet\">\n" : "<style>\nbody {\nbackground: #FFFFFF;\n	margin: 0px;\n	padding: 0px;\n}\n</style>\n") + "</td></head>\n<body>\n"+ this.options.html + "</body>\n</html>";
};
textEditor.prototype.setHTML = function(html)
{
	//var oFrame = document.all ? frames[this.iframeID] : $(this.iframeID).contentWindow;
	$(this.iframeID).contentWindow.document.body.innerHTML = html;
};
textEditor.prototype.createButtons = function()
{
	var x = this.options.buttons;
	var td ='';
	//alert(this.options.imagesPath);
	for(var i = 0; i < x.length; i++)
	{
		//window.open(this.options.imagesPath+ x[i][1]);
		td +='<div id="' + this.options.fieldName + '_' + x[i][0] + '" title="'+x[i][2]+'" class="editor_button" ><img width="24" height="24" onmousedown="setSelected(this);" onmouseup="unsetSelected(this);" onblur="unsetSelected(this);" onclick="runCommand (\''+ this.iframeID +'\',\'' + x[i][0] + '\',\'\');"  src="'+this.options.imagesPath+ x[i][1]+'" /></div>';
	}
	return td;
};

function runCommand(iframeID,command,option) 
{
	var oFrame;
	var iframe = $(iframeID)
	var _this = iframe.editor;
	if(!_this.disableOnHtmlSource||command == 'rte-toggle-html')
	{
		oFrame = document.all ? frames[iframeID] : $(iframeID).contentWindow;
		if (!/(insertlink|addimage|rte-toggle-html|inserthtml)/.test(command)) {
			try {
				oFrame.focus();
				oFrame.document.execCommand(command, false, option);
				oFrame.focus();
			} 
			catch (e) {
			}
		}
		else {
			switch (command) {
				case 'insertlink':{
					try {
						runCommand(iframeID, "Unlink", null);
						runCommand(iframeID, "CreateLink", prompt("Enter a URL:", "http://"));
					} 
					catch (e) {
					}
				};break;
				case 'addimage':{
					var path = prompt('Enter Image URL:', 'http://');
					if ((path != null) && (path != "")) 
						runCommand(iframeID, 'InsertImage', path);
				};break;
				case 'rte-toggle-html':{
					
					$(iframeID).editor.switchToTextArea();
				};break;
				case 'inserthtml':{
					if(!isBrowser.IE)
					{
						runCommand(iframeID, "insertHTML",option);
					}
					else
					{
						oFrame.focus();
						iframe.contentWindow.document.selection.createRange().pasteHTML(option);
						oFrame.focus(); 
					}
				};break;
			}
		}
	}
}
textEditor.prototype.insertHTML =  function (html)
{
	runCommand(this.iframeID,'inserthtml',html); 
};
textEditor.prototype.getHTML = function ()
{	
	if(this.options.on_getHTML)this.options.on_getHTML();
	var element = $(this.options.fieldName + '_work_area');
	var textarea = element.getElementsByTagName('textarea')[0];
	var display = element.style.display;
	if(display == 'block')
	{
		$(this.iframeID).contentWindow.document.body.innerHTML = textarea.value;
	}
	//this.stripFonts();
	return $(this.iframeID).contentWindow.document.body.innerHTML;
};

textEditor.prototype.stripFonts = function ()
{
	var html = $(this.iframeID).contentWindow.document.body.innerHTML;
	if(!this.options.fontsPanel&& !this.full)
	{
		var i = this.fontStyles.length;
		
		while(i--)
		{
			html = html.replace(this.fontStyles[i].toLowerCase(),''); 
			html = html.replace(this.fontStyles[i],'');
		}
	}
	 $(this.iframeID).contentWindow.document.body.innerHTML = html;
};

textEditor.prototype.getParsedHTML = function()
{

	this.stripFonts();
	var tags = this.videoInsertedTags;
	var currentHTML =  this.iframeEl.contentWindow.document.body.innerHTML;
	try
	{
		for(var i = 0; i < tags.length; i++)
		{
		
			if(!this.videoTags[tags[i][0]][3])
			{
				var strReplace = ('[' + tags[i][0] + ']' + tags[i][1] + '[/' + tags[i][0] + ']');
				tags[i][1] = tags[i][1].replace(this.videoTags[tags[i][0]][1], '');
				this.videoTags[tags[i][0]][0] = this.videoTags[tags[i][0]][0];
				this.videoTags[tags[i][0]][0] = this.videoTags[tags[i][0]][0].replace(/\$1/g, this.videoTags[tags[i][0]][2] + tags[i][1]);
				currentHTML = currentHTML.replace(/amp;/g, '');
				currentHTML = (currentHTML.replace(strReplace, this.videoTags[tags[i][0]][0]));
			}
			else
			{
				var strReplace = '[' + tags[i][0] + ']' + tags[i][1] + '[/' + tags[i][0] + ']';
				currentHTML = currentHTML.replace(/amp;/g,'').replace(strReplace,this.videoTags[tags[i][0]][3](tags[i][1],strReplace,currentHTML.replace(/amp;/g,'')))
			}
		}
	}catch(e){}
   var string =  currentHTML;
   var rx = new RegExp('\\[\s*?img.+?\\]','gi'); 
   var rx_end = new RegExp('\\[\\/\s*?img\s*\\]','gi');
   var matche1 = string.match(rx);
   if(matche1 != null)
   {
	   var matche2 = string.match(rx_end);
	   var length = matche1.length;
	   var positions_r1 = new Array();
	   var last_search = 0;
		for(var i = 0; i < length; i++)
		{
		   var regx = matche1[i];
		   var start = string.indexOf(regx,last_search);
		   var regx_end = matche2[i];
		   var end = (string.indexOf(regx_end,last_search))+regx_end.length;
		   last_search = end;
		   var string_tag = string.substring(start,end);   
		   var srcThumb = string_tag.match(/srcThumb\s*=\s*".+?"/gi);
		   srcThumb = new String(srcThumb).replace('srcThumb','src');
		   var srcLink = string_tag.match(/srcLink\s*=\s*".+?"/gi);
		   srcLink = new String(srcLink).replace('srcLink','href');
		   
		   var size = string_tag.match(/size\s*=\s*".+?"/gi);
		   if(size)
		   {
		   		if(/medium/.test(size))
		   			size = 'class="medium_screenshot"';
		   		else size = 'class="small_screenshot"'; 
		   }
		   else size = 'class="small_screenshot"';
		   
		   	
		   
		   var text = string_tag.match(/\](.+?)\[/);
		   text = text?(new String(text[0])).replace(']','').replace('[',''):'';
		   var html = '<div '+size+'>';
		   html += '<a ' + srcLink + '>';
		   html += '<img ' + srcThumb + ' alt="' + text + '" />';
		   html += '<br />';
		   html += text;
		   html += '</a>';
		   html += '</div>';
		   string = string.replace(string_tag,html);
		}
		currentHTML = string;
	} 
	return currentHTML;
};

textEditor.prototype.switchToTextArea= function ()
{
	if(!this.disableOnHtmlSource)
	{
		var div = $(this.options.fieldName + '_work_area');
		var textarea = div.getElementsByTagName('textarea')[0];
		textarea.value = this.getHTML();
		textarea.focus();
		this.disableOnHtmlSource = true;		
		show(div);
		hide(this.word_area);
		this.disabledPanels(true);
	}
	else
	{
		show(this.word_area);
		var div = $(this.options.fieldName +'_work_area');
		var textarea = div.getElementsByTagName('textarea')[0];
		hide(div);
		this.iframeEl.contentWindow.document.body.innerHTML = textarea.value;
		this.disableOnHtmlSource = false;
		this.disabledPanels(false);
	}
};
textEditor.prototype.disabledPanels = function (disabled)
{
	try
	{
		var img = this.panel_2.getElementsByTagName('img');
		for(var i = 0; i < img.length; i++)
		{
			if (img[i].className != 'rte-toggle-html') 
			{
				if(disabled)
				{
					img[i].parentNode.style.opacity = '0.1';
					img[i].parentNode.style.filter = 'alpha(opacity=10)';
				}
				else
				{
					img[i].parentNode.style.opacity = '1';
					img[i].parentNode.style.filter = '1';
				}
			}
		}
		if(disabled)
		{
			this.panel_1.style.opacity = '0.1';
			this.panel_1.style.filter = 'alpha(opacity=10)';
			this.videoButton.style.opacity = '0.1';
			this.videoButton.style.filter  = 'alpha(opacity=10)';
			this.emoticonsDrop.style.opacity = '0.1';
			this.emoticonsDrop.style.filter = 'alpha(opacity=10)';
		}else
		{
			this.panel_1.style.opacity = '1';
			this.panel_1.style.filter = '1';
			this.videoButton.style.opacity = '1';
			this.videoButton.style.filter  = '1';
			this.emoticonsDrop.style.opacity = '1';
			this.emoticonsDrop.style.filter = '1';
		}
	}
	catch(e)
	{}
};

textEditor.prototype.getPalletePanel = function ()
{
	var primary_colors =
	[
		'#000000' ,'#A0522D' ,'#556B2F' ,'#006400' ,'#483D8B' ,'#000080' ,'#4B0082' ,'#2F4F4F' ,
		'#8B0000' ,'#FF8C00' ,'#808000' ,'#008000' ,'#008080' ,'#0000FF' ,'#708090' ,'#696969' ,
		'#FF0000' ,'#F4A460' ,'#9ACD32' ,'#2E8B57' ,'#48D1CC' ,'#4169E1' ,'#800080' ,'#808080' ,
		'#FF00FF' ,'#FFA500' ,'#FFFF00' ,'#00FF00' ,'#00FFFF' ,'#00BFFF' ,'#9932CC' ,'#C0C0C0' ,
		'#FFC0CB' ,'#F5DEB3' ,'#FFFACD' ,'#98FB98' ,'#AFEEEE' ,'#ADD8E6' ,'#DDA0DD' ,'#FFFFFF'
	];
	
	var html = '<div unselectable="on"  id="'+this.options.fieldName+'_palette_wrapper'+'"class="forecolor_editor" style="display:none">';
	html += '<table unselectable="on" id="'+this.options.fieldName+'_palette'+'"cellspacing="0" cellpadding="0" border="0"><tbody>';
	var count = 0;
	for(var i = 0; i < 5 ; i ++)
	{
		html += '<tr>';
		for(var j = 0; j < 8; j ++)
		{
			html += '<td unselectable="on" class="cell_forecolor_editor">'+
						'<div unselectable="on" style="background-color:' + primary_colors[count] + ';height: 15px; width: 10px; cursor:pointer;" ><img width="7" height="15" src="'+this.options.imagesPath+'transparentpixel.gif" unselectable="on" />&nbsp;</div>'+
					'</td>';
			count ++;
		}
		html += '</tr>';
	}
	html += '</tbody></table>';
	html += '</div>';
	return html;
};

textEditor.prototype.getFontStylePanel = function ()
{

	var html = '<div unselectable="on"  class="fonts_editor" style="display:none" id="'+this.options.fieldName+'_font_panel">';
	for(var i = 0; i < this.fontStyles.length; i++)
	{
		html += '<div unselectable="on"  class="normal_menu_editor">';
		html += '<font unselectable="on"  face="' + this.fontStyles[i] + '">' + this.fontStyles[i] + '</font>';
		html += '</div>';
	}
	html += '</div>';
	return html;
};

textEditor.prototype.getFontSizePanel = function ()
{ 
	var html ='<div unselectable="on" class="size_editor" style="display: none;" id="'+this.options.fieldName + '_size_panel">';
	for(var j = 0; j < 7; j++)
	{
		html += '<div unselectable="on" class="normal_size_menu_editor" ><font unselectable="on" size="'+(j+1)+'" >'+(j+1)+'</font></div>';
	}
	html += '</div>';
	return html;
}

textEditor.prototype.getEmoticonsPanel = function ()
{
	var emoticons =
	{
		':mellow:':'mellow.gif',
		':ohmy:':'ohmy.gif',
		':wink:':'wink.gif',
		':huh:':'huh.gif',
		':laugh:':'laugh.gif',
		':smile:':'smile.gif',
		':sleep:':'sleep.gif',
		':dry:':'dry.gif',
		':hail:':'hail.gif',
		':wub:':'wub.gif',
		':mad:':'mad.gif',
		':sad:':'sad.gif',
		':blink:':'blink.gif',
		':nonono:':'nonono.gif',
		':dunce:':'dunce.gif',
		':dribble:':'dribble.gif',
		':zipped:':'zipped.gif',
		':cry:':'cry.gif',
		':ill:':'ill.gif',
		':licklips:':'licklips.gif',
		':kicking:':'kicking.gif',
		':shiny:':'shiny.gif',
		':tongue:':'tongue.gif'
	}
	this.emoticons = emoticons;
	var html = '<div id="'+this.options.fieldName + '_emoticon_panel" unselectable="on" id="ed-0_popup_emoticons_menu" class="rte-popupmenu" style="padding: 3px; cursor: default; width: auto; height: 200px; overflow-x: hidden; overflow-y: auto; position: absolute; z-index: 100;display:none">';
	html += '<table unselectable="on">';
	var closeTr = false;
	var i = 0;
	for(x in emoticons)
	{
		if ((i)%3 == 0)
		{
			if(!closeTr)
			{
				html += '  <tr unselectable="on">';
				closeTr = true;
			}
			else
			{
				html += '  </tr>';
				closeTr = false;
			}
		}
		html += '   <td unselectable="on"><div unselectable="on"><img unselectable="on" title="'+x+'"onclick="setEmoticon(\''+this.iframeID+'\',this)" src="'+this.options.emoticonsPath + emoticons[x] +'" style="cursor:pointer;"></div></td>';
		i++;
	}
	html += '</table>';
	html += '</div>';
	return html;
};

textEditor.prototype.setPaletteEvents = function ()
{
	var x = isBrowser.IE ?this.palettePanel.getElementsByTagName('img'): this.palettePanel.getElementsByTagName('div');
	var _this = this;
	var click = function (e)
	{
		var el = isBrowser.IE ? getTarget(e).parentNode : getTarget(e);
		if(el.tagName.toLowerCase() == 'img') el = el.parentNode;
		var color = el.style.backgroundColor.replace(/#/g,'');
		if(!isBrowser.IE && !isBrowser.OP)
		{
			var x = color.replace(/[rgb()]/g,'').split(',');
			color = RGBtoHex(x[0],x[1],x[2]);
		}
		color = isBrowser.IE || isBrowser.OP ? color : color.replace(/[rgb()]/g,'').split(',');
		color = isBrowser.SF ? '#'+color : color;
		_this.setForeColor(color);
	}
	for (var i=0; i < x.length; i++) 
	{
		x[i].onclick = click;
	}
};
textEditor.prototype.setForeColor = function(color)
{
	hide($(this.options.fieldName+'_palette_wrapper'));
	setRange(this.iframeID);
	if (document.all) {

		var x = frames[this.iframeID];
		x.focus();
		var sel = frames[this.iframeID].document.selection; 
		if (sel != null) {
			var newRng = sel.createRange();
			newRng = this.rng;
			newRng.select();
		}
	}
	runCommand(this.iframeID, 'ForeColor', color);
};

textEditor.prototype.setFontStyleEvents = function ()
{
	var xEl = this.fontStylePanel.getElementsByTagName('div');
	var _this = this;
	var click = function (e)
	{
		var el = getTarget(e);
		var x;
		if(el.tagName.toLowerCase() =='div')
		{
			x = el.getElementsByTagName('font')[0];
		}
		else
		{
			x = el;
		}
		var selectedFont = x.face;
		_this.setFontStyle(selectedFont);
	}
	for(var i = 0; i< xEl.length; i++) 
	{
		xEl[i].onclick = click;
	}
}

textEditor.prototype.setFontStyle = function (font)
{
	var selected = font;
	runCommand(this.iframeID, 'fontname', font);
	hide(this.fontStylePanel);
}

textEditor.prototype.setFontSize = function (size)
{
	runCommand(this.iframeID, 'fontsize', size);
	hide(this.fontSizePanel);
};
textEditor.prototype.setFontSizeEvents = function()
{
	var x = this.fontSizePanel.getElementsByTagName('div');
	var _this = this;
	var click = function (e)
	{
		var el = getTarget(e);
		var size;
		if(el.tagName.toLowerCase() == 'font')
		{
			size = el.size;
		}
		else
		{
			size = el.getElementsByTagName('font')[0].size;
		}
		_this.setFontSize(size);
	};
	for(var i = 0; i < x.length ; i++)
	{
		x[i].onclick = click;
	}
};

textEditor.prototype.hideMenus = function (e)
{
	var el = getTarget(e);
	var class_name = el.className;
	if(!/menu_clicker/.test(class_name))
	{
		hideAllDrops(this);
	}
}
textEditor.prototype._destruct = function(total)
{
	//try
	//{
		var i = this.events.length;
		while (i--) {if(typeof this.events[i] != 'undefined')removeEvent(this.events[i][0],this.events[i][1],this.events[i][2]);};
		this.container.parentNode.removeChild(this.container);
		if(total)for(x in this)delete this[x];
		this.disableOnHtmlSource = false;
		if(this.options.on_close)this.options.on_close();
	//}catch(e){};
};
textEditor.prototype.clear = function ()
{
	$(this.iframeID).contentWindow.document.body.innerHTML="";
	$(this.options.textarea).value="";
};
textEditor.prototype.chekTags = function(e)
{   var event = getE(e);
	var key = getPressedKey(e) ;
	var charKey = String.fromCharCode(key);
	var selection;
	var _this = this;
	var x;
	if (this.iframeEl.contentWindow.getSelection)
	{
		x = this.iframeEl.contentWindow.document.createRange();
		selection = this.iframeEl.contentWindow.getSelection();
	}
	else 
	{
		x = this.iframeEl.contentWindow.document.selection.createRange();
		selection = this.iframeEl.contentWindow.document.selection;
	}
	var parentNode = selection.anchorNode;
	var offset = isBrowser.IE ? x.offsetLeft : selection.anchorOffset;
	var range = x;
	
	if(key == '58')
	{
		if(!this.tagStarted)
		{
			this.tagStarted = true;
		}
		else
		{
			this.tagFinished = true;
			this.cacheTag += charKey;
			if(isDefined(this.emoticons[this.cacheTag]))
			{
				var img =  this.emoticons[this.cacheTag];
				var str =this.cacheTag.substring(0,this.cacheTag.length-1);
				stopEvent(event);
				if(!isBrowser.IE)
				{
					range.setStart(parentNode,offset-str.length);
					range.setEnd(parentNode,offset);	
					selection.addRange(range);
					try{selection.deleteFromDocument();}catch(e){};
					this.insertHTML('<img src="'+_this.options.emoticonsPath+img+'" title="'+this.cacheTag+'">');
				}
				else
				{
					x.moveStart('character',str.length*(-1));	
					x.expand('character');
					x.select();
					try{x.execCommand('Delete',false,'');}catch(e){}
					runCommand(_this.iframeID, 'InsertImage', _this.options.emoticonsPath+img);
				}				
			}
			this.cacheTag ='';
			this.tagFinished = false;
			this.tagStarted = false;
		}
	}
	if(this.tagStarted && !this.tagFinished &&(!/(32|37|38|39|40|46)/.test(key)||/(\(|')/.test(charKey)))
	{
		this.cacheTag += charKey;
	}
	if(this.tagStarted && key=='8')
	{
		this.cacheTag = this.cacheTag.substring(0,this.cacheTag.length-2);
	}
	if(/:(D|\(|\)|o|O|'\(|p|P)/.test(this.cacheTag.toUpperCase()))
	{
		
		var str = this.cacheTag.toUpperCase();
		var img;
		var strToReplace;
		var valid =  false;
		var i =  this.emoticonsMSN.length;while(i--)
		{
			if(this.emoticonsMSN[i][0]==str)
			{
				img = this.emoticons[this.emoticonsMSN[i][1]];
				i = 0;
				valid =  true;
			}
		}
		if(valid)
		{
			stopEvent(event);
			if(!isBrowser.IE)
			{
				range.setStart(parentNode,offset-(str.length-1));
				range.setEnd(parentNode,offset);	
				selection.addRange(range);
				try{selection.deleteFromDocument();}catch(e){};
				this.insertHTML('<img src="'+_this.options.emoticonsPath+img+'" title="'+this.cacheTag+'">');
			}
			else
			{
				x.moveStart('character',(str.length*(-1)));	
				x.expand('character');
				x.select();
				try{x.execCommand('Delete',false,'');}catch(e){}
				runCommand(_this.iframeID, 'InsertImage', _this.options.emoticonsPath+img);
			}				
			this.cacheTag ='';
			this.tagFinished = false;
			this.tagStarted = false;
		}
	}
}

textEditor.prototype.chekMSNtags = function(e)
{
	var event = getE(e);
	var key = getPressedKey(e) ;
	var charKey = String.fromCharCode(key);
	this.emoticonsMSN;
};

textEditor.prototype.stockPreviewReplacement= function(replacement,target)
{
	//console.log(this.stockBlocks);
};

function getForeColorPallete(id,x)
{
		var _this_editor = $(x).editor;
		
		
	if (!_this_editor.disableOnHtmlSource) toogle($(id));	
		if(_this_editor.options.fontsPanel)hide(_this_editor.fontStylePanel);
		hide(_this_editor.fontSizePanel);
		if (_this_editor.options.emoticons) 
			hide(_this_editor.emoticonsPanel);
};

function setRange(frameID) 
{
	var oFrame;
	var ex = $(frameID);
	if (document.all) {
		oFrame = frames[frameID];
		var selection = oFrame.document.selection; 
		if (selection != null) ex.editor.rng = selection.createRange();
	} else {
		oFrame = $(frameID).contentWindow;
		var selection = oFrame.getSelection();
		ex.editor.rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	}
}
function getFontPanel(id,x) 
{
	var _this_editor = $(x).editor;
	if (!_this_editor.disableOnHtmlSource)toogle($(id));
		hide(_this_editor.palettePanel_wrapper);
		hide(_this_editor.fontSizePanel);
		if (_this_editor.options.emoticons) 
			hide(_this_editor.emoticonsPanel);
}
function getFontSizePanel(id, x){
	
	var _this_editor = $(x).editor;
	if (!_this_editor.disableOnHtmlSource) toogle($(id));
		hide(_this_editor.palettePanel_wrapper);
	if(_this_editor.fontsPanel) hide(_this_editor.fontStylePanel);
		if (_this_editor.options.emoticons) 
			hide(_this_editor.emoticonsPanel);
}
function hideAllDrops(_this)
{
	hide(_this.palettePanel_wrapper);
	if(_this.options.fontsPanel)hide(_this.fontStylePanel);
	hide(_this.fontSizePanel);
}
function getEmoticonPanel(id,x)
{
	try
	{
		var _this_editor = $(x).editor;			
		if (!_this_editor.disableOnHtmlSource) toogle($(id));
		hide(_this_editor.palettePanel_wrapper);
		if(_this_editor.options.fontsPanel)hide(_this_editor.fontSizePanel);
		hide(_this_editor.fontStylePanel);
	}
	catch(e)
	{}
}
function setEmoticon(frameID,el)
{		
	var _this = $(frameID).editor;
	hide(_this.emoticonsPanel);
	_this.emoticonsIMG.push(el.src);
	runCommand(frameID, 'InsertImage', el.src);
}
function setSelected(e)
{
	addClass(e.parentNode,'rte-selected');
}
function unsetSelected(e)
{
	removeClass(e.parentNode,'rte-selected');
}
function putVideo(id)
{
	var iframe = $(id);
	var _this = iframe.editor;
	if(!_this.disableOnHtmlSource)
	{
		var url='';
		try
		{
			url = prompt('Enter Video URL:', 'http://');
		} 
		catch(e){}
		if(/(http|https):\/\//.test(url))
		{
			var x = url.replace(/(http|https):\/\//, '');
			x = x.split('/')[0];
			x = x.split('.');
			var domain = x.length >= 3 ? x[1] : x[0];
			var tag = '[' + domain + ']' + url + '[/' + domain + ']';
			runCommand(id, 'inserthtml', tag);
			iframe.editor.videoInsertedTags.push([domain,url]);
		}
	}
}



