// Javascript from Moodle modules
// This file is included on every elp page! Is this necessary? Anyway, needs to be cleaned up.

var SAVED = 0;
var EDITING = 1;
//var formGridMode = SAVED;
var http_request = false;
var currentCandoSkill = 0;
var currentCandoGrade = 0;
var locked="false";
var codeblocks = document.getElementsByName('goalsbar');


//Page setup for cando page
function initCandoPage()
{
	addOnClickToCandoTable();
	addCandoGridFunctions();
	changeGridMode(SAVED);
};

/*
// Shanes function to display initial helpdesk if javascript is enabled
// Otherwise user is informed javascript is disabled 
function showHelpText(from)
{
	helpfrom = document.getElementById(from);
	helptext = document.getElementById('helptext');

	helptext.firstChild.data = helpfrom.firstChild.data;
};*/

/*
// shade in table row, skip over the information tables
function shadeRow( row , num , page)
{
   if(page=="sa")
     var skip = "goal";
   else
     var skip = "sa";

   var data = document.getElementById('sa_grid').getElementsByTagName('tr').item(row).getElementsByTagName('td')
   
   for( var z = 0; z < data.length; z++ )
   {
      if(z <= num && data.item(z).getAttribute('class') != skip)
      {
         data.item(z).setAttribute('class' , page);
      }
      else
      {
         if(data.item(z).getAttribute('class')!=skip)
            data.item(z).removeAttribute('class');
      }
   }
};*/

/*
	Change mode from editing to saved or V.V.
*/
function changeGridMode(to)
{
	var saveButton = document.getElementById('savebutton');
	var langSelect = document.getElementById('langselect');
	
	if(to == EDITING)  // change to Saved
	{
		// When editing, we don't want the user to change the language (They'll lose changes)
		langSelect.setAttribute('disabled' , 'disabled');
		// Save the grid, change to saved mode
		saveButton.setAttribute('onClick','changeGridMode('+SAVED+'); saveGrid();');
		// Naturally, if they have edited stuff, they need to be able to save.
		saveButton.removeAttribute('disabled');
		formGridMode = SAVED;
	}
	else if (to == SAVED) //change to editing
	{
		// If we have just saved our stuff, we don't need the save button
		//saveButton.setAttribute('onClick','saveGrid();');	
		saveButton.setAttribute('disabled' , 'disabled');
		
		// We do need to be able to move to a new language though!
		langSelect.removeAttribute('disabled');
		formGridMode = EDITING;
	}
};


//Shanes function to save the grid selections
function saveGrid()
{
	var poststr = '';
	var gridFormInputs = document.getElementById('gridform').getElementsByTagName('input');
	var gridFormSelects = document.getElementById('gridform').getElementsByTagName('select');

	var input = gridFormSelects.item(0);  //lang_id
	if(input.value == '') 
	{
	  alert("You must choose a Target Language");  // this line of code will cause a translation problem
	}
	poststr += input.name + "=" + input.value + "&";


        //all the selects
        for( var z = 1; z < gridFormSelects.length; z++ )
        {
                input = gridFormSelects.item(z); 
                poststr += input.name + "=" + input.value + "&";
        }


	//all the other inputs
	for( var z = 0; z < gridFormInputs.length; z++ )
	{
		input = gridFormInputs.item(z);	
		if(input.checked || input.type == 'hidden' || input.type == 'text') 
		  poststr += input.name + "=" + input.value + "&";
	}
    makePOSTRequest('../SelfAssessment/save.php', poststr);
	changeGridMode();
};

//Function to update language
function saveLanguage()
{
	var poststr = '';
	var formInputs = document.getElementById('langform').getElementsByTagName('input');
	var formTexts = document.getElementById('langform').getElementsByTagName('textarea');

	var input = formInputs.item(0); 
	poststr += input.name + "=" + input.value + "&";

	//all the other inputs
	for( var z = 0; z < formTexts.length; z++ )
	{
       input = formTexts.item(z);	 
	   poststr += input.name + "=" + input.value + "&";
	}

    makePOSTRequest('../Admin/save.php', poststr);
};

//Function to upload cando proof
function saveEvidences()
{
        var poststr = '';
        var formInputs = document.getElementById('evidenceform').getElementsByTagName('input');

        //all the other inputs
        for( var z = 0; z < formInputs.length; z++ )
        {
           input = formInputs.item(z);        
           poststr += input.name + "=" + input.value + "&";
        }

    makePOSTRequest('../SelfAssessment/evidence.php', poststr);
};

