//utilities to make random html/js coding easier
function get(id) {
  return document.getElementById(id);
}

function set(id,val){
	get(id).innerHTML=val;
}
function getVal(id){
	return get(id).value;
}
function setVal(id,val){
	get(id).value=val;
}
function onEnter(f,event){
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) 
       f();
}
function append(id, val) {
	set(id, get(id).innerHTML + val);
}
function hide(id){
	get(id).style.visibility='hidden'
}
function show(id){
	get(id).style.visibility='visible'
}

function setClass(id,className){
	var theElement=get(id);
	theElement.css = (theElement.style) ? theElement.style : theElement;
	theElement.className = className;
}
function refresh(){
	window.location.href=window.location.href;
}

function enable(id){
	get(id).disabled = false;
}
function disable(id){
	get(id).disabled = true;
}


function isNumber(num){
  try{
    return typeof(eval(num)) == "number" && !isNaN(num);
  }catch(e){
    return false;
  }
  return false;
}
function isNum(num){
  return isNumber(num);
}
/*** 1.6 compatibility ***
 * code from
 * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array
 */
/**
 * Find the first index of the element in this array
 */
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this && this[from] === elt)
        return from;
    }
    return -1;
  };
}
/**
 * Find the last index of the element in this array
 */
if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]);
    if (isNaN(from))
    {
      from = len - 1;
    }
    else
    {
      from = (from < 0) ? Math.ceil(from) : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

    for (; from > -1; from--)
    {
      if (from in this && this[from] === elt)
        return from;
    }
    return -1;
  };
}
/**
 * Make a copy of the array that contains only the elements of the original
 * that fun returns true for.
 *
 * @param {a -> boolean} fun The predicate function
 * @return {Array[a]} The filtered list
 *
 * Called 'keep' in some languages. I can't remember which.
 **/
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}
/**
 * Call fun for each item of this array and save the results in a new array.
 *
 * @param {a -> b} fun The mapping function
 * @return {Array[b]} The new list
 **/
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}
/**
 * Call fun on each element of this array. fun shouldn't return anything
 * because it will be ignored.
 *
 * @param {a -> ()} fun The function to be called.
 */
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}
/**
 * Return true if fun returns true for all items in this array
 *
 * Notice that it is true for an empty array.
 * It's like folding && across the array.
 */
if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          !fun.call(thisp, this[i], i, this))
        return false;
    }

    return true;
  };
}
/**
 * Return true if fun returns true for any item in this array
 *
 * Notice that it is false for an empty array.
 * It's like folding || across the array.
 */
if (!Array.prototype.some)
{
  Array.prototype.some = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          fun.call(thisp, this[i], i, this))
        return true;
    }

    return false;
  };
}
/*** 1.8 compatibility, code from same source ***/
/**
 * Reduce a list to single value with a for loop.
 * This captures the common model of a for loop with a total or
 * buffer that gets added to each time in some way.
 *
 * eg to write 'join'
 * var s = ''
 * for(var i in ara) {
 *   s += ara[i]
 * }
 * becomes
 * ara.reduce(function (s,x) { return s + x }, '')
 *
 * formatted a certain way, this is just as long, so you generally only
 * want to use it in cases where you already have the accumulator part written.
 * ara.reduce(function (s,x) { // <-- NOT the recommended formatting
 *   return s + x
 * },
 *            '')
 */
