//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------
function loadUP()
{
	try
	{
		// check if user XML data has been loaded already
		if (UP_MAIN.oUpXml)
		{
			// get form reference
			var oFieldForm = UP_FORM;
			
			// recheck form ok
			if(oFieldForm)
			{
				var oFormField;
				
				// get collection of nodes in the xml user data
				var oDataFields	= UP_MAIN.oUpXml.documentElement.selectSingleNode("DATA").childNodes;
				
				// move thrue the collection of user properties
				for (var iIndex=0; iIndex<oDataFields.length ;iIndex++)
				{
					// get property name
					sDataName		= "up_"+oDataFields[iIndex].nodeName.toLowerCase();
					
					// get property text
					sFieldValue		= oDataFields[iIndex].text;
					
					// get property
					oFormField		= oFieldForm.all[sDataName];
					
					// load field data
					loadItem(oFormField, sFieldValue);
				}
			}
		}
	}
	catch(e)
	{
		alert("ERROR in function loadUP():\n"+e.description);
	}
}


function loadItem(oFormField, sFieldValue)
{
	try
	{
		// check if the field exists
		if (oFormField)
		{
			// check is the field array type (like if there many radio/checkbox buttons)
			if (oFormField.length>0)
			{
				if (oFormField.tagName=="SELECT" && oFormField.datatype=="code")
				{
					oFormField.value	= sFieldValue;
				}
				else
				{
					// split values of lookup field 
					var aValues		= sFieldValue.split(" ");
					var bContinue;

					// move thrue the fields
					for (var jIndex=0; jIndex<oFormField.length ;jIndex++)
					{

						// reset stopping flag
						bContinue	= true;

						// move thrue the collection of values and check if the current selected field is in the collection
						for (var kIndex=0; bContinue && kIndex<aValues.length ;kIndex++)
						{
							if (aValues[kIndex]==oFormField[jIndex].value)
								bContinue	= false;
						}

						// check if current field is part of the value
						if (!bContinue)
							oFormField[jIndex].checked	= true;
						else
							oFormField[jIndex].checked	= false;
					}
				}
			}
			else
			{
				if (oFormField.datatype=="codes")
				{

				}
				else
				{
					if (oFormField.type=="radio" || oFormField.type=="checkbox")
					{
						if (sFieldValue=="1" || sFieldValue.toLowerCase()=="true")
						{
							oFormField.checked	= true;
						}
					}
					else
					{
						oFormField.value	= sFieldValue;
					}
				}
			}
		}
	}
	catch(e)
	{
		alert("ERROR in function loadItem().Error=\n"+e.description);
		//alert("ERROR in function loadItem():\noFormField="+oFormField.outerHTML+"\nsFieldValue="+sFieldValue+"\nError=\n"+e.description);
	}
}


function updateUPXml()
{
	if (UP_MAIN.oUpXml)
	{
		// get form reference
		var oFieldForm = UP_FORM;
		
		// recheck form ok
		if(oFieldForm)
		{
			var oFormField;
			
			var oDataFields	= UP_MAIN.oUpXml.documentElement.selectSingleNode("DATA").childNodes;
			
			for (var iIndex=0; iIndex<oDataFields.length ;iIndex++)
			{
				sDataName		= "up_"+oDataFields[iIndex].nodeName.toLowerCase();
				
				sFieldValue		= "";
				
				oFormField		= oFieldForm.all[sDataName];
				
				if (oFormField)
				{
					if (oFormField.length>0)
					{
						if (oFormField.datatype=="code")
						{
							sFieldValue		= oFormField.value;
						}
						else
						{
							var aValues		= sFieldValue.split(" ");
							for (var jIndex=0; jIndex<oFormField.length ;jIndex++)
							{
								if (oFormField[jIndex].checked)
									sFieldValue	+= oFormField[jIndex].value + " ";
							}
							if (sFieldValue!="");
								sFieldValue	= sFieldValue.substring(0,sFieldValue.length-1);
						}
					}
					else
					{
						if (oFormField.datatype=="codes")
						{
							
						}
						else
						{
							if (oFormField.type=="radio" || oFormField.type=="checkbox")
							{
								if (oFormField.checked)
									sFieldValue		= "1";
								else
									sFieldValue		= "0";
							}
							else
							{
								sFieldValue		= oFormField.value;
							}
						}
					}
					
					oDataFields[iIndex].text	= sFieldValue;
					
				}
			}
		}
	}
}


