﻿// Global Variables
var optionsFindGroup = "";
var scheduleFindGroup = "";


function showOptions( )
{
   // Local Variables
   var id = "OptionsWindow";
   var options = document.getElementById( id );
   var left = parseInt( options.style.left ) ;

   if ( options != null )
   {
      // Center the reports window on first open
      if ( left == 0 )
      {
         centerWindow( id );
      }

      // Clear the schedule form
      clearSchedule( );
 
      // Populate the schedule time select lists
      schedulePopulateDropdown( );

      // Populate the default group lists
      optionsGetDeviceGroups( );
      scheduleGetDeviceGroups( );

      // Set the default pane
      showDeviceGroupOptions( );
      showHourlySchedule( );

      options.style.visibility = "visible";

      // Grab Focus
      setWindowFocus( id );
   }
}


function closeOptions( )
{
   // Local Variables
   var options = document.getElementById( "OptionsWindow" );
   var DeviceGroupsPane = document.getElementById( "Options_DeviceGroups" );
   var AutoPollPane = document.getElementById( "Options_AutoPoll" );

   if ( options != null )
   {
      options.style.visibility = "hidden";

      // Fix for IE 6.0
      DeviceGroupsPane.style.visibility = "hidden";
      AutoPollPane.style.visibility = "hidden";
   }
}


function showDeviceGroupOptions( )
{
   // Local Variables
   var DeviceGroupsPane = document.getElementById( "Options_DeviceGroups" );
   var AutoPollPane = document.getElementById( "Options_AutoPoll" );

   DeviceGroupsPane.style.display = "block";
   DeviceGroupsPane.style.visibility = "visible";
   AutoPollPane.style.display = "none";
   AutoPollPane.style.visibility = "hidden";
}


function showAutoPollOptions( )
{
   // Local Variables
   var DeviceGroupsPane = document.getElementById( "Options_DeviceGroups" );
   var AutoPollPane = document.getElementById( "Options_AutoPoll" );

   DeviceGroupsPane.style.display = "none";
   DeviceGroupsPane.style.visibility = "hidden";
   AutoPollPane.style.display = "block";
   AutoPollPane.style.visibility = "visible";
}


function showHourlySchedule( )
{
   // Local Variables
   var SchedHourly = document.getElementById( "Options_ScheduleHourly" );
   var SchedDaily  = document.getElementById( "Options_ScheduleDaily" );
   var SchedWeekly = document.getElementById( "Options_ScheduleWeekly" );
   var SchedOnce   = document.getElementById( "Options_ScheduleOnce" );

   SchedHourly.style.display = "block";
   SchedDaily.style.display  = "none";
   SchedWeekly.style.display = "none";
   SchedOnce.style.display   = "none";
}


function showDailySchedule( )
{
   // Local Variables
   var SchedHourly = document.getElementById( "Options_ScheduleHourly" );
   var SchedDaily  = document.getElementById( "Options_ScheduleDaily" );
   var SchedWeekly = document.getElementById( "Options_ScheduleWeekly" );
   var SchedOnce   = document.getElementById( "Options_ScheduleOnce" );

   SchedHourly.style.display = "none";
   SchedDaily.style.display  = "block";
   SchedWeekly.style.display = "none";
   SchedOnce.style.display   = "none";
}


function showWeeklySchedule( )
{
   // Local Variables
   var SchedHourly = document.getElementById( "Options_ScheduleHourly" );
   var SchedDaily  = document.getElementById( "Options_ScheduleDaily" );
   var SchedWeekly = document.getElementById( "Options_ScheduleWeekly" );
   var SchedOnce   = document.getElementById( "Options_ScheduleOnce" );

   SchedHourly.style.display = "none";
   SchedDaily.style.display  = "none";
   SchedWeekly.style.display = "block";
   SchedOnce.style.display   = "none";
}

function showOnceSchedule( )
{
   // Local Variables
   var SchedHourly = document.getElementById( "Options_ScheduleHourly" );
   var SchedDaily  = document.getElementById( "Options_ScheduleDaily" );
   var SchedWeekly = document.getElementById( "Options_ScheduleWeekly" );
   var SchedOnce   = document.getElementById( "Options_ScheduleOnce" );

   SchedHourly.style.display = "none";
   SchedDaily.style.display  = "none";
   SchedWeekly.style.display = "none";
   SchedOnce.style.display   = "block";
}


