function showReports( )
{
   // Local Variables
   var id = "ReportsWindow";
   var reports = document.getElementById( id );
   var left = parseInt( reports.style.left ) ;

   if ( reports != null )
   {
       // Center the reports window on first open
       if ( left == 0 )
       {
          centerWindow( id );
       }

      // Populate the form controls
      getGroupsLH( );
      cpReportLoadDeviceGroups( );

      // Set the default pane
      showLHReport( );

      reports.style.visibility = "visible";

      // Grab Focus
      setWindowFocus( id );
   }
}


function closeReports( )
{
   // Local Variables
   var reports = document.getElementById( "ReportsWindow" );

   if ( reports != null )
   {
      reports.style.visibility = "hidden";
      
      // Order the calendar control to close as well
      closeCalendar( );
   }
}


function getGroupsLH( id )
{
   var request = buildRequest( );

   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            var response = parseDocument( request.responseText );
            var GroupList = document.getElementById( "GroupSelectLH" );
            var items = response.getElementsByTagName( "group" );

            // Clear the list of all existing options
            GroupList.options.length = 0;

            if ( items.length > 0 )
            {    
               for ( var i = 0; i < items.length; i++ )
               {
                   var item = items[i];
                 
                   // Get the details of this map element
                   var id = nodeValue( item, "id" );
                   var name = nodeValue( item, "name" );

                   GroupList.options[i] = new Option( name, id );
               }

               getGroupMembersLH( );
            }
            else
            {
                errorHandler( response );
            }
         }
      }
   }

   // Initialise the parameter list
   var param = new Parameter( "SessionID", getSessionID( ) );

   ajaxCall( request, "GetDeviceGroups", param, callback );
}


function getGroupMembersLH( )
{
   var request = buildRequest( );
   var select = document.getElementById( "GroupSelectLH" );

   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
          if( request.status == 200 )
          { 
             var response = parseDocument( request.responseText );
             var items = response.getElementsByTagName( "groupmember" );
             var list = document.getElementById( "DeviceListLH" );

             // Remove the existing child nodes
             removeAllChildNodes( "DeviceListLH" );

             if ( items.length > 0 )
             {
                // Append the new collection of child nodes
                for ( var i = 0; i < items.length; i++ )
                {
                   var item = items[i];

                   // Create and initialise the new html elements
                   var control = document.createElement( "DIV" );
                   var checkbox = document.createElement( "INPUT" );
                   var label = document.createElement( "SPAN" );
                   control.className = "Device";
                   checkbox.type = "Checkbox";
                   checkbox.id = "DeviceSelectLH" + nodeValue( item, "id" );
                   checkbox.name = "DeviceSelectLH";
                   checkbox.value = nodeValue( item, "id" );
                
                   label.appendChild( document.createTextNode( nodeValue( item, "name" ) ) );

                   control.appendChild( checkbox );
                   control.appendChild( label );
                   list.appendChild( control );
                
                   // This must be done after the item is added to support IE
                   if ( nodeValue( item, "checked" ) == "True" )
                   {
                      checkbox.checked = true;
                   }
                }
             }
             else
             {
                errorHandler( response );
             }
          }
      }
   }
  
   try
   {
      var params = new Array(2);
      var groupID = select.options[ select.selectedIndex ].value;
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "GroupID", groupID );
   
      ajaxCall( request, "GetDeviceGroupMembers", params, callback );
   }
   catch ( ex )
   {
      // TODO: Throw a warning
   }
}


function showLHReport( )
{
   // Local Variables
   var paramPane = document.getElementById( "LocationHistoryParameters" );
   var completedPollPane = document.getElementById( "CompletedPollsParameters" );
   var accountUsagePane = document.getElementById( "AccountUsageReport" );
   var resultsPane = document.getElementById( "ResultsTab" );

   paramPane.style.display = "block";
   completedPollPane.style.display = "none";
   accountUsagePane.style.display = "none";
   resultsPane.style.display = "none";
}


