/**
 * 
 * 
 * @author tam
 */

var logger = LogFactory.getLog("main");

/**
 * Submit a link asynchronously; call to submitURL with _anchor.href.
 * 
 * @param _anchor
 * @param _update
 * @param _callbackFunction
 * @return
 */
function submitLink(_anchor, _update, _callbackFunction) {
	return submitURL(_anchor.href, _update, _callbackFunction);
}

/**
 * Submit a URL asynchronously and returns false if the submission was
 * successful.
 * 
 * @param _url
 * @param _update
 * @return
 */
function submitURL(_url, _update, _callbackFunction) {
	try {
		if (!_update) {
			// just discard the output? or follow the link?
		}
		if (typeof _update == 'string') {
			_update = new Array(_update);
		}

		logger.info("URL is: " + _url);
		var xrp = new XMLRPCProvider();
		xrp.onComplete = function(_responseText, _responseXML) {
			var d;
			/*
			 * if (typeof DOMParser != "undefined") { d = ((new
			 * DOMParser).parseFromString(_responseText, "application/xml"));
			 * for(var i = 0; i < _update.length; i++) { logger.info("Replacing
			 * element: " + _update[i]); var newContent =
			 * d.getElementById(_update[i]); if(newContent == null) {
			 * logger.warn("No new content element found for id: " +
			 * _update[i]); continue; } replaceElement(newContent, _update[i]); } }
			 * else {
			 */
			var target = document.createElement("div");
			target.innerHTML = _responseText;

			for ( var i = 0; i < _update.length; i++) {
				var newContent = getHTMLById(target, _update[i]);
				if (newContent == null) {
					logger.warn("No new content element found for id: "
							+ _update[i]);
					continue;
				}
				replaceElement(newContent, _update[i]);
			}
			/* } */
			runDojoLoads(target);
			// execute the callback function
			if (_callbackFunction) {
				_callbackFunction();
			}
		}
		xrp.get(_url);
		return false;
	} catch (e) {
		// if anything goes wrong, just follow the link as usual.
		return true;
	}
}

/**
 * Submits a form asynchronously.
 * 
 * @param _form
 * @param _update
 * @param _submitElement
 * @return
 */
function submitForm(_form, _update, _submitElement, _callbackFunction) {
	try {
		
		//_form.elements["updateParts"].value=_update;
		
		if (!_update) {
			// just discard the output? or follow the link?
		}
		if (typeof _update == 'string') {
			_update = new Array(_update);
		}

		logger.info("ACTION is: " + _form.action);
		

		var xrp = new XMLRPCPost();

		xrp.onComplete = function(_responseText, _responseXML) {

			var target = document.createElement("div");
			target.innerHTML = _responseText;
			for ( var i = 0; i < _update.length; i++) {
				var newContent = getHTMLById(target, _update[i]);
				if (newContent == null) {
					logger.warn("No new content element found for id: "
							+ _update[i]);
					continue;
				}
				replaceElement(newContent, _update[i]);
			}

			runDojoLoads(target);
						 
			
			if (_callbackFunction) {

				_callbackFunction();
			}
		}
		xrp.submit(_form, _submitElement);
		return false;
	} catch (e) {
		logger.warn("Error submitting form asyn: " + e.message);
		return true;
	}
}

/**
 * run the dojo on load functions
 */
function runDojoLoads(target)
{
	var newScripts = target.getElementsByTagName("script");
	if(newScripts.length > 0)
	{
		var newDojoHtml = newScripts[newScripts.length - 1];
		// remove html comment
		newDojoScript = newDojoHtml.innerHTML;
		newDojoScript = newDojoScript.replace(/<!--(.*)/g, "$1");
		newDojoScript = newDojoScript.replace(/(.*)\/\/ -->/g, "$1");
		eval(newDojoScript);
	}
}

/**
 * Utility function to replace an element in the HTML DOM tree.
 * 
 * @param _newElement
 * @param _elementId
 * @return
 */
function replaceElement(_newElement, _elementId) {
	var curContent = document.getElementById(_elementId);
	var par = curContent.parentNode;
	if (document.importNode) {
		_newElement = document.importNode(_newElement, true);
	}
	par.replaceChild(_newElement, curContent);
}

/**
 * Utility method to "lookup"
 * 
 * @param container
 * @param id
 * @return
 */
function getHTMLById(container, id) {
	logger.info("Id: " + id + " in container: " + container.nodeName
			+ " with id = " + container.id)
	for ( var i = 0; i < container.childNodes.length; i++) {
		var child = container.childNodes[i];
		if (child.nodeType == 1) {
			if (child.id == id) {
				logger.info("Found element");
				return child;
			}
			if (child.childNodes.length > 0) {
				var innerChild = getHTMLById(child, id);
				if (innerChild != null) {
					return innerChild;
				}
			}
		}
	}
	return null;
}

