
/** 
* Copyright 2005 Giampaolo Bellavite (giampaolo@bellavite.com)
* @version     1.0, 2005-09-04
 */
 
 
// Initialize the onClick event for span nodes having the ow:formajax attribute.
function ow_formAjaxInit(){
	var spanNodes = document.getElementsByTagName("span");
	ow_formAjax_status = 0; // There is no cfajax call in course (global var)

	for (var i=0;i<spanNodes.length;i++) {
		if (spanNodes[i].getAttribute("ow:formajax")) {
			spanNodes[i].onclick = function (evt) {
				ow_toInput(this);
			}
		}
	}
}

// Create the input field for editing the text
function ow_toInput(spanEl) {
	if (!ow_formAjax_status) {
	spanEl.onclick = null;
	//var tmp = +spanEl.innerHTML.replace(/"/g,"&quot;")+;
	spanEl.innerHTML = '<textarea cols="80" rows="5" name="ow_input" onBlur="ow_fromInput(this)">'+spanEl.innerHTML.replace(/"/g,"&quot;")+'</textarea><input type="button" value="Salva" />';
	spanEl.childNodes[0].select();
	DWREngine.setPreHook(function() { ow_waitFor(spanEl.childNodes[0]) });
	DWREngine.setPostHook(function() { ow_done(spanEl.childNodes[0]) }); }
}

// Catched from the onBlur event on the input field, calls the coldfusion function via cfajax
function ow_fromInput(inputEl) {
	var spanEl = inputEl.parentNode;
	var arguments = spanEl.getAttribute("ow:formajax").split(',');
	var method = arguments[0];
	var argumentList = "'" + ow_escape(inputEl.value) + "', ";
	for (var i = 1;i<arguments.length;i++) {
		argumentList += "'" + arguments[i] + "', ";
	}
	eval("DWREngine._execute(_cfscriptLocation, null, '" + method + "', " + argumentList + "ow_retFunction)");
}

// Fictional function called after cfajax has been executed
function ow_retFunction () {
	return true;
}

// Disable the input field while cfajax is executing
function ow_waitFor(inputNode) {
	ow_formAjax_status = 1; // There is a cfajax call in course
	inputNode.disabled=true;
}

// Escape disturbing javascript characters 

function ow_escape(s) {
		s = s.replace(/\'/g,"\\'");
		s = s.replace(/"/g,"&quot;");
		return s;
}

// Re-enable the input field after cfajax has been executed
function ow_done(inputNode) {
	ow_formAjax_status = 0; // There are no more cfajax calls in course
	var spanNode = inputNode.parentNode;
	inputNode.disabled=false;
	spanNode.innerHTML = inputNode.value;
	// restore the old event
	spanNode.onclick = function (evt) {
		ow_toInput(this);
	}
}

// This code comes from:
// http://www.sitepoint.com/blog-post-view.php?id=171578
// but thanks to Massimo Foti for letting me know it :)

function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != "function"){
		window.onload = func;
	} 
	else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}

addLoadEvent(ow_formAjaxInit);
