/*
* 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($) {

    $.fn.rte = function(options) {

    $.fn.rte.html = function(iframe) {
        return iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
    };

    $.fn.rte.defaults = {
        media_url: "",
        content_css_url: "rte.css",
        dot_net_button_class: null,
        max_height: 400
    };

    // 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 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=350;
            iframe.width="100%";
            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');

            textarea.after(iframe);

            var css = "";
			
//            if(opts.content_css_url) {
//                css = "<link type='text/css' rel='stylesheet' href='" + opts.content_css_url + "' />";
//            }

            var doc = "<html><head>"+css+"<style>html,body{margin:0;padding:0;}</style></head><body class='frameBody'>"+content+"</body></html>";
            tryEnableDesignMode(doc, function() {
                $("#toolbar-" + element_id).remove();
                toolbar();
                // hide textarea
                textarea.hide();

            });

        }

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

            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(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 tb = $("#text-format");

            $("#insert-model").hide();
            tb.show();

            $('.bold', tb).unbind("click").click(function(){ formatText('bold');return false; });
            $('.italic', tb).unbind("click").click(function(){ formatText('italic');return false; });
            $('.underline', tb).unbind("click").click(function(){ formatText('underline');return false; });
            $('.unorderedlist', tb).unbind("click").click(function(){ formatText('insertunorderedlist');return false; });
            $('.orderedlist', tb).unbind("click").click(function(){ formatText('insertorderedlist');return false; });
            
            $('.link', tb).unbind("click").click(function(){
				formatText( "CreateLink" , "#tmp#" );
				
				Email.link();
			});

            var iframeDoc = $(iframe.contentWindow.document);
			
            $('.image', tb).unbind("click").click(function(){
				Email.IMG = null;
				
				var selection = _getSelectElement();
				Email.IMG = $( selection );
				
				if( Email.IMG.length == 0 ){
					$img = $("<img>");
					$img.css("width","143px").css("height","83px");
					iframeDoc.find("body").prepend( $img );
					
					Email.IMG = $img;
				}
				
				Email.upload();
			});

			$('#link-close').click(function(){
				$("#link").hide();
				$("#overlayer").hide();
			});

			$('#upload-close').click(function(){
				$("#upload").hide();
				$("#overlayer").hide();
			});
			
			$('#link-insert').click(function(){
				$a = iframeDoc.find('a[href=#tmp#]');
				
				$a.css( 'color' , Email.color );
				$a.attr( 'target' , '_blank' );
				$a.attr( 'href' , $('#link-url').val() );

				$("#link").hide();
				$("#overlayer").hide();
			});

			$('#upload-insert').click(function(){

				YAHOO.util.Connect.setForm( "upload-form", true , true );

				YAHOO.util.Connect.asyncRequest( "POST" , $("#upload-form").attr("action") , {
						upload: function( o ){
							var response = eval("("+o.responseText+")");
							Email.IMG.attr( "src" , response.src );
						},
						failure: function(response){
							alert("Erro no upload.");
						}
				});
				
				$("#upload").hide();
				$("#overlayer").hide();
			});

            $main = textarea.parent().parent();
            $hd = $main.find(".hd");
            
            $main.find(".button-save").unbind("click").click(function(){
				$a = iframeDoc.find('a');

				$a.css( 'color' , Email.color );
				$a.attr( 'target' , '_blank' );
				
                var content = $(iframe).contents().find("body").html();
				
                textarea.val(content);
                $(iframe).hide();

                $main.find(".bd").html(content).show();

                $main.find('.button-normal').show();
                $main.find('.button-editable').hide();

                $("#insert-model").show();
                tb.hide();

				Email.active = false;

				$.post("/email/bkp", {ds: $("#email").html()} , function(response){
					if( response == "ok" ){
						var date = new Date(),
							day = "0" + date.getDay(),
							month = "0" + (date.getMonth()+1),
							minutes = "0" + date.getMinutes();

						if( day.length == 3 ){
							day = date.getDay();
						}

						if( month.length == 3 ){
							month = date.getMonth();
						}

						if( minutes.length == 3 ){
							minutes = date.getMinutes();
						}

						$("#back-message").html( "Última versão salva em "+
							day + "/" +
							month + "/" +
							date.getFullYear() +
							" às " + date.getHours() + ":" + minutes )
						.css( 'font-size' , '11px' )
						.css( 'color' , '#838383' );
					}
				});
            });

            $main.find(".button-cancel").unbind("click").click(function(){
                $(iframe).hide();
                $main.find(".bd").show();

                $main.find('.button-normal').show();
                $main.find('.button-editable').hide();

                $("#insert-model").show();
                tb.hide();

				Email.active = false;
            });



            iframeDoc.keyup(function() {
                var body = $('body', iframeDoc);
                
                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 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;
        }

		function _getTarget(ev) {
			var n = ev.target || ev.srcElement;
			try {
				if (n && 3 == n.nodeType) {
					return n.parentNode;
				}
			} catch(e) { }

			return n;
		}
		function _getDoc(){
			return iframe.contentWindow.document;
		}

		function _getWindow(){
			return iframe.contentWindow;
		}
		
		function _getSelection()
		{
			var sel = null;

			if ( _getDoc() && _getWindow() )
			{
				if ( _getDoc().selection )
					sel = _getDoc().selection;
				else
					sel = _getWindow().getSelection();
			}

			return sel;
		}

		function _getRange()
		{
			var sel = _getSelection();

			if( sel == null )
				return null;

			if ( $.browser.msie ) {
				try {
					return sel.createRange();
				} catch (e) {
					return null;
				}
			}

			if (sel.rangeCount > 0) {
				return sel.getRangeAt(0);
			}
			return null;

		}

		function _getSelectElement(){

			var doc = _getDoc(),
			range = null,
			sel = null,
			elm = null,
			currentEvent;

			if ( $.browser.msie ) {
				currentEvent = _getWindow().event; //Event utility assumes window.event, so we need to reset it to this._getWindow().event;
				range = _getRange();

				if (range) {
					elm = range.item ? range.item(0) : range.parentElement();
					if (elm == doc.body) {
						elm = null;
					}
				}
				if ((currentEvent !== null) && (currentEvent.keyCode === 0)) {
					elm = _getTarget( currentEvent );
				}
			} else {
				sel = _getSelection();
				range = _getRange();

				if (!sel || !range) {
					return null;
				}

				if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) {
					if (sel.anchorNode.parentNode) { //next check parentNode
						elm = sel.anchorNode.parentNode;
					}
					if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) {
						elm = sel.anchorNode.nextSibling;
					}
				}

				if (!elm) {
					elm = range.commonAncestorContainer;
					if (!range.collapsed) {
						if (range.startContainer == range.endContainer) {
							if (range.startOffset - range.endOffset < 2) {
								if (range.startContainer.hasChildNodes()) {
									elm = range.startContainer.childNodes[range.startOffset];
								}
							}
						}
					}
				}
			}

			if( currentEvent !== null ){
				try {
					switch (currentEvent.type) {
						case 'click':
						case 'mousedown':
						case 'mouseup':
							elm = _getTarget( currentEvent );
							break;
						default:
							//Do nothing
							break;
					}
				} catch(e){}
			}

			if (!elm || !elm.tagName) {
				elm = doc.body;
			}

			if (elm && !elm.parentNode) { //Not in document
				elm = doc.body;
			}

			if (elm === undefined) {
				elm = null;
			}
			return elm;
		}

        // enable design mode now
        enableDesignMode();

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

})(jQuery);

