// Cross-Browser Rich Text Editor  v2.0
// http://www.kevinroth.com/rte/demo.htm
// Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM)

//init variables
var ROOTURL = '/cocoon/joanlingard/';
var isRichText = false;
var rng;
var currentRTE;
var currentEditBox;
var currentImageEditBoxName;

function initRTE() {
	//check to see if designMode mode is available
	if (document.getElementById) {
		if (document.all) {
			//check for internet explorer 5.5+
			if (document.URLUnencoded) isRichText = true;
		} else {
			//check for browsers that support designmode
			if (document.designMode) isRichText = true;
		}
	}
}

function writeRichText(rte, html, width, height, buttons, rootURL) {
	if (isRichText) {
		writeRTE(rte, html, width, height, buttons, rootURL);
	} else {
		writeDefault(rte, html, width, height, buttons);
	}
}

function writeDefault(rte, html, width, height, buttons) {
	document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>');
}


function enableDesignMode(rte, html) {
	//enable designmode
	var updateHTML = "document.getElementById('" + rte + "').contentWindow.document.body.innerHTML = '" + html + "';";
	
	if (document.all) {
		frames[rte].document.designMode = "On";
		setTimeout(updateHTML, 250);
	}
	else {
		setTimeout(updateHTML + "document.getElementById('" + rte + "').contentDocument.designMode = 'On';", 1000);
		//attach a keyboard handler for Mozilla to make keyboard shortcuts for formatting text work
		document.getElementById(rte).contentWindow.document.addEventListener("keypress", kb_handler, true);
	}
}

function updateRTE(rte) {

	//set message value
	var oHdnMessage = document.getElementById('hdn' + rte);
	var oMessageFrame = document.getElementById(rte);
	
	if (isRichText) {
		if (oHdnMessage.value == null) oHdnMessage.value = "";
		oHdnMessage.value = oMessageFrame.contentWindow.document.body.innerHTML;
		//exception for Mozilla
		if (oHdnMessage.value.indexOf('<br>') > -1 && oHdnMessage.value.length == 8) oHdnMessage.value = "";
	}
}

// Sets the View HTML source 
function setViewHTMLSource(rte, value) {
       
	//Added - Alan Cloughley 19/12/2003 
        if (!(document.getElementById("chkSrc" + rte).checked == value))
        {
            document.getElementById("chkSrc" + rte).checked = value;        
            toggleHTMLSrc(rte);
            
        }
}


function toggleHTMLSrc(rte) {
	//contributed by Bob Hutzel (thanks Bob!)
	var doc = document.getElementById(rte).contentWindow.document;
	
	if (document.getElementById("chkSrc" + rte).checked) {
	
		document.getElementById("Buttons1_" + rte).style.visibility = "hidden";
		document.getElementById("Buttons2_" + rte).style.visibility = "hidden";
		if (document.all) {
			doc.body.innerText = doc.body.innerHTML;
		} else {
			var htmlSrc = doc.createTextNode(doc.body.innerHTML);
			doc.body.innerHTML = "";
			doc.body.appendChild(htmlSrc);
		}

	} else {
		document.getElementById("Buttons1_" + rte).style.visibility = "visible";
		document.getElementById("Buttons2_" + rte).style.visibility = "visible";
		if (document.all) {
			doc.body.innerHTML = doc.body.innerText;
		} else {
			var htmlSrc = doc.body.ownerDocument.createRange();
			htmlSrc.selectNodeContents(doc.body);
			doc.body.innerHTML = htmlSrc.toString();
		}
	}
}

//Function to format text in the text box
function FormatText(rte, command, option) {
	if ((command == "forecolor") || (command == "hilitecolor")) {
		parent.command = command;
		buttonElement = document.getElementById(command + rte);
		document.getElementById('cp' + rte).style.left = getOffsetLeft(buttonElement) + "px";
		document.getElementById('cp' + rte).style.top = (getOffsetTop(buttonElement) + buttonElement.offsetHeight) + "px";
		if (document.getElementById('cp' + rte).style.visibility == "hidden")
			document.getElementById('cp' + rte).style.visibility="visible";
		else {
			document.getElementById('cp' + rte).style.visibility="hidden";
		}
		
		//get current selected rte
		currentRTE = rte;
		
		//get current selected range
		var sel = document.getElementById(rte).contentWindow.document.selection; 
		if (sel!=null) {
			rng = sel.createRange();
		}
	}
	else if (command == "createlink") { // && browser.isIE55up == false
		var szURL = prompt("Enter a URL:", "");
		document.getElementById(rte).contentWindow.document.execCommand("Unlink",false,null)
		document.getElementById(rte).contentWindow.document.execCommand("CreateLink",false,szURL)
	}
	else {
		document.getElementById(rte).contentWindow.focus();
	  	document.getElementById(rte).contentWindow.document.execCommand(command, false, option);
		document.getElementById(rte).contentWindow.focus();
	}
}

//Function to set color
function setColor(color) {
	var parentCommand = parent.command;
	var rte = currentRTE;
	
	if (document.all) {
		//retrieve selected range
		var sel = document.getElementById(rte).contentWindow.document.selection; 
		if (parentCommand == "hilitecolor") parentCommand = "backcolor";
		if (sel!=null) {
			var newRng = sel.createRange();
			newRng = rng;
			newRng.select();
		}
	}
	else {
		document.getElementById(rte).contentWindow.focus();
	}
	document.getElementById(rte).contentWindow.document.execCommand(parentCommand, false, color);
	document.getElementById(rte).contentWindow.focus();
	document.getElementById('cp' + rte).style.visibility="hidden";
}