function runLHReport( )
{
   // Local Variables
   var paramPane = document.getElementById( "LocationHistoryParameters" );
   var completedPollPane = document.getElementById( "CompletedPollsParameters" );
   var resultsPane = document.getElementById( "ResultsTab" );
   var accountUsagePane = document.getElementById( "AccountUsageReport" );
   var results = document.getElementById( "ReportResults" );
   var request = buildRequest( );

   // Define the callback function
   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
          if( request.status == 200 )
          { 
             var response = parseDocument( request.responseText );
             var items = response.getElementsByTagName( "locationdata" );
             var results = document.getElementById( "ReportResults" );

             if ( items.length > 0 )
             {
                // Create a table element and attach it to the results pabe
                var center = document.createElement( "CENTER" );
                var table = document.createElement( "TABLE" );
                table.style.width = "95%";
                center.appendChild( table );
                results.appendChild( center );

                var tb = document.createElement( "TBODY" );
                tb.id = "LH_Results";
                table.appendChild( tb );

                // Add the report header and start construction of the table
                table.className = "ReportTable";
                tb.appendChild( buildHeaderLH( ) );

                // Process the collection and build the table rows
                for ( var i = 0; i < items.length; i++ )
                {
                   var item = items[i];
                   var lookupID = nodeValue( item, "locationlookupid" );
                   var deviceLat = nodeValue( item, "latitude" );
                   var deviceLng = nodeValue( item, "longitude" );

                   // Create and initialise the new html elements
                   var row = document.createElement( "TR" );

                   // Populate the row with the data returned by the server
                   var actions = document.createElement( "TD" );
                   if ( ( deviceLat != "" ) && ( deviceLng != "" ) )
                   {
                      var selectDevice = document.createElement( "INPUT" );
                      selectDevice.id = "LHDevice_" + lookupID;
                      selectDevice.type = "checkbox";
                      selectDevice.onclick = "";
                      selectDevice.value = lookupID;
                      actions.appendChild( selectDevice );
                   }
                   actions.style.textAlign = "center";   
                   actions.className = "LocationHistoryData";
                   row.appendChild( actions );
                
                   var device = document.createElement( "TD" );
                   device.id = "LHDeviceName_" + lookupID;
                   device.innerText = nodeValue( item, "devicename" );
                   device.className = "LocationHistoryData";
                   row.appendChild( device );

                   var latitude = document.createElement( "TD" );
                   latitude.id = "LHLatitude_" + lookupID;
                   latitude.innerText = deviceLat;
                   latitude.className = "LocationHistoryData";
                   row.appendChild( latitude );

                   var longitude = document.createElement( "TD" );
                   longitude.id = "LHLongitude_" + lookupID;
                   longitude.innerText = deviceLng;
                   longitude.className = "LocationHistoryData";
                   row.appendChild( longitude );

                   var lookupdate = document.createElement( "TD" );
                   lookupdate.id = "LHLookupDate_" + lookupID;
                   lookupdate.innerText = nodeValue( item, "lookupdate" );
                   lookupdate.className = "LocationHistoryData";
                   row.appendChild( lookupdate );

                   var comments = document.createElement( "TD" );
                   comments.innerText = nodeValue( item, "comments" );
                   comments.className = "LocationHistoryData";
                   row.appendChild( comments );

                   var username = document.createElement( "TD" );
                   username.innerText = nodeValue( item, "username" );
                   username.className = "LocationHistoryData";
                   row.appendChild( username );

                   tb.appendChild( row );
                }

                // Get a reference to the command panel for the results pane
                var commandPanel = document.getElementById( "Results_CommandPanel" );
                removeAllChildNodes( "Results_CommandPanel" );

                // Add the buttons to the command panel
                var displayButton = document.createElement( "INPUT" );
                displayButton.value = "Display";
                displayButton.type = "Button";
                displayButton.className = "Button";
                displayButton.onclick = displaySelectedResultsLH;

                var buttonWrapper = document.createElement( "DIV" );
                buttonWrapper.style.position = "absolute";
                buttonWrapper.style.bottom = "0px";
                buttonWrapper.style.right = "0px";
                buttonWrapper.className = "Control";

                // Add the select all button to the command panel
                var selectAllWrapper = document.createElement( "DIV" );
                var selectAllDevices = document.createElement( "INPUT" );
                var selectAllText = document.createTextNode( "Select All" );
                selectAllDevices.onclick = resultsSelectAllLH;
                selectAllDevices.type = "Checkbox";
                selectAllDevices.id = "Results_SelectAllLH"

                // Add the append button to the command panel
                var appendWrapper = document.createElement( "DIV" );
                var appendDevices = document.createElement( "INPUT" );
                var appendText = document.createTextNode( "Add selected to current results" );
                appendDevices.checked = "checked";
                appendDevices.type = "Checkbox";
                appendDevices.id = "Results_AppendResultsLH"

                var checkboxWrapper = document.createElement( "DIV" );
                checkboxWrapper.style.position = "absolute";
                checkboxWrapper.style.bottom = "0px";
                checkboxWrapper.style.left = "0px";
                checkboxWrapper.className = "Control";


                // Display the new nodes
                buttonWrapper.appendChild( displayButton );
                appendWrapper.appendChild( appendDevices );
                appendWrapper.appendChild( appendText );
                selectAllWrapper.appendChild( selectAllDevices );
                selectAllWrapper.appendChild( selectAllText );
                checkboxWrapper.appendChild( selectAllWrapper );
                checkboxWrapper.appendChild( appendWrapper );
                commandPanel.appendChild( buttonWrapper );
                commandPanel.appendChild( checkboxWrapper );
              
                // Clear the loading flag
                setLoading( resultsPane, false );
             }
             else
             {
                // Call the error handler to deal with a potential session timeout
                errorHandler( response );

                // Clear the loading flag
                setLoading( resultsPane, false );

                // Ensure that the command buttons are absent
                var commandPanel = document.getElementById( "Results_CommandPanel" );
                removeAllChildNodes( "Results_CommandPanel" );

                // Inform the user that no data was returned
                var notice = document.createElement( "DIV" );
                var items = response.getElementsByTagName( "timeout" );

                // Determine the reason for the problem
                if ( items.length == 0 )
                {
                   notice.innerText = "There were no transactions recorded during this period.";
                }
                else
                {
                   notice.innerText = "The application server has timed out waiting for a " + 
                                      "response from the database.  Please try your request " + 
                                      "again with a more restrictive date range.";
                }

                notice.className = "Control";
                notice.style.width = "100%";
                results.appendChild( notice );
             }
          }
      }
   }


   if ( ( paramPane != null ) && ( resultsPane != null ) )
   {
      paramPane.style.display = "none";
      completedPollPane.style.display = "none";
      resultsPane.style.display = "block";
      accountUsagePane.style.display = "none";
 
      // Remove the existing child nodes
      removeAllChildNodes( "ReportResults" );
      setLoading( resultsPane, true );

      // Build the parameter list
      var params = new Array(3);
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "FromDate", valueOf( "LHFromDate" ) );
      params[2] = new Parameter( "ToDate", valueOf( "LHToDate" ) );
      var nextParam = 3;

      // Get the list of devices
      var deviceList = document.getElementById( "DeviceListLH" );
      var selectedDevices = deviceList.getElementsByTagName( "Input" );
      
      for ( var i = 0; i < selectedDevices.length; i++ )
      {
         var dev = selectedDevices[i];
         
         if ( dev.checked == true )
         {
            params[ nextParam ] = new Parameter( "long", dev.value, "DeviceData" );
            nextParam++;
         }
      }
      
      // Build up the AJAX Call
      ajaxCall( request, "GetLocationHistoryData", params, callback );
   }
}


