var hx_ed_current = null;
var hx_ed_currentElement = null;
var hx_original_html = "";
var hx_current_document = null;
var hx_current_iframe = null;
var hx_ed_toolbar = null;
var hx_propWO = null;
var hx_stop_com = "<div class=\"hl_stop\" style=\"background-color:gray;width:100%;height:2px;overflow:hidden;\"></div>";

 var hx_ed_pFTitle = new xgMenu();
 hx_ed_pFTitle.add("<h1>Big Title</h1>","h1");
 hx_ed_pFTitle.add("<h2>Medium Title</h2>","h2");
 hx_ed_pFTitle.add("<b>Small Title</b>","bold");

hx_ed_pFTitle.onclick = function(key){
    var text = hx_ed_getSelectedRange();

    if (text.length == 0) text = "Your title";
    if (key == "h1"){
         hx_ed_executeCommand("formatBlock","<H1>");
    }else
    if (key == "h2"){
         hx_ed_executeCommand("formatBlock","<H2>");
    }else
    if (key == "bold"){
         hx_ed_executeCommand("removeFormat",null);
         hx_ed_executeCommand("bold",null);
    }
}


var hx_ed_pFont = new xgMenu();
hx_ed_pFont.add("<font face='Lucida Grande'>Lucida Grande</font>","Lucida Grande");
hx_ed_pFont.add("<font face='Arial'>Arial</font>","Arial");
hx_ed_pFont.add("<span style='font-family:Heeloo'>Heeloo</span>","Heeloo");
hx_ed_pFont.add("<font face='Georgia'>Georgia</font>","Georgia");
hx_ed_pFont.add("<font face='Tahoma'>Tahoma</font>","Tahoma");
hx_ed_pFont.add("<font face='Verdana'>Verdana</font>","Verdana");
hx_ed_pFont.add("<font face='Helvetica'>Helvetica</font>","Helvetica");


