/**
 * C4U Javascript library for ajax requests
 * 
 * Copyright (c) 1999-2010 by Community4you GmbH
 */

/**
 * Performs an ajax request which fills the specified element.
 * 
 * This method calls the specified url and stores the result in the childs.
 * 
 * @param aSynchronousRequest if true, this is a synchonous request
 * @param theURL the url
 * @param theAnchor the optional anchor which should be focused after loading
 * the new page
 * @param theProgressDialogType the type of the progress dialog
 * @param theNewWidth the new width of the element
 * @param theNewHeight the new height of the element
 * @return true on success
 */
jQuery.fn.ajaxHtmlGet = function(aSynchronousRequest, theURL, theAnchor,
    theProgressDialogType, theNewWidth, theNewHeight)
{
  // for wait dialogs, we need no synchronous request (this hides the wait dialog in ie)
  if (!theProgressDialogType || (theProgressDialogType == 'wait_dialog'))
    aSynchronousRequest = false;
  
  if (theNewWidth)
    _element.css('width', theNewWidth);
  if (theNewHeight)
    _element.css('height', theNewHeight);
  
  showProgressDialog(theProgressDialogType, this.attr('id'));

  var _element = this;

  var _result = false;
  jQuery.ajax(
  {
    type : "GET",
    url : theURL,
    cache : false,
    async : !aSynchronousRequest,
    dataType : "html",
    error : function()
    {
      hideProgressDialog(theProgressDialogType, _element.attr('id'));
      // no notification at the moment
    },
    success : function(theHTML)
    {
      hideProgressDialog(theProgressDialogType, _element.attr('id'));
      _element.empty();
      _element.append(theHTML);
      
      _result = true;
    }
  });

  return _result;
}

/**
 * HTML get function for usage in links.
 * 
 * @param aSynchronousRequest if true, this is a synchonous request
 * @param theID the id of the element where the result should be copied to. If
 * the element does not exist, it will be created
 * @param theAjaxURL the url
 * @param theProgressDialogType the type of the progress dialog
 * @param theAnchor the optional anchor which should be focused after loading
 * the new page
 * @param theNewWidth the new width of the element
 * @param theNewHeight the new height of the element
 * @param theFrameID the optional frame id to use, if in frame mode
 */
function ajaxHtmlGet(theID, aSynchronousRequest, theAjaxURL, theAnchor,
    theProgressDialogType, theNewWidth, theNewHeight, theFrameID)
{
  //maybe, we must call the script in a different frame
  if (theFrameID != null)
  {
    if ((window.parent != null) && (window.parent.frames[theFrameID] != null) &&
        (window != window.parent.frames[theFrameID]) &&
        typeof(window.parent.frames[theFrameID].ajaxHtmlGet) && 
        (typeof(window.parent.frames[theFrameID].ajaxHtmlGet) == 'function'))
    {
      window.parent.frames[theFrameID].ajaxHtmlGet(theID, aSynchronousRequest, theAjaxURL, theAnchor,
          theProgressDialogType, theNewWidth, theNewHeight, theFrameID);
      return;
    }
  }

  jQuery(document).ready(function()
  {
    var _id;
    var _div;
  
    if (theID)
    {
      var _id = '#' + theID;
      var _div = jQuery(_id);
      
      if (_div.size() < 1)
      {
        // create a new element
        jQuery("body").append('<div id="' + theID + '" style="display:none" />');
        _div = jQuery(_id);
      }
    }
    else
      return;
    
    // make an ajax request to the specified url
    _div.ajaxHtmlGet(aSynchronousRequest, theAjaxURL, theAnchor,
        theProgressDialogType, theNewWidth, theNewHeight);
  });
}

/**
 * Submits an ajax form with jquery form.
 * 
 * @param theID the id of the element where the result should be copied to (either a 
 * surrounding div or the form itself).
 * @param theAjaxURL the url
 * @param theProgressDialogType the type of the progress dialog
 * @param theAnchor the optional anchor
 */
function ajaxHtmlFormSubmit(theID, theAction, theAnchor, theProgressDialogType)
{
  if (!theID)
    return;

  var _id = '#' + theID;
  var _div = jQuery(_id);
  if (_div.size() != 1)
    return;
  
  var _form;
  if (_div.attr('action'))
  {
    _form = _div;
    theID = _form.parent().attr('id');
    _id = '#' + theID;
  }
  else
    _form = _div.find("form").first();
  if (_form.size() != 1)
    return;
  
  showProgressDialog(theProgressDialogType, theID);

  // make an ajax request to the specified url
  jQuery(document).ready(function()
  {
    _form.ajaxSubmit(
    {
      target: _id,
      success: function(theHTML)
      {
        hideProgressDialog(theProgressDialogType, theID);
      },
      error: function()
      {
        hideProgressDialog(theProgressDialogType, theID);
      }
    })
  });
}

