// Cary Dunn <cdunn@elctech.com>

toggleKlass = function(state, id, klass) {
  if(state) {
    if(!$("#"+id).hasClass(klass)) {
      $("#"+id).addClass(klass)
    }
  } else {
    if($("#"+id).hasClass(klass)) {
      $("#"+id).removeClass(klass)
    }
  }
}

toggleHidden = function(id) {
  var old_field = document.getElementById(id); // So we can use .attributes
  var attrs = old_field.attributes;
  var new_field = "<input "; // Need to create the input by hand since jQuery won't allow .attr('type',xxx);
  
  // Take care of attributes
  for(var i = 0; i < attrs.length; i++) {
    if(attrs[i].nodeName == "value") {
      new_field += "value=\""+$(old_field).val()+"\" ";
    } else if(attrs[i].nodeName != "type") {
      new_field += attrs[i].nodeName+"=\""+attrs[i].nodeValue+"\" ";
    }
  }
  // Swap type field
  ($(old_field).attr("type") == "hidden") ? new_field += "type=\"text\" />" : new_field += "type=\"hidden\" />";
  
  // Modify DOM
  $(old_field).before($(new_field));
  $(old_field).remove();
}

secs_to_human = function(num) {
  var units = [
    ["week", 7*24*3600],
    ["day", 24*3600],
    ["hour", 3600],
    ["minute", 60],
    ["second", 1]
  ]
  if(!isNumeric(num) || num == 0) {return "0 seconds";}
  var output = [];
  
  var secs = num;
  for(var i = 0; i < units.length; i++) {
    var quot = parseInt(secs/units[i][1]);
    if(quot > 0) {
      var output_str = ""+quot+" "+units[i][0];
      output_str += (Math.abs(quot) > 1 ? "s" : "");
      output.push(output_str);
      secs -= quot * units[i][1];
    }
  }
  
  return output.join(", ");
}

isNumeric = function(value) {
  if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
  return true;
}