function hx_installToolbar(objid,small){
    var full = 0;
	if (typeof(small) == "undefined"){
		small = false;
		full = 3;
	}else
	if (typeof(small) == "boolean"){
	    full = 1;
	}else{
	    full = 2;
	}

	var obj = xg.obj(objid);
	//if (!small)
	if (full != 1) {
	    obj.style.backgroundImage = "url('http://imgs.heeloo.net/icons/edit/toolbar.bg.gif')";
	}
	obj.style.padding = "2px";
	var _toolbars = new Array("x_font","x_title","_sep","bold","italic","underline","StrikeThrough","_sep","SuperScript","SubScript",
			"_sep","x_hr","x_stop",
			"_sep","align_left","align_center","align_right","align_justify",
			"_sep","indent_more","indent_less",
			"_sep","InsertUnorderedList","InsertOrderedList",
			"_sep","x_clear",
			"_sep","x_link","x_html",
			"_sep","x_image","x_movie","x_doc","x_music"
	);
	if (full == 1){
		_toolbars = new Array("bold","italic","underline","StrikeThrough");
	}else
	if (full == 2){
	    _toolbars = new Array("bold","italic","underline","StrikeThrough","_sep","align_left","align_center","align_right","align_justify","_sep","x_image","x_movie","x_doc","x_music");
	}

	var _html = "<table border='0' cellspacing='0' cellpadding='0' width='100%'><tr><td align='center' valign='middle'><table border='0' cellspacing='0'><tr><td>";
	for (var i=0;i<_toolbars.length ;i++){
			var src = _toolbars[i]+".gif";

			var tb = _toolbars[i];
			if (tb == "italic") src = "italic_x.png";
			if (tb == "underline") src = "underline_x.png";
			if (tb == "StrikeThrough") src = "strike_x.png";
			if (tb == "SuperScript") src = "SuperScript_x.png";
			if (tb == "SubScript") src = "SubScript_x.png";
			if (tb == "InsertOrderedList") src = "numbers_x.png";
			if (tb == "InsertUnorderedList") src = "points_x.png";
			if (tb == "align_left") src="align_left_x.png";
			if (tb == "align_right") src = "align_right_x.png";
			if (tb == "align_center") src = "align_center_x.png";
			if (tb == "align_justify") src = "align_justify_x.png";
			if (tb == "indent_more") src="indent_more_x.png";
            if (tb == "indent_less") src="indent_less_x.png";

			if (_toolbars[i] == "bold") src = "bold_x.png";
			if (_toolbars[i] == "x_movie") src = "video_x.png";
			if (_toolbars[i] == "x_music") src = "mp3_x.png";
			if (_toolbars[i] == "x_doc") src = "doc_x.png";
			if (_toolbars[i] == "x_image") src = "image_x.png";
		    if (_toolbars[i] == "x_link") src="link_x.png";
			if (_toolbars[i] == "x_title") src="fontsize_x.png";
			if (_toolbars[i] == "x_hr") src="hr.png";
			if (_toolbars[i] == "x_stop") src="stop.png";
			if (_toolbars[i] == "x_clear") src = "clear.png";
			if (_toolbars[i] == "x_html") src = "html_x.png";

			var _tb ="";
			if (_toolbars[i]=="_sep") {
			    _tb = "<img style='' src='http://imgs.heeloo.net/icons/edit/toolbar.end.gif' border='0' height='14px'/>";
			    _html +="<div style='margin:2px;padding:2px;float:left;'>"+_tb+"</div>";
			}else
			if (tb == "x_font"){
			     _html += "<div style='float:left;margin:2px;padding:2px;margin-top:1px;margin-right:3px;background-color:rgba(255,255,255,0.1);font-family:Tahoma;font-size:11px;' onmouseup='hx_ed_mup(this,&quot;"+_toolbars[i]+"&quot;);' >FONT</div>";
			}
			else{
			    _tb = "<img src='http://imgs.heeloo.net/icons/edit/ed_"+src+"' height='12px'/>";
			    _html += "<div class='_ttclass' style='margin:2px;padding:2px;float:left;margin-right:3px;border-radius:0px;' onmouseup='hx_ed_mup(this,&quot;"+_toolbars[i]+"&quot;);' onmouseover='hx_ed_mover(this)' "+
                "onmouseout='hx_ed_mout(this)' onmousedown='hx_ed_click(this,&quot;"+_toolbars[i]+"&quot;);return false;' "+
                "onclick='return false;';onfocus = 'return false' title='"+hx_ed_getTitle(_toolbars[i])+"'>"+_tb+"</div>";
			}
	}
    _html +="</td></tr></table></td></tr></table>";
	obj.innerHTML = _html;
	//obj.style.width = "100%";
	obj.style.height = "22px";
    hx_ed_toolbar = obj;
	xg.installToolTips("div","_ttclass");
}
function hx_ed_getTitle(t){
	if (t == "x_movie") t = "Insert movie";
	if (t == "x_music") t = "Insert music";
	if (t == "x_doc") t = "Insert documents";
	if (t == "x_image") t = "Insert pictures";
	if (t == "x_link") t="Insert Link URLs";
	if (t == "x_h1") t="Title <H1>";
	if (t == "x_h2") t="Subtitle <H2> ";
	if (t == "x_hr") t="Horizontal line";
	if (t == "x_stop") t="%stop%";
	if (t == "x_clear") t = "Clean formating";
	if (t == "x_html") t = "Insert HTML";
	return t;
}
function hx_ed_mover(obj){
	obj.style.backgroundColor = "rgba(255,255,255,0.5)";
	obj.style.boxShadow = "inset 0px 0px 10px rgba(0,0,0,0.3)";
	xg.showToolTip(obj,"Some cool stuff");
}

function hx_ed_mout(obj){
	obj.style.backgroundColor = "transparent";
	obj.style.boxShadow = "";
}


function hx_ed_mup(obj,command){
    obj.style.marginTop = "2px";
    var x = xg.util.getLeft(obj)-18;
    var y = xg.util.getTop(obj)+32;
    if (command == "x_title"){
            hx_ed_pFTitle.show(x,y);
            hx_ed_pFTitle.popup.setOrientation(2);
            return;
    }else
    if (command == "x_font"){
        hx_ed_pFont.show(x,y);
        hx_ed_pFont.popup.setOrientation(2);
    }
}


hx_ed_pFont.onclick = function(key){
    var text = hx_ed_getSelectedRange();
    hx_ed_executeCommand("fontName",key);
}


function hx_ed_click(obj,command){
	obj.style.marginTop="3px";

    if (command == "x_title" || command == "x_font"){
        return;
    }

	if (command.startsWith("align_")) command = "Justify"+command.substring(6).firstUpperCase();
	if (command == "indent_more") command = "Indent";
	if (command == "indent_less") command = "Outdent";



	if (command.startsWith("x_")){
		hx_ed_execute(command);
	}else{
		if(hx_ed_currentElement != null){
			if (command == "JustifyLeft"){
                    hx_ed_currentElement.contentEditable = true;
					hx_ed_currentElement.style.float = "left";
		        	hx_ed_currentElement.align="left";
                    hx_current_iframe.contentWindow.reposPH();
			}else
				if (command == "JustifyRight"){
					hx_ed_currentElement.style.float = "right";
                    hx_ed_currentElement.align = "right";
                    hx_current_iframe.contentWindow.reposPH();

                }

		}else{
			hx_current_document.execCommand(command,false,null);
		}
	}
}