function unLock()
{
    var poststr = '';
	var formInputs = document.getElementById('langform').getElementsByTagName('input');
	var formTexts = document.getElementById('langform').getElementsByTagName('textarea');

    var input = formInputs.item(0); 
	poststr += input.name + "=" + input.value + "&";
	formInputs.item(2).disabled=true;

	for( var z = 0; z < formTexts.length; z++ )
	{
       input = formTexts.item(z);
       input.disabled=true;	 
	}
	 document.getElementById('langtable').deleteRow(0)
    makePOSTRequest('../Admin/unlock.php', poststr);
};

// Shanes function to accept the posted data and pass to database
function makePOSTRequest(url, parameters) 
{
  http_request = false;
  if (window.XMLHttpRequest) 
  { // Mozilla, Safari,...
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) 
	 {
		http_request.overrideMimeType('text/xml');
	 }
  }
  

  if (!http_request) 
  {
	 alert('Cannot create XMLHTTP instance');
	 return false;
  }
  
  //http_request.onreadystatechange = alertContents;
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
  
};

//Shances function to set the background image...
function setBGImage()
{
	var image = document.getElementById('background-image').firstChild.data;
	thing = document.getElementById('content');
	thing.style.setProperty('background-image', "url(" + image + ")",null);
	
};

// Function to add the on click functions to the cando table
// Main table can now respond to clicks 
function addOnClickToCandoTable()  /// and shade if checked
{
	var gridTable = document.getElementById('sa_grid');
	var rows = gridTable.getElementsByTagName('tr');

    var gridinfo = 0;
    
	for( var z = 1; z < rows.length; z++ )
	{		
		var data = rows.item(z).getElementsByTagName('td');

		for( var i = 0; i < data.length; i++ )
		{
			var func = "changeCando(" + (z-1) + "," + (i) + ",'hover');shadeBorder("+gridinfo+")";
			var func2 = "changeCando(" + (z-1) + "," + (i) + ",'clicked');shadeGoalBar("+gridinfo+")";
			data.item(i).setAttribute('onmouseover',func);
			data.item(i).setAttribute('onmouseout',"unshadeBorder("+gridinfo+");");
			data.item(i).setAttribute('onClick',func2);
			gridinfo++;
		}
	}
};



// Shade in the goal bar area for the cando you have selected
var shaded = null;
function shadeGoalBar(data)
{ 
   if(codeblocks[data] == shaded)
    {
      codeblocks[data].style.backgroundColor = "white";
      locked="false";
      shaded=null;
      radioFunction("disable");
    }
   else if(codeblocks[data] != shaded)
    {
      if(shaded == null)
        codeblocks[data].style.backgroundColor = "white";
      else
       shaded.style.backgroundColor = "white";
        
      codeblocks[data].style.backgroundColor = "black";
      locked="true";
      shaded = codeblocks[data];   
      radioFunction("enable")  
    }   
};


// Alter the border around the goal bar area you are hovering on 
function shadeBorder(data)
{
  if(locked == "false")
    codeblocks[data].style.borderColor = 'red';
};

//Reset the border around the goal bar area you just left
function unshadeBorder(data)
{
    codeblocks[data].style.borderColor = 'black';
};

//function to enable and disable radio buttons
function radioFunction(mode)
{
  	var candos = document.getElementById('candos'); 
	var input = candos.getElementsByTagName('input'); 

	for( var z = 0; z < input.length; z++ )
	{
	  if(mode == "enable")
	   input.item(z).removeAttribute('disabled');
	  else
	   input.item(z).setAttribute('disabled','disabled');
	}
};