function optionsGetDeviceGroups( )
{
   var request = buildRequest( );

   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            var response = parseDocument( request.responseText );
            var GroupList = document.getElementById( "Options_GroupSelect" );
            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" );

                   // Replace the "all devices" group with an option to 
                   // create a new group
                   if ( id == -1 )
                   {
                      name = "Create New Device Group";
                   }
                   
                   GroupList.options[i] = new Option( name, id );
                   
                   if ( name == optionsFindGroup )
                   {
                      GroupList.selectedIndex = i;
                   }
               }

               optionsLoadGroupData( );
            }
            else
            {
                errorHandler( response );
            }
         }
      }
   }

   // Initialise the parameter list
   var param = new Parameter( "SessionID", getSessionID( ) );

   ajaxCall( request, "GetDeviceGroups", param, callback );
}


function optionsLoadGroupData( )
{
   // Defer processing to the relevant functions
   // TODO: Load the information about this group
   loadGroupDetails( );

   // Load the list of devices associated with the group
   loadSelectedGroupData( );
   loadAllDevices( );
}


function loadGroupDetails( )
{
   // Local Variables
   var select = document.getElementById( "Options_GroupSelect" );
   
   if ( select != null )
   {
      var value = select.options[ select.selectedIndex ].value;

      // Store the current selection
      optionsFindGroup = select.options[ select.selectedIndex ].innerText;
      
      if ( value != -1 )
      {
         var request = buildRequest( );

         var callback = function( )
         {
            if ( request.readyState == 4 )
            {
               if( request.status == 200 )
               { 
                  var response = parseDocument( request.responseText );
                  var items = response.getElementsByTagName( "group" );
                  var deviceName = document.getElementById( "Options_GroupName" );
                  var deviceDesc = document.getElementById( "Options_GroupDesc" );

                  if ( items.length > 0 )
                  {
                     var item = items[0];
                  
                     // Read off the values and place them into the text fields
                     deviceName.value = nodeValue( item, "name" );
                     deviceDesc.value = nodeValue( item, "description" );
                  }
                  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( "GroupID", value );
   
         ajaxCall( request, "GetDeviceGroupDetails", params, callback );
      }
      else
      {
         // The user is attempting to create a new device group, clear the entry
         var deviceName = document.getElementById( "Options_GroupName" );
         var deviceDesc = document.getElementById( "Options_GroupDesc" );

         deviceName.value = "";
         deviceDesc.value = "";
      }
   }
}


function loadSelectedGroupData( )
{
   // Local Variables
   var select = document.getElementById( "Options_GroupSelect" );
   
   if ( select != null )
   {
      var value = select.options[ select.selectedIndex ].value;

      if ( value != -1 )
      {
         var request = buildRequest( );
         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( "Options_GroupMembers" );

                  // Remove the existing child nodes
                  removeAllChildNodes( "Options_GroupMembers" );

                  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 device = document.createElement( "OPTION" );
                        device.innerText = nodeValue( item, "name" );
                        device.value = nodeValue( item, "id" );
                
                        list.appendChild( device );
                     }
                  }
                  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( "GroupID", value );
   
         ajaxCall( request, "GetDeviceGroupMembers", params, callback );
      }
      else
      {
         // This is a default group so just remove all the children
         removeAllChildNodes( "Options_GroupMembers" );
      }
   }
}


function loadAllDevices( )
{
   var request = buildRequest( );
   var select = document.getElementById( "Options_GroupSelect" );

   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( "Options_UserDevices" );

             // Remove the existing child nodes
             removeAllChildNodes( "Options_UserDevices" );

             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 device = document.createElement( "OPTION" );
                   device.innerText = nodeValue( item, "name" );
                   device.value = nodeValue( item, "id" );
                
                   list.appendChild( device );
                }
             }
             else
             {
                errorHandler( response );
             }
          }
      }
   }
  
   var params = new Array(2);
   params[0] = new Parameter( "SessionID", getSessionID( ) );
   params[1] = new Parameter( "GroupID", "-1" );
   
   ajaxCall( request, "GetDeviceGroupMembers", params, callback );
}