function buildHeaderLH( )
{
   var header = document.createElement( "TR" );
   var tdAction = document.createElement( "TD" );
   var tdDevice = document.createElement( "TD" );
   var tdLatitude = document.createElement( "TD" );
   var tdLongitude = document.createElement( "TD" );
   var tdDate = document.createElement( "TD" );
   var tdComments = document.createElement( "TD" );
   var tdUser = document.createElement( "TD" );

   // Apply the relevant styles and populate the header elements
   tdAction.className = "ReportHeader";
   tdAction.innerText = "Select";
   tdDevice.className = "ReportHeader";
   tdDevice.innerText = "Device";
   tdLatitude.className = "ReportHeader";
   tdLatitude.innerText = "Latitude";
   tdLongitude.className = "ReportHeader";
   tdLongitude.innerText = "Longitude";
   tdDate.className = "ReportHeader";
   tdDate.innerText = "Date";
   tdComments.className = "ReportHeader";
   tdComments.innerText = "Comments";
   tdUser.className = "ReportHeader";
   tdUser.innerText = "User";

   // Append the table header elements
   header.appendChild( tdAction );
   header.appendChild( tdDevice );
   header.appendChild( tdLatitude );
   header.appendChild( tdLongitude );
   header.appendChild( tdDate );
   header.appendChild( tdComments );
   header.appendChild( tdUser );

   return header;
}


