
// FIREBUG CONSOLE FALLBACK
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

// isset equivalent 
function isset(varname){
  return(typeof(window[varname])!='undefined');
}
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
 
	jQuery.cookie = function(name, value, options) {
		if (typeof value != 'undefined') { // name and value given, set cookie
			options = options || {};
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				var date;
				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date = options.expires;
				}
				expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
			}
			// CAUTION: Needed to parenthesize options.path and options.domain
			// in the following expressions, otherwise they evaluate to undefined
			// in the packed version for some reason...
			var path = options.path ? '; path=' + (options.path) : '';
			var domain = options.domain ? '; domain=' + (options.domain) : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
		} else { // only name given, get cookie
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	};
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqmodal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 07/06/2008 +r13
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};
$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t)});};
$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;
 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));
 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);
//		==================

//      JQuery Text resize + Cookie recall

//      by Jonny Kamaly

//      based on script written by Faisal &amp; Homar
//
//		from http://www.shopdev.co.uk/blog/text-resizing-with-jquery/ 
//
//		updated from default 9/26/08
 
	var resizefunctions = {
		textresize : function(){
			// show text resizing links
			$(".font-settings").show();
			// var $cookie_name = "famililink_font_size";
			var originalFontSize = $("body").css("font-size");
			// if exists load saved value, otherwise store it
			// if($.cookie($cookie_name)) {
			///	 var $getSize = $.cookie($cookie_name);
			//	 $("b").css({fontSize : $getSize + ($getSize.indexOf("px")!=-1 ? "" : "px")}); // IE fix for double "pxpx" error
			// } else {
			//	$.cookie($cookie_name, originalFontSize);
			// }
			// reset link
			/*$(".FontSizeReset").bind("click", function() {
				$("html").css("font-size", originalFontSize);
				$.cookie($cookie_name, originalFontSize);
			});*/
			// text Ò+" link
			$(".increase-font-size").bind("click", function() {
			  var currentFontSize = $("body").css("font-size");
			  var new_font_size = current_font_size + 1;
			  if (new_font_size > 7) new_font_size = 7;
			  var newFontSize = font_size_array[new_font_size];
				$("body").css("font-size", newFontSize);
				// $.cookie($cookie_name, newFontSize);
				// reset font size var and send ajax call back
				current_font_size = new_font_size;
				update_font_size(current_font_size);
			  return false;
			});
			$(".decrease-font-size").bind("click", function() {
			  var currentFontSize = $("body").css("font-size");
			  var new_font_size = current_font_size - 1;
			  if (new_font_size < 1) new_font_size = 1;
			  var newFontSize = font_size_array[new_font_size];			  
				$("body").css("font-size", newFontSize);
				// $.cookie($cookie_name, newFontSize);
				// reset font size var and send ajax call back
				current_font_size = new_font_size;
				update_font_size(current_font_size);
			  return false;
			});
			console.log("attached font resize functions: " + current_font_size);
		}
	}
	function update_font_size(current_font_size) {
		console.log("Updating font size to: " + current_font_size);
		$.ajax({
			  url: '/api.php',
			  data: 'action=update_font_size&current_font_size' + current_font_size,
			  dataType: 'json',
			  type: 'post',
			  error : function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
				  console.log("Ajax Error: "+textStatus.msg);
			  },			  
			  success: function (j) {
				console.log("Ajax Success: "+j);			  
			  }
		});
	}
	// initialize font array
	var font_size_array = new Array();
	font_size_array[1] = "xx-small";
	font_size_array[2] = "x-small";
	font_size_array[3] = "small";
	font_size_array[4] = "medium";
	font_size_array[5] = "large";
	font_size_array[6] = "x-large";
	font_size_array[7] = "xx-large";
	// set current font size
	var current_font_size = 2;
	 
	$(document).ready(function(){
		resizefunctions.textresize();
	});

// tool tip function.  
	$(document).ready(function(){
            var jq = $('.tooltip');
            if (typeof jq.cluetip == 'function')
            {
                jq.cluetip({});
            }
        });