function UpdateDeviceGroup( )
{
   var group = document.getElementById( "Options_GroupSelect" );
   var groupName = document.getElementById( "Options_GroupName" );
   var groupDesc = document.getElementById( "Options_GroupDesc" );
   var index = group.selectedIndex;   

   var request = buildRequest( );   

   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
          if( request.status == 200 )
          { 
             var group = document.getElementById( "Options_GroupSelect" );
             var index = group.selectedIndex;   

             // Only process the following code when we are creating a new group
             if ( index == 0 )
             {             
                // Get the name of the current group
                optionsFindGroup = document.getElementById( "Options_GroupName" ).value;

                // Reload the drop down
                optionsGetDeviceGroups( );           
             }
          }
      }
   }
   
   var params = new Array(4);
   params[0] = new Parameter( "SessionID", getSessionID( ) );
   params[1] = new Parameter( "GroupID",   group.options[ index ].value );
   params[2] = new Parameter( "GroupName",  groupName.value );
   params[3] = new Parameter( "GroupDescription",  groupDesc.value );
   
   ajaxCall( request, "SetDeviceGroupDetails", params, callback );
}


function addDeviceToGroup( )
{
   var allDevices = document.getElementById( "Options_UserDevices" );
   var group = document.getElementById( "Options_GroupSelect" );
   var index = allDevices.selectedIndex;
   
   if ( index != -1 )
   {
      var request = buildRequest( );   

      var callback = function( )
      {
         if ( request.readyState == 4 )
         {
             if( request.status == 200 )
             { 
                loadSelectedGroupData( );
             }
         }
      }
  
      var params = new Array(3);
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "GroupID",   group.options[ group.selectedIndex ].value);
      params[2] = new Parameter( "DeviceID",  allDevices.options[ index ].value );
   
      ajaxCall( request, "AddDeviceGroupMember", params, callback );
   }
   else
   {
      alert( "You must save your new group before you can add devices to it." );
   }
}


function removeDeviceFromGroup( )
{
   var groupDevices = document.getElementById( "Options_GroupMembers" );
   var group = document.getElementById( "Options_GroupSelect" );
   var index = groupDevices.selectedIndex;
   
   if ( index != -1 )
   {
      var request = buildRequest( );   

      var callback = function( )
      {
         if ( request.readyState == 4 )
         {
             if( request.status == 200 )
             { 
                loadSelectedGroupData( );
             }
         }
      }
  
      var params = new Array(3);
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "GroupID",   group.options[ group.selectedIndex ].value);
      params[2] = new Parameter( "DeviceID",  groupDevices.options[ index ].value );
   
      ajaxCall( request, "RemoveDeviceGroupMember", params, callback );
   }
   else
   {
      alert( "You must save your new group before you can add devices to it." );
   }
}


