/*
* jQuery RTE plugin 0.5.1 - create a rich text form for Mozilla, Opera, Safari and Internet Explorer
*
* Copyright (c) 2009 Batiste Bieler
* Distributed under the GPL Licenses.
* Distributed under the The MIT License.
*/

// define the rte light plugin
(function($) {
	
    //NB: origional rte.html method incorrectly returns body of last created var iframe
	$.fn.rte_html = function() {
		
		function removeSpellcheckTags(taggedHtml)
		{
			var $workingHTML = $("<div></div>").html(taggedHtml)
			
			$(".spellcheck-word-highlight", $workingHTML).each( function() { 
				$(this).replaceWith( $(this).html() )
			})
			$(".spellcheck-suggestbox", $workingHTML).remove()

			return $workingHTML.html()
		}

		//find iframe that matches the id and return its content
		if( $(this).is('textarea') ) 
		{
            var iframe = $(this).siblings('iframe#' + $(this).attr('id') );
            if(iframe == undefined || iframe.get(0) == undefined || (iframe.get(0).contentWindow == undefined && iframe.get(0).contentDocument == undefined))
            {
                return '';
            }
			var html = iframe.contents().find('body');
		} 
		else 
		{
			var html = $(this).contents().find('body');
		}

		html = removeSpellcheckTags(html.html());
		return html;
		
	}; 
	
	//NB: origional rte.html method incorrectly returns body of last created var iframe
	$.fn.rte_text = function() {

		//find iframe that matches the id and return its content
		if( $(this).is('textarea') )
			return $(this).siblings('iframe#' + $(this).attr('id') ).contents().find('body').text()

		return $(this).contents().find('body').text()

	}; 

	$.fn.rte_focus = function() {
        if( $(this).is('textarea') ) {
			$(this).siblings('iframe#' + $(this).attr('id') ).addClass('iframe.rte-zone-expand');
			$(this).siblings('iframe#' + $(this).attr('id') ).each( function() {
				return this.contentWindow.focus()
			}) 
		} else {
			$(this).each( function() {
				$(this).addClass('iframe.rte-zone-expand');
				return this.contentWindow.focus()
			})       
		}
    };
	
	$.fn.rte = function(options) {

    	$.fn.rte.defaults = {
        	media_url: "",
        	content_css_url: "",
        	content_css_data: null,
        	dot_net_button_class: null,
        	max_height: 350,
        	click_callback : null,
			spellcheck_button : false
    	};// build main options before element iteration
    	var opts = $.extend($.fn.rte.defaults, options);

		// iterate and construct the RTEs
	    return this.each( function() {

	        var textarea = $(this);
	        var iframe;
			var selectElement;
			var element_id = textarea.attr("id");


	        // enable design mode
	        function enableDesignMode() {

	            var content = textarea.val();

	            // Mozilla needs this to display caret
	            if($.trim(content)=='') {
	                content = '<br />';
	            }

	            // already created? show/hide
	            if(iframe) {
	                textarea.hide();
	                $(iframe).contents().find("body").html(content);
	                $(iframe).show();
	                $("#toolbar-" + element_id).remove();
	                textarea.before(toolbar());
	                return true;
	            }

	            // for compatibility reasons, need to be created this way
	            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 = element_id;
	            if(textarea.attr('name'))
	                iframe.title = textarea.attr('name');
	
				if($.browser.safari)
				{
					
					textarea.after(iframe);

					$(iframe).mouseup(function(event) //not triggered by Safari
					{ 

						if(iframe.contentWindow.document.selection)
							selectElement = iframe.contentWindow.document.selection.createRange();  // Fix IE loosing the focus (and much more)

						if(opts.click_callback)
							$(iframe).contents().click(opts.click_callback);	

						return true;

					});

					$(iframe).blur(function(event)
					{ 
					
						if(iframe.contentWindow.document.selection)
							selectElement = iframe.contentWindow.document.selection.createRange();  // Fix IE loosing the focus (and much more)

					});
					
					var css = "";
					if(opts.content_css_url) 
						css = "<link type='text/css' rel='stylesheet' href='" + opts.content_css_url + "' />";
					if(opts.content_css_data)
						css += "<style type='text/css'>" + opts.content_css_data + "</style>";
					
					var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
					tryEnableDesignMode(doc, function() 
					{ 
						if(opts.click_callback)
						$(iframe).contents().click(opts.click_callback);	
					})
					$("#toolbar-" + element_id).remove();
					textarea.before(toolbar());
					// hide textarea
					textarea.hide();
					// enable the tab key to tab out of the RTE
					// enable the tab key to tab out of the RTE
					if(opts.focus_after_element){
						// console.log(opts.focus_after_element);
						iframe.contentWindow.document.body.onkeydown = function(e){
							if(e.which == 9){
								e.preventDefault();
								e.stopPropagation();
								if(e.shiftKey)
								{
									$("a.unorderedlist").focus();
								} else {
									
									opts.focus_after_element.focus();
								}
							}
						};
					}
				}
				else
				{

					$(iframe).load(function()
					{				
			            var css = "";
			            if(opts.content_css_url) {
			                css += "<link type='text/css' rel='stylesheet' href='" + opts.content_css_url + "' />";
			            }
			            if(opts.content_css_data) {
			                css += "<style type='text/css'>" + opts.content_css_data + "</style>";
			            }
	
			            var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
			           	tryEnableDesignMode(doc, function() {
			                $("#toolbar-" + element_id).remove();
			                textarea.before(toolbar());
		    	            // hide textarea
		        	        textarea.hide();
	        	        
		        	        $(iframe).mouseup(function(event) {
								if(iframe.contentWindow.document.selection)
									selectElement = iframe.contentWindow.document.selection.createRange();  // Fix IE loosing the focus (and much more)
								
								return true;
							});
		
							$(iframe).blur(function(event){ 
								if(iframe.contentWindow.document.selection)
									selectElement = iframe.contentWindow.document.selection.createRange();  // Fix IE loosing the focus (and much more)
							});
						
							if(opts.click_callback)
							{
								$(iframe).contents().click(opts.click_callback);	
							}
		            	});
	            	})
					textarea.after(iframe);
				}
	            
	        }

			function tryEnableDesignMode(doc, callback) 
			{
				if(!iframe)
					return false;

				try 
				{
					if($.browser.safari)
					{
						iframe.contentWindow.document.write(doc);
					}
					else
					{
						if(iframe && iframe.contentWindow && iframe.contentWindow.document)
						{
							iframe.contentWindow.document.write(doc);
						}
						else
						{
							$(iframe).contents().find('body').html(doc);
						}
					}
	            }
				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(doc, callback)}, 500);
	            return false;
	        }          

 	       	function disableDesignMode(submit) {
	            var content = $(iframe).contents().find("body").html();

	            if($(iframe).is(":visible")) {
	                textarea.val(content);
	            }

	            if(submit != true) {
	                textarea.show();
	                $(iframe).hide();
	            }
	        }               

	        // create toolbar and bind events to it's elements
	        function toolbar() {
				
				var spellcheck_button = (!opts.spellcheck_button || ($.browser.msie && $.browser.version < 8))? "" : "<li class='spellcheck'><a href='#' title='Spell Check'>Spell Check</a></li>";
				// per accessibility requirements
				var tb_str = '<div id="toolbar-'+element_id+'">' +
					'<div id="ColorPicker"></div>' +
					'<div class="wysiwyg">'    +
					  '<a href="#" title="Bold" class="bold" tabindex="0">Bold</a>'     +
						'<a href="#" title="Italic" class="italic" tabindex="0">Italic</a>' +
						'<a href="#" title="Underline" class="underline" tabindex="0">Underline</a>' +
						'<a href="#" title="Enlarge" class="enlarge" tabindex="0">Enlarge</a>' +
						'<a href="#" title="Smaller" class="smaller" tabindex="0">Smaller</a>' +
						'<a href="#" title="Indent Right" class="indent-right" tabindex="0">Right indent</a>' +
						'<a href="#" title="Indent Left" class="indent-left" tabindex="0">Left indent</a>' +
						'<a href="#" title="Font Color" class="font-color" tabindex="0">Font color</a>' +
						'<a href="#" title="Link" class="link" tabindex="0">Link</a>' +
					//	'<a href="#" tttle="Image" class="image" tabindex="0">Image</a>' +
						'<a href="#" title="Numbered List" class="numbered" tabindex="0">Numbered List</a>' +
						'<a href="#" title="Unordered List" class="unorderedlist" tabindex="0">Unordered list</a>' +
					'</div></div>';
				var tb = $(tb_str);
	            var tb2 = $("<div class='rte-toolbar' id='toolbar-"+ element_id +"'><div>\
	                <p>\
	                    <select>\
	                        <option value=''>Block style</option>\
	                        <option value='p'>Paragraph</option>\
	                        <option value='h3'>Title</option>\
	                        <option value='address'>Address</option>\
	                    </select>\
	                </p>\
	                </div></div>");

	            $('select', tb).change(function(){
	                var index = this.selectedIndex;
	                if( index!=0 ) {
	                    var selected = this.options[index].value;
	                    formatText("formatblock", '<'+selected+'>');
	                }
	            });
	            $('.bold', tb).click(function(){formatText('bold');return false;});
	            $('.italic', tb).click(function(){formatText('italic');return false;});
	            $('.underline', tb).click(function(){formatText('underline');return false;});
							// $('a',tb).click(function(){ console.log(this);console.log(document.activeElement.onclick ); });
							
							$('a',tb)
								.focus(function(e){ 
									$(this).css('outline',FOCUS_OUTLINE) ;
									$(this).css('outline-offset',FOCUS_OFFSET);
								})
								.blur(function(e){ $(this).css('outline','none') })
								.keydown(function(e){
									if(e.which===ENTER_KEY){
										$(this).css('outline','none')
									}
								})
								.keyup(function(e){
									if(e.which===ENTER_KEY){
										iframe.contentWindow.document.body.focus();
									}
								});

				
				// Spell Check plugin
				// IE7 has known issue
				if(!$.browser.msie || $.browser.version > 7)
					$('.spellcheck', tb).click(function(){spellCheck();return false;});

		
				// Custom buttons
	            $('.enlarge', tb).click(function(){ 
		
			            if ($.browser.msie) {
			                formatText("fontSize", qc("fontSize") + 1);
			            } else if ($.browser.safari) {
					      formatText("fontSize", qcb("fontSize") + 1);
					//		getRange().surroundContents($(iframe.contentWindow.document.createElement("span")).css("font-size", "larger")[0]);
			            } else {
			                formatText("increaseFontSize", "big");
			            }
			       
					return false;
					
				});
				
	            $('.smaller', tb).click(function(){ 
		
			            if ($.browser.msie) {
			                formatText("fontSize", qc("fontSize") - 1);
			            } else if ($.browser.safari) {
					       formatText("fontSize", qcs("fontSize") - 1);
						//	getRange().surroundContents($(iframe.contentWindow.document.createElement("span")).css("font-size", "smaller")[0]);
			            } else {
			                formatText("decreaseFontSize", "small");
			            }

					return false; 
					
				});
				
	            $('.indent-right', tb).click(function(){formatText('indent');return false;});
	            $('.indent-left', tb).click(function(){formatText('outdent');return false;});
	
	            $('.font-color', tb).click(function(){ 
					colorPicker( $(this), tb );
					//formatText("foreColor", '#990000');									
            		return false;});
				
	            $('.numbered', tb).click(function(){formatText('insertorderedlist');return false;});
	            $('.unorderedlist', tb).click(function(){formatText('insertunorderedlist');return false;});
	            $('.link', tb).click(function(){
	                var p=prompt("URL:");
	                if(p) {
						// modified by brad@staff.atmail.com to check for a protocol
						// default to http:// if none specified (avoids accidental relative links)
						p = p.replace(/^\s+/, '');
						if (p.indexOf('http://') != 0 && p.indexOf('https://') != 0 && p.indexOf('ftp://') != 0) {
							p = 'http://' + p;
						}
						// end mods
	                    formatText('CreateLink', p);
	                }
					return false;});

	            $('.image', tb).click(function(){
	                var p=prompt("Please enter the full Internet URL of the image you wish to attach:");
	                if(p)
	                    formatText('InsertImage', p);
	                return false;});

	            $('.disable', tb).click(function() {
	                disableDesignMode();
	                var edm = $('<a class="rte-edm" href="#">Enable design mode</a>');
	                tb.empty().append(edm);
	                edm.click(function(e){
	                    e.preventDefault();
	                    enableDesignMode();
	                    // remove, for good measure
	                    $(this).remove();
	                });
	                return false;
	            });

	            // .NET compatability
	            if(opts.dot_net_button_class) {
	                var dot_net_button = $(iframe).parents('form').find(opts.dot_net_button_class);
	                dot_net_button.click(function() {
	                    disableDesignMode(true);
	                });
	            // Regular forms
	            } else {
	                $(iframe).parents('form').submit(function(){
	                    disableDesignMode(true);
	                });
	            }
                
				/*
				var iframeDoc = $(iframe.contentWindow.document);

	            var select = $('select', tb)[0];
	            iframeDoc.mouseup(function(){
	                setSelectedType(getSelectionElement(), select);
	                return true;
	            });

	            iframeDoc.keyup(function() {
	                setSelectedType(getSelectionElement(), select);
	                var body = $('body', iframeDoc);
	                if(body.scrollTop() > 0) {
	                    var iframe_height = parseInt(iframe.style['height'])
	                    if(isNaN(iframe_height))
	                        iframe_height = 0;
	                    var h = Math.min(opts.max_height, iframe_height+body.scrollTop()) + 'px';
	                    iframe.style['height'] = h;
	                }
	                return true;
	            });
				*/
	            return tb;
	        };     
		
	        function formatText(command, option) {
	            iframe.contentWindow.focus();
	            try{
	                iframe.contentWindow.document.execCommand(command, false, option);
	            }catch(e){
	                //console.log(e)
	            }
	            iframe.contentWindow.focus();
	        };

			function qc(command) {
	            iframe.contentWindow.document.focus();
	            var value = iframe.contentWindow.document.queryCommandValue(command);	
				if(value == null && command == 'fontSize')
					value = 1;	// Workaround for HTML size in IE (default size is 1)
				return value;
	        };
		   var globalFontCounter = 1;
			function qcb(command) {
	            // var value = iframe.contentWindow.document.queryCommandValue(command);	
				// if(value == null && command == 'fontSize')
					// value = 1;	// Workaround for HTML size in IE (default size is 1)
					globalFontCounter++;
					value = globalFontCounter;
					if (value >=6){
						globalFontCounter =7;
					}
					value = globalFontCounter;
					//console.log(value);
				return value;
	        };
	        
			function qcs(command) {
	            // var value = iframe.contentWindow.document.queryCommandValue(command);	
				// if(value == null && command == 'fontSize')
					// value = 1;	// Workaround for HTML size in IE (default size is 1)
					globalFontCounter--;
					value = globalFontCounter;	
					if (value <=2){
						globalFontCounter =1;
					}
					value = globalFontCounter;
					
				//	console.log(value);
				return value;
	        };
	
	        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 getSelection() {
	            if ($.browser.msie) {
	                //return (this.editor.parentWindow.getSelection) ? this.editor.parentWindow.getSelection() : this.editor.selection;
	                //return this.editor.selection;
	            } else {
	                return iframe.contentDocument.defaultView.getSelection();
	            }
	        }
	
	        function getRange() {
	            var s = getSelection();
	            if (!s) {return null;}
	            return (s.getRangeAt) ? s.getRangeAt(0) : s.createRange();
	        }
	
	        function getSelectionElement() {
	            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;
	        };

			// Color picker
			function colorPicker(element, toolbar) {

			    defaultOptions = {
			        "z-index": 0,
			        offsetTop: 0,
			        offsetLeft: 0,
			        colors: [
			            "#ffffff",
			            "#cccccc",
			            "#c0c0c0",
			            "#999999",
			            "#666666",
			            "#333333",
			            "#000000",

			            "#ffcccc",
			            "#ff6666",
			            "#ff0000",
			            "#cc0000",
			            "#990000",
			            "#660000",
			            "#330000",

			            "#ffcc99",
			            "#ff9966",
			            "#ff9900",
			            "#ff6600",
			            "#cc6600",
			            "#993300",
			            "#663300",

			            "#ffff99",
			            "#ffff66",
			            "#ffcc66",
			            "#ffcc33",
			            "#cc9933",
			            "#996633",
			            "#663333",

			            "#ffffcc",
			            "#ffff33",
			            "#ffff00",
			            "#ffcc00",
			            "#999900",
			            "#666600",
			            "#333300",

			            "#99ff99",
			            "#66ff99",
			            "#33ff33",
			            "#33cc00",
			            "#009900",
			            "#006600",
			            "#003300",

			            "#99FFFF",
			            "#33FFFF",
			            "#66CCCC",
			            "#00CCCC",
			            "#339999",
			            "#336666",
			            "#003333",

			            "#CCFFFF",
			            "#66FFFF",
			            "#33CCFF",
			            "#3366FF",
			            "#3333FF",
			            "#000099",
			            "#000066",

			            "#CCCCFF",
			            "#9999FF",
			            "#6666CC",
			            "#6633FF",
			            "#6600CC",
			            "#333399",
			            "#330099",

			            "#FFCCFF",
			            "#FF99FF",
			            "#CC66CC",
			            "#CC33CC",
			            "#993399",
			            "#663366",
			            "#330033"
			        ],
			        colorChosen: null
			    };

				var opts = $.extend({}, defaultOptions);					
				var position = element.position();
				var picker = $("#ColorPicker", toolbar).html('').css({
		               position: "absolute",
		               left: position.left,
		               "z-index": opts["z-index"]
		           }).addClass("ColorPickerMenu");
				//the main problem with positioning the picker manually with every hit is that scrollposition changes the absolute placement in the scrollable context
				visiblePanelContext = getVisiblePanelContext(); 
				if( visiblePanelContext == '#messageList' )
					scrollingWindowContext = $(visiblePanelContext).find('#primary_content').find('#mail_info')
				else
					scrollingWindowContext = $(visiblePanelContext).find('#primary_content')
				scrollPosContext = scrollingWindowContext.scrollTop()
				if(!scrollPosContext) {
					scrollPosContext = 0;
				}
                if($.browser.msie && $.browser.version == 7 || $.browser.version == 8)
                {
                    picker.css('margin-top', 27 + 'px')
                }
                else
                {
                    picker.css('top', position.top+27+scrollPosContext + 'px');
                }

                for (var i = 0; i < opts.colors.length; i++) {
		               var c = opts.colors[i];
		               $("<div/>").css("background-color", c).appendTo(picker).click(
		                   (function(color) {
		                       return function() {
								if ($.browser.msie) {
									// Fix for losing the current selected item
                                    if(selectElement) selectElement.select();
									formatText("ForeColor", color);
								} else {
		                        	formatText("foreColor", color);									
								}
									picker.hide();
		                           //$(this).parent().hide();
		                       };
		                   })(c)
		               );
		           }

				
		           var autoHide = true;
		           picker.appendTo(element.parent()).
		               show().
		               mouseout(function() {
		                   autoHide = true;
		                   element.currentTimeout = window.setTimeout(function() { if (autoHide === true) { picker.hide(); } }, 500);
		               }).
		               mouseover(function() {
		                   if ( element.currentTimeout) {
		                       window.clearTimeout( element.currentTimeout);
		                       element.currentTimeout = null;
		                   }
		                   autoHide = false;
		               });
					 
			
			
			};
			
			
			//
			// Spell Check
			//    for TIME processing spell check, 50kb sounds fine to start.  
			function spellCheck() {
				
				var text = $(iframe).rte_text();
				$(iframe).contents().find('body').spellchecker({
					url: moduleBaseUrl + "/composemessage/spellcheck",       // default spellcheck url
					lang: "en",                     // default language 
					engine: "pspell",               // pspell or google
					addToDictionary: false,         // display option to add word to dictionary (pspell only)
					wordlist: {
						action: "after",               // which jquery dom insert action
						element: $("#text-content")    // which object to apply above method
					},      
					suggestBoxPosition: "below",    // position of suggest box; above or below the highlighted word
					innerDocument: true            // if you want the badwords highlighted in the html then set to true
				}).spellchecker("check");
				
			}
			
	        // enable design mode now
	        enableDesignMode();

    	}); //return this.each
    
	};// rte

})(jQuery);