// BUTTON ROLLOVER FUNCTIONS
	$(document).ready(function(){
		// bind rollover events
		$('.rollover-button').each(function(i) {
			set_rollover_button(this);
			 
	     });
 
	});
	function set_rollover_button(button, prevent_click_event_flag) {
			 
//		alert ("this id = " + $(button).attr("src"));
		 // set vars
		 button.off_src = button.src;
		 button.hover_src = button.off_src.replace("_off", "_hover");
		 
		 // preload rollover image
		 jQuery("<img>").attr("src", button.hover_src);
						 
//		alert ("off src = " + button.off_src + " hover src = " + button.hover_src);
		 // add mouseover and mouseout events
		 $(button).bind("mouseover", function() {    
			button.src = button.hover_src;
		 });
		 $(button).bind("mouseout", function() {
			button.src = button.off_src;
		 }); 
						 
		 // if button is not a toggle button, add click event that unbinds mouseout (for active state)			 
		 if ( (!$(button).hasClass("record-toggle-button")) && (!$(button).hasClass("record-close-button"))  && (!$(button).hasClass("increase-font-size")) && (!$(button).hasClass("decrease-font-size")) && (!prevent_click_event_flag)) {
		 
			 $(button).bind("click", function() {
				// unbind mouse events
				$(button).unbind("mouseover, mouseout");
			 });
			 
		 }
			 
	}	      

