var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_nav = ((agt.indexOf('mozilla') != -1) && (agt.indexOf('spoofer') == -1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera') == -1) && (agt.indexOf('webtv') == -1));
var is_nav4up = (is_nav && (is_major >= 4));
var is_ie = (agt.indexOf("msie") != -1);
var is_ie3  = (is_ie && (is_major < 4));
var is_ie4  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5") == -1) && (agt.indexOf("msie 6") == -1) && (agt.indexOf("msie 7") == -1) && (agt.indexOf("msie 8") == -1) && (agt.indexOf("msie 9") == -1));
var is_ie5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5") != -1));
var is_ie6  = (is_ie && (is_major == 4) && (agt.indexOf("msie 6") != -1));
var is_ie7  = (is_ie && (is_major == 4) && (agt.indexOf("msie 7") != -1));
var is_ie8  = (is_ie && (is_major == 4) && (agt.indexOf("msie 8") != -1));
var is_ie9  = (is_ie && (is_major == 4) && (agt.indexOf("msie 9") != -1));
var is_ie4up = (is_ie && (is_major >= 4));
var is_ie5up = (is_ie4up && !is_ie4);
var is_ie6up = (is_ie5up && !is_ie5);
var is_ie7up = (is_ie6up && !is_ie6);
var is_ie8up = (is_ie7up && !is_ie7);
var is_ie9up = (is_ie8up && !is_ie8);
var is_mac = (agt.indexOf("mac") != -1);
var is_gecko = (agt.indexOf("gecko") != -1);

function getObject(id)
{
	//if (is_ie4) 
		//var el = eval(id);
	//if (is_ie5up || is_gecko)
		var el = document.getElementById(id);
	return el;
}

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1, menubar=0,resizable=1, width=790,height=600');");
}
function popUpFeedback(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1, width=790,height=800');");
}
function popUpQ(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,resizable=1,scrollbars=1,location=0,statusbar=0,menubar=0,width=550,height=450');");
}
function popUpG(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,resizable=1,scrollbars=1,location=0,statusbar=0,menubar=0,width=650,height=550');");
}
function popUp2(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=auto,location=0,statusbar=0,menubar=0,resizable=0, width=500,height=400');");
}
function popUpGraphCalc(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0, width=800,height=500');");
}
//This one is used on the teacher page
function popUp3(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1, width=600,height=600');");
}
function popUpVideo(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0, width=690,height=640');");
}
function popUpChart(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1, width=435,height=535');");
}
function popUpPrint(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1, width=800,height=600');");
}
function popUpGallery(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0, statusbar=1, menubar=0,resizable=1, width=500,height=410');");
}
function popUpAudio(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1, width=290,height=200');");
}
function popUpTestGraph(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1, width=670,height=360');");
}
function popUpModal(url, width, height, callback, beforeclose)
{
	if(jQuery("#modal_page").length <= 0)
	{
		jQuery("body").append('<div id="modal_page" style="display:none"></div>');
		createModal('modal_page');
	}
	else
		jQuery("#modal_page_iframe").remove();
		
	jQuery("#modal_page").html('<iframe id="modal_page_iframe" name="modal_page_iframe" width="100%" height="550" frameborder="0" scrolling="auto" src=""></iframe>');
	
	jQuery('#modal_page_iframe').attr("scrollbars", 0);
	
	if(!width)
		width = 800;
	if(height && height != "auto")
	{
		var size = getViewportSize();
		if(height == 'max' || height > size[1]-40)
			height = size[1]-40;
		jQuery('#modal_page_iframe').attr("height", height-120);
	}
	else
	{
		height = "auto";
		jQuery('#modal_page_iframe').attr("height", 550);
	}

	jQuery("#modal_page").dialog("option", "width", width);
	jQuery("#modal_page").dialog("option", "height", height);

	if(callback)
	{
		jQuery('#modal_page').unbind("dialogclose");
		jQuery('#modal_page').bind("dialogclose", callback);
	}
	
	if(beforeclose)
	{
		jQuery('#modal_page').unbind("dialogbeforeclose");
		jQuery('#modal_page').bind("dialogbeforeclose", beforeclose);
	}
	
	jQuery('#modal_page').dialog("open");
	jQuery('#modal_page_iframe').attr("src", url);
}

function closePopUpModal()
{
	closeModal("modal_page");
}

function resizePopUpModal(width, height)
{
	if(height)
	{
		var size = getViewportSize();
		if(height == 'max' || height > size[1]-40)
			height = size[1]-40;
		jQuery('#modal_page_iframe').attr("height", height-120);
		jQuery("#modal_page").dialog("option", "height", height);
		getObject("modal_page").style.height = (height-102)+'px';
	}
	
	jQuery("#modal_page").dialog("option", "width", width);
	jQuery("#modal_page").dialog("option", "position", "center");
}

function closeModal(id)
{
	jQuery('#'+id).dialog("close");
}

function createModal(id, w, open, create)
{
	if(!w)
		var w = 800;
	
	if(create && jQuery('#'+id).length <= 0)
		jQuery("body").append('<div id="'+id+'"></div>');
	
	if(jQuery('#'+id) && jQuery('#'+id).dialog)
	{
		jQuery('#'+id).dialog({
				autoOpen: false,
				width: w,
				modal: true,
				resizable:false,
				overlay: {
					"background-color": "#d7d5d5",
					"opacity": "0.80",
					"-moz-opacity": "0.80"
				},
				buttons: {
					"Close": function() { jQuery(this).dialog("close"); } 
				}
		});
	
		if(open)
			jQuery('#'+id).dialog("open");
	}
}

var modal_closed = false;
function confirmModal(msg, callback, button_name_ok, button_name_cancel)
{
	if(jQuery("#confirm_modal").length <= 0)
		jQuery("body").append('<div id="confirm_modal">'+msg+'</div>');
	else
		jQuery("#confirm_modal").html(msg);
	
	createModal("confirm_modal", 400);

	var buttons = {};
	
	if(callback && isArray(callback))
	{
		var callback_cancel = callback[1];
		callback = callback[0];
	}
	
	modal_closed = false;
	
	if(callback && !(button_name_cancel === false))
		buttons[button_name_cancel ? button_name_cancel : "Cancel"] = function() { modal_closed = true; jQuery(this).dialog("close"); if(callback_cancel) callback_cancel() };
	buttons[button_name_ok ? button_name_ok : "OK"] = function () { modal_closed = true; var r = true; if(callback) r = callback(); if(r != false) jQuery(this).dialog("close"); };
	
	jQuery("#confirm_modal").dialog("option", "beforeclose", function () { return modal_closed; });
	jQuery("#confirm_modal").dialog("option", "buttons", buttons);
	
	jQuery("#confirm_modal").dialog("open");
}

function addLoadEvent(func)
{
	if(typeof func == 'string')
  	eval('func = function() {'+func+';}');
    
	var oldonload = window.onload;
  if (typeof window.onload != 'function')
  	window.onload = func;
  else
  	window.onload = function() { oldonload(); func(); }
}

function disableEnter(k)
{
	var key;
	if(window.event)
		key = window.event.keyCode;
	else
		key = k.which;

	if(key == 13)
		return false;
}

function doOnEnter(f, e)
{
	var key;
	if(window.event)
		key = window.event.keyCode;
	else
		key = e.which;

	if(key == 13)
		f();
}

function chooseImage(imageid, id)
{
	if(!id) id = 'imageid';
	if(window.opener && !window.opener.closed)
	{
		window.opener.document.getElementById(id).value = imageid;
		if(window.opener.chooseImageCallBack)
			window.opener.chooseImageCallBack(id);
	}
  window.close();
}

function chooseTable(tableid)
{
	if(window.opener && !window.opener.closed)
		window.opener.document.getElementById('tableid').value = tableid;
  window.close();
}

function showHide(obj, s, type)
{
	if(s)
  	show(obj, type);
  else
  	hide(obj);
}

function swap(obj, type)
{
	if(document.getElementById(obj).style.display == 'none')
  	show(obj, type);
  else
  	hide(obj);
}

function show(obj, type)
{
	if(document.getElementById(obj))
		document.getElementById(obj).style.display = type || type == "" ? type : 'block';
}

function hide(obj)
{
	if(document.getElementById(obj))
		document.getElementById(obj).style.display = 'none';
}

function checkByClassName(c)
{
	var boxes = document.getElementsByClassName(c);
  for(i=0; i<boxes.length; i++)
  	boxes[i].checked = "checked";
}

function uncheckByClassName(c)
{
	var boxes = document.getElementsByClassName(c);
  for(i=0; i<boxes.length; i++)
  	boxes[i].checked = false;
}

function showTab(tab)
{
	if(tab.value)
  {
  	setImage("menu_tab_image_back", "/images/tabs/"+tab.value+"_back.jpg");
    setImage("menu_tab_image_selected", "/images/tabs/"+tab.value+"_selected.jpg");
  	show("menu_tab_image");
  }
  else
  	hide("menu_tab_image");
}

function setImage(img, src)
{
	document.getElementById(img).src = src;
}

function showToolTip(e, id)
{
	if(document.all)e = event;
	var obj = document.getElementById(id ? id : 'hint');
	//var obj2 = document.getElementById('bubble_tooltip_content');
	//obj2.innerHTML = text;
	obj.style.display = 'block';
	
	var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
	var leftPos = e.clientX - 200;
	if(leftPos<0)
		leftPos = 0;
	obj.style.left = leftPos + 'px';
	obj.style.top = e.clientY - obj.offsetHeight -1 + st + 'px';
}	

function hideToolTip(id)
{
	document.getElementById(id ? id : 'hint').style.display = 'none';
}
  
var bubbleStatus = new Array();
function showImageBubble(e, i){
		for(j in bubbleStatus)
			hideImageBubbleAction(j);
      
		bubbleStatus[i] = true;
		if(document.all)
    	e = event;
		
		var obj = document.getElementById('hint'+i);
		obj.style.display = 'block';
		
		var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
		var leftPos = e.clientX - 100;
		if(leftPos<0)
    	leftPos = 0;
		obj.style.left = leftPos + 'px';
    var topPos = e.clientY - 15 - obj.offsetHeight -1 + st;
    if(topPos < document.body.scrollTop)
    	topPos = document.body.scrollTop;
		obj.style.top = topPos + 'px';
	}	
	
  function hideImageBubble(i)
  {
  	bubbleStatus[i] = false;
  	setTimeout("hideImageBubbleAction("+i+")", 400);
  }
  
	function hideImageBubbleAction(i)
	{
  	if(!bubbleStatus[i])
			document.getElementById('hint'+i).style.display = 'none';
	}

  function showToolTip2(e){
		if(document.all)e = event;
		
		var obj = document.getElementById('spanishHint');
		//var obj2 = document.getElementById('bubble_tooltip_content');
		//obj2.innerHTML = text;
		obj.style.display = 'block';
		
		var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
		var leftPos = e.clientX - 100;
		if(leftPos<0)leftPos = 0;
		obj.style.left = leftPos + 'px';
		obj.style.top = e.clientY - obj.offsetHeight -1 + st + 'px';
	}	
  
	function hideToolTip2()
	{
		document.getElementById('spanishHint').style.display = 'none';
		
	}
  
/**
 * DHTML textbox character counter (IE4+) script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function charMessage(id, maxLength) {
	var charObj = id.value || id.id || id.name ? id : getObject(id);
	if (charObj.value.length >= maxLength) 
   	alert("The optimum length for each passage is 400-600 characters.\n\nYou have entered "+charObj.value.length+" characters.");
}

function charCount(id, visCnt) { 
	var charObj = id.value || id.id || id.name ? id : getObject(id);
	if (visCnt)
  {
    visCnt = document.getElementById(visCnt);
  	content = charObj.value.length;
  	if (document.getElementById && !document.all)
    {
      rng = document.createRange();
      rng.setStartBefore(visCnt);
      htmlFrag = rng.createContextualFragment(content);
      while (visCnt.hasChildNodes())
	      visCnt.removeChild(visCnt.lastChild);
      visCnt.appendChild(htmlFrag);
    }
    else
	  	visCnt.innerText=content;
  }
}

function popWindow(loc, title, w, h, r, m)
{
	t = getWindow("top", h);
  l = getWindow("left", w);
  if(w == 'full' || w > screen.availWidth)
  	w = screen.availWidth;
  if(h == 'full' || h > screen.availHeight)
  	h = screen.availHeight;  	
    
	win = window.open(loc, title, 'top='+t+',left='+l+',width='+w+',height='+h+',status=no,resizable='+r+',scrollbars='+(h > screen.availHeight || w > screen.availWidth ? "yes" : r)+',toolbar='+(m == 'yes' ? "yes" : "no")+',location='+(m == 'yes' ? "yes" : "no")+',directories='+(m == 'yes' ? "yes" : "no")+',menubar='+(m == 'yes' ? "yes" : "no"));
	win.focus();
}

function getWindow(t, s)
{
	if(t == "top")
  {
  	if(s > screen.availHeight)
    	return 0;
    return (screen.availHeight-s)/2
  }
  else
  {
  	if(s > screen.availWidth)
    	return 0;
    return (screen.availWidth-s)/2
  }
}

function getViewportSize()
{
	var viewportwidth;
	var viewportheight;
 
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined')
	{
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	}
 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	}
 
	// older versions of IE
	else
	{
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	return new Array(viewportwidth, viewportheight);
}

function getDateFromMySQLDate(date, part)
{
	mo = date.substr(5, 2);
  d = date.substr(8, 2);
  y = date.substr(0, 4);
  h24 = date.substr(11, 2);
  h = h24 > 12 ? h24-12 : h24;
  mi = date.substr(14, 2);
  s = date.substr(17, 2);
  ap = h24 >= 12 ? "pm" : "am";
  
	if(date)
  {
  	if(part == 'm')
    	return mo;
    else if(part == 'd')
    	return d;
    else if(part == 'y')
    	return y;
    else if(part == 't')
    	return h+":"+mi+":"+s+ap;
    else if(part == 'all')
    	return getDateFromMySQLDate(date)+" "+getDateFromMySQLDate(date, 't');
    else
			return mo+"/"+d+"/"+y;
  }
  return false;
}

if(!document.getElementsByClassName) {
document.getElementsByClassName = function(clsName){
	var retVal = new Array();
  var elements = document.getElementsByTagName("*");
  for(var i = 0;i < elements.length;i++){
  	if(elements[i].className.indexOf(" ") >= 0){
    	var classes = elements[i].className.split(" ");
      for(var j = 0;j < classes.length;j++){
      	if(classes[j] == clsName)
        	retVal.push(elements[i]);
      }
    }
    else if(elements[i].className == clsName)
    	retVal.push(elements[i]);
	}
  return retVal;
}
}

function addTeacher(selectid, name, id)
{
	var sl = document.getElementById(selectid);
  if(name && id)
  {
    sl.options[sl.options.length] = new Option(name, id);
    sl.value = id;
  }
  if(sl.onchange)
  	sl.onchange();
}

function number_format(a, b, c, d) {
	if(!b)
  	b = 0;
	if(!c)
  	c = ".";
  if(!d)
  	d = ",";
	// number_format(number, decimals, comma, formatSeparator)
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

function serialize (txt) {
	switch(typeof(txt)){
	case 'string':
		return 's:'+txt.length+':"'+txt+'";';
	case 'number':
		if(txt>=0 && String(txt).indexOf('.') == -1) return 'i:'+txt+';';
		return 'd:'+txt+';';
	case 'boolean':
		return 'b:'+( (txt)?'1':'0' )+';';
	case 'object':
		var i=0,k,ret='';
		for(k in txt){
			//alert(isNaN(k));
			if(!isNaN(k)) k = Number(k);
			ret += serialize(k)+serialize(txt[k]);
			i++;
		}
		return 'a:'+i+':{'+ret+'}';
	default:
		return 'N;';
		alert('var undefined: '+typeof(txt));return undefined;
	}
}

function unserialize(txt){
	var level=0,arrlen=new Array(),del=0,final=new Array(),key=new Array(),save=txt;
	while(1){
		switch(txt.substr(0,1)){
		case 'N':
			del = 2;
			ret = null;
		break;
		case 'b':
			del = txt.indexOf(';')+1;
			ret = (txt.substring(2,del-1) == '1')?true:false;
		break;
		case 'i':
			del = txt.indexOf(';')+1;
			ret = Number(txt.substring(2,del-1));
		break;
		case 'd':
			del = txt.indexOf(';')+1;
			ret = Number(txt.substring(2,del-1));
		break;
		case 's':
			del = txt.substr(2,txt.substr(2).indexOf(':'));
			ret = txt.substr( 1+txt.indexOf('"'),del);
			del = txt.indexOf('"')+ 1 + ret.length + 2;
		break;
		case 'a':
			del = txt.indexOf(':{')+2;
			ret = new Array();
			arrlen[level+1] = Number(txt.substring(txt.indexOf(':')+1, del-2))*2;
		break;
		case 'O':
			txt = txt.substr(2);
			var tmp = txt.indexOf(':"')+2;
			var nlen = Number(txt.substring(0, txt.indexOf(':')));
			name = txt.substring(tmp, tmp+nlen );
			//alert(name);
			txt = txt.substring(tmp+nlen+2);
			del = txt.indexOf(':{')+2;
			ret = new Object();
			arrlen[level+1] = Number(txt.substring(0, del-2))*2;
		break;
		case '}':
			txt = txt.substr(1);
			if(arrlen[level] != 0){alert('var missed : '+save); return undefined;};
			//alert(arrlen[level]);
			level--;
		continue;
		default:
			if(level==0) return final;
			alert('syntax invalid(1) : '+save+"\nat\n"+txt+"level is at "+level);
			return undefined;
		}
		if(arrlen[level]%2 == 0){
			if(typeof(ret) == 'object'){alert('array index object no accepted : '+save);return undefined;}
			if(ret == undefined){alert('syntax invalid(2) : '+save);return undefined;}
			key[level] = ret;
		} else {
			var ev = '';
			for(var i=1;i<=level;i++){
				if(typeof(key[i]) == 'number'){
					ev += '['+key[i]+']';
				}else{
					ev += '["'+key[i]+'"]';
				}
			}
			eval('final'+ev+'= ret;');
		}
		arrlen[level]--;//alert(arrlen[level]-1);
		if(typeof(ret) == 'object') level++;
		txt = txt.substr(del);
		continue;
	}
}

function previewQuestion(e, q)
{
  if(document.all)e = event;
  
  var obj = document.getElementById('question_preview_'+q);
  obj.style.display = 'block';
  var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

  var leftPos = e.clientX + 20;
  var topPos = e.clientY - obj.offsetHeight -1 + st;
  
  // hack because of IE using the div container as the base point instead of the browser window
  if(navigator.userAgent.toLowerCase().indexOf('ie')>=0 && obj.parentNode.parentNode.parentNode.id == 'classify_div_interior')
  {
    if(!isNaN(obj.style.left))
	    obj.style.left = (obj.style.left + 50) + 'px';
  }
  else
  {
    if(leftPos<0)leftPos = 0;
    if(topPos<st)topPos = st;
    obj.style.left = leftPos + 'px';
    obj.style.top = topPos + 'px';
  }
}	

function hidePreviewQuestion(q)
{
	document.getElementById('question_preview_'+q).style.display = 'none';
}

function addQuestionUserFavorite(questionid, strandid, elementid)
{
	confirmModal("Are you sure you wish to add this question to your favorites folder?  You will have easy access to this question when you later create a benchmark.", function () {
		jQuery.ajax({
			url: "/modules/questions/_brains/_ajax_question_actions.php",
			cache: false,
			type: "POST",
			async: true,
			data: ({action : "addUserFavorite", data : jQuery.toJSON({'questionid':questionid, 'strandid':strandid, 'elementid':elementid})}),
			dataType: "html",
			success: function(msg){
				if(msg == '1')
				{
					jQuery("#addQuestionUserFavorite_"+questionid).hide();
					jQuery("#removeQuestionUserFavorite_"+questionid).show();
					confirmModal("This question has been successfully added to your favorites.");
				}
				else
					confirmModal("This question could not be added to your favorites.<br /><br />Please try again.<br /><br />Error: "+msg);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				confirmModal("This question could not be added to your favorites.<br /><br />Please try again.");
			}
		})
	}, "Yes", "No");
}

function removeQuestionUserFavorite(questionid)
{
	confirmModal("Are you sure you wish to remove this question from your favorites folder?", function () {
		jQuery.ajax({
			url: "/modules/questions/_brains/_ajax_question_actions.php",
			cache: false,
			type: "POST",
			async: true,
			data: ({action : "removeUserFavorite", data : jQuery.toJSON({'questionid':questionid})}),
			dataType: "html",
			success: function(msg){
				if(msg == '1')
				{
					jQuery("#removeQuestionUserFavorite_"+questionid).hide();
					jQuery("#addQuestionUserFavorite_"+questionid).show();
					confirmModal("This question has been removed from your favorites.");
				}
				else
					confirmModal("This question could not be removed from your favorites.<br /><br />Please try again.<br /><br />Error: "+msg);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				confirmModal("This question could not be removed from your favorites.<br /><br />Please try again.");
			}
		})
	}, "Yes", "No");
}

function hoverDisplay(e, id)
{
  if(document.all)e = event;
  
  var obj = document.getElementById(id);
  obj.style.display = 'block';
  var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

  var leftPos = e.clientX - obj.offsetWidth - 10;
  var topPos = e.clientY - obj.offsetHeight + st;
  
  if(leftPos < 0)
  	leftPos += obj.offsetWidth + 20;
  if(topPos<st)topPos = st;
  obj.style.left = leftPos + 'px';
  obj.style.top = topPos + 'px';
}

function hideHoverDisplay(id)
{
	document.getElementById(id).style.display = 'none';
}

function loadJavaScriptFile(url)
{
	var headID = document.getElementsByTagName("head")[0];
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = url;
  headID.appendChild(newScript);
}

var ajax_data_loaded = new Array();
function replaceContents(id, url, force_reload)
{
	if(force_reload || !ajax_data_loaded[id])
  {
  	if(typeof HTML_AJAX == 'undefined')
    {
    	loadJavaScriptFile("/js/ajax.js");
      
      var bodyID = document.getElementsByTagName("body")[0];
      var newDiv = document.createElement('div');
      newDiv.id = 'HTML_AJAX_LOADING';
      bodyID.appendChild(newDiv);
    }
      
  	setTimeout('HTML_AJAX.replace("'+id+'", "'+url+'")', 500);
    ajax_data_loaded[id] = true;
  }
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
  }
	return [curleft,curtop];
}

function orderDateReset()
{
	getObject('date_pre').selectedIndex = 0;
}

function orderDateSet(dp)
{
	var date_pre = dp ? dp : getObject('date_pre').value;
  var fm = getObject('fm');
  var fd = getObject('fd');
  var fy = getObject('fy');
  var tm = getObject('tm');
  var td = getObject('td');
  var ty = getObject('ty');
  
  var now = new Date();

  if(date_pre == 'months_12')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()+1);
    from.setMonth(now.getMonth()-12);
    if(from.getDate() == 1)
    	from.setMonth(from.getMonth()+1);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'months_6')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()+1);
    from.setMonth(now.getMonth()-6);
    if(from.getDate() == 1)
    	from.setMonth(from.getMonth()+1);

    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'months_3')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()+1);
    from.setMonth(now.getMonth()-3);
    if(from.getDate() == 1)
    	from.setMonth(from.getMonth()+1);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'months_1')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()+1);
    from.setMonth(now.getMonth()-1);
    if(from.getDate() == 1)
    	from.setMonth(from.getMonth()+1);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'days_7')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()-6);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'days_7_full')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()-7);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = (now.getDate()-1) < 10 ? "0"+(now.getDate()-1) : (now.getDate()-1);
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'months_1_next')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()-1);
    from.setMonth(now.getMonth()+1);
    if(from.getDate() == 1)
    	from.setMonth(from.getMonth()+1);
    
    tm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    td.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    ty.value = from.getFullYear();
    
    fm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    fd.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    fy.value = now.getFullYear();
  }
  else if(date_pre == 'days_7_next')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()+6);
    
    tm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    td.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    ty.value = from.getFullYear();
    
    fm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    fd.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    fy.value = now.getFullYear();
  }
  else if(date_pre == 'to_date_year')
  {
  	fm.selectedIndex = 0;
    fd.selectedIndex = 0;
    fy.value = now.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'to_date_quarter')
  {
  	fm.selectedIndex = Math.floor(now.getMonth()/3)*3;
    fd.selectedIndex = 0;
    fy.value = now.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'to_date_month')
  {
  	fm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    fd.selectedIndex = 0;
    fy.value = now.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'to_date_week')
  {
    from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()-now.getDay());
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'previous_year')
  {
  	fm.selectedIndex = 0;
    fd.selectedIndex = 0;
    fy.value = now.getFullYear()-1;
    
    tm.selectedIndex = 11;
    td.selectedIndex = 30;
    ty.value = now.getFullYear()-1;
  }
  else if(date_pre == 'previous_quarter')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setMonth((Math.floor(now.getMonth()/3)-1)*3);
    
    to = new Date();
    to.setTime(now.getTime());
    to.setMonth(Math.floor(now.getMonth()/3)*3);
    to.setDate(-1);
    
  	fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.selectedIndex = 0;
    fy.value = from.getFullYear();
    
    tm.value = to.getMonth() < 9 ? "0"+(to.getMonth()+1) : (to.getMonth()+1);
    td.value = to.getDate()+1;
    ty.value = to.getFullYear();
  }
  else if(date_pre == 'previous_month')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setMonth(now.getMonth()-1);
    
    to = new Date();
    to.setTime(now.getTime());
    to.setMonth(now.getMonth());
    to.setDate(-1);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.selectedIndex = 0;
    fy.value = from.getFullYear();
    
    tm.value = to.getMonth() < 9 ? "0"+(to.getMonth()+1) : (to.getMonth()+1);
    td.value = to.getDate()+1;
    ty.value = to.getFullYear();
  }
  else if(date_pre == 'previous_week')
  {
    from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()-now.getDay()-7);
    
    to = new Date();
    to.setTime(now.getTime());
    to.setDate(now.getDate()-now.getDay()-1);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = to.getMonth() < 9 ? "0"+(to.getMonth()+1) : (to.getMonth()+1);
    td.value = to.getDate() < 10 ? "0"+to.getDate() : to.getDate();
    ty.value = to.getFullYear();
  }
  else if(date_pre == 'today')
  {
  	fm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    fd.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    fy.value = now.getFullYear();
    
  	tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
  else if(date_pre == 'yesterday')
  {
  	from = new Date();
    from.setTime(now.getTime());
    from.setDate(now.getDate()-1);
    
    fm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    fd.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    fy.value = from.getFullYear();
    
    tm.value = from.getMonth() < 9 ? "0"+(from.getMonth()+1) : (from.getMonth()+1);
    td.value = from.getDate() < 10 ? "0"+from.getDate() : from.getDate();
    ty.value = from.getFullYear();
  }
  else if(date_pre == 'all')
  {
  	fm.selectedIndex = 0;
    fd.selectedIndex = 0;
    fy.selectedIndex = 0;

    tm.value = now.getMonth() < 9 ? "0"+(now.getMonth()+1) : (now.getMonth()+1);
    td.value = now.getDate() < 10 ? "0"+now.getDate() : now.getDate();
    ty.value = now.getFullYear();
  }
}

function checkInternetConnection(f, submit_button)
{
	hide("error_msg");
  
  if(submit_button && getObject(submit_button+"_show") && getObject(submit_button+"_hide"))
  {
  	show(submit_button+"_hide");
    hide(submit_button+"_show");
		
		if(getObject(submit_button+"_show_top"))
			hide(submit_button+"_show_top");
  }
  
	if(HTML_AJAX)
  {
  	HTML_AJAX.grab("/check.php?force_refresh="+Math.floor(Math.random()*10000000000), function (result) {
    		if(result)
      		f.submit();
      },
      {
      	onError: function (e) {
        		msg = "<b>Error Submitting: Internet Connection Latency Detected.</b><br /><br />Please submit again."; 
            if(getObject("error_msg_text"))
            {
            	getObject("error_msg_text").innerHTML = msg;
              show("error_msg");
            }
            else
            	alert(msg.replace(/<br \/>/, "\n"));
            
						iframe_form_submitted = false;
            if(submit_button && getObject(submit_button+"_show") && getObject(submit_button+"_hide"))
            {
            	hide(submit_button+"_hide");
              show(submit_button+"_show");
							if(getObject(submit_button+"_show_top"))
								show(submit_button+"_show_top");
            }
          },
        timeout: 5000
      }
    );
 		return false;
	}
  return true;
}

function submitIframeForm()
{
	if(!iframe_form_submitted && getObject("iframe_form").onsubmit()) 
	{
		iframe_form_submitted = true;
		if(getObject("iframe"))
			getObject("iframe").onload = function () { setTimeout("iframe_form_submitted = false", 1000) };
		setTimeout("iframe_form_submitted = false", 2000);
		getObject("iframe_form").submit()
	}
}

//Checks to see if a student did not choose a teacher, or select do not report
function submitFrameForm()
{
	if(getObject("teacher_id").value == 'choose_teacher')
		confirmModal("Please select a teacher to report the results, or choose &quot;Do Not Report to Teacher&quot;.");
	else
		getObject("iframe_form").submit(); 
}

String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
  + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
  + this + s.substr(0, l - t) : this;
};

function pause(millis) 
{
  var date = new Date();
  var curDate = null;
  
  do { curDate = new Date(); } 
  while(curDate-date < millis);
} 

function loadQuestionResults(resultid, order, sort, module, extra)
{
	if(!resultid)
  	resultid = "";
  if(!order)
  	order = "";
  if(!sort)
  	sort = "";
  if(!module)
  	module = "test/test";
	url = "/modules/"+module+"/question_results.php?resultid="+resultid+"&order="+order+"&sort="+sort+(extra ? "&"+extra : "");
	HTML_AJAX.replace("question_results_div", url);
}

function loadVocabResults(resultid, order, sort, module, extra)
{
	if(!resultid)
  	resultid = "";
  if(!order)
  	order = "";
  if(!sort)
  	sort = "";
  if(!module)
  	module = "test/test";
	url = "/modules/"+module+"/vocab_results.php?resultid="+resultid+"&order="+order+"&sort="+sort+(extra ? "&"+extra : "");
	HTML_AJAX.replace("vocab_results_div", url);
}

function loadItemResults(resultid, order, sort, module, extra)
{
	if(!resultid)
  	resultid = "";
  if(!order)
  	order = "";
  if(!sort)
  	sort = "";
  if(!module)
  	module = "dragdrop/dragdrop";
	url = "/modules/"+module+"/item_results.php?resultid="+resultid+"&order="+order+"&sort="+sort+(extra ? "&"+extra : "");
	HTML_AJAX.replace("item_results_div", url);
}

function checkStudentUsername(user)
{
	HTML_AJAX.grab('/modules/student/student_request.php?action=user_check&username='+user, 
  	function(result) {
    	if(result == "1")
      {
      	username_valid = true;
        document.getElementById("user_check").innerHTML = "";
      }
      else
      {
      	username_valid = false;
	     	document.getElementById("user_check").innerHTML = result;
      }
    }
  );
}

function checkSchoolID()
{
	var s = getObject("schoolid");
	$("#schoolid_error").html("");
	$("#schoolid_message").html("");
	$('#schoolid').removeClass('bg_ok').removeClass('bg_error');
	
	if(s.value)
	{
		getObject("schoolid").disabled = "disabled";
		
		$.get("/modules/account/check_data.php?field=schoolid&schoolid="+s.value, function (r) {
			getObject("schoolid").disabled = false;
			
			if(r == "1")
			{
				$("#schoolid_message").html("Found");
				$("#schoolid_error").html("");
				$('#schoolid').addClass('bg_ok');
			}
			else
			{
				$("#schoolid_message").html("");
				$("#schoolid_error").html("Not Found");
				$('#schoolid').addClass('bg_error');
			}
		});
	}
}

function parseSelectedTab()
{
	var selected_tab = 0;
	if(self.document.location.hash && self.document.location.hash.match(/#tab-(\d+)/))
	{
		var original_hash = unescape(self.document.location.hash);
		var anchor = null;
		
		selected_tab = original_hash.replace(/#tab-(\d+)(#.*)?/, "$1");
		
		if(original_hash.match(/#tab-(\d+)#(.*)/))
		{
			anchor = original_hash.replace(/#tab-(\d+)#(.*)/, "$2");
			setTimeout("self.document.location.hash = '"+anchor+"'; self.document.location.hash = '"+original_hash+"'", 200);
		}
	}
	return selected_tab;
}

function selectTab(event, ui)
{
	// Objects available in the function context:
	// ui.tab     // anchor element of the selected (clicked) tab
	// ui.panel   // element, that contains the selected/clicked tab contents
	// ui.index   // zero-based index of the selected (clicked) tab

	window.location.href='#tab-'+ui.index;
}

function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
  return plaintext;
}

var hexcase = 0;
var b64pad  = "";
var chrsz   = 8; 

function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

function core_md5(x, len)
{
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
  {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
    {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
    }
  }
	return "";
}

function setSessionValue(name, value)
{
	var v = {};
	if(!value && isArray(name))
	{
		for(var i=0; i<name.length; i++)
		{
			val = name[i];
			v['name['+i+']'] = name[i].name;
			v['value['+i+']'] = name[i].value;
		}
	}
	else
		v = {name: name, value: value};
		
	HTML_AJAX.post('/set_session.php', v);
}

function isArray(obj)
{
	if(obj.constructor.toString().indexOf("Array") == -1)
		return false;
	return true;
}

function addGetVariable(string, variable, val)
{
	// process for each variable in the array
	if(isArray(variable))
  {
  	for(i=0; i<variable.length; i++)
    	string = addGetVariable(string, variable[i], (isArray(val) ? val[i] : val));
    return string;
  }
  
  // if the val is an object, extract its value
	if(typeof(val) == 'object')
  	if(val.selectedIndex != "undefined")
    	val = val.options[val.selectedIndex].value;
    else
    	val = val.value;
  
  // do the adding
	regexp = new RegExp(variable+"=[^&]*");

	// variable is already there
	if(string.match(regexp))
  	return string.replace(regexp, variable+"="+val);

  // variable is not there, add it to the end
 	if(string.match(/\?/))
 		return string+"&"+variable+"="+val;

 	//otherwise put it as only
 	return string+"?"+variable+"="+val;
}

function html_entity_decode( string, quote_style ) {
    // Convert all HTML entities to their applicable characters  
    // 
    // version: 901.714
    // discuss at: http://phpjs.org/functions/html_entity_decode
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function get_html_translation_table(table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 902.2516
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }

    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }

    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
	    entities['38']  = '&amp;';
	    entities['60']  = '&lt;';
	    entities['62']  = '&gt;';
	    entities['160'] = '&nbsp;';
	    entities['161'] = '&iexcl;';
	    entities['162'] = '&cent;';
	    entities['163'] = '&pound;';
	    entities['164'] = '&curren;';
	    entities['165'] = '&yen;';
	    entities['166'] = '&brvbar;';
	    entities['167'] = '&sect;';
	    entities['168'] = '&uml;';
	    entities['169'] = '&copy;';
	    entities['170'] = '&ordf;';
	    entities['171'] = '&laquo;';
	    entities['172'] = '&not;';
	    entities['173'] = '&shy;';
	    entities['174'] = '&reg;';
	    entities['175'] = '&macr;';
	    entities['176'] = '&deg;';
	    entities['177'] = '&plusmn;';
	    entities['178'] = '&sup2;';
	    entities['179'] = '&sup3;';
	    entities['180'] = '&acute;';
	    entities['181'] = '&micro;';
	    entities['182'] = '&para;';
	    entities['183'] = '&middot;';
	    entities['184'] = '&cedil;';
	    entities['185'] = '&sup1;';
	    entities['186'] = '&ordm;';
	    entities['187'] = '&raquo;';
	    entities['188'] = '&frac14;';
	    entities['189'] = '&frac12;';
	    entities['190'] = '&frac34;';
	    entities['191'] = '&iquest;';
	    entities['192'] = '&Agrave;';
	    entities['193'] = '&Aacute;';
	    entities['194'] = '&Acirc;';
	    entities['195'] = '&Atilde;';
	    entities['196'] = '&Auml;';
	    entities['197'] = '&Aring;';
	    entities['198'] = '&AElig;';
	    entities['199'] = '&Ccedil;';
	    entities['200'] = '&Egrave;';
	    entities['201'] = '&Eacute;';
	    entities['202'] = '&Ecirc;';
	    entities['203'] = '&Euml;';
	    entities['204'] = '&Igrave;';
	    entities['205'] = '&Iacute;';
	    entities['206'] = '&Icirc;';
	    entities['207'] = '&Iuml;';
	    entities['208'] = '&ETH;';
	    entities['209'] = '&Ntilde;';
	    entities['210'] = '&Ograve;';
	    entities['211'] = '&Oacute;';
	    entities['212'] = '&Ocirc;';
	    entities['213'] = '&Otilde;';
	    entities['214'] = '&Ouml;';
	    entities['215'] = '&times;';
	    entities['216'] = '&Oslash;';
	    entities['217'] = '&Ugrave;';
	    entities['218'] = '&Uacute;';
	    entities['219'] = '&Ucirc;';
	    entities['220'] = '&Uuml;';
	    entities['221'] = '&Yacute;';
	    entities['222'] = '&THORN;';
	    entities['223'] = '&szlig;';
	    entities['224'] = '&agrave;';
	    entities['225'] = '&aacute;';
	    entities['226'] = '&acirc;';
	    entities['227'] = '&atilde;';
	    entities['228'] = '&auml;';
	    entities['229'] = '&aring;';
	    entities['230'] = '&aelig;';
	    entities['231'] = '&ccedil;';
	    entities['232'] = '&egrave;';
	    entities['233'] = '&eacute;';
	    entities['234'] = '&ecirc;';
	    entities['235'] = '&euml;';
	    entities['236'] = '&igrave;';
	    entities['237'] = '&iacute;';
	    entities['238'] = '&icirc;';
	    entities['239'] = '&iuml;';
	    entities['240'] = '&eth;';
	    entities['241'] = '&ntilde;';
	    entities['242'] = '&ograve;';
	    entities['243'] = '&oacute;';
	    entities['244'] = '&ocirc;';
	    entities['245'] = '&otilde;';
	    entities['246'] = '&ouml;';
	    entities['247'] = '&divide;';
	    entities['248'] = '&oslash;';
	    entities['249'] = '&ugrave;';
	    entities['250'] = '&uacute;';
	    entities['251'] = '&ucirc;';
	    entities['252'] = '&uuml;';
	    entities['253'] = '&yacute;';
	    entities['254'] = '&thorn;';
	    entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

//New Tool Tips uses input forms with a title selected by form id
function ToolTips(formID,position,width)
{
	//Tool Tips Code
	$("#"+formID+" :input[title]").tipTip({ 
	defaultPosition: position,
	maxWidth: width,
	activation: 'focus'
	}); 
}