function hx_ed_getHTML(){
    var html = "";
    hx_ed_save();
	return hx_current_document.body.innerHTML;
}

function hx_ed_addHTML(){
	var obj = xg.obj("hx_ed_ta_html");
	var text = obj.value;
	hx_ed_pasteHTML(text);
}

function hx_ed_addLink(){
	var text = xg.obj("hx_ed_link_text").value;
	var url = xg.obj("hx_ed_link_url").value;
	var html = "&nbsp;<a href='"+url+"' target='_blank'>"+text+"</a>&nbsp;";
	hx_ed_pasteHTML(html);
}

function hx_ed_execute(cmd){
	if (cmd == "x_clear"){
	    hx_ed_executeCommand("removeFormat",null);
    		var mytext = hx_ed_getSelectedRange();
		if (mytext.length == 0) return;
		 var stripped = mytext.replace(/(<([^>]+)>)/ig,"");
		 hx_ed_pasteHTML(stripped);
	}else
	if (cmd == "x_stop"){
            hx_ed_pasteHTML("%stop%");
		//hx_ed_pasteHTML(hx_stop_com);
	}else
	if (cmd == "x_hr"){
		hx_ed_pasteHTML("<hr/>");
	}else
	if (cmd == "x_html"){
		var dlg_html = new xgDialog(myServer+"/xg/add_html.html",400,370);
		dlg_html.skin = "black";
		dlg_html.create(null);
		dlg_html.show();
		dlg_html.onclose = function(){ dlg_html.destroy()}
	}else
	if (cmd == "x_link"){
		var text = hx_ed_getSelectedRange();
		var dlg_link = new xgDialog(myServer+"/xg/add_link.html?text="+text,400,200);
		dlg_link.skin = "black";
		dlg_link.create(null);
		dlg_link.show();
		dlg_link.onclose = function(){
			dlg_link.destroy();
		}
	}else
	if (cmd == "x_image"){
		var dlg_show_pictures = new xgDialog(myServer+"/apps/procs/dialogfiles.html?type=gallery&token="+GenerateID(),500,450);
		dlg_show_pictures.skin="black";
		dlg_show_pictures.create(null);
		dlg_show_pictures.show();
		dlg_show_pictures.onclose = function(res){

		if (res != null && res.length > 0){
			var _width = 450;
			var imgURL = res[3];
			var th = "<img  src='"+imgURL+"'   border='0'/>";
			hx_ed_pasteHTML(th);
			}
		this.destroy();
	}
	}else
	if (cmd == "x_movie"){
		var dlg_show_movies = new xgDialog(myServer+"/apps/procs/dialogfiles.html?type=movie&token="+GenerateID(),500,450);
		dlg_show_movies.skin="black";
		dlg_show_movies.create(null);
		dlg_show_movies.show();
		dlg_show_movies.onclose = function(res){
		if (res != null && res.length > 0){
			var _width = 450;
			var imgURL = res[0];
			var th = "<div class='movie_placeholder' src='"+res[2]+"' style='background-image:url("+res[2]+");background-repeat:no-repeat;background-position:center center'>$apps.movie(id="+imgURL+")</div>&nbsp;";
			hx_ed_pasteHTML(th);
			}
		this.destroy();
	}
	}else
		if (cmd == "x_music"){
		var dlg_show_music = new xgDialog(myServer+"/apps/procs/dialogfiles.html?type=music&token="+GenerateID(),500,450);
		dlg_show_music.skin="black";
		dlg_show_music.create(null);
		dlg_show_music.show();
		dlg_show_music.onclose = function(res){
		if (res != null && res.length > 0){
			var _width = 450;
			var imgURL = res[0];
         	var th = "<div class='music_placeholder' src='"+res[2]+"' CONTENTEDITABLE=false style='background-repeat:no-repeat;background-position:center center'>$apps.music(id="+imgURL+")</div>&nbsp;";
			hx_ed_pasteHTML(th);
			}
		this.destroy();
	}

	}else
		if (cmd == "x_doc")	{
			var dlg_show_music = new xgDialog(myServer+"/apps/procs/dialogfiles.html?type=docs&token="+GenerateID(),500,450);
		dlg_show_music.skin="black";
		dlg_show_music.create(null);
		dlg_show_music.show();
		dlg_show_music.onclose = function(res){
		if (res != null && res.length > 0){
			var _width = 450;
			var imgURL = res[0];
			var th = "<div class='docs_placeholder' src='http://filetypes.heeloo.net/"+res[2]+"' ><img src='http://filetypes.heeloo.net/"+res[2]+"'/><div><a href='"+res[3]+"' target='_self'>"+res[1]+"</a></div></div>&nbsp;";
			hx_ed_pasteHTML(th);
			}
		this.destroy();
	}

		}



}