/*
	Does lots of initialisation
	1. Make all icando/iwanto icando by default
	2. Disable anything that's not a button
	3. Make all radio buttons do the colour thing, possibly show the objective and change editing mode.
	4. Make all select buttons change editing mode.
		(Cos otherwise, if a goal is set and you change the date, you couldn't save.)
*/
function addCandoGridFunctions()
{
	var candos = document.getElementById('candos'); 
	var input = candos.getElementsByTagName('input'); 
 
 	// For each input TAG ... make it display cando instead of wanto
    for( var z = 0; z < input.length; z++)
    {
       var type = input.item(z).type;
       
       if(type != 'button' && type != 'text')
       {
	       // Get the name of this TAG ...
	       var name = 'q'+input.item(z).name; // ... precede it with a 'q'
	       
	       // Note here that we are just using the input tag to get the name, precede that with a 'q' to get the icando/iwanto text.
           showCando(name);
       }
    }
    
    // Disable everything that's not a button
    for( var z = 0; z < input.length; z++ )
       if(input.item(z).type != 'button')
	      input.item(z).setAttribute('disabled','disabled');
    

	/*
		For each radio button, if clicked, then the corresponding item would change appropriate colour.
		(This code adds the functions to do this.)
		
		i.e. If the icando radio button named 'icando_2_3_4', was clicked, then the main grid item (also named icando_2_3_4),
		would change to green (icando colour) and the icando text (named qicando_2_3_4) would also change to green.
		The colorData function would do this.
		However, it would be more efficient, if the colour data function could work out which item was associated with it,
		(i.e. could figure it's own name) and then used that to colour the bars. This would be more efficient, as you wouldn't
		need parameters to each function.
	*/
    for( var z = 0; z < input.length; z++ )
	{
       if(input.item(z).type == 'radio')
       {
	      var myclass = input.item(z).parentNode.className;

          // Parent class of the input field contains the div that has the appropriate class
          // Use this to determine the appropriate colour
          var color = '#ddd'; // Assume reset
	      if(myclass=="objective")
		     color = 'orange';
		  else if(myclass=="icando")
		     color = 'mediumseagreen';
		     
          var name = 'q'+input.item(z).name;
          
          // Now associate a function with the radio button
	      var func;
       
	      if(myclass=="objective")
	      {
			  wantostring = new String(name);
		      wantostring = wantostring.replace("cand", "want");
	          func = "showObjective('"+name+"'); colorData('" + name + "' , '" + color + "'); colorData('" + wantostring + "' , '" + color + "')";
	      }
	      else if(myclass=="icando")
             func = "showCando('"+name+"'); colorData('" + name + "' , '" + color + "')";
          else if (myclass=="reset")
          	 // CDaly: Need to hide the upload button (if it exists, i.e. if a productive skill)
             func = "showCando('"+name+"'); hideUpload('"+name+"'); colorData('" + name + "' , '" + color + "')";
	      
	      // In each case, we will want to change mode to editing.
	      func += "; changeGridMode("+EDITING+")";
	      input.item(z).setAttribute('onCLick', func);

		  // Now check the initial data
	      if(input.item(z).checked) 
	      {
	          // Colour in bar on main grid and the cando
	          colorData(name , color);	//color cando now if a checkbox is already checked 
	          if(myclass=="objective")
	          {
	             showObjective(name);
	             colorData(wantostring, color); // overwrite the just drawn cando.
	          }
	      }
	      else // If icando button isn't checked ...
	         if(myclass=="icando")
	            hideUpload(name); // ... hide the upload button
       }     
	}

	// If something is selected, change the mode to editing	 
    var select = candos.getElementsByTagName('select'); 
 
    for( var z = 0; z < select.length; z++)
    {
       var func = "changeGridMode("+EDITING+")";
       select.item(z).setAttribute('onClick', func);
    }
};

function hideUpload(id)
{
   // We only want to hide upload, which only exists for the productive skills
   // Extract the skill from the id. A little ignorent, but we're desparate
   var skill = id.charAt(8);
   // Is it a productive skill?
   if(skill == '2' || skill == '3' || skill == '4')
   {
	   // ... yep, turn off examples icons
	   examplestring = new String(id);
	   examplestring = examplestring.replace("q", "e");
	   document.getElementById(examplestring).style.display = "none"; //ecando
   }	
}

function showObjective(id)
{
   document.getElementById(id).style.display = "none"; //qcando
   wantostring = new String(id);
   wantostring = wantostring.replace("cand", "want");
   document.getElementById(wantostring).style.display = "block"; //qwanto
  
   //turn off examples icons
   examplestring = new String(id);
   examplestring = examplestring.replace("q", "e");
   document.getElementById(examplestring).style.display = "none"; //ecando
  
  
   //turn on objective dropdown
   objectivestring = new String(wantostring);
   objectivestring = objectivestring.replace("q", "e");
   document.getElementById(objectivestring).style.display = "block"; //ewanto
};

