/**
* the commonUtils object
*/
var commonUtils = {};

commonUtils.processing=null;
/**
* update the div value
*/
commonUtils.updateDiv = function(id, value){
	var divById = document.getElementById(id);
	divById.innerHTML = value;
}

/**
* send a form request via Ajax
*/
commonUtils.submitAjaxForm = function(divId, formId) {
	var frm = document.getElementById(formId);
	var params = "";
	for (var i = 0; i < frm.length; i++) {
		params += frm.elements[i].name;
		params += "=";
		params += escape(frm.elements[i].value);
		params += "&";
	} 
	commonUtils.sendAjaxReq(frm.action, divId, params);
}

/**
* send e ajax request with parameters
*/
commonUtils.sendAjaxReq = function(url, divId, params) {
	
	// instantiate the XML Http Request    
    var xmlhr = null;  
	try {
		// Firefox, Opera 8.0+, Safari
          xmlhr=new XMLHttpRequest();
		  xmlhr.overrideMimeType('text/xml; charset=iso-8859-1');
    } catch (e) {
		// Internet Explorer
		try {
			xmlhr=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlhr=new ActiveXObject("Microsoft.XMLHTTP");
		}
    }      
        
	xmlhr.open('POST', url , true);
	xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1'); 
	xmlhr.onreadystatechange = function() {
		if (xmlhr.readyState == 1) {
			if (divId) {
				commonUtils.updateDiv(divId, "<img src='/img/loading.gif' width='16'/>");
			}
		} else if (xmlhr.readyState == 4 && xmlhr.status == 200) {
			if (xmlhr.responseText) {
			if (divId) {
				commonUtils.updateDiv(divId, xmlhr.responseText);
				parseScript(xmlhr.responseText);
			}
			else eval(xmlhr.responseText);
			}
			commonUtils.processing=null;
		} else if (xmlhr.readyState == 4) {
 			alert('Invalid response received - Status: ' + xmlhr.status);
			commonUtils.processing=null;
		}
	}
	commonUtils.processing=url;
  	xmlhr.send(params);
}

function parseScript(_source)
{
		var source = _source;
		var scripts = new Array();
 
		// Strip out tags
		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);
 
			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}
 
		// Loop through every script collected and eval it
		for(var i=0; i<scripts.length; i++) {
			try {
				eval(scripts[i]);
			}
			catch(ex) {
				alert(ex);
				// do what you want here when a script fails
			}
		}
		// Return the cleaned source
		return source;
}