/**
* Callback object of the retrieveStaticContent function
*/
var staticContentCallbackObject =
{
  success: function(o)
  {
    contentElem.innerHTML = o.responseText;
    hideLoadingBox();
  },
  failure: function(o)
  {
    contentElem.innerHTML = 'Helaas, kon deze content niet inladen, probeer het a.u.b. nogmaals.';
    hideLoadingBox();
  },
  cache: true
};

/**
* Functions that converts a string of options into a associative array giving 1 or 2 seperators
*
* @param array options
* @param string sep1
* @param string sep2
* @return mixed
*/
function convertOptionsResponseToAssociativeArray(options, sep1, sep2)
{
  var array       = new Array();
  var tempArray   = options.split(sep1);
  var i           = 0;

  if (!sep2)
  {
    for (i = 0; i < tempArray.length; i++)
    {
      array[tempArray[i]] = tempArray[i];
    }
  }
  else
  {

    for (i = 0; i < tempArray.length; i++)
    {
      var tempValueArray = tempArray[i].split(sep2);

      if (tempValueArray[1])
        array[tempValueArray[0]] = tempValueArray[1];
      else
        array[tempValueArray[0]] = tempValueArray[0];
    }
  }

  return array;
}

/**
* Functions that makes sure the code is gonna be globaly available
*
* @param string code
* @return mixed
*/
function loadCodeGlobal(code)
{
  var globalReference = this; // global scope reference
  if (window.execScript) {

    window.execScript(code); // eval in global scope for IE
    return null; // execScript doesn’t return anything
  }
  return globalReference.eval ? globalReference.eval(code) : eval(code);
}

/**
* Function for retrieving dynamic content using AJAX
*
* @param string url
* @param string targetDivId
* @param boolean renderBreadCrumb
* @return void
*/
function retrieveDynamicContent(url, targetDivId, renderBreadCrumb)
{
  if (!url)
    return;

  if (typeof(renderBreadCrumb) == 'boolean')
    renderBreadCrumb = renderBreadCrumb;
  else
    renderBreadCrumb = true;

  scrollToTop();
  showLoadingBox();

  // Makes sure the controller knows in what context he should render the page
  url = defaultSiteUrl + url + '/&requestType=ajax&showBreadCrumb=' + renderBreadCrumb;

  var dynamicContentCallbackArgs = new Array();
  dynamicContentCallbackArgs[0] = url;

  if (targetDivId)
    dynamicContentCallbackArgs[1] = targetDivId;

  /**
  * Callback object of the retrieveDynamicContent function
  */
  var dynamicContentCallbackObject =
  {
    success: function(o)
    {
      var targetDivId = null;
      var targetDivElem = null;

      if (o.argument && o.argument[1])
        targetDivId = o.argument[1];

      if (targetDivId)
      {
        if (targetDivElem = document.getElementById(targetDivId))
          targetDivElem.innerHTML = o.responseText;

      }
      else
      {
        contentElem.innerHTML = o.responseText;
      }

      // This code checks if there are any script tags in the response and then takes the first 1 to eval it
      var scripts = contentElem.getElementsByTagName('script');

      if (scripts[0])
      {
        if (scripts[0].innerHTML)
        {

          // Make sure the code is gonna be globally available
          loadCodeGlobal(scripts[0].innerHTML);

          // Checks if the view has an initView function and if so it will execute this function.
          if (typeof initView == 'function')
            initView();

        }
      }
      hideLoadingBox();
    },
    failure: function(o)
    {
      var targetDivId = null;
      var targetDivElem = null;

      if (o.argument && o.argument[1])
        targetDivId = o.argument[1];

      if (targetDivId)
      {
        if (targetDivElem = document.getElementById(targetDivId))
          targetDivElem.innerHTML = 'Helaas, kon deze content niet inladen, probeer het a.u.b. nogmaals.';

      }
      else
      {
        contentElem.innerHTML = 'Helaas, kon deze content niet inladen, probeer het a.u.b. nogmaals.';
      }

      hideLoadingBox();
    },
    cache: false,
    argument: dynamicContentCallbackArgs
  };

  var transaction = YAHOO.util.Connect.asyncRequest('GET', url, dynamicContentCallbackObject, null);

  if (pageTracker)
    pageTracker._trackPageview(url);
}

/**
* Function for retrieving static content using AJAX
*
* @param string url
* @return void
*/
function retrieveStaticContent(url)
{
  if (!url)
    return;

  if (!staticContentCallbackObject)
    return;

  // Check if the url provided is to an external location
  if (url.match(/http:\/\/.*/))
  {
    window.open(url);
    return;
  }

  scrollToTop();
  showLoadingBox();

  // Built up the url
  url = defaultSiteUrl + url + '/&requestType=ajax';

  var transaction = YAHOO.util.Connect.asyncRequest('GET', url, staticContentCallbackObject, null);

  if (pageTracker)
    pageTracker._trackPageview(url);

}

/**
* Function for retrieving dynamic small content using AJAX
*
* @param string url
* @return void
*/
function retrieveDynamicSuggests(url, callbackFunction)
{
  if (!url)
    return;

  // Built up the url
  url = defaultSiteUrl + url;

  var dynamicSuggestsCallbackArgs = new Array();
  dynamicSuggestsCallbackArgs[0] = callbackFunction;

  /**
  * Callback object of the AutoCompletes
  */
  var dynamicSuggestsCallback =
  {
    success: function(o)
    {
      var callbackFunction = '';

      if (o.argument && o.argument[0])
        callbackFunction = o.argument[0];

      callbackFunction = callbackFunction + '("' + o.responseText + '");';

      if (callbackFunction)
        eval(callbackFunction);

    },
    failure: function(o)
    {

    },
    cache: true,
    argument: dynamicSuggestsCallbackArgs
  };

  var transaction = YAHOO.util.Connect.asyncRequest('GET', url, dynamicSuggestsCallback, null);
}