/*
	This function takes an id, makes the element visible,
		makes the corresponding wantto invisible
		makes the examples visible
		turns off the objectives.
		
	So by default, all candos are visible, all wantos invisible.
*/
function showCando(id)
{
   document.getElementById(id).style.display = "block"; //qcando
   wantostring = new String(id);
   wantostring = wantostring.replace("cand", "want");
   document.getElementById(wantostring).style.display = "none"; //qwanto
 
   //turn on examples icons
   examplestring = new String(id);
   examplestring = examplestring.replace("q", "e");
   document.getElementById(examplestring).style.display = "block"; //ecando
  
   //turn off on objective dropdown
   objectivestring = new String(wantostring);
   objectivestring = objectivestring.replace("q", "e");
   document.getElementById(objectivestring).style.display = "none"; //ewanto
};

/*
	There should be two items with this name, the bar in the top grid and the bar in the current candotable
*/
function unsetRadio(name)
{
  var radios = document.getElementsByName(name);
  for(var i=0; i < radios.length; i++)
     radios.item(i).checked=false;
  
  // Change the element to the reset color
  colorData('q'+name,'#ddd');     
};

// function to color in the cando bars
function colorData(name, color)
{
   var data = document.getElementsByName(name);
   for( var i = 0; i < data.length; i++)
   { 
  	  var cell = data[i];
  	  if(cell.className == "largecode")
  	     cell.parentNode.style.backgroundColor = color;
      cell.style.backgroundColor = color;
   }
};


// Shanes function to alter the visible candos
function changeCando( skill , grade ,method)
{
  if(locked == "false" || method=="clicked")
  {	
	var toShow = 'cando_' + skill + '_' + grade;
	var toHide = 'cando_' + currentCandoSkill + '_' + currentCandoGrade;
	
	
	currentCandoSkill = skill;
	currentCandoGrade = grade;

	var hider = document.getElementById(toHide);
	var show = document.getElementById(toShow);

    hider.setAttribute('class' , 'candohidden');
	show.setAttribute('class' , 'candoshow');
  } 
};
/////////////////////////////////////////////////////////////////////////////
//                                                                         //
// NOTICE OF COPYRIGHT                                                     //
//                                                                         //
// Moodle - Filter for converting TeX notation to typeset mathematics      //
// using jsMath                                                            //
//                                                                         //
// Copyright (C) 2005-2006 by Davide P. Cervone                            //
// This program is free software; you can redistribute it and/or modify    //
// it under the terms of the GNU General Public License as published by    //
// the Free Software Foundation; either version 2 of the License, or       //
// (at your option) any later version.                                     //
//                                                                         //
// This program is distributed in the hope that it will be useful,         //
// but WITHOUT ANY WARRANTY; without even the implied warranty of          //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           //
// GNU General Public License for more details:                            //
//                                                                         //
//          http://www.gnu.org/copyleft/gpl.html                           //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////

/****************************************************************/
/*
 *  Configure the jsMath filter here.  See also the filter.php file.
 */

jsMath = {
  Moodle: {
    version: 1.8,               // version of this file
    processSlashParens: 1,      // process \(...\) in text?
    processSlashBrackets: 1,    // process \[...\] in text?
    processDoubleDollars: 1,    // process $$...$$ in text?
    processSingleDollars: 0,    // process $...$ in text?
    fixEscapedDollars: 0,       // convert \$ to $ outside of math mode?
    mimetexCompatible: 1,       // make jsMath handle mimetex better?
    doubleDollarsAreInLine: 0,  // make $$...$$ be in-line math?
    allowDoubleClicks: 1,       // show TeX source for double-clicks?
    allowDisableTag: 1,         // allow ID="tex2math_off" to disable tex2math?
    showFontWarnings: 0,        // show jsMath font warning messages?
    processPopups: 1,           // process math in popup windows?
    loadFiles: null,            // a single file name or [file,file,...]
    loadFonts: null,            // a single font name or [font,font,...]
    scale: 120,                 // the default scaling factor for jsMath
    filter: 'filter/jsmath'     // where the filter is found
  }
};

//  If you want to use your own custom delimiters for math instead
//  of the usual ones, then uncomment the following four lines and
//  insert your own delimiters within the quotes.  You may want to
//  turn off processing of the dollars and other delimiters above
//  as well, though you can use them in combination with the
//  custom delimiters if you wish.

//     jsMath.Moodle.customDelimiters = [
//        '[math]','[/math]',        // to begin and end in-line math
//        '[display]','[/display]'   // to begin and end display math
//     ];

