//VNC's RTE 1.0
(function($) {
jQuery.fn.vnc_rte = function() {
	var css_url = '/images/rte/rte.css';
	var img_loc = '/images/rte/';
	var gentleClean = true; //true, false or 'ask'

	var nlTag='|div|p|table|tbody|tr|td|th|title|script|comment|li|h1|h2|h3|h4|h5|h6|hr|ul|ol|option|select|'; 
	var tagNl='|p|th|style|'; 
	var regCmt=new RegExp(); 
	regCmt.compile("^<!--(.*)-->$"); 
	var regHyph=new RegExp(); 
	regHyph.compile("-$"); 

	if(document.designMode || document.contentEditable)
    {
        jQuery(this).each( function(){
            var textarea = jQuery(this);
            enableDesignMode(textarea);
        });
    }
    
    function formatText(iframe, command, option) {

		iframe.contentWindow.focus();
		if (!document.all) iframe.contentWindow.document.execCommand('useCSS',false, true); //no spans for bold, italic
		if ("leftrightcenterjustify".indexOf(command) !=-1) command = "justify" + command;
		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;
        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(css_url)
            var css = "<link type='text/css' rel='stylesheet' href='"+css_url+"' />";
        var content = textarea.val();
        // Mozilla need this to display caret
        if(jQuery.trim(content)=='')
            content = '<br />';
        var doc = "<html><head>"+css+"</head><body class='frameBody'>"+content+"</body></html>";
        tryEnableDesignMode(iframe, doc, function() {
            jQuery(iframe).before(toolbar(iframe));
            textarea.remove();
        });
    }
    
    function disableDesignMode(iframe, submit) {
		var content = get_xhtml(iframe.contentWindow.document.getElementsByTagName("body")[0]);
		content = tidyH(content);
	
        if(submit==true)
            var textarea = jQuery('<input type="hidden" />');
        else
            var textarea = jQuery('<textarea></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;
		t.value=t.value.replace(location.href+'#','#'); //IE anchor bug
        jQuery(iframe).before(textarea);
        if(submit!=true)
            jQuery(iframe).remove();
    }
    
    function toolbar(iframe) {
        var tb = jQuery("<div class='rte-toolbar'><div>\
            <p>\
                <select>\
                    <option value=''>Bloc style</option>\
                    <option value='p'>Paragraph</option>\
                    <option value='h3'>Title</option>\
                </select>\
            </p>\
            <p>\
                <a href='#' class='vnc_rte_bold' title='Chữ in đậm'><img src='"+img_loc+"bold.png' alt='bold' /></a>\
                <a href='#' class='vnc_rte_italic' title='Chèn in nghiên'><img src='"+img_loc+"italic.png' alt='italic' /></a>\
				<a href='#' class='vnc_rte_underline' title='Chèn gạch dưới'><img src='"+img_loc+"underline.png' alt='underline' /></a>\
            </p>\
            <p>\
                <a href='#' class='vnc_rte_left' title='Canh trái'><img src='"+img_loc+"left.png' alt='Left' /></a>\
                <a href='#' class='vnc_rte_center' title='Canh giữa'><img src='"+img_loc+"center.png' alt='Center' /></a>\
				<a href='#' class='vnc_rte_right' title='Canh phải'><img src='"+img_loc+"right.png' alt='Right' /></a>\
            </p>\
			<p>\
                <a href='#' class='vnc_rte_unorderedlist' title='Chèn danh sách'><img src='"+img_loc+"unordered.gif' alt='unordered list' /></a>\
                <a href='#' class='vnc_rte_link' title='Chèn URL'><img src='"+img_loc+"link.png' alt='link' /></a>\
                <a href='#' class='vnc_rte_image' title='Chèn hình'><img src='"+img_loc+"image.png' alt='image' /></a>\
                <a href='#' class='vnc_rte_disable' title='Đóng trình soạn thảo'><img src='"+img_loc+"close.gif' alt='close rte' /></a>\
            </p></div></div>");
        jQuery('select', tb).change(function(){
            var index = this.selectedIndex;
            if( index!=0 ) {
                var selected = this.options[index].value;
                formatText(iframe, "formatblock", '<'+selected+'>');
            }
        });

		jQuery('.vnc_rte_bold', tb).click(function(){ formatText(iframe, 'bold');return false; });
        jQuery('.vnc_rte_italic', tb).click(function(){ formatText(iframe, 'italic');return false; });
		jQuery('.vnc_rte_underline', tb).click(function(){ formatText(iframe, 'underline');return false; });
		jQuery('.vnc_rte_left', tb).click(function(){ formatText(iframe, 'left');return false; });
        jQuery('.vnc_rte_center', tb).click(function(){ formatText(iframe, 'center');return false; });
		jQuery('.vnc_rte_right', tb).click(function(){ formatText(iframe, 'right');return false; });
        jQuery('.vnc_rte_unorderedlist', tb).click(function(){ formatText(iframe, 'insertunorderedlist');return false; });
        jQuery('.vnc_rte_link', tb).click(function(){ 
            var p=prompt("URL:");
            if(p)
                formatText(iframe, 'CreateLink', p);
            return false; });
        jQuery('.vnc_rte_image', tb).click(function(){ 
            var p=prompt("Image URL:");
            if(p)
                formatText(iframe, 'InsertImage', p);
            return false; });
        jQuery('.vnc_rte_disable', tb).click(function(){ disableDesignMode(iframe); tb.remove(); return false; });
        jQuery(iframe).parents('form').submit(function(){ 
            disableDesignMode(iframe, true); });
        var iframeDoc = jQuery(iframe.contentWindow.document);
        
        var select = jQuery('select', tb)[0];
        iframeDoc.mouseup(function(){ setSelectedType(getSelectionElement(iframe), select);return true;});
        iframeDoc.keyup(function(){ setSelectedType(getSelectionElement(iframe), select);return true;});
        
        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;
    }

	function cleanUp(iframe){  //clean up crud inserted by Micro$oft Orifice
		iframe.contentWindow.document.execCommand("removeformat",false,null);
		var h=iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
		var vicious=false;
		if (gentleClean=="ask") vicious=confirm('Remove all styles and classes?');
		if (gentleClean===true || (vicious && gentleClean=="ask")){ 
			h=h.replace(/<\/?(SPAN|DEL|INS|U|DIR)[^>]*>/gi, "")
			.replace(/\b(CLASS|STYLE)=\"[^\"]*\"/gi, "")
			.replace(/\b(CLASS|STYLE)=\w+/gi, "");
		}
//		if(!o('fontname'+idTa) || !o('fontsize'+idTa)) h=h.replace(/<\?FONT[^>]*>/gi, "");
		h=h.replace(/<\/?(FONT|SPAN|COL|XML|ST1|SHAPE|V:|O:|F:|F |PATH|LOCK|IMAGEDATA|STROKE|FORMULAS)[^>]*>/gi, "")
		.replace(/\bCLASS=\"?MSO\w*\"?/gi, "")
		.replace(/[–]/g,'-') //long –
		.replace(/[‘’]/g, "'") //single smartquotes ‘’ 
		.replace(/[“”]/g, '"') //double smartquotes “”
		.replace(/align="?justify"?/gi, "") //justify sends some browsers mad
		.replace(/<(TABLE|TD|TH|COL)(.*)(WIDTH|HEIGHT)=["'0-9A-Z]*/gi, "<$1$2") //no fixed size tables (%OK) [^A-Za-z>]
		.replace(/<([^>]+)>\s*<\/\1>/gi, ""); //empty tag
		iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML=h;
	}

	function tidyD(h){ //FF designmode likes <B>,<I>...
		h=h.replace(/<(\/?)strong([^>]*)>/gi, "<$1B$2>"); 
		h=h.replace(/<(\/?)em([^>]*)>/gi, "<$1I$2>");
		return h;
	}

	function tidyH(h){ //...but <B>,<I> deprecated
		h=h.replace(/<(\w+)[^>]*>\s*<\/\1>/gi, ""); //empty tag <([^>]+)>\s*<\/\1>
		h=h.replace(/(<\/?)[Bb]>/g, "$1strong>");
		h=h.replace(/(<\/?)[Ii]>/g, "$1em>");
		h=h.replace(/(<\/?)[Bb](\s+[^>]*)>/g, "$1strong$2>");
		h=h.replace(/(<\/?)[Ii](\s+[^>]*)>/g, "$1em$2>");
		h=h.replace(location.href+'#','#'); //IE anchor bug
		return h;
	}

function get_xhtml(node,ndNl,inPre){
 var i; 
 var tx=''; 
 var kids=node.childNodes; 
 var kidsL=kids.length; 
 var tagNm; 
 var doNl=ndNl?true:false; 
 var sz=["small","xx-small","x_small","small","medium","large","x-large","xx-large"];
 for(i=0; i<kidsL; i++){
  var kid=kids[i]; 
  switch(kid.nodeType){
   case 1:{
    var tagNm=String(kid.tagName).toLowerCase(); 
    if(tagNm=='')break; 
    if(tagNm=='font') { 
     if (kid.size) {kid.style.fontSize=sz[kid.size]; kid.removeAttribute('size');} 
     if (kid.face) {kid.style.fontFamily=kid.face; kid.removeAttribute('face');}
     if (kid.color) {kid.style.color=kid.color; kid.removeAttribute('color');}
     tagNm='span'; 
     }
    if(tagNm=='!'){
     var bits=regCmt.exec(kid.tx); 
     if(bits){
      var innerTx=bits[1]; 
      tx+=tidyCmt(innerTx); 
     }
    }else{
     if(nlTag.indexOf('|'+tagNm+'|')!=-1){
      if((doNl||tx!='')&&!inPre)tx+='\n'; 
      else doNl=true; 
     }
     tx+='<'+tagNm; 
     var attr=kid.attributes; 
     var atLn=attr.length; 
     var atVal; 
     var atLang=false; 
     var atXml=false; 
     var atXmlns=false; 
     var isAlt=false; 
     for(j=0; j<atLn; j++){
      var atNm=attr[j].nodeName.toLowerCase(); 
      if(!attr[j].specified&&(atNm!='selected'||!kid.selected)
         && (atNm!='style'||kid.style.cssText=='')
         && atNm!='value')
       continue; 
      if(atNm=='_moz_dirty'||atNm=='_moz_resizing'||tagNm=='br'&&atNm=='type'&&kid.getAttribute('type')=='_moz')
       continue; 
      var valid_attr=true;
      switch(atNm){
       case "color":atNm="style"; 
        tVal="color:"+kid.color+";";
        if (window.atVal){atVal+=tVal ;}else{atVal=tVal;}
        break;
       case "style":atVal=kid.style.cssText.toLowerCase(); 
        break; 
       case "class":atVal=kid.className; 
        break; 
       case "noshade":
       case "checked":
       case "selected":
       case "multiple":
       case "nowrap":
       case "disabled":atVal=atNm;
        break; 
       default:try{
        atVal=kid.getAttribute(atNm,2); 
       }catch(e){ valid_attr=false; }
      }
      if(valid_attr){
       if(!(tagNm=='li'&&atNm=='value')){
        tx+=' '+atNm+'="'+tidyAt(atVal)+'"';  
       }
      }
      if(atNm=='alt')isAlt=true; 
     }
     if(tagNm=='img'&&!isAlt) tx+=' alt=""';
    if(kid.canHaveChildren||kid.hasChildNodes()){
     tx+='>'; 
     if(tagNl.indexOf('|'+tagNm+'|')!=-1){}
     tx+=get_xhtml(kid,true,inPre||tagNm=='pre'?true:false); 
     tx+='</'+tagNm+'>'; 
    }else{ 
     if(tagNm=='style'||tagNm=='title'||tagNm=='script'){
      tx+='>';  
      var innerTx; 
      if(tagNm=='script'){
       innerTx=kid.tx; 
      }else innerTx=kid.innerHTML; 
      if(tagNm=='style'){
       innerTx=String(innerTx).replace(/[\n]+/g,'\n'); 
      }
      tx+=innerTx+'</'+tagNm+'>'; 
     }else{ tx+=' />'; }
    }
   }
   break; 
  }
  case 3:{
   if(!inPre){
    if(kid.nodeValue!='\n'){ tx+=tidyTxt(kid.nodeValue); }
   }
   else tx+=kid.nodeValue; 
   break; 
  }
  case 8:{
   tx+=tidyCmt(kid.nodeValue); 
   break; 
  }
  default: break; 
  }
 }
 return tx; 
}
function tidyCmt(tx){
 tx=tx.replace(/--/g,"__"); 
 if(regHyph.exec(tx)){
  tx+=" "; 
 }return "<!--"+tx+"-->"; 
}
function tidyTxt(tx){
 return String(tx).replace(/\n{2,}/g,"\n").replace(/\&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\u00A0/g,"&nbsp;");
}
function tidyAt(tx){
 return String(tx).replace(/\&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
}
}
})(jQuery);

function vnc_init_editor() {
	if (!jquery_form_loaded) {
		jQuery.getScript('/zlib/jquery.form.js', function(){ jquery_form_loaded = true; } );
	}
	if (comm_editor==1) {
	  jQuery('#ta').vnc_rte();
	  comm_editor=0;
	} else {
	  comm_editor=1;
	}
	if(comment_url.indexOf('?')!==-1){
		a_comment_url=comment_url+'&random='+(new Date().getTime());
	}else{
		a_comment_url=comment_url+'?random='+(new Date().getTime());
	}
	jQuery('#switch_editor').click(function(){ jQuery('#comment_submit').load(a_comment_url, {html_editor: comm_editor}, vnc_init_editor); return false; });
	jQuery('#cancel_comment').click(function(){ jQuery('#comment_submit').html(''); return false; });
	jQuery('#v_preview').click(function(){ jQuery('form#editor').ajaxSubmit({data: {preview:1}, complete: function(r) { jQuery('#vnc_preview').html(r.responseText); }}); return false; });
}

function vnc_submit_comment_link () {
	jQuery('#submit_comment_link').click(function(){
		comment_url=this.href;
		if(comment_url.indexOf('?')!==-1){
			a_comment_url=comment_url+'&random='+(new Date().getTime());
		}else{
			a_comment_url=comment_url+'?random='+(new Date().getTime());
		}
		jQuery('#comment_submit').load(a_comment_url, {html_editor: comm_editor}, vnc_init_editor);
		return false;
	}); 	
}