function valueOf( id )
{
   var element = document.getElementById( id );
   var retVal = "";
   
   if ( element != null )
   {
      retVal = element.value;
   }
   
   return retVal;
}


function displaySelectedResultsLH( )
{
   // Close the reports windw
   closeReports( );
   
   // Display the selected location history elements
   var results = document.getElementById( "ReportResults" );
   var warning = document.getElementById( "DeviceWarning" );
   var deviceList = results.getElementsByTagName( "Input" );
 
   // Check to see if we need to clear the existing devices
   var clearAll = document.getElementById( "Results_AppendResultsLH" );
            
   if ( ( clearAll != null ) && ( ! clearAll.checked ) )
   {
      devices.clear( );
      warning.style.visibility = "hidden";
   }
   
   for ( var i = 0; i < deviceList.length; i++ )
   {
      var device = deviceList[i];
      
      // Only display those devices marked for display
      if ( device.checked )
      {
         try
         {
            // Determine the device name
            var deviceID = device.value;

            var deviceName = document.getElementById( "LHDeviceName_" + deviceID ).innerText;
            var deviceLat  = document.getElementById( "LHLatitude_"   + deviceID ).innerText;
            var deviceLong = document.getElementById( "LHLongitude_"  + deviceID ).innerText;
            var lookupDate = document.getElementById( "LHLookupDate_" + deviceID ).innerText;

            // Add a push-pin to the map
            var deviveObject = new Device( deviceName, "Historic Data", lookupDate, "HistoricData.gif", deviceLat, deviceLong, "" );
            devices.add( deviveObject );
         }
         catch( ex )
         {
            // TODO: Log an error
         }
      }
   }
   
   // Render the device collection
   devices.display( );
}


function showAUReport( )
{
   // Local Variables
   var paramPane = document.getElementById( "LocationHistoryParameters" );
   var completedPollPane = document.getElementById( "CompletedPollsParameters" );
   var accountUsagePane = document.getElementById( "AccountUsageReport" );
   var resultsPane = document.getElementById( "ResultsTab" );
   var request = buildRequest( );

   // Define the callback function
   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
          if( request.status == 200 )
          { 
             var accountUsagePane = document.getElementById( "AccountUsageReport" );
             var response = parseDocument( request.responseText );
 
             // Remove all of the existing child nodes
             removeAllChildNodes( "AccountUsageReport" );
             
             // Create the layout for the account usage report
             var heading = document.createElement( "DIV" );
             heading.className = "Heading Control";
             heading.innerText = "Account Usage Report";
             accountUsagePane.appendChild( heading );
 
             var items = response.getElementsByTagName( "accountusage" );

             if ( items.length > 0 )
             {
                var current = nodeValue( items[0], "currentlookups" );
                var remaining = nodeValue( items[0], "remaininglookups" );
                var total = nodeValue( items[0], "totallookups" );
                
                var wrapper = document.createElement( "DIV" );
                wrapper.className = "Control";
                accountUsagePane.appendChild( wrapper );
                
                var table = document.createElement( "TABLE" );
                table.className = "AccountUsageTable";
                wrapper.appendChild( table );
                
                var tbody = document.createElement( "TBODY" );
                table.appendChild( tbody );
                
                // Create the second row
                var row1 = document.createElement( "TR" );
                tbody.appendChild( row1 );
                
                var remHeader = document.createElement( "TD" );
                remHeader.className = "AccountUsageHeader";
                remHeader.innerText = "Lookups Remaining";
                row1.appendChild( remHeader );

                var remData = document.createElement( "TD" );
                remData.className = "AccountUsageData";
                remData.innerText = remaining;
                row1.appendChild( remData );

                // Create the first row
                var row2 = document.createElement( "TR" );
                tbody.appendChild( row2 );
                
                var curHeader = document.createElement( "TD" );
                curHeader.className = "AccountUsageHeader";
                curHeader.innerText = "Lookups Used To Date";
                row2.appendChild( curHeader );

                var curData = document.createElement( "TD" );
                curData.className = "AccountUsageData";
                curData.innerText = current;
                row2.appendChild( curData );

                // Create the third row
                var row3 = document.createElement( "TR" );
                tbody.appendChild( row3 );
                
                var ttlHeader = document.createElement( "TD" );
                ttlHeader.className = "AccountUsageHeader";
                ttlHeader.innerText = "Total";
                row3.appendChild( ttlHeader );

                var ttlData = document.createElement( "TD" );
                ttlData.className = "AccountUsageData";
                ttlData.innerText = total;
                row3.appendChild( ttlData );
             }
          }
      }
   }

   // Build up the parameter list
   param = new Parameter( "SessionID", getSessionID( ) );

   // Build up the AJAX Call
   ajaxCall( request, "GetAccountUsageData", param, callback );

   // Change the display mode
   paramPane.style.display = "none";
   completedPollPane.style.display = "none";
   accountUsagePane.style.display = "block";
   resultsPane.style.display = "none";
}


