/* ajax.js - common ajax caller */

/*  args is an array containing:
    [0] - the php file that contains the ajax PHP functions
    [1] - the php function to call in [0] and the js function used for callback
    [2] - a <form> ID - all <input> values are passed via POST (empty if using [3-n])
    [3-n] - variables passed to functions via POST - 'v0', 'v1' ... (taskID should be [3])
*/
function ajaxCall(args)
{
  var arg = args.split('~');

  var f = arg[1]; // PHP function to run and the JS function to use as callback
  var p = "";     // Will hold all parameters
  if (arg[2] != ""){
    // For submitted "forms" - either a true form or an array of elements in a form
    p = "f=" + f;

    if (arg[2].substring(0, 1) == "."){
      // get array from a CSS class selector
      p+= createPost(arg[2]);
     
    }else{
      // For actual form - WARNING looks for the name="xxxxx" NOT id="xxxxx" for each element
      p+= "&" + $(arg[2]).serialize(); // carries out any encoding of "strange" chars (like '%' !!)
    }

  }else{
    // For use when specific values passed over
    // 2nd argument reserved for taskID (empty if not required)
    p = "f=" + f;
    for (var i=2;i<arg.length;i++){
      p+= "&v" + (i - 2) + "=" + escape(arg[i]); // The escape() encodes "strange" chars
    }
  }

//  if ($F('this_script') != "" && $F('this_script') != "admin"){
//    var u = "ajaxJSPHP/" + arg[0];  // If using clean URLs

//  }else{
//alert("We're using clean URLs - shouldn't get here!");
    var u = "../ajaxJSPHP/" + arg[0]; // If using unclean URLs
//  }

//alert("u: {"+u+"}\np: {"+p+"}\nf: {"+f+"}");
	var ajax = new Ajax.Request(u, {parameters: p, onComplete: eval(f)});
}

// This automatically converts both keys and values to strings.
function createPost(className)
{
  var post = "";

  $$(className).each(function(field){
    post+= "&" + $(field).id + "=" + escape($F(field));
  });

  return post;
}