﻿function Soap(p_url, p_function, p_params, p_callback) {

	var that = this;
	
	this.soapFunction = p_function;
	this.callback = p_callback;


	var soapEnvelope = '<?xml version="1.0" encoding="utf-8"?>' +
		'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
		'<soap:Body>' +
		'<{0} xmlns="http://livegadgets.net/services/">{1}</{2}>' +
		'</soap:Body>' +
		'</soap:Envelope>';


	var ajax = new Ajax();
	ajax.method="POST";
	ajax.url=p_url;
	//ajax.postContentType = "application/soap+xml";
	ajax.postContentType = "text/xml";
	//ajax.req.setRequestHeader("SOAPAction",ajaxVersion);
	ajax.postData=setPostData(p_function, p_params);
	ajax.onload=serviceOnLoad;



	function serviceOnLoad(p_req) {
		onCallback(p_req, that.soapFunction, that.callback);
	}

	function onCallback(p_req, fn, p_callback) {
		if (p_callback) {
			var res = getReturnString(p_req, fn);
			p_callback(res);
		}
	}

	function _hesc(p_str){
		return p_str.replace(/&/g,"&amp;").replace(/>/g,"&gt;").replace(/</g,"&lt;");
	}

	function serialize(p_params) {
		var xml="";
		if (p_params) {
			for (var i in p_params) {
				xml += "<{0}>{1}</{2}>".format(i, _hesc(p_params[i]), i);
			}
		}
		return xml;
	}
	
	function setPostData(p_function, p_payload) {
		//ajax.req.setRequestHeader("SOAPAction",p_function);
		return soapEnvelope.format(p_function, serialize(p_payload), p_function);
	}
	
	function getReturnString(p_req, p_function) {
	
		var root = p_req.responseXML.documentElement;
		var soapBody = getChildNode(root,"soap:Body");
		var xResponse = getChildNode(soapBody,p_function+"Response");
		
		if (xResponse.childNodes.length==0) {
			return null;
		} else {
			var Result = getChildNode(xResponse,p_function+"Result");
			//return getInnerText(Result);
			return Result;
		}
	}

	this.execute = function() {
		ajax.load();
	};

	//ajax.load();
	
}