function createUPXml()
{
	// check if user XML data has been loaded already
	if (UP_MAIN.oUpXml)
	{
		// get form reference
		var oFieldForm = UP_FORM;
		
		// recheck form ok
		if(oFieldForm)
		{
			var oItem;
			
			// select [DATA] nodes in order to append to it the new constructed nodes
			var oDATANode	= UP_MAIN.oUpXml.selectSingleNode("//DATA");
			
			var sTempNodeName;
			// move thrue the elements of the form
			for (var iIndex = 0 ; iIndex < oFieldForm.length ;iIndex++)
			{
				oItem		= oFieldForm.item(iIndex);
				
				sTempNodeName	= oItem.name.toUpperCase();
				if (sTempNodeName.indexOf("UP_")==0)
				{
					sTempNodeName	= sTempNodeName.split("UP_")[1].toUpperCase();
					
					// check if the node has not been already created
					if (!oDATANode.selectSingleNode(sTempNodeName))
					{
						// create node
						var oNode	= UP_MAIN.oUpXml.createElement(sTempNodeName);
						
						// append node to the main [DATA] node
						oDATANode.appendChild(oNode);
					}
				}
			}
		}
	}
}



//--------------------------------------------------------
//--------------------------------------------------------
//--------------------------------------------------------

function GetUserData()
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];
	    	args["appID"]	= APPLICATION_ID;
	    	args["userID"]	= USER_ID;

		//invoke specific method
		invokeMethod("GetUserData",args); 
		
		try
		{
			//gets the result from the server
			return  getResult();
		}
		catch(e)
		{
			alert("ERROR in function GetUserData():\n"+e.description);
			//alert(e.description)
			return null;
		}
		
	}

}

//--------------------------------------------------------

function UpdateUserData(oUserProfileData)
{
	with(new SOAPClient())
	{
		//call the user profile service
		callService(WEB_SERVICE_URL);

		//initialize all args according to the method's signature
		var args = [];

		args["appID"]		= APPLICATION_ID;
		args["userID"]		= USER_ID;
		args["userData"]	= oUserProfileData.xml;

		//invoke specific method
		invokeMethod("UpdateUserData",args); 

		try
		{
			//gets the result from the server
			return getResult();
		}
		catch(e)
		{
			alert("function UpdateUserData Error:\n"+e.description)
			return null;
		}
	}

}

//--------------------------------------------------------

function CreateUserProfile(oUserProfileData)
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];

	    args["appID"]		= APPLICATION_ID;
	    args["userData"]	= oUserProfileData.xml;
		
		//invoke specific method
		invokeMethod("CreateUserProfile",args); 
				
		try
		{
			//gets the result from the server
			return getResult();
		}
	    catch(e)
	    {
			alert("function CreateUserProfile Error:\n"+e.description)
			return null;
		}
		
	}

}

//--------------------------------------------------------

function ActivateUser()
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];

	    args["appID"]		= APPLICATION_ID;
	    args["userID"]		= USER_ID;
		
		//invoke specific method
		invokeMethod("ActivateUser",args); 
		
		try
		{
			//gets the result from the server
			return getResult();
		}
	    catch(e)
	    {
			return null;
		}
		
	}

}

//--------------------------------------------------------

function DeactivateUser()
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];

	    args["appID"]		= APPLICATION_ID;
	    args["userID"]		= USER_ID;
		
		//invoke specific method
		invokeMethod("DeactivateUser",args); 
		
		try
		{
			//gets the result from the server
			return getResult();
		}
	    catch(e)
	    {
			return null;
		}
	}

}


//--------------------------------------------------------

function EnableMailing()
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];

	    args["appID"]		= APPLICATION_ID;
	    args["userID"]		= USER_ID;
		
		//invoke specific method
		invokeMethod("EnableMailing",args); 
		
		try
		{
			//gets the result from the server
			return getResult();
		}
	    catch(e)
	    {
			return null;
		}
	}

}


//--------------------------------------------------------

function DisableMailing()
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];

	    args["appID"]		= APPLICATION_ID;
	    args["userID"]		= USER_ID;
		
		//invoke specific method
		invokeMethod("DisableMailing",args); 
		
		try
		{
			//gets the result from the server
			return getResult();
		}
	    catch(e)
	    {
			return null;
		}
	}

}


//--------------------------------------------------------

function ConfirmUser()
{
	with(new SOAPClient()){

		//call the user profile service
		callService(WEB_SERVICE_URL);
	    
	   	//initialize all args according to the method's signature
	   	var args = [];

	    args["appID"]		= APPLICATION_ID;
	    args["userID"]		= USER_ID;
		
		//invoke specific method
		invokeMethod("ConfirmUser",args); 
		
		try
		{
			//gets the result from the server
			return getResult();
		}
	    catch(e)
	    {
			return null;
		}
	}

}