function showCPReport( )
{
   // Local Variables
   var paramPane = document.getElementById( "LocationHistoryParameters" );
   var completedPollPane = document.getElementById( "CompletedPollsParameters" );
   var accountUsagePane = document.getElementById( "AccountUsageReport" );
   var resultsPane = document.getElementById( "ResultsTab" );

   paramPane.style.display = "none";
   completedPollPane.style.display = "block";
   accountUsagePane.style.display = "none";
   resultsPane.style.display = "none";
}


function cpReportLoadDeviceGroups( )
{
   var request = buildRequest( );

   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            var response = parseDocument( request.responseText );
            var GroupList = document.getElementById( "Reports_GroupSelectCP" );
            var items = response.getElementsByTagName( "group" );

            // Clear the list of all existing options
            GroupList.options.length = 0;

            if ( items.length > 0 )
            {    
               for ( var i = 0; i < items.length; i++ )
               {
                   var item = items[i];
                 
                   // Get the details of this map element
                   var id = nodeValue( item, "id" );
                   var name = nodeValue( item, "name" );

                   GroupList.options[i] = new Option( name, id );
               }

               cpReportLoadScheduleList( );
            }
            else
            {
                errorHandler( response );
            }
         }
      }
   }

   // Initialise the parameter list
   var param = new Parameter( "SessionID", getSessionID( ) );

   ajaxCall( request, "GetDeviceGroups", param, callback );
}


function cpReportLoadScheduleList( )
{
   // Local Variables
   var select = document.getElementById( "Reports_GroupSelectCP" );
   
   // Store the current selection
   scheduleFindGroup = select.options[ select.selectedIndex ].innerText;
   
   if ( select != null )
   {
      var value = select.options[ select.selectedIndex ].value;
      var request = buildRequest( );

      var callback = function( )
      {
         if ( request.readyState == 4 )
         {
            if( request.status == 200 )
            { 
               var response = parseDocument( request.responseText );
               var ScheduleList = document.getElementById( "Reports_ScheduleSelectCP" );
               var items = response.getElementsByTagName( "scheduledpoll" );

               // Clear and default the schedule list
               ScheduleList.options.length = 0;

               if ( items.length > 0 )
               {    
                  for ( var i = 0; i < items.length; i++ )
                  {
                     var item = items[i];
                 
                     // Get the details for the schedule
                     var id = nodeValue( item, "id" );
                     var name = nodeValue( item, "name" );
                     var desc = nodeValue( item, "description" )
                     var label = name + " - " + desc;

                     ScheduleList.options[i] = new Option( label, id );
                  }
               }
               else
               {
                  errorHandler( response );
               }
               
               // Update the select list for poll dates
               cpReportLoadPollDates( );
            }
         }
      }

      // Build up the parameter list and execute the remote method
      var params = new Array(2);
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "GroupID", value );

      ajaxCall( request, "GetScheduledPolls", params, callback );
   }
}