if (!Array.prototype.reduce)
{
  Array.prototype.reduce = function(fun /*, initial*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    // no value to return if no initial value and an empty array
    if (len == 0 && arguments.length == 1)
      throw new TypeError();

    var i = 0;
    if (arguments.length >= 2)
    {
      var rv = arguments[1];
    }
    else
    {
      do
      {
        if (i in this)
        {
          rv = this[i++];
          break;
        }

        // if array contains no values, no initial value to return
        if (++i >= len)
          throw new TypeError();
      }
      while (true);
    }

    for (; i < len; i++)
    {
      if (i in this)
        rv = fun.call(null, rv, this[i], i, this);
    }

    return rv;
  };
}
/**
 * reduceRight is the same as reduce, except that it starts at the end
 * of the array. If your language supports only recursion, there is more of
 * a difference.
 */
if (!Array.prototype.reduceRight)
{
  Array.prototype.reduceRight = function(fun /*, initial*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    // no value to return if no initial value, empty array
    if (len == 0 && arguments.length == 1)
      throw new TypeError();

    var i = len - 1;
    if (arguments.length >= 2)
    {
      var rv = arguments[1];
    }
    else
    {
      do
      {
        if (i in this)
        {
          rv = this[i--];
          break;
        }

        // if array contains no values, no initial value to return
        if (--i < 0)
          throw new TypeError();
      }
      while (true);
    }

    for (; i >= 0; i--)
    {
      if (i in this)
        rv = fun.call(null, rv, this[i], i, this);
    }

    return rv;
  };
}
/*** Array utils ***/
/**
 * Make arrays print closer to the way that they are entered. This is called
 * homoiconicity and is generally a Good Thing.
 *
 * I hope this doesn't mess up any browsers. I just couldn't stand the
 * ridiculous way nested lists were printed.
 */
Array.prototype.toString = function() { return "[" + this.join() + "]" }
/** Java-like synonym for Array.push **/
Array.prototype.add = Array.prototype.push;
/** Is this array empty? **/
Array.prototype.isEmpty = function () { return this.length==0 }
/** Is the array passed empty?
 * The utility of this duplicate is questionable except that it's so
 * convenient to pass to other code.
 **/
function isEmpty(l) { return l.length==0 } // hmpf
/**
 * Sum the numbers in the array.
 *
 * This could be easily changed to be a synonym of Array.join('') for arrays of
 * strings but that Would Not Be Proper. Don't you think?
 */
Array.prototype.sum = function() {
  var total = 0
  for(var i = 0; i < this.length; i++)
    total += this[i]
  return total
}
//returns an array without the given element
Array.prototype.remove = function(val) {
  var acc = []
  for(var i = 0; i < this.length; i++)
    if(this[i]!=val)
      acc.push(this[i])
  return acc
}
/**
 * Find the element in the array for which f (a function) returns true
 * TODO:Bulletproof this the same way the built in indexOf is.
 */
Array.prototype.find = function(f) {
  for(var i = 0; i < this.length; i++)
    if(f(this[i]))
      return this[i]
}
Array.prototype.findLast = function(f) {
  for(var i = this.length; i < -1; i--)
    if(f(this[i]))
      return this[i]
}
//returns the index of the value in the array, or -1 if not found
// (I am not totally convinced of this function's widespread utility: NCS)
// = array.map(prop('value')).indexOf(obj.value)
// or
// = array.indexOf(obj.value,{ key: prop('value') })
// (if you give indexOf a third parameter, key, like Common Lisp
function indexOfVal(array,obj){
	var index=-1;
	for(var i=0;i<array.length;i++)
		if(array[i].value==obj.value)
			index=i;
	return index;
}
/**
 * Is this defined somewhere? I feel like it should be, but I don't see it.
 * O(n)
 */
Array.prototype.equals = function(that) {
  if(typeof this !== typeof that) // If either is not an array/object
    return false
  if(this.length !== that.length)
    return false
  for(var i = 0; i < this.length; i++)
    if(this[i] !== that[i])
      return false
  return true
}
/**
 * Same here, ought to be defined somewhere, but isn't. O(2n)
 *
 * Improvements are welcome; this is an important function.
 * At this point I'm not completely sure that 'in' operator
 * the one of type (object*object -> boolean) is defined in old versions of js.
 */
Object.prototype.equals = function(that) {
  if(typeof this !== typeof that)
    return false
  for(var i in this)
    if(!(i in that) || this[i] !== that[i])
      return false
  for(var i in that)
    if(!(i in this) || this[i] !== that[i])
      return false
  return true
}
/**
 * foldl and foldr are a lot easier to use (for me) than reduce and reduceRight
 * methods
 */
function foldl(f, i, l) { return l.reduce(f, i) }
function foldr(f, i, l) { return l.reduceRight(f, i) }

/*** String utils ***/
// I am not totally sure this will work guys but I had to try it
String.prototype.filter = Array.prototype.filter
String.prototype.forEach = Array.prototype.forEach
String.prototype.map = Array.prototype.map
String.prototype.every = Array.prototype.every
String.prototype.some = Array.prototype.some
String.prototype.reduce = Array.prototype.reduce
String.prototype.reduceRight = Array.prototype.reduceRight
String.prototype.remove = Array.prototype.remove

// trim whitespace on either side of the string
String.prototype.trim = function() { return this.replace(/^\W+|\W+$/, ''); };
//compares two strings, ignoring case
//TODO: Test this
String.prototype.equalsIgnoreCase = function (that) {
  return this.toLowerCase()===that.toLowerCase()
}

//clean up string to remove certain characters
function removeDelimiters(theString) {
  var goodChars = function (c) {
    return !(c == '\'' || c == ';' || c == '\"' || c == '`' || c == '\|' || c == '\\');
  }
  if(theString === null)
    return theString;
  else
    return theString.filter(goodChars).join('');
}
/**
 * String formatting, using Prototype.js syntax, which I think is based on Ruby or Java.
 * Syntax: #{property}
 * Prefix with a slash to prevent interpolation: \#{why would you ever type this?}
 * Happily, it works with arrays too: #{0} etc
 *
 * It's probably pretty slow, at least it would be in Python.
 * Passing that function in there like that...
 *
 * The regex is improved from Prototype.js, whose implementation was otherwise
 * super convoluted and over-powerful. It says: look at the preceding character and make
 * sure it's not a \. Then capture the property inside the #{ } and put in the value from
 * the object passed.
 *
 * TODO: Test this!
 */
String.prototype.format = function (obj) {
  return this.replace(/([^\\]|^|\r|\n)#\{(.*?)\}/g,
                      function(all, before, property) {
                        return before+obj[property]
                      })
}
String.prototype.startsWith = function(s) {
    return this.slice(0, s.length)===s
}
String.prototype.endsWith = function(s) {
    return s.length==0 ? true : this.slice(-s.length)===s
}
/*** Function utils ***/
/**
 * Chain together two functions.
 * If I were addicted to ML, I would assert that
 * var seq = meth(Function.prototype.chain)
 * but the name 'chain' is fine with me.
 *
 * Use:
 * this.isTagsEmpty = prop('tags').chain(isEmpty)
 * print(node1.isTagsEmpty())
 * OR
 * var discussion = children.filter(prop('tags').chain(isEmpty))
 */
Function.prototype.chain = function (g) {
  var f = this
  return function () { return g(f.apply(null, arguments)) }
}
/**
 * Partial call. Pass some arguments to the function and return a new function that takes
 * the rest of the arguments.
 *
 * To use:
 * // assume 'someid' is a div somewhere
 * ['foo', 'bar', 'baz'].forEach(append.c('someid'))
 * // this will append 'foo' 'bar' and 'baz' to someid
 *
 * This is frequently used and needs to be really short, which why its name is
 * a stupid pun: partial 'call'=='c'. Yeah, I know.
 */
Function.prototype.c = function () {
  var args = []
  for(var i = 0; i < arguments.length; i++)
    args.push(arguments[i])
  var f = this
  return function() {
    var l = []
    for(var i = 0; i < arguments.length; i++)
      l.push(arguments[i])
    return f.apply(null, args.concat(l))
  }
}
/** wrap (!) in a function for passing around */
function not(x) { return !x }
/** wrap () in a function for passing around */
function id(x) { return x }
/** wrap === in a function for passing around */
function eq (x,y) { return x===y }
/** wrap !== in a function for passing around */
function ne (x,y) { return x!==y }
// TODO: doNothing should be here too, if utils were always loaded before ajax

/** overload by number of arguments (no type dispatch right now)
 *
 * If the caller passes too many arguments, the function with the next smallest number
 * of arguments is called. This ignores functions with more arguments. For example,
 *
 * Overload a function with 2 and 4 arguments. Pass it 3 arguments, and the 2-arg
 * function is called. I decided this was better than passing a whole bunch of undefined
 * values to something that wasn't expecting any undefined values (why else would you be
 * overloading?)
 */
function overload() {
  var overloads = []
  var fs = arguments
  for(var i = 0; i < arguments.length; i++)
    overloads[arguments[i].length] = arguments[i]
  return function() {
    for(var args = arguments.length; args > -1; args--)
      if(overloads[args])
        return overloads[args].apply(null, arguments)
    throw "No appropriate overload found"
  }
}
/** fill in the argument list with optional values if not enough are passed.
 *
 * There are a couple of non-obvious points. Optional arguments are
 * matched with formal arguments at the time the function is
 * created. So if the number of passed arguments and optional
 * arguments combined still isn't enough, you will get undefined
 * values in the middle.
 *
 * For example:
 * optional(function(x,y,z) { ... }, [3])(1)
 * gives x=1, y=undefined, z=3. z is given the default value 3, never y. */
function optional(f, optargs) {
  return function() {
    var args = []
    for(var i = 0; i < arguments.length; i++)
      args.push(arguments[i])
    if(args.length < f.length) {
      for(i = 0; i < f.length - args.length - optargs.length; i++)
        args.push(undefined)
      args = args.concat(optargs.slice(args.length - f.length))
    }
    return f.apply(null, args)
  }
}
/** public method -> function
 * @param {Method | String} method The method (or method name) to be made independent
 * @param args Arguments to be passed to the method.
 * This distinction exists because Javascript requires use
 * of the call method on functions in order to specify the calling object.
 *
 * Actually it is kind of nice in that it allows partial application as
 * a bonus. That doesn't mean I like it because of that.
 *
 * It's not clear to me whether passing a method or a method name is safer
 * or faster. It's less typing to pass the method name because you don't have
 * name the class prototype.
 */
function meth() {
  var method = arguments[0]
  var args = [] //why arguments doesn't have a slice method is beyond me
  for(var i = 1; i < arguments.length; i++)
    args.push(arguments[i])
  if((typeof method)==='function')
    return function (x) { return method.apply(x,args) }
  else
    return function (x) { return x[method].apply(x,args) }
}
/**
 * Almost the same thing, except for properties and the parameter must be a string.
 *
 * @param {String} property The name of the property to return
 */
function prop(property) {
  return function (x) { return x[property] }
}

/**
* Get a URL parameter and return it to you.
* For example if the current URL is "...?action=blah&id=3" then calling getURLParam("id") will return "3".
*/
function getURLParam(strParamName){
  return getParam(window.location.href, strParamName)
}
/**
 * This is the worker for getURLParam that does not refer to the DOM
 * (and hence is testable from test.js)
 */
function getParam(strUrl, strParamName) {
  var start = strUrl.indexOf("?");
  if ( start > -1 ){
    var strQuery = strUrl.substr(start+1).toLowerCase();
    var aPair = strQuery.split("&").find(function (pair) {
          return pair.startsWith(strParamName.toLowerCase()) })
    if(aPair)
        return unescape(aPair.split("=")[1])
  }
  return '';
}

//Gets the selected radio button
function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

