function getQueryString()
// Parse querystring, store the name/value pairs in properties of an object, return that object.
{
  var argname, argvalue, pos, ix;
  var args = new Object();
  var query = location.search.substring(1); 
  var pairs = query.split("&");
  var str = "";
  for (ix = 0; ix < pairs.length; ix++)
  {
    pos = pairs[ix].indexOf('=');
    if (pos < 0)
    {
      continue;
    }
    argname = pairs[ix].substring(0,pos);
    argvalue = (pairs[ix].substring(pos+1)).replace(/\+/g, " ");
    args[argname] = unescape(argvalue);
    str = str + " " + argname + "=" + argvalue;
  }
  return args;
}

function replaceAllChars(str,rep)
{
  return str.replace(/./g,rep);
}

function makeNoCache()
{
  // tack onto Ajax call so force to not use cache!
  return '?nocache=' + new Date().getTime();
}

// jquery disable() function
$.fn.disable = function() {
  return this.each(function() {
    if (typeof this.disabled != "undefined") this.disabled = true;
  });
}

// jquery enable() function
$.fn.enable = function() {
  return this.each(function() {
    if (typeof this.disabled != "undefined") this.disabled = false;
  });
}

function showhide(shows,hides) 
{
  var show_ids = shows.split('|');
  var hide_ids = hides.split('|');
  var ix,show_id,hide_id;

  for(ix=0;ix<hide_ids.length;ix++)
  {
    hide_id = trimWS(hide_ids[ix]);
    if (hide_id.length) $("#"+hide_id).hide();
//  if(container != '') $("#"+container+" div").hide();
  }
  
  for(ix=0;ix<show_ids.length;ix++)
  {
    show_id = trimWS(show_ids[ix]);
    if (show_ids.length) $("#"+show_id).show();
  }
}

function showLoadingImage()
{
  if ($("#loading-image").length) $("#loading-image").show();
}

function hideLoadingImage()
{
  if ($("#loading-image").length) $("#loading-image").hide();
}

function trimWS(val)
// Remove leading and trailing whitespace.
{
  if (val == null)
  {
    return "";
  }
  val = val.toString();
  if (val.length <= 0)
  {
    return "";
  }
  val = val.replace(/^\s+/g, "");
  val = val.replace(/\s+$/g, "");
  return val;
}

function sortAssociative(this_array)
{
  var tmp_array = [];
  var key;
  var ix;
  for (this_key in this_array)
  {
    tmp_array.push([this_key, this_array[this_key]]);
  }
/*
var tmp;
tmp = '';
  for (this_key in this_array)
  {
tmp += this_key + '|' + this_array[this_key] + "\n";
  }
alert(tmp);
*/
//  tmp_array.sort(function () {return arguments[0][1].toLowerCase() > arguments[1][1].toLowerCase(); });
  // safari fix
  tmp_array.sort(function () {if (arguments[0][1].toLowerCase() > arguments[1][1].toLowerCase()) return 1; else return -1; });

/*
tmp = '';
  for (tmp_key in tmp_array)
  {
tmp += tmp_key + '|' + tmp_array[tmp_key][1] + "\n";
  }
alert(tmp);
*/
  var out_array = [];
  for (ix = 0; ix<tmp_array.length; ix++)
  {
    out_array[tmp_array[ix][0]] = tmp_array[ix][1];
  }
  return out_array;
}

function validUsername(username)
{
  // same as one in User class
  username = trimWS(username);
  if ((username.length < 5) || !username.match(/[a-zA-Z]/)) return false;
  return true;
}

