/*
	jQuery RTE plugin 0.2 - create a rich text form for Mozilla, Opera, and Internet Explorer
 
	Copyright (c) 2007 Batiste Bieler
	Distributed under the GPL (GPL-LICENSE.txt) licenses.
	
	Modified by Eric Chauvel 2008 
 
*/

// define the rte light plugin
jQuery.fn.rte = function(config_rte, media_url,width_rte,height_rte) {

		if(document.designMode || document.contentEditable)
		{
				$(this).each( function(){
						var textarea = $(this);
						enableDesignMode(textarea);
				});
		}
		
		function hexa(v) {	
			var hex = "0123456789ABCDEF" ;						
			
			h = (v >> 4) ;				
			hh = hex.substring(h,h + 1) ;				
			l = (v & 0xF) ;
			ll = hex.substring(l,l + 1) ;
			
			return hh + ll ;
		}	
		
		
		function formatText(iframe, command, option) {
				iframe.contentWindow.focus();
				try{
						iframe.contentWindow.document.execCommand(command, false, option);
				}catch(e){console.log(e)}
				iframe.contentWindow.focus();
		}

		function tryEnableDesignMode(iframe, doc, callback) {
				try {
						iframe.contentWindow.document.open();
						iframe.contentWindow.document.write(doc);
						iframe.contentWindow.document.close();
				} catch(error) {
						console.log(error)
				}
				if (document.contentEditable) {
						iframe.contentWindow.document.designMode = "On";
						callback();
						return true;
				}
				else if (document.designMode != null) {
						try {
								iframe.contentWindow.document.designMode = "on";
								callback();
								return true;
						} catch (error) {
								console.log(error)
						}
				}
				setTimeout(function(){tryEnableDesignMode(iframe, doc, callback)}, 250);
				return false;
		}

		function enableDesignMode(textarea) {
				// need to be created this way
				var iframe = document.createElement("iframe");
				iframe.frameBorder=0;
				iframe.frameMargin=0;
				iframe.framePadding=0;
				iframe.height=200;
				if(textarea.attr('class'))
						iframe.className = textarea.attr('class');
				if(textarea.attr('id'))
						iframe.id = textarea.attr('id');
				if(textarea.attr('name'))
						iframe.title = textarea.attr('name');
				textarea.after(iframe);
			
				var content = textarea.val();
				// Mozilla need this to display caret
				if($.trim(content)=='')
						content = '<br>';
 
				var doc = content ;
				tryEnableDesignMode(iframe, doc, function() {
						$("#toolbar-"+iframe.title).remove();
						$(iframe).before(toolbar(iframe));
						textarea.remove();
				});
				if(width_rte !=0  )$(".rte-zone").css({width:width_rte}) ;
				if(height_rte !=0 ) $(".rte-zone").css({height:height_rte}) ;
				if(width_rte !=0  )$(".rte-toolbar").css({width:width_rte}) ;
		}

		function disableDesignMode(iframe, submit) {
				var content = iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
				if(submit==true)
						var textarea = $('<input type="hidden" />');
				else
						var textarea = $('<textarea cols="40" rows="10"></textarea>');
				textarea.val(content);
				t = textarea.get(0);
				if(iframe.className)
						t.className = iframe.className;
				if(iframe.id)
						t.id = iframe.id;
				if(iframe.title)
						t.name = iframe.title;
				$(iframe).before(textarea);
				if(submit!=true)
						$(iframe).remove();
				return textarea;
		}

		function toolbar(iframe) {
			if (config_rte == "") {
				config_rte = "format,font,bold,italic,justifyleft,justifycenter,justifyright,forecolor,backcolor,insertunorderedlist,insertorderedlist,link,mailto,image,disable";
			}
			
			var toolbar = "<div class='rte-toolbar' id='toolbar-"+iframe.title+"'><div>\r" ;
			if(config_rte.search(/format/i) != -1) {
				toolbar += "<p>\r\
									<select class='formatblock'>\r\
											<option value=''>Bloc style</option>\r\
											<option value='p'>Paragraph</option>\r\
											<option value='h1'>Title 1</option>\r\
											<option value='h2'>Title 2</option>\r\
											<option value='h3'>Title 3</option>\r\
									</select>\r\
							</p>\r\
								"
			}
			toolbar += "<p>" ;
			if(config_rte.search(/font/i) != -1) {
				toolbar += "<p>\r\
									<select class='font'>\r\
											<option value='Arial, Helvetica, sans-serif' style='font-Family:Arial, Helvetica, sans-serif'>Arial</option>\r\
											<option value='Courier New, Courier, mono' style='font-Family:Courier New, Courier, mono'>Courier</option>\r\
											<option value='Times New Roman, Times, serif' style='font-Family:Times New Roman, Times, serif'>Times</option>\r\
											<option value='Verdana, Arial, Helvetica, sans-serif' style='font-Family:Verdana, Arial, Helvetica, sans-serif'>Verdana</option>\r\
									</select>\r\
							</p>\r\
								"
			}
			toolbar += "<p>" ;			
			if(config_rte.search(/bold/i) != -1) {
				toolbar += "<a href='#' class='bold'><img src='"+media_url+"bold.gif' alt='bold' /></a>\r" ;
			}
			if(config_rte.search(/italic/i) != -1) {
				toolbar += "<a href='#' class='italic'><img src='"+media_url+"italic.gif' alt='italic' /></a>\r" ;
			}
			toolbar += "</p>\r<p>" ;
			if(config_rte.search(/justifyleft/i) != -1) {
				toolbar += "<a href='#' class='justifyleft'><img src='"+media_url+"justifyleft.gif' alt='justifyleft' /></a>\r" ;
			}
			if(config_rte.search(/justifycenter/i) != -1) {
				toolbar += "<a href='#' class='justifycenter'><img src='"+media_url+"justifycenter.gif' alt='justifycenter' /></a>\r" ;
			}					
			if(config_rte.search(/justifyright/i) != -1) {
				toolbar += "<a href='#' class='justifyright'><img src='"+media_url+"justifyright.gif' alt='justifyright' /></a>\r" ;
			}								
			toolbar += "</p>\r<p>" ;
			if(config_rte.search(/forecolor/i) != -1) {
				toolbar += "<a href='#' class='forecolor'><img src='"+media_url+"forecolor.png' alt='forecolor' /></a>\r" ;
				toolbar += "<div class='color_font' style='display: none;'>\r" ;
				for(r = 0;r < 257;r += 64) {
					if(r == 256) r = 255 ;
					for(v = 0;v < 257;v += 64) {
						if(v == 256) v = 255 ;
						for(b = 0;b < 257;b += 64) {
							if(b == 256) b = 255 ;														
							toolbar += "<a href='#' class='color' name='color" + hexa(r) + hexa(v) + hexa(b) + "' style='background-color:#" + hexa(r) + hexa(v) + hexa(b) + ";'> </a>\r" ;
						}
					}
				}
				toolbar += "</div>\r" ;				
			}		
/*		toolbar += "</p>\r<p>" ;			
			if(config_rte.search(/backcolor/i) != -1) {
				toolbar += "<a href='#' class='backcolor'><img src='"+media_url+"backcolor.png' alt='ibackcolor' /></a>\r" ;
			}
*/							
			toolbar += "</p>\r<p>" ;
			if(config_rte.search(/insertunorderedlist/i) != -1) {
				toolbar += "<a href='#' class='insertunorderedlist'><img src='"+media_url+"insertunordered.gif' alt='insertunordered list' /></a>\r" ;
			}					
			if(config_rte.search(/insertorderedlist/i) != -1) {
				toolbar += "<a href='#' class='insertorderedlist'><img src='"+media_url+"insertorderedlist.gif' alt='insertordered list' /></a>\r" ;
			}				
			toolbar += "</p>\r<p>" ;
			if(config_rte.search(/link/i) != -1) {
				toolbar += "<a href='#' class='link'><img src='"+media_url+"link.png' alt='link' /></a>\r" ;
			}					
			if(config_rte.search(/mailto/i) != -1) {
				toolbar += "<a href='#' class='mailto'><img src='"+media_url+"mailto.png' alt='mailto' /></a>\r";
			}				
			toolbar += "</p>\r<p>" ;
			if(config_rte.search(/image/i) != -1) {
				toolbar += "<a href='#' class='image'><img src='"+media_url+"image.png' alt='image' /></a>\r" ;
			}	
			toolbar += "</p>\r<p>" ;
			if(config_rte.search(/disable/i) != -1) {
				toolbar += "<a href='#' class='disable'><img src='"+media_url+"close.gif' alt='close rte' /></a>\r" ;
			}				
			toolbar += "</p>\r</div>\r</div>\r" ;	
			
			var tb = $(toolbar) ;	

				$('.formatblock', tb).change(function(){
						var index = this.selectedIndex;
						if( index!=0 ) {
								var selected = this.options[index].value;
								formatText(iframe, "formatblock", '<'+selected+'>');
						}
				});
				$('.font', tb).change(function(){
						var index = this.selectedIndex;
						if( index!=0 ) {
								var selected = this.options[index].value;
								formatText(iframe, "fontname",selected);
						}
				});				
				$('.bold', tb).click(function(){ formatText(iframe, 'bold');return false; });
				$('.italic', tb).click(function(){ formatText(iframe, 'italic');return false; });
				$('.insertunorderedlist', tb).click(function(){ formatText(iframe, 'insertunorderedlist');return false; });
				$('.insertorderedlist', tb).click(function(){ formatText(iframe, 'insertorderedlist');return false; });
				$('.justifyleft', tb).click(function(){ formatText(iframe, 'justifyleft');return false; });
				$('.justifycenter', tb).click(function(){ formatText(iframe, 'justifycenter');return false; })
				$('.justifyright', tb).click(function(){ formatText(iframe, 'justifyright');return false; });
				$('.forecolor', tb).click(function(){
						if($('.color_font',tb).css("display")  == "none") {
							$('.color_font',tb).slideDown("normal");		
						} else {
							$('.color_font',tb).slideUp("normal");
						}
						return false; });
				$(".color[name^='color']", tb).each(function(){		
						$(this).click(function(){
								var p=$(this).css("background-color");		
								formatText(iframe, 'forecolor', p);
								$('.color_font',tb).slideUp("normal");
								return false; });				
				});					
				$('.backcolor', tb).click(function(){
						var p=prompt("couleur","#");
						if(p)
								formatText(iframe, 'backcolor', p);
						return false; });
				$('.link', tb).click(function(){
						var p=prompt("URL:","http://");
						if(p)
								formatText(iframe, 'CreateLink', p);
						return false; });
				$('.mailto', tb).click(function(){
						var p=prompt("e mail","mailto:");
						if(p)
								formatText(iframe, 'CreateLink', p);
						return false; });
				$('.image', tb).click(function(){
						var p=prompt("image URL:");
						if(p)
								formatText(iframe, 'InsertImage', p);
						return false; });
				$('.disable', tb).click(function() {
						var txt = disableDesignMode(iframe);
						var edm = $('<a href="#">Enable design mode</a>');
						tb.empty().append(edm);
						edm.click(function(){
								enableDesignMode(txt);
								return false;
						});
						return false;
				});
				$(iframe).parents('form').submit(function(){
						disableDesignMode(iframe, true); });
				var iframeDoc = $(iframe.contentWindow.document);

				var select = $('select', tb)[0];
				iframeDoc.mouseup(function(){
						setSelectedType(getSelectionElement(iframe), select);
						return true;
				});
				iframeDoc.keyup(function(){
						setSelectedType(getSelectionElement(iframe), select);
						var body = $('body', iframeDoc);
						if(body.scrollTop()>0)
								iframe.height = Math.min(350, parseInt(iframe.height)+body.scrollTop());
						return true;
				});

		/*________/Souligne\__________*/
		$("img",tb).each(function(){		
				$(this).hover(function() {
					$(this).css({border:'1px solid #ecc0c4',cursor:'help'});
					},function() {
						$(this).css({border:'1px solid #FFFFFF',cursor:'help'});
				});				
		});
		
				return tb;
		}

		function setSelectedType(node, select) {
				while(node.parentNode) {
						var nName = node.nodeName.toLowerCase();
						for(var i=0;i<select.options.length;i++) {
								if(nName==select.options[i].value){
										select.selectedIndex=i;
										return true;
								}
						}
						node = node.parentNode;
				}
				select.selectedIndex=0;
				return true;
		}

		function getSelectionElement(iframe) {
				if (iframe.contentWindow.document.selection) {
						// IE selections
						selection = iframe.contentWindow.document.selection;
						range = selection.createRange();
						try {
								node = range.parentElement();
						}
						catch (e) {
								return false;
						}
				} else {
						// Mozilla selections
						try {
								selection = iframe.contentWindow.getSelection();
								range = selection.getRangeAt(0);
						}
						catch(e){
								return false;
						}
						node = range.commonAncestorContainer;
				}
				return node;
		}
}

