var editorFontFamily = 'Verdana';
var editorFontSize = 12;


var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer") >= 0);
var xmlreq = initXmlReq();

var editingSection;
var editBuffer;
var editPosition;

var command = "";
var wasToolbarInit = false;
var setImg = false;
var isEditorShown = false;



function initXmlReq() {
	var req = false;
	//native XMLHttpRequest object
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} 
		catch(e) {
			req = false;
		}
	} 
	//IE/Windows ActiveX version
	else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch(e) {
				req = false;
			}
		}
    }
	return req;
}


function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}



function dataLocation(elemid) {
	return location.pathname + '&id=' + elemid;
}



function showImageUploader(elemid, position, isSetImg) {
	hideDocUploader();
	hideLinkInserter();
	var section = document.getElementById(elemid);
	var ed = document.getElementById('inline-editor-img');
	var xpos, ypos;
	if (isSetImg) {
		setImg = isSetImg;
		editingSection = elemid;
		selimg = document.getElementById(editingSection).src;
		selimg = selimg.substring(selimg.lastIndexOf('/')+1, selimg.length);
		document.getElementById('upload-img').contentWindow.document.getElementById('sel-image').value = selimg;
		document.getElementById('upload-img').contentWindow.document.getElementById('image-preview').src = 'content/thumbnails/'+selimg;
	}
	
	//SET POSITION
	if (position == 'right') {
		xpos = section.offsetLeft + section.offsetWidth -1;
		ypos = section.offsetTop - 10;
	}
	else if (position == 'bottom') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop + section.offsetHeight - 1;
	}
	else if (position == 'over') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop;
	}
	else {
		posAry = getScrollXY(); 
		xpos = posAry[0];
		ypos = posAry[1];
	}
	ed.style.left = xpos+'px';
	ed.style.top = (ypos+10)+'px';
	ed.style.visibility = 'visible';
	
	var drag = document.getElementById('inline-editor-img.drag');
	drag.style.left = (xpos) +'px';
	drag.style.top = (ypos) +'px';
	drag.style.visibility = 'visible';

	//INIT INTERFACE
	InitToolbarButtons();
	InitColorPalette();
	return false;
}

function showDocUploader(elemid, position) {
	hideImageUploader();
	hideLinkInserter();
	var section = document.getElementById(elemid);
	var ed = document.getElementById('inline-editor-doc');
	var xpos, ypos;
	
	//SET POSITION
	if (position == 'right') {
		xpos = section.offsetLeft + section.offsetWidth -1;
		ypos = section.offsetTop - 10;
	}
	else if (position == 'bottom') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop + section.offsetHeight - 1;
	}
	else if (position == 'over') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop;
	}
	else {
		posAry = getScrollXY(); 
		xpos = posAry[0];
		ypos = posAry[1];
	}
	ed.style.left = xpos+'px';
	ed.style.top = (ypos+10)+'px';
	ed.style.visibility = 'visible';
	
	var drag = document.getElementById('inline-editor-doc.drag');
	drag.style.left = (xpos) +'px';
	drag.style.top = (ypos) +'px';
	drag.style.visibility = 'visible';

	//INIT INTERFACE
	InitToolbarButtons();
	InitColorPalette();
	return false;
}


function showLinkInserter(elemid, position, page) {
	hideImageUploader();
	hideDocUploader();
	var section = document.getElementById(elemid);
	var ed = document.getElementById('inline-editor-link');
	var innerPage = document.getElementById('insert-link-frame');
	innerPage.src = page;
	var xpos, ypos;
	//SET POSITION
	if (position == 'right') {
		xpos = section.offsetLeft + section.offsetWidth -1;
		ypos = section.offsetTop - 10;
	}
	else if (position == 'bottom') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop + section.offsetHeight - 1;
	}
	else if (position == 'over') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop;
	}
	else {
		posAry = getScrollXY(); 
		xpos = posAry[0];
		ypos = posAry[1];
	}
	ed.style.left = xpos+'px';
	ed.style.top = (ypos+10)+'px';
	ed.style.visibility = 'visible';
	
	var drag = document.getElementById('inline-editor-link.drag');
	drag.style.left = (xpos) +'px';
	drag.style.top = (ypos) +'px';
	drag.style.visibility = 'visible';

	//INIT INTERFACE
	InitToolbarButtons();
	InitColorPalette();
	return false;
}


