// Javascript from Moodle modules
/**
 * This function is used to add/remove
 * the style named 'checked' to/from the
 * passed element's parent DIV.
 *
 * This function is used when checking
 * checkboxes or radio buttons.
 *
 * @param object el This element's parent will be used when adjusting the style
 * @param string parentClass Name of the parent DIV class to find
 * @param string groupClassName Name of a group of elements that should have the class 'checked' removed before toggling the passed one (el).
 * @return void
 **/
function assessToggleStyle(el, parentClass, groupClassName) {
    // Holds the parent element
    var obj;

    if (groupClassName) {
        var parent   = findParentNode(el, 'DIV', groupClassName);
        var elements = parent.getElementsByTagName('input');

        // Turn remove the style 'checked' from all elements in elements
        for (i = 0; i < elements.length; i++) {
            obj = findParentNode(elements[i], 'DIV', parentClass);

            if (obj.className.indexOf('checked') != -1) {
                obj.className = obj.className.replace(new RegExp(' ?checked'), '');
            }
        }
    }

    // Toggle the passed element
    obj = findParentNode(el, 'DIV', parentClass); 

    if (obj.className.indexOf('checked') == -1) {
        obj.className += ' checked';
    } else {
        obj.className = obj.className.replace(new RegExp(' ?checked'), '');
    }
}

/**
 * Holds the assessAutoSave object
 *
 * @var object
 **/
var assessAjaxObject = new assessAutoSave();

/**
 * Constructor - set defaults
 *
 * @return void
 **/
function assessAutoSave() {
    this.saveTimeoutId = 0;
    this.saveInProgress = false;
    this.formsToSave = Array();
    this.varsAreSet = false;
    this.saveInterval = 15000;      // Overall save interval.  Can only save every this.saveInterval miliseconds
    this.changeInterval = 10000;    // Save interval for all form elements
    this.textChangeInterval = 4000; // Save interval for textareas (overrides this.changeInterval)
    this.lastSave = 0;
}
/**
 * Variable setup routine - adds method to window.onload
 *
 * @param string wwwroot WWW root of the site
 * @param int offSet User's time minus current time (seconds)
 * @return void
 **/
assessAutoSave.prototype.setVars = function(wwwroot) {
    if (!this.varsAreSet) {
        this.wwwroot = wwwroot;

        if (typeof window.onload == "function") {
            var oldmethod = window.onload;
            window.onload = function() {
                oldmethod();
                assessAjaxObject.setListeners();
            }
        } else {
            window.onload = function() {
                assessAjaxObject.setListeners();
            }
        }
    }
    this.varsAreSet = true;
};
/**
 * Adds event listerns to form elements
 *
 * @return void
 **/
assessAutoSave.prototype.setListeners = function() {
    var forms = document.getElementsByName('assessaddformautosave');
    var other, textareas, form, datachange, datakeyup, iframs;

    for (var f = 0; f < forms.length; f++) {
        form = forms[f];
        form.assessCount = f;  // Used as a key later

        other = Array();
        textareas = Array();

        iframes = form.getElementsByTagName('iframe');
        for (i = 0; i < iframes.length; i++) {
            textareas.push(iframes[i].contentWindow.document);
        }
        for (i = 0; i < form.length; i++) {
            el = form.elements[i];
            if (el.tagName == 'TEXTAREA') {
                textareas.push(el);
            } else if (el.type != 'hidden' && el.type != 'button' && el.type != 'submit') {
                other.push(el);
            }
        }
        datachange = { formel: form, interval: this.changeInterval };
        YAHOO.util.Event.addListener(other, "click", assessAjaxObject.registerChange, datachange, assessAjaxObject);
        datakeyup = { formel: form, interval: this.textChangeInterval };
        YAHOO.util.Event.addListener(textareas, "keyup", assessAjaxObject.registerChange, datakeyup, assessAjaxObject);
    }
};
/**
 * Registers a form for saving and fires off setSaveTimeout()
 *
 * @param object e Event object
 * @param object data data.formel is the element of the form to save; data.interval is the wait till save
 * @return void
 **/
assessAutoSave.prototype.registerChange = function(e, data) {
    this.formsToSave[data.formel.assessCount] = data.formel;
    this.setSaveTimeout(data.interval);
};
/**
 * Sets a timeout for when to save the queue of forms.  Also
 * ensures that the save does not happen more frequently than
 * this saveInterval time.
 *
 * @param int milisec Miliseconds to save
 * @return void
 **/
