(function($){
	$(document).ready(function() {
		// Identify the options menus
		$('.hoverOptions').each(function(index, Element){
			// Add a unique Class to each hoverOptions and link the previous A to that class
			var divClass = 'hoverOptionsDiv_' + index;
			var linkClass = 'hoverOptionsLink_' + index;
			$(Element).addClass(divClass).data('hoverOptionID',index);
			
		});
		// Link the options menu
		$('.hoverOptions').prev('a').click(function(ev){
			$showOptionsMenu(ev, $(this));
		});
		// Make sure the options menu gets repositioned if the window's resized
		$(window).resize(function(ev){
			$('.hoverOptions:visible').each(function(index, Element){
				var hoverLink = $('.hoverOptionsLink_'+ $(Element).data('hoverOptionID'));
				positionHoverOptions($(Element), hoverLink);
			});
		});
	});
	
	$showOptionsMenu = function(ev, hoverItem){
		ev.preventDefault();
		
		// check to see if the hoverItem has been previously initialised
		if(typeof(hoverItem.data('hoverOptionID')) == 'undefined'){
			var hoverOptionID = hoverItem.next().data('hoverOptionID');
			hoverItem.addClass('hoverOptionsLink_'+hoverOptionID).data('hoverOptionID',hoverOptionID);
		}else{
			var hoverOptionID = hoverItem.data('hoverOptionID');
		}
		//handlerIn
		var hoverOptionsDiv = $('.hoverOptionsDiv_'+hoverOptionID);
		if(!hoverOptionsDiv.is(':visible')){
			//hide all other hover options other than this one
			$('.hoverOptions').not(hoverOptionsDiv).hide(); 
			positionHoverOptions(hoverOptionsDiv, hoverItem);
		}else{
			hoverOptionsDiv.hide();
		}
	}
	
	var positionHoverOptions = function(hoverOptionsDiv, hoverItem){
		// Absolutely position the hoveroptionsDiv and add it to the body
		hoverOptionsDiv.css({position:'absolute',whiteSpace:'nowrap'}).show().appendTo('body'); 
		var topOffset = ((hoverItem.outerHeight() - hoverOptionsDiv.outerHeight())/2) + hoverItem.offset().top ; //calculate the offset required to vertically centre the hovered options menu 
		var leftOffset = hoverItem.offset().left - hoverOptionsDiv.outerWidth();
		hoverOptionsDiv.css({
			left:leftOffset +'px',
			top:topOffset+'px',
		});
		var newOffset = hoverOptionsDiv.offset();
		if(newOffset.left < 0){ // Oops, the user can't see the dialogue, to the right with it!
			hoverOptionsDiv.css({
				left:  (hoverItem.offset().left + hoverItem.outerWidth())+ 'px',
			});
		}
	}
})(jQuery);;
(function($){
	
	$(document).ready(function(){
		window.classSchedulePath = $("#classSchedulePath").val();
		window.drupalPath = $("#drupalPath").val();
		initializePage(); //just put this in a function so we can call it after an ajax query returns
	});
	jQuery.expr[":"].regex = function(elem, index, match) {
		var matchParams = match[3].split(","),
			validLabels = /^(data|css):/,
			attr = {
				method: matchParams[0].match(validLabels) ? 
							matchParams[0].split(":")[0] : "attr",
				property: matchParams.shift().replace(validLabels,"")
			},
			regexFlags = "ig",
			regex = new RegExp(matchParams.join("").replace(/^\s+|\s+$/g,""), regexFlags);
		return regex.test(jQuery(elem)[attr.method](attr.property));
	}

	function initializePage(){
		$("td:regex(class, .*classID_.*)").unbind("hover");
		$("td:regex(class, .*studentID_.*)").unbind("dblclick");
		/**
		** Function disabled for performance reasons.
		** Allows a mouse hover to highlight all the cells with the same student class in them
		***
		$("td:regex(class, .*classID_.*)").hover(function(){
			//cycle through and grab the full classID classname
			infoArray = $(this).attr("class").split(" ");
			for(var i in infoArray){
				if(infoArray[i].indexOf("classID_") >-1){
					classID = infoArray[i];
				}
			}
			classID = classID.split(" ");
			classID = classID[0];
			$("." + classID).css("background-color","beige");
			
		},function(){
			//cycle through and grab the full classID classname
			infoArray = $(this).attr("class").split(" ");
			for(var i in infoArray){
				if(infoArray[i].indexOf("classID_") >-1){
					classID = infoArray[i];
				}
			}
			classID = classID.split(" ");
			classID = classID[0];
			$("." + classID).css("background-color","white");
			
		
		}); */
		$("td.classCell").dblclick(function(){ editCell($(this)) });
		$('td.studentName').dblclick(function(){replicateClasses($(this));});
	}

	displayDialog = function(title, content, modal, buttons,dimensions){
			var modal = typeof(modal) != 'undefined' ? modal : true; //default is modal
			var width =  typeof(dimensions) != 'undefined' ? dimensions[0] : 'auto';
			var height =  typeof(dimensions) != 'undefined' ? dimensions[0] : 'auto';
			var buttons = typeof(buttons) != 'undefined' ? buttons : {};
			var tempID = new Date().getTime();
			tempID = 'dialog_' + tempID;
			$('body').append('<div id="'+tempID+'">' + content +'</div>');
			var newDialogBox = $('#'+tempID);
			newDialogBox.dialog({
				modal: modal,
				title: title,
				buttons: buttons,
				height: height,
				width: width,
				resizable: false
			});
			return newDialogBox;
		}

	function replicateClasses(theCell){
		var copyToStudent = theCell.attr('class');
		copyToStudent = copyToStudent.match(/studentID_[0-9]{1,4}/);
		copyToStudent = copyToStudent[0].replace('studentID_','');
		
		$.post(window.drupalPath+"/?q=classschedule_beastajax",{fetchStudents: true},function(result){
			var studentsArray = $.parseJSON(result);
			var studentsDropDown = '<p style="font-weight:bold;"><br/><label for="studentToCopy">Select Student To Copy:</label><select name="studentToCopy">';
			for(x in studentsArray){
				studentsDropDown += '<option value="' + studentsArray[x]['UID'] + '"> ' + x + '</option>';
			}
			studentsDropDown += '</select></p>';
			var theContent = 'Use this function to make this student attend all the same classes as another student <br/>' +
								'Please note, this will <strong>remove</strong> any currently scheduled classes for this student that conflict <br/>'+ studentsDropDown;
			var theDialog = displayDialog('Replicate Classes', theContent, true,{
					Cancel: function(){
							theDialog.dialog('destroy');
					},
					Copy: function(){
							var copyFromStudent = theDialog.find('select[name=studentToCopy] > option:selected').val();
							$.post(window.drupalPath+'/?q=classschedule_beastajax', 
								{
									replicateClasses: 1,
									copyToStudent: copyToStudent,
									copyFromStudent: copyFromStudent
								},
								function(data){
									results = $.parseJSON(data);
									if(results['success']){
										for(x in results['newClasses']){
											var curClass = results['newClasses'][x];
											var cellID = curClass['classTimeSlot']+curClass['classDay']+copyToStudent;
											var cellID = cellID.replace(/[^a-zA-Z0-9]/g,'');
											$('#cell'+cellID).html(curClass['className']);
										}
									}else{
										alert(results['errorMessage']);
									}
								});	
							theDialog.dialog('destroy');
						}
					
				});
		});

	}

	 $.fn.populateNewClass = function(cells){
		//called by the iframe that has "create new class" or "edit class" when it closes
		for(var i in cells){
			if(i == 0){
				classID = cells[i];
			}else{
				var classCell = $("#"+cells[i][0]);
				classCell.html(cells[i][1]);
				//cycle through the classes assigned to this cell and remove any classID_ classes
				infoArray = classCell.attr("class").split(" ");
				for(var i in infoArray){
					if(infoArray[i].indexOf("classID_") >-1){
						classCell.removeClass(infoArray[i]);
					}
				}
				classCell.addClass("classID_"+classID);
			}
		}
		initializePage();
	}
	function cancelEditTimeSlot(formID,disableLoadingGIF){
		var theForm = $('#'+formID);
		disableLoadingGIF  = disableLoadingGIF || 0;
		if(typeof(formID) == "object"){
			theCell = formID;
		}else{
			if(formID.indexOf("timeSlot") >= 0){
				theForm.each(function(i){cancelEditTimeSlot($(this),1)});
			}else{
				theCell = theForm.parent();
				
			}
		}
		
		infoArray = theCell.attr("class").split(" ");
		for(var i in infoArray){
			subArray = infoArray[i].split("_");
			switch (subArray[0]){
				case "studentID":{
					var studentID = subArray[1];break }
				case "timeSlot":{
					var timeSlot = subArray[1]; break }
				case "weekDay":{
					var weekDay = subArray[1]; break}
			}
		}
		if(disableLoadingGIF == 0){ //used for when were coming back from class add as otherwise the loading gif will go to the last applicable cell
			theCell.addClass('classscheduleLoading').html('');
		}
		cellID = theCell.attr("id");
		$.post(window.drupalPath+"/?q=classschedule_beastajax",{
			studentID: studentID,
			timeSlot: timeSlot,
			weekDay: weekDay ,
			cellID: cellID,
			cancelEdit: 1},
			function(result){
				var result = $.parseJSON(result);
				console.log(result);// debug
				cellID = result['cellID'];
				$("#"+cellID).html(result['output']);
				$("#"+cellID).removeClass('classscheduleLoading');
				initializePage();
			}
		);
	}

	function clearTimeSlot(formID){
		formID = "#" + formID;
		var theForm = $(formID);
		var parent = theForm.parent();
		timeSlot = theForm.find("[name=timeSlot]").val();
		studentID =theForm.find("[name=studentID]").val();
		weekDay = theForm.find("[name=weekDay]").val();
		parent.html("");
		//cycle through the classes assigned to this cell and remove any classID_ classes
		infoArray = parent.attr("class").split(" ");
		for(var i in infoArray){
			if(infoArray[i].indexOf("classID_") >-1){
				parent.removeClass(infoArray[i]);
			}
		}
		parent.addClass("classID_0");
		$.post(window.drupalPath+"/?q=classschedule_beastajax",{
			studentID: studentID,
			timeSlot: timeSlot,
			weekDay: weekDay ,
			clearTimeSlot: 1},
			function(result){
				parent.html(result);
				initializePage();
			}
		);
	}


	function editCell(start) {
		editForm = $("form.editTimeslotForm");
		if(editForm.length > 0){ //if there are any other open edit forms remove them
			cancelEditTimeSlot(editForm.attr("id"));
			initializePage();
		}
		var cellID = start.attr("id");
		$("#"+cellID).addClass('classscheduleLoading').html('');
		infoArray = start.attr("class").split(" ");
		for(var i in infoArray){
			subArray = infoArray[i].split("_");
			switch (subArray[0]){
				case "studentID":{
					var studentID = subArray[1];break }
				case "timeSlot":{
					var timeSlot = subArray[1]; break }
				case "weekDay":{
					var weekDay = subArray[1]; break}
			}
		}
		$.post(window.drupalPath+"/?q=classschedule_beastajax",{
				studentID: studentID,
				timeSlot: timeSlot,
				weekDay: weekDay ,
				cellID: cellID,
				edit: 1},
				function(result){
					var result = $.parseJSON(result);
					var cellID = result['cellID'];
					$("#" + cellID).html(result['content']).removeClass('classscheduleLoading');
					var formID = result['formID'];
					var theForm = $('#'+formID);
					$("#" + cellID).unbind("dblclick");
					$().tb_init("a.thickbox, area.thickbox, input.thickbox"); //thickbox! yay!
					
					//bind the cancel button
					$("#cancelEdit").click(function(ev){ev.preventDefault();cancelEditTimeSlot(result['formID'])});
					//bind the clear button
					$("#clearTimeSlot").click(function(ev){ev.preventDefault();clearTimeSlot(result['formID'])});
					
					//bind the insert class (in reality 'insert class' adds the student to the class)
					theForm.find('.insertClass').click(function(ev){
						ev.preventDefault();
						var theForm = $(this).parent();
						classID = theForm.find("select[name=class]").val();
						timeSlot = theForm.find("input[name=timeSlot]").val();
						studentID = theForm.find("input[name=studentID]").val();
						weekDay = theForm.find("input[name=weekDay]").val();
						$.post(window.drupalPath+"/?q=classschedule_beastajax",{
							studentID: studentID,
							timeSlot: timeSlot,
							weekDay: weekDay ,
							classID: classID,
							changeClass: 1},
							function(result){
								result = result.split("!-!++_)_");
								$("#" + cellID).html(result[0]);
								
								//cycle through the classes assigned to this cell and remove any classID_ classes
								infoArray = $("#" + cellID).attr("class").split(" ");
								for(var i in infoArray){
									if(infoArray[i].indexOf("classID_") >-1){
										$("#" + cellID).removeClass(infoArray[i]);
									}
								}
								$("#" + cellID).addClass("classID_"+result[1]);
								initializePage();
							}
						);
					});
					
					theForm.find('.editClass').click(function(ev){
						ev.preventDefault();
						$().tb_show("",window.drupalPath + "?q=classschedule_editclass_nostyle&noStyle=1&CID="+theForm.find("[name=class]").val()+"&KeepThis=true&TB_iframe=true&height=400&width=600",false);
					});
				}
				
		);

	}
})(jQuery);;
(function($){
/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "sites/all/modules/classschedule/scripts/thickbox/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	$().tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
$.fn.tb_init =function (domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	$().tb_show(t,a,g);
	this.blur();
	return false;
	});
}