function hx_ed_executeCommand(command,value){
    hx_current_document.execCommand(command,false,value);
}

function hx_ed_pasteHTML(html){
	var doc = hx_current_document;
 if (doc.selection){
	 doc.parentWindow.focus();
	 var range = doc.selection.createRange();
	range.select();
	range.pasteHTML(html);
  }else{
	doc.execCommand('insertHTML', false, html);
  }
	try{
	doc.parentWindow.focus();
	doc.focus();
	}catch(E){}
}

hx_ed_getSelectedRange = function(){
	var doc = hx_current_document;
	if (xg.browser.sName == "ie"){
		var trange = doc.selection.createRange();
		return trange.htmlText;
	}else{
		var selection = hx_current_iframe.contentWindow.getSelection();
		var range = selection.getRangeAt(0);
		return range.toString();
	}
}

function hx_ed_save(){
   hx_current_iframe.contentWindow.removePH();
}

function hx_putOriginalHTML(frmid){
var _frm = xg.obj(frmid);
	var doc = _frm.contentWindow.document;
	var html = hx_original_html;
	//html = replaceStr(html,"%stop%",hx_stop_com);
	doc.body.innerHTML = html;
	hx_current_document = doc;
	hx_current_iframe = _frm;
    //_frm.contentWindow.window.createPH();
	try{
		doc.body.focus();
	}catch(e){}

	if (xg.browser.sName == "ie") hx_current_document.body.attachEvent( "onpaste", hx_onpasteE);

	hx_current_document.onpaste = function(evt){
		hx_onpasteE(evt);
		return false;
	}
}


function hx_onpasteE(evt){
		if (typeof(event) != "undefined") evt = event;
		var mytext = "";

		if (evt.clipboardData){
			mytext = evt.clipboardData.getData("text/html");
		}else
			if (window.clipboardData){
				mytext = window.clipboardData.getData("text/html");
			}
	//	xg.setValue("_txt20",mytext);
		mytext = hx_regHTML(mytext);
		hx_ed_pasteHTML(mytext);
		return false;
}

