/**
 * AjaxHandler.class.js file
 *
 * @author Aaron <aaron@doc-net.com>
 * @copyright Doctor Net Ltd &copy; 2008
 * @package SprintToolv3.default
 */
/**
 * AjaxHandler class
 *
 * Processes AJAX requests using jQuery
 *
 * @static
 */
function AjaxHandler() {}
AjaxHandler.str_url = '';
AjaxHandler.arr_data = new Array();
AjaxHandler.str_custom_xml = false;
AjaxHandler.bol_busy = false;

/**
 * Reset
 */
AjaxHandler.reset = function() {
   AjaxHandler.str_url = '';
   AjaxHandler.arr_data = new Array();
   AjaxHandler.str_custom_xml = false;
};
/**
 * Set the URL
 *
 * @param String str_url
 */
AjaxHandler.set_url = function(str_url) {
   AjaxHandler.str_url = str_url;
};

/**
 * Add some data
 *
 * @param String str_field Field name
 * @param Mix mix_val Field value
 */
AjaxHandler.add_data = function(str_field, mix_val) {
   AjaxHandler.arr_data[str_field] = mix_val;
};

/**
 * Set the custom XML
 *
 * To be used instead of add_data to specify
 * bespoke XML
 */
AjaxHandler.set_custom_xml = function(str_xml) {
   AjaxHandler.str_custom_xml = str_xml;
};

/**
 * Build up the XML document to send over AJAX
 *
 * @return String
 */
AjaxHandler.build_xml = function() {
   // Allow use of custom XML if set
   if (AjaxHandler.str_custom_xml) {
      return AjaxHandler.str_custom_xml;
   }
   var str_xml = '<'+'?xml version="1.0"?><root><fields>';
   for (str_field in AjaxHandler.arr_data) {
      // This will try to include the functions attached to AjaxHandler.arr_data
      if ((typeof AjaxHandler.arr_data[str_field]) != 'function') {
         str_xml += '<'+str_field+'><![CDATA['+AjaxHandler.arr_data[str_field]+']]></'+str_field+'>';
      }
   }
   str_xml += '</fields></root>';
   return str_xml;
}

/**
 * Set up a "busy" icon before dispatching the AjaxRequest
 *
 * Refer to do_dispatch() for parameters
 */
AjaxHandler.dispatch = function(fnc_success, fnc_failure) {
   $('#busy-wait-icon').show();
   if (AjaxHandler.bol_busy) {
      var int_timeout = 1000;
   } else {
      var int_timeout = 1;
   }
   setTimeout(function() {AjaxHandler.do_dispatch(fnc_success, fnc_failure)}, int_timeout);
}

/**
 * Perform the AJAX request
 *
 * Pass in the response object from the ajax call as a parameter to the callback(s).
 *
 * @param Function fnc_success (Optional) Function to be called on success
 * @param Function fnc_failure (Optional) Function to be called on failure
 */
AjaxHandler.do_dispatch = function(fnc_success, fnc_failure) {
   AjaxHandler.bol_busy = true;
   $.ajax({
      /*
       * We can't afford to have this trigger a second create, because the first
       * create hasn't come back yet with an id. Using syncrhonous mode forces
       * the create to complete before the user can continue.
       */
      async:false,
      type: "POST",
      url: AjaxHandler.str_url,
      data: 'str_xml='+escape(AjaxHandler.build_xml()),
      // If the AJAX call completed successfully
      success: function(obj_response) {
         AjaxHandler.bol_busy = false;
         // if the server-side script returned success
         if($('response', obj_response).attr('success') == 'true') {
             // If we've passed in an anonymous function into do_dispatch(), call it,
             // passing in the response object as a parameter.
            if (fnc_success) {
               fnc_success(obj_response);
            }
         } else if($('response', obj_response).attr('success') == 'logged_out') {
            // user has been logged out, so tell them this is the case, wait for them to hit OK and then forward to the login screen
            alert('You have been logged out, possibly due to a period of inactivity.  Please click OK to be forwarded to the login screen.');
            window.location = '/auth/login';
         // server-side didn't return success
         } else {
            // If we've passed in an anonymous function into do_dispatch(), call it,
            // passing in the response object as a parameter.
            if (fnc_failure) {
               fnc_failure(obj_response);
            } else {
               AjaxHandler.ajax_failure($('message', obj_response).text());
            }
         }
         $('#busy-wait-icon').hide();
      },
      // AJAX call didn't complete successfully
      error: function(obj, str, exc) {
         AjaxHandler.bol_busy = false;
         $('#busy-wait-icon').hide();
         AjaxHandler.ajax_failure('Sorry, there was a problem\n\n(Error code: AJAX-002)');
      }
   });


};

/**
 * Alert user that the AJAX request failed
 *
 * @param String str_msg (Optional) Error message to display
 */
AjaxHandler.ajax_failure = function(str_msg) {
   if (!str_msg) {
      str_msg = 'Sorry, there was a problem';
   }
   alert(str_msg);
};