// Global Variables
var map = null;
var pinID = 1;
var serverName = "http://staging.blackboxlbs.com/";
//var serverName = "http://localhost:9080/";
var imageRoot= "Images/";
var browser = new Browser( );
var mapScrollX, mapScrollY;
var devices = new DeviceData( );


// Constructor for Browser Object
function Browser( )
{
   var userAgent
   var str, i

   this.engine = "unknown";
   this.version = null;

   userAgent = navigator.userAgent;

   if ( ( i = userAgent.indexOf( "MSIE" ) ) >= 0 )
   {
      this.engine = "MSIE";
      this.version = parseFloat( userAgent.substr( i + 4 ) );
   }
   else if ( ( i = userAgent.indexOf( "Netscape6/" ) ) >= 0 )
   {
      this.engine = "Netscape";
      this.version = parseFloat( userAgent.substr( i + 10 ) );
   }
   else if ( ( i = userAgent.indexOf( "Gecko" ) ) >= 0 )
   {
      this.engine = "Gecko";
      this.version = 6.1;
   }

   return;
}


function toggleLoadingMessage( )
{
    if ( document.getElementById("Loading") != null )
    {
        if ( document.getElementById("Loading").style.visibility != "visible" )
        {
            document.getElementById("Loading").style.visibility = "visible";
        }
        else
        {
            document.getElementById("Loading").style.visibility = "hidden";
        }
    }
}


function setLoading( id, isLoading )
{
   var element = document.getElementById( id );

   if ( element == null )
   {
      element = id;
   }

   if ( element != null )
   {
      if ( isLoading )
      {
         element.style.backgroundImage = "url( 'Images/Spinner-Green.gif' )"; 
         element.style.backgroundRepeat = "no-repeat";
         element.style.backgroundPosition = "center center";
      }
      else
      {
         element.style.backgroundImage = ""; 
         element.style.backgroundRepeat = "";
         element.style.backgroundPosition = "";
      }
   }
}


function initialise( )
{
    // Load a new virtual earth map of australia
    map = new VEMap( 'myMap' );
    map.LoadMap( new VELatLong(-27.68, 135.08) );
    map.AttachEvent( 'onclick', regionHandler );

    // Set the default measurement unit to kilometers
    map.SetScaleBarDistanceUnit( VEDistanceUnit.Kilometers );

    // Set the default tool
    setScrollTool( );

    // Hide the standard dashboard controls 
    map.HideDashboard( );
    
    // Display the login prompt
    showLogin( );
}


function parseDocument( docString )
{
    // Provides cross browser functionality for the retrieval of xml documents
    var retVal;

    if ( document.implementation.createDocument )
    {
        var parser = new DOMParser( );
        retVal = parser.parseFromString( docString, "text/xml" );
    }
    else if ( window.ActiveXObject )
    {
       retVal = new ActiveXObject( "Microsoft.XMLDOM" );
       retVal.async="false";
       retVal.loadXML( docString );
    }

    return retVal;
}


function buildRequest( )
{
    var request = null;

    // Attempt to build the request message
    if ( window.XMLHttpRequest )
    {
        request = new XMLHttpRequest( );
    }
    else if ( window.ActiveXObject )
    {
        request = new ActiveXObject( "Microsoft.XMLHTTP" );
    }

    return request;
}

function Parameter( name, value )
{
   return Parameter( name, value, "" );
}


function Parameter( name, value, group )
{
   this.name = name;
   this.value = value;
   this.group = group;

   return;
}

function ajaxCall( request, methodName, parameters, callback  )
{
    var messageBody = null;
    var currentGroup = "";

    // Netscape security checking (for development)
    if ( ( typeof netscape != 'undefined' ) && 
         ( serverName != "http://www.blackboxlbs.com/" ) )
    {
        try
        {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        }
        catch ( ex )
        {
            // Do nothing
        }            
    }

    if ( request != null )
    {
        if ( callback != null )
           request.onreadystatechange = callback;

        try
        {
           request.open( "POST", serverName + "BlackBoxWebservice/BlackBoxMiddleTier.asmx", true );
        }
        catch( ex )
        {
           request.open( "POST", "http://blackboxlbs.com/BlackBoxWebservice/BlackBoxMiddleTier.asmx", true );        
        }
        
        request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
        request.setRequestHeader( "Content-Type", "text/xml" )
        request.setRequestHeader( "SOAPAction", "http://www.blackboxlbs.com/" + methodName )
        
        // Build the message body
        messageBody =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        messageBody += "<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/\">\n";
        messageBody += "   <soap:Body>\n";
        messageBody += "      <" + methodName + " xmlns=\"http://www.blackboxlbs.com/\" ";

        // Handle the parameter list
        if ( parameters == null ) 
        {
           messageBody += "/>\n";
        }
        else
        {
           messageBody += ">\n";

           if( parameters.length != undefined ) 
           {
              if ( parameters[0] != null )
              {
                 // Assume we've recieved an array object
                 for ( i = 0; i < parameters.length; i++ )
                 {
                    if ( currentGroup != parameters[i].group )
                    {
                       // Close the current group
                       if ( ( currentGroup != "" ) )
                          messageBody += "         </" + currentGroup + ">\n";      
                          
                       // Store the new group and open the parameter set
                       if ( parameters[i].group != undefined )
                       {
                          currentGroup = parameters[i].group;
                          messageBody += "         <" + currentGroup + ">\n";
                       }
                    }
                 
                    // Apply indentation for groups
                    if ( currentGroup != "" )
                       messageBody += "   ";
                       
                    messageBody += "         <" + parameters[i].name + ">";
                    messageBody += parameters[i].value;
                    messageBody += "</" + parameters[i].name + ">\n";
                 }
                 
                 // Close the current group (if necessary)
                 if ( currentGroup != "" )
                    messageBody += "         </" + currentGroup + ">\n";
              }
           }
           else if ( parameters.name != undefined )
           {
              // Check if we've just been passed a single parameter object
              messageBody += "         <" + parameters.name + ">";
              messageBody += parameters.value;
              messageBody += "</" + parameters.name + ">\n";
           }
   
           messageBody += "      </" + methodName + ">\n";
        }

        messageBody += "   </soap:Body>\n";
        messageBody += "</soap:Envelope>";

        request.setRequestHeader( "Length", messageBody.length );
        request.send( messageBody );
    }
}


