/**
 * gets the Ajax request for the given URL and then
 * populates the response in the element
 */
function getAjaxRequest(requestURL, elementId) {
  var e = element(elementId);
  if (e != null) {
    // gets Ajax request and populates the response
    AjaxRequest.get(
      {
        'url' : requestURL,
        'onSuccess' : function(req) {
                        e.innerHTML = req.responseText;
                        launchJs(req.responseText);
                      }
      }
    );
  }
}

/**
 * gets the Ajax form request for the given URL and then
 * populates the response in the element - also saves
 * the original content of the element in a hidden element
 */
function getAjaxFormRequest(requestURL, elementId) {
  var e = element(elementId);
  if (e != null) {
    // gets Ajax request and populates the response
    AjaxRequest.get(
      {
        'url' : requestURL,
        'onSuccess' : function(req) {
                        saveFormField(elementId);
                        e.innerHTML = req.responseText;
                        launchJs(req.responseText);
                      }
      }
    );
  }
}

/**
 * submits the Ajax form and populates the response
 * in the element - also updates the content of the
 * hidden element
 */
function submitAjaxForm(form, elementId) {
  var e = element(elementId);
  if (e != null) {
    AjaxRequest.submit(
      form,
      { 'onSuccess' : function(req) {
                        e.innerHTML = req.responseText;
                        launchJs(req.responseText);
                        if (! hasFormError(req.responseText)) {
                          // removes temp element
                          var d = element('_' + elementId);
                          if (d != null) {
                            removeTempField(d);
                          }
                        }
                      }
      }
    );
  }
}

/**
 * submits the Ajax form and populates the response
 * in the element - if there is a success element, the
 * element is filled with the response text, otherwise
 * the first element is filled - also updates the content
 * of the hidden element
 */
function submitAjaxFormAlternate(form, elementId, targetElementId) {
  var e = element(elementId);
  if (e != null) {
    AjaxRequest.submit(
      form,
      { 'onSuccess' : function(req) {
                        if (hasFormError(req.responseText)) {
                          e.innerHTML = req.responseText;
                        } else {
                          var t = element(targetElementId);
                          if (t != null) {
                            t.innerHTML = req.responseText;
                          } else {
                            e.innerHTML = req.responseText;
                          }
                          // removes temp element
                          var d = element('_' + elementId);
                          if (d != null) {
                            removeTempField(d);
                          }
                        }
                        launchJs(req.responseText);
                      }
      }
    );
  }
}

/**
 * cancels the Ajax form request and restores the
 * content from the hidden element
 */
function cancelAjaxFormRequest(elementId) {
  var e = element(elementId);
  var d = element('_' + elementId);
  if (e != null && d != null && d.innerHTML != '') {
    e.innerHTML = d.innerHTML;
    removeTempField(d);
  }
}

/**
 * saves the form field in a hidden div element
 * which can be used to restore the content on cancel
 */
function saveFormField(elementId) {
  var e = element(elementId);
  var d = element('_' + elementId);
  if (d == null) {
    d = document.createElement('div');
    d.setAttribute('id', '_' + elementId);
    appendTempField(d);
  }
  d.innerHTML = e.innerHTML;
}

/**
 * finds all javascripts in the response text and
 * evaluates them - should be called after a
 * successful Ajax request
 */
function launchJs(responseText) {
  try {
    var regex = "(?:<script.*?>)((\n|.)*?)(?:<\/script>)";
    var match = new RegExp(regex, 'img');
    var scripts = responseText.match(match);
    if (scripts) {
      var js = '';
      for (var s=0; s<scripts.length; s++) {
        var match = new RegExp(regex, 'im');
        js += scripts[s].match(match)[1];
      }
      js = filterJs(js);
      eval(js);
    }
  } catch (e) {
    // there are some broken javascripts
    // in the response text
    alert(e.message);
  }
}

/**
 * filter out html comment <!-- //--> surrounding
 * the script blocks - used to prevent problem in
 * older browser
 */
function filterJs(script) {
  var regex = "^.*(?:\<\!\-{2})|(?:\/{2}\s*\-{2}\>).*$";
  var match = new RegExp(regex, 'img');
  return (script.replace(match, ''));
}

/**
 * check if there's any error element in the
 * response text
 */
function hasFormError(responseText) {
  var regex = "(?:<div class=\"error\">)(.+)(?:<\/div>)";
  var match = new RegExp(regex, 'img');
  var errors = responseText.match(match);
  return (errors) ? true : false;
}

function appendTempField(d) {
  var t = element('_tmp_');
  if (t != null) t.appendChild(d);
}

function removeTempField(d) {
  var t = element('_tmp_');
  if (t != null) t.removeChild(d);
}

function copyContent(sourceId, elementId) {
  var s = element(sourceId);
  var e = element(elementId);

  if (e != null && s!= null) {
     e.innerHTML = s.innerHTML;
  }
}

/**
 * scroll the screen to the specified
 * element (vertical only)
 */
function scrollTo(elementId) {
  var x = 0, y = 0;

  var e = element(elementId);
  if (e != null) {
    // x = e.offsetLeft;
    y = e.offsetTop - 10;
    while((e = e.offsetParent) != null) {
      // x += e.offsetLeft;
      y += e.offsetTop;
    }
  }

  window.scroll(x, y);
}

