function clshelperLib(windowRefernce)
{
    var topWindow = windowRefernce;
    var me = this
	//common javascript utility functions
	this.lpad           = _lPad ;
	this.ltrim          = _ltrim;
	this.rtrim          = _rtrim;
	this.removeLineBreaks = _removeLineBreaks;
	this.getKeyCode     = _getKeyCode;
	this.HTMLEncode     = _HTMLEncode;
	this.HTMLDecode     = _HTMLDecode;
	this.GetURL         = _getURL;
	this.checkValidSwitch = _checkValidSwitch;
	this.disposeObject  = _disposeObject;	
	this.getISODate     = _getISODate;
	this.getDayDiff     = _getDayDiff;
	this.getSpeedDate   = _getSpeedDate;
	this.convertXsDurationToTime = _xsdurationToTime;
	this.deserialiseQueryString =   _deserialiseQueryString;
	
	//soap request functions
	this.buildRuleParamXml          = _buildRuleParamXml;
	this.processSoapRequest         = _processSoapRequest;
	this.processSoapRequestAsync    = _processSoapRequestAsync;
	this.processServerRequest       = _processServerRequest;
	this.cleanSoapResponse          = _cleanSoapResponse;
	this.formatForDisplay           = _formatForDisplay;
	
	//function that can be called to check a record set for changes - PROBABLY OBSOLETE. CHECK AND REMOVE LATER -[RV]
	this.alertChanges   = _alertChanges;
	
	//log and message display related functions
	this.errLog         = _errLog;
	this.errLogAsync    = _errLogAsync;
	this.confirmLog     = _confirmLog;
	
    //WSF related functions
	this.openPopup      = _openPopup;
	this.openPopupEx    = _openPopup;
	this.showLoading    = _showLoading;
	this.hideLoading    = _hideLoading;
	this.wsfMapPath     = _wsfMapPath;
	this.mapPath        = _mapPath;
	this.formatISODateForDisplay     = _formatISODateForDisplay;
	this.roundNumber    = _roundNumber;
	
	this.attachEvents   = _attachEvent;
	this.detachEvents   = _detachEvent;
	
	this.addReservedLocation = _addReservedLocation
	var reservedLocations = ",mc,widgets,webservices,wsfdesigner,design,"
	
    
    function _formatForDisplay(data, type)
    {
        var returnValue = data.replace(/&#13;/g, "<br/>")
        
        switch(type)
        {
            case "boolean":
                returnValue = (data == 1 || data == "yes")?"Yes":"No"
                break;
            case "datetime":            
                returnValue = _formatISODateForDisplay(data);
                break;
            case "time":
                returnValue = _xsdurationToTime(data);
                break;
                
        }
        return returnValue;
    }
    
    function _cleanSoapResponse(responseXml)
    {
        var re=/&apos;/g
		responseXml = responseXml.replace(re ,"'")
		re  = /%26/g
		responseXml = responseXml.replace(re ,"&")
        return responseXml
    }
	
	function _buildRuleParamXml()
	{
	    var returnValue = "<document><record>"
        for(var i = 0; i< arguments.length ; i+= 2)
        {
            var paramName = arguments[i];
            var paramValue = arguments[i+1];
            returnValue += "<" + paramName + ">" + paramValue + "</" + paramName + ">";
        }
        returnValue += "</record></document>"
        return returnValue
	}
	
	function _xsdurationToTime(xsduration)
    {
        if(xsduration.indexOf("T") != -1)
        {
            var hrs = "", min = "00", sec = "0";
            var hrs = xsduration.substring(xsduration.indexOf("T") + 1, xsduration.indexOf("H"))
            
            if(isNaN(hrs)) hrs = "0";
            if(xsduration.indexOf("M") > 0)
            {
                if(xsduration.indexOf("H") > 0)
                {
                    min = xsduration.substring(xsduration.indexOf("H") + 1, xsduration.indexOf("M"))
                }
                else
                {
                    min = xsduration.substring(xsduration.indexOf("T") + 1, xsduration.indexOf("M"))
                }
            }
            
            if(xsduration.indexOf("S") > 0)
            {
                sec = xsduration.substring(xsduration.indexOf("M") + 1, xsduration.indexOf("S"))
            }
            
            xsduration = _lPad(hrs,2) + ":" + _lPad(min,2)
        }
        return xsduration;
    }

    function _getDayDiff(arrStart,arrFinish)
    {
	    try{
	    var dStart  = new Date(arrStart[0],arrStart[1]-1,arrStart[2])
	    var dFinish = new Date(arrFinish[0],arrFinish[1]-1,arrFinish[2])
	    return (((((dFinish.valueOf()-dStart.valueOf())/1000)/60)/60)/24)
	    }catch(e){}
	    return 0
    }


    function _roundNumber(num, dec) 
    {
	    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	    return result;
    }

    function _formatISODateForDisplay(date)
    {
        var arrMonthName = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
        
        var dayIndex    = 2;
        var monthIndex  = 1;
        var yearIndex   = 0;
        var sTime = " "
        if(typeof(date) == "string")
        {
            if(date.indexOf("T")> 0 )
            {
                date = date.substring(0,date.indexOf("T"));
            }
            var arrDateTime = date.split(" ");
            
            var arrDate = arrDateTime[0].split("-");
            date = new Date(arrDate[yearIndex],arrDate[monthIndex]-1,arrDate[dayIndex])
            if(arrDateTime.length == 2)
            {
                sTime += arrDateTime[1]
            }
        }
        return _lPad(date.getDate(),2) + "-" + arrMonthName[date.getMonth()] + "-" + date.getFullYear() +  sTime
    }
    
    function _lPad(sValue,length)
	{
		sValue= "" + sValue
		if(sValue.length < length)
		{
		    for(var i = 0; i< (length - sValue.length); i++)
		    {
		        sValue = "0" + sValue;
		    }
		}
		return sValue	
	}

    function _resolveDomReference(windowRef, domReference) 
    {
       if (typeof(domReference) != "object" && windowRef.document.getElementById(domReference)) 
       {
           domReference = windowRef.document.getElementById(domReference);
       }
       return domReference;
    }

    function _attachEvent(windowRef, domReference, eventName, ptrEventHandler, useCapture)
    {
        var domReference = _resolveDomReference(windowRef, domReference);
        if(eventName.indexOf("on") == 0)
        {
            eventName = eventName.substring(2)
            
        }
        
        // DOM
        if (domReference.addEventListener) 
        {
            if(useCapture == null) useCapture = false;
            domReference.addEventListener(eventName, ptrEventHandler, useCapture);
        }
        // IE
        else if (domReference.attachEvent) 
        {
            domReference.attachEvent("on" + eventName, ptrEventHandler);
	    }        
    }

    function _detachEvent(windowRef, domReference, eventName, ptrEventHandler, useCapture)
    {
        var domReference = _resolveDomReference(windowRef, domReference);
        
        if(eventName.indexOf("on") == 0)
        {
            eventName = eventName.substring(2)
        }
        
        // DOM
        if (domReference.addEventListener) 
        {
            if(useCapture == null) useCapture = false;
            domReference.removeEventListener(eventName, ptrEventHandler, useCapture);
        }
        // IE
        else if (domReference.attachEvent) 
        {
            domReference.detachEvent("on" + eventName, ptrEventHandler);
	    }        
    }

	//eventhandler used by all controls for attaching, detaching and raising events.
	this.clsEventHandler = clsEventHandler;
	
	function _addReservedLocation(sLocation)
	{
	    reservedLocations += sLocation + ","
	}
	
	function _mapPath(w, url)
	{
	    var currentLocation = w.location.href.split("/")
        currentLocation[currentLocation.length - 1] = url;
        	    
	    return currentLocation.join("/");
	}
	
    this.hostPrefix = "";
    function _wsfMapPath(sURL, applicationID)
    {
        var contextRef;
        try
        {
            contextRef = top.context;
        }catch(e){}
    
        if(sURL == null)
        {
            return sURL;
        }
    
        if(applicationID != null)
        {
            sURL = sURL.replace("$application", "/mc/em/application/" + applicationID);
        }
        else if(contextRef != null)
        {
            if(contextRef.session != null)
            {
                sURL = sURL.replace("$application", "/mc/em/application/" + contextRef.session.applicationid);
            }
        }
        
        var skinURL = "/widgets/skin";
        if(contextRef != null && contextRef.session != null && contextRef.session.application != null)
        {
            if(contextRef.session.application.skin != null)
            {
                skinURL += "/" + contextRef.session.application.skin;
            }
        }
        sURL = sURL.replace("$skin", skinURL);
        

        if(me.hostPrefix.length == 0)
        {
            var arrTempURL = topWindow.location.href.split("/");
            
            for(var i=3;i < arrTempURL.length; i++)
            {
                if(arrTempURL[i].length > 0 && arrTempURL[i].indexOf("http") != 0 && i < arrTempURL.length - 1)
                {
                    if(reservedLocations.indexOf("," + arrTempURL[i].toLowerCase() + ",") >= 0)
                    {
                        break;
                    }
                    me.hostPrefix  += "/" + arrTempURL[i];
                }
            }
            
        }
        
        if(sURL.indexOf(me.hostPrefix + "/") != 0)
        {
            sURL = me.hostPrefix + sURL;
        }

        return sURL;
    }

	function _alertChanges(quickChanges)
	{	
		var node = quickChanges.selectSingleNode("document");
		
		node = node.firstChild;
		
		var dialogTop = topWindow.screen.availHeight;
		var dialogLeft = topWindow.screen.availWidth-200;
		
		while (node != null)
		{
			var sLastQueriedAt = top.XMLLib.getNodeText(node, ".//WFSys_lastELQueryTimeStamp");
			if (sLastQueriedAt.length>0)
			{
				var oContext = getContext();
				if(oContext!=null)
				{	
					oContext.lastELQueryTimeStamp = sLastQueriedAt;
				}
			}
			dialogTop = dialogTop - 102;
			topWindow.showModelessDialog(_wsfMapPath("/widgets/code/objectupdate.htm"), node, "dialogHeight: 100px; dialogWidth: 250px; dialogTop: " + dialogTop + "px; dialogLeft: "+ dialogLeft + "px; edge: raised; help: Yes; resizable: No; status: No;unadorned:yes");	
			node = node.nextSibling;
		}
	}

    function getContext()
    {
	    var oContext = top.context;
	    if(oContext == null && top.wct != null)
	    {
		    oContext = top.wct.adam;
		}
	    return oContext	;
    }

    //logging and message displat related functions 
	function loadErrLogLangLocaliser(sPath)
	{
		var objXMLErrLog;
		objXMLErrLog= top.XMLLib.objXMLDocTemplate.cloneNode(true);
		objXMLErrLog.async = true;
		objXMLErrLog.load(sPath);
		top.context.cache["objErrLogLangXML"] = objXMLErrLog;
		return;
	}
	
	function _confirmLog(description)
	{	
		this.description = description;

		var sImage;
		var sMessage;
		var sLocation ="<b>Confirm</b>" ;

		sMessage = this.description;
		
        var iWidth    = 400;
        var iHeight   = 200;

        if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf("MSIE 6.0") > 0 )
        {
            iHeight += 52; 
        }        
        
	    var iLeft     = (window.screen.availWidth - iWidth) / 2;
	    var iTop      = (window.screen.availHeight - iHeight) / 2;		
		
		return topWindow.showModalDialog(_wsfMapPath("/widgets/code/confirmlog.htm") ,this,"dialogLeft:" + iLeft + "px;dialogTop:" + iTop + "px;dialogHeight:" + iHeight + "px;dialogWidth:" + iWidth + "px;unadorned:yes");
	}
	
	function _errLogAsync(callback, page, line, versionNo, description)
	{
	
        var iWidth    = 400;
        var iHeight   = 200;
	
        var dialog = top.DHTMLLib.showCustomDialog(top , "height:" + iHeight + "px;width:" + iWidth + "px;", null, "allowtransparency");
        
        var errorObject = _getErrorObject(page, line, versionNo, description);
        
        dialog.dialogArguments      = errorObject;
        dialog.container.innerHTML  = "<iframe src='" + _wsfMapPath("/widgets/code/errorlog.htm") + "' style='height:" + iHeight + "px;width:" + iWidth + "px;border:0px' frameborder='0' allowtransparency = 'true'></iframe>"
        dialog.callBackRef          = _cb_errorLog;
        dialog.callBackArguments    = callback;
	
	    
	}
	
	function _cb_errorLog(returnValue, args)
	{
	    if(args != null)
	    {
	        args(returnValue);
	    }
	}
	
	function _errLog(page, line, versionNo, description)
	{	
        var errorObject = _getErrorObject(page, line, versionNo, description);
	//	var objPopup = topWindow.createPopup()
	//	objPopup.document.body.innerHTML = sErrorHTML		
	//	objPopup.show(( window.screen.availWidth-400)/2,(window.screen.availHeight-200)/2,400,200)
	    if(!topWindow.showModalDialog)
	    {
	        alert(top.XMLLib.getNodeText(errorObject.description,"/err"))
	    }
	    else
	    {
            var iWidth    = 400;
            var iHeight   = 200;
            
            if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf("MSIE 6.0") > 0 )
            {
                iHeight += 52; 
            }        
                    
		    var iLeft     = (window.screen.availWidth - iWidth) / 2;
		    var iTop      = (window.screen.availHeight - iHeight) / 2;
	        
    //	    top.DHTMLLib.showModalDialog(topWindow , _wsfMapPath("/widgets/code/errorlog.htm"), me, "dialogHeight:200px;dialogWidth:400px;unadorned:yes;status:no;resizable:no;help:no;");
		    topWindow.showModalDialog(_wsfMapPath("/widgets/code/errorlog.htm"), errorObject , "dialogTop:" + iTop + "px;dialogLeft:" + iLeft + "px;dialogHeight:" + iHeight + "px;dialogWidth:" + iWidth + "px;unadorned:yes;status:no;resizable:no;help:no;");
        }
	}
	
	function _getErrorObject(page, line, versionNo, description)
	{
	    var errorObject = {}
		try
		{

			var sLangFolder = top.context.session.languageFolder;
			var sLangXML = "";

			if ( sLangFolder != "" && top.context.cache["objErrLogLangXML"] != null)
			{
				var objXMLErrLog;
				objXMLErrLog        = top.XMLLib.objXMLDocTemplate.cloneNode(true);
				objXMLErrLog.async  = true;

				if (top.context.cache["objErrLogLangXML"] == null)
				{
					sErrLogXMLPath  = _wsfMapPath("/mc/" + sLangFolder + "application/"  + top.context.session.applicationid + "/ErrLog_Localiser.xml");
					loadErrLogLangLocaliser(sErrLogXMLPath);
				}

				objXMLErrLog = top.context.cache["objErrLogLangXML"];

				sLangXML = objXMLErrLog.xml;
				
				if ( sLangXML != "")
				{
					var sDesc       = "<document><record><desc>" + description + "</desc></record></document>";
					var objTmpXML   = top.XMLLib.objXMLDocTemplate.cloneNode(true);
					var sXML        = "<root><source>" + sDesc + "</source><language>" + sLangXML + "</language></root>";

					var re  = /&apos;/g;
					sXML    = sXML.replace(re ,"'");
					re      = /&/g;
					sXML    = sXML.replace(re ,"%26");
					
					m_objXSLForLocaliser = top.XMLLib.objXSLDocTemplate.cloneNode(true);
					m_objXSLForLocaliser.loadXML('<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" omit-xml-declaration="yes" /><xsl:template match="/"><document><record><xsl:apply-templates select="//source/document/record" mode="localise" /></record></document></xsl:template><xsl:template match="record" mode="localise"><xsl:variable name="valDesc" select="desc" /><xsl:variable name="valSep">##</xsl:variable><xsl:choose><xsl:when test="contains($valDesc, $valSep)"><desc><xsl:call-template name="strsplit"><xsl:with-param name="string" select="$valDesc" /><xsl:with-param name="pattern">##</xsl:with-param></xsl:call-template></desc></xsl:when><xsl:otherwise><xsl:variable name="valDescNormalised" select="normalize-space($valDesc)" /><xsl:variable name="valLngDesc" select="//root/language/document/record[code=$valDescNormalised]/label" /><xsl:choose><xsl:when test="string-length($valLngDesc) > 0"><xsl:value-of select="$valLngDesc" /></xsl:when><xsl:otherwise><xsl:value-of select="$valDesc" /></xsl:otherwise></xsl:choose></xsl:otherwise></xsl:choose></xsl:template><xsl:template name="strsplit"><xsl:param name="string" /><xsl:param name="pattern" /><xsl:choose><xsl:when test="not($string)" /><xsl:when test="not($pattern)"><xsl:call-template name="strsplit-characters"><xsl:with-param name="string" select="$string" /></xsl:call-template></xsl:when><xsl:otherwise><xsl:call-template name="strsplit-pattern"><xsl:with-param name="string" select="$string" /><xsl:with-param name="pattern" select="$pattern" /></xsl:call-template></xsl:otherwise></xsl:choose></xsl:template><xsl:template name="strsplit-characters"><xsl:param name="string" /><xsl:if test="$string"><xsl:value-of select="substring($string, 1, 1)" /><xsl:call-template name="strsplit-characters"><xsl:with-param name="string" select="substring($string, 2)" /></xsl:call-template></xsl:if></xsl:template><xsl:template name="strsplit-pattern"><xsl:param name="string" /><xsl:param name="pattern" /><xsl:choose><xsl:when test="contains($string, $pattern)"><xsl:if test="not(starts-with($string, $pattern))"><xsl:variable name="valDesc" select="substring-before($string, $pattern)" /><xsl:variable name="valDescNormalised" select="normalize-space($valDesc)" /><xsl:variable name="valLngDesc" select="//root/language/document/record[code=$valDescNormalised]/label" /><xsl:choose><xsl:when test="string-length($valLngDesc) > 0"><xsl:value-of select="$valLngDesc" /></xsl:when><xsl:otherwise><xsl:value-of select="$valDesc" /></xsl:otherwise></xsl:choose></xsl:if><xsl:call-template name="strsplit-pattern"><xsl:with-param name="string" select="substring-after($string,$pattern)" /><xsl:with-param name="pattern" select="$pattern" /></xsl:call-template></xsl:when><xsl:otherwise><xsl:variable name="valDesc" select="$string" /><xsl:variable name="valDescNormalised" select="normalize-space($valDesc)" /><xsl:variable name="valLngDesc" select="//root/language/document/record[code=$valDescNormalised]/label" /><xsl:choose><xsl:when test="string-length($valLngDesc) > 0"><xsl:value-of select="$valLngDesc" /></xsl:when><xsl:otherwise><xsl:value-of select="$valDesc" /></xsl:otherwise></xsl:choose></xsl:otherwise></xsl:choose></xsl:template></xsl:stylesheet>');
					//<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" omit-xml-declaration="yes"/><xsl:template match="/"><document><record><xsl:apply-templates select="//source/document/record" mode="localise"/></record></document></xsl:template><xsl:template match="record" mode="localise"><xsl:variable name="valDesc" select="desc"/><xsl:variable name="valLngDesc" select="//root/language/document/record[code=$valDesc]/label"/><xsl:choose><xsl:when test="string-length($valLngDesc) > 0"><desc><xsl:value-of select="$valLngDesc"/></desc></xsl:when><xsl:otherwise><desc><xsl:value-of select="$valDesc"/></desc></xsl:otherwise></xsl:choose></xsl:template></xsl:stylesheet>')
					var sTransResp = top.XMLLib.transformXML(sXML,m_objXSLForLocaliser);

					if (sTransResp!=null)
					{
						description = top.XMLLib.getNodeText(sTransResp,"//document/record");
					}
					alert(description);
				}
			}
		}catch(e){}
		
		var re      = /##/g;
		description = description.replace(re ,"");
		
		errorObject.page = page;
		errorObject.line = line;
		errorObject.versionNo = versionNo;
		errorObject.description = description;
		
		var sImage;
		var sMessage;
		var sLocation ="<b>Alert</b>" ;

		sMessage    = errorObject.description;

		if (errorObject.page == "")
		{
			sImage = _wsfMapPath("/widgets/assets/erralert.gif");
		}
		else
		{
			sLocation += "Location : " + this.page;
			sImage = _wsfMapPath("/widgets/assets/errcritical.gif");
		}

		if(errorObject.line != "")
		{
			sLocation += " at line "+ errorObject.line;
		}

		/*
		var sErrorHTML ='<HTML><HEAD><META HTTP-EQUIV="content-type" CONTENT="text/html" charset="UTF-8" /><META HTTP-EQUIV="MSThemeCompatible" CONTENT="Yes" /></HEAD>';
		sErrorHTML += '<body leftmargin="0" topmargin="0" scroll="no" style="font:menu;"><form name="theform" method="post" onSubmit="return false;" ><table style="border:1px outset" border="0" cellpadding="2" cellspacing="0" border="0"  width="100%" height="100%" style="filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#E8E8f2, endColorstr=#B4B3CD)"><tr><td width="35px"><IMG id="msgimg" src="' + sImage + '" style="display:inline"></td><td height="50px;" width="365px" style="font:menu;padding:2px"><div id="errLocation" style="overflow-Y:auto;font:menu">'+ sLocation + '</div></td></tr><tr><td valign="top" colspan="2" align="center"><div id="errormessage" style="text-align:left;height:100%;width:390px;overflow-Y:auto;overflow-X:auto;border:1px #7f9db9 solid ;background-color:white;font:menu;padding:2px" >' + sMessage +'</div></td></tr>';
		sErrorHTML += '<tr><td colspan="2" valign="middle" align="right" height="35px" ><input type="button" id="Clipboard" value="Send to Clipboard" style="font:menu;" ></td></tr></table></form></body></HTML>';	
		*/
		return errorObject;
    
	}

	//functions to show and hide the AJAX loading box
	function _hideLoading(windowRef)
	{
		if(windowRef == null)
		{
		    return;
		}
		try
		{
		    if(windowRef.loadingDialog == null) 
		    {
		        return
		    }
		}catch(e){return}
		
		windowRef.activeProcesses = windowRef.activeProcesses -1;
		if(windowRef.activeProcesses < 0)
		{
		    windowRef.activeProcesses = 0;
		}
		if(windowRef.activeProcesses == 0)
		{
			windowRef.loadingDialog.style.display = "none";
		}
	}

	function _showLoading(windowRef)
	{
		if(windowRef == null) 
		{
		    return;
		}
		try
		{
		    if(windowRef.loadingDialog == null)
		    {
			    windowRef.loadingDialog             = windowRef.document.createElement("div");
			    windowRef.document.body.appendChild(windowRef.loadingDialog);
			    windowRef.loadingDialog.innerHTML   = "<IMG src='" + _wsfMapPath("/widgets/assets/animated_loading.gif") + "' align='absmiddle'/>&nbsp;Working on your request...";
			    windowRef.loadingDialog.className   = "loadingwindow";
			    windowRef.activeProcesses           = 0;
		    }
		    
		    windowRef.activeProcesses++;
		    windowRef.loadingDialog.style.display   = "block";
		}
		catch(e)
		{}
	}
	
    //functions to assist soap requests
    function makeSoapBody(requestObject, serviceName, soapAction, functionName, args, argumentsStartIndex)
    {
		requestObject.setRequestHeader ("Content-Type", "text/xml; charset=utf-8") ;
		

		var requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		requestXML += "<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/\">";

		requestXML += "<soap:Body>";
		requestXML += "<" + functionName + " xmlns=\"http://wolf.co.in/webservices/" + soapAction + "\">";
	//	if(args.length == 5)
	//		args[4] = ""  + args[4].replace("<document><record>","<document><record><WFSys_lastELQueryTimeStamp>" + getLastQueryTime() + "</WFSys_lastELQueryTimeStamp>" )
		for (var i = argumentsStartIndex; i < args.length; i += 2) 
		{ 
			requestXML += "<" + args[i] + ">" ;
			requestXML +=  args[i+1] ;
			requestXML += "</" + args[i] + ">" ;
		} 
		requestXML += "</" + functionName + ">";
		requestXML += "</soap:Body>";
		requestXML += "</soap:Envelope>";
		
		requestXML = requestXML.replace("<record>", "<record><wsf_clienttimezoneoffset>" + (new Date()).getTimezoneOffset() + "</wsf_clienttimezoneoffset>");
		
		requestObject.setRequestHeader ("Content-Length",requestXML.length);
		requestObject.setRequestHeader ("SOAPAction", "http://wolf.co.in/webservices/" + soapAction + "/" + functionName);
		
		//replace all amperands which are not followed by amp;
		requestXML = requestXML.replace(/&(?!amp;|lt;|gt;)/g,"&amp;");
		//replace all amperands before the amp;
		return requestXML.replace(/&/g,"%26");
    }

	function _processServerRequest(sWebService, sWebMethod, sNameSpace, sParamName, sParam)
	{
		var sEnvelope = createEnvelope(sWebMethod,sNameSpace,sParamName,sParam);
		var sSoapAction = sNameSpace +"/"+ sWebMethod;
		var result = _processSoapRequest(null, _wsfMapPath("/webservices/wf.object/utilityprocessor.asmx") , "wf.object", "RequestService", "sSoapEnvelope", "<![CDATA[" + sEnvelope + "]]>", "sSoapAction", sSoapAction, "sURL",sWebService);
		if (result == null) 
		{
		    return;
		}
		
		var xmlResponse = getNodeText(result, "//RequestServiceResponse");
		if(xmlResponse.length == 0) 
		{
		    return;	
		}
		
		xmlResponse = xmlResponse.replace("xmlns=", "replaced=");
		xmlResponse = xmlResponse.replace(/&amp;lt;/g, "<");
		xmlResponse = xmlResponse.replace(/&amp;gt;/g, ">");
		xmlResponse = xmlResponse.replace(/&gt;/g, ">");
		xmlResponse = xmlResponse.replace(re=/&lt;/g, "<");
		
		var sResponse = top.XMLLib.getNodeXML(xmlResponse, "//" + sWebMethod + "Result/*");
		return sResponse;

		function createEnvelope(sFunctionName,sSoapAction)
		{
			var OutXML = "<" + sFunctionName + " xmlns=\"" + sSoapAction + "\">"; 
			for (var i = 2; i < arguments.length; i += 2) 
			{ 
				if(arguments[i].length>0)
				{
					OutXML += "<" + arguments[i] + ">"; 
					OutXML +=  arguments[i+1]; 
					OutXML += "</" + arguments[i] + ">"; 
				}
			} 
			OutXML += "</" + sFunctionName + ">"; 
			return OutXML; 
		}
	}
	
	function getXMLHttpRequest()
	{
	    var xmlHttp 
	    if(window.addEventListener)
	    {
	        xmlHttp = new XMLHttpRequest();
        }
        else
        {
            xmlHttp = new ActiveXObject("MSXML2.XMLHTTP") 
        }
        return xmlHttp;
	}	
	

	function _processSoapRequest(windowRef, serviceName, soapAction, functionName) 
	{ 
		_showLoading(windowRef);
		
		var requestObject = getXMLHttpRequest();
		requestObject.open("POST", serviceName, false);
		
		var requestXML  = makeSoapBody(requestObject, serviceName, soapAction, functionName, arguments, 4);
		
		requestObject.send(requestXML); 
		
		var result      = requestObject.responseXML;
		
		var objCallBackDetails  = new callbackDetails(null, requestObject, functionName, requestXML, serviceName, soapAction, windowRef);
		
		var soapResponse        = processSoapResponse(result, objCallBackDetails);
		
		_hideLoading(windowRef);
		return soapResponse.result;
	} 

	function _processSoapRequestAsync(windowRef, callBackFn, serviceName, soapAction, functionName) 
	{ 
		_showLoading(windowRef);
		var requestObject = getXMLHttpRequest();
		requestObject.open ("POST", serviceName, true);

		var requestXML = makeSoapBody(requestObject, serviceName, soapAction, functionName, arguments, 5);
		requestObject.onreadystatechange = standardCallback ;//function(){standardCallback(m_arrCallBackArray.length-1)}
		m_arrCallBackArray[m_arrCallBackArray.length] = new callbackDetails(callBackFn, requestObject, functionName, requestXML, serviceName, soapAction, windowRef);
		requestObject.send(requestXML);
		return m_arrCallBackArray.length-1;
	} 

	var m_arrCallBackArray = new Array();
	function callbackDetails(callBackFn, requestObject, functionName, outXML, serviceName, soapAction, windowRef)
	{
	    this.async          = ((callBackFn == null)? false: true)
		this.pending        = true;
		this.fnRef          = callBackFn;
		this.xmlObject      = requestObject;
		this.FunctionName   = functionName;
		this.RequestXML     = outXML;
		this.ServiceName    = serviceName;
		this.windowRef      = windowRef;
		this.soapAction     = soapAction;
		this.callTime       = new Date();
	}
	
	var m_arrSessionStack = new Array();
	var m_sessionLastValidated;
	function pushSessionStack()
	{
	    var returnValue = {message : "sessionstack", result : null};
		for(var i=0; i < m_arrSessionStack.length; i++)
		{
			objCallBackDetails = m_arrSessionStack[i];
			objCallBackDetails.pending = true;
			
			objCallBackDetails.xmlObject.open ("POST", objCallBackDetails.ServiceName, objCallBackDetails.async) ;			
    
    		objCallBackDetails.xmlObject.setRequestHeader ("Content-Type", "text/xml; charset=utf-8"); 
    		objCallBackDetails.xmlObject.setRequestHeader ("Content-Length",objCallBackDetails.RequestXML.length);
			objCallBackDetails.xmlObject.setRequestHeader ("SOAPAction", "http://wolf.co.in/webservices/" + objCallBackDetails.soapAction + "/" + objCallBackDetails.FunctionName);
			objCallBackDetails.xmlObject.onreadystatechange = standardCallback;
			objCallBackDetails.xmlObject.send(objCallBackDetails.RequestXML);
			
			if(objCallBackDetails.async == false)
			{
	            returnValue.result = _checkAndCleanResponse(objCallBackDetails.xmlObject.responseXML)
			}
			objCallBackDetails.callTime = new Date();
			m_arrSessionStack[i] = null;
		}
		m_arrSessionStack = new Array();
		return returnValue;
	}
	
	function _checkAndCleanResponse(Result)
	{
	    if(window.addEventListener)
	    {
	        var sResponseXML = Result.xml.replace(/xmlns=/g,"xmlns1=");
	        
	        Result = top.XMLLib.objXMLDocTemplate.cloneNode(true);
	        
	        Result.loadXML(sResponseXML);
	        
	    }
	    
	    return Result;
	
	}
	
	
	function _cb_processSoapResponse(validSession)
	{
	    if(validSession == true)
	    {
	        sessionValidating = false
	        pushSessionStack();
	    }
	}
	
	var sessionValidating = false;
	function processSoapResponse(result, objCallBackDetails)
	{
	    result = _checkAndCleanResponse(result);
	    
		if (result.selectSingleNode("//faultstring") != null)
		{
			var sErrMessage = top.XMLLib.getNodeText(result,"//faultstring");
			
			if (sErrMessage.indexOf("ex9886120856") >= 0 )
			{
				//section checks whether the session re-validation is in process
				if(sessionValidating == true)
				{
					m_arrSessionStack[m_arrSessionStack.length]  = objCallBackDetails;
					return {message : "sessiontimeout", result : null};
				}
				//section checks whether the session has been re-validated between response from server and now
				try{
					if(objCallBackDetails.callTime.valueOf() <= m_sessionLastValidated.valueOf() && sessionValidating == false)
					{
						m_arrSessionStack[m_arrSessionStack.length] = objCallBackDetails;
						pushSessionStack();
						return {message : "sessiontimeout", result : null};
					}
				}catch(e){}
				
				m_arrSessionStack[0] = objCallBackDetails;
				sessionValidating = true;
				alert("Your Session has expired. Please login again.");
				top.EMLib.doLogin(null, _cb_processSoapResponse);
				m_sessionLastValidated = new Date();
				return {message : "sessiontimeout", result : null};
				
			}
			else if(sErrMessage.indexOf("License Exception")>=0)
			{
                me.errLog("License validation exception" ,"","","<b>Your License has expired</b>. Please contact your System Administrator or Vendor for further assitance.");
			}
			else
			{
				me.errLogAsync("Unhandled Exception in Web Service \nService : " + objCallBackDetails.ServiceName + " (" + objCallBackDetails.FunctionName +")" ,"","",sErrMessage);
				return {message : "failure", result : null};
			}		
		} 
		
		var xmldoc = top.XMLLib.objXMLDocTemplate.cloneNode(true);
		if(result.selectSingleNode("//" + objCallBackDetails.FunctionName + "Result") != null)
		{
			var sResponse   = top.XMLLib.getNodeText(result,"//" + objCallBackDetails.FunctionName + "Result");
			
			
			var Err         = top.XMLLib.getNodeXML(sResponse, "err");
			
			
			if (Err.length > 0)
			{
			    Err = Err.replace("<err>","").replace("</err>", "");
			    Err = Err.replace(/^\\'/g,"")
			    Err = Err.replace(/\\'$/g,"")
			    
			    if(objCallBackDetails.fnRef)
			    {
			        me.errLogAsync(null, "Handled Exception in Web Service \nService : " + objCallBackDetails.ServiceName + " (" + objCallBackDetails.FunctionName +")" , "", "", Err);
			    }
			    else
			    {
			        me.errLog("Handled Exception in Web Service \nService : " + objCallBackDetails.ServiceName + " (" + objCallBackDetails.FunctionName +")" , "", "", Err);
			    }
				
                
				return {message : "failure", result : null};
			}
			else
			{
				Err = top.XMLLib.getNodeXML(sResponse,"//alert").replace("<alert>","").replace("</alert>", "");
				
			    Err = Err.replace(/^'/g,"")
			    Err = Err.replace(/'$/g,"")
			    
				if(Err.length > 0)
				{
				    if(objCallBackDetails.fnRef)
				    {
					    me.errLogAsync(null,"", "", "",Err);
					}
					else
					{
					    me.errLog("", "", "",Err);
					}
				}
			}
		}
		
		return {message : "success", result : result};
	}
	
	function standardCallback()
	{
		for (var i=0;i<m_arrCallBackArray.length;i++)
		{
			var objCallBackDetails = m_arrCallBackArray[i];
			if(objCallBackDetails.pending == true)
			{
				if(objCallBackDetails.xmlObject.readyState != 4)
				{
				    continue;
				}
				
				Result = objCallBackDetails.xmlObject.responseXML;
				objCallBackDetails.pending = false;
				
				var processResponse = processSoapResponse(Result,objCallBackDetails);
				
				if(processResponse.message == "success" || processResponse.message == "failure")
				{
					try{objCallBackDetails.fnRef(processResponse.result,i)}catch(e){}
					_hideLoading(objCallBackDetails.windowRef);
					objCallBackDetails.xmlObject    = null;
					objCallBackDetails.fnRef        = null;
					objCallBackDetails.FunctionName = null;
					objCallBackDetails.RequestXML   = null;
					objCallBackDetails.windowRef    = null;
				}
			}
		}
	}

	//event handlers commonly used by all controls/widgets
	function clsEventHandler()
	{
		var m_arrEventHandlers = new Array();
		this.detachEvent    = detachEvent;
		this.attachEvent    = attachEvent;
		this.raiseEvent     = raiseEvent;
		this.dispose        = _dispose;
		
		function _dispose()
		{
			for(var sMethod in m_arrEventHandlers)
			{
				for(var sPtr in m_arrEventHandlers[sMethod])
				{
					try{m_arrEventHandlers[sMethod][sPtr] = null;}catch(e){}	
				}
				try{m_arrEventHandlers[sMethod] = null;}catch(e){}
			}
		}
		
		function detachEvent(sEventName,ptrEventHandler)
		{
		    try{
			var sEventName = sEventName.toLowerCase();
			var pointerName = "wsf_ptr" + ptrEventHandler.toString();
			if(m_arrEventHandlers[sEventName] == null && m_arrEventHandlers[sEventName][pointerName])
			{
				m_arrEventHandlers[sEventName][pointerName] = null;
            }
            }catch(e){}
		}
		
		function attachEvent(sEventName,ptrEventHandler)
		{   

			var sEventName = sEventName.toLowerCase();
			if(m_arrEventHandlers[sEventName] == null)
			{
				m_arrEventHandlers[sEventName] = new Array()
            }
            var pointerName = "wsf_ptr" + ptrEventHandler.toString();
			m_arrEventHandlers[sEventName][pointerName] = ptrEventHandler;
		}

		function raiseEvent(sEventName,evt)
		{
			if(evt==null)
			{
				evt = new Object();
			}
			evt.type = sEventName;
			evt.cancel=false;
			
		    if(evt.srcElement != null && evt.rootsrcElement == null)
		    {
			    evt.rootsrcElement = evt.srcElement
			}
			//evt.srcElement = me
			
			var ptrCollection = m_arrEventHandlers[sEventName.toLowerCase()];
			
			var returnValue = true;
			for(k in ptrCollection)
			{
			

			    if(k.indexOf("wsf_ptr") == 0)
			    {
				    try
				    {
    //					system.evt=evt					
					    ptrCollection[k](evt);
					    if(evt.cancel == true)
					    {
						    returnValue = false;
					    }
				    }catch(e){returnValue = true;}
                }
			}
			return returnValue;
		}
	}
	
	
	function _openPopup( popupName, dialogArgs, arguments, windowRef, cb)
	{
	
		if (windowRef == null)
		{
		    windowRef = window;
        }
        
        objTop = windowRef;
        for(var i = 0; i < 10;i++)
        {
            if(objTop.wct != null)
                break;
            objTop = objTop.parent;                   
        } 
        
		var objWCT = new top.EMLib.clsWCT()
		
		if (objTop.wct != null)
		{
			objWCT.adam = objTop.wct.adam;
		}
		else if(objTop.context != null)
		{
			objWCT.adam = objTop.context;
		}
		
		
		objWCT.parentWCT = objTop.wct;
		
		objWCT.bfu = popupName;
		objWCT.popupArgs = arguments;
		
	    var iHeight = 500;
        if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf("MSIE 6.0") > 0 )
        {
            iHeight += 52; 
        }
		
		if (dialogArgs == "")
		{
			dialogArgs = "status:no;height:" + iHeight + "px;width:600px;";
		}
		else
		{
		    dialogArgs = dialogArgs.toLowerCase().replace(/dialog/g, "");
		}
		
		objWCT.adam.libraries = top.libraries;
	//			m_stringTrack+= "@7.2-" + _getSpeedDate() 
	
        var dialog = top.DHTMLLib.showCustomDialog(top , dialogArgs, null, "allowtransparency");
        
        dialog.dialogArguments      = objWCT;
        dialog.container.innerHTML  = "<iframe src='" + _wsfMapPath("/widgets/runtime/htc/wct.htm") + "' style='" + dialogArgs + ";border:0px' frameborder='0' allowtransparency = 'true'></iframe>"
        dialog.callBackRef          = _cb_openPopup;
        dialog.callBackArguments    = cb;
	
		//return windowRef.showModalDialog(_wsfMapPath("/widgets/runtime/htc/wct.htm"), objWCT, dialogArgs, windowRef);
		
		function _cb_openPopup(returnValue, args)
		{
		    if(args != null)
		    {
		        try{args(returnValue)}catch(e){};
		    }
		    
		}
	}


    //common utility functions 
	function _checkValidSwitch(sSwitch)
	{
		for (var i=1;i<arguments.length;i++)
		{
			if (sSwitch == arguments[i])
			{
				return sSwitch;
			}
		}
		return -1;	
	}

	function _getKeyCode(sKeyCode)
	{
		for (var i = 1; i < arguments.length; i++)
		{
			if (sKeyCode == arguments[i])
			{
				return sKeyCode;
			}
		}
		return -1;	
	}

	function _getISODate(dateObj)
	{
		var sMonth = "" + (dateObj.getMonth()-0+1)
		var sDate = "" + dateObj.getDate();
		if(sMonth.length == 1)
		{
		    sMonth  = "0" + sMonth;
		}
		if(sDate.length==1)
		{
		    sDate = "0" + sDate;
		}
		var sISO = dateObj.getFullYear() + '-' + sMonth + '-' + sDate;
		return sISO;
	}
	
	function _disposeObject(obj)
	{
		for(var sMethod in obj)
		{
			try{obj[sMethod] = null;}catch(e){}
		}
	}

	function _deserialiseQueryString(href)
	{
	    if(!href)
	    {
	        href = top.location.href;
	    }
	    var queryString = {};
        try{
        var qs = href.split("?")[1].split("&")
        for (var i = 0; i< qs.length; i++)
        {
            var param = qs[i].split("=");
            if(param[1] != null && param[1] != "")
            {
                queryString[param[0].toLowerCase()] = param[1];
            }
        }}catch(e){}
        return queryString;	    
	}
	
	var m_errMessages = ""
	
	function _getSpeedDate()
	{
		dt = new Date();
		return "-##-" + dt.getMinutes() + ":" + dt.getSeconds() + ":" + dt.getMilliseconds() + " ";
	}
		
    function _ltrim(s)
	{
		return s.replace( /^\s*/, "" );
	}

	function _rtrim(s)
	{
		return s.replace( /\s*$/, "" );
	}

	function _removeLineBreaks(str)
	{
		try{
			var re = /\r/g;
			str = str.replace(re,"");
			re = /\n/g;
			str = str.replace(re,"");
			re = /\t/g;
			str = str.replace(re,"");
			return str;
		}catch(e){}
	}

	function _getURL(sURL)
	{
		var arrLocation = topWindow.location.href.split("/");
		var sRoot = arrLocation[0] + "/" + arrLocation[1] + "/" + arrLocation[2];
		if (sURL.substring(0,1) == "/")
		{
			return sRoot + sURL;
        }
	}

	function _HTMLDecode(t) 
	{
		var h,d,e,i,c,r,j
		
		h = '&,",<,>,\',\''.split(",");
		e = "&amp;amp;,&amp;quot;,&amp;lt;,&amp;gt;,&apos;,&amp;apos;".split(",");
		d = t;
	/*	if (t.length > 0 )
			for (i=0;i< t.length;i++)
			{
				c = t.substr(i,1)
				r = 0
				for (j=0 ;j<e.length;j++)
				{
					if (c == e[j])
					{
						d += h[j]
						r = 1
						break;
					}
				}
				if (r == 0)  d += c
			}
	*/
		var re = /&amp;/g
		d =d.replace(re,"&")	
		var re = /&apos;/g
		d =d.replace(re,"'")	
		var re = /&quot;/g
		d =d.replace(re,"\"")	
		var re = /&lt;/g
		d =d.replace(re,"<")	
		var re = /&gt;/g
		d =d.replace(re,">")	
		return d
	}

	function _HTMLEncode(t) 
	{
		var h,d,e,i,c,r,j
		
		h = '&,",<,>'.split(",")
		e = "&amp;amp;,&amp;quot;,&amp;lt;,&amp;gt;".split(",")
		d = ""
		if (t.length > 0 )
			for (i=0;i< t.length;i++)
			{
				c = t.substr(i,1)
				r = 0
				for (j=0 ;j<h.length;j++)
				{
					if (c == h[j])
					{
						d += e[j]
						r = 1
						break;
					}
				}
				if (r == 0)  d += c
			}
		return d
	}
		
}