// RECORD ROW FUNCTIONALITY      
      
	// establish record objects and vars
	var checked_records_count = 0;
	var all_records = new Array();
	var event_list_flag = false;
	function close_all_records() {
		for (i in all_records) {
			if (all_records[i].open_status == true) {
				all_records[i].close();
			}
		}
	}
	function uncheck_all_records() {
		// if this isn't the calendar page, uncheck all rows
		if (!$('body').hasClass("calendar-section")) {
			for (i in all_records) {
				if (all_records[i].checked_status == true) {
					all_records[i].uncheck();
				}
			}
		}
	}
	function uncurrent_all_records() {
		$('tr.current').removeClass("current");
	}
	function record(first_row) {
		// get element vars
		console.log('looking for moreinfo button');
		this.moreinfobutton = $(first_row).find("input[src*=moreinfo]").get(0);
		if (typeof(this.moreinfobutton)=="undefined") {
			console.log('moreinfo button not found, trying readmore');
			this.moreinfobutton = $(first_row).find("input[src*=readmore]").get(0);
			if (typeof(this.moreinfobutton)=="undefined") console.log('readmore button not found');
		}
		this.teaser_row = $(first_row);
		this.toggle_cells = $(first_row).find("td:not(.checkbox-col)");
		this.body_row = $(first_row).next();
		this.close_button = this.body_row.find(".record-close-button");
		this.checkbox_col = $(first_row).find("td.checkbox-col");
		this.checkbox = $(first_row).find(":checkbox");
		this.new_img = $(first_row).find("img[src*=new_flag]");
		this.unread_img = $(first_row).find("img[src*=icons/unopen]");
		this.original_height = $('.column-wrapper').height();		
		this.message_box = this.body_row.find(".message-box");
//		this.read_img = $(first_row).find("img[src*=icons/open]");
//		this.toggle_button = $(first_row).find(".record-toggle-button").get(0);
//		this.id = this.toggle_button.value;
		// set status vars
		this.checked_status = false;
		this.open_status = false;
		this.read_status = false;
		if (this.body_row.hasClass("hidden") == false) {
			this.open_status = true;
		}
		if (this.checkbox.checked == true) {
			this.checked_status = true;
		}
		// if this is a green checkbox row, add steps
		if (event_list_flag == true) {
			this.checked_img = this.checkbox_col.find("img");
			this.event_row = true;
			if (this.checked_img.css("display") == "block") {
				this.checked_status = true;
				checked_records_count++;
			}
		}
		// checkbox methods
		this.check = function() {
			// close all rows
			close_all_records();
			// set to checked
			this.checked_status = true;
			this.checkbox.attr("checked", true);
			// if green button row, do action
			if (event_list_flag == true) {
				// replace input with checkbox img
				this.checkbox.hide();
				this.checked_img.show();
				// send mark_event_done message
				var cached_id = this.checkbox.get(0).value;
				console.log("sending event marked notice via ajax:" + "action=mark_event_done&event_id=" + cached_id);
				$.ajax({
					  url: '/api.php',
					  data: 'action=mark_event_done&event_id=' + cached_id,
					  dataType: 'json',
					  type: 'post',
					  error : function (XMLHttpRequest, textStatus, errorThrown) {
						  // typically only one of textStatus or errorThrown 
						  // will have info
						  console.log("Ajax Error: "+textStatus.msg);
					  },			  
					  success: function (j) {
						console.log("Ajax Success: "+j);			  
					  }
				});
			}
			// update counter
			checked_records_count++;
			console.log("checkboxes = "+ checked_records_count);
			refresh_button_row();
		}
		this.uncheck = function() {
			// set to unchecked
			this.checked_status = false;
			this.checkbox.attr("checked", false);
			// if green button row, do action
			if (event_list_flag == true) {
				this.checkbox.show();
				this.checked_img.hide();
				// send mark_event_done message
				var cached_id = this.checkbox.get(0).value;
				console.log("sending event marked notice via ajax:" + "action=unmark_event_done&event_id=" + cached_id);
				$.ajax({
					  url: '/api.php',
					  data: 'action=unmark_event_done&event_id=' + cached_id,
					  dataType: 'json',
					  type: 'post',
					  error : function (XMLHttpRequest, textStatus, errorThrown) {
						  // typically only one of textStatus or errorThrown 
						  // will have info
						  console.log("Ajax Error: "+textStatus.msg);
					  },			  
					  success: function (j) {
						console.log("Ajax Success: "+j);			  
					  }
				});
			}
			// update counter
			checked_records_count--;
			console.log("checkboxes = "+ checked_records_count);
			refresh_button_row();
		}
		this.toggle_checkbox = function() {
			if (this.checked_status == true) {
				this.uncheck();
			}
			else {
				this.check();
			}
		}
		// open/close methods
		this.open = function() {
			// clear message list
			uncheck_all_records();
			close_all_records();
			uncurrent_all_records();
			// if row has new message class, remove it
			if (this.teaser_row.hasClass("new-message")) {
				this.teaser_row.removeClass("new-message");
				this.new_img.addClass("hidden");
				this.unread_img.addClass("hidden");
//				this.read_img.removeClass("hidden");
			}
			this.teaser_row.addClass("current");
			// show record body
			this.body_row.removeClass("hidden");
			// swap toggle button
			this.set_button_to_less();
			this.open_status = true;
			// if this is a message, set message to read via ajax
			if ($(".messages-table").length > 0 && this.read_status != true) {
				var cached_id = this.id;
				console.log("sending message read notice via ajax:" + "action=mark_message_read&message_id=" + cached_id);
				$.ajax({
					  url: '/api.php',
					  data: 'action=mark_message_read&message_id=' + cached_id,
					  dataType: 'json',
					  type: 'post',
					  error : function (XMLHttpRequest, textStatus, errorThrown) {
						  // typically only one of textStatus or errorThrown 
						  // will have info
						  console.log("Ajax Error: "+textStatus.msg);
					  },			  
					  success: function (j) {
						console.log("Ajax Success: "+j);			  
					  }
				});
				this.read_status = true;	
			}
			// calculate new height and set column wrapper
			this.message_height = this.message_box.height();
			if (this.message_height > this.original_height) {
				this.new_page_height = this.message_height + 7;
				$('.column-wrapper').height(this.new_page_height);	 							
			}
		}
		this.close = function() {
			// show record body
			this.body_row.addClass("hidden");
			this.teaser_row.removeClass("current");
//			uncurrent_all_records();
			// swap toggle button
			this.set_button_to_more();
			this.open_status = false;
			// set column wrapper back to original height
			if (this.new_page_height) {
				$('.column-wrapper').height(this.original_height);	 			
			}
		}
		this.toggle = function() {
			console.log('moreinfobutton: ' + this.moreinfobutton.src);//  20090226-- want to have entire row activate more-info functionality
			this.moreinfobutton.click();//  20090226-- want to have entire row activate more-info functionality
			return true;  //  20090226-- want to have entire row activate more-info functionality
			if (this.open_status == true) {
				this.close();
			}
			else {
				this.open();
			}
		}
		// toggle button methods
		this.set_button_to_less = function() {
			var old_src = this.toggle_button.src;
			// figure out which image to swap to
			if (old_src.search(/more/) > 0) {
				new_src = old_src.replace(/more/, "less");
			}
			this.set_button(new_src);
		}
		this.set_button_to_more = function() {
			var old_src = this.toggle_button.src;
			// figure out which image to swap to
			if (old_src.search(/less/) > 0) {
				new_src = old_src.replace(/less/, "more");
			}
			this.set_button(new_src);
		}
		this.toggle_the_button = function() {
			var old_src = this.toggle_button.src;
			// figure out which image to swap to
			if (old_src.search(/more/) > 0) {
				new_src = old_src.replace(/more/, "less");
			}
			else {
				new_src = old_src.replace(/less/, "more");
			}
			this.set_button(new_src);
		}
		this.set_button = function(new_src) {
			// make sure image is hover version
			if (new_src.search(/off/) > 0) {
				new_src = new_src.replace(/off/, "hover");
			}
			// reset vars
			this.toggle_button.hover_src = new_src;
			this.toggle_button.off_src = new_src.replace("_hover", "_off");
			// swap image
			this.toggle_button.src = new_src;
		}
		// apply toggle event
		var cached_this = this;
		this.toggle_cells.each(function() {
			$(this).css("cursor", "pointer");
			$(this).bind("click", function(event) {
				cached_this.toggle();
//				return false;  // commented out 20090226-- want to have entire row activate more-info functionality
			});
		});
		// set close button event
		this.close_button.bind("click", function(event) {
			// show record body
			cached_this.close();
			// stop click event
			return false;
		});
		// set checkbox event
		this.checkbox_col.bind("click", function() {
			cached_this.toggle_checkbox();
		});
		// set checkbox cursor
		this.checkbox_col.css("cursor", "pointer");
		this.checkbox.css("cursor", "pointer");
	}
	// instantiate records 
	$(document).ready(function(){
		if ( $("table.event-list-table").length > 0 ) {
			//do something
			event_list_flag = true;
		}
		$('tr[@class*=record-teaser]').each(function(i) {
			all_records[i] = new record(this);
		}); 
	})