$.fn.tb_show = function(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click($().tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click($().tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click($().tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					$().tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					$().tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					$().tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click($().tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='jQuery().tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='jQuery().tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click($().tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						$.tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					$().tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
$.fn.tb_showIframe =  function(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

$.fn.tb_remove = function() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
})(jQuery);

;
(function($){

// Basic Cookie functions
function createCookie(name,value,minutes) {
	if (minutes) {
		var date = new Date();
		date.setTime(date.getTime()+(minutes*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

$(document).ready(function(){ 
	
	// Enable Show More Info button
	$('#classchedule_moreInfo').click(function(ev){
		ev.preventDefault();
		if($('#classschedule_users > thead > tr th.classschedule_userData').is(':visible')){
			$('.classschedule_userData').hide();
			$('#classchedule_moreInfo').text('Show More Info');
		}else{
			$('.classschedule_userData').show();
			$('#classchedule_moreInfo').text('Hide More Info');
		}
	});
	
	// Enable tablesorter
	$('#classschedule_users').tablesorter({
		 headers: {
            0: {
                sorter: false,
            },
            1:{
                 sorter: 'text',
			},
			2:{
                 sorter: 'text',
			},
            4: {
                sorter: false
            }
        }
	});
	
	/**
	** Enable User Multi-select
	**/ 
	var selectionBoxes = $('input.classschedule_selectUser');
	selectionBoxes.change(function(ev){
		var curCheckbox = $(this);
		if($('input.classschedule_selectUser:checked').length > 0){
			// If at least one section box is checked
			$('#classschedule_deleteSelectedUsers, #classschedule_generatePasswordPDF').parent().show();
		}else{
			// If no selection boxes are checked
			$('#classschedule_deleteSelectedUsers, #classschedule_generatePasswordPDF').parent().hide();
		}
	});
	/** 
	** Enable User multi-pass-reset
	**/
	$('#classschedule_generatePasswordPDF').click(function(ev){
		var checkedUsers = $('input.classschedule_selectUser:checked');
		var userIDsArray = [];
		var listOfUsers = [];
		$.each(checkedUsers, function(index, Element){
			var parentRow = $(Element).parents('tr');
			listOfUsers.push($('.classschedule_data_fullName',parentRow).text());
			userIDsArray.push($(Element).data('uid')); 
			
		});
		var generatePasswordPDFDialog = $('<div>'+ '<em>Are you sure you wish to reset passwords for the following users?</em> <br/>'+ listOfUsers.join(',')+'</div>').dialog({
			modal:true,
			title: 'Are you sure?',
			buttons: {
				Reset: function(){
					generatePasswordPDFDialog.dialog('close');
					window.location = Drupal.settings.introPDFAddress +  userIDsArray.join('&UID[]=');
						
				},
				Cancel: function(){
					generatePasswordPDFDialog.dialog('close');
				}
			}
		});
	});
	
	/**
	** Enable User multi-delete
	**/
	$('#classschedule_deleteSelectedUsers').click(function(ev){
		var checkedUsers = $('input.classschedule_selectUser:checked');
		var listOfUsers = [];
		var userIDsArray = []
		$.each(checkedUsers, function(index, Element){
			var parentRow = $(Element).parents('tr');
			listOfUsers.push($('.classschedule_data_fullName',parentRow).text());
			userIDsArray.push($(Element).data('uid')); 
			
		});
		var deleteMultipleUsersDialog = $('<div>'+ '<em>Are you sure you wish to delete the following users?</em> <br/>'+ listOfUsers.join(',')+'</div>').dialog({
			modal:true,
			title: 'Are you sure?',
			buttons: {
				Delete: function(){
					deleteMultipleUsersDialog.html('<div class="classscheduleLoading">&nbsp;</div>').dialog('option', 'title', 'Please Wait...');
					$.get(Drupal.settings.ajaxAddress,{
						function: 'deleteMultipleUsers',
						userArray: userIDsArray
						},
						function(data){
							if(data){
								deleteMultipleUsersDialog.dialog('close');
								for(i in userIDsArray){
									var parentRow = $('#studentrow_'+userIDsArray[i]);
									parentRow.addClass('classschedule_disabledUser');
									parentRow.find('.classschedule_activeUserOptions').hide();
									parentRow.find('.classschedule_selectUser').hide().attr('checked',false);
									parentRow.find('.classschedule_deletedUserOptions').show();
									// If we're currently showing deleted users, unhide the row
									if($('#classschedule_showDeleted').is(':checked')){
										parentRow.show();
									}
								}
							}else{
								deleteMultipleUsersDialog.text('Error deleting one or more users, please refresh the page');
							}
						}
					);
						
				},
				Cancel: function(){
					deleteMultipleUsersDialog.dialog('close');
				}
			}
		});
	});

	/**
	** Enable User Search
	**/
	// make :Contains selector case insensitive
	$.expr[':'].Contains = function(x, y, z){
		return jQuery(x).text().toUpperCase().indexOf(z[3].toUpperCase())>=0;
	};
	$('#classschedule_searchUser').click(function(){
		if($(this).val() == 'Search By Name'){
			$(this).val('');
		}
	});
	$('#classschedule_searchUser').keyup(function(){
		var inputBox = $(this);
		// Reset user multiselect checkboxes to avoid confusion
		$('input.classschedule_selectUser').attr('checked',false);
		if(inputBox.val() !=  ''){
			$('#classschedule_users > tbody > tr').hide();
			var matchingUsers = $('tr > td:nth-child(2):Contains('+$.trim(inputBox.val())+')','#classschedule_users').closest('tr').show();
		}else{
			$('#classschedule_users > tbody > tr').show();
			//Reclick the show: tickboxes (won't change the value)
			$('#classschedule_showStudents').trigger('change');
			$('#classschedule_showTeachers').trigger('change');
			$('#classschedule_showParents').trigger('change');
			$('#classschedule_showDeleted').trigger('change');
		}
	});
	/**
	* Enable filter-checkboxes
	**/
	$('#classschedule_showStudents').change(function(){
		var checkBox = $(this);
		// Reset user multiselect checkboxes to avoid confusion
		$('input.classschedule_selectUser').attr('checked',false);
		if(checkBox.is(':checked')){
			createCookie('classschedule_users_showStudents',true,5);
			if($('#classschedule_showDeleted').is(':checked')){
				$('tr:contains(Student)','#classschedule_users').show();
			}else{
				// If show deleted isn't checked, make sure we don't show 'em!
				$('tr:not(.classschedule_disabledUser):contains(Student)','#classschedule_users').show();
				$('tr.classschedule_disabledUser:contains(Student)','#classschedule_users').hide();
			}
		}else{
			createCookie('classschedule_users_showStudents',false,5);
			$('tr:contains(Student)','#classschedule_users').hide();
		}
	});
	$('#classschedule_showTeachers').change(function(){
		var checkBox = $(this);
		// Reset user multiselect checkboxes to avoid confusion
		$('input.classschedule_selectUser').attr('checked',false);
		if(checkBox.is(':checked')){
			if($('#classschedule_showDeleted').is(':checked')){
				$('tr:contains(Teacher)','#classschedule_users').show();
			}else{
				// If show deleted isn't checked, make sure we don't show 'em!
				$('tr:contains(Teacher):not(.classschedule_disabledUser)','#classschedule_users').show();
				$('tr.classschedule_disabledUser:contains(Teacher)','#classschedule_users').hide();
			}
			createCookie('classschedule_users_showTeachers',true,5);
		}else{
			createCookie('classschedule_users_showTeachers',false,5);
			$('tr:contains(Teacher)','#classschedule_users').hide();
		}
	});
	$('#classschedule_showParents').change(function(){
		var checkBox = $(this);
		// Reset user multiselect checkboxes to avoid confusion
		$('input.classschedule_selectUser').attr('checked',false);
		if(checkBox.is(':checked')){
			createCookie('classschedule_users_showParents',true,5);
			if($('#classschedule_showDeleted').is(':checked')){
				$('tr:contains(Parent)','#classschedule_users').show();
			}else{
				// If show deleted isn't checked, make sure we don't show 'em!
				$('tr:contains(Parent):not(.classschedule_disabledUser)','#classschedule_users').show();
				$('tr.classschedule_disabledUser:contains(Parent)','#classschedule_users').hide();
			}
		}else{
			createCookie('classschedule_users_showParents',false,5);
			$('tr:contains(Parent)','#classschedule_users').hide();
		}
	});
	$('#classschedule_showDeleted').change(function(){
		var checkBox = $(this);
		// Reset user multiselect checkboxes to avoid confusion
		$('input.classschedule_selectUser').attr('checked',false);
		if(checkBox.is(':checked')){
			createCookie('classschedule_users_showDeleted',true,5);
			// Trigger the students, teachers and parents to show deleted
			$('#classschedule_showStudents').trigger('change');
			$('#classschedule_showParents').trigger('change');
			$('#classschedule_showTeachers').trigger('change');
		}else{
			createCookie('classschedule_users_showDeleted',false,5);
			// Trigger the students, teachers and parents to hide deleted
			$('#classschedule_showStudents').trigger('change');
			$('#classschedule_showParents').trigger('change');
			$('#classschedule_showTeachers').trigger('change');	
		}
	});
	/**
	** Read the cookies and display only the users they dictate
	**/
	if(readCookie('classschedule_users_showParents') == 'false'){
		$('#classschedule_showParents').attr('checked',false).change(); //hide the parents!
		createCookie('classschedule_users_showParents',false,5);
	}
	if(readCookie('classschedule_users_showTeachers') == 'false'){
		$('#classschedule_showTeachers').attr('checked',false).change(); //hide the teachers!
		createCookie('classschedule_users_showTeachers',false,5); // Set the cookie for another five minutes
	}
	if(readCookie('classschedule_users_showStudents') == 'false'){
		$('#classschedule_showStudents').attr('checked',false).change(); //hide the parents!
		createCookie('classschedule_users_showStudents',false,5);
	}
	if(readCookie('classschedule_users_showDeleted') == 'true'){
		$('#classschedule_showDeleted').attr('checked',true).change(); //show deleted users!
		createCookie('classschedule_users_showDeleted',true,5);
	}
	/** 
	** Enable delete and reset password dialog boxes
	**/
	$(".classschedule_deleteUser").click(function(ev){
		ev.preventDefault();
		start = $(this);
		
		var theURL = start.attr("href");
		var parentOptionsHover = start.closest('.hoverOptions');
		var parentRow = $('.hoverOptionsLink_'+parentOptionsHover.data('hoverOptionID')).closest('tr');
		var userName = $('.classschedule_data_fullName',parentRow).text();
		$("#dialogBox").text("Are you sure you want to delete " + userName +"?");
		$("#dialogBox").dialog({
			title: "Warning",
			modal: true,
			buttons: {
				"Delete": function() {
					$("#dialogBox").html('<div class="classscheduleLoading">&nbsp;</div>').dialog('option', 'title', 'Please Wait...');
					$.post(theURL,function(data){
						$("#dialogBox").dialog('close');
						if(data == 1){
							parentRow.addClass('classschedule_disabledUser');
							parentRow.find('.classschedule_activeUserOptions').hide();
							parentRow.find('.classschedule_deletedUserOptions').show();
							// If we're currently showing deleted users, unhide the row
							if($('#classschedule_showDeleted').is(':checked')){
								parentRow.show();
							}
							parentOptionsHover.hide();
						}else{
							$("#dialogBox").text("Failed to delete user, please contact your administrator");
							$("#dialogBox").dialog({
								title: "Error",
								modal: true,
								buttons: {
									"Ok": function(){
										$(this).dialog("close");
									}
								}
							});
						}
					});
				},
				"No": function(){
					$(this).dialog("close");
				}
			}
		});
	});
	$(".classschedule_undeleteUser").click(function(ev){
		ev.preventDefault();
		start = $(this);
		
		var theURL = start.attr("href");
		var parentOptionsHover = start.closest('.hoverOptions');
		var parentRow = $('.hoverOptionsLink_'+parentOptionsHover.data('hoverOptionID')).closest('tr');
		var userName = $('.classschedule_data_fullName',parentRow).text();
		$("#dialogBox").html("Are you sure you want to <em>un</em>delete " + userName +"?");
		$("#dialogBox").dialog({
			title: "Warning",
			modal: true,
			buttons: {
				"Yes": function() {
					$("#dialogBox").html('<div class="classscheduleLoading">&nbsp;</div>').dialog('option', 'title', 'Please Wait...');
					$.post(theURL,function(data){
						if(data == 1){
							$("#dialogBox").dialog('close');
							// Restore the row!
							parentRow.removeClass('classschedule_disabledUser');
							parentRow.find('.classschedule_activeUserOptions').show();
							parentRow.find('.classschedule_deletedUserOptions').hide();
							parentRow.find('.classschedule_selectUser').show();
							parentOptionsHover.hide();
						}else{
							$("#dialogBox")
							$("#dialogBox").text("Failed to undelete user, please contact your administrator");
							$("#dialogBox").dialog({
								title: "Error",
								modal: true,
								buttons: {
									"Ok": function(){
										$(this).dialog("close");
									}
								}
							});
						}
					});
				},
				"No": function(){
					$(this).dialog("close");
				}
			}
		});
	});
	$(".classschedule_resetPass").click(function(ev){
		ev.preventDefault();
		start = $(this);
		var theURL = start.attr("href");
		var parentOptionsHover = start.closest('.hoverOptions');
		var parentRow = $('.hoverOptionsLink_'+parentOptionsHover.data('hoverOptionID')).closest('tr');
		var userName = parentRow.find('.classschedule_data_fullName').text();
		$("#dialogBox").html("Are you sure you want to reset " + userName +"\'s password? <br/>WARNING: This will also reset their email password if they have an email address with the school");
		$("#dialogBox").dialog({
			title: "Warning",
			modal: true,
			buttons: {
				"Yes": function() {
					$("#dialogBox").html('<div class="classscheduleLoading">&nbsp;</div>').dialog('option', 'title', 'Please Wait...');
					$.post(theURL,function(data){
						data = $.parseJSON(data);
						if(data["status"] == 1){
							$("#dialogBox").dialog("destroy");
							$("#dialogBox").text(userName+"\'s password has been successfully reset to "+data.password);
							$("#dialogBox").dialog({
								title:"Success",
								buttons: {
									"Ok": function(){
										$(this).dialog("close");
									}
								}});
						}else{
							$("#dialogBox").text(data.error);
							$("#dialogBox").dialog({
								title: "Error",
								modal: true,
								buttons: {
									"Ok": function(){
										$(this).dialog("close");
									}
								}
							});
						}
					});
				},
				"No": function(){
					$(this).dialog("close");
				}
			}
		});
	});
});
})(jQuery);;

(function($){$.extend({tablesorter:new
function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);;