function clearSchedule( )
{
   // Local Variables
   var elIsHourly = document.getElementById( "Schedule_Hourly" );
   // Hourly
   var elStartTime   = document.getElementById( "Options_ScheduleHourlyStart" );
   var elEndTime     = document.getElementById( "Options_ScheduleHourlyEnd" );
   var elHourFreq    = document.getElementById( "Options_ScheduleHourlyFrequency" );
   // Daily
   var elDailyTime   = document.getElementById( "Options_ScheduleDailyTime" );
   var elEveryXDays  = document.getElementById( "Options_ScheduleDailyEveryXDays" );
   var elWeekdays    = document.getElementById( "Options_ScheduleDailyEveryWeekday" );
   // Weekly
   var elWeeklyTime  = document.getElementById( "Options_ScheduleWeeklyTime" );
   var elWeeklyFreq  = document.getElementById( "Options_ScheduleWeeklyFrequency" );
   var elOnSunday    = document.getElementById( "Options_ScheduleWeeklySunday" );
   var elOnMonday    = document.getElementById( "Options_ScheduleWeeklyMonday" );
   var elOnTuesday   = document.getElementById( "Options_ScheduleWeeklyTuesday" );
   var elOnWednesday = document.getElementById( "Options_ScheduleWeeklyWednesday" );
   var elOnThursday  = document.getElementById( "Options_ScheduleWeeklyThursday" );
   var elOnFriday    = document.getElementById( "Options_ScheduleWeeklyFriday" );
   var elOnSaturday  = document.getElementById( "Options_ScheduleWeeklySaturday" );

   // Initialise the variables
   elIsHourly.checked = true;
   showHourlySchedule( );
   elStartTime.selectedIndex = 0;
   elEndTime.selectedIndex = 0;
   elHourFreq.value = "";
   elDailyTime.selectedIndex = 0;
   elEveryXDays.checked = true;
   elWeekdays.value = "";
   elWeeklyTime.selectedIndex = 0;
   elWeeklyFreq.value = "";
   elOnSunday.checked = false;
   elOnMonday.checked = false;
   elOnTuesday.checked = false;
   elOnWednesday.checked = false;
   elOnThursday.checked = false;
   elOnFriday.checked = false;
   elOnSaturday.checked = false;
}


function schedulePopulateDropdown( )
{
   var StartTime  = document.getElementById( "Options_ScheduleHourlyStart" );
   var EndTime    = document.getElementById( "Options_ScheduleHourlyEnd" );
   var DailyTime  = document.getElementById( "Options_ScheduleDailyTime" );
   var WeeklyTime = document.getElementById( "Options_ScheduleWeeklyTime" );
   var time, hour, halfHour, index;
   index = 0;
   
   if ( StartTime.options.length == 0 )
   {
      for ( var i = 0; i < 24; i++ )
      {
         if ( i < 10 )
            time = "0" + i;
         else
            time = i;
            
         hour = time + ":00";
         halfHour = time + ":30";
         
         // Store the hour
         StartTime.options[index] = new Option( hour, hour );
         EndTime.options[index] = new Option( hour, hour );
         DailyTime.options[index] = new Option( hour, hour );
         WeeklyTime.options[index] = new Option( hour, hour );
         index++;

         // Store the Half Hour
         StartTime.options[index] = new Option( halfHour, halfHour );
         EndTime.options[index] = new Option( halfHour, halfHour );
         DailyTime.options[index] = new Option( halfHour, halfHour );
         WeeklyTime.options[index] = new Option( halfHour, halfHour );
         index++;
      } 
   
   }
}


function scheduleGetDeviceGroups( )
{
   var request = buildRequest( );

   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            var response = parseDocument( request.responseText );
            var GroupList = document.getElementById( "Options_ScheduleGroupSelect" );
            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" );

                   // Replace the "all devices" with a message to
                   // force group selection
                   if ( id == -1 )
                   {
                      name = "*** Select Device Group ***";
                   }

                   GroupList.options[i] = new Option( name, id );
                   
                   if ( name == scheduleFindGroup )
                   {
                      GroupList.selectedIndex = i;
                   }
               }

               optionsLoadScheduleList( );
            }
            else
            {
                errorHandler( response );
            }
         }
      }
   }

   // Initialise the parameter list
   var param = new Parameter( "SessionID", getSessionID( ) );

   ajaxCall( request, "GetDeviceGroups", param, callback );
}


function optionsLoadScheduleList( )
{
   // Local Variables
   var select = document.getElementById( "Options_ScheduleGroupSelect" );
   
   // 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( "Options_ScheduleIdSelect" );
               var items = response.getElementsByTagName( "scheduledpoll" );

               // Clear and default the schedule list
               ScheduleList.options.length = 0;
               ScheduleList.options[0] = new Option( "Create New Schedule", "-1" );

               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" );

                     ScheduleList.options[i + 1] = new Option( name, id );
                  }
               }
               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( "GroupID", value );

      ajaxCall( request, "GetScheduledPolls", params, callback );
   }
}