// DATA HELPER FUNCTIONS
	var cached_compose_name; 
	$(document).ready(function(){
	  // Login Name Helper
	  
	  var login_name_msg = $('.login-name-msg');
  	  $('.login-name-input').keyup(function () {
  	  	  console.log("starting the login name validator");
		var t = this; 
		// if this is a new key click
		if (this.value != this.lastValue) {
		  if (this.timer) clearTimeout(this.timer);
		  login_name_msg.removeClass('login-name-error').html('<em>Checking availability...</em>');
		  // set timer for each request
		  this.timer = setTimeout(function () {
			$.ajax({
			  url: '/api.php',
			  data: 'action=check_login_name&user_string=' + t.value,
			  dataType: 'json',
			  type: 'post',
			  error : function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
				  console.log("Ajax Error: "+textStatus.msg);
				  login_name_msg.html(textStatus.msg); // the options for this ajax request
				},
			  success: function (j) {
				console.log("Ajax Success: "+j.value);			  
                if (j.ok)
                {
                    if (j.msg)
                    {
                        login_name_msg.html(j.msg);
                    }
                }
                else
                {
                    if (j.msg)
                    {
                        login_name_msg.addClass('login-name-error').html(j.msg);
                    }
                }
			  }
			});
		  }, 200);
		  
		  this.lastValue = this.value;
		}
	  });
	  
	  // Manager Picker Helper
	  
	  var manager_name_msg = $('.manager-name-msg');
	  $('.manager-name-input').keyup(function () {
	  	  console.log("starting the manager name validator");
		var t = this; 
		// if this is a new key click
		if (this.value != this.lastValue) {
		  if (this.timer) clearTimeout(this.timer);
		  manager_name_msg.removeClass('error').html('<em>Checking users...</em>');
		  // set timer for each request
		  this.timer = setTimeout(function () {
			$.ajax({
			  url: '/api.php',
			  data: 'action=check_manager_name&user_string=' + t.value,
			  dataType: 'json',
			  type: 'post',
			  error : function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
				  manager_name_msg.addClass('error').html(textStatus.msg); // the options for this ajax request
				  manager_name_msg.css("color","#F00");
				},			  
			  success: function (j) {
				manager_name_msg.html(j.msg);
				if (j.ok) {
				  manager_name_msg.removeClass('error')
				} else {
				  manager_name_msg.addClass('error')
				}
			  }
			});
		  }, 200);
		  
		  this.lastValue = this.value;
		}
	  });
	})

// WEEKLY SCHEDULE CLICKABLE FUNCTION
	$(document).ready(function(){
		// weekly calendar page
		$(".daily-schedule-table").each(function() {
			// for each day, get link
			var link = $(this).find("th a").get(0);
			// for each td, apply click and hover event
			$(this).find("td").each(function() {
				$(this).bind("click", {link:link}, function() {
					window.location = link;
				});
				$(this).hover(
				  function () {
					$(this).addClass("hover");
				  }, 
				  function () {
					$(this).removeClass("hover");
				  }
				);
			});
		});
		// monthly cal table
		$(".monthly-cal-table td").each(function() {
			$(this).bind("click", function() {
				var url_string = "?day&timestamp=" + this.id;
				window.location = url_string;
			})
			$(this).hover(
			  function () {
				$(this).addClass("hover");
			  }, 
			  function () {
				$(this).removeClass("hover");
			  }
			);
		});
	})

