// JavaScript Document

function reloadAttachments() {
  // for some reason I can't call the Ajax directly, but by adding the 30 millisec timeout, it works fine...
  window.setTimeout('attachmentAjax('+arguments[0]+')', 30);   
}

function attachmentAjax() {
  new Ajax.Updater('attachments', 'student.php', {parameters:'action=updateAttachments&conductID='+arguments[0], evalScripts:true, asynchronous:true});	
}

function reloadLog() {
  // for some reason I can't call the Ajax directly, but by adding the 30 millisec timeout, it works fine...
  window.setTimeout('reloadLogAjax(\''+arguments[0]+'\')', 30);   
}

function reloadLogAjax() {
  maskScreen();
  new Ajax.Updater('logArea', 'logs.php', {parameters:'action='+arguments[0], evalScripts:true, asynchronous:true});	
}

function updateMenuButtons () {
  $buttons = new Array('generalButton','conductsButton','lettersButton','smsButton','emailButton','chartButton');
  for($i=0; $i<$buttons.length; $i++) { 
    if(updateMenuButtons.arguments[0] == $buttons[$i]) {
	  $($buttons[$i]).className='selectedTab';
	  $($buttons[$i]+'Image').src = "assets/graphics/menu/tabSelected.jpg"; }
	else {
	  $($buttons[$i]+'Image').src = "assets/graphics/menu/tab.jpg";
	  document.getElementById($buttons[$i]).className='tabNav'; }
	}
}

function updateChart() {
  new Ajax.Updater('chart', 'student.php', {parameters:'action=updateChart&studentID='+updateChart.arguments[0]+'&chartType='+document.getElementById('chartType').value+'&recordType='+document.getElementById('recordType').value+'&pieYscale='+document.getElementById('pieYscale').value+'&pieDepth='+document.getElementById('pieDepth').value+'&pieRadius='+document.getElementById('pieRadius').value+'&chartColour='+document.getElementById('chartColour').value+'&chartView='+$('chartView').value, evalScripts:true, asynchronous:true});
}

function updateConductChart() {
  new Ajax.Updater('chart', 'conduct.php', {parameters:'action=updateChart&type='+arguments[0]+'&chartType='+document.getElementById('chartType').value+'&pieYscale='+document.getElementById('pieYscale').value+'&pieDepth='+document.getElementById('pieDepth').value+'&pieRadius='+document.getElementById('pieRadius').value+'&chartColour='+document.getElementById('chartColour').value, evalScripts:true, asynchronous:true});
}

function editCheck() {
  $args = editCheck.arguments;
  if($args[0].options[$args[0].selectedIndex].text == 'Edit list...')
    alert('This facility will be added shortly. In the interim please contact your\n           system administrator to have values added here.'); 
  if($args[0].options[$args[0].selectedIndex].text == 'New conduct') {
	maskScreen(); positionMessage('newConductType', 350, 300); $field = $args[0].id; }
  if($args[0].options[$args[0].selectedIndex].text == 'New action') {
	maskScreen(); positionMessage('newActionTaken', 350, 140); $field = $args[0].id; }
  if($args[0].options[$args[0].selectedIndex].text == 'New') {
	maskScreen(); positionMessage('newPointsValue', 350, 140); $field = $args[0].id; }
}

function colourThis() {
  if(arguments[0].options[arguments[0].selectedIndex].value < 0)
    arguments[0].style.backgroundColor = 'red';
  if(arguments[0].options[arguments[0].selectedIndex].value > 0)
    arguments[0].style.backgroundColor = 'green';
}