function buildDayList( sunday, monday, tuesday, wednesday, thursday, friday, saturday )
{
   // Local Variables
   var days;

   if ( sunday )
      days = "Sunday";
   else
      days = "";

   if ( monday )
   {
      if ( days != "" )
         days += ", ";
         
      days += "Monday";
   }
      
   if ( tuesday )
   {
      if ( days != "" )
         days += ", ";
        
      days += "Tuesday";
   }

   if ( wednesday )
   {
      if ( days != "" )
         days += ", ";
         
      days += "Wednesday";
   } 

   if ( thursday )
   {
      if ( days != "" )
         days += ", ";
         
      days += "Thursday";
   } 

   if ( friday )
   {
      if ( days != "" )
         days += ", ";
         
      days += "Friday";
   } 

   if ( saturday )
   {
      if ( days != "" )
         days += ", ";
         
      days += "Saturday";
   } 
      
   return days;
}


function UpdateSchedule( )
{
   // Get a reference to each of the form elements
   var elGroupID     = document.getElementById( "Options_ScheduleGroupSelect" );
   var elScheduleID  = document.getElementById( "Options_ScheduleIdSelect" );
   var elIsHourly    = document.getElementById( "Schedule_Hourly" );
   var elIsDaily     = document.getElementById( "Schedule_Daily" );
   var elIsWeekly    = document.getElementById( "Schedule_Weekly" );
   var elIsOnce      = document.getElementById( "Schedule_Once" );   
   // Hourly
   var elStartTime   = document.getElementById( "Options_ScheduleHourlyStart" );
   var elEndTime     = document.getElementById( "Options_ScheduleHourlyEnd" );
   var elHourFreq    = document.getElementById( "Options_ScheduleHourlyFrequency" );
   // Daily
   var elDailyTime   = document.getElementById( "Options_ScheduleDailyTime" );
   var elEveryXDays  = document.getElementById( "Options_ScheduleDailyEveryXDays" );
   var elDailyFreq   = document.getElementById( "Options_ScheduleDailyFrequency" );
   var elWeekdays    = document.getElementById( "Options_ScheduleDailyEveryWeekday" );
   // Weekly
   var elWeeklyTime  = document.getElementById( "Options_ScheduleWeeklyTime" );
   var elWeeklyFreq  = document.getElementById( "Options_ScheduleWeeklyFrequency" );
   var elOnSunday    = document.getElementById( "Options_ScheduleWeeklySunday" );
   var elOnMonday    = document.getElementById( "Options_ScheduleWeeklyMonday" );
   var elOnTuesday   = document.getElementById( "Options_ScheduleWeeklyTuesday" );
   var elOnWednesday = document.getElementById( "Options_ScheduleWeeklyWednesday" );
   var elOnThursday  = document.getElementById( "Options_ScheduleWeeklyThursday" );
   var elOnFriday    = document.getElementById( "Options_ScheduleWeeklyFriday" );
   var elOnSaturday  = document.getElementById( "Options_ScheduleWeeklySaturday" );

   // Get the current value of the common form elements
   var groupID = elGroupID.options[ elGroupID.selectedIndex ].value;
   
   if ( groupID != -1 )
   {
      // Determine the schedule id
      var scheduleID;
      if ( elScheduleID.options.length == 0 ) // We should never enter this 
         scheduleID = -1;                     // condition
      else
         scheduleID = elScheduleID.options[ elScheduleID.selectedIndex ].value;

      // Test to see what kind of a schedule we're processing
      if ( elIsHourly.checked )
      {
         // Get the current value of the common form elements
         var startTime = elStartTime.options[ elStartTime.selectedIndex ].value;
         var endTime   = elEndTime.options[ elEndTime.selectedIndex ].value;
         var freq      = elHourFreq.value;

         if ( freq == "" )
            freq = 1;
      
         // Save the hourly schedule
         saveHourlySchedule( groupID, scheduleID, startTime, endTime, freq );
      }
      else if ( elIsDaily.checked )
      {
         // Get the current value of the common form elements
         var time     = elDailyTime.options[ elDailyTime.selectedIndex ].value;
         var freq     = elDailyFreq.value;
     
         if ( freq == "" )
            freq = 1;
      
         var weekdays = elWeekdays.checked;
      
         // Save the daily schedule
         saveDailySchedule( groupID, scheduleID, time, weekdays, freq );
      }
      else if ( elIsWeekly.checked )
      {
         var time = elWeeklyTime.options[ elWeeklyTime.selectedIndex ].value;
         var freq = elWeeklyFreq.value;

         if ( freq == "" )
            freq = 1;

         var days = buildDayList( elOnSunday.checked, elOnMonday.checked, elOnTuesday.checked, 
                                  elOnWednesday.checked, elOnThursday.checked, elOnFriday.checked, 
                                  elOnSaturday.checked );
         // Save the weekly schedule
         SaveWeeklySchedule( groupID, scheduleID, time, days, freq );
      }
   }
   else
   {
      alert( "You must select a device group from the drop down list\nbefore you can create a scheduled poll." );
   }
}