function hideImageUploader() {
	document.getElementById('inline-editor-img').style.visibility = 'hidden';
	document.getElementById('inline-editor-img.drag').style.visibility = 'hidden';
	return false;	
}


function hideDocUploader() {
	document.getElementById('inline-editor-doc').style.visibility = 'hidden';
	document.getElementById('inline-editor-doc.drag').style.visibility = 'hidden';
	return false;	
}


function hideLinkInserter() {
	document.getElementById('inline-editor-link').style.visibility = 'hidden';
	document.getElementById('inline-editor-link.drag').style.visibility = 'hidden';
	return false;	
}


function updateRevisionList() {
	//READ REVISION LIST
	xmlreq.open("POST", "/edit/revisions.php", false);
	xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlreq.send('file='+dataLocation(editingSection));
	try {
		var revisionValue = xmlreq.responseXML.documentElement;
		//SET REVISION LIST
		var versionSelect = document.getElementById('version-select');
		var children = revisionValue.getElementsByTagName('rev');
		for (i = versionSelect.length - 1; i >= 0; i--) {
			versionSelect.remove(i);
		}
		for (i = 0; i < children.length; i++) {
			var currChild = children.item(i);
			var currOpt = new Option(currChild.getAttribute('name'), currChild.getAttribute('value'));
			try {
				versionSelect.add(currOpt, null);
			}
			catch (e) {
				versionSelect.add(currOpt, -1);
			}
		}
		versionSelect.selectedIndex = 0;
	} catch (ex) {} 
}


function getMouseXY(e) {
	if (isIE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	}
	else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
	// catch possible negative values in NS4
	if (tempX < 0) tempX = 0;
	if (tempY < 0) tempY = 0;
	// show the position values in the form named Show
	// in the text fields named MouseX and MouseY
	return new Array(tempX, tempY);
}


function showEditor(elemid, position) {
	var section = document.getElementById(elemid);
	var edText = document.getElementById('edit-text');
	var editValue = '';
	var ed = document.getElementById('inline-editor');
	var xpos, ypos;
	
	isEditorShown = true;

	//READ DATA
	xmlreq.open("POST", "/edit/data.php", false);
	xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlreq.send('file='+dataLocation(elemid));
	editValue += xmlreq.responseText;

	//INIT INTERFACE
	InitToolbarButtons();
	InitColorPalette();

	//SET DATA
	var ddd = document.getElementById('edit-text').contentWindow.document;
	ddd.designMode = "on";
	if (isIE) {
		ddd = document.getElementById('edit-text').contentWindow.document;
		ddd.open();
		var oNewNode = ddd.createElement("body");
		oNewNode.innerHTML = editValue;
		ddd.appendChild(oNewNode);
	}
	else {
		var html = document.getElementById('edit-text').contentWindow.document.body.ownerDocument.createRange();
		html.selectNodeContents(document.getElementById('edit-text').contentWindow.document.body);
		document.getElementById('edit-text').contentWindow.document.body.innerHTML = editValue;
	}
	ddd.body.style.fontFamily = editorFontFamily;
	ddd.body.style.fontSize = editorFontSize;
	editingSection = elemid;
	editPosition = position;

	updateRevisionList();	
	
	//SET POSITION
	if (position == 'right') {
		xpos = section.offsetLeft + section.offsetWidth;
		ypos = section.offsetTop;
	}
	else if (position == 'bottom') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop + section.offsetHeight;
		if (isIE) {
			ypos += 14;	
		}
	}
	else if (position == 'over') {
		xpos = section.offsetLeft;
		ypos = section.offsetTop;
	}
	else {
		posAry = getScrollXY(); 
		xpos = posAry[0];
		ypos = posAry[1];
	}
	ed.style.left = xpos+'px';
	ed.style.top = (ypos+10)+'px';
	ed.style.visibility = 'visible';

	var drag = document.getElementById('inline-editor.drag');
	drag.style.left = (xpos) +'px';
	drag.style.top = (ypos) +'px';
	drag.style.visibility = 'visible';
		
	//SET MODE
	var viewsrc = document.getElementById('checkbox_viewsrc');
	var vis = 'visible';
	if (viewsrc.checked) {
		vis = 'hidden'
	}
	document.getElementById("toolbar1").style.visibility = vis;
	document.getElementById("toolbar2").style.visibility = vis;  
	document.getElementById("toolbar3").style.visibility = vis;  
	
	setInterval("refreshEditor();", 300);
	return false;
}