//  [Note that the code below doesn't do any special quoting of the
//  strings, so you should not use single quotes or backslashes as
//  part of your strings, unless you know what you are doing.  See
//  the jsMath author's documentation for the tex2math plugin for
//  more caveats about using custom delimiters.]

/****************************************************************/
/****************************************************************/
//
//            DO NOT MAKE CHANGES BELOW THIS
//
/****************************************************************/
/****************************************************************/

jsMath.Autoload = {
  findTeXstrings: 0,
  findLaTeXstrings: 0,
  findCustomStrings: jsMath.Moodle.customDelimiters,
  loadFiles: jsMath.Moodle.loadFiles,
  loadFonts: jsMath.Moodle.loadFonts
};

if (jsMath.Moodle.processSingleDollars ||
    jsMath.Moodle.processDoubleDollars ||
    jsMath.Moodle.processSlashParens ||
    jsMath.Moodle.processSlashBrackets ||
    jsMath.Moodle.fixEscapedDollars) {

  jsMath.Autoload.findCustomSettings = {
    processSingleDollars: jsMath.Moodle.processSingleDollars,
    processDoubleDollars: jsMath.Moodle.processDoubleDollars,
    processSlashParens:   jsMath.Moodle.processSlashParens,
    processSlashBrackets: jsMath.Moodle.processSlashBrackets,
    fixEscapedDollars:    jsMath.Moodle.fixEscapedDollars,
    custom: 0
  };
}

jsMath.Autoload.scripts = document.getElementsByTagName('script');
jsMath.Autoload.root = jsMath.Autoload.scripts[jsMath.Autoload.scripts.length-1].src;
jsMath.Autoload.root = jsMath.Autoload.root.replace('/lib/javascript-mod.php',
                                                    '/'+jsMath.Moodle.filter+'/jsMath/');
jsMath.Autoload.scripts = null;

jsMath.tex2math = {
  doubleDollarsAreInLine: jsMath.Moodle.doubleDollarsAreInLine,
  allowDisableTag:        jsMath.Moodle.allowDisableTag
}
if (jsMath.Moodle.mimetexCompatible) {
  if (!jsMath.Autoload.loadFiles) {jsMath.Autoload.loadFiles = []}
  if (typeof(jsMath.Autoload.loadFiles) == 'string')
    {jsMath.Autoload.loadFiles = [jsMath.Autoload.loadFiles]}
  jsMath.Autoload.loadFiles[jsMath.Autoload.loadFiles.length] = "plugins/mimeTeX.js";
}

jsMath.Controls = {cookie: {scale: jsMath.Moodle.scale, global: 'never'}};
if (!jsMath.Moodle.allowDoubleClicks) {
  jsMath.Click = {CheckDblClick: function () {}};
}
if (!jsMath.Moodle.showFontWarnings) {
  jsMath.Font = {Message: function () {}};
}

/*
 *  Hook into overlib() so that we check the contents for
 *  mathematics after it appears.
 */
jsMath.Moodle.overlib = function () {
  jsMath.Moodle.oldOverlib();
  if (jsMath.Moodle.overlibStarted) return;
  jsMath.Moodle.overlibStarted = 1;
  jsMath.Autoload.ReCheck();
  jsMath.Autoload.Run(document.getElementById('overDiv'));
  jsMath.Synchronize(
    "jsMath.Moodle.oldProgress = jsMath.Controls.cookie.progress;" +
    "jsMath.Controls.cookie.progress = 0;"
  );
  jsMath.ProcessBeforeShowing('overDiv');
  jsMath.Synchronize(
    "jsMath.Controls.cookie.progress = jsMath.Moodle.oldProgress;" +
    "jsMath.Moodle.overlibStarted = 0;"
  );
}

jsMath.noGoGlobal = 1;
jsMath.noChangeGlobal = 1;
jsMath.noShowGlobal = 1;

jsMath.Moodle.onload = window.onload
window.onload = function () {
  jsMath.Moodle.oldOverlib = window.overlib;
  if (jsMath.Moodle.onload) {jsMath.Moodle.onload()} // call old handler
  if (document.getElementById("Process_jsMath")) {   // set by filter.php
    jsMath.Autoload.Check();
    jsMath.Process();
    if (jsMath.Moodle.processPopups) {
      //  Hook into overlib library
      jsMath.Synchronize(function () {window.overlib = jsMath.Moodle.overlib});
    }
  }
}

document.write('<script src="'+jsMath.Autoload.root+'plugins/autoload.js"></script>');