function saveHourlySchedule( groupID, scheduleID, startTime, endTime, frequency )
{  
   var request = buildRequest( );

   // Define a simple callback bandler
   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            // Local Variables
            var response = parseDocument( request.responseText );

            // Refresh the schedule window
            optionsRefreshSchedule( );
            alert( "Save Successful." );

            errorHandler( response );
         }
      }
   }

   // Build up the parameter list and execute the remote method
   var params = new Array(6);
   params[0] = new Parameter( "SessionID", getSessionID( ) );
   params[1] = new Parameter( "GroupID", groupID );
   params[2] = new Parameter( "ScheduleID", scheduleID );
   params[3] = new Parameter( "StartTime", startTime );
   params[4] = new Parameter( "EndTime", endTime );
   params[5] = new Parameter( "Frequency", frequency );

   // Submit the request and close the options window
   ajaxCall( request, "AddHourlySchedule", params, callback );
}


function saveDailySchedule( groupID, scheduleID, time, weekdays, frequency )
{
   var request = buildRequest( );

   // Define a simple callback bandler
   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            // Local Variables
            var response = parseDocument( request.responseText );

            // Refresh the schedule window
            optionsRefreshSchedule( );
            alert( "Save Successful." );

            errorHandler( response );
         }
      }
   }

   // Build up the parameter list and execute the remote method
   var params = new Array(6);
   params[0] = new Parameter( "SessionID", getSessionID( ) );
   params[1] = new Parameter( "GroupID", groupID );
   params[2] = new Parameter( "ScheduleID", scheduleID );
   params[3] = new Parameter( "Time", time );
   params[4] = new Parameter( "Weekdays", weekdays );
   params[5] = new Parameter( "Frequency", frequency );

   // Submit the request and close the options window
   ajaxCall( request, "AddDailySchedule", params, callback );
}


function SaveWeeklySchedule( groupID, scheduleID, time, days, frequency )
{
   var request = buildRequest( );

   // Define a simple callback bandler
   var callback = function( )
   {
      if ( request.readyState == 4 )
      {
         if( request.status == 200 )
         { 
            // Local Variables
            var response = parseDocument( request.responseText );

            // Refresh the schedule window
            optionsRefreshSchedule( );
            alert( "Save Successful." );

            errorHandler( response );
         }
      }
   }

   // Build up the parameter list and execute the remote method
   var params = new Array(6);
   params[0] = new Parameter( "SessionID", getSessionID( ) );
   params[1] = new Parameter( "GroupID", groupID );
   params[2] = new Parameter( "ScheduleID", scheduleID );
   params[3] = new Parameter( "Time", time );
   params[4] = new Parameter( "DaysOfTheWeek", days );
   params[5] = new Parameter( "Frequency", frequency );

   // Submit the request and close the options window
   ajaxCall( request, "AddWeeklySchedule", params, callback );
}


