// A function to display custom application errors
var errors = [];
//errors.watch("length", error_display);

function error_display(p, o, n)
{
  var errorDisplay = errors.join('<br />');
  $j('#errors').html(errorDisplay);
  $j('#errors').show();
  return n;
}

jQuery(document).keypress(function(e) {
  var code = e.keyCode || e.which;
  if ((code == 13) && (e.originalTarget.form.className != 'inplaceeditor-form'))
  {
    jQuery('#' + e.originalTarget.form.id).submit();
  }
});

// Handle 'Current Students' login
jQuery(function() {
	jQuery('#current_students_button').click(function() {		
		$('#dialog').load('/inc/dialogs/login.php').dialog({
			bgiframe: true,
			autoOpen: false,
			height: 200,
			modal: true,
			resizable: false,
			draggable: false,
			buttons: {
				'Log In': function() {
				  jQuery('#login_form').submit();
					jQuery(this).dialog('close');
				},
				'Cancel': function() {
					jQuery(this).dialog('close');
				}
			},
			close: function() {
				jQuery([]).add($("#username")).add(jQuery("#password")).val('');
				jQuery('#dialog').empty();
			}
		});
		jQuery('#dialog').dialog('open');
		return false;
	}); 
});

// Attendance Functions
function process_attendance (id) {
	var total = null;
	var v = '';
  jQuery('.student-' + id + ' option:selected').each(function(){
    if (jQuery(this).val() == 'P') { total += .25; v += '1~'; }
    if (jQuery(this).val() == 'A') { total += 0; v += '0~'; }
	if (jQuery(this).val() == '') {  v += '-1~'; }

  });
  
  v = v.substring(0, v.length-1);
  document.getElementById('sta_'+id).value = v;
  var attendance;
  switch(total)
  {
    case 0:
      attendance = 'absent';
      break;
    case 0.25:
      attendance = '&frac14; day present';
      break;
    case 0.5:
      attendance = '&frac12; day present';
      break;
    case 0.75:
      attendance = '&frac34; day present';
      break;
    case 1:
      attendance = 'present';
      break;
    default:
    	attendance = '';
    	break;
  }
  jQuery('#attendance-' + id).html(attendance);
  
}