function refreshEditor() {
	//if (!isEditorShown) return;
	if (!isIE || !isEditorShown) return;
	document.getElementById('edit-text').contentWindow.document.body.style.display = 'inline';
	document.getElementById('edit-text').contentWindow.document.body.style.display = 'block';
}


function hideEditor() {
	isEditorShown = false;
	editBuffer = document.getElementById('edit-text').contentWindow.document.body.innerHTML;
	document.getElementById('checkbox_viewsrc').checked = false;
	if (isIE) {
		var ddd = document.getElementById('edit-text').contentWindow.document;
		ddd.close();
		ddd.designMode = "off";
	}
	document.getElementById('inline-editor').style.visibility = 'hidden';
	document.getElementById('inline-editor.drag').style.visibility = 'hidden';
	document.getElementById("toolbar1").style.visibility = 'hidden';
	document.getElementById("toolbar2").style.visibility = 'hidden';  
	document.getElementById("toolbar3").style.visibility = 'hidden';  
	return false;
}


function previewChanges() {
	var ed = document.getElementById('inline-editor');
	var xpos, ypos;
	var section;
	section = document.getElementById(editingSection);
	section.innerHTML = 
		"<a class='osweb-link' id='"+editingSection+"-editR' href='#' onclick='return showEditor(\""+editingSection+"\");' >edit&#187;</a>"
		+getEditingHTML()
		+"<a class='osweb-link' id='"+editingSection+"-edit' href='#' onclick='return showEditor(\""+editingSection+"\");' >&#171;edit</a>"
}


function saveChanges() {
	var data = getEditingHTML();
	xmlreq.open("POST", "/edit/save.php", true);
	xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlreq.send(
		'file='+dataLocation(editingSection)
		+'&data='+escape(data)
	);
	previewChanges();
	setTimeout('updateRevisionList();', 1000);
}


function InitToolbarButtons() {
	var kids = document.getElementsByTagName('div');
	for (var i=0; i < kids.length; i++) {
		if (kids[i].className == "imagebutton") {
			kids[i].onmouseover = tbmouseover;
			kids[i].onmouseout = tbmouseout;
			kids[i].onmousedown = tbmousedown;
			kids[i].onmouseup = tbmouseup;
			kids[i].onclick = tbclick;
		}
	}
}


function tbmousedown(e) {
	try {
		this.style.border="inset 2px";
	}
	catch (ex) {}
}


function tbmouseup() {
	this.style.border="outset 2px";
}


function tbmouseout() {
	this.style.border="solid 2px #FFFFFF";
}


function tbmouseover() {
	this.style.border="outset 2px";
}


function insertNodeAtSelection(win, insertNode) {
	// get current selection
	var sel = win.getSelection();
	// get the first range of the selection
	// (there's almost always only one range)
	var range = sel.getRangeAt(0);
	// deselect everything
	sel.removeAllRanges();
	// remove content of current selection from document
	range.deleteContents();
	// get location of current selection
	var container = range.startContainer;
	var pos = range.startOffset;
	// make a new range for the new selection
	range = document.createRange();
	if (container.nodeType==3 && insertNode.nodeType==3) {
		// if we insert text in a textnode, do optimized insertion
		container.insertData(pos, insertNode.nodeValue);
		// put cursor after inserted text
		range.setEnd(container, pos+insertNode.length);
		range.setStart(container, pos+insertNode.length);
	}
	else {
		var afterNode;
		if (container.nodeType==3) {
			// when inserting into a textnode
			// we create 2 new textnodes
			// and put the insertNode in between
			var textNode = container;
			container = textNode.parentNode;
			var text = textNode.nodeValue;
			// text before the split
			var textBefore = text.substr(0,pos);
			// text after the split
			var textAfter = text.substr(pos);
			var beforeNode = document.createTextNode(textBefore);
			afterNode = document.createTextNode(textAfter);
			// insert the 3 new nodes before the old one
			container.insertBefore(afterNode, textNode);
			container.insertBefore(insertNode, afterNode);
			container.insertBefore(beforeNode, insertNode);
			// remove the old node
			container.removeChild(textNode);
		}
		else {
			// else simply insert the node
			afterNode = container.childNodes[pos];
			container.insertBefore(insertNode, afterNode);
		}
		range.setEnd(afterNode, 0);
		range.setStart(afterNode, 0);
	}
	sel.addRange(range);
}


