var m_ajax_request_type = 'GET';
var debug = "";

/**
 * [Private function] Initialize RPC object
 */ 
 
function ajaxInitObject()
{
	var A;
	try
	{
		A=new ActiveXObject('Msxml2.XMLHTTP');
	}
	catch (e)
	{
		try
		{
			A=new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (oc)
		{
			A=null;
		}
	}
	if(!A && typeof XMLHttpRequest != 'undefined')
	{
		A = new XMLHttpRequest();
	}
	if (!A)
	{
		alert('Could not create RPC connection object.');
	}
	return A;
}

/**
 * [Private function] Performs the actual call
 */ 
function callAjaxMethodImpl(a_ajax_url, a_confirm, a_args)
{
	var i, x, n;
	var post_data;
	if (m_ajax_request_type == 'GET')
	{
	
		a_ajax_url += a_ajax_url.indexOf("?") == -1 ? '?' : '&';
		for (i = 0; i < a_args.length; i+=2)
		{
			//a_ajax_url += a_args[i+0] + '=' + a_args[i+1] + '&';
			//a_ajax_url += encodeURIComponent(a_args[i+0]) + '=' + encodeURIComponent(a_args[i+1]) + '&';
			a_ajax_url += escape(a_args[i+0]) + '=' + escape(a_args[i+1]) + '&';
		}
		
		a_ajax_url += 'ajax_rnd=' + new Date().getTime();
		debug = a_ajax_url;
		post_data = null;
	}
	else
	{
		for (i = 0; i < a_args.length; i+=2)
		{
			post_data += (i > 0 ? '&' : '') + encodeURIComponent(a_args[i+0]) + '=' + encodeURIComponent(a_args[i+1]);
		}
	}
	x = ajaxInitObject();
	if (x == null)
	{
		return;
	}
	x.open(m_ajax_request_type, a_ajax_url, true);
	if (m_ajax_request_type == 'POST')
	{
		x.setRequestHeader('Method', 'POST ' + a_ajax_url + ' HTTP/1.1');
		x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}
	x.onreadystatechange = function()
	{
		if (x.readyState != 4)
		{
			return;
		}
   		//alert("Status is "+x.status)
		//alert(x.responseText);
		
		if (x.getResponseHeader("content-type").substring(0,8) == 'text/xml')
		{
			a_confirm(x.responseXML);
		}
		else
		{
			a_confirm(x.responseXML);
			//a_confirm(x.responseText);
		}
	}
	
	x.send(post_data);
	delete x;
}

/**
 * [Public function] Calls the RPC URL provided.
 *
 * @param a_ajax_url
 *        An URL to whoever is to receive to ajax call
 * @param a_javascript_confirm_method
 *        The name of a javascript method which is called when a response is received
 * @param a_key_value_pairs
 *        [Optional] Arguments send to the server.
 */
function callAjaxMethod()
{
	var args = new Array();
	for (var i = 2; i < callAjaxMethod.arguments.length; i++)
	{
		args[i-2] = callAjaxMethod.arguments[i];
	}
	callAjaxMethodImpl(callAjaxMethod.arguments[0], callAjaxMethod.arguments[1], args);
}


/**
 * [Public function] Opens a window with URL and parameters specified.
 *
 * @param a_ajax_url
 *        An URL to whoever is to receive to ajax call
 * @param a_javascript_confirm_method
 *        This parameter is ignored.
 * @param a_key_value_pairs
 *        [Optional] Arguments send to the server.
 */
function debugAjaxMethod()
{
	var url = debugAjaxMethod.arguments[0];

	for (var i = 2; i < debugAjaxMethod.arguments.length; i+=2)
	{
		if (i > 2)
		{
			url += '&';
		}
		else
		{
			url += '?';
		}
		url += debugAjaxMethod.arguments[i] + '=' + debugAjaxMethod.arguments[i+1];
	}

	window.open(url,'ajax_debug_window');
}


/**
 * [Public function] Returns the element of the first element with the name specified.
 * 
 * E.g: var element = getXmlElementValue(dom, "element1", "element2", "field");
 *
 *      The returned element is the "field" element.
 *
 *      Xml looks like this: <element1><element2><field>value</field></element2></element1>
 *
 * @param a_dom
 *    a DOM object which this method process.
 * @param a_element_name
 *    an list of element names, minimum one argument
 * @return
 *    the element the specified
 */
function getXmlElement()
{
	//alert('1');
	if (getXmlElement.arguments.length == 0)
	{
		alert('Too few arguments in getXmlElement call.');
	}
	
	var node = getXmlElement.arguments[0];
	
	//alert('2');	
	for (var i = 1; i < getXmlElement.arguments.length; i++)
	{
		//alert('*' + getXmlElement.arguments[i] + '*');
		node = node.getElementsByTagName(getXmlElement.arguments[i])[0];
		//alert(node);
	}
	//alert('3');
	return node;
}


/**
 * [Public function] Returns the element value of the first element with the name specified.
 * 
 * E.g: var value = getXmlElementValue(dom, "element1", "element2", "field");
 *
 *      The returned value is the "value" value.
 *
 *      Xml looks like this: <element1><element2><field>value</field></element2></element1>
 *
 * @param a_dom
 *    a DOM object which this method process.
 * @param a_element_name
 *    an list of element names, minimum one argument
 * @return
 *    the last elements value is returned
 */
function getXmlElementValue()
{
	var emptyString = '';

	if (getXmlElementValue.arguments.length == 0)
	{
		alert('Too few arguments in getXmlElement call.');
	}
	
	var node = getXmlElementValue.arguments[0];
	
	for (var i = 1; i < getXmlElementValue.arguments.length; i++)
	{
		node = node.getElementsByTagName(getXmlElementValue.arguments[i])[0];		

		
	}

	if (node.firstChild != null){
		return node.firstChild.data;
	}else{
		return emptyString;
	}
	
	
}


/**
 * [Public function] Calls the RPC URL provided with all fields in the form provided. 
 *                   Fields with an empty name or empty value is discarded.
 *
 * @param a_ajax_url
 *        An URL to whoever is to receive to ajax call
 * @param a_javascript_confirm_method
 *        The name of a javascript method which is called when a response is received
 * @param a_form
 *        The form object containing parameters
 */
function callAjaxMethodAllArgs(a_ajax_url, a_javascript_confirm_method, a_form)
{
	var args = new Array();
	for (var i = 0; i < a_form.elements.length; i++)
	{
		if (a_form.elements[i].name != '' && a_form.elements[i].value != '')
		{
			args[i*2+0] = a_form.elements[i].name;
			args[i*2+1] = a_form.elements[i].value;
		}
	}

	callAjaxMethodImpl(a_ajax_url, a_javascript_confirm_method, args);
}

/**
 * [Public function] Serializes a DOM tree into plain text/xml.
 *
 * @param a_element
 *        A DOM element
 * @return
 *        A String representation of the DOM element
 */
function serialize(a_element)
{
	return serialize_impl(a_element,0);
}


/**
 * [Private function] Implementation of the serialize function.
 */
function serialize_impl(a_element,a_indent)
{
	var output = '';

	for (var i = 0; i < a_element.childNodes.length; i++)
	{
		var element = a_element.childNodes[i];

		for (var j = 0; j < a_indent; j++)
		{
			output += '   ';
		}
	
		if (element.nodeType == 3) // #text
		{
			output += element.nodeValue + '\n';
		}
		else
		{
			output += '<' + element.nodeName;
	
			if (element.hasAttributes)
			{
				if (element.attributes != null)
				{
					for (var j = 0; j < element.attributes.length; j++)
					{
						output += ' '+element.attributes[j].nodeName+'=\"'+element.attributes[j].nodeValue+'\"';
					}
				}
			}

			if (element.childNodes.length > 0)
			{
				output += '>\n';
	
				output += serialize_impl(element, a_indent+1);
		
				for (var j = 0; j < a_indent; j++)
				{
					output += '   ';
				}
		
				output += '</' + element.nodeName + '>\n';
			}
			else
			{
				output += '/>\n';
			}
		}
	}

	return output;
}