function nodeValue( xmlDoc, node )
{
   // Local Variables
   var retVal;

   try
   {
      retVal = xmlDoc.getElementsByTagName( node )[0].firstChild.nodeValue;
   }
   catch ( ex )
   {
      retVal = "";
   }

   return retVal;
}


function removeAllChildNodes( node )
{
   // Accept both node and string parameters
   if ( typeof(node) == "string" )
   {
      node = document.getElementById( node );
   }

   // Verify that we've been passed a valid reference and 
   // then remove all of the child nodes
   if( ( node != undefined ) && ( node != null ) )
   {
      var len = node.childNodes.length;
   
	while ( node.hasChildNodes( ) )
	{
	   node.removeChild( node.firstChild );
	}
   }
}

function showRoadMap( )
{
   map.SetMapStyle(VEMapStyle.Road);
}


function showAerialMap( )
{
   map.SetMapStyle(VEMapStyle.Hybrid);
}


function panMap( x, y )
{
   mapScrollX = x;
   mapScrollY = y;
   moveMap( );
   
   // Set a timeout on this event
   setTimeout( "moveMap( )", 100 );
}


function panToLatLong( latitude, longitude )
{
   // Local Variables
   var latLong = new VELatLong( latitude, longitude )

   map.PanToLatLong( latLong );
}


function moveMap( )
{
   if ( ( mapScrollX != null ) && ( mapScrollY != null ) )
   {
      map.Pan( mapScrollX, mapScrollY );

      // Set a timeout on this event
      setTimeout( "moveMap( )", 50 );
   }
}


function windowResize( )
{
   // Get the current map center
   var mapCenter = map.GetCenter( );
  
   // Find the browser window size
   var mapWidth = 0, mapHeight = 0;

   // Get the window size
   if ( typeof( window.innerWidth ) == 'number' )
   {
      // FireFox
      mapWidth = window.innerWidth;
      mapHeight = window.innerHeight;
   }     
   else if ( document.documentElement )
   {
      // IE 6.0+
      mapWidth = document.documentElement.clientWidth;
	  mapHeight = document.documentElement.clientHeight;
   }

   // Resize the map
   map.Resize( mapWidth, mapHeight );
   map.PanToLatLong( mapCenter );
}


function centerWindow( id )
{
   var element = document.getElementById( id );
   var width, height, x, y;

   if ( element == null )
   {
      element = id
   }
   
   try
   {
      if ( browser.engine != "MSIE" )
      {
         width = parseInt( element.style.width );
         height = parseInt( element.style.height );
      
         x = ( window.innerWidth - width ) / 2;
         y = ( window.innerHeight  - height ) / 2;
      }
      else
      {
         width = parseInt( element.style.width );
         height = parseInt( element.style.height );

         x = ( document.body.offsetWidth - width ) / 2;
         y = ( document.body.offsetHeight  - height ) / 2;     
      }
      
      // Update the elements x and y position
      element.style.left = ( x + "px" );
      element.style.top = ( y + "px" );
   }
   catch( ex )
   {
      // Eat the exception
      throw ex;
   }
}


function errorHandler( response )
{
   if ( response != null )
   {
      // Check for applicaiton error messages
      var items = response.getElementsByTagName( "sessionexpired" );
      
      if ( items.length > 0 )
      {
         doLogout( );
         
         setLoginMessage( "Session Expired" );
      }
   }
}


function showHelp( )
{
   // Local Variables
   var id = "HelpWindow";

   if ( document.getElementById( id ) != null )
   {
      // Initialise the login window
      centerWindow( id );
      
      // Display the login prompt
      document.getElementById( id ).style.visibility = "visible";
      
      // Grab Focus
      setWindowFocus( id );
   }
}


function closeHelp( )
{
   if ( document.getElementById("HelpWindow") != null )
   {
      // Display the login prompt
      document.getElementById("HelpWindow").style.visibility = "hidden";
   }
}


function zoomIn( )
{
   // Recenter the map
   map.SetCenter( map.GetCenter( ) );

   map.ZoomIn( );
}


function zoomOut( )
{  
   // Recenter the map
   map.SetCenter( map.GetCenter( ) );

   map.ZoomOut( );
}


function showBestMap( )
{
   // Local Variables
   var loc = new Array( );
   var deviceArray = devices.toArray( );
   var index = 0;

   // Gather the list of lats and longs
   for ( var i = 0; i < deviceArray.length; i++ )
   {
      var latitude = deviceArray[i].getLatitude( );
      var longitude = deviceArray[i].getLongitude( );
   
      if ( ( latitude != "" ) && ( longitude != "" ) )
      {
         loc[index] = new VELatLong( latitude , longitude );
         index++;
      }
   }

   // Pan and center the map
   if ( loc.length != 0 )      
   {
      map.SetMapView( loc );
   }
}