function saveForm() {
  // call as saveForm(div to update, page to use, action to append to arguments, field with field infoList);
  maskScreen(); $die = false;
  $args = saveForm.arguments; $fieldList = new Array(); $selectList = new Array(); $checkList = new Array();
  $infoList = document.getElementById($args[3]).value.split('|');
  if($infoList[0].length > 0) {
    if(document.getElementById($infoList[0]).value.indexOf('|') != -1) $fieldList = document.getElementById($infoList[0]).value.split('|');
	else $fieldList[0] = document.getElementById($infoList[0]).value; }
  if($infoList[1].length > 0) {
    if(document.getElementById($infoList[1]).value.indexOf('|') != -1) $selectList = document.getElementById($infoList[1]).value.split('|');
	else $selectList[0] = document.getElementById($infoList[1]).value; }
  if($infoList[2].length > 0) {
    if(document.getElementById($infoList[2]).value.indexOf('|') != -1) $checkList = document.getElementById($infoList[2]).value.split('|');
	else $checkList[0] = document.getElementById($infoList[2]).value; }
  var $arguments ='';
  for($i=0; $i<$fieldList.length; $i++) {
	if($args[4]) { if(document.getElementById($fieldList[$i]).value == '') $die = true; }
    $arguments += document.getElementById($fieldList[$i]).name +'='+ document.getElementById($fieldList[$i]).value +'&'; }
  for($i=0; $i<$selectList.length; $i++) { 
	if($args[4]) { if(document.getElementById($selectList[$i]).options[document.getElementById($selectList[$i]).selectedIndex].value == '') $die = true;  }
    $arguments += document.getElementById($selectList[$i]).name +'='+ document.getElementById($selectList[$i]).options[document.getElementById($selectList[$i]).selectedIndex].value +'&'; }
  for($i=0; $i<$checkList.length; $i++) {
	$arguments += document.getElementById($checkList[$i]).name +'=';
	if(document.getElementById($checkList[$i]).checked) $arguments += document.getElementById($checkList[$i]).value +'&';
	else $arguments += '0&';
  } // alert($arguments);
  if(!$die) {
	if($args[2] == 'newConductType') {	$arguments += 'destinationField='+$field+'&'; showLoading('formButtons'); }
    new Ajax.Updater($args[0], $args[1]+'.php', {parameters:$arguments+'action='+$args[2], evalScripts:true, asynchronous:true});
    if(($args[2] == 'newConduct' || $args[2] == 'updateConduct') && $args[1] == 'student')
      new Ajax.Updater('thumbnailGraph','student.php', {parameters:'action=updateChartThumb', evalScripts:true, asynchronous:true});
  } else 
	alert('Please complete all fields'); 
}

function saveSimpleForm() {
  maskScreen();
  if($args[2] == 'newPointsValue') showLoading('pointsButtons'); 
  if($args[2] == 'newActionTaken') showLoading('actionButtons'); 
  new Ajax.Updater(arguments[0], arguments[1]+'.php', {parameters:arguments[3]+'&action='+arguments[2], evalScripts:true, asynchronous:true});	
}


function saveList() {
  var $arguments ='';
  for($i=0; $i<$('fieldCount').value; $i++) { $thisItem = 'listItem'+$i; $thisID = 'listRecID'+$i;
	if($($thisItem)) {
	  $arguments += 'recID[]='; if($($thisID)) $arguments += $($thisID).value; $arguments +='&listValue[]='+$($thisItem).value+'&'; } }
  new Ajax.Updater(arguments[0], arguments[1]+'.php', {parameters:$arguments+'action='+arguments[2]+'&list='+arguments[3], evalScripts:true, asynchronous:true});	
}

function saveConductList() {
  var $arguments ='';
  for($i=0; $i<$('fieldCount').value; $i++) { 
    $thisItem = 'listItem'+$i; $thisID = 'listRecID'+$i; $thisPositive = 'positive'+$i; $thisAction = 'defaultAction'+$i; $thisPoints = 'defaultPoints'+$i; $thisLetter = 'defaultLetter'+$i; $thisMessage = 'indicatorMessage'+$i;
	if($($thisItem)) {
	  $arguments += 'recID[]='; if($($thisID)) $arguments += $($thisID).value; $arguments +='&listValue[]='+$($thisItem).value+'&defaultAction[]='+$($thisAction).options[$($thisAction).selectedIndex].value+'&defaultPoints[]='+$($thisPoints).options[$($thisPoints).selectedIndex].value+'&defaultLetter[]='+$($thisLetter).options[$($thisLetter).selectedIndex].value+'&indicatorMessage[]='+$($thisMessage).options[$($thisMessage).selectedIndex].value+'&positive[]'; }
	  if($($thisPositive).checked) $arguments+='=1&'; else $arguments+='=0&';}
    //alert($arguments);
  new Ajax.Updater(arguments[0], arguments[1]+'.php', {parameters:$arguments+'action='+arguments[2]+'&list='+arguments[3], evalScripts:true, asynchronous:true});	
}

function saveStaffList() {
  var $arguments ='';
  for($i=0; $i<$('fieldCount').value; $i++) { 
    $thisID = 'tutorRecID'+$i; $thisTitle = 'tutorNameTitle'+$i; $thisNameFirst = 'tutorNameFirst'+$i; $thisNameLast = 'tutorNameLast'+$i; $thisForm = 'tutorFormClass'+$i; $thisEmail = 'tutorEmail'+$i; $thisAccessName = 'tutorAccessName'+$i; $thisAccessPassword = 'tutorAccessPassword'+$i; $thisAdmin = 'positive'+$i; 
	if($($thisNameLast) && $($thisNameLast).value != '') {
	  $arguments += 'recID[]='; if($($thisID)) $arguments += $($thisID).value; $arguments +='&tutorNameTitle[]='+$($thisTitle).value+'&tutorNameFirst[]='+$($thisNameFirst).value+'&tutorNameLast[]='+$($thisNameLast).value+'&tutorFormClass[]='+$($thisForm).options[$($thisForm).selectedIndex].value+'&tutorEmail[]='+$($thisEmail).value+'&tutorAccessName[]='+$($thisAccessName).value+'&tutorAccessPassword[]='+$($thisAccessPassword).value+'&tutorIsAdministrator[]='; }
	  if($($thisAdmin).checked) $arguments+='yes&'; else $arguments+='no&';}
  new Ajax.Updater(arguments[0], arguments[1]+'.php', {parameters:$arguments+'action='+arguments[2], evalScripts:true, asynchronous:true});	
}

