// APSolva.js - bits and bobs collected over the years

/* APSolvaAjax.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 ajaxPath = "/include/"; // will change from site to site
  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') != ""){
    var u = ajaxPath + arg[0];  // If using clean URLs

  }else{
alert("We're using clean URLs - shouldn't get here!");
    var u = ajaxPath + 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;
}

/* apsolva.js - Helper JavaScript functions for various things
                Gleaned over the years
*/


/*  trim
    Remove characters on the left, right or both sides of the string.
    String.prototype.trim([chars: String = " "], [type: Integer = 0]): String
      chars - set of characters that will be removed
      type - specifies where the trim will occur, possible values are:
        * 0 = remove on both sides
        * 1 = remove characters on the left
        *	2 = remove characters on the right
*/
String.prototype.trim = function(c, t)
{
    return c = "[" + (c == undefined ? " " : c.replace(/([\^\]\\-])/g, "\\\$1")) + "]+",
    this.replace(new RegExp((t != 2 ? "^" : "") + c + (t != 1 ? "|" + c + "$" : ""), "g"), "");
}

/*  pad
   	Returns the string with a substring padded on the left, right or both sides.
    String.pad(length: Integer, [substring: String = " "], [type: Integer = 0]): String
      length - amount of characters that the string must have
      substring - string that will be concatenated
      type - specifies the side where the concatenation will happen, where:
        * 0 = left
        * 1 = right
        * 2 = both sides (centres text!)
*/
String.prototype.pad = function(l, s, t)
{
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
}

/*  isPositiveInt
    Returns true if the number is an integer and positive, false if not.
*/
function isPositiveInt(s)
{
  if (s == "") return true;
  for (i = 0 ; i < s.length ; i++){
    if ((s.charAt(i) < '0') || (s.charAt(i) > '9')) return false
  }
  return true;
}

// Cookie functions
function createCookie(name, value, days)
{
	if (days){
  	var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}else{
    var expires = "";
  }

	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name, "", -1);
}

// Don't display an object
function apsolvaHide(anObject)
{
  $(anObject).setStyle({display:"none"});
}
// Display an object
function apsolvaShow(anObject, blockInline)
{
  $(anObject).setStyle({display:blockInline});
}

// Validate an email address
function validEmail(address)
{
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

  return(reg.test(address));
}