function update_attendance (id) {
	if (typeof id !== "undefined") {
		process_attendance(id);
	} else {
		$('.attendance_total').each(function() {
			var pieces = $(this).attr('id').split('-');
			var id = pieces[1];
			process_attendance(id);
		});
	}
}
jQuery(function() {
  jQuery('.mark_period').click(function() {
    var pieces = $(this).attr('id').split('-');
    var change_class = '.period-' + pieces[1];
    $(change_class).val(pieces[2]);
    update_attendance();
    return false;
  });
  jQuery('.mark_student').click(function() {
    var pieces = $(this).attr('id').split('-');
    var change_class = '.student-' + pieces[1];
    $(change_class).val(pieces[2]);
    update_attendance();
    return false;
  });
  jQuery('.choice').change(function(){
    var pieces = $(this).attr('id').split('-');
    update_attendance(pieces[1]);
  });
});

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() 
{
  var xmlHttp;

  try
  {
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
 
 if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

function loadCal(path,loc,type,yr,mon)
{
	if (xmlHttp)
	{
		try
		{
			document.getElementById(loc).innerHTML = '<br><br><br><center><img src="/images.new/ajax-loader.gif"></center>';
	      	params = "loc="+loc+"&M="+mon+"&Y="+yr+"&type="+type;
			//alert(params);
			xmlHttp.open("POST", "inc/"+path, true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleloadCal;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleloadCal() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getloadCal();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getloadCal()
{
	var response1 = xmlHttp.responseText;
	var respA1 = response1.split("|");
	//alert(response1);
	document.getElementById(respA1[1]).innerHTML=respA1[0];
}

function overlay2() 
{
	var docHeight = document.height || document.body.offsetHeight;
	
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}

	el = document.getElementById("overlay");
	el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
	el2 = document.getElementById("lightbox");
	el2.style.visibility = (el2.style.visibility == "visible") ? "hidden" : "visible";
	if(el.style.visibility == "visible")
	{
		el.style.display="block";
		//document.getElementById("overlay").style.height=yWithScroll+"px";	
		document.getElementById("lightbox").style.top=document.documentElement.scrollTop + 20 + "px";
		
	}
	else
	{
		el.style.display="none";
		//document.body.style.overflow="auto";
		document.getElementById("overlay").style.height="100%";
		document.getElementById("outerContainer").style.width="350px";
		document.getElementById("outerContainer").style.height="150px";
	}
	
	if(el2.style.visibility == "visible")
	{
		el2.style.display="block";
	}
	else
	{
		el2.style.display="none";
	}
	
}

function getDirections(toAddress)
{
	Over = document.getElementById("innerContainer");
  	tmp = '<table border="0" cellspacing="0" cellpadding="5" width="100%">';
  	tmp += '<tr><td align="left" style="border-bottom:1px solid #353535;">';
  	tmp += '<font style="font-family:verdana;font-size:12px;color#353535;"><b>Enter your starting point:</b>';
	tmp += '</td></tr>';
	tmp += '<tr><td align="left" style="padding-top:8px;">';
	tmp += '<font style="font-family:verdana;font-size:12px;color#353535;">Address:&nbsp;<input type="text" id="addr" name="addr" size="30">';
	tmp += '</font>';
	tmp += '</td></tr>';
	tmp += '<tr><td align="left" style="padding-top:6px;">';
	tmp += '<b>Please enter your city and state or zip code.</b>';
  	tmp += '</td></tr>';
	tmp += '<tr><td align="left" style="padding-top:1px;">';
	tmp += '<table border="0" cellpadding="2" cellspacing="2">';
	tmp += '<tr>';
	tmp += '<td>';
	tmp += '<font style="font-family:verdana;font-size:12px;color#353535;">City:&nbsp;<input type="text" id="city" name="city" size="20">';
	tmp += '</td>';
	tmp += '<td>';
	tmp += 'State:&nbsp;<input type=text id="state" name="state" size="3" maxsize="2">';
	tmp += '</td>';
	tmp += '<td>';
	tmp += 'Zip Code:&nbsp;<input type="text" id="zip" name="zip" size="12">';
	tmp += '</font>';
	tmp += '</td>';
	tmp += '</table>';
  	tmp += '</td></tr>';
	tmp += '<tr><td align="center" style="padding-top:8px;">';
	tmp += '<input type="button" name="cancel_btn" id="cancel_btn" value=" Cancel " onclick="overlay2();">';
	tmp += '<input type="button" name="go_btn" id="og_btn" value=" Submit " onclick="getDirections2(\''+toAddress+'\');">';
	tmp += '</td></tr>';
  	tmp += '</table>';
	document.getElementById("outerContainer").style.width="575px";
	document.getElementById("outerContainer").style.height="200px";
  	Over.innerHTML = tmp;
	overlay2();
}

function getDirections2(toAddress)
{
	var fromAddress;
			
	fromAddress=document.getElementById("addr").value+","+document.getElementById("city").value+","+document.getElementById("state").value+" "+document.getElementById("zip").value;
	
	window.open('directions.php?t='+toAddress+'&f='+fromAddress, 'Directions', 'location=0,status=0,scrollbars=1,menubar=0,resizable=1,width=675,height=600');
	overlay2();
}

jQuery(document).ready(function() {
  jQuery('.confirm').live('click', function() {
    return confirm('Are you sure?');
  });
  // jQuery('.date').datepicker();
});

function updateClassGrade(s,v,l,cl,co)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "s="+s+"&v="+v+"&l="+l+"&cl="+cl+"&co="+co;
			//alert(params);
			xmlHttp.open("POST", "/inc/updateClassGrade.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleClassGrade;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function updateClassGrade2(v,l,cl,co)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "v="+v+"&l="+l+"&cl="+cl+"&co="+co;
			//alert(params);
			xmlHttp.open("POST", "/inc/updateClassGrade2.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleClassGrade;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function updateClassGrade3(s,v,l,cl,co,ex)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "s="+s+"&v="+v+"&l="+l+"&cl="+cl+"&co="+co+"&ex="+ex;
			//alert(params);
			xmlHttp.open("POST", "/inc/updateClassGrade3.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleClassGrade;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleClassGrade() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getClassGrade();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getClassGrade()
{
	var response1 = xmlHttp.responseText;
	//alert(response1);
}


function updateExamDate(v)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "v="+v+"&d="+document.getElementById("exdate").value;
			//alert(params);
			xmlHttp.open("POST", "/inc/updateExamDate.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleUpdateAppField;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function updateTerm(v)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "v="+v+"&t="+document.getElementById("term").value;
			//alert(params);
			xmlHttp.open("POST", "/inc/updateAppTerm.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleUpdateAppField;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleUpdateAppField() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getAppField();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getAppField()
{
	var response1 = xmlHttp.responseText;
	//alert(response1);
}

function setPassFail(v,l,cl,co)
{
	var el = document.getElementsByName("pf");
	
	for(i=0;i <= (el.length-1);i++)
	{
		el[i].value=v;
	}
	updateClassGrade2(v,l,cl,co);
}

function getTranscript(s)
{
	var chk = document.getElementsByName("level_sel");
	var level='';
	for(i=0;i<chk.length;i++)
	{
		if(chk[i].checked)
		{
			level += chk[i].value + ','; 
		}
	}
	level = level.slice(0, -1);
	window.open('/admin/reports/grades/transcript/?id='+s+'&l='+level);
}

function getTranscript2()
{
	var chk = document.getElementsByName("level_sel");
	var level='';
	for(i=0;i<chk.length;i++)
	{
		if(chk[i].checked)
		{
			level += chk[i].value + ','; 
		}
	}
	level = level.slice(0, -1);
	if(document.getElementById('class1').value == '')
	{
		alert('Please enter a class number.');
		document.getElementById("class1").focus();
		return false;
	}
	else
	{
		window.open('/admin/reports/grades/transcript/?class='+document.getElementById('class1').value+'&l='+level);
	}
}

function transferCourse(s,c,cl,t)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "s="+s+"&c="+c+"&cl="+cl+"&t="+t;
			//alert(params);
			xmlHttp.open("POST", "/inc/transferCourse.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleTransferCourse;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleTransferCourse() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getTransferCourse();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getTransferCourse()
{
	var response1 = xmlHttp.responseText;
	//alert(response1);
}

function updateAttendance(s)
{
	var v, tmp;
	v = s.split("-");
	tmp = '';
	for(i=0;i < v.length;i++)
	{
		st = "sta_"+v[i];
		tmp += v[i]+"|"+document.getElementById(st).value+";";
	}
	document.getElementById("alst").value = tmp;
	
	if(document.getElementById("clinical_1").checked)
	{
		c1 = '1';
	}
	else
	{
		c1 = '0';
	}
	
	if(document.getElementById("clinical_2").checked)
	{
		c2 = '1';
	}
	else
	{
		c2 = '0';
	}
	
	if(document.getElementById("clinical_3").checked)
	{
		c3 = '1';
	}
	else
	{
		c3 = '0';
	}
	
	if(document.getElementById("clinical_4").checked)
	{
		c4 = '1';
	}
	else
	{
		c4 = '0';
	}

	if (xmlHttp)
	{
		try
		{
			tb_show('<b>Loading...</b>','/inc/loading.php?height=85&width=150','');
	      	params = "alst="+tmp+"&class="+document.getElementById('class').value+"&date="+document.getElementById('date').value+"&f=submit2&c1="+c1+"&c2="+c2+"&c3="+c3+"&c4="+c4;
			//alert(params);
			xmlHttp.open("POST", "/admin/attendance/functions.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleUpdateAttendance(''+document.getElementById('class').value+'', ''+document.getElementById('date').value+'');
			xmlHttp.send(params);
			
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleUpdateAttendance(c,d) 
{
	setTimeout(function(){
		window.location = '/admin/attendance/?class='+c+'&date='+d;		
	}, 1000);
}

function checkAttendance(c,d)
{
	if (xmlHttp)
	{
		try
		{
	      	params = "c="+c+"&d="+d;
			//alert(params);
			xmlHttp.open("POST", "/inc/checkAttendance.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleCheckAttendance;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleCheckAttendance() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getCheckAttendance();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getCheckAttendance()
{
	var response1 = xmlHttp.responseText;
	var resp = response1.split("_");
	if(resp[0] == 'CLEAR')
	{
		setTimeout(function(){
		window.location = '/admin/attendance/?class='+resp[1]+'&date='+resp[2]+'&s=1';		
		}, 1000);
	}
	else
	{
		setTimeout(function(){
			checkAttendance(''+resp[1]+'',''+resp[2]+'');
		}, 5000);
	}
}

function delExam(e)
{
	if (xmlHttp)
	{
		try
		{
			var conf = confirm("Are you sure you want to delete this exam?");
			if(conf){
				params = "e="+e;
				//alert(params);
				xmlHttp.open("POST", "/inc/delExam.php", true);
				xmlHttp.setRequestHeader("Content-Type", 
										"application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = handleDelExam;
				xmlHttp.send(params);
			}
			else
				return false;
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleDelExam() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getDelExam();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getDelExam()
{
	var response1 = xmlHttp.responseText;
}

function clearWarning(s,t)
{
	if (xmlHttp)
	{
		try
		{
			params = "s="+s+"&t="+t;
			//alert(params);
			xmlHttp.open("POST", "/inc/clearWarning.php", true);
			xmlHttp.setRequestHeader("Content-Type", 
									"application/x-www-form-urlencoded");
			xmlHttp.onreadystatechange = handleClearWarning;
			xmlHttp.send(params);
		}
		catch(e)
		{
			alert(e.toString());
		}
	}
}

function handleClearWarning() 
{
	if (xmlHttp.readyState == 4) 
	{
		if (xmlHttp.status == 200) 
		{
			try
			{
				getClearWarning();
			}
			catch(e)
			{
				alert(e.toString());
			}
		} 
		else
		{
			alert(xmlHttp.statusText);   
		}
	}
}

function getClearWarning()
{
	var response = xmlHttp.responseText;
	
	if(response == '1'){
		document.getElementById("attendance-warn1").style.display='none';
	}
	else{
		document.getElementById("attendance-warn2").style.display='none';
	}
}

function dateMask(event, field) {
	// To work with before IE6 browsers
	if(!event) event = window.event;

	var flag = false;
	var keyCode = event.keyCode;

	// skip control characters
	if(keyCode <= 31 ) flag = true;

	if(keyCode >= 48 && keyCode <= 57) {
		flag = true;
	}

	if (field.value.length == 2) {
		field.value = field.value + "/";
	}

	if (field.value.length == 5) {
		field.value = field.value + "/";
	}

	if (flag == false) event.keyCode = 0;

	return flag;
}