//Function to add image
function AddImage(rte) {
	imagePath = prompt('Enter Image URL:', 'http://');				
	if ((imagePath != null) && (imagePath != "")) {
		document.getElementById(rte).contentWindow.focus()
		document.getElementById(rte).contentWindow.document.execCommand('InsertImage', false, imagePath);
	}
	document.getElementById(rte).contentWindow.focus()
}

//function to perform spell check
function checkspell() {
	try {
		var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
		tmpis.CheckAllLinkedDocuments(document);
	}
	catch(exception) {
		if(exception.number==-2146827859) {
			if (confirm("ieSpell not detected.  Click Ok to go to download page."))
				window.open("http://www.iespell.com/download.php","DownLoad");
		}
		else
			alert("Error Loading ieSpell: Exception " + exception.number);
	}
}

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 Select(rte, selectname, commandname)
{
	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(rte).contentWindow.document.execCommand(commandname, false, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
	document.getElementById(rte).contentWindow.focus();
}

function kb_handler(evt, rte) {
	//contributed by Anti Veeranna (thanks Anti!)
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			evt.target.ownerDocument.execCommand(cmd,false,true);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}


//functions to support form image browser
function showImageBrowser(editBoxName, siteId, sectionId, folderId) {
        // Set the global current text box for updating image filename
        currentImageEditBoxName = editBoxName;
        folderIdInputBox = document.getElementById('/folderId');
        folderBrowserUrl = '/cocoon/joanlingard/browseimages/' + siteId + '/' + sectionId + '/' + folderId + '/';
        window.open(folderBrowserUrl, 'imagebrowserwindow', 'width=600,height=600,resizable=1,scrollbars=1'); 
        return true;
}

function returnImageId(imageId) {
    imageIdDisplay = document.getElementById(currentImageEditBoxName + 'display');
    imageIdInputBox = document.getElementById(currentImageEditBoxName);
    imageIdInputBox.value=imageId;
    imageIdDisplay.src=ROOTURL + "getimage/" + imageId + "/100/0";
}

function showFolderBrowser(siteId, sectionId, folderId) {

        // Set the global current text box for updating image filename
        //currentEditBox = document.getElementById('folder');
        folderIdInputBox = document.getElementById('/folderId');
        folderBrowserUrl = '/cocoon/joanlingard/browsefolder/' + siteId + '/' + sectionId + '/' + folderId + '/';
        window.open(folderBrowserUrl, 'folderbrowserwindow', 'width=450,height=550,resizable=1,scrollbars=1'); 
        return true;
}

function selectFolder(folderId, folderName) {
    /* copy hidden text and name */
    folderIdInputBox = document.getElementById('/folderId');
    folderInputBox = document.getElementById('/folder');
    folderIdInputBox.value=folderId;
    folderInputBox.value=folderName;

}

function showStructureBrowser(siteId, sectionId, folderId) {

        // Set the global current text box for updating image filename
        structureBrowserUrl = '/cocoon/joanlingard/browsestructure/' + siteId + '/' + sectionId + '/' + folderId + '/';
        window.open(structureBrowserUrl, 'folderbrowserwindow', 'width=450,height=550,resizeable'); 
        return true;
}

function selectStructureFolder(folderId, folderName) {
    
    /* get hidden and visible input boxes */
    hiddenFolderIdInputBox = document.getElementById('/folderid');
    hiddenSiteIdInputBox = document.getElementById('/siteid');
    hiddenSectionIdInputBox = document.getElementById('/sectionid');
    structureInputBox = document.getElementById('/structure');

    /* set values for all 4 boxes */
    hiddenFolderIdInputBox.value = folderId;
    hiddenSiteIdInputBox.value = '0';
    hiddenSectionIdInputBox.value = '0';
    structureInputBox.value = folderName;

}
  
function selectStructureSite(siteValue, siteName)
{
    
    /* get hidden and visible input boxes */
    hiddenFolderIdInputBox = document.getElementById('/folderid');
    hiddenSiteIdInputBox = document.getElementById('/siteid');
    hiddenSectionIdInputBox = document.getElementById('/sectionid');
    structureInputBox = document.getElementById('/structure');

    /* set values for all 4 boxes */
    hiddenFolderIdInputBox.value = '0';
    hiddenSiteIdInputBox.value = siteValue;
    hiddenSectionIdInputBox.value = '0';
    structureInputBox.value = siteName;

} 

function selectStructureSiteSection(siteSectionValue, siteAndSection)
{
    
    /* get hidden and visible input boxes */
    hiddenFolderIdInputBox = document.getElementById('/folderid');
    hiddenSiteIdInputBox = document.getElementById('/siteid');
    hiddenSectionIdInputBox = document.getElementById('/sectionid');
    structureInputBox = document.getElementById('/structure');

    /* set values for all 4 boxes */
    hiddenFolderIdInputBox.value = '0';
    hiddenSiteIdInputBox.value = '0';
    hiddenSectionIdInputBox.value = siteSectionValue;
    structureInputBox.value = siteAndSection;

} 

initRTE();