// PHOTO PAGE FUNCTIONALITY
      
	$(document).ready(function(){
		// for each photo browse module
		nomoreinfo=false;
		$('.photo-box').each(function() {
			$(this).bind("click", function() {
				console.log('looking for moreinfo button');
				this.moreinfobutton = $(this).find("input[src*=moreinfo]").get(0);
				if (typeof(this.moreinfobutton)=="undefined") {
					console.log('moreinfo button not found, trying readmore');
					this.moreinfobutton = $(this).find("input[src*=readmore]").get(0);
					if (typeof(this.moreinfobutton)=="undefined") console.log('readmore button not found');
				}
				console.log(this.moreinfobutton.src);//  20090226-- want to have entire row activate more-info functionality
				if (!nomoreinfo) this.moreinfobutton.click();//  20090226-- want to have entire row activate more-info functionality
				return true;  //  20090226-- want to have entire row activate more-info functionality
			});
		});
		$('.photo-box').find("input[src*=playvideo]").each(function() {
			$(this).bind("click", function() {
				console.log('enlarge pressed');//  20090226-- want to have entire row activate more-info functionality
				nomoreinfo=true;
				this.click();
				return true;
			});
		});
		$('.photo-box').find("input[src*=enlarge]").each(function() {
			$(this).bind("click", function() {
				console.log('enlarge pressed');//  20090226-- want to have entire row activate more-info functionality
				nomoreinfo=true;
				this.click();
				return true;
			});
		});
		$('.photo-browse').find(":checkbox").each(function() {
			$(this).bind("click", function() {
			// add click event to each photo box
				if (this.active == true) {
					// set to inactive
					$(this).removeClass("active");
					$(this).find(":checkbox").attr("checked", false);
					this.active = false;
					checked_records_count--;
				}
				// else set to active
				else {
					$(this).addClass("active");
					$(this).find(":checkbox").attr("checked", true);
					this.active = true;
					checked_records_count++;
				}
				console.log("checked photos = "+checked_records_count);
				refresh_button_row();
			});
		});
		$('.photo-browse').each(function() {
			// add hover events and cursor to photo boxes
			$(this).css("cursor", "pointer");
			$(this).hover(function() {
			  $(this).addClass("hover");
			},
			function(){
			  $(this).removeClass("hover");
			});
		});
		     
	})	 

// BUTTON ROW FUNCTIONALITY
      
	$(document).ready(function(){
		refresh_button_row();
		     
	})	 
	function refresh_button_row() {
	    // for each button element
	    $(".buttons-row input").each(function(){
	    	// get name and sibling
	    	var button_name = this.value;
	    	var disabled_button_img = $(this).next();
	    	// if this button is in the page buttons array
	    	if ((page_buttons) && (page_buttons[button_name])) {
	    		// get button settings and elements
	    		var this_button = page_buttons[button_name];
	    		// get action based on how many items are checked
	    		if ((checked_records_count == 0) && (this_button['unchecked'])) { 
	    			new_state = this_button['unchecked'];
	    		}
	    		else if ((checked_records_count > 1) && (this_button['multichecked'])) {
				 new_state = this_button['multichecked'];
	    		}
	    		else {
	    			new_state = 1;
	    		}
	    		// set new state
	    		switch(new_state) {
	    			case 0:	    
	    				// button is removed from page	    
	    				$(this).hide();
	    				$(disabled_button_img).hide();	    
	    			break;
	    			case 1:
	    				// button is active
	    				$(this).show();
	    				$(disabled_button_img).hide();	    
	    			break;
	    			case 2:
	    				// button is disabled	    
	    				$(this).hide();
	    				$(disabled_button_img).show();	    
	    				$(disabled_button_img).removeClass("hidden");	    				    
	    			break;
	    		}			// end switch
	    	}				// end if then page button subroutine
	    });	  		    	// end buttons jQuery loop
	}

// HOMEPAGE GREEN CHECKBOX / AJAX FUNCTIONALITY
	$(document).ready(function(){
		// if this is the homepage, set message to read via ajax
		if ($(".homepage-table").length > 0) {
			$(".checkbox-col").each(function() {
				var checked_img = $(this).find("img");
				// alert(checked_img);
				if (checked_img.css("display") == "block") {
					this.checked_status = true;
				}
				else {
					this.checked_status = false;
				}
				$(this).bind("click", function() {
					if (this.checked_status != true) {
						set_checkbox_to_true(this);
					}
					else {
						set_checkbox_to_false(this);
					}
				 });					 
			});				// end checkbox loop
		}					// end if homepage
	})