function processDate() {
  // expects that the field given in arguments[0] will be of the form dateXXX
  var $dayNames = new Array("Sun", "Mon", "Tue","Wed", "Thurs", "Fri","Sat");
  var $thisDate = ''; if(arguments[2] < 10) $thisDate += '0'; 
      $thisDate += arguments[2]+'/';  if(arguments[3] < 10) $thisDate += '0'; 
	  $thisDate += arguments[3]+'/'+arguments[1];
  document.getElementById(arguments[0]).value = $thisDate;
  var $displayDate = new Date(); $displayDate.setFullYear(arguments[1],arguments[2]-1,arguments[3]);
  document.getElementById(arguments[0].substr(0,4)+'Display'+arguments[0].substr(4,arguments[0].length-4)).value = 
    $dayNames[$displayDate.getDay()]+'. '+arguments[3]+'/'+arguments[2]+'/'+arguments[1];
}

function showHide() {
  $div = document.getElementById(arguments[0]);
  if($div.style.display == 'block') $div.style.display = 'none';
  else $div.style.display = 'block';
}

function hide() {
  $(arguments[0]).style.display = 'none';
}

function show() {
  $(arguments[0]).style.display = 'block';
}

function showLoading() {
  $(arguments[0]).innerHTML = '<p style="margin-left:140px"><img src="assets/graphics/loadingSmall.gif" /></p>';
}

function updateAction() {
  $thisRecord = arguments[0].id.substr(19,arguments[0].id.length-19);
  $('conductType'+$thisRecord).value = arguments[0].value;
  for(i=0; i<document.getElementById('actionTaken'+$thisRecord).length; i++) {
    if(document.getElementById('actionTaken'+$thisRecord).options[i].text.toLowerCase() == $conducts[arguments[0].value]['defaultAction'].toLowerCase()) {
      document.getElementById('actionTaken'+$thisRecord).selectedIndex = i;
	  var $foundAction = true;
      break; } }
  if(!$foundAction) document.getElementById('actionTaken'+$thisRecord).selectedIndex = 0;
  for($j=0; $j<document.getElementById('points'+$thisRecord).length; $j++) {
    if(document.getElementById('points'+$thisRecord).options[$j].text == $conducts[arguments[0].value]['defaultPoints']) {
      document.getElementById('points'+$thisRecord).selectedIndex = $j;
	  var $foundPoints = true;
      break; } }
  if(!$foundPoints) document.getElementById('points'+$thisRecord).selectedIndex = 0;
}

function updateSelector() {
  $thisRecord = arguments[0].id.substr(11,arguments[0].id.length-11);
  $('conductTypeSelector'+$thisRecord).selectedIndex = 0;
}

function openWindow() {
  $args=openWindow.arguments;
  // 0 = window name, 1 = file to load, 2 = width, 3 = height, 4 = scrollbars
  thisWindow = window.open($args[1],$args[0],'width='+$args[2]+',height='+$args[3]+',scrollbars='+$args[4]);
  $leftPosition = (screen.width-$args[2])/2; $topPosition=(screen.height-$args[3]-40)/2;
  thisWindow.moveTo($leftPosition,$topPosition);
  thisWindow.focus();
  }

function inputList() {
  var $fieldList =''; var $selectList = '';
  for($i=0; $i<document.getElementsByTagName('input').length; $i++)
	$fieldList  += document.getElementsByTagName('input')[$i].id + '|'; 
  for($i=0; $i<document.getElementsByTagName('select').length; $i++)
	$selectList  += document.getElementsByTagName('select')[$i].id + '|';
  document.write('<p> fields '+$fieldList+'</p>');
  document.write('<p> selects '+$selectList+'</p>');
}

function hideShowPie() {
  $chartType = document.getElementById('chartType').value; 
  $pieTypes = new Array(5,6,8,9);
  if ($pieTypes.indexOf($chartType)!==-1) document.getElementById('pieSettings').style.display = 'block';
  else document.getElementById('pieSettings').style.display = 'none';
}

