$(document).ready(function() {
	
	// these add specific classes for navigational highlighting
	// and expanding sub menus. The "current" class added to
	// the li is done with php.
	$('.current').children('ul').addClass('child');
	$('li ul li.current').closest("ul").addClass('child');

	$('.left-nav li').click(function() {
			$(this).children('ul').slideDown();
	});

  showStatusMessage();
  
	// empty search field on focus and 
	// and add "Search" on blur
  $("#search_term").blur(function () {
    if ($("#search_term").val() == "") {
      $(this).val("Search");
    }
  });
  $("#search_term").focus(function () {
    $(this).val("");
  });

	// lightbox the photos on patient profiles [use modal for a.procedure-compare]

		// $('.thumbnail a').lightBox({fixedNavigation:true});


	// function to highlight top columns
	    $.each(new Array(5), function(i) {
			$('.col-' + i).hover(function() {
			  $('#hd-' + i).addClass('focused');
			}, function() {
			  $('#hd-' + i).removeClass('focused');
			});
	    });


});

// Text Extraction function used by table sorter
// create regex outside function so it only has to be built once
//   need [^>]+ to avoid matching tags inside the link
var linkExtract = new RegExp(/<a[^>]+>(.*)<\/a>/i);
var isCommaDigit = new RegExp(/^\d+,(\d+,)*\d+$/);
var extractLinks = function(node) {
  //var nodeText = node.innerHTML.replace("\n", ""); // regex won't match past newline
  var nodeText = node.innerHTML;
  var formattedText = nodeText.match(linkExtract);
  if (formattedText != null) {
    //alert("formatted: "+formattedText[1]);
    nodeText = formattedText[1];
  }
  if (nodeText.match(isCommaDigit) != null) {
    nodeText = nodeText.replace(",", ""); // sorter doesn't handle commas
  }
  if (nodeText == '0') {
    // if first row is a zero, will sort alphabetically not numerically
    //   this hack makes the sorter recognize that we are sorting numbers
    nodeText = '-1';
  } else if (nodeText == '<!-- no digit -->') {
    // on last 12 months report we need a digit to fill in for blanks
    nodeText = '-2';
  }
  //alert("node:"+nodeText+":");
  return nodeText;
}

function showStatusMessage() {
  /* reveal status message if there is one (queries the class) */
  if ($("#status-message").hasClass("error-message")) {
    $("#status-message").show();
    $("#status-message").highlightFade({start:'red',end:'#ffbfbf',speed:2000});
  } else if ($("#status-message").hasClass("success-message")) {
    $("#status-message").show();
    $("#status-message").highlightFade({start:'#2f6cff',end:'#cfdcff',speed:2000});
  }
  if ($("#instruction-message")) {
    $("#instruction-message").highlightFade({start:'#00a800',end:'#a6f4a6',speed:2000});
  }
}

function assignBalloon(id) {
  if (!$("#"+id)) {
    return;
  }

  var balloon = $.create('div', {'id':id+'-balloon', 'class':'balloon'});
  var contentWrapper = $.create('div', {'id':id+'-balloon-wrapper'});
  var content = $.create('p', {'id':id+'-balloon-content'}, ['Not Set']);
  
  $(contentWrapper).append($(content));
  $(balloon).append($(contentWrapper));
  $("#"+id+"_wrapper").append($(balloon));

  return;
}

/*
function removeBalloon(id) {
  if ($("#patient-balloon")) {
    if (id) { 
      if (id == balloonDiv) {
        $("#patient-balloon").remove();
        $("#visit-submit").attr("disabled", false);
      }
    } else {
      $("#patient-balloon").remove();
      $("#visit-submit").attr("disabled", false);
    }
  }
}
*/

function enableBalloon(id, error) {
  $("#"+id+"-balloon-content").html(error);
  $("#"+id+"-balloon").show();
  setSubmit();
}

function disableBalloon(id) {
  $("#"+id+"-balloon").hide();
  setSubmit();
}

function setSubmit() {
  var hasError = false
  for (i in validateFields) {
    var field = "#"+validateFields[i]+"-balloon";
    if ($(field).is(":visible")) {
      hasError = true;
      break;
    }
  }

  $("#visit-submit").attr("disabled", hasError);
  $("#visit-update").attr("disabled", hasError);
  $("#visit-delete").attr("disabled", hasError);
  return hasError;
}

/* Downloaded from: http://code.google.com/p/sprintf/ */
/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

function ucwords(str) {
  // Uppercase the first character of every word in a string  
  // 
  // version: 1004.2314
  // discuss at: http://phpjs.org/functions/ucwords    
  // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // +   improved by: Waldo Malqui Silva
  // +   bugfixed by: Onno Marsman
  // +   improved by: Robin
  // *     example 1: ucwords('kevin van zonneveld');    
  // *     returns 1: 'Kevin Van Zonneveld'
  // *     example 2: ucwords('HELLO WORLD');
  // *     returns 2: 'HELLO WORLD'
  return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
      return $1.toUpperCase();    });
}