function set_checkbox_to_true(checkbox_col) {
	// replace input with checkbox img
	$(checkbox_col).find(":checkbox").hide();
	$(checkbox_col).find("img").show();
	// send mark_event_done message
	var cached_id = $(checkbox_col).find(":checkbox").get(0).value;
	console.log("sending event marked notice via ajax:" + "action=mark_event_done&event_id=" + cached_id);
	$.ajax({
		  url: '/api.php',
		  data: 'action=mark_event_done&event_id=' + cached_id,
		  dataType: 'json',
		  type: 'post',
		  error : function (XMLHttpRequest, textStatus, errorThrown) {
			  // typically only one of textStatus or errorThrown 
			  // will have info
			  console.log("Ajax Error: "+textStatus.msg);
		  },			  
		  success: function (j) {
			console.log("Ajax Success: "+j);			  
		  }
	});
	checkbox_col.checked_status = true;
}
function set_checkbox_to_false(checkbox_col) {
	// replace checkbox img with input
	$(checkbox_col).find(":checkbox").get(0).checked = false;
	$(checkbox_col).find(":checkbox").show();
	$(checkbox_col).find("img").hide();
	// send mark_event_done message
	var cached_id = $(checkbox_col).find(":checkbox").get(0).value;
	console.log("sending event marked notice via ajax:" + "action=unmark_event_done&event_id=" + cached_id);
	$.ajax({
		  url: '/api.php',
		  data: 'action=unmark_event_done&event_id=' + cached_id,
		  dataType: 'json',
		  type: 'post',
		  error : function (XMLHttpRequest, textStatus, errorThrown) {
			  // typically only one of textStatus or errorThrown 
			  // will have info
			  console.log("Ajax Error: "+textStatus.msg);
		  },			  
		  success: function (j) {
			console.log("Ajax Success: "+j);			  
		  }
	});
	checkbox_col.checked_status = false;
}

// STATUS POLLING
  var status_last_time = null;
function calendar_reload_page()
{
    window.location.reload();
}
function calendar_update_header(response)
{
    var cur_time = response['current_time'];

    if (cur_time)
    {
        if (status_last_time)
        {
            if (status_last_time['j'] != cur_time['j'])
            {
                setTimeout(calendar_reload_page, 2000);
            }
            else if ((status_last_time['g'] != cur_time['g'])
                     || (status_last_time['i'] != cur_time['i'])
                     || (status_last_time['A'] != cur_time['A']))
            {
                var ntime = cur_time['g'] + ':' + cur_time['i'] + ' ' + cur_time['A'];
                $('#cal-daymode-time').html(ntime);
            }
        }

        status_last_time = cur_time;
    }
}
    var status_check_callbacks = new Array();
    function add_status_check_handler(hdlr)
    {
        status_check_callbacks[status_check_callbacks.length] = hdlr;
    }
    function run_status_check_handlers(response)
    {
        var cb;
        var idx;

        for (idx=0 ; idx < status_check_callbacks.length ; idx++)
        {
            cb = status_check_callbacks[idx];
            cb(response);
        }
    }

	var status_timer;
	var popup_visible_flag = false;
	function check_status() {
		console.log("checking status");
		// clear status timer
		if (status_timer) clearTimeout(status_timer);
		// get status update, handle respone and and reset timer upon success
		$.ajax({
			  url: '/api.php',
			  data: 'action=get_user_status',
			  dataType: 'json',
			  type: 'post',
			  error : function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
				  console.log("Ajax Error: "+textStatus.msg);
			  },			  
			  success: function (j) {
				console.log("Ajax Success: "+j);
				if (j) {
					handle_status_response(j);

                        // set timer for new status check
                        status_timer = setTimeout(check_status, 10000);
				}
                else
                {
                    // a null return value indicates no users are logged in, so let's give up
                    // checking.
                }
			 }
		});
	}
	function handle_status_response(response) {
		// check for new messages
		newmessages = 0;
		for (i in response['nav_updates']) {
			newid="#"+i+"_new_flag";
			if (response['nav_updates'][i]>0) {
				$(newid).removeClass("hidden");
			} else {
				$(newid).addClass("hidden");
			}
			// newmessages += response[messages][i][new[total]];
		}
		// if there is no popup currently visible, launch 1 popup
		for (i in response['events']) { 
			if (popup_visible_flag != true) {
				popup_visible_flag = true;
				launch_popup(response['events'][i]);
			}
		}
		// old loop: for (i in response['events']) { launch_popup(response['events'][i]); }

        // run all the registered handlers
        run_status_check_handlers(response);
            
	}
	$(document).ready(function(){
		status_timer = setTimeout(check_status, 5);
	})