function deleteStudent () {
  if(confirm('Are you sure you wish to delete this student record? It can\'t be retrieved once you have done this!')) {
  maskScreen();
  document.location.href = 'student.php?studentNumber='+arguments[0]+'&action=deleteStudent'; }
}


function addItemDiv() {
  var ni = $('itemX');
  var numi = $('fieldCount');
  var num = parseInt($('fieldCount').value); numi.value = num +1; 
  var divIdName = "item"+num;
  var newdiv = document.createElement('div');
  newdiv.setAttribute("id",divIdName);
  newdiv.innerHTML = '<div id="item'+num+'" class="valueListEditing">'+
  					 '  <input type="text" id="listItem'+num+'" name="listItem[]" value="" />'+
					 '  <a href="javascript:removeItemDiv('+num+')"><img src="assets/graphics/iconDeleteSmall.png" alt="X" title="Delete item" /></a>'+
					 '</div>';
  ni.appendChild(newdiv);
  $('listItem'+num).focus();
}

function removeItemDiv() {
  $('itemX').removeChild($('item'+arguments[0]));
}

function insertText() {
  var $field = arguments[0]; var $value = arguments[1];
  if (document.selection) { 
    $field.focus();
	$sel = document.selection.createRange();
	$sel.text = $value; }
  else if ($field.selectionStart || $field.selectionStart == '0') {
	var $startPos = $field.selectionStart;
	var $endPos = $field.selectionEnd;
	var $currentScroll = $field.scrollTop;
	$field.value = $field.value.substring(0, $startPos)+ $value+ $field.value.substring($endPos, $field.value.length);
	$field.focus();
	$field.selectionStart = $endPos + $value.length;
	$field.selectionEnd = $endPos + $value.length;
	$field.scrollTop = $currentScroll;
	} else {
	  $field.value += $value;
	}
} 

function positionMessage() {
  // provide div, width and height (in that order) as called paramters
  var pagesize = maskGetPageSize();
  var arrayPageScroll = maskGetPageScrollTop();
  $(arguments[0]).setStyle({left: ((pagesize[0] - arguments[1])/2)+"px", top: (arrayPageScroll[1] + ((pagesize[1]-arguments[2])/2))+"px" })
  $(arguments[0]).setStyle({display:"block"});
}

function createOption() {
  $(arguments[0]).options[($(arguments[0]).length)]=new Option(arguments[1], arguments[1], false, false); 
  $(arguments[0]).selectedIndex = ($(arguments[0]).length)-1;
  if(arguments[2]) { 
    $(arguments[2]).style.display = 'none';
    unmaskScreen(); }
}

function formCheck() { //v1.3 a modification of MM_vaildateForm() v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=formCheck.arguments;
  for (i=0; i<(args.length-1); i+=4) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+=' - '+args[i+1]+' must contain an e-mail address.\n';
      } else if (test.indexOf('isValue')!=-1) { 
        if (val!=args[i+3]) errors+=' - '+args[i+1]+' is not valid.\n';
	  } else if (test.indexOf('isPhone')!=-1) {
		if(val.charAt(0) != 0) errors +=' - '+args[i+1]+' doesn\'t start with a zero, please include your area code.\n';
  		if(val.length != 11) errors +=' - '+args[i+1]+' doesn\'t appear to be the correct length.';
	  } else if (test.indexOf('isCard')!=-1) { 
        if (makeNumber(val)!=makeNumber(args[i+3])) errors+=' - '+args[i+1]+' is not valid.\n';		
	  } else if (test.indexOf('noSpace')!=-1) { 
        if (val.indexOf(" ")!=-1) errors+=' - '+args[i+1]+' is required.\n';		
	  } else if (test!='R') { num = makeNumber(val);
        if (isNaN(num)) errors+=' - '+args[i+1]+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=parseFloat(test.substring(8,p)); max=parseFloat(test.substring(p+1));
          if (num<min || max<num) errors+=' - '+args[i+1]+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += ' - '+args[i+1]+' is required.\n'; }
  } if (errors) { alert('There\'s somthing wrong with your form:\n'+errors); return false; }
  	else { maskScreen(); return true; }
  }
	
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/*
Event.observe(document, 'keypress', 
function(event) { 
  var thisKey = event.charCode ? event.charCode : event.keyCode;
  if(event.ctrlKey) {
    switch(thisKey) {
	  case 78:
	  case 110: 
	    document.location.href = 'student.php?action=new';
	  break;
	  case 70:
	  case 102:
	    document.location.href = 'student.php?action=search';
	  break;
	}}
  return false;});
*/