function optionsLoadScheduleData( )
{
   // Local Variables
   var select = document.getElementById( "Options_ScheduleIdSelect" );
   
   if ( select != null )
   {
      var value = select.options[ select.selectedIndex ].value;

      if ( value != -1 )
      {
         var request = buildRequest( );
         var callback = function( )
         {
            if ( request.readyState == 4 )
            {
               if( request.status == 200 )
               { 
                  // Local Variables
                  var response = parseDocument( request.responseText );
                  var items = response.getElementsByTagName( "scheduledpoll" );

                  // Clear the existing scheduled data
                  clearSchedule( );

                  if ( items.length > 0 )
                  {
                     // Load the schedule details
                     var scheduleType = nodeValue( items[0], "scheduletype" );
                     
                     if ( scheduleType == 0 )
                     {
                        // Mark this schedule as an Hourly Poll
                        var schType = document.getElementById( "Schedule_Hourly" );
                        schType.checked = true;
                        showHourlySchedule( );
                        
                        // Load the schedule data
                        var elStartTime = document.getElementById( "Options_ScheduleHourlyStart" );
                        var elEndTime   = document.getElementById( "Options_ScheduleHourlyEnd" );
                        var elHourFreq  = document.getElementById( "Options_ScheduleHourlyFrequency" );
                        var startTime   = nodeValue( items[0], "starttime" );
                        var endTime     = nodeValue( items[0], "endtime" );
                        
                        // Set the start time
                        for ( var i = 0; i < elStartTime.options.length; i++ )
                        {
                           var item = elStartTime.options[i];

                           if ( item.value == startTime )
                           {
                              elStartTime.selectedIndex = i;
                           }
                        }

                        // Set the end time
                        for ( var i = 0; i < elEndTime.options.length; i++ )
                        {
                           var item = elEndTime.options[i];
                           
                           if ( item.value == endTime )
                           {
                              elEndTime.selectedIndex = i;
                           }
                        }
                        
                        // Set the frequency
                        elHourFreq.value  = nodeValue( items[0], "frequency" );
                     }
                     else if ( scheduleType == 1 )
                     {
                        // Mark this schedule as an Daily Poll
                        var schType = document.getElementById( "Schedule_Daily" );
                        schType.checked = true;
                        showDailySchedule( );
                        
                        // Load the schedule data
                        var elTime = document.getElementById( "Options_ScheduleDailyTime" );
                        var elEveryXDays = document.getElementById( "Options_ScheduleDailyEveryXDays" );
                        var elEveryWeekday = document.getElementById( "Options_ScheduleDailyEveryWeekday" );
                        var elDailyFreq = document.getElementById( "Options_ScheduleDailyFrequency" );
                        var time   = nodeValue( items[0], "time" );
                        var weekdays = nodeValue( items[0], "weekdays" );
                        
                        // Set the poll time
                        for ( var i = 0; i < elTime.options.length; i++ )
                        {
                           var item = elTime.options[i];

                           if ( item.value == time )
                           {
                              elTime.selectedIndex = i;
                           }
                        }
                        
                        // Setup the rest of the form
                        if ( weekdays == 1 )
                        {
                           elEveryWeekday.checked = true;
                        }
                        else
                        {
                           elEveryXDays.checked = true;
                           elDailyFreq.value = nodeValue( items[0], "frequency" );
                        }
                     }
                     else if ( scheduleType == 2 )
                     {
                        // Mark this schedule as an Weekly Poll
                        var schType = document.getElementById( "Schedule_Weekly" );
                        schType.checked = true;
                        showWeeklySchedule( );
                        
                        // Load the schedule data
                        var elTime = document.getElementById( "Options_ScheduleWeeklyTime" );
                        var elWeeklyFreq = document.getElementById( "Options_ScheduleWeeklyFrequency" );
                        var elOnSunday    = document.getElementById( "Options_ScheduleWeeklySunday" );
                        var elOnMonday    = document.getElementById( "Options_ScheduleWeeklyMonday" );
                        var elOnTuesday   = document.getElementById( "Options_ScheduleWeeklyTuesday" );
                        var elOnWednesday = document.getElementById( "Options_ScheduleWeeklyWednesday" );
                        var elOnThursday  = document.getElementById( "Options_ScheduleWeeklyThursday" );
                        var elOnFriday    = document.getElementById( "Options_ScheduleWeeklyFriday" );
                        var elOnSaturday  = document.getElementById( "Options_ScheduleWeeklySaturday" );
                        var time   = nodeValue( items[0], "time" );
                        var days   = nodeValue( items[0], "daysoftheweek" );
                        
                        // Set the poll time
                        for ( var i = 0; i < elTime.options.length; i++ )
                        {
                           var item = elTime.options[i];

                           if ( item.value == time )
                           {
                              elTime.selectedIndex = i;
                           }
                        }
                        
                        // Set the frequency
                        elWeeklyFreq.value = nodeValue( items[0], "frequency" );

                        // Setup the check boxes
                        if ( days.match( "Sunday" ) != null )
                           elOnSunday.checked = true;
                           
                        if ( days.match( "Monday" ) != null )
                           elOnMonday.checked = true;
                        
                        if ( days.match( "Tuesday" ) != null )
                           elOnTuesday.checked = true;

                        if ( days.match( "Wednesday" ) != null )
                           elOnWednesday.checked = true;

                        if ( days.match( "Thursday" ) != null )
                           elOnThursday.checked = true;

                        if ( days.match( "Friday" ) != null )
                           elOnFriday.checked = true;

                        if ( days.match( "Saturday" ) != null )
                           elOnSaturday.checked = true;
                     }
                     else
                     {
                        // Mark this schedule as a One Off Poll
                        var schType = document.getElementById( "Schedule_Once" );
                        schType.checked = true;
                        showOnceSchedule( );
                     }
                  }
                  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, "GetScheduleDetails", params, callback );
      }
      else
      {
         // This is a default group so just remove all the children
         clearSchedule( );
      }
   }
}


function optionsDeleteSchedule( )
{
   // Local Variables
   var elScheduleID = document.getElementById( "Options_ScheduleIdSelect" );

   // Determine the schedule id
   var scheduleID;
   if ( elScheduleID.options.length == 0 ) // We should never enter this 
      scheduleID = -1;                     // condition
   else
      scheduleID = elScheduleID.options[ elScheduleID.selectedIndex ].value;

   if ( scheduleID != -1 )
   {
      var request = buildRequest( );
      var callback = function( )
      {
         if ( request.readyState == 4 ) 
         {
            if( request.status == 200 )
            { 
                // Local Variables
                var response = parseDocument( request.responseText );

                // Refresh the schedule form
                optionsRefreshSchedule( );

                errorHandler( response );
            }
         }
      }

      var params = new Array(2);
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "ScheduleID", scheduleID );

      // Submit the request and close the options window
      ajaxCall( request, "RemoveSchedule", params, callback );
   }
   else
   {
      alert( "You must select a schedule from the drop down list\nbefore you can delete it." );
   }
}


function optionsRefreshSchedule( )
{
   // Local Variables
   var select = document.getElementById( "Options_ScheduleGroupSelect" );
 
   // Save the current device group
   scheduleFindGroup = select.options[ select.selectedIndex ].innerText;
                
   // Reset the schedule tab
   clearSchedule( );
   schedulePopulateDropdown( );
   scheduleGetDeviceGroups( );
   showHourlySchedule( );
}


function optionsDeleteGroup( )
{
   // Local Variables
   var elGroupID = document.getElementById( "Options_GroupSelect" );

   // Determine the schedule id
   var groupID;
   if ( elGroupID.options.length == 0 ) // We should never enter this 
      groupID = -1;                     // condition
   else
      groupID = elGroupID.options[ elGroupID.selectedIndex ].value;

   if ( groupID != -1 )
   {
      var request = buildRequest( );
      var callback = function( )
      {
         if ( request.readyState == 4 ) 
         {
            if( request.status == 200 )
            { 
                // Local Variables
                var response = parseDocument( request.responseText );

                // Clear the group name
                optionsFindGroup = "";

                // Refresh the form
                optionsGetDeviceGroups( );

                errorHandler( response );
            }
         }
      }

      var params = new Array(2);
      params[0] = new Parameter( "SessionID", getSessionID( ) );
      params[1] = new Parameter( "GroupID", groupID );

      // Submit the request and close the options window
      ajaxCall( request, "RemoveDeviceGroup", params, callback );
   }
   else
   {
      alert( "You must select a device group from the drop down list\nbefore you can delete it." );
   }
}