// popup functions
	function launch_popup(event) {
		console.log("launch popup event = " + event);
		// build popup in dom
		var popup = $('<div class="popup"></div>').appendTo("body");
		if (event.message) var popup_message = $(event.message).appendTo(popup);
		if (event.buttonimage) {
			var button_html = '<input type="image" value="' + event.buttonlabel + '" src="/famililink/images/round_buttons/btn_' + event.buttonimage + '_off.png" alt="' + event.buttonlabel + '" />';
			var popup_button = $(button_html).appendTo(popup);
		}
		else if (event.image) {
			var button_html = '<img src="/famililink/images/' + event.image + '" alt="' + event.buttonlabel + '" />';
			 console.log("button html = "+ button_html);
			var popup_button = $(button_html).appendTo(popup);
		}
		else if (event.buttonlabel) {
			var button_html = '<input type="submit" value="' + event.buttonlabel + '" />';
				var popup_button = $(button_html).appendTo(popup);
		}
		switch(event.status) {
			case 1:
				var popup_class = "notice";
				var overlay_class = "hidden";
			break;    
			case 2:
				var popup_class = "alert";
				var overlay_class = "hidden";
			break;
			case 3:
				var popup_class = "confirmation";
				// var popup_button = $('<input type="submit" value="' + event.buttonlabel + '" />').appendTo(popup);
				var overlay_class = "jqmOverlay";
			break;
		}
		// set rollover and focus state
		if (event.buttonimage) {
			set_rollover_button(popup_button.get(0), true);
			popup_button.blur();
			popup_button.css("outline", "none");
		}
        else
        {
            popup.find('.rollover-button').each(function(i) {
                set_rollover_button(this, true);
            });
        }
		popup.addClass(popup_class);
		// instantiate popup
		popup.jqm({
			modal: true,
			toTop: true,
			overlayClass: overlay_class
		}); 
		console.log("Instantiated jqm modal popup:" + popup);
		// add closing event
		popup.find("input").bind("click", {event: event}, function() {
			$(popup).jqmHide();
			// send ajax log message #2, with answer
			log_event(event, this.value);
			// set popup visible flag
			popup_visible_flag = false;
		});
		popup.find("a").bind("click", {event: event}, function() {
			$(popup).jqmHide();
			// send ajax log message #2, with answer
			log_event(event, this.value);
			// set popup visible flag
			popup_visible_flag = false;
		});
		console.log("Showing popup: " + event.message);
		// send ajax log message #1
		log_event(event);
		// also want type, id, title, text
		$(popup).jqmShow();
	}
	function log_event(event, answer) {
		// build query string
		var query_string = "action=log_event&event_id=" + event.event_id + "&type=" + event.type;
		if (answer) {
			query_string += "&answer=" + answer; 
		}
		console.log("Sending ajax request: " + query_string);
		// send ajax request
		$.ajax({
			url: '/api.php',
			data: query_string,
			dataType: 'json',
			type: 'post',
			error : function (XMLHttpRequest, textStatus, errorThrown) {
			  console.log("Ajax Error: "+textStatus.msg);
			},			  
			success: function (j) {
			  console.log("Ajax Success: "+j);
			}
		});
	}

// demo popups
	$(document).ready(function(){
		$('.trigger-notice').bind("click", function() {
			var event_json = {"event_id":12345,"status":1,"buttonlabel":"","buttonimage":"dismiss","type":"medical","starttime":1222187323,"duration":54000,"message":"<div class=\"dismiss\"><a href=\"#\" >DISMISS [X]</a></div><p>Sample Notice</p>"};
			var event = eval(event_json);
			popup_visible_flag = true;
			launch_popup(event);
			return false;
		});
		$('.trigger-alert').bind("click", function() {
			var event_json = {"event_id":12346,"status":2,"buttonlabel":"Confirm","buttonimage":"confirm","type":"medical","starttime":1222187323,"duration":54000,"message":"Sample Alert"};
			var event = eval(event_json);
			popup_visible_flag = true;
			launch_popup(event);
			return false;
		});
		$('.trigger-confirmation').bind("click", function() {
			var event_json = {"event_id":12347,"status":3,"buttonlabel":"Confirm","buttonimage":"confirm","type":"medical","starttime":1222187323,"duration":54000,"message":"Sample Confirmation"};
			var event = eval(event_json);
			popup_visible_flag = true;
			launch_popup(event);
			return false;
		});							
	})