function cpReportLoadPollDates( )
{
   // Local Variables
   var select = document.getElementById( "Reports_ScheduleSelectCP" );
   
   // Store the current selection
   if ( select.selectedIndex >= 0 )
   {
      scheduleToFind = select.options[ select.selectedIndex ].innerText;
   
      if ( select != null )
      {
         var value = select.options[ select.selectedIndex ].value;
         var request = buildRequest( );

         var callback = function( )
         {
            if ( request.readyState == 4 )
            {
               if( request.status == 200 )
               { 
                  var response = parseDocument( request.responseText );
                  var DateList = document.getElementById( "Reports_DateSelectCP" );
                  var items = response.getElementsByTagName( "polldate" );

                  // Clear and default the schedule list
                  DateList.options.length = 0;

                  if ( items.length > 0 )
                  {    
                     for ( var i = 0; i < items.length; i++ )
                     {
                        var item = items[i];
                    
                        // Get the details for the schedule
                        var date = nodeValue( item, "date" );

                        DateList.options[i] = new Option( date, date );
                     }
                  }
                  else
                  {
                     errorHandler( response );
                  }
               }
            }
         }

         // Build up the parameter list and execute the remote method
         var params = new Array(2);
         params[0] = new Parameter( "SessionID", getSessionID( ) );
         params[1] = new Parameter( "ScheduleID", value );

         ajaxCall( request, "GetScheduledPollDates", params, callback );
      }
   }
   else
   {
      // Get a reference to the screen control
      var DateList = document.getElementById( "Reports_DateSelectCP" );

      // Clear and default the schedule list
      DateList.options.length = 0;      
   }
}


function runCPReport( )
{
   // Local Variables
   var scheduleSelect = document.getElementById( "Reports_ScheduleSelectCP" );
   var dateSelect = document.getElementById( "Reports_DateSelectCP" );
   var paramPane = document.getElementById( "LocationHistoryParameters" );
   var completedPollPane = document.getElementById( "CompletedPollsParameters" );
   var accountUsagePane = document.getElementById( "AccountUsageReport" );
   var resultsPane = document.getElementById( "ResultsTab" );

   if ( ( scheduleSelect.selectedIndex >= 0 ) && ( dateSelect.selectedIndex >= 0 ) )
   {
      // Generate the report results
      var request = buildRequest( );

      var callback = function( )
      {
         if ( request.readyState == 4 )
         {
            if( request.status == 200 )
            { 
               buildCPReport( request.responseText );
            }
         }
      }

      if ( ( paramPane != null ) && ( resultsPane != null ) )
      {
         paramPane.style.display = "none";
         completedPollPane.style.display = "none";
         resultsPane.style.display = "block";
         accountUsagePane.style.display = "none";
 
         // Remove the existing child nodes
         removeAllChildNodes( "ReportResults" );
         setLoading( resultsPane, true );

         // Calculate the values to be passed to the web service
         var scheduleID = scheduleSelect.options[ scheduleSelect.selectedIndex ].value;
         var pollDate = dateSelect.options[ dateSelect.selectedIndex ].value;
   
         // Build up the parameter list and execute the remote method
         var params = new Array(3);
         params[0] = new Parameter( "SessionID", getSessionID( ) );
         params[1] = new Parameter( "ScheduleID", scheduleID );
         params[2] = new Parameter( "PollDate", pollDate );

         // Call the AJAX method
         ajaxCall( request, "GetScheduledPollData", params, callback );      
      }
   }
   else
   {
      alert( "You must select a schedule poll group before you can view it's results." );
   }
}


