/*
 * jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */

/*(function() {

	var fieldSelection = {

			replaceSelection: function() {
				return (
					function() {
						return {msg:"hi"};
					}
				)();

			}

	};

	jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();*/

(function($) {
	 var opts = {};	  
	 $.fn.gmxeditor = function(settings) {
	
		return this.each(function() {
			var textarea = $(this);
			$.fn.gmxeditor.init(textarea,settings);
		
		});

	};
	
	/*$.fn.fancybox.makebold = function(obj) {
		 document.getElementById($(obj).parents(".gmxeditormain").find("iframe").attr("id")).contentWindow.document.execCommand("Bold", false, null);;
	}*/
	
	 function formatText(iframe, command, option) {
        iframe.contentWindow.focus();
        try{
            iframe.contentWindow.document.execCommand(command, false, option);
        }catch(e){console.log(e)}
        iframe.contentWindow.focus();
    }
    
	
	$.fn.gmxeditor.enableDesign = function(iframe,doc) {
		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";
            return true;
        }
        else if (document.designMode != null) {
            try {
                iframe.contentWindow.document.designMode = "On";
				
                return true;
            } catch (error) {
                console.log(error)
            }
        }
		
		//iframe.contentWindow.document.body.contentEditable = true;
        //setTimeout(function(){enableDesign(iframe)}, 250);
		 iframe.contentWindow.focus();
       
	};
		
    function selectColor(color, iframe) {
		$(".gmxColor").remove();
		 formatText(iframe, 'ForeColor',color);
		 
	}

	 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) {
        
         var tb = $("\
             <div class='gmxEditorBut'>\
                <button class='gmxEditorBold'></button>\
				<button class='gmxEditorItalic'></button>\
				<button class='gmxEditorUnderline'></button>\
				<button class='gmxEditorLink'></button>\
				<button class='gmxEditorColor'></button>\
            </div>\
            ");
        $('.gmxEditorBold', tb).click(function(){ formatText(iframe, 'bold');return false; });
        $('.gmxEditorItalic', tb).click(function(){ formatText(iframe, 'italic');return false; });
		$('.gmxEditorUnderline', tb).click(function(){ formatText(iframe, 'underline');return false; });
        $('.gmxEditorLink', tb).click(function(){ 
            var p=prompt("URL:");
            if(p)
                formatText(iframe, 'CreateLink', p);
            return false; 
		});
        $('.gmxEditorColor', tb).click(function(){ 
			pos = $(this).offset();
			$('<div class="gmxColor" style="position:absolute;"><table cellpadding="0" cellspacing="0"><tr><td id="RTE_FFFFFF">&nbsp;</td>	<td id="RTE_FFCCCC">&nbsp;</td><td id="RTE_FFCC99">&nbsp;</td><td id="RTE_FFFF99">&nbsp;</td><td id="RTE_FFFFCC">&nbsp;</td><td id="RTE_99FF99">&nbsp;</td>	<td id="RTE_99FFFF">&nbsp;</td><td id="RTE_CCFFFF">&nbsp;</td><td id="RTE_CCCCFF">&nbsp;</td><td id="RTE_FFCCFF">&nbsp;</td></tr><tr><td id="RTE_CCCCCC">&nbsp;</td><td id="RTE_FF6666">&nbsp;</td><td id="RTE_FF9966">&nbsp;</td><td id="RTE_FFFF66">&nbsp;</td>	<td id="RTE_FFFF33">&nbsp;</td><td id="RTE_66FF99">&nbsp;</td><td id="RTE_33FFFF">&nbsp;</td><td id="RTE_66FFFF">&nbsp;</td><td id="RTE_9999FF">&nbsp;</td><td id="RTE_FF99FF">&nbsp;</td></tr><tr><td id="RTE_C0C0C0">&nbsp;</td><td id="RTE_FF0000">&nbsp;</td>	<td id="RTE_FF9900">&nbsp;</td><td id="RTE_FFCC66">&nbsp;</td>	<td id="RTE_FFFF00">&nbsp;</td>	<td id="RTE_33FF33">&nbsp;</td><td id="RTE_66CCCC">&nbsp;</td><td id="RTE_33CCFF">&nbsp;</td>		<td id="RTE_6666CC">&nbsp;</td><td id="RTE_CC66CC">&nbsp;</td></tr><tr>	<td id="RTE_999999">&nbsp;</td><td id="RTE_CC0000">&nbsp;</td><td id="RTE_FF6600">&nbsp;</td><td id="RTE_FFCC33">&nbsp;</td><td id="RTE_FFCC00">&nbsp;</td>		<td id="RTE_33CC00">&nbsp;</td><td id="RTE_00CCCC">&nbsp;</td><td id="RTE_3366FF">&nbsp;</td><td id="RTE_6633FF">&nbsp;</td><td id="RTE_CC33CC">&nbsp;</td></tr><tr><td id="RTE_666666">&nbsp;</td><td id="RTE_990000">&nbsp;</td><td id="RTE_CC6600">&nbsp;</td><td id="RTE_CC9933">&nbsp;</td><td id="RTE_999900">&nbsp;</td><td id="RTE_009900">&nbsp;</td>	<td id="RTE_339999">&nbsp;</td><td id="RTE_3333FF">&nbsp;</td>	<td id="RTE_6600CC">&nbsp;</td><td id="RTE_993399">&nbsp;</td></tr><tr><td id="RTE_333333">&nbsp;</td><td id="RTE_660000">&nbsp;</td><td id="RTE_993300">&nbsp;</td><td id="RTE_996633">&nbsp;</td><td id="RTE_666600">&nbsp;</td><td id="RTE_006600">&nbsp;</td><td id="RTE_336666">&nbsp;</td>	<td id="RTE_000099">&nbsp;</td><td id="RTE_333399">&nbsp;</td><td id="RTE_663366">&nbsp;</td></tr><tr><td id="RTE_000000">&nbsp;</td><td id="RTE_330000">&nbsp;</td><td id="RTE_663300">&nbsp;</td><td id="RTE_663333">&nbsp;</td>		<td id="RTE_333300">&nbsp;</td><td id="RTE_003300">&nbsp;</td><td id="RTE_003333">&nbsp;</td><td id="RTE_000066">&nbsp;</td><td id="RTE_330099">&nbsp;</td><td id="RTE_330033">&nbsp;</td></tr></table><div>').appendTo('body'); 
			
			$(".gmxColor").css({'top':pos.top+20,'left':pos.left});
			$('.gmxColor').click(function(e) {
			   e.stopPropagation();
			});
		
			jQuery(document).click(function() {
				jQuery(".gmxColor").hide();
			});
			
			
			if (document.getElementsByTagName)
				var x = document.getElementsByTagName('TD');
			else if (document.all)
				var x = document.all.tags('TD');
			for (var i=0; i < x.length; i++) {
				x[i].onmouseover = function() {
						this.style.border = '1px solid #FFF';
						this.style.cursor = 'hand';
						this.style.cursor = 'pointer';
				};
				x[i].onmouseout = function() {
						this.style.border = '1px solid #000';
						this.style.cursor = 'default';
				};
				x[i].onmousedown = function() {
						selectColor('#' + this.id.replace('RTE_', ''), iframe);	
				};
				x[i].style.background = '#' + x[i].id.replace('RTE_', ''); 
			}
							   
															 
															 
		 return false; 
		});
      /*  var iframeDoc = $(iframe.contentWindow.document);
        
          iframeDoc.mouseup(function(){ 
            getSelectionElement(iframe);
            return true;
        });
        iframeDoc.keyup(function(){ 
           getSelectionElement(iframe);
            return true;
        });*/
		
		$(iframe).parents('form').submit(function(){
            disableDesignMode(iframe, true); 
		});
        
        return tb;
	};
	    
   
	$.fn.gmxeditor.init = function(textarea,settings) {
		//$(obj).hide();
		//if (jQuery.fn.pngFix) $(document).pngFix();
		//var theIframe = document.getElementById("gmx_editor")

//theIframe.contentWindow.document.body.contentEditable = true;
		//$('<div class="gmxeditormain"><div style=""><button onclick="$.fn.fancybox.makebold(this)">B</button><button>I</button><button>U</button><button>C</button><button>A</button></div><div><iframe name="gmx_editor"  id="gmx_editor" style="background-color: white;height: 20px;font: normal 80% arial, sans-serif;	border: 1px black solid;overflow: visible;width: 200px; cursor:text;margin:0px;padding:0px;" onload="$.fn.fancybox.showIframe(this)" scrolling="no" marginheight="0" marginwidth="0"></iframe></div></div>').insertBefore(obj);
		 var iframe = document.createElement("iframe");
        iframe.frameBorder=0;
        iframe.frameMargin=0;
        iframe.framePadding=0;
        iframe.width=textarea.attr('gmxEditorWidth');
		iframe.height=textarea.attr('gmxEditorHeight');
		iframe.scrolling="no";
		iframe.marginHeight=0;
		iframe.marginWidth=0;
        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 css = "";
        if(settings.css_url)
            var css = "<link type='text/css' rel='stylesheet' href='"+settings.css_url+"' />"
		
		 var content = textarea.val();

		  //if($.trim(content)=='')
            //content = '<br>';
		 var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
		  textarea.remove();
		$.fn.gmxeditor.enableDesign(iframe,doc);
		
		$(iframe).before(toolbar(iframe))
		//var theIframe = document.getElementById("gmx_editor")
//		$('#gmx_editor').contentDocument.document.designMode= "On";
  		//theIframe.contentWindow.document.body.contentEditable = true;

	};
	
	
	
})(jQuery);