assessAutoSave.prototype.setSaveTimeout = function(milisec) {
    var now = new Date();
    var timepassed = now.getTime() - this.lastSave;
    if (timepassed < this.saveInterval && this.lastSave != 0) {
        var timeleft = this.saveInterval - timepassed;
        if (timeleft > milisec) {
            milisec = timeleft;
        }
    }
    if (this.saveTimeoutId != 0) {
        clearTimeout(this.saveTimeoutId);
    }
    this.saveTimeoutId = setTimeout("assessAjaxObject.saveTimeoutId = 0; assessAjaxObject.saveForms();", milisec);
};
/**
 * Submits all forms that are targeted for saving
 *
 * @return void
 **/
assessAutoSave.prototype.saveForms = function() {
    if (!this.saveInProgress) {
        this.saveInProgress = true;

        if (this.formsToSave.length > 0) {
            var form, callback;

            if (typeof window.onunload == "function") {
                window.onunload();  // Moves HTMLEditor text to its textarea
            }

            for (var key in this.formsToSave) {
                form = this.formsToSave[key];

                callback = { success:this.handleSuccess,
                             failure:this.handleFailure,
                             argument:form,
                             scope:assessAjaxObject };

                YAHOO.util.Connect.setForm(form);  // Sets all form data for submitting
                YAHOO.util.Connect.asyncRequest('POST', this.wwwroot+'/mod/assess/rest.php', callback);
            }
            this.formsToSave = Array();
        }
    } else {
        // Still performing save - wait longer
        this.setSaveTimeout(this.saveInterval);
    }
};
/**
 * Handles successful asyncRequest call - sends feedback to user
 *
 * @return void
 **/
assessAutoSave.prototype.handleSuccess = function(o) {
    var divs = o.argument.getElementsByTagName('div');

    if (o.responseXML != null) {
        var root = o.responseXML.documentElement;
        var submissionid = root.getElementsByTagName('submissionid')[0].firstChild.nodeValue;
        var timesaved = root.getElementsByTagName('timesaved')[0].firstChild.nodeValue;

        // Update the time
        divs[0].getElementsByTagName('span')[0].innerHTML = timesaved;

        // Update the submissionid if not 0
        if (submissionid != 0) {
            var inputs = o.argument.getElementsByTagName('input');
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].name == 'submissionid') {
                    inputs[i].value = submissionid;
                    break;
                }
            }
        }
        this.handleCommon(divs[1], divs[0]);
    } else {
        // No XML returned, failed
        this.handleCommon(divs[0], divs[1]);
    }
};
/**
 * Handles failed asyncRequest call - sends feedback to user
 *
 * @return void
 **/
assessAutoSave.prototype.handleFailure = function(o) {
    var divs = o.argument.getElementsByTagName('div');
    this.handleCommon(divs[0], divs[1]);
};
/**
 * Handles common asyncRequest tasks for success/failure
 *   - Display success/failure info to user
 *   - Update variables
 *
 * @return void
 **/
assessAutoSave.prototype.handleCommon = function(hide, show) {
    // Set visibility
    if (YAHOO.util.Dom.hasClass(show, 'hidden')) {
        YAHOO.util.Dom.removeClass(show, 'hidden')
    }
    if (!YAHOO.util.Dom.hasClass(hide, 'hidden')) {
        YAHOO.util.Dom.addClass(hide, 'hidden');
    }

    this.saveInProgress = false;

    var date = new Date();
    this.lastSave = date.getTime();
};<?php    
/**
 * podcaster javascript
 *
 * @author  Humboldt Universitaet zu Berlin
 *            Christoph Soergel <christoph.soergel@cms.hu-berlin.de>
 * @version 1.0
 * @package podcaster
 *
 **/
if (!defined('MOODLE_INTERNAL')) {
  die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
}
?>
<!--
//
function repository_openpopup(url,name,options,fullscreen) {
  fullurl = url;
  windowobj = window.open(fullurl,name,options);
  if (fullscreen) {
     windowobj.moveTo(0,0);
     windowobj.resizeTo(screen.availWidth,screen.availHeight);
  }
  windowobj.focus();
  return false;
}
// -->
var slideNo=-1;
var currentSlideNo=0;
var autoSync = false;

<!-- TabView -->
var tabView = new YAHOO.widget.TabView("tabset");

<!--goto next slide -->
function gotoNextSlide(){
	if(numberOfSlides!=slideNo){
		slideNo += 1;
		displaySlide();
	}else{
		alert("Slide Show Ends!");
	}	
}