function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	while (mOffsetParent){
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetTop;
}


function getOffsetLeft(elm) {
	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	while (mOffsetParent) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetLeft;
}


function paletteMenuOut() {
	document.onclick = hidePaletteMenu;
}


function hidePaletteMenu() {
	document.onclick = null;
	var palette = document.getElementById("colorpalette");
	palette.style.visibility = 'hidden';
}



function imageAddress(imgpath) {
	if (isIE) return imgpath;
	else return window.location.protocol +"//"+ window.location.host + imgpath;
}


function openImage(selImg) {
	window.open('/edit/viewimage.php?img=' + selImg + '&w=' + window.screen.availWidth + '&h=' + window.screen.availHeight, 
		'_blank', 
		'width=300,height=300,menubar=no,toolbar=no,resizable=yes,status=no,scrollbars=yes'
	);
	return false;
}



function tbclick() {
	if ((this.id == "forecolor") || (this.id == "hilitecolor")) {
		command = this.id;
		var palette = document.getElementById("colorpalette");
		buttonElement = document.getElementById(this.id);
		palette.style.left = "0px";
		palette.style.top = "0px";
		var paletteLabel = document.getElementById("palette-label");
		if (this.id == "forecolor") {
			paletteLabel.innerHTML = 'Font color';
		}
		else {
			paletteLabel.innerHTML = 'Highlight color';
		}
		palette.style.visibility = "visible";
		palette.onmouseout = paletteMenuOut;
	}
	else if (this.id == "create-article-link") {
		showLinkInserter('inline-editor', 'right', '/edit/insertlink.php?type=create-article-link');
	}
	else if (this.id == "createlink") {
		showLinkInserter('inline-editor', 'right', '/edit/insertlink.php?type=createlink');
	}
	else if (this.id == "create-email") {
		showLinkInserter('inline-editor', 'right', '/edit/insertlink.php?type=create-email');
	}
	else if (this.id == "create-anchor-link") {
		showLinkInserter('inline-editor', 'right', '/edit/insertlink.php?type=create-anchor-link');
	}
	else if (this.id == "create-anchor") {
		showLinkInserter('inline-editor', 'right', '/edit/insertlink.php?type=create-anchor');
	}
	else if (this.id == "uploadimage") {
		showImageUploader('inline-editor', 'right');
	}
	else if (this.id == "create-doc") {
		showDocUploader('inline-editor', 'right');
	}
	else if (this.id == "createimage") {
		imagePath = prompt('Enter Image URL:', 'http://');
		if ((imagePath != null) && (imagePath != "")) {
			document.getElementById('edit-text').contentWindow.document.execCommand('InsertImage', false, imagePath);
		}
	}
	else if (this.id == "insert-img") {
		imageName = document.getElementById('upload-img').contentWindow.document.getElementById('sel-image').value;
		imagePath = window.location.protocol +"//"+ window.location.host + '/edit/content/thumbnails/'+imageName;
		floatType = document.getElementById('upload-img').contentWindow.document.getElementById('sel-float').value;
		selSize =  document.getElementById('upload-img').contentWindow.document.getElementById('sel-size').value;
		if (selSize == 'full') {
			imagePath = window.location.protocol +"//"+ window.location.host + '/edit/content/images/'+imageName;
		}
		if (setImg) {//BEGIN SET IMG
			document.getElementById(editingSection).src = imagePath;
			document.getElementById(editingSection+"-IMAGE").value = imagePath;
		}//END SET IMG
		else {//BEGIN INSERT IMG
			if (isIE) {
				if (selSize == 'linked') {
					newhtml = "<a href='#' onclick=\"return openImage('"+imageName+"');\">"
						+"<img src='"+imagePath+"' style='"+floatType+"; border:none;'/></a>";
				}
				else {
					newhtml = "<img src='"+imagePath+"' style='"+floatType+"; border:none;'/>";
				}
				insertHTML(newhtml);
			}
			else {
				e = document.getElementById("edit-text");
				if (selSize == 'linked') {
					linkElem = e.contentWindow.document.createElement("a");
					linkElem.setAttribute("href", "#");
					linkElem.setAttribute("onclick", "return openImage('"+imageName+"');");

					elem = e.contentWindow.document.createElement("img");
					elem.setAttribute("src", imagePath);
					elem.setAttribute("style", floatType+";	border:none;");
				
					linkElem.appendChild(elem);
					insertNodeAtSelection(e.contentWindow, linkElem);
				}
				else {
					elem = e.contentWindow.document.createElement("img");
					elem.setAttribute("src", imagePath);
					elem.setAttribute("style", floatType+";	border:none;");
					insertNodeAtSelection(e.contentWindow, elem);
				}
			}
		}//END INSERT IMG
	}
	else if (this.id == "insert-doc") {
		docName = document.getElementById('upload-doc').contentWindow.document.getElementById('sel-doc').value;
		docPath = window.location.protocol +"//"+ window.location.host + '/edit/content/docs/'+docName;
		if (isIE) {
			var rng = document.getElementById('edit-text').contentWindow.document.selection.createRange();
			link_text = rng.htmlText;
			if (link_text.length == 0) {
				window.alert('Please select a text range.');
				return;
			}
			newhtml = "<a href='"+docPath+"' target='_blank' >"+link_text+"</a>";
			insertHTML(newhtml);
		}
		else {
			e = document.getElementById("edit-text");
			linkElem = e.contentWindow.document.createElement("a");
			linkElem.setAttribute("href", docPath);
			linkElem.setAttribute("target", "_blank");
			var sel = e.contentWindow.getSelection();
			var range = sel.getRangeAt(0);
			link_text = range.toString();
			if (link_text == "") {
				window.alert('Please select a text range.');
				return;
			}	
			linkElem.appendChild(document.createTextNode(link_text));
			insertNodeAtSelection(e.contentWindow, linkElem);
		}
	}
	else if (this.id == "createtable") {
		e = document.getElementById("edit-text");
		rowstext = prompt("enter rows");
		colstext = prompt("enter cols");
		rows = parseInt(rowstext);
		cols = parseInt(colstext);
		if ((rows > 0) && (cols > 0)) {
			table = e.contentWindow.document.createElement("table");
			table.setAttribute("border", "1");
			table.setAttribute("cellpadding", "2");
			table.setAttribute("cellspacing", "0");
			tbody = e.contentWindow.document.createElement("tbody");
			for (var i=0; i < rows; i++) {
				tr =e.contentWindow.document.createElement("tr");
				for (var j=0; j < cols; j++) {
					td =e.contentWindow.document.createElement("td");
					br =e.contentWindow.document.createElement("br");
					td.appendChild(br);
					tr.appendChild(td);
				}
				tbody.appendChild(tr);
			}
			table.appendChild(tbody);      
			insertNodeAtSelection(e.contentWindow, table);
		}
	}
	else if (this.id == "preview") {
		previewChanges();
	}
	else if (this.id == "save") {
		saveChanges();
	}
	else if (this.id == "close") {
		hideEditor();
	}
	else if (this.id == "close-img") {
		hideImageUploader();
	}
	else if (this.id == "close-doc") {
		hideDocUploader();
	}
	else if (this.id == "close-link") {
		hideLinkInserter();
	}
	else if (this.id == "insert-link") {
		lnk_doc = document.getElementById('insert-link-frame').contentWindow.document;
		link_address = lnk_doc.getElementById('link-address').value;
		link_target = lnk_doc.getElementById('link-target').value;
		lnk_type = lnk_doc.getElementById('link-type').value;
		
		if (isIE) {
			var rng = document.getElementById('edit-text').contentWindow.document.selection.createRange();
			link_text = rng.htmlText;
			if (link_text.length == 0) {
				window.alert('Please select a text range.');
				return;
			}
			if (lnk_type == 'link') {
				newhtml = "<a href='"+link_address+"' target='"+link_target+"'>"+link_text+"</a>";
			}
			else if (lnk_type == 'email') {
				newhtml = "<a href='mailto:"+link_address+"'>"+link_text+"</a>";
			}
			else if (lnk_type == 'anchor-link') {
				newhtml = "<a href='#"+link_address+"' style='text-decoration: underline;'>"+link_text+"</a>";
			}
			else if (lnk_type == 'anchor') {
				newhtml = "<a name='"+link_address+"'>"+link_text+"</a>";
			}
			else if (lnk_type == 'article') {
				newhtml = "<a href='"+window.location.protocol +"//"+ window.location.host
					+"/edit/article.php?"+escape(link_address)+"'>"+link_text+"</a>";
			}
			insertHTML(newhtml);
		}
		else {
			e = document.getElementById("edit-text");
			var sel = e.contentWindow.getSelection();
			var range = sel.getRangeAt(0);
			link_text = range.toString();
			if (link_text == "") {
				window.alert('Please select a text range.');
				return;
			}	
			linkElem = e.contentWindow.document.createElement("a");
			if (lnk_type == 'link') {
				linkElem.setAttribute("href", link_address);
				linkElem.setAttribute("target", link_target);
			}
			else if (lnk_type == 'email') {
				linkElem.setAttribute("href", "mailto:"+link_address);
			}
			else if (lnk_type == 'anchor-link') {
				linkElem.setAttribute("href", "#"+link_address);
				linkElem.setAttribute("style", "text-decoration: underline;");
			}
			else if (lnk_type == 'anchor') {
				linkElem.setAttribute("name", link_address);
			}
			else if (lnk_type == 'article') {
				linkElem.setAttribute("href", window.location.protocol +"//"+ window.location.host+"/edit/article.php?"+link_address);
			}
			linkElem.appendChild(document.createTextNode(link_text));
			insertNodeAtSelection(e.contentWindow, linkElem);
		}
	}
	else {
		document.getElementById('edit-text').contentWindow.document.execCommand(this.id, false, null);
	}
}