//--------------------------------------------------------




//===============================================================================
// SOAPClient.js
// 
//
// The SOAPClient script enables client-side script to invoke remote methods
// exposed by Web Services, or other Web servers, that support the SOAP and Web Services
// Description Language (WSDL) 1.1. 
//
// This behavior provides developers the opportunity to use and leverage SOAP, 
// without requiring expert knowledge of its implementation.
// 
//===============================================================================
// Written By	: Liran Peleg
// Company	: Scepia Ltd.
// Created On	: 16/02/04
// Modified On	: 16/02/04
//===============================================================================
function SOAPClient(){

  this.method = {name:'',args:''};
  this.service = {url:'',namespace:''};
  this.credentials = {username:'',password:''}
  this.error = {code:0,description:'',raw:''}
   
   SOAPClient.prototype.invokeMethod = function(name,args) {
	
	this.method["name"] = name;
        this.method["args"] = args
                     
    } 


      SOAPClient.prototype.setCredentials = function(username,password) {
	
	this.credentials["username"] = username;
                this.credentials["password"] = password;
                     
    }   


      SOAPClient.prototype.callService = function(uri,ns){
		
       	this.service["url"] = uri
	
	//this.service["namespace"] = (!ns) ? 'http://tempuri.org/' : ns;
	this.service["namespace"] = ns;
		
	return this.service;
      }

     SOAPClient.prototype.send = function(){

         with( new ActiveXObject("microsoft.xmlhttp") ){
	
	 open("POST",this.service.url,false,this.credentials["username"],this.credentials["password"]);
		
          setRequestHeader("SOAPAction", ((!this.service.namespace) ? "/" : this.service.namespace) + this.method.name);
	  setRequestHeader("Content-Type", "text/xml; charset='utf-8' ");

	  send(this.payload().xml);
	
	  if(status !=200) 
	  {	
		throw new SOAPError(status,responseXML)
	  }

          return (status==200) ? responseXML : null;

        }
   }

   SOAPClient.prototype.setBegin_Env = function(){

         var header = "<?xml version='1.0'?><SOAP-ENV:Envelope xmlns='' "

          + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
 
          + "xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' " 

          + "xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' "

          + "xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' " 
	
	  + "xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' " 

	  + "xmlns:http='http://schemas.xmlsoap.org/wsdl/http/' " 
           
          + "xmlns:s='http://www.w3.org/2001/XMLSchema' "

          + "xmlns:tm='http://microsoft.com/wsdl/mime/textMatching/' " 

 	  + "xmlns:mime='http://schemas.xmlsoap.org/wsdl/mime/' "

          + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"
		
          return header
    }


    SOAPClient.prototype.setEnd_Env = function(){

          return "</SOAP-ENV:Envelope>"
    }

   SOAPClient.prototype.setBody_Env = function(){

       var body = [];

        body.push("<SOAP-ENV:Body>");

        body.push("<" + this.method["name"]);

	if(this.service["namespace"]){
		
	   body.push(" xmlns='"+this.service["namespace"]+"'")              
	}

        body.push(">");
        

        for(var i in this.method["args"]){

            body.push("<"+i+">" + this.method["args"][i]+ "</"+i+">");            
        }

	body.push("</"+this.method["name"]+">");

	body.push("</SOAP-ENV:Body>");

	return body.join('')
	
   }

    SOAPClient.prototype.payload = function(){

         var env = [];

	
         env.push(this.setBegin_Env());

         env.push(this.setBody_Env());

         env.push(this.setEnd_Env());
	
         var xmldoc = new ActiveXObject("microsoft.xmldom");

         xmldoc.loadXML(env.join(''));

		  if(xmldoc.parseError.errorCode !=0) 
			throw new Error("SOAPSender::payload \r\n"+xmldoc.parseError.reason);

         return xmldoc;

         
   }

    SOAPClient.prototype.getResult = function(){
		
         var payload = this.send();
		
          var res = payload.selectSingleNode("//soap:Body//"+this.method["name"]+"Result");
		
	//return empty response in case of an error  
	if(res == null){
		
		res = payload.selectSingleNode("//soap:Body//"+this.method["name"]+"Response");
          }

         return res;

         
   } 

	function SOAPError(status,fault){
		this.status = (!status) ? 200 : status;
   		this.code = fault.selectSingleNode("//faultcode").text;
		this.description = fault.selectSingleNode("//faultstring").text;
		this.details = fault.selectSingleNode("//detail").text;
		this.rawXml = fault.xml;
		
         }  
    
}