<!-- goto previous slide -->
function gotoPrevSlide(){
	if(slideNo > 1){
		slideNo -= 1;
		displaySlide();
	}else{
		alert("We are at the first slide!");
	}
}

<!-- goto first slide -->
function gotoFirstSlide(){
	if(slideNo != 1){
		slideNo= 1;
		displaySlide();
	}else{
		alert("Already on the first slide!");
	}
}

<!-- goto first slide -->
function gotoLastSlide(){
	if(slideNo != numberOfSlides){
		slideNo=numberOfSlides;
		displaySlide();
	}else{
		alert("Already on the last slide!");
	}
}

function displaySlide(){
	var slide= slidePath+"Slide"+slideNo+".JPG";
	var FO = {	movie:slide,width:600,height:450,majorversion:"7",build:"0",bgcolor:"#FFFFFF"};
	UFO.create(	FO, "slide-show");	
}

<!-- Trig Auto Sync -->
function trigAutoSync(){
	autoSync= document.getElementById('autosync').checked;
	checkAutoSync();
}

<!-- Handle Presenters Auto Sync -->
function checkAutoSync(){
	clearMsg();
	if(autoSync){
		if(currentSlideNo!=slideNo) syncSlide();
	}
	setTimeout('checkAutoSync()',1000);
}

<!-- Clear Messages -->
function clearMsg(){
	document.getElementById('slide-nav').innerHTML= '';
}

<!-- Async Calls -->

var handleGetSuccess = function(o){
	if(o.responseText !== undefined){
		currentSlideNo = o.responseText;
	}
}

var handleGetFailure = function(o){
	if(o.responseText !== undefined){
		document.getElementById('currentslide').innerHTML= 'Error: '+o.statusText;
	}
}

var callbackGet =
{
	success:handleGetSuccess,
	failure:handleGetFailure,
	argument: { param:"param", bar:"bar" }
};

<!-- Async Call the server to update the current slide number -->
var handleSetSuccess = function(o){
	if(o.responseText !== undefined){
		document.getElementById('slide-nav').innerHTML= 'The Global Current Slide Changed';
		currentSlideNo = slideNo;
	}
}

var handleSetFailure = function(o){
	if(o.responseText !== undefined){
		alert('Updating the status failed:'+o.statusText);
	}
}

var callbackSet =
{
	success:handleSetSuccess,
	failure:handleSetFailure,
	argument: { param:"param", bar:"bar" }
};

var callbackResetPr = {
  success: function(o) {
    alert(o.responseText);
  }
}
/**
 * ================================================================================
 * original source: http://developer.apple.com/internet/webcontent/examples/detectplugins_source.html
 * which as of 2008/06/06 included usage criteria stipulating that the code can be 
 * incorporated into your own code without restriction, and be redistributed, but 
 * is not to be distributed as "Apple sample code" after having made changes.
 * much thanks to Apple for this :-)
 *
 * subsequently modified for use as a block within Moodle courses
 *  by Dean Stringer @ Waikato University, New Zealand
 * changes:
 *  6th June 2008 - initial release
 *  o removed redirectCheck(), goURL(), detectQuickTimeActiveXControl() and detectDirector()
 *  o removed redirectURL and redirectIfFound params from all detect* subs
 *  o added detectAcrobat(), detectJava(), detectCookies() and showResult()
 * ================================================================================
 */

// initialize global variables
var detectableWithVB = false;
var pluginFound = false;

function canDetectPlugins() {
    if( detectableWithVB || (navigator.plugins && navigator.plugins.length > 0) ) {
	return true;
    } else {
	return false;
    }
}

function detectFlash() {
    pluginFound = detectPlugin('Shockwave','Flash'); 
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('ShockwaveFlash.ShockwaveFlash');
    }
    return pluginFound;
}

//function detectDirector() { 
// not including Director, Flash player is used typically to play shockwave files
// created in Adobe Director
//  pluginFound = detectPlugin('Shockwave','Director'); 
//    // if not found, try to detect with VisualBasic
//    if(!pluginFound && detectableWithVB) {
//	pluginFound = detectActiveXControl('SWCtl.SWCtl');
//    }
//    return pluginFound;
//}

function detectQuickTime() {
    pluginFound = detectPlugin('QuickTime');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('QuickTime.QuickTime');
    }
    return pluginFound;
}