/**
 * Submits an element in a form via ajax.
 * 
 * @param theID the id of the element where the result should be copied to. If
 * the element does not exist, it will be created
 * @param theFormElementID the ID of the form element
 * @param theProgressDialogType the type of the progress dialog
 * @param theParams the optional params
 * @param theAnchor the optional anchor
 * @param aSynchronousRequest if true, this is a synchronous request
 */
function ajaxHtmlFormElementSubmit(theID, theFormElementID, 
    aSynchronousRequest, theAnchor, theParams, theProgressDialogType)
{
  if (!theID)
    return;

  var _id = '#' + theID;
  var _div = jQuery(_id);
  
  if (_div.size() != 1)
    return;
  
  var _form = _div.parents().find("form").first();
  if (_form.size() != 1)
    return;
  
  // patch the form url and add the required form parameters (form id and form context id)
  var _url = _form.attr('action');
  
  var _fcid = _form.find("input[name='_fcid']");
  var _fid = _form.find("input[name='_fid']");
  var _activePage = _form.find("input[name='_current_page']");
  
  _url = _url + "?_fcid=" + escape(_fcid.attr('value')) + "&_fid=" + escape(_fid.attr('value')) + 
    "&_current_page=" + escape(_activePage.attr('value'))
  
  if (theParams)
    _url = _url + "&" + theParams;
  
  ajaxHtmlGet(theID, aSynchronousRequest, _url, theAnchor, theProgressDialogType, 
      null, null, null);
}

/**
 * Ajax form timeout function.
 * 
 * This function sends an alive request to the server and sets the timeout
 * again.
 * 
 * @param theID the form id
 * @param theURL the url
 * @param theTimeout the timeout
 * @param isAjax if true, make ajax requests
 * @param theErrorCount the number of current errors
 * @param theCounter the counter for disabling the browser cache
 */
function sendIsAliveRequest(theID, theURL, theTimeout, isAjax, theErrorCount, theCounter)
{
  if (!theURL)
    return;
  
  var _url = theURL + "&counter=" + theCounter;
  theCounter = theCounter + 1;

  if (isAjax)
  {
    // synchronous ajax request
    var _result = false;
    jQuery.ajax(
    {
      type : "GET",
      url : _url,
      cache : false,
      async : true,
      error : function()
      {
        if (theErrorCount < 3)
        {
          // add timeout again; but only 3 times
          initializeIsAliveRequestHandler(theID, theURL, theTimeout,
              isAjax, theErrorCount + 1, theCounter);
        }
      },
      success : function(theHTML)
      {
        // add timeout again
        initializeIsAliveRequestHandler(theID, theURL, theTimeout, isAjax, 0, theCounter);
      }
    });
  }
  else
  {
    // create an image on demand and set url
    var _id = "#" + theID + "_hidden_img";
    var _img = jQuery(_id);
    
    if (_img.size() == 0)
    {
      // create new image
      var _formID = "#" + theID;
      var _form = jQuery(_formID);
      
      if (_form.size() == 1)
      {
        _form.append('<img id="' + theID + '_hidden_img" src="' + _url + '"/>');
      }
    }
    else
    {
      // refresh image via js
      _img.attr("src", _url);
    }
    
    // set timeout and call again
    initializeIsAliveRequestHandler(theID, theURL, theTimeout, isAjax, 0, theCounter);
  }
}

/**
 * Creates an ajax function which will periodically contact the server or an
 * periodically refreshed image.
 * 
 * @param theID the form id
 * @param theURL the url
 * @param theTimeout the timeout in milliseconds
 * @param isAjax if true, use ajax requests
 * @param theErrorCount the number of current errors
 * @param theCounter the counter for disabling the browser cache
 */
function initializeIsAliveRequestHandler(theID, theURL, theTimeout, isAjax,
    theErrorCount, theCounter)
{
  if (!theURL)
    return;

  if (!theErrorCount)
    theErrorCount = 0;
  if (!theCounter)
    theCounter = 0;

  window.setTimeout("sendIsAliveRequest('" + theID + "','" + theURL + "', "
      + theTimeout + ", " + isAjax + ", " + theErrorCount + ", " + theCounter + ")",
      theTimeout);
}