function insertHTML(newhtml) {
	document.getElementById('edit-text').focus();
	var key = "OSWEB-REPLACE-KEY";
	var rng = document.getElementById('edit-text').contentWindow.document.selection.createRange();
	rng.text = key;
	var pos;
	var html = document.getElementById('edit-text').contentWindow.document.body.innerHTML;
	if ((pos = html.indexOf(key)) != -1) {
		document.getElementById('edit-text').contentWindow.document.body.innerHTML = html.substring(0, pos) + newhtml + html.substring(pos + key.length);
	}
	else document.getElementById('edit-text').contentWindow.document.body.innerHTML += newhtml;
	document.getElementById('edit-text').contentWindow.document.selection.empty();
}


function Select(selectname) {
	var cursel = document.getElementById(selectname).selectedIndex;
	/* First one is always a label */
	if (cursel != 0) {
		var selected = document.getElementById(selectname).options[cursel].value;
		document.getElementById('edit-text').contentWindow.document.execCommand(selectname, false, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}


function loadVersion() {
	document.getElementById('checkbox_viewsrc').checked = false;
	document.getElementById("toolbar1").style.visibility = 'visible';
	document.getElementById("toolbar2").style.visibility = 'visible';
	document.getElementById("toolbar3").style.visibility = 'visible';  
	var versionSelect = document.getElementById('version-select');
	var selectedVersion = '';
	if (versionSelect.selectedIndex > 0) {
		selectedVersion = versionSelect.options[versionSelect.selectedIndex].value;
	}
	//READ DATA
	xmlreq.open("POST", "/edit/data.php", false);
	xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlreq.send('file=' + dataLocation(editingSection) + '&ver=' + selectedVersion);
	var editValue = xmlreq.responseText;

	//SET DATA
	var ddd = document.getElementById('edit-text').contentWindow.document;
	ddd.designMode = "on";
	if (isIE) {
		ddd = document.getElementById('edit-text').contentWindow.document;
		ddd.open();
		var oNewNode = ddd.createElement("body");
		oNewNode.innerHTML = editValue;
		ddd.appendChild(oNewNode);
	}
	else {
		ddd.body.innerHTML = editValue;
	}
}



function viewsource(source) {
	var html;
	var vis;
	if (source) {
		vis = "hidden";
		if (isIE) {
			html = document.getElementById('edit-text').contentWindow.document.body.innerHTML;
			document.getElementById('edit-text').contentWindow.document.body.innerText = html;
		}
		else {
			html = document.createTextNode(document.getElementById('edit-text').contentWindow.document.body.innerHTML);
			document.getElementById('edit-text').contentWindow.document.body.innerHTML = "";
			html = document.getElementById('edit-text').contentWindow.document.importNode(html,false);
			document.getElementById('edit-text').contentWindow.document.body.appendChild(html);
		}
	}
	else {
		vis = "visible";
		if (isIE) {
			html = document.getElementById('edit-text').contentWindow.document.body.innerText;
			document.getElementById('edit-text').contentWindow.document.body.innerHTML = html;			
		}
		else {
			html = document.getElementById('edit-text').contentWindow.document.body.ownerDocument.createRange();
			html.selectNodeContents(document.getElementById('edit-text').contentWindow.document.body);
			document.getElementById('edit-text').contentWindow.document.body.innerHTML = html.toString();
		}
	}
	document.getElementById("toolbar1").style.visibility = vis;
	document.getElementById("toolbar2").style.visibility = vis;  
	document.getElementById("toolbar3").style.visibility = vis;  
}


function getEditingHTML() {
	var editElem = document.getElementById('edit-text');
	if (document.getElementById('checkbox_viewsrc').checked) {
		if (isIE) {
			return editElem.contentWindow.document.body.innerText;
		}
		else {
			html = editElem.contentWindow.document.body.ownerDocument.createRange();
			html.selectNodeContents(editElem.contentWindow.document.body);
			return html.toString();
		}
	}
	else {
		return editElem.contentWindow.document.body.innerHTML;
	}
}



//COLOR PALETTE
function InitColorPalette() {
	var kids = document.getElementsByTagName('TD');
	for (var i=0; i < kids.length; i++) {
		if (kids[i].className == "coloritem") {
			kids[i].onmouseover = colorOver;
			kids[i].onmouseout = colorOut;
			kids[i].onmousedown = colorClick;
		}
	}
}

function colorOver() {
	this.style.border='1px solid #FFF';
}

function colorOut() {
	this.style.border='1px solid #000';
}

function colorClick() {
	if (isIE) {
		if (command == 'hilitecolor') command = 'BackColor';
	}
	document.getElementById("edit-text").contentWindow.document.execCommand(command, false, this.id);
	document.getElementById("colorpalette").style.visibility = "hidden";
	document.onclick = null;
}




var nn6 = !isIE;
var isdrag=false;
var x,y;
var dobj;
var dobj2;

function movemouse(e) {
	if (isdrag) {
		var xpos = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
		var ypos = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
		dobj.style.left = (xpos) + 'px';
		dobj.style.top  = (ypos) + 'px';
		dobj2.style.left = (xpos) + 'px';
		dobj2.style.top  = (ypos+10) + 'px';
		return false;
	}
}

function selectmouse(e) {
	try {
	var fobj       = nn6 ? e.target : event.srcElement;
	var topelement = nn6 ? "HTML" : "BODY";
	while (fobj.tagName != topelement && fobj.className != "dragme") {
		fobj = nn6 ? fobj.parentNode : fobj.parentElement;
	}
	if (fobj.className=="dragme") {
		isdrag = true;
		dobj = fobj;
		var alsoMove = dobj.id.split(".");
		dobj2 = document.getElementById(alsoMove[0]);
		tx = parseInt(dobj.style.left+0,10);
		ty = parseInt(dobj.style.top+0,10);
		x = nn6 ? e.clientX : event.clientX;
		y = nn6 ? e.clientY : event.clientY;
		document.onmousemove=movemouse;
		return false;
	}
	}
	catch (ex) {
	}
}

function deselectmouse(e) {
	isdrag = false;
	dobj = null;
	dobj2 = null;
}

document.onmousedown = selectmouse;
document.onmouseup = deselectmouse;



function showLogoutLink() {
	try {
	var logoutElem = document.getElementById('logout');	
	if (logoutElem == null) return;
	logoutElem.style.left = (document.body.clientWidth - logoutElem.offsetWidth) + "px";
	logoutElem.style.top = '0px';
	logoutElem.style.visibility = 'visible';
	var modeElem = document.getElementById('edit-mode');	
	if (modeElem == null) return;
	modeElem.style.left = (document.body.clientWidth - modeElem.offsetWidth - logoutElem.offsetWidth - 2) + "px";
	modeElem.style.top = '0px';
	modeElem.style.visibility = 'visible';
	} catch (ex) {}
}


