//---------------------------------------------------------------------------------
//  (c) 2007 Guardian Networks, Inc
//---------------------------------------------------------------------------------

CreateNamespace ( "XMLRequest" );
CreateNamespace ( "XMLResponse" );
CreateNamespace ( "ErrorHandler" );

ErrorHandler =
{
  XmlError : function ( XmlResponse )
  {
    var Error = XmlResponse.GetElements("Error");
    alert ( "Service Error: " + Error[0].getAttribute ( "Message" ));
  }
}


XMLResponse = function()
{
}

XMLResponse.prototype = 
{
  DomDoc : function ( XmlDoc )
  {
    if (window.ActiveXObject)
    {
        var doc=new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(XmlDoc);
    }
    else
    {
        var parser=new DOMParser();
        var doc=parser.parseFromString(XmlDoc,"text/xml");
    }

    this._DomDoc=doc;

    doc = null;
  },
  
  
  GetElements : function ( ElementName )
  {
      return this._DomDoc.getElementsByTagName ( ElementName );  
  },
  
  GetElement : function ( ElementName, ID )
  {
    try
    {
      var Element = this._DomDoc.getElementsByTagName ( ElementName );  
      return Element[ID].text;
    }
    catch ( E )
    {
      return "";
    }
  },
  
  Replace : function ( FromThis, ToThis )
  {
    this._XmlDoc = this._XmlDoc.replace ( "xmlns" , "filename" );
    this._DomDoc = (new DOMParser()).parseFromString(this._XmlDoc,"text/xml");
  },
  
  ToString : function ( )
  {
    return this._DomDoc.xml;
  }
}


XMLRequest =
{
  Initialize : function ( )
  {
    this._SessionKey = 0;
    this._Facility = "";
    this._Command = "";
    this._Parameters = "";
    this._ServerNotFound = false;
    this._LastAlias = 1;
  },
  
	SetNewSessionKey :   function ( SessionKey )
  {
	  this._SessionKey = SessionKey
  },
  
  GetSessionKey : function ()
  {
    return this._SessionKey;
  },
  
  SetServer : function ( ServerAddress )
{
    this._ServerArray = ServerAddress.split(',');
  },

  Send : function ( Facility, Command, Parameters, MessageTypeToPublish, ErrorMessageTypeToPublish )
  {
    this._Facility = Facility;
    this._Command = Command;
    this._Parameters = Parameters;

    this._LastAlias++;
    
    if ( this._LastAlias >= this._ServerArray.length )
    {
      this._LastAlias = 0;
    }
		var xmlSend = new XMLSend( this._ServerArray[this._LastAlias], this._SessionKey, this._ToString (this._RequestID), MessageTypeToPublish, ErrorMessageTypeToPublish );	
	},
	
	ServerWasNotFound : function ( ErrorText )
	{
	  if (( !this._ServerNotFound ) || ( this._ServerNotFound == false ))
	  {
	    if ( ErrorText != "" )
	    {
	      alert("Session Timed Out, please click ‘OK’ to refresh session");
	      //alert("Unable to communicate on port 20, please contact your IT dept to verify that this port is open.");
	      //alert("Server Was Not Found.  Please Refresh. [" + ErrorText + "]");
	    }
	    else
	    {
              alert("Session Timed Out, please click ‘OK’ to refresh session");
	      //alert("Unable to communicate on port 20, please contact your IT dept to verify that this port is open.");
	    }
	    this._ServerNotFound = true;
	  }
	},
	
	_ToString : function (  )
    {


        var XML = '<?xml version="1.0"?><Request S="' + this._SessionKey + '" F="' + this._Facility +
            '" C="' + this._Command + '"><Parameters>' + this._Parameters + '</Parameters></Request>';
        
        return XML;
    }
  
}

XMLSend = function( Server, SessionKey, Request, MessageTypeToPublish, ErrorMessageTypeToPublish, RequestID )	  
{


  var XmlHttp = null;
  if (window.XMLHttpRequest)
  {
    XmlHttp = new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    XmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  XmlHttp.open("POST",Server ,true);
  XmlHttp.onreadystatechange = StateChange;
  XmlHttp.send(Request);   
 // Gutenberg.PublishNow("LogThis","Sent: " + Request);   

  function StateChange()
  {
    var oDomDoc;
    var Error;
    
      
    switch ( XmlHttp.readyState)
    {
      case 1 : break;
      case 2 : break;
      case 3 : break;
      case 4 :
        if ( XmlHttp.statusText == "OK" )
        {
          var XmlResponse = new XMLResponse();
          XmlResponse.DomDoc(XmlHttp.responseText);  
          var Error = XmlResponse.GetElements("Error");  
          
          if ( Error.length > 0 )
          {
						if ( Error[0].getAttribute("SessionExpired") == "1" )
						{
							alert("Session Key expired, please login again.");
							window.history.back();
						}
            if ( ErrorMessageTypeToPublish )
            {
              Gutenberg.PublishNow(ErrorMessageTypeToPublish,XmlResponse);
            }
            else
            {
              Gutenberg.PublishNow("Error",XmlResponse);
            }        
          }
          else
          {
            var Result = XmlResponse.GetElements("Result");
            this._SessionKey = Result[0].getAttribute("SessionKey");
            //Result = XmlResponse.GetElement ( "Memory", 0 );
            Gutenberg.PublishNow ( MessageTypeToPublish , XmlResponse );
          //  Gutenberg.PublishNow ( "LogThis" , "Server Memory: " + Result );

          }
        }
        else
        {
          XMLRequest.ServerWasNotFound(XmlHttp.statusText);
        }   
        break;
      default:
        alert ( "XML transmit error. State: " + xmlhttp.readyState );
        break;
    }
  } 
} 

Gutenberg.Subscribe ("Error" , ErrorHandler.XmlError );
Gutenberg.Subscribe ( "Initialize1" , XMLRequest.Initialize );