function dropQuotes(str,wh)
{
  var w;
  if (arguments.length < 2) 
  {
    w = 1;
  }
  else
  {
    w = wh;
  }
  if ((w == 1) || (w == 3))
  {
    str = str.replace(/\'/g, "");
  }
  if ((w == 2) || (w == 3))
  {
    str = str.replace(/\"/g, '');
  }
  return str;
}

function isNumeric(str)
{
  if (str == null) return 0;

  var valid_chars = "0123456789.";
  var ch, ix;

  for (ix = 0; ix < str.length; ix++) 
  { 
    ch = str.charAt(ix); 
    if (valid_chars.indexOf(ch) == -1) return false;
  }
  return true;
}

function makeNumeric(str)
{
  if (!isNumeric(str)) return 0;
  return str;
}

function changeQuizRotation(new_rotation_id)
// if new_rotation_id passed, not called from change event
// if new_rotation_id passed, was called from change event
{
  var from_header = false;
  if (arguments.length > 0) 
  {
    from_header = true; //from specific call (header rotation change) - they will call buildQuizList
    $("#quiz_rotation_id").val(new_rotation_id);
  }
  var quiz_rotation_id = $('#quiz_rotation_id').val();
  var for_user_id = getForUserId();
  if (for_user_id != USER_ID) 
  { 
    changePulldownRotation(quiz_rotation_id,for_user_id); 
    return; // no need to sync with header  
  }
  if (!from_header) // from select rotation change, and changing self
  {
    if (typeof(changeHeaderRotation) == "function") 
      changeHeaderRotation(quiz_rotation_id);
    else if (typeof(parent.changeHeaderRotation) == "function") 
      parent.changeHeaderRotation(quiz_rotation_id);
  }
  updateFlexigrid();
}

function changePulldownRotation(rotation_id,user_id)
{
  var url = '/rotation_set.php' + makeNoCache() + '&rotation_id=' + rotation_id + '&user_id=' + user_id;
  $.get(url,'',changePulldownRotationDone);
}

function changePulldownRotationDone()
{
  updateFlexigrid();
}

function getForUserId()
{
  var args = getQueryString();
  // who am I doing this for?
  if (args['user_id'] !== undefined)
    return args['user_id'];
  else if (args['uid'] !== undefined)
    return args['uid'];
  else if (args['filter_user'] !== undefined)
    return args['filter_user'];
  else if (args['id'] !== undefined)
    return args['id'];
  else
    return USER_ID;
}

function updateFlexigrid()
{
  var report_id = null;
  if (reportid = self.report)
    reportid.flexReload(); // flexigrid
  else if (reportid = self.parent.report)
    reportid.flexReload(); // flexigrid
  else if (reportid = top.report)
    reportid.flexReload(); // flexigrid
}

function updateCurrentStatus()
{
  if (typeof(top.changeCurrentStatus) == "function") 
  {
    top.changeCurrentStatus();
    return;
  }
  // problem here, if change status while in a popup window...how get to it?
//  var obj = top.popupWindowGetWinId('current-status');
//  var obj = $("#current-status",window.parent.document);
}

function dumpObject(o) {
	    var objectInfo = "";
	    var objectToDebug = o;
	    for (var prop in objectToDebug) {
	        objectInfo += "property: " + prop + " value: [" + objectToDebug[prop] + "]\n";
	    }
	    objectInfo += "toString(): " + " value: [" + objectToDebug.toString() + "]";
	    alert(objectInfo);
	}

function encodeVideoPopupArg(video_id,set_mute,hide_title,hide_icd9,hide_linked,hide_documents)
// prepend 'x' and flags (1 or 2) to video id, then hex it
// there are corresponding php and javascript versions!
{
  var set_mute = set_mute?2:1;
  var hide_title = hide_title?2:1;
  var hide_icd9 = hide_icd9?2:1;
  var hide_linked = hide_linked?2:1;
  var hide_documents = hide_documents?2:1;
  var val = ''+set_mute+hide_title+hide_icd9+hide_linked+hide_documents+video_id; // to string
  val = parseInt(val); // back to number
  return 'x'+val.toString(16);
}

function formatDate(d)
{
  if (d.length < 8)
  {
    var now = new Date();
    var yyyy = now.getFullYear();
    yyyy = yyyy.toString();
    var mm = (now.getMonth() + 1).toString();
    if (mm.length < 2) mm = '0'+mm;
    var dd = (now.getDate()).toString();
    if (dd.length < 2) dd = '0'+dd;
    d = yyyy+mm+dd;
  }
  return d.substr(4,2) + '/' + d.substr(6,2) + '/' + d.substr(0,4);
}

var DatePattern = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
function normalizeDate(d)
{
  var nd = '';
  var parts;
  if (d.length > 0)
  {
    parts = DatePattern.exec(d);
    if (parts != null) // invalid date, check fields will catch this
    {
      var mm = parseInt(parts[1],10);
      var dd = parseInt(parts[2],10);
      var yyyy = parts[3];
      if (mm<10) mm = '0' + mm;
      if (dd<10) dd = '0' + dd;
      nd = yyyy+mm+dd;
    }
  }
  return nd;
}
 