// DISPLAY CONTROLS DROPDOWNS
	$(document).ready(function(){
		$(".display-controls select").each(function() {
			$(this).bind("change", function() {
/*
				alert($(this).attr("name") + " select value = " + $(this).val());
				alert ('<input type="hidden" value="" name="e_c"/>');
*/
				$(".display-controls").append('<input type="hidden" value="' + $(this).val() + '" name="e_c"/>');
				$('#postform1').submit();
				return false;
			});
		});
	})

// JQUERY DATEPICKER
        $(document).ready(function(){
//          $('#datepicker_start').datepicker({ changeMonth: false, changeYear: false, changeFirstDay: false });
//          $('#datepicker_end').datepicker({ changeMonth: false, changeYear: false, changeFirstDay: false });
    });

// COMPOSE NAME AUTOCOMPLETE
  $(document).ready(function(){
    // var dummy_data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
          var jq = $(".compose-name-input");
          if ((jq.length > 0) && (typeof jq.autocomplete == 'function'))
          {
              jq.autocomplete("/autocomplete.php", {
                      multiple: true,
                          width : 200,
                          matchContains: true
                          });
          }
  });
  
	$(document).ready(function(){
// ticket#15 disable & grey out navigation links until after save or cancel
		$("input:hidden").each(function() {
                        // look at all the hidden inputs
			console.log($(this).attr("name") + " : " + $(this).val());
			if($(this).attr("name") == "menustate"   && $(this).val() == "disabled" ) { // msgs, pics, contacts
				$("ul.primary-nav a")         // select navigation tabs
					.fadeTo("fast", 0.67) // fade out primary nav links
					.click(function () {  // add click handler
						return false; // return false, so we don't follow link
					});
;


			}
		});
		$("#errornotice").click(function(){
//			alert ("found erornotice");
			$(this).hide();
			});

// LONG FORM SUBMIT, create modal popup with "Please be patient while processing is complete. Thank you."
// ticket#22 don't display modal dialog of user cancels sgoodwin 2/25/2009
// changed selector to click handler and not cancel inputs
		$(".longrunsubmit").click(function(event) {
			if ($(event.target).is('input')) {
        			var event_json = {"event_id":0,"status":3,"buttonlabel":"Please be patient while processing is complete. Thank you.","type":"submit","starttime":1222187323,"duration":54000,"image":"misc/loading.gif"};
        			var event = eval(event_json);
        			popup_visible_flag = true;
        			launch_popup(event);
//        			for (i=0;i<15000;i++) {};
        			return true;
        		}
        		else {
//        			alert('not an input');
        		}
		});


	});

/*
 * support for calling "nested" forms.
 * used to load a new url in the page without using query strings
 */

function flink_makeCallFormInput(name, value, prefx)
{
    var rv = '';

    if (typeof value == 'object')
    {
        var npfx = (prefx.length > 0) ? prefx + '[' + name + ']' : name;
        var key;
        for (key in value)
        {
            rv += flink_makeCallFormInput(key, value[key], npfx);
        }
    }
    else
    {
        rv = '<input type="hidden" name="' + prefx;
        if (prefx.length > 0)
        {
            rv += '[';
        }
        rv += name;
        if (prefx.length > 0)
        {
            rv += ']';
        }
        rv += '" value="' + value + '"/>';
    }

    return rv;
}

function flink_makeCallFormContainer(url, params)
{
    var fs = '<div style="display: none;"><form method="POST" action="' + url + '">';
    
    var key;
    for (key in params)
    {
        fs += flink_makeCallFormInput(key, params[key], '');
    }
    
    fs += '<input type="submit" name="submit" value="submit"/></form></div>';
    
    return $(fs);
}

/*
 * create a form object to load a new url in the page without using query strings
 * The form is appended to the body (hidden). The parameters are an associative array that
 * may contain other asociative or regular arrays (technically, other objects).
 */

function flink_callForm(url, params)
{
    var div = flink_makeCallFormContainer(url, params);
    var form = $('form', div);
    var submit = $('input[type="submit"]', form);

    $('body').append(div);

    submit.trigger('click');
}
