// esoText javascript file
// Usage:
// var et = new esoText("elementIdToReplace");
// et.setContent("asdf");
// etc.

// p b i a[href] img[float] hr ul ol
// hdr = p class='cmsHdr'

var $ = function(id) {return document.getElementById(id);};

var ua = navigator.userAgent.toLowerCase();
var isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));

var esoTextEditors = [];

function esoText(id, contents, width, height) {
this.id = id;
this.width = width || "888px";
this.height = height || "400px";

esoTextEditors[id] = this;

this.controls = {
"removeformat": {name: "Remove formatting", icon: "remove.png", onoff: false},
"bold": {name: "Bold", icon: "b.png", onoff: true},
"italic": {name: "Italic", icon: "i.png", onoff: true},
"insertorderedlist": {name: "Ordered list", icon: "ol.png", onoff: true},
"insertunorderedlist": {name: "Unordered list", icon: "ul.png", onoff: true},
"superscript": {name: "Superscript", icon: "sup.png", onoff: true},
"subscript": {name: "Subscript", icon: "sub.png", onoff: true},
"inserthorizontalrule": {name: "Horizontal rule", icon: "hr.png", onoff: false},
"header": {name: "Header", icon: "h1.png", onoff: true},
"insertlink": {name: "Hyperlink", icon: "a.png", onoff: true},
"insertimage": {name: "Image", icon: "img.png", onoff: false}
};

html = "<div id='" + this.id + "_esoText' class='esoText'>\
<div class='bar'>\
<div class='controls' id='" + this.id + "_controls'>\
</div>\
</div>\
<div class='display'><iframe frameborder='0' id='" + this.id + "_rte' style='width:" + this.width + "; height:" + this.height + "; background:#fff'></iframe></div>\
<input type='hidden' name='" + this.id + "' id='" + this.id + "_hidden' value=''/></div>";

$(this.id).innerHTML = html;

imgDiv = document.createElement("div");
imgDiv.innerHTML = "<div id='" + this.id + "_image' class='esoTextImageBox' style='display:none; color:#000'><div style='font:20px arial,helvetica,sans-serif'>Insert an image</div>\
<form action='http://visacorp.aths.com.au/visacorp-0.0.0/esoText.upload-image.php' enctype='multipart/form-data' method='post' target='" + this.id + "_iframe'>\
<p><input type='file' name='image'/></p>\
<div class='clear'></div>\
<p style='float:left; margin-right:10px'>Align</p>\
<p style='float:left'><input type='radio' name='align' value='left' id='" + this.id + "_alignLeft'/> <label for='" + this.id + "_alignLeft' class='checkbox auto'>Left</label><br/>\
<input type='radio' name='align' value='right' id='" + this.id + "_alignRight'/> <label for='" + this.id + "_alignRight' class='checkbox auto'>Right</label><br/>\
<input type='radio' name='align' value='none' checked='checked' id='" + this.id + "_alignNone'/> <label for='" + this.id + "_alignNone' class='checkbox auto'>None</label></p>\
<input type='hidden' name='id' value='" + this.id + "'/>\
<p style='clear:both'><input type='submit' value='Insert' name='submit'/> <input type='button' value='Cancel' onclick='esoTextEditors[\"" + this.id + "\"].closeImage()'/></p>\
</form>\
<iframe name='" + this.id + "_iframe' style='display:none'></iframe></div>";

$("asdf").appendChild(imgDiv);

for (var i in this.controls) {
	a = document.createElement("a");
	a.href = "#";
	a.title = this.controls[i].name;
	a.innerHTML = "<img src='http://visacorp.aths.com.au/static.visacorp.com/0.0.0/esoText/" + this.controls[i].icon + "' alt='" + this.controls[i].name + "'/>";
	a.esoText = this;
	a.command = i;
	a.onclick = function onclick() {
		this.esoText.command(this.command);
		return false;
	};
	$(this.id + "_controls").appendChild(a);
	this.controls[i].element = a;
}

if ($(this.id + "_rte").contentWindow) this.rte = $(this.id + "_rte").contentWindow;	
else this.rte = window.frames[this.id + "_rte"];

// Write the initial HTML/content.	
  content  = "<html><head><style>";
	  content += "body {";
  content += "	margin:0px;"
  content += "	padding:3px;"
	content += "	background:#fff;"
  content += " 	font:13px verdana,arial,helvetica,sans-serif";
  content += "}";
	  content += "</style></head><body>" + contents;
  content += "</body></html>";

  // Write the content.
  
  this.rte.document.open();
	  this.rte.document.write(content);
	  this.rte.document.close();
	  
	  	  
	  // Turn on design mode
	  this.rte.document.designMode = "on";
	  
	  this.rte.document.esoText = this;

	  // Create event handlers to update the commands when the text cursor is moved.
	this.rte.document.onmouseup = this.rte.document.onkeyup = function()
	{
		this.esoText.update();
	};
	
	eventFunction = function()
        {
          this.esoText.update();
        };
        if (document.addEventListener) {
        this.rte.document.addEventListener("keyup", eventFunction, false);
        this.rte.document.addEventListener("mouseup", eventFunction, false);
	}
	this.rte.document.onkeypress = test = function(e) {
		if (!e) return true;
		if (e.keyCode == 13) {
			//alert('adsf')
			if (this.queryCommandValue("fontsize") == 4 || this.queryCommandValue("fontsize") == "20px")
				this.esoText.command("header"); 
		}
	}
	
	if (document.addEventListener) this.rte.document.addEventListener("keypress", test, false);
	
	this.rte.document.execCommand("fontsize", false, 2);
		


this.getContent = function() {
return this.rte.document.body.innerHTML;
}

this.update = function() {
for (var i in this.controls) {
	if (this.controls[i].onoff) {
		if (i == "header") {
			if (this.rte.document.queryCommandValue("fontsize") == 4 || parseFloat(this.rte.document.queryCommandValue("fontsize")) > 14)
				this.controls[i].element.className = "active";
			else	   		this.controls[i].element.className = "";
		} else if (i == "insertlink") {
			if (this.rte.document.queryCommandValue("forecolor") == "rgb(0, 0, 238)" || this.rte.document.queryCommandState("underline"))
				this.controls[i].element.className = "active";
			else this.controls[i].element.className = "";
		} else {
		if (this.rte.document.queryCommandState(i))
		this.controls[i].element.className = "active";
		else	  		this.controls[i].element.className = "";
		}
		
	}
}

};

this.command = function(command) {
this.rte.focus();
switch (command) {
	case "insertlink":
		if (this.rte.document.queryCommandValue("forecolor") == "rgb(0, 0, 238)" || this.rte.document.queryCommandState("underline"))
			this.rte.document.execCommand("unlink", false, false);
		else this.insertLink();
		break;
	case "insertimage": this.insertImage(); break;
	case "header":
		size = this.rte.document.queryCommandValue("fontsize") == 4 || parseFloat(this.rte.document.queryCommandValue("fontsize")) > 14 ? 2 : 4;
		this.rte.document.execCommand("fontsize", false, size);
		break;
	default: this.rte.document.execCommand(command, false, false);
}
this.rte.focus();
this.update();
}

this.insertLink = function()
  {
	// Get the selected text of the editor.
	selection = this.getSelection();
	  if (isIE) {
			linkText = selection.htmlText;
	  } else {
			linkText = selection.toString();
	  }
  
	if (linkURL = prompt("Enter the Link URL...", "http://")) {
	  // No text was selected to put the link on, so prompt the user.
	  if (!linkText) {
		linkText = prompt("Enter the Link Text...");
  		 }
  		 // Target
  		 if (confirm("Would you like this link to open in a new window when clicked on?"))
  		 this.insertHTML("<a href='" + linkURL + "' target='_blank'>" + linkText + "</a>");
  		 else this.insertHTML("<a href='" + linkURL + "'>" + linkText + "</a>");
  	}
  }
  this.insertImage = function()
  {
  if ($(this.id + "_image").style.display == "block") this.closeImage();
  else {
  	$(this.id + "_image").style.display = "block";
  	pos = this.findPos(this.controls.insertimage.element);
  	$(this.id + "_image").style.left = pos[0] + "px";
  	$(this.id + "_image").style.top = (pos[1] + 20) + "px";
  	this.controls.insertimage.element.className = "active";
	}	 
  }
  
  this.findPos = function(obj) {
	var curleft = curtop = 0;
		if (obj.offsetParent) {
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		}
	return [curleft,curtop];
}

  this.closeImage = function()
  {
  	$(this.id + "_image").style.display = "none";
  	this.controls.insertimage.element.className = ""; 
  }
  
  
 this.insertHTML = function(html)
  { 
	this.rte.focus();
	
	// IE makes things quite hard... :/
  	if (isIE) {
  		objRng = this.rte.document.selection.createRange();
  		objRng.pasteHTML(html);
  		objRng.collapse(false);
  		objRng.select();
  		
  	} else {
  		this.rte.document.execCommand("insertHTML", false, html);
  	}
  }
  
  this.getSelection = function()
  {
	  if (isIE) {
			selection = this.rte.document.selection;
			if (selection != null) {
		range = selection.createRange();
	  }
	  } else {
			selection = this.rte.getSelection();
			range	  = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
	  }
	  return range;
  }


}