function detectReal() {
    pluginFound = detectPlugin('RealPlayer');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = (detectActiveXControl('rmocx.RealPlayer G2 Control') ||
		       detectActiveXControl('RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)') ||
		       detectActiveXControl('RealVideo.RealVideo(tm) ActiveX Control (32-bit)'));
    }	
    return pluginFound;
}

function detectWindowsMedia() {
    pluginFound = detectPlugin('Windows Media');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('MediaPlayer.MediaPlayer');
    }
    return pluginFound;
}

function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = detectPlugin.arguments;
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
	var pluginsArrayLength = navigator.plugins.length;
	// for each plugin...
	for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    // loop through all desired names and check each against the current plugin name
	    var numFound = 0;
	    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
		// if desired plugin name is found in either plugin name or description
		if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) || 
		    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    // this name was found
		    numFound++;
		}   
	    }
	    // now that we have checked all the required names against this one plugin,
	    // if the number we found matches the total number provided then we were successful
	    if(numFound == daPlugins.length) {
		pluginFound = true;
		// if we've found the plugin, we can stop looking through at the rest of the plugins
		break;
	    }
	}
    }
    return pluginFound;
} // detectPlugin


// Here we write out the VBScript block for MSIE Windows
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
    document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('</scr' + 'ipt>');
}

// ================================================================================
// additions (June/2008 onwards)
// ================================================================================

function detectAcrobat() {
    pluginFound = detectPlugin('Adobe Acrobat'); 
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
    pluginFound = detectActiveXControl('AcroPDF.PDF');  // ver7+
    }
    if(!pluginFound && detectableWithVB) {
    pluginFound = detectActiveXControl('PDF.PdfCtrl');    // ver6-
    }
    return pluginFound;
}

function detectJava() {
    pluginFound = detectPlugin('Java Plug-in'); 
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
    pluginFound = navigator.javaEnabled();
    // note: navigator.javaEnabled() does not reveal whether Java is installed or not in IE. It merely tells you if 
    // the applet tag is enabled or disabled. You can disable the applet tag in the IE security settings 
    }
    return pluginFound;
}

function detectCookies() {
    pluginFound = navigator.cookieEnabled;
    return pluginFound;
}

function showResult(pluginName, status) {
    statusImg = 'cross_red_small.gif';
    if (status) statusImg = 'tick_green_small.gif';
    document.write('<br><img src="' + browserCapImgPath + statusImg + '">');
    document.write('&nbsp;' + pluginName);
}
/**
 * This function checks that the selected action is valid, via checking that the
 * selected action is valid and that there is at least one checked course
 * (eg: checkchecked())
 *
 * @param object    form        Document form object
 * @return boolean
 **/
function course_management_checksubmit(form) {
    var destination = form.courseaction.options[form.courseaction.selectedIndex].value;
    if (destination == "" || !course_management_checkchecked(form)) {
        form.courseaction.selectedIndex = 0;
        return false;
    } else {
        // Modifies the forms action value to submit to selected page
        return course_management_form_action(form, destination);
    }
}

/**
 * This function checks all inputs on the form that are of type checkbox to
 * ensure that at least one checkbox is selected
 *
 * @param object    form    Document form object
 * @return boolean
 **/
function course_management_checkchecked(form) {
    var inputs = document.getElementsByTagName("INPUT");
    var checked = false;
    inputs = filterByParent(inputs, function() {return form;});
    for(var i = 0; i < inputs.length; ++i) {
        if (inputs[i].type == "checkbox" && inputs[i].checked) {
            checked = true;
            // Only needs to check for one checked value
            break;
        }
    }
    return checked;
}

/**
 * This function modifies the form's action to passed destination url and
 * optionally submits.
 *
 * @param object    form        Document form object
 * @param string    destination URL of destination
 * @param boolean   submit      Submits form if set to true...returns bool otherwise
 **/
function course_management_form_action(form, destination, submit) {
    form.action = destination;
    if (submit) {
        form.submit();
    } else {
        return true;
    }
}function getClasses(element) {
	if (document.getElementById(element).getAttribute("class")) return document.getElementById(element).getAttribute("class");
	else return document.getElementById(element).getAttribute("className");
}

function toggleClass(element,c1,c2) {
  var classes = getClasses(element).split(" ");
  
  for (i=0; i<classes.length; i++) {
    if (classes[i] == c1) classes[i] = c2;
    else if (classes[i] == c2) classes[i] = c1;
  }
  
	document.getElementById(element).setAttribute("class", classes.join(" "));
	document.getElementById(element).setAttribute("className", classes.join(" "));
}