/**
* Function for retrieving a number of objects using AJAX
*
* @param string type
* @return void
*/
function updateNumberOfObjects(type)
{
  if (!type)
    return;

  if (type == 'all')
  {
    var callback =
    {
      success: function(o)
      {

        if (o.responseText)
        {
          var items = o.responseText.split('|');
          var i = null;

          for (i = 0; i < items.length; i++)
          {
            var item = items[i].split(',');
            var elem = null;

            switch (item[0])
            {
              case 'Monitored':

                if (elem = document.getElementById('monitored_nr'))
                  elem.innerHTML = item[1];

              break;

              case 'DreamHouses':

                if (elem = document.getElementById('dream_houses_nr'))
                  elem.innerHTML = item[1];

              break;

              case 'DreamStreets':

                if (elem = document.getElementById('dream_streets_nr'))
                  elem.innerHTML = item[1];

              break;

              case 'DreamAreasNeighbourhoods':

                if (elem = document.getElementById('dream_areas_neighbourhoods_nr'))
                  elem.innerHTML = item[1];

              break;

              case 'DreamRooms':

                if (elem = document.getElementById('dream_rooms_nr'))
                  elem.innerHTML = item[1];

              break;
            }
          }
        }
      },
      failure: function(o)
      {
      },
      cache: false
    }
  }
  else
  {
    var elem = null;

    if (elem = document.getElementById(type + '_nr'))
    {
      var callback =
      {
        success: function(o)
        {
          elem.innerHTML = o.responseText;
        },
        failure: function(o)
        {
        },
        cache: false
      }
    }
  }

  var transaction = YAHOO.util.Connect.asyncRequest('GET', defaultSiteUrl + 'remote/numobjects_call.php?type=' + type, callback, null);
}

/**
* Function for posting content of a form using AJAX
*
* @param string formName
* @param boolean postFile
* @param string currentTab
* @return void
*/
function postForm(formName, postFile, formErrorElemId)
{
  if (!formName)
    return;

  if (!postFile)
    postFile = false;

  var formObject = null;

  if (formObject = document.getElementById(formName))
  {
    if (postFile)
    {
      YAHOO.util.Connect.setForm(formObject, true);
    }
    else
    {
      YAHOO.util.Connect.setForm(formObject);
    }

    var postFormCallbackArgs = new Array();
    postFormCallbackArgs[0] = formErrorElemId;

    showLoadingBox();

    var callback =
    {
      success: function(o)
      {
        var responseXML = null;

        var formErrorElemId = '';

        if (o.argument && o.argument[0])
          formErrorElemId = o.argument[0];

        // Clear previous messages
        toggleFormResponse('hide', 'success', '', formErrorElemId);

        if (responseXML = o.responseXML)
          handleFormPostActions(responseXML, formErrorElemId);

        hideLoadingBox();
      },
      failure: function(o)
      {
        contentElem.innerHTML = 'Helaas, dit formulier kon niet worden opgeslagen, probeer het a.u.b. nogmaals.';
        hideLoadingBox();
      },
      upload: function(o) {
        var responseXML = null;

        var formErrorElemId = '';

        if (o.argument && o.argument[0])
          formErrorElemId = o.argument[0];

        // Clear previous messages
        toggleFormResponse('hide', 'success', '', formErrorElemId);

        if (responseXML = o.responseXML)
          handleFormPostActions(responseXML, formErrorElemId);

        hideLoadingBox();
      },
      cache: false,
      argument: postFormCallbackArgs
    }

    var transaction = YAHOO.util.Connect.asyncRequest('POST', defaultSiteUrl + 'index.php', callback, null);
  }
}

/**
* Function that finds the actions in the XML response
*
* @param string responseXML
* @param string formErrorElemId
* @return void
*/
function handleFormPostActions(responseXML, formErrorElemId)
{
  var actions = null;

  // Read out the actions given in the xml response
  if (actions = responseXML.getElementsByTagName('action'))
  {
    for (i = 0; i < actions.length; i++)
    {
      var type = null;
      var value = null;

      if (type = actions[i].getElementsByTagName('type'))
      {
        type = type[0].firstChild.nodeValue;

        if (value = actions[i].getElementsByTagName('value'))
        {
          if (value[0].firstChild && value[0].firstChild.nodeValue)
            value = value[0].firstChild.nodeValue;
          else
            value = null;

          handleFormPostAction(type, value, formErrorElemId);
        }
      }
    }
  }
}

/**
* Function that handles the action of postForm
*
* @param string type
* @param string value
* @param string formErrorElemId
* @return void
*/
function handleFormPostAction(type, value, formErrorElemId)
{
  switch (type)
  {
    case 'success':
      toggleFormResponse('show', 'success', value, formErrorElemId);
    break;
    case 'error':
      toggleFormResponse('show', 'error', value, formErrorElemId);
    break;
    case 'reloadHomepage':

      var baseHref = getBaseHref();

      if (value)
        window.location.href = baseHref + value;
      else
        window.location.href = baseHref;

    break;
    case 'redirectExternalSite':
      if (value)
        window.location.href = value;
    break;
    case 'retrieveDynamicContent':
      retrieveDynamicContent(value);
    break;
    case 'updateNumberOfObjects':
      updateNumberOfObjects(value);
    break;
    case 'callFunction':
      try
      {
        eval(value);
      }
      catch(error)
      {
        // do nothing
      }
    break;
  }
}