function buildCPReport( responseData )
{
   var response = parseDocument( responseData );
   var items = response.getElementsByTagName( "poll" );
   var results = document.getElementById( "ReportResults" );
   var resultsPane = document.getElementById( "ResultsTab" );

   if ( items.length > 0 )
   {
      // Create a table element and attach it to the results pabe
      var center = document.createElement( "CENTER" );
      var table = document.createElement( "TABLE" );
      table.style.width = "95%";
      center.appendChild( table );
      results.appendChild( center );

      var tb = document.createElement( "TBODY" );
      table.appendChild( tb );

      // Add the report header and start construction of the table
      table.className = "ReportTable";
      tb.id = "CP_Results";
      tb.appendChild( buildHeaderLH( ) );

      // Process the collection and build the table rows
      for ( var i = 0; i < items.length; i++ )
      {
         var item = items[i];
         var pollID = nodeValue( item, "id" );
         var deviceLat = nodeValue( item, "latitude" );
         var deviceLng = nodeValue( item, "longitude" );

         // Create and initialise the new html elements
         var row = document.createElement( "TR" );

         // Populate the row with the data returned by the server
         var actions = document.createElement( "TD" );
         if ( ( deviceLat != "0" ) && ( deviceLng != "0" ) )
         {
            var selectDevice = document.createElement( "INPUT" );
            selectDevice.type = "checkbox";
            selectDevice.onclick = "";
            selectDevice.value = pollID;
            actions.appendChild( selectDevice );
         }
         actions.style.textAlign = "center";   
         actions.className = "LocationHistoryData";
         row.appendChild( actions );
                
         var device = document.createElement( "TD" );
         device.id = "CPDeviceName_" + pollID;
         device.innerText = nodeValue( item, "device" );
         device.className = "LocationHistoryData";
         row.appendChild( device );

         var latitude = document.createElement( "TD" );
         latitude.id = "CPLatitude_" + pollID;
         latitude.innerText = deviceLat;
         latitude.className = "LocationHistoryData";
         row.appendChild( latitude );

         var longitude = document.createElement( "TD" );
         longitude.id = "CPLongitude_" + pollID;
         longitude.innerText = deviceLng;
         longitude.className = "LocationHistoryData";
         row.appendChild( longitude );

         var lookupdate = document.createElement( "TD" );
         lookupdate.id = "CPLookupDate_" + pollID;
         lookupdate.innerText = nodeValue( item, "date" );
         lookupdate.className = "LocationHistoryData";
         row.appendChild( lookupdate );

         var comments = document.createElement( "TD" );
         comments.innerText = nodeValue( item, "comment" );
         comments.className = "LocationHistoryData";
         row.appendChild( comments );

         var username = document.createElement( "TD" );
         username.innerText = "Autopoll";
         username.className = "LocationHistoryData";
         row.appendChild( username );

         tb.appendChild( row );
      }

      // Get a reference to the command panel for the results pane
      var commandPanel = document.getElementById( "Results_CommandPanel" );
      removeAllChildNodes( "Results_CommandPanel" );

      // Add the buttons to the command panel
      var displayButton = document.createElement( "INPUT" );
      displayButton.value = "Display";
      displayButton.type = "Button";
      displayButton.className = "Button";
      displayButton.onclick = displaySelectedResultsCP;

      var buttonWrapper = document.createElement( "DIV" );
      buttonWrapper.style.position = "absolute";
      buttonWrapper.style.bottom = "0px";
      buttonWrapper.style.right = "0px";
      buttonWrapper.className = "Control";

      // Add the select all button to the command panel
      var selectAllWrapper = document.createElement( "DIV" );
      var selectAllDevices = document.createElement( "INPUT" );
      var selectAllText = document.createTextNode( "Select All" );
      selectAllDevices.onclick = resultsSelectAllCP;
      selectAllDevices.type = "Checkbox";
      selectAllDevices.id = "Results_SelectAllCP"

      // Add the append button to the command panel
      var appendWrapper = document.createElement( "DIV" );
      var appendDevices = document.createElement( "INPUT" );
      var appendText = document.createTextNode( "Add to current results" );
      appendDevices.checked = "checked";
      appendDevices.type = "Checkbox";
      appendDevices.id = "Results_AppendResultsCP"

      var checkboxWrapper = document.createElement( "DIV" );
      checkboxWrapper.style.position = "absolute";
      checkboxWrapper.style.bottom = "0px";
      checkboxWrapper.style.left = "0px";
      checkboxWrapper.className = "Control";


      // Display the new nodes
      buttonWrapper.appendChild( displayButton );
      selectAllWrapper.appendChild( selectAllDevices );
      selectAllWrapper.appendChild( selectAllText );
      appendWrapper.appendChild( appendDevices );
      appendWrapper.appendChild( appendText );
      checkboxWrapper.appendChild( selectAllWrapper );
      checkboxWrapper.appendChild( appendWrapper );
      commandPanel.appendChild( buttonWrapper );
      commandPanel.appendChild( checkboxWrapper );

      // Clear the loading flag
      setLoading( resultsPane, false );
   }
   else
   {
      // Call the error handler to deal with a potential session timeout
      errorHandler( response );

      // Clear the loading flag
      setLoading( resultsPane, false );

      // Ensure that the command buttons are absent
      var commandPanel = document.getElementById( "Results_CommandPanel" );
      removeAllChildNodes( "Results_CommandPanel" );

      // Inform the user that no data was returned
      var notice = document.createElement( "DIV" );
      var items = response.getElementsByTagName( "timeout" );

      // Determine the reason for the problem
      notice.innerText = "The application server has timed out waiting for a " + 
                         "response from the database.  Please try your request " + 
                         "again with a more restrictive date range.";
      notice.className = "Control";
      notice.style.width = "100%";
      results.appendChild( notice );
   }
}