function hx_regHTML(html){

    return hl_cleanupHTML(html);

	 // start by completely removing all unwanted tags
	 var regs = new Array();

	regs[0] = new RegExp(/<[/]?(font|span|script|xml|del|center|left|right|ins|[ovwxp]:\w+)[^>]*?>/g);
	regs[1] = new RegExp(/<([a-z][a-z0-9]*)\b (?:(?:class|lang|id|style|size|face|align)\s*=\s*(?:'[^<']*'|""[^<""]*""|[^\s<>]+)\s+)+.*?>/ig);
	regs[2] = new RegExp(/<!--[^\[](.*?)-->/g);
	regs[3] = new RegExp(/<[^\/>]*>([\s]?)*<\/[^>]*>/g);
	regs[4] = new RegExp(/<([a-z][a-z0-9]*)\b (?:(?:class|lang|id|style|size|face|align)\s*=\s*(?:'[^<']*'|""[^<""]*""|[^\s<>]+)\s+)+.*?>/ig);

	var c = "";
	for (var i=0;i<regs.length ;i++){
		var reg = regs[i];
		if (i == 1) c = "<$1>";
		if (i == 4) c = "<$1>";
		html = html.replace(reg, c);
	}
	html = replaceStr(html,"\r","");
	html = replaceStr(html,"&nbsp;"," ");
	html = replaceStr(html,"\n\r","<br/>");
	html = replaceStr(html,"\r\n","<br/>");
	html = replaceStr(html,"<p> </p>","");
	return html;
}

function hx_installEdit(objid,editable){
    if (typeof(editable) == "undefined") editable = true;

	var obj = xg.obj(objid);
    obj.className = "xedit_htmlarea";
	obj.style.overflow = "auto";

    var _iframe = "<iframe id=\"hx_frm_"+objid+"\" onselectstart=\"return false;\" unselectable onload=\"hx_putOriginalHTML('hx_frm_"+objid+"')\" src=\""+myServer+"/xg/xg-editarea.htm?token="+GenerateID+"\" width=\"100%\" height=\"100%\" frameborder=\"0\" allowtransparency=\"true\"></iframe>";

    if (!editable) _iframe = "<iframe id=\"hx_frm_"+objid+"\" onselectstart=\"return false;\" unselectable onload=\"hx_putOriginalHTML('hx_frm_"+objid+"')\" src=\""+myServer+"/xg/xg-editarea-ne.htm?token="+GenerateID+"\" width=\"100%\" height=\"100%\" frameborder=\"0\" allowtransparency=\"true\"></iframe>";

    var html = obj.innerHTML;
    var txt = xg.obj("txta_"+objid);
    if (txt != null) html = xg.getValue(txt.id);
	hx_original_html = html;;
	obj.innerHTML = _iframe;

	var _lastSpace = 0;

}

function hx_getRange(obj){
if (xg.browser.sName == "ie"){
		var trange = obj.selection.createRange();
		return trange.htmlText;
	}else{
		var selection = hx_current_document.getSelection();
		var range = selection.getRangeAt(0);
		return range.toString();
	}

	return null;
}

function hx_ed_showWOProps(target){
    var type = "";
    if (target.tagName == "IMG") type = "IMG";
    var left = 0;
    var top = 0;
    left = xg.util.getLeft(hx_current_iframe)+hx_current_iframe.offsetWidth-150;
    top = xg.util.getTop(hx_current_iframe);

    var dlg = new xgDialog(myServer+"/apps/procs/webobject.props.html?type="+type,250,300,left,top);
    dlg.skin="blackpopup";
    dlg.create(null,true);
    dlg.show();
    hx_propWO = dlg;
    dlg.onclose = function(){
        this.destroy();
    }
}

function hx_ed_hideWOProps(){
    if (hx_propWO != null){
       try{hx_propWO.destroy()}catch(e){}
        hx_propWO = null;
    }
}

var  hl_cleanupHTML =  function(content) {
        // We have a TON of cleanup to do. Line breaks are already stripped.

        // Protect pre|script tags
        content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
            a = a.replace(/<br ?\/?>[\r\n]*/g, '<wp_temp>');
            return a.replace(/<\/?p( [^>]*)?>[\r\n]*/g, '<wp_temp>');
        });

        // Pretty it up for the source editor
        var blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tr|th|td|div|h[1-6]|p';
        content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'mg'), '</$1>\n');
        content = content.replace(new RegExp('\\s*<(('+blocklist1+')[^>]*)>', 'mg'), '\n<$1>');

        // Mark </p> if it has any attributes.
        content = content.replace(new RegExp('(<p [^>]+>.*?)</p>', 'mg'), '$1</p#>');

        // Sepatate <div> containing <p>
        content = content.replace(new RegExp('<div([^>]*)>\\s*<p>', 'mgi'), '<div$1>\n\n');

        // Remove <p> and <br />
        content = content.replace(new RegExp('\\s*<p>', 'mgi'), '');
        content = content.replace(new RegExp('\\s*</p>\\s*', 'mgi'), '\n\n');
        content = content.replace(new RegExp('\\n\\s*\\n', 'mgi'), '\n\n');
        content = content.replace(new RegExp('\\s*<br ?/?>\\s*', 'gi'), '\n');

        // Fix some block element newline issues
        content = content.replace(new RegExp('\\s*<div', 'mg'), '\n<div');
        content = content.replace(new RegExp('</div>\\s*', 'mg'), '</div>\n');

        var blocklist2 = 'blockquote|ul|ol|li|table|thead|tr|th|td|h[1-6]|pre';
        content = content.replace(new RegExp('\\s*<(('+blocklist2+') ?[^>]*)\\s*>', 'mg'), '\n<$1>');
        content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'mg'), '</$1>\n');
        content = content.replace(new RegExp('<li([^>]*)>', 'g'), '\t<li$1>');

        if ( content.indexOf('<object') != -1 ) {
            content = content.replace(new RegExp('\\s*<param([^>]*)>\\s*', 'mg'), "<param$1>");
            content = content.replace(new RegExp('\\s*</embed>\\s*', 'mg'), '</embed>');
        }

        // Unmark special paragraph closing tags
        content = content.replace(new RegExp('</p#>', 'g'), '</p>\n');
        content = content.replace(new RegExp('\\s*(<p [^>]+>.*</p>)', 'mg'), '\n$1');

        // Trim whitespace
        content = content.replace(new RegExp('^\\s*', ''), '');
        content = content.replace(new RegExp('\\s*$', ''), '');

        // put back the line breaks in pre|script
        content = content.replace(/<wp_temp>/g, '\n');

        // Hope.
        return content;
    }

