// ajax.js
// JavaScript AJAX implementation

var xmlHttp

/**
 * Escapes a value properly to be sent in the query string
 * @param string the value
 * @return string escaped value
 */
function ajaxEscapeValue( value ){
  var escapes = [
    /\+/g, "%2B"
    ];
  var max = escapes.length; // for efficiency
  for( var i = 0; i < max; i += 2 ){
    value = value.replace( escapes[i], escapes[i+1] );
  }
  return value;
}

// ajaxPrepareQS
// fields - array of form fields to encode for the AJAX request
// RETURN: the data string to pass to the server
function ajaxPrepareQS(fields){
  var escapeFunc = escape; // Set a function pointer in case we change
                           // later
  var passData = '';
  for(var x = 0; x < fields.length; x++){
    if(!fields[x] || !fields[x].type || fields[x].type == 'button' ){
      continue;
    }
    var val = null;
    switch(fields[x].type){
      case 'text':
      case 'textarea':
      case 'password':
      case 'hidden':
        val = ajaxEscapeValue( fields[x].value );
        break;
      case 'checkbox':
      case 'radio':
        if(fields[x].checked){
          val = fields[x].value;
        }
        break;
      case 'select-one':
        if(fields[x].selectedIndex >= 0 &&
           fields[x].selectedIndex < fields[x].options.length){
          val = fields[x].options[fields[x].selectedIndex].value;
        }
        break;
      case 'select-multiple':
        // This is a special case where we must set the passData
        // up here for each selected item in the list
        for(var i = 0; i < fields[x].options.length; i++){
          if(fields[x].options[i].selected){
            if(passData.length != 0){
              passData += '&';
            }
            passData += fields[x].name + '='
                      + escapeFunc(fields[x].options[i].value);
          }
        }
        break;
    }
    // append the value to the full query string
    if(val != null){
      if(passData.length != 0){
        passData += '&';
      }
      passData += fields[x].name + '=' + escapeFunc(val);
    }
  }
  return passData;
}

/**
 * Perform an access denied check on our object
 * @return bool true if access was denied, false if it was allowed
 */
function ajaxAccessDeniedCheck(obj){
  if(obj._AccessDenied === false){
    var msg = { name : "access_denied",
                type : MsgQSidebar.T_ERR,
                msg  : "You do not have sufficient permissions to " +
                       "complete your request; speak with your " +
                       "Webview administrator if you feel this is in " +
                       "error.",
                dur  : 5000
    };
    MsgQSidebar.addMsg(msg);
    return true;
  }
  return false;
}

// ajaxRun
// url - server url to process
// callback - javascript function to use as the callback
// method - GET or POST
// qs - the query string for GET, the post data for POST
// noAsync - true to run non asynchronously
function ajaxRun(url, callback, method, qs, noAsync){
  if(!noAsync){
    noAsync = false;
  }
  var xmlHttp = null;
  xmlHttp = GetXmlHttpObject();
  if(xmlHttp == null){
    alert("Your browser does not support AJAX!");
    return;
  }
  url = clientURL() + url;
  if(method=="GET"){
    url = url + "?" + qs;
  }
  // We want to pass the xml object to our callbacks so we can have
  // multiple async calls going at once
  var cb = callback;
  callback = function(){
    var xmlObj = xmlHttp;
    if( xmlObj && xmlObj.readyState == 4 && xmlObj.status == 200){
      try{
        var obj = eval("(" + xmlObj.responseText + ")");
        if(ajaxAccessDeniedCheck(obj)){
          return;
        }
      }catch(e){
        ;
      }
    }
    cb(xmlObj);
    wv_resize_iframe();
    return;
  }
  // The magic happens next
  xmlHttp.open( method, url, !noAsync );
  xmlHttp.onreadystatechange = callback;
  if(method=="POST"){
    xmlHttp.setRequestHeader('Content-Type',
                             'application/x-www-form-urlencoded');
    xmlHttp.send(qs);
  }else{
    xmlHttp.send(null);
  }
  return;
}

// GetXmlHttpObject
// RETURN: The ajax object
function GetXmlHttpObject(){
  var xmlHttp=null;
  try{
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }catch(e){
  // Internet Explorer
    try{
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}

// clientURL
// RETURN: URL to pre-pend to ajaxFunction's url parameter
function clientURL(){
  var url = /http:\/\/[^\/]+\/wv\/[^\/]+/.exec(document.location) + '/';
  return url;
}