function displaySelectedResultsCP( )
{
   // Close the reports windw
   closeReports( );
   
   // Display the selected location history elements
   var results = document.getElementById( "ReportResults" );
   var warning = document.getElementById( "DeviceWarning" );
   var deviceList = results.getElementsByTagName( "Input" );
 
   // Check to see if we need to clear the existing devices
   var clearAll = document.getElementById( "Results_AppendResultsCP" );
            
   if ( ( clearAll != null ) && ( ! clearAll.checked ) )
   {
      devices.clear( );
      warning.style.visibility = "hidden";
   }
   
   for ( var i = 0; i < deviceList.length; i++ )
   {
      var device = deviceList[i];
      
      // Only display those devices marked for display
      if ( device.checked )
      {
         try
         {
            // Determine the device name
            var deviceID = device.value;

            var deviceName = document.getElementById( "CPDeviceName_" + deviceID ).innerText;
            var deviceLat  = document.getElementById( "CPLatitude_"   + deviceID ).innerText;
            var deviceLong = document.getElementById( "CPLongitude_"  + deviceID ).innerText;
            var lookupDate = document.getElementById( "CPLookupDate_" + deviceID ).innerText;

            // Add a push-pin to the map
            var deviveObject = new Device( deviceName, "Scheduled Poll", lookupDate, "Salesman.gif", deviceLat, deviceLong, "" );
            devices.add( deviveObject );
         }
         catch( ex )
         {
            // TODO: Log an error
         }
      }
   }
   
   // Render the device collection
   devices.display( );
}


function selectAllLH( )
{
   var findAll = document.getElementById( "Params_SelectAllLH" );
   var resultList = document.getElementById( "DeviceListLH" );
   var devices = resultList.getElementsByTagName( "input" );
   
   for ( var i = 0; i < devices.length; i++ )
   {
      if ( devices[i].checked != findAll.checked ) 
      {
         devices[i].checked = findAll.checked;
      }
   }
}


function resultsSelectAllLH( )
{
   var findAll = document.getElementById( "Results_SelectAllLH" );
   var resultList = document.getElementById( "LH_Results" );
   var devices = resultList.getElementsByTagName( "input" );
   
   for ( var i = 0; i < devices.length; i++ )
   {
      if ( devices[i].checked != findAll.checked ) 
      {
         devices[i].checked = findAll.checked;
      }
   }
}


function resultsSelectAllCP( )
{
   var findAll = document.getElementById( "Results_SelectAllCP" );
   var resultList = document.getElementById( "CP_Results" );
   var devices = resultList.getElementsByTagName( "input" );
   
   for ( var i = 0; i < devices.length; i++ )
   {
      if ( devices[i].checked != findAll.checked ) 
      {
         devices[i].checked = findAll.checked;
      }
   }
}
