/*******************************************************************************
* Author: Justin Barlow - www.netlobo.com
* Project Netlobo Ajax v1.1
* the ajaxUpdate( ) function tries to make AJAX operations easier by performing
* many common AJAX related operations in one place. The function will request
* the data from the given "url" and inject it into the html element with the
* given "elemid" using the element's innerHTML method. This function is most
* useful when the requested "url" returns html formatted text or plain text. The
* "url" does not have to return XML.
* 
* The "options" parameter is an anonymous object which includes the following
* available options:
* 
* params:     Parameters for the requested url in the format p1=1&p2=0&p3=2
* meth:       The request method. Can be "get" or "post". Default is "post".
* async:      Toggles asynchronous mode. Default is true.
* startfunc:  A function or list of functions to be called before the AJAX
*             request is made. A list of functions must be separated by the
*             semi-colon like this: "showLoad(); animateText(); hideDiv('bob')".
*             You can pass parameters into the functions.
* endfunc:    A function or list of functions to be called after a successful
*             AJAX request. Uses the same format as "startfunc".
* errorfunc:  A function or list of functions to be called when the AJAX request
*             is unsuccessful. Uses the same format as "startfunc".
* noauthfunc: A function or list of functions to be called when the AJAX request
*             is not authenticated (http status code 403 is encountered). Uses
*             the same format as "startfunc".
* 
* Returns true on success and false on failure.
* 
* Example Usage:
* 
	ajaxUpdate( "rightdiv", "getData.jsp", {
		params:"id=12&AJAX=true",
		meth:"post",
		async:true,
		startfunc:"elemOn('loading')",
		endfunc:"elemOff('loading'); elemOn('rightdiv')",
		errorfunc:"ajaxError()",
		noauthfunc:"ajaxNoAuth()" }
	);
* 
*******************************************************************************/
function ajaxUpdate( elemid, url, options ){
	var params = options.params || "";
	var meth = options.meth || "post";
	var async = options.async;
	if( async == null )
		async = true;
	var startfunc = options.startfunc || "";
	var endfunc = options.endfunc || "";
	var errorfunc = options.errorfunc || "";
	var noauthfunc = options.noauthfunc || "";
	var req = false;
	if( window.XMLHttpRequest )
		req = new XMLHttpRequest();
	else if( window.ActiveXObject )
		req = new ActiveXObject( "Microsoft.XMLHTTP" );
	else
	{
		/*
		 alert(  "Your browser cannot perform the requested action. "+
				"Either your security settings are too high or your "+
				"browser is outdated. Try the newest version of "+
				"Internet Explorer or Mozilla Firefox." );
		*/
		return false;
	}
	if( startfunc != "" )
		eval( startfunc );
	req.onreadystatechange =
		function()
		{
			if ( req.readyState == 4 ) 
			{
				if ( req.status == 200 )
				{
					if( elemid != '' )
						document.getElementById(elemid).innerHTML = req.responseText;
					if( endfunc != "" )
						eval( endfunc );
					return true;
				}
				else
				{
					if( req.status == 403 && noauthfunc != "" )
						eval( noauthfunc );
					else
					{
						if( endfunc != "" )
							eval( endfunc );
						if( errorfunc != "" )
							eval( errorfunc );
					}
					return false;
				}
			}
		};

	if(meth == "get"){
		req.open( meth, url+( params != "" ? "?"+params : "" ), async );
		req.send(null);
	} else {
		req.open(meth, url, async);
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		req.send(params);
	}
}



function fnLoading(id){
	try{
		document.getElementById(id).style.visibility = 'visible';
		document.getElementById(id).style.display = 'block';
		document.getElementById(id).innerHTML = '<img src="./img/ajax-loader.gif" id="ajaxloader">';
	}catch(err){
		// Do nothing
	}
}


// Make a GET-string of POST-Vars
function fnBuildParams(id){

	var strResult = "";
	var oForm = document.getElementById(id);
	var allTheInputsInTheForm = oForm.getElementsByTagName('INPUT'); 
	var allTheTextAreaInTheForm = oForm.getElementsByTagName('TEXTAREA'); 

    // loop through all input tags and build string
	for (var i=0; i < allTheInputsInTheForm.length; i++){
		var field = allTheInputsInTheForm[i];
		strResult = strResult + '&' + field.name + '=' + encodeMyHtml(field.value);
	}

	// loop thru textfields aswell
	for (var i=0; i < allTheTextAreaInTheForm.length; i++){
		var field = allTheTextAreaInTheForm[i];
		strResult = strResult + '&' + field.name + '=' + encodeMyHtml(field.value);
	}
	
	
	// Add Hartassar around everything
	strResult = strResult;
	strResult = "\"" + strResult;
	return strResult;
}



function encodeMyHtml(strValue){
	encodedHtml = escape(strValue);
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	return encodedHtml;
}

// NOTE: This function  !!!! REQUIRES !!! breakrows in parameters!!!!
function fnSubmit(idForm,idResults,page){
	// Build parameters
	param = fnBuildParams(idForm);

	// Send an Ajax-request
	result = ajaxUpdate(idResults,page, {
		params:param,
		startfunc:"fnLoading('" + idResults + "')"
		}
	);

	// Reset form
	if (result == 'Ditt mail är skickat!' || result == 'Ditt tips är skickat!')
		document.getElementById(idForm).reset();
	
	return false;
}

