	window.et_version="14j";
	window.php='/chat/php_'+window.et_version+"/";

/*	
		REQUIRED PAGE DIVs for all ET - pages using this function

		1) Two language flags FIRST: img class='lang1 translate' & SECOND img class='lang2 translate' (Language select flags)
			See the library/template/book_page.html for examples of div ids for translations. 
			The translations are processed in functions : ET_Show_English('')  &  ET_Show_Translations()

		2) div id='page_url'
		3) div class='error_message'
		4) VIDEO:  video_player video_href video_path

		5) wait_message ü For displaying an animated gif showing that something is being loaded

		M A I N T E N A N C E
		=====================

	2012-01-17	-	new ET_linkto() for linking either by toggle load to index page we are in or linking to that page a href

	2011-12-10	-	ET load_html set no_reset to any non null value to avoid clearing all others with a setActive() !! Eg emoticons
	2011-12-06	-	/php_version for all php to make a clean release (version same as js version eg php_14e
	2011-12-05	-	AD_group_list(pars) not allow for a userid that must be a member of listed groups
				For room changing. Now when changing rooms, the user only sees rooms for groups which they are a member.
	2011-12-04	-	gmt_diff added to ET load()
	2011-12-01	-	ET_search() new function

	2011-11-25	-	CKeditor js calls 
	
	2011-11-20	-	Fixed the AD_event_update() duration bug.
	2011-11-20	-	Moved php scripts into /php_version from admin folder. (We will shut down the admin page someday)
				et_classroom added to AD_user_update

	2011-10-14	-	New function ET_activate_tabs();
	2011-10-11	-	Added IPA status from etlw_guest from admin/ php/user_show.php for blocked users
	2011-10-02	-	NEW Generic function for loading php script into a div.  ET load()
	2011-09-08	-	new function ET_domain() to find the domain and avoid hard coding it
	2011-09-04	-	window.debug added to window object
	2011-08-26	-	function ET_sql_interface() passing in the query to run.

	2011-08-22	-	Added:	navi_timestamp and navi_direction for:
					AD_event_list() 

	2011-08-21	-	Added cookie functions and old quiz question scripts. QUESTION SCRIPTS need updating !!!

	2011-08-20	-	Changed ET_slide_show() to allow output in a specified DIV
	2011-08-18	-	Added ET_too_busy() function to prevent scripts running when other big scripts are already active.
				Later when someone clicks such a button we can display some text.

	2011-08-10	-	Extended security options to ET load_html() - Allow specification of a list of specific mdl_user.
	2011-08-08	-	Re write ET_get_profile to make it much more efficient
	2011-07-30	-	Added empty function ET_toggle_edit()
	2011-07-24	-	Allow entry of events retrospectively. In the past.
	2011-07-23	-	(7b) Incorporating all of admin.js as one script file!!
	2011-06-13	-	(7a) for loading toggle pages as full html and extracting the body part
				get_page > admin/ php/extract_html.php (was load_html.php)
	2011-06-10	-	ET_chatpeep() 
	2011-06-05	-	New menu OL instead of table
	2011-05-14	-	new function random_letters(parameter_string)

	2011-04-21	-	separate ET_slide_search() function 
	2011-04-19	-	function ET_postchat_message() replace @dquote and @squote This allows the posting of complex messages
				involving nested delimiters
	2011-04-18	-	ET load_html pass window.helper to allow teacher helpers to post to the main hall
	2011-04-17	-	added guest window.userid='1' to window.redirect checks 
	2011-04-14	-	added window.country window.et_teacher
	2011-04-12	-	window.redirect added to redirect guests	
	2011-04-06	-	ET_play_sound() - Works like ET_play_video
	2011-03-19	.	Big bug fixes in url_fld() function ie: &et_teacher=x&teacher=Y ...
	2011-03-04	-	Show skype only to skypers
	2011-02-01	-	ET_div_click() FINISH THIS LATER eg: CAE gifts - click shuffle position until correct scripting
	2011-01-31	-	Posting pages from library books to the chat - ET_get_profile() must be called from the book
				as only teachers can do this. 
	2011-01-11	-	LETS DEVELOP THE posting page links DIV page_url - Perhaps onclick on the menu should change page_url???

	2010-12-29	-	ET_adjust_layout() new function for page layout 
	2010-12-21	-	REMOVED all language text tables and re-wrote the flags !!! 
	2010-12-17	-	Adding buttons for external toggles to post into the chat room and fix the member/guest problems in ET_user_text()
	2010-12-11	-	Make report_interval_idss an array to allow simultaneous reports and queries REMOVED TOO COMPLEX and BUGGY!!
	2010-12-08	-	report_start parameter - ADD a js script to run AFTER the php has completed!!
	2010-12-01	-	Created for new example book in library/example/
		Header and footer functions replaced by REAL <A CLASS='' HREF..> with .ready() appending the window.regress

	2010-09-30	-	Version j > to replace url_fld() with a similar function which looks through an optional variable.
	2010-09-12	-	New ET_user_text() function for use from report_profile() in all pages
				This will combine all classes MEMBER gGUEST and languages into one piece of logic

	2010-08-19	-	Added functions report_start() and report_check()
	2010-08-19 	-	New js login intercept to set up our own SESSION data
	2010-08-14	-	TR CLASS SECTION search for class CONTAINS section and NOT CLASS = "SECTION"	
	2010-08-09	-	Fixed the double slash in the window.live_page
	2010-08-04	-	2c Table automatic row numbering function numberRows() added for new books
	2010-08-01	-	page_path > Go live link in header FIX (2b)
	2010-07-27	- 	Included all scripts in one - added table_mouse too (2b)
 	2010-07-21	-	EnglishTap new JavaScript library  - (We had IE problems (2a)

	//	Functions for running reports using Ajax in the home page

	//	2011-04-02	slide functions moved here from chatroom
	//	2011-03-31	function AD_new_members() added with country filter >> admin/ php/new_members.php
	//			+ country filter to AD_role_list()
	//	2011-03-18	added AD_upload() from form 
	//	2010-09-12	window.profile_ready var must be true before we can run queries.
	//	2010-08-31	edit_problem() function array positions of record moved. Comes from list_problems.php	

*/	


	// G L O B A L  D A T A 

	window.domain='';
	if (top.location == location) {window.iframed=false;} else {window.iframed=true;}

	window.params='';	//	For ET_load() extra data string delimited

	// G L O B A L  U S E R  P R O F I L E 
	window.profile_ready=false;	// boolean
	window.profile=''; 		// url string

	window.interval='';
	window.count=0;
	window.busy=false;	// Set to true to tell scripts that they should wait a while
	window.current_room='0';

	window.userid='';
	window.username='';
	window.sid='';	// ID of selected who we are working on 

	window.ipa='';
	window.ipa_name='';
	window.ipa_status='';

	window.firstname='';
	window.lastname='';

	window.debug=false;

	window.variable='';	// Fly variable  for common block 
	window.highlight='';	// Marked div for shuffles etc., 
	window.session_id='';
	window.eofmarker="%eof%";
	window.mustlogin="You must sign on to do this";

	// Set up DEFAULT user profile vars including system roles
	window.roles='';	// To be a string of numbers indicating all site roles combined
	window.admin=false;
	window.course_admin=false;
	window.teacher=false; 	// I AM a teacher YES/NO

	window.et_teacher='';	// My teachers ID if I have one
	window.et_classroom='';	// Default room to enter when first going to the chat room 

	window.helper=false;
	window.student=false;

	// New Essential student information into window object Dec 25th 2010 
	window.phone='';
	window.mobile='';
	window.skype='';
	window.icq='';
	window.aim='';
	window.yahoo='';
	window.msn='';
	window.qq='';
	window.email='';
	window.country='';

	// The whole url data string returned from profile_report 
	window.guest=true;

	window.target="";
	window.url='';
	window.urldata="";
	window.stack='';		// Keeps track of which process initiated another process, to allow a return.
	window.pathlabel="englishtap"; // url label which must exist on any installation as part of the root folder name
	window.lang='en';
	window.translating=false;
	window.redirect='';	// set to redirect after loading the user profile if the user is not signed on
	window.answers=false;

	sortdef=new Object();
	sortdef.order='al';
	sortdef.element=0;

	video_text=new Object();	// To control the horizontal scroll bar for the video text
	video_text.starttime='';
	video_text.totaltime='';
	video_text.intervalMS='';
	video_text.div='';

	//	Set true when the users profile data query has returned. Regardless of whether the user is logged on or not. 
	var report_oncomplete=new Function();



	// 	NOT TO BE CONFUSED WITH document.ready !!!
	//	This can be set when we are ready :
	//	For example when all requierd MySQL queries have completed. (Note: These can be kicked off but not completed
	//	at the time of document.ready 


	word_keys=new Array();
	word_translated=new Array();

	BrowserDetect=new Object();
	
	//	MAYBE THIS IS IN the BrowserDetect object !?
	//	iPod can be used for other similar devices. there is a DIV class='ipod'	
	iPod=false;

	var screenW = 640, screenH = 480;
	if (parseInt(navigator.appVersion)>3) {
		screenW = screen.width;
		screenH = screen.height;
	} else if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3 && navigator.javaEnabled()) {
		var jToolkit = java.awt.Toolkit.getDefaultToolkit();
		var jScreenSize = jToolkit.getScreenSize();
		screenW = jScreenSize.width;
		screenH = jScreenSize.height;
	}

	//	P A G E  T O G G L I N G 
	window.active_page='';	
	// Disable Moodle OR chat 
	allow_moodle='';
	window.allow_moodle=true;
	allow_chat='';
	window.allow_chat=true;
	userid='';
	window.userid='';
	username='';
	live='';
	window.live=false;
	regress='';
	window.regress=''; // Path to return back to the homepage level 

	function ET_linkto(lp) {

		// BUG - Need a better way to do these links. The ET_load_htlm part works but the open doesn't

		// If the current page is an 'index.html' then load the new link into a toggle else link to it.
		// Later - Link to new if not in a book toggle

		lp_array=(ET_tokens(lp)+"||||||||").split("|");
		page=lp_array[0];

		//lert("URL "+window.url+ " link to "+ page);

		if(window.url.indexOf("index.html")>=0) {
			ET_load_html(page);
		} else {
			window.open(page,'_blank'); return false;
		}
		return false;
	}

	function ET_login(lp) {
		ET_load('/chat/php_'+window.et_version+'/login.php');
		return;
	}

	function ET_login_submit() {

		// This function allows us to intercept the moodle login and return FALSE if we need to 

		username=$('#username').val();
		password=$('#password').val();

		//lert("Function et_login() ENGLISH TAP LOGIN INTERCEPT js User:"+username+" Pw:"+password);
		// VALIDATE HERE and DO YOUR SET UP OF $_SESSION 
		//	return false;

		//lert("Function ET_login_submit() ENGLISH TAP LOGIN INTERCEPT js COMPLETE !! ");

		return true;

	}

	function ET_IntoView(focus_string) {
		defn=(focus_string+"|||").split("|");
		id=defn[0];totop=defn[1];
		elem=document.getElementById(id);
		elem.scrollIntoView(totop);

		// window.location = window.url + "#" + anchor;

		return;
	}

	function ET_search(spars) {

		sarray=(spars+"||||").split("|");
		stype=sarray[0];
		sdiv=sarray[1];
		if(sdiv=='') {sdiv='toggle_external';}

		// Choose the search form

		switch(stype) {
		case('member'):
			// Now using a server side php generated member search form
			ET_load(window.php+"user_search.php|"+sdiv);
			break;

		case('event'):
			// This is the page with the member search criteria form
			ET_load_html('chat/html/search_events.html|'+sdiv+'|Event Search Form');
			break;
		default:
			break;
		}
		return false;
	}

	function ET_edit_submit(edit_string) {

		// html edit page - buttons for admins on each page

		//lert("function ET_edit_submit() start ");

		edit_pars=(edit_string+"||||").split("|");
		edit_det=edit_pars[0];

		// 	<form action="#" sample_posteddata.php" method="post">

/*
//			CKEDITOR.replace( 'editor1',{fullPage : true,extraPlugins : 'docprops'});

			toedit=$('#toggle_external').html();
			$("textarea#editor1").text(toedit);
			//lert("Replaced the text area with the whole page ");

*/

		ET_php_load(window.php+'page_update.php');
		//lert("ET_edit_submit() completed ");

		return false;
	}

	function ET_activate_tabs() {

			// ACTIVATE TABS When page loads...
		$(".tab_content").hide(); //Hide all content
		$("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(".tab_content:first").show(); //Show first tab content

			//	On Click Event
		$("ul.tabs li").click(function () {

			$("ul.tabs li").removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".tab_content").hide(); //Hide all tab content

			var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			return false;
		});

	}

	function ET_settab(tabdefn) {

		//	T O G G L E	T A B S	marker mover	Use ID of TAB (Not Tab content DIV !!!)

		tab_array=(tabdefn+"||||").split("|");
		tab_id=tab_array[0];
		tab_div=tab_array[1];

		if(tab_div!='') {setActive(tab_div);}

		$("ul.tabs li").removeClass("active");		//Remove any "active" class
		$('#'+tab_id).addClass("active");		//Add "active" class to selected tab

		//lert("function ET_settab() COMPLETE ");
		return false;
	}

	//	S T R I N G	F U N C T I O N S
	//	===========	=================

	function stripTags(string, tag) {

		// Strip HTML tags from a string (NOT USED YET: php version of strip_tags(string,optional_allowed_tags) )

		var tagMatcher = new RegExp('</?' + tag + '>','g');
		return string.replace(tagMatcher, '');
	}


	function ET_htmlchars(convert_string) {
		//	This is to convert Chinese characters to Unicode numbers

		//lert('function ET_htmlchars()');
		convert_array=(convert_string+"||||").split("|");
		source_id=convert_array[0];
		destination_id=convert_array[1];
		options=convert_array[2];

		var source_str = $('#'+source_id).val();
		var destination_str = '';

		for(i=0; i<source_str.length; i++) {
			swap=false;ascii=source_str.charCodeAt(i);

			if(ascii>127) {swap=true;}

			switch(ascii) {
			case(60):swap=true;break;
			case(62):swap=true;break;
			}

			if(swap==true) {
				destination_str += '&#' + source_str.charCodeAt(i) + ';';
			} else {
				destination_str += source_str.charAt(i);
			}
		}
		$('#'+destination_id).html(destination_str);
		//lert('function ET_htmlchars() COMPLETE '+destination_str);
		return false;
	}

	function Asc(Str) {return Str.charCodeAt(0);}
	function Chr(AsciiNum) {return String.fromCharCode(AsciiNum)}

	function ET_tokens_class(div_class) {

		var myDIVs = getElmsByClassName(div_class,null,null)
		elm_count=myDIVs.length;

		for (elm=0; elm<(elm_count); elm++) {
			// paragraph_text=myDIVs[elm].innerHTML; OLD 
			original_text=$(myDIVs[elm]).html();
			paragraph_text=ET_tokens(original_text);
			//myDIVs[elm].innerHTML=paragraph_text;
			$(myDIVs[elm]).html(paragraph_text);
			//lert("Changed '" + original_text + "' to '" + paragraph_text+"' for user "+window.username+ " ready="+window.profile_ready);
		}

		//lert("function ET_tokens_class() compete for "+ elm_count+" in class: "+div_class);

		return;
	}

	function ET_tokens(tstring) {

		// Token string replacements for data

		tstring=tstring.replace(/@folder/g,window.folder);
		tstring=tstring.replace(/@userid/g,window.userid);
		tstring=tstring.replace(/@username/g,window.username);
		tstring=tstring.replace(/@regress/g,window.regress);
		tstring=tstring.replace(/@version/g,window.et_version);
		tstring=tstring.replace("@domain",'http://'+window.domain);
		tstring=tstring.replace(/@sid/g,window.sid);
		tstring=tstring.replace(/@s_username/g,window.s_username);

		return tstring;
	}

	function ET_crossword_check(cw_pars) {

		cw_array=(cw_pars+"||||").split("|");
		cwid=cw_array[0];
		//lert("function ET_crossword_check() checking crossword "+cwid);

		var crossword_table = document.getElementById(cwid);
		var crossword_inputs = crossword_table.getElementsByTagName("input");

		total_inputs=crossword_inputs.length;
		total_correct=0;
		
		answers=$('#'+cwid+'_answers').val();
		//lert("Correct answers for CW "+cwid+" are: "+answers);

		for (var cwi = 0; cwi < total_inputs; cwi++) {
			elem=crossword_inputs[cwi];
			entered_letter=elem.value;
			correct_letter=answers.substr(cwi,1);
			if (entered_letter.toLowerCase()==correct_letter.toLowerCase()) {total_correct++;} else {
				if(entered_letter!='') {
					//lert(entered_letter+" should have been "+correct_letter);
				}
			}
		}
		percent=Math.round((total_correct*100)/total_inputs);
		$("#crossword_"+cwid+"_result").val("Your score: "+percent+" % ");
		ET_error("You scored "+percent+" % ");
		return false;
	}

	function ET_domain(the_url) {
		return the_url.match(/:\/\/(.[^/]+)/)[1];
	}

	function ET_autoscroll(scroll_string) {

	//	New function to gradually scroll a div to show text
	//	Nudge it by a percentage from it's current position to allow manual + auto scrolling to coexist

	//	If the auto_scroll runs too quickly - You can change the total time setting on the page calling this function
	//	but it's probably because this page is moving the bar too far !! 

	//	video_text=new Object();	// To control the horizontal scroll bar for the video text
	//	video_text.starttime='';
	//	video_text.totaltime='';
	//	video_text.div='';
	//	video_text.intervalMS='';

	//lert("function ET_autoscroll() start "+scroll_string);

	scroll_defn=(scroll_string+"|||||||||").split("|");
	video_text.div=scroll_defn[0];
	video_text.totaltime=(scroll_defn[1]*1000);	// The total run time is in seconds - We change it to millisecs
	video_text.intervalMS=(scroll_defn[2]);		// The interval time is already in millisecs to keep it nice and smooth :) We hope
	video_text.intervalID='';

	now=new Date();
	video_text.starttime=now;
	nudge_interval=video_text.intervalMS;

	one_nudge_percentage=(video_text.intervalMS/video_text.totaltime)*100;

	//	one nudge will move the vertical scroll by this percentage of the difference
	//	between the height of the scroll content and the height of the scroll pane

	// ET_error("ET_autoscroll() div:"+video_text.div+" TOT: "+(video_text.totaltime/1000)+" secs. NUDGE: "+(video_text.intervalMS));
	video_text.intervalID=setInterval("ET_autoscroll_nudge('')",nudge_interval);
	//lert("function ET_autoscroll() completed "+scroll_string);

	}

	function ET_autoscroll_nudge() {

		// use the current video_text Object
		// NEED to subtract the div height from the calculation otherwise we are moving from the top to the VERY bottom.

		milli_seconds=now-(video_text.starttime);
		curpos=$("#"+video_text.div).attr("scrollTop");
		time_part=((video_text.intervalMS*100)/video_text.totaltime);
		shove_distance=( (time_part* $("#"+video_text.div).attr("scrollHeight") )/100);
		newpos=curpos+shove_distance;
		$("#"+video_text.div).attr({ scrollTop: newpos });
		return;
	}

	function ET_too_busy() {
		// L A T E R - we could display some advice here about closing tabs etc., or rebooting ha ha
		return;
	}

	function ET_reset() {
		// Clear up various var etc., and intervals.
		// Stop any scripts that no longer need to complete
		// T H I S  could re-activate buttons or scripts which were disabled while a process was running
		window.busy=false;
		$('.error_message').html("");
		ET_stop_Int();
	}

	function ET_postscript(ps_toggle,ps_marker,ps_function) {
		//lert("function ET_postscript() STARTS ");
		if (window.count>10) {
			// Time to give up
			window.count=0;
			ET_stop_Int();
		} else {
			toggle_contents=$("#"+ps_toggle).html();
			if (toggle_contents.indexOf(ps_marker)>=0) {
				// It's done! so we can run that script now, can't we?
				//lert("function ET_postscript() marker found in " + toggle_contents+" so ready for function ");
				result=ps_function();
			} else {
				window.count++;
			}
		}
		//lert("function ET_postscript() complete ");
	}

	function ET_Show_English(lp) {

		if(window.profile_ready==false) {return;}
		//lert("function ET_Show_English('') STARTING  ");

		$('.lang').hide();
		$('.en').show();

		if (window.guest==true) {
			$('.guest').show();
			$('.member').hide();
		} else {
			$('.member').show();
			$('.guest').hide();

		}
		$('.lang1').removeClass('tiny').addClass('icon');
		$('.lang2').removeClass('icon').addClass('tiny');

		//lert("function ET_Show_English('') complete  guest:"+window.guest);	

		window.translating=false;
		return;
	}

	function ET_Show_Translations() {

		//lert("function ET_Show_Translations() started ");
		$('.translate').show();

		//	language is other than English so:
		//	Show all the translations for the other language 
		//	hide the engish equivalents of each	

		$('.lang2').removeClass('tiny').addClass('icon');
		$('.lang1').removeClass('icon').addClass('tiny');

		translations=$('.' + window.lang);
		tn_count=translations.length;
		change_count=0;

		//lert("There are " + tn_count + " translations into " + window.lang);

		for (tn=0; tn<tn_count; tn++) {
			this_id=translations[tn].id;display=0;
			if (window.guest==true) {
				if (jscss('check',translations[tn],'member','')) {display=0;} else {display=1;}
			} else {
				// This DIV is for members
				if (jscss('check',translations[tn],'guest','')) {display=0;} else {display=1;}
			}

			if (display==1) {
				id_stem=this_id.substr(0,this_id.length-2);
				lang_part=this_id.substr(this_id.length-2);
				//lert("this language id : " + this_id + "STEM:" + id_stem + " Language part = " + lang_part);
				id_lang2a=id_stem+lang_part;
				//lert("First part = " + id_array[0]);
				english_id=id_stem+"en";
				foreign_id=id_stem+window.lang;

				//lert("Hiding " + other_id);
				$('#'+english_id).hide();
				$('#'+foreign_id).show();
				change_count++;
			}
		}
		window.translating=true;
		//lert("ET_Show_Translations() COMPLETE ");
		return;

	}

	function ET_toggle_edit(epars) {
		// To come soon
		//lert("Not ready yet - please wait for this development ");
		return;
	}

	function ET_set_links() {
		//	prefix all class=regress hrefs with the regress 

		$("a.homepage_link").attr("href",regress+"index.html");

		//	C-L-A-M links

		$("a.chat_link").attr("href","/chat/live/index.html");
		$("a.library_link").attr("href","/library/index.html");
		$("a.admin_link").attr("href","/admin/index.html");
		$("a.moodle_link").attr("href","/moodle/index.php");
		$("a.url").attr("href",window.live_page);
		$("a.url").html(window.live_page);
		$("a.refresh").attr("href",window.url);

		//lert("function ET_set_links() complete ");
	}

	function ET_answers_toggle(tp) {
		if(window.answers==true) {
			ET_hide_answers();
			window.answers=false;
		} else {
			ET_show_answers();
			window.answers=true;
		}
	}

	function ET_hide_answers() {
		// $('.article').hide();$('.redmark').hide();$('.gap').show();
		// $('.answer').className=(item.className=='nosee')?'seeme':'nosee';
		//lert("function ET_hide_answers() START ");
		$('div.gap').removeClass('nosee');
		$('.answer').addClass('nosee');
		$('.explain').addClass('nosee');
		//lert("function ET_hide_answers() COMPLETE ");
		return;
	}

	function ET_show_answers() {
		// F O R     L I B R A R Y     B O O K S 
		// $('.article').show();$('.redmark').show();$('.gap').hide();
		// $('.answer').className=(item.className=='nosee')?'seeme':'nosee';
		$('.answer').removeClass('nosee');
		$('.explain').removeClass('nosee');
		$('div.gap').addClass('nosee');
		//lert("function ET_show_answers() ");
		/* Need to make it inline style */
		return;
	}

	function sort_sentence(sopts) {
		//lert("function sort_sentence() STARTED ");
		// sopt_array=(sopts+"|||").split("|");
		// target_input=sopt_array[0];
		sentence=$('#sentence_unmixed').val();
		$('#sentence_normal').html(sentence);

		sarray=new Array;
		sarray=sentence.split(" ");
		alphabetical=sarray.sort();
		newstring="";
		for (i=0;(i<alphabetical.length);i++) {
			newstring+=alphabetical[i]+" ";}
		newstring=newstring.toLowerCase();
		newstring=newstring.replace(/\./g,"");
		newstring=newstring.replace(/\?/g,"");
		newstring=newstring.replace(/\,/g,"");
		//lert("Leon sentence "+sentence + " >>> " + newstring);
		$('#sentence_mixed').html(newstring);
		//lert("function sort_sentence() COMPLETED ");
		return false;
	}

	//	external pages CLICKing stuff - Shuffle text around until it's all in the right place.

	function ET_div_click(click_dets) {

		//lert("function ET_div_clicks() - STARTED "+click_dets);
		click_array=(click_dets+"|||").split("|");
		switch(click_array[0]) {
		case("set"):
			//lert("set");
			div_class=click_array[1];
			div_count=parseInt(click_array[2]);
			window.highlight=div_class+"1";		// div id class+'1' must exist in this page. 
			$('.'+div_class).addClass('shuffle_on');	

			for(div_seq=1; (div_seq<div_count); div_seq++) {
				// .removeClass('flag')
				$('#'+div_class+div_seq).click(function () {ET_div_click('here'); });
			}
			//lert("function ET_div_clicks() - div class: "+div_class+" will be shuffled onclick ");
			break;
		default:
			//	Normal div shuffle click. If contents contain text other than:
			//	UNDERSCORES and SPACES then mark this id
			//	else post the current marked DIV contents here
			//	and empty the current div setting this as the new current div EG SHUFFLE IT!!	
				// contents=$('#'+	
			//lert("function ET_div_clicks() - div class: "+div_class+" normal click action ID: ");
			break;
		}
	}

	function englishtap(et_params) 	{

		//	T h I S 	I S	T h e	E N G L I S H 	T A P 	SETUP	S C R I P T

		// Start of StatCounter Code for Default Guide ( W H A T   shall we do with it?)
		// <script type="text/javascript">var sc_project=2761821;var sc_invisible=1;var sc_security="624e5474";</script>
		// <script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script>

		et_settings=(et_params+"|||||||||").split("|");
		et_data=et_settings[0];

		//lert("function englishtap() SITE SETUP starting ");

		url= ("" + this.location).replace(/\\/,"/"); 
		window.url=("" + this.location).replace(/\\/,"/");
		the_url=window.url;
		window.domain=ET_domain(the_url);

		//lert("domain set to : "+window.domain+" in version "+window.et_version);

		urlstart=window.url.substr(0,3);
		if (url.indexOf('?')>=0) {
			window.urlmain = url.substring(0,url.indexOf('?'));
			window.urldata = url.substring((url.indexOf('?')) + 1);
		} else {
			window.urlmain=url;
			window.urldata="";
		}

		if(urlstart==("htt") || (urlstart=='www') ) {window.live=true;} else {window.live=false;}

		url_array=url.split("/");

		last_slash=url.lastIndexOf("/");
		window.fullpath=url.substr(0,last_slash+1);

		found_label=0;
		page_level=0;
		page_path='';

		et_pos=url.indexOf(window.pathlabel);
		et_url=url.substr(et_pos);
		page_path=et_url.substr(et_url.indexOf('/')+1);
		if (page_path.indexOf('?')>=0) {page_path = page_path.substring(0,page_path.indexOf('?'));} 

		dir_level=et_url.count("/")-1;

		window.folder=page_path.substr(0,page_path.lastIndexOf("/"));
		window.live_page=window.domain+'/'+page_path;
		//lert("window.live_page:"+window.live_page);
	
		// The old regress is STRANGE but window.regress seems to be the same thing.
		regress=""; 
		for(i=0; (i<dir_level); i++) {regress+="../";}

		if ((dir_level==0) && (page_path=="index.html/")) { window.live_page=window.domain;}

		//	R E B U I L D   K E Y W O R D S   T A B L E
		//	R E S E T   H E A D E R    and 	F O O T E R 
		//lert("function englishtap() HAS COMPLETE the javascript initialisation !!  regress:"+window.regress);

		if (navigator.appName == 'Netscape') {
			var visitor_language = navigator.language; } else {
			var visitor_language = navigator.browserLanguage;
		}

		window.lang=visitor_language.substr(0,2);
		url_lang=url_fld("lang=");
		if (url_lang!='') {window.lang=url_lang;}
		//lert("URL language set to " + url_lang);
		if (window.lang=="cn") {window.lang="zh";}
		$("#lang2").attr("src",regress+"media_library/images/flags/flag"+window.lang+".jpg");

		//	Show first in English

		ET_Show_English('');
		if(window.lang!='en') {
			$(".translate").show();
			image='/media_library/images/flags/flag'+window.lang+".jpg";
			$(".lang2").attr("src",image);
		}
		ET_set_links();		//	set the hrefs for certain defined classes of anchor 

		$(".version").html(window.et_version);

		if(url_fld("debug")=='') {window.debug=false;} else {window.debug=true;}

		//lert("function englishtap() completed setup ");

		return true;
	}

	function ET_replace(replace_string) {

		rep_array=(replace_string+"||||").split("|");
		rep_div=rep_array[0];
		rep_token=rep_array[1];
		rep_real=rep_array[2];

		var myDIVs = getElmsByClassName(rep_div,null,null)
		elm_count=myDIVs.length;

		for (elm=0; elm<(elm_count); elm++) {
			paragraph_text=myDIVs[elm].innerHTML;
			paragraph_text=paragraph_text.replace(rep_token,rep_real);
			myDIVs[elm].innerHTML=paragraph_text;
		}
		return;
	}

	function ET_symbols(div_class) {

		// Replaces certain tokens shortcuts with html code

		//lert("function ET_symbols replacing tokens in div class = " + div_class);

		var myDIVs = getElmsByClassName(div_class,null,null)
		elm_count=myDIVs.length;

		phone_template='<img class="phonetics" src="/library/pronunciation/images/phones_gif/@word.gif" alt="@word" />';

		for (elm=0; elm<(elm_count); elm++) {
			paragraph_text=myDIVs[elm].innerHTML;

			html=phone_template.replace(/@word/g,'bag');paragraph_text=paragraph_text.replace(/@bag/g,html);
			html=phone_template.replace(/@word/g,'boot');paragraph_text=paragraph_text.replace(/@boot/g,html);

			html=phone_template.replace(/@word/g,'cat');paragraph_text=paragraph_text.replace(/@cat/g,html);
			html=phone_template.replace(/@word/g,'clock');paragraph_text=paragraph_text.replace(/@clock/g,html);
			html=phone_template.replace(/@word/g,'computer');paragraph_text=paragraph_text.replace(/@computer/g,html);

			html=phone_template.replace(/@word/g,'fish');paragraph_text=paragraph_text.replace(/@fish/g,html);

			html=phone_template.replace(/@word/g,'house');paragraph_text=paragraph_text.replace(/@house/g,html);
			html=phone_template.replace(/@word/g,'nose');paragraph_text=paragraph_text.replace(/@nose/g,html);

			html=phone_template.replace(/@word/g,'shower');paragraph_text=paragraph_text.replace(/@shower/g,html);

			html=phone_template.replace(/@word/g,'tree');paragraph_text=paragraph_text.replace(/@tree/g,html);

			html=phone_template.replace(/@word/g,'vase');paragraph_text=paragraph_text.replace(/@vase/g,html);
			html=phone_template.replace(/@word/g,'yacht');paragraph_text=paragraph_text.replace(/@yacht/g,html);
			html=phone_template.replace(/@word/g,'zebra');paragraph_text=paragraph_text.replace(/@zebra/g,html);

			myDIVs[elm].innerHTML=paragraph_text;
		}

		//lert("Changed add class " + div_class+ " phonetics ");
		return;
	}


	function multisort(a,b) {

		var x = a[sortdef.element];
		var y = b[sortdef.element];

		switch(sortdef.order) {
		case ("dr"):
			return y-x;
			break;

		case ("ar"):
			return (x-y);			
			break;

		case ("dl"):
			return ((x < y) ? 1 : ((x > y) ? -1 : 0));
			break;

		default:
			// 'al' default = ascending left justified - Alphabetical
			return ((x < y) ? -1 : ((x > y) ? 1 : 0));
			break;
		}
	}

// REDUNDANT 
//	function sortfld0(a,b) {return ((a[0] < b[0]) ? -1 : ((a[0] > b[0]) ? 1 : 0));}
//	function sortfld1(a,b) {return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 1));}
//	function sortfld2(a,b) {return ((a[2] < b[2]) ? -1 : ((a[2] > b[2]) ? 1 : 1));}
//	function sortfld3(a,b) {return ((a[3] < b[3]) ? -1 : ((a[3] > b[3]) ? 1 : 1));}
//	function sortfld4(a,b) {return ((a[4] < b[4]) ? -1 : ((a[4] > b[4]) ? 1 : 1));}


	function setActive(show_id) {

		//	This is used to load hidden content that is already in this page 
		//	Only one toggle class can be visible at any one time here 
		//lert("Page '" + window.urlmain + "' Function setActive() making " + show_id + " active.  Current active = " + window.active_page);

		ET_reset();
		$("#report_data").hide();
		$("#toggle_external").hide();
		$(".error_message").html("");

		$('.toggle').hide();
		if ($('#'+show_id).hasClass('tab_content')==true) {$('.tab_content').hide();}

		$('#'+show_id).show();

			// In this version we first need to look at the menu to see what to do with this page 

		window.active_page=show_id;

			//evlert("function englishtap.js setACtive() COMPLETE - now showing " + window.urlmain + "?toggle=" + show_id);
		return;
	}

	function ET_url_page(show_string) {

		show_array=(show_string+"|||").split("|");
		show_name=show_array[0];
		show_type=show_array[1];

		//lert("function ET_url_page STARTING ");

		ET_reset();

		// Check the URL for any internal or external pages to show  >> setActive() OR get_page() 
		show_what=url_fld("show");
		active_toggle=url_fld("toggle");

		if (show_what!="") {ET_show_it(show_what);return;}

		if (active_toggle=="") {
		
			// No active internal toggle page so check for external page load 

			active_page=url_fld("page");
			//lert("Active page : "+active_page);

			if (active_page=='') {
				active_video=url_fld("video");
				if (active_video=='') {
					if(show_name=='') {
						// No active internal toggle page so check for external page load 
						$(".error_message").html("No default page content has been loaded yet. !!!");
						return false;
					} else {
						// Set the default toggle active according to TYPE  
						switch(show_type) {
						case("toggle"):
							setActive(show_name);
							break;
						case("page"):
							//lert("Default >> "+show_name);
							ET_load_html(show_name+"|toggle_external|default page");
							break;
						case("video"):
							//lert("Default >> "+show_name);
							ET_play_video(show_name);
							break;

						default:
							break;
						}
					}
				} else {
					//lert("There is a video " + active_video + "in the url so lets play itplaying active video");
					ET_play_video(active_video);
					// Load active video 
				}
			} else {
				// Load the active_page 
				//lert("loading HTML page from the URL "+active_page+" URL : "+window.urldata);
				purl=window.folder+"/"+active_page;
				ET_load_html(purl+"|toggle_external|"+active_page);
			}
		} else {
			//	Set the active toggle =INTERNAL 
			setActive(active_toggle);
		}

		//lert("function ET_url_page COMPLETE  "+show_name+" type: "+show_type);

		return;
	}

	function ET_show_it(sw) {

		show_array=(sw+"|||").split("|");
		show_command=show_array[0].toLowerCase();

		switch(show_command) {

		case('calendar'):AD_event_list('');break;
		case('event'):AD_event_list('');break;

		case('time'):AD_timezones('');break;

		default:break;
		}

		//lert("function ET_show_it() "+show_command);

		return;
	}

	function ET_error(emsg) {

		m_array=(emsg+"|||").split("|");
		emsg=m_array[0];
		m_div=m_array[1];

		popit=(m_array[2]!='');

		if (popit==true) {
			$('#toggle_external').html('<div class="warning">'+emsg+'</div>');
			setActive('toggle_external');
		} else {
			if (m_div=='') {m_div="error_message";} 
			$("."+m_div).show();
			$("."+m_div).html(emsg);
		}

		return;
	}

	function ET_div_fill(dstr) {
		d_array=(dstr+"|||").split("|");
		dhtml=d_array[0];did=d_array[1];daction=d_array[2];
		if (did=='') {did="error_message";} 
		$("#"+did).show();
		switch(daction) {
			case('+'):$("#"+did).append('<br />'+dhtml);break;
			default:$("#"+did).html(dhtml);break;
		}
		return;
	}

	function ET_help(keyword) {

		// Now a case statement BUT to go into a file with a php help script to come later. (Even admin help edit + multi-language!!)

		switch(keyword) {
		case('event_students'):
			message_text="You can enter a single student user id here if this event is a one-to-one ";
			message_text+=" or leave it blank if you are entering a group event ";
			message_text+=" Hover your mouse over their name in moodle or in the chat to see their id. ";
			break;
		case("event_type"):
			message_text="The calendar <b>event type</b> determines who can view this event and what this event is.";
			message_text+=" Conference events may be seen by anybody. Your availability can only be seen by your students and admin. ";
			break;
		default:
			message_text="No help for "+keyword;
			break;
		}
		$('.help_message').html(message_text);
		return;
	}

	function url_fld(search_data) {

			// Format =  'label | url format data string '  eg user|?user=me > 'me'

		search_data=search_data+'||||';
		search_array=search_data.split("|");

		search_label=search_array[0];
		search_text=search_array[1].replace(/\&amp\;/g,"&");;

		if (search_text=='') {search_text=window.urldata;}
		search_text = '&'+search_text.substring((search_text.indexOf('?')) + 1);

			//lert("function() url_fld() looking for "+search_label+" in "+search_text);

		if(search_label.indexOf("=")==-1) {search_label=search_label+"="};
		if(search_label.substring(0)!='&') {search_label='&'+search_label};

		lab_pos=search_text.indexOf(search_label);

		if (lab_pos>=0)	{
			fld_value = search_text.substring((search_text.indexOf(search_label)) + search_label.length);
			atpos=fld_value.indexOf('&');

			if (atpos==0){
				fld_value="";
			} else 	{
				if (atpos>0) {
					fld_value=fld_value.substring(0,fld_value.indexOf('&'));
				}
			}
		} else 	{
	        	fld_value = "";
			// Not found in the urldata
	        }

		if(fld_value.indexOf("#")!=-1) {
			fld_value=fld_value.substring(0,fld_value.indexOf('#'));
		}

			//lert("function() url_fld() with label " + search_label + " has extracted " + fld_value  + " from " + search_text);
		return fld_value;
	}

	function isDST() {

		// Test for DST on the users browser - Note: sometimes we need to know whether it's dst in london from China

		// will return 0 if DST is not observed or if the DST is not in effect 
		// and 1 if the DST is in effect.
		// Useful with other scripts where you are doing calculations to determine time offsets
		// from UTC (or GMT) time. 

		var d=new Date();
		var dY=d.getFullYear();
		var d1=new Date(dY,0,1,0,0,0,0); 
		var d2=new Date(dY,6,1,0,0,0,0);
		var d1a=new Date((d1.toUTCString()).replace(" GMT",""));
		var d2a=new Date((d2.toUTCString()).replace(" GMT",""));
		var o1=(d1-d1a)/3600000;
		var o2=(d2-d2a)/3600000;
		var rV=0;
		if (o1!=o2) {
	   		d.setHours(0);d.setMinutes(0);d.setSeconds(0);d.setMilliseconds(0);
			var da=new Date((d.toUTCString()).replace(" GMT",""));
			o3=(d-da)/3600000;		
			rV=(o3==o1)?0:1;
		}
		return rV;	
	}


	// VIDEO AND MEDIA FUNCTIONS 
	function ET_play_sound(sound_dets) {
		// Set the sound player toggle active and mark it up properly
		//lert("function ET_play_sound() started"); 
		setActive('sound_player');
		sound_array=(sound_dets+"|||").split("|");
		sound_file=sound_array[0];
		sound_file=ET_tokens(sound_file);
		//lert("function ET_play_sound() about to play "+sound_file); 
		sound_title=sound_array[1];
		play_script="javascript:soundManager.play('"+sound_file+"','"+window.regress+sound_file+"');";
		//lert(play_script);
		$("#sound_play_icon").attr("onclick",play_script);
		//lert("function ET_play_sound() complete for sound : "+sound_file);
		return;
	}

	function ET_play_video(video_pars) {

		// Sometimes just show the video player alongside the currently visible toggle.
		// NOTE : The video MUST be in media_library/videos/x

		video_defn=(video_pars+"||||").split("|");
		video_file=video_defn[0];
		video_file=ET_tokens(video_file);

		play_id_prefix=video_defn[1];	// Default page player is 'video'
		if(video_defn[1]=='') {
			clear_toggle=true;
			setActive('video_player');
		} else {
			clear_toggle=false;
			$("#video_player").show();
		}

		//	I F 	No full pathname in the video file name THEN use the media_library videos

		$("#video_href").attr("href",video_file);
		$f("video_href","/flowplayer/flowplayer-3.1.5.swf", {
		clip: { autoPlay:false }
		});

		document.getElementById("page_url").innerHTML=window.live_page + "?video="+video_url + "&amp;lang="+window.lang;
		document.getElementById("page_url").href=window.live_page + "?video="+video_url + "&amp;lang="+window.lang;
		//$('#send_link').html(urlmain+'?toggle='+video_file);

	}

// ===================================================================
// Date formating script
// ===================================================================
// HISTORY
// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

// I had this set  =0 even though my time zone was GMT+1
// maybe because the times are stored in GMT without a difference.

function LZ(x) {return(x<0||x>9?"":"0")+x}


function isDate(val,format) {
	// ------------------------------------------------------------------
	// isDate ( date_string, format_string )
	// Returns true if date string matches format of format string and
	// is a valid date. Else returns false.
	// It is recommended that you trim whitespace around the value before
	// passing it to this function, as whitespace is NOT ignored!
	// ------------------------------------------------------------------
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

function compareDates(date1,dateformat1,date2,dateformat2) {

	// -------------------------------------------------------------
	// compareDates(date1,date1format,date2,date2format)
	//   Compare two date strings to see which is greater.
	//   Returns:
	//   1 if date1 is greater than date2
	//   0 if date2 is greater than date1 of if they are the same
	//  -1 if either of the dates is in an invalid format
	// -------------------------------------------------------------

	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

function formatDate(date,format) {

	//lert("function formatDate(); START ");

	/*
		formatDate (date_object, format)
		Returns a date_string in the output format specified.
		The format string uses the same abbreviations as in getDateFromFormat()
		WARNING - Unspecified H returns 12:00
	*/

	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();  
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions

	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);

	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);

	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);

	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="pm"; }
	else { value["a"]="am"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);

	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}

	//lert("function formatDate() COMPLETE ");
	return result;
	}
	
	// ------------------------------------------------------------------
	// Utility functions for parsing in getDateFromFormat()
	// ------------------------------------------------------------------
	function _isInteger(val) {
		var digits="1234567890";
		for (var i=0; i < val.length; i++) {
			if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
		return true;
	}


	function _getInt(str,i,minlength,maxlength) {
		for (var x=maxlength; x>=minlength; x--) {
			var token=str.substring(i,i+x);
			if (token.length < minlength) { return null; }
			if (_isInteger(token)) { return token; }
		}
		return null;
	}
	
function getDateFromFormat(val,format) {

	// ------------------------------------------------------------------
	// getDateFromFormat( date_string , format_string )
	//
	// LOOKS LIKE A KIND OF ICONV() Date() FUNCTION
	// EXCEPT that the EXTERNAL DISPLAY FORMAT MUST MATCH THE PATTERN SPECIFIED
	// ALSO NOTE: 	if no time is supplied it takes the CURRENT TIME
	//		even if it's a different
	// 		date (Not today) I don't like this.
	//
	// This function takes a date string and a format string. It matches
	// If the date string matches the format string, it returns the 
	// getTime() of the date. If it does not match, it returns 0.
	// ------------------------------------------------------------------

	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;

//	Default time of date (reset only for today)
	var hh=0;
	var mm=0;
	var ss=0;
	
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
			//lert("Date token = " + token);

		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4;}
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 50) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				//lert("Year = " + year);
				}
			}

		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;
			//hh--;
			}

		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") {
	 hh-=12;
	 }

	month=Number(month);

//lert("Year = " + year + "Month = " + month + "day of month = " + date + "hh="+hh+" mm="+mm+"ss="+ss);
	var newdate=new Date(year,month-1,date,hh,mm,ss);
//lert("newdate BEFORE TODAY CHECK set to  = " + newdate);

//	IF TODAYS DATE and hh,mm,ss NOT SET USE NOW!!!
	if(newdate.getFullYear()==now.getFullYear()){
		if(newdate.getDate()==now.getDate()){
			if (newdate.getDay()==now.getDay()){
//lert("Same date !!!");
				if ((ss==0) && (mm==0) && (hh==0)){
//lert("Seconds set to current time");
					// USE CURRENT TIME ONLY FOR TODAY's DATE WHEN TIME HASN'T BEEN SET
					var hh=now.getHours();
					var mm=now.getMinutes();
					var ss=now.getSeconds();
					var newdate=new Date(year,month-1,date,hh,mm,ss);
				}
			}
		}
	}

//lert("newdate AFTER TODAY CHECK set to  = " + newdate);

//lert(" hh= " + hh + " mm=" + mm + " ss = " + ss + " nowyear " + now.getFullYear() + " newdateyear " + newdate.getFullYear());
//lert("Compare : " + Math.round((newdate.getTime()/86400000)+0.49) + " " + Math.round((now.getTime()/86400000)+0.49) + "<BR>First=" + newdate + "<BR>Second=" + now );

	ret_val = new Date();
	ret_val = newdate

//lert("Returning date from getDateFromFormat() as " + ret_val);
	return ret_val;

//	return newdate;

	}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------

function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
	monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			d=getDateFromFormat(val,l[j]);
			if (d!=0) { return new Date(d); }
			}
		}
	return null;
	}


	function addclock(clock_time,date_obj) {

		//	addclock(clock_time,date_obj)
		//	Returns a new date object after adding the clock time to the date_obj provided	
		//	EXTRACT THE TOTAL seconds from the O'clock time	

		newdate=new Date();
		newdate.setTime(date_obj.valueOf());
	
		clock_hours=clock_time.substr(0,clock_time.indexOf(":"));
		clock_minutes=clock_time.substr(clock_time.indexOf(":")+1,2);

		newdate.setMilliseconds((clock_hours*1000*60*60)+(clock_minutes*1000*60));

		return newdate;

	}

	/*	timezone(date_obj)
		Returns a new date object being this time adjusted to the viewers timezone
		NOTE: There are some GLOBAL time variables 
		Args: date_obj ANY DATE OBJECT
		window.gmt_diff any offset from GMT in hours */

function timezone(date_obj) {

//	BEWARE TIME ZONES ARE OFFSET BY MINUTES ASWELL AS HOURS
//	(set hdiff=HOURS mdiff=MINS)

	m_diff=(window.gmt_diff % 1);
	h_diff=(window.gmt_diff-m_diff);
	m_diff=(m_diff*60);

//lert("Your timezone difference from GMT is " + h_diff + " hours and " + m_diff + " minutes ");

	newdate=new Date();
	newdate.setTime(date_obj.valueOf());

	newdate.setMilliseconds((h_diff*60*60*1000)+(m_diff*60*1000));

//lert("timezone() is returning yourdate_obj as : " + yourdate_obj);

	return newdate;

}

function world_date(dval){

	// Date format for dates passed INTO this function
	in_format="MMM dd yyyy kk:mm";
	
	// Date format to display must show the day of the week
	out_format="E NNN dd yyyy kk:mm";

	lesson_start=getDateFromFormat(dval,in_format);

	vdate=timezone(lesson_start);
	viewer_time=formatDate(vdate,out_format);

	//lert("in date = " + dval + " Viewer time = " + viewer_time);

	return viewer_time;
}

function lookup(lookup_options) {

	/* Change all <div class="lookup"> to a dictionary link */

/*	engdict='<a href="http://dictionary.cambridge.org/search/british/?q=@word&amp;x=0&y=0">@word</a>';
	var myDIVs = getElmsByClassName("lookup",null,null)
	elm_count=myDIVs.length;
	for (elm=0; elm<(elm_count); elm++) {
		lookup_word=myDIVs[elm].innerHTML;
		reference=engdict.replace(/@word/g,lookup_word);
		myDIVs[elm].innerHTML=reference;
	}

*/
	return;

}


	function SS_daily_slide(r_opts,selection_list) {

		/*	This function should always return a list item based on the current date DAY
			If the same ilst is used each day , the returned item will change each day.
	
			Set up Data for data grid
			var now=new Date();
			format="MMM dd";
			date_key=formatDate(now,format);	*/

		//lert("Setting up word of the day ");

		/*
		list_size=selection_list.length;
		recordset=new Array();i=-1;
		var now=new Date();
		udate=formatDate(now,"yyMMdd");
		numb_date=Number(udate);
		date_key=(numb_date%list_size);
		return selection_list[date_key];
		*/
	}

	function SS_flip_image(image_number,img_id) {

		// WAS used in guess who games etc., to hide/show images

		cur_image=document[img_id].src;
		//lert("recordset" + recordset);
		//lert("Flipping image number " + image_number);
		//lert("Current image id : " + img_id);
		//lert("Current image is : " + cur_image);
		//lert("Flipping image number " + image_number + " ID:" + img_id + " " + cur_image);

		if(cur_image.indexOf("blank")==-1) {
			document.getElementById(img_id).src=window.regress + 'media_library/images/buttons/blank.gif';}
		else {
			word_rec=recordset[image_number];
			this_image=get_image(word_rec);
			//lert("GET IMAGE number: " + image_number + " RETURNED " + this_image);
	//LEON
			document.getElementById(img_id).src=this_image;
		}
	}


	function new_slide() {

		//lert("create new word slide");
		var Slide=new Array(maxfld);
		for (ino=0; (ino<50); ino++) {
			Slide[ino]='';
		}	
		return Slide;
	}

	/*	FUNCTION phonetics - Make a string of phonetic symbols from	*/
	function string_to_slug(str) {

		str = str.replace(/^\s+|\s+$/g, ''); // trim
  
		// remove accents, swap ñ for n, etc
		var from = "ÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛàáäâèéëêìíïîòóöôùúüûÑñÇç·/_,:;";
		var to   = "AAAAEEEEIIIIOOOOUUUUaaaaeeeeiiiioooouuuunncc------";

		for (var i=0, l=from.length ; i<l ; i++) {
			str = str.replace(new RegExp(from[i], "g"), to[i]);
		}

		str = str.replace(/[^a-zA-Z0-9 -]/g, '') // remove invalid chars
		//.replace(/\s+/g, '-') // collapse whitespace and replace by -
		//.toLowerCase();

		return str;
	}

	String.prototype.count = function(match) {
		var res = this.match(new RegExp(match,"g"));
		if (res==null) { return 0; }
		return res.length;
	}

	//	To find the index/position of an element in an array, you can call
	//	YourArray.findIndex(”Services”); or YourArry.findIndexByCol("label",column);

	//pads left
	String.prototype.lpad = function(padString, length) {
		var str = this;
		while (str.length < length)
		str = padString + str;
		return str;
	}
 
	//pads right
	String.prototype.rpad = function(padString, length) {
		var str = this;
		while (str.length < length)
	        str = str + padString;
		return str;
	}

	//trimming space from both side of the string
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
 
	function ET_trim(str) {return str.replace(/^\s+|\s+$/g,"");}

	//trimming space from left side of the string
	String.prototype.ltrim = function() {
		return this.replace(/^\s+/,"");
	}
 
	//trimming space from right side of the string
	String.prototype.rtrim = function() {
		return this.replace(/\s+$/,"");
	}


	Array.prototype.findIndex = function(value){
		var ctr = "";
		for (var i=0; i < this.length; i++) {
			// use === to check for Matches. ie., identical (===), ;
			if (this[i] == value) {
				return i;
			}
		}
		return ctr;
	};

	//	Locate a value in a specified column of a multidimensional array
	Array.prototype.findIndexByCol = function(value,cIdx) {

	var ctr = "";

	//lert("findIndexByCol value="+value+" looking in column " + cIdx + " all " + this.length + " columns");

	for (var i=0; i < this.length; i++) {
		// use === to check for Matches. ie., identical (===), ;
		//lert("First value = " + this[i][cIdx]);
		if (this[i][cIdx] == value) {
			//lert("FOUND " + this[i][cIdx]+"===="+value);
			return i;
		} else {
			//lert("Comparing  our  value :  " + value + " !=  to array value : [" + cIdx + "] " + this[i][cIdx]);
		}
	}
	//lert=("No value found");
	return ctr;
	};


	//	Locate a sub-value in a specified column of a multidimensional array
	Array.prototype.findstringInCol = function(value,cIdx) {

	var ctr = "";

	//lert("findstringInCol value="+value+" looking in column " + cIdx + " all " + this.length + " columns");

	for (var i=0; i < this.length; i++) {
		// use === to check for Matches. ie., identical (===), ;
		//lert("First value = " + this[i][cIdx]);
		//if (this[i][cIdx] == value) {

		if (this[i][cIdx].indexOf(value)!=(-1)) {

			//lert("FOUND " + this[i][cIdx]+"===="+value);
			return i;
		} else {
			//lert("Comparing  our  value :  " + value + " !=  to array value : [" + cIdx + "] " + this[i][cIdx]);
		}
	}
	//lert=("No value found");
	return ctr;
	};

	function ET_setmenu() {
		numberRows('main_menu',1);
		addTableRolloverEffect('main_menu','tableRollOverEffect1','tableRowClickEffect1');
		return;
	}

	function menu_matches() {

		OLmenu_id="main_menu";
		reset_menu(OLmenu_id);

		// This displays only the menu items which match the user selection

		// Nov 15th 2011 - Script appeared to fail but there was a list item LI without an anchor.
		// All LIs must have anchor tags (SO: Check var anchors null!!)

		// all pages use this id for the left column menu. and the search input must have id='menu_search_text'
		// this function hides all but the rows which contain the search string value 	

		searchVal = document.getElementById('menu_search_text').value.toLowerCase();

		if(searchVal=='') {return false;}
		var ol_menu = document.getElementById(OLmenu_id);
		var listitems = ol_menu.getElementsByTagName("li");

		visible_count=0;

		for (var ili = 0; ili < listitems.length; ili++) {

			// extract the first anchor tag html
			var anchors = listitems[ili].getElementsByTagName("a");
			contents=anchors[0].innerHTML.toLowerCase();

			match_found=false;
			
			if (searchVal=='') {
				// Cleared the search so reset to normal
				anchors[0].setAttribute('style', 'background-color: #ffffff');
			} else {
				if (contents.indexOf(searchVal)>=0)  {
					// Highlight this menu item
					anchors[0].setAttribute('style', 'background-color: #ffdddd');
					match_found=true;
					visible_count++;
				} else {
					// dim this menu item
					anchors[0].setAttribute('style', 'background-color: #eeeeee');
					anchors[0].setAttribute('style', 'color: #cccccc');
				}
			}
			if(match_found==false) {listitems[ili].className +='nosee';}

		}
		//lert("function menu_matches() highlighting done " + OLmenu_id);
		return false;
	}

	function reset_menu(menu_id) {

		var book_menu = document.getElementById(menu_id);
		var listitems = book_menu.getElementsByTagName("li");

		visible_count=0;

		for (var ili = 0; ili < listitems.length; ili++) {
			// First make the list item visible again if it is hidden.
			// listitems[ili].className.replace( /(?:^|\s)nosee(?!\S)/ , '' )
			listitems[ili].className='';

			var anchors = listitems[ili].getElementsByTagName("a");
			// Cleared the search so reset to normal
			anchors[0].setAttribute('style', 'background-color: #ffffff');
			anchors[0].setAttribute('style', 'color: #000000');

		}
		//lert("function reset_menu() COMPLETE ");
		return;
	}

	// L E O N ' S  D A T A B A S E  - F U N C T I O N S  	-
	//	Pages must contain divs report_data and report_load	(report_data is the correct tab DIV for the chat)

	function ET_php_load(php_string) {
		
		php_array=(php_string+"||||").split("|");

		php_script=php_array[0];
		php_script=ET_tokens(php_script);

		//lert("loading "+php_script);

		php_arguments=php_array[1];	// not working in this version

		setActive('toggle_external');
		$("#toggle_external").load(php_script,{'regress':[window.regress],
		'page':[window.folder],
		'roles':[window.roles]});

		//lert("ET_php_load complete ");

		return;

	}

	function ET_chatpeep(peep_string) {

		//lert("function ET_chatpeep() started ");

		peep_dets=(peep_string+"|||").split("|");
		peep_div=peep_dets[0];
		peep_allowed=true;
		php="/chat/live/message_history.php";
		max_select=5;

		if(peep_allowed) {
			$("#"+peep_div).load(php,{'regress':[window.regress],
			'userid':[window.userid],
			'criteria':['new'],
			'gmt_diff':[window.gmt_diff],
			'max_select':[max_select],'roles':[window.roles]});
		}
		//lert("function ET_chatpeep() Chat messages displayed ");		
	}

	function ET_upload(upload_str) {

		// Updates from the form in /admin/uploader.html

		//lert("function ET_upload() starting "+upload_str);

		ET_reset();

		upload_defn=(upload_str+"|||").split("|");
		upload_div=upload_defn[0];	

		if (upload_div=='') {
			upload_div='report_data';
		}

		// E X T R A C T 	T H E 	F O R M 	S E L E C T E D 	U P L O A D 	V A L U E S

		source_file=$('#source_file').val();
		et_book=$("#upload_book option:selected").val();
		et_book_folder="library/".et_book;

		// F O R M  validation 
		if(source_file=='') {
			ET_error("You have not selected a source file from your PC to upload");
			return false;
		}

		destination_file=$('#destination_file').val();
		
		$("#"+upload_div).load(window.php+"upload.php",{'regress': [window.regress]
		,'source_file':[source_file]
		,'et_book':[et_book]
		,'userid': [window.userid]
		,'admin': [window.admin],'roles':[window.roles]});

		//lert("function ET_upload() complete ");
		return false;
		//		, function (){ET_upload_callback("");}

	}

	function ET_upload_callback(upload_str) {
		return;
	}

	function ET_page_file_list(media_string) {
		// Get the relevant folder from the section SELECT OPTION for BOOK
		// Each book can have these sub folders:
		//	sound	images	videos

		media_array=(media_string+"||||").split("|");
		file_type=media_array[0];

		// The book pathname can be passed OR can be in the admin page form 
		book_pathname=media_array[1];

		if (book_pathname=='') {
			book_pathname=$("#upload_book option:selected").val();
		}

		param=file_type;
		param=param+"|"+book_pathname+"/"+file_type;
		param=param+"|media_view";
		//lert(param);
		ET_file_list(param);
		return;
	}
	
	function ET_file_list(file_string) {

		//lert("function ET_file_list()  params="+file_string);
		dir_array=(file_string+"||||").split("|");

		filetype=dir_array[0];
		folder=dir_array[1];
		display_div=dir_array[2];
		file_mask=dir_array[3];

		// Default folder for dir list
		if(folder=='') {folder='media_library/videos';}

		if(display_div=='') {
			display_div='report_data';
			setActive('report_data');
		}

		dir_folder='';
		access_allowed=true;
		if (window.guest==true) {access_allowed=false;}		

			// Note: the path to this folder is relative to the file_list script.
		if (access_allowed==true) {
			$('#'+display_div).html("");
			$('#'+display_div).load(window.php+"file_list.php"
			,{'folder':[folder],'filetype':[filetype],'roles':[window.roles]});
		} else {
			$('.error_message').html("Guests don't have persission to list media files ");			
		}

		//lert("Function ET_file_list() COMPLETE "+file_string);
	}

	// E N G L I S H     T A P    S L I D E S    js
	// N O T  needed fo rthe new etlw_slides data base but only to convert the js slides into the database !!


	word_fld=0;
	image_fld=1;
	context_fld=2;
	wiki_fld=3;
	sound_fld=4;
	pron_fld=5;
	href_fld=6;
	speech_fld=7;
	dict_fld=8;
	trans_fld=9;
	taboo_fld=10;
	anagram_fld=11;
	hint_fld=12;
	choice_fld=13; // choices where some may not be correct for mc
	answer_fld=14; // list of possible correct answers
	// A textual answer to a question
	correct_fld=15;
	// The correct choice from a multiple choice Q - eg 1 2 or 3 (Count from 1 not zero)
	group_fld=16;
	video_fld=17;
	maxfld=20;

	function ET_slide_select(params) {
		// produces the <FORM to select slides by keyword >> ET_slide_search() on submit
		ET_load_html('admin/slide_search.html|toggle_external|Select a language slide');
		return;
	}

	function ET_slide_search(slide_opts) {

		// Show the results of the slide selection
		// <FORM for slide search submits criteria here 

		slide_array=(slide_opts+"|||||||||||").split("|"); // Not used yet here
		slide_keyword=$('#slide_keyword').val();
		slide_word=$('#slide_word').val();
		slide_show_div=$('#slide_show_div').val();
		//lert("Slide display div = "+slide_show_div);
		setActive(slide_show_div);
		action='';

		// R A D I O    B U T T O N S 
		mc_radio=$('input[name=multiple_choice]:checked').val();
		vid_radio=$('input[name=has_video]:checked').val();
		answer_radio=$('input[name=needs_answer]:checked').val();
		true_radio=$('input[name=true_false]:checked').val();
		mp3_download=$('input[name=mp3_download]:checked').val();

		slide_show=new Array();
		slide_show[0]='';
		slide_show[1]=slide_keyword;
		slide_show[2]=action;
		slide_show[3]=mc_radio;
		slide_show[4]=vid_radio;
		slide_show[5]=answer_radio;
		slide_show[6]=true_radio;
		slide_show[7]=mp3_download;
		slide_show[8]=slide_show_div;
		slide_show[9]=slide_word;

		slide_show_string=slide_show.join("|");
		//lert("ET_slide_search() >> "+slide_show_string);
		ET_slide_show(slide_show_string);
		return false;
	}

	function ET_slide_list(slide_opts) {

		//lert("function ET_slide_list START ");
		setActive('toggle_external');
		slide_array=(slide_opts+"|||").split("|");
		keyword=slide_array[0];

		//	Load the Chat Slide presentor into the toggle_external
		$("#toggle_external").load(window.php+"slide_list.php",{'regress':[window.regress]
		,'keywords': [keyword],'roles':[window.roles]});

		//lert("function ET_slide_list COMPLETED keyword:"+keyword);
		return;
	}

	function ET_slide_show(show_string) {
		// to show one selected slide (if no slide id , select the next slide then timestamp it and display it
		//lert("function ET_slide_show started. show string >> "+show_string);

		show_array=(show_string+"||||||||||||").split("|");
		slide_id=show_array[0];
		slide_keywords=show_array[1];
		action=show_array[2];
		mc_radio=show_array[3];
		video_radio=show_array[4];
		answer_radio=show_array[5];
		truefalse=show_array[6];
		mp3_download=show_array[7];
		load_div=show_array[8];
		slide_word=show_array[9];
		navibar=show_array[10];

		if(load_div=='') {
			load_div="toggle_external";
			setActive('toggle_external');
		}

		$("#"+load_div).html(' ');

		edit_it=false;
		if(window.course_admin==true) {edit_it=true;}

		//lert("function ET_slide_show START slide id : "+slide_id+" showstring:"+show_string);

		$("#"+load_div).load(window.php+"slide_show.php",{'regress':[window.regress],'version':[window.et_version]
		,'slide': [slide_id]
		,'keywords': [slide_keywords]
		,'userid': [window.userid]
		,'navibar': [navibar]
		,'load_div': [load_div]
		,'room':[window.current_room]
		,'mc_radio': [mc_radio]
		,'video_radio': [video_radio]
		,'answer_radio': [answer_radio]
		,'true_radio': [truefalse]
		,'download_radio': [mp3_download]
		,'edit':[edit_it],'action':[action]
		,'word':[slide_word],'action':[action]
		,'roles':[window.roles]});

		//lert("function ET_slide_show COMPLETED");
		return;
	}

	function ET_slide_update() {
		//lert("Function ET_slide_update() STARTED ");

		$('#report_data').html("");
		setActive('report_data');

		slide_id=$('#slide_id').val();

		slide_word=$('#slide_word').val();
		slide_image=$('#slide_image').val();
		slide_video=$('#slide_video').val();
		slide_context=$('#slide_context').val();
		slide_keywords=$('#slide_keywords').val();
		slide_answer=$('#slide_answer').val();

		//lert("Function AD _user_update() MIDway ");

		update_page=window.php+"slide_update.php";
		$("#report_data").load(update_page,{'userid':[window.userid]
		,'id':[slide_id]
		,'word':[slide_word]
		,'image':[slide_image]
		,'video':[slide_video]
		,'context':[slide_context]
		,'keywords':[slide_keywords]
		,'answer':[slide_answer]
		,'roles':[window.roles]});

		//lert("function ET_slide_update() COMPLETE "+update_page);
		// ET_slide_select('');
		return false;
	}

	function ET_slide_submit_mc(answer_data) {

		// Function to submit a slide answer
		//lert("function ET_slide_submit_mc() ");

		answer_array=(answer_data+"||||").split("|");

		slide_id=$('#submit_mc_slide_id').val();
		slide_keywords=$('#submit_mc_slide_keywords').val();
		slide_correct=$('#submit_mc_correct').val();

		answer_text=$("#answer_text").val();
		answer_mc=$("#slide_mc_select option:selected").val();

		if (answer_mc=='0') {
			user_choice_desc="Your did not answer this question !! ";
		} else {
			user_choice="abcdefghijklm".substr(answer_mc-1,1);
			user_choice_desc="Slide : "+slide_id+" Your answer was : "+user_choice+" the correct answer is "+slide_correct;

			php=window.php+"slide_post_answer.php";
			$("#report_data").load(php, {'userid': [window.userid]
			,'teacher': [window.teacher]
			,'helper': [window.helper]
			,'slide': [slide_id]
			,'answer_text': [answer_text]
			,'answer_mc': [answer_mc]
			,'roles':[window.roles]});
		}

		// M O V E   to   N E X T  Slide with these keywords
		ET_slide_show("|"+slide_keywords);

		//lert("function ET_slide_submit() COMPLETE "+user_choice_desc);
		return false;
	}

	function ET_slide_scores(score_defn) {

		//lert("function ET_slide_scores() ");

		score_array=(score_defn+"||||").split("|");

		php=window.php+"slide_scores.php";
		$("#report_data").html("");
		setActive('report_data');
		$("#report_data").load(php, {'userid': [window.userid]
		,'teacher': [window.teacher]
		,'helper': [window.helper]
		,'roles':[window.roles]});
	}

			// E N G L I S H T A P    L I B R A R Y    js

	function get_page(page_path,toggle_div,post_name) {
		// O L D   function > NOW use ET_load_html
		// Don't rename this function as it's in the HTML of lots of pages 
		// Does the DOM Manipulation then calls ET_load_html() 
		// evlert("function get_page() started.");		

		page_string=page_path+"|"+toggle_div+"|"+post_name;
		ET_load_html(page_string);
		//lert("function get_page() completed.  window.teacher='"+window.teacher+"'");		
		return;
	}

	function ET_form_help(help_string) {
		help_array=(help_string+"|||").split("|");
		help_file_path='form_help/'+help_array[0]+".html";
		help_div=help_array[1];
		load_string=help_file_path+"|"+help_div+"||||||s";
		ET_load_html(load_string);
		//lert("function ET_form_help() loading "+load_string);
		return;
	}

	function ET_load_html(page_string) {

		//	full path name needed from domain .com/ (Eg 'chat/help/index.html'
		//	- Don't rename this function as it's in html docs everywhere!
		//	---- ---- ----

		//	TO LOAD - an external HTML page into the TOGGLE of the main page
		//	page_path = the relative path to the page.
		//	A F T E R   L O A D I N G -
		//	===========================
		//	We might need to kick things off in the page using javascript, so we ALWAYS call the callback function
		//	ET_load_callback()	which takes it's instructions from window.variable as a delimited string

		if(window.busy==true) {ET_too_busy();return;} 
		window.busy=true;

		page_defn=(ET_tokens(page_string)+"||||||||").split("|");
		page_path=page_defn[0];
		toggle_div=page_defn[1];
		if (toggle_div=='') {toggle_div="toggle_external";}

		//lert("function ET_load_html() STARTED loading into "+toggle_div);

		post_name=page_defn[2];
		window.variable=page_defn[3];
		// EG: 'video='+kickoff_video;

		security=page_defn[4];	// Will provide the means to prevent non-admins etc., fom loading pages
		uidx=page_defn[5];	// List of user ids that are allowed to load this page

		load_tab=page_defn[6];
		if(load_tab!='') {ET_settab(load_tab);}

		post_options=page_defn[7];	// contains 's' = suppress
		reset=(page_defn[8]=='');	// null here calls setActive and clears all others

		page_path=ET_tokens(page_path);
		$(".error_message").html("");

		if (ET_role_check(security)==false) {
			ET_error("You don't have permission to access this page.");
		} else {

			// Only toggle (Switch view from previous toggle) - IF this div is in that toggle class.

		if( (reset==true) && ($('#'+toggle_div).hasClass('toggle')||$('#'+toggle_div).hasClass('tab_content'))) {
			// Hide previously showing right column content and display a loading image in the toggle_external
			$('#toggle_external').html('<img src="/chat/images/wait.gif" class="picture" alt="Image" /> ');
			setActive('toggle_external');
			window.active_page=toggle_div;	// Must come after setting the wait_message active!!		
		} else {$('#'+toggle_div).show();}

			path_array=(page_path+"///").split("/");
			html=path_array[path_array.length-1];
			purl=window.domain+'/'+page_path;
			
			$("#"+toggle_div).load(window.php+"extract_html.php", {'page_path': [page_path]
			,'purl': [purl]
			,'debug': [window.debug]
			,'thisurl': [window.url]
			,'teacher': [window.teacher]
			,'helper': [window.helper]
			,'userid': [window.userid]
			,'regress': [window.regress]
			,'phone': [window.phone]
			,'mobile': [window.mobile]
			,'skype': [window.skype]
			,'security': [security]
			,'roles': [window.roles]
			,'uidx': [uidx]
			,'name': [post_name]
			,'options': [post_options]}, function (){ET_load_html_callback();});

		}

			// We want page_callbacks to be a variable function 

		//	There may be DIVs class teacher etc., here which will remain invisible unless we wait for the page to load and..
		//	ET_user_text() again !!!
		//lert("function ET_load_html() COMPLETED with site roles: "+window.roles+" userid : "+window.userid);
		return;
	}

	function ET_load(load_string) {

		//	G E N E R I C - js interface for loading a PHP file into a div

		//lert("function ET_load ("+load_string+") starting ");

		if(window.busy==true) {ET_too_busy();return;} 
		window.busy=true;

		load_string=ET_tokens(load_string);
		load_array=(load_string+"|||||||").split("|");
		load_script=load_array[0];
		load_div=load_array[1];	if(load_div=='') {load_div='toggle_external';}
		info=load_array[2];	// Can be used to pass options IDs into form scripts etc.,
		allowed_roles=load_array[3];
		window.variable=load_array[4];

			// optional tab for ET_settab()
		tab_id=load_array[5];	
		if(tab_id!='') {ET_settab(tab_id);}
		$('#'+load_div).html("");

			//	ONLY set active toggle classes


		if($('#'+load_div).hasClass('toggle')||$('#'+load_div).hasClass('tab_content')) {
//			setActive(load_div);
			$('#toggle_external').html('<img src="/chat/images/wait.gif" class="picture" alt="Image" /> ');
			setActive('toggle_external');
			window.active_page=load_div;	// Must come after setting the wait_message active!!		
		} else {
			$('#'+load_div).show();
		}

		$("#"+load_div).load(load_script
		,{'userid':[window.userid]
		,'username':[window.username]
		,'sid':[window.sid]
		,'params':[window.params]
		,'page':[window.url]
		,'debug': [window.debug]
		,'ready': [window.profile_ready]
		,'room':[window.current_room]
		,'lang':[window.lang]
		,'info':[info]
		,'allowed':[allowed_roles]
		,'regress':[window.regress]
		,'folder':[window.folder]
		,'version':[window.et_version]
		,'gmt_diff':[window.gmt_diff]
		,'roles':[window.roles]}, function (){ET_load_html_callback();});

		//lert("function ET_load has loaded " + load_script + " into " + load_div);
		return;
	}

	function ET_load_html_callback() {

		//	All the things to do after loading a page can be found in window.variable
		//	This version only allows one name/value pair - We need a delimiter to have more. the amersand seems the obvious choice
		//	so that it looks like URL data video=myvid.flv&view=divid etc.,

		toggle_div=window.active_page;
		setActive(toggle_div);

		ET_user_text();		// All language and tokens

		//lert("function ET_load_callback() setting active content in "+toggle_div);

		instructions=(window.variable+"==").split("=");
		instruction_type=instructions[0];
		instruction=instructions[1];

			// Reset before kicking off any intervales in window.interval var
		ET_reset();

		switch(instruction_type) {
		case('chessboard'):
			Chess_set_position(instruction);
			break;

		case('clocks'):
			ET_clocks();
			window.interval=setInterval("ET_clocks();",5000);
			break;

		case('view'):
			//lert("About to move view to show "+instruction);
			ET_Into_View(instruction);
			break;

		case('video'):
			flowplayer(instruction,'/flowplayer/flowplayer-3.1.5.swf');
			break;

		default:
			break;
		}

		//lert('function ET_load_callback() video = "'+kickoff_video+'" ');
		return;
	}

	function ET_Into_View() {

		
		return;
	}

	function ET_role_check(role_csv) {
		if (role_csv=='') return true;
		allowed_roles=role_csv.split(",");

		// lert("function ET_role_check() checking for any "+window.roles+" in "+role_csv);
		// check allowed_roles again window.roles

		my_roles=window.roles+',';
		for(ar=0; ar<allowed_roles.length; ar++) {
			next_role=allowed_roles[ar];
			if(my_roles.indexOf(next_role+',')>=0) {
				//lert("Found role "+next_role+" in site roles "+my_roles);
				return true;
			}
		}
		//lert("Failed to find  "+next_role+" in site roles "+my_roles);
		return false;
	}	

	//	C H A T    R O O M	I N T E R F A C E 	
	function ET_postchat(message_settings) {

		if(window.userid=='1') {ET_error("You don't have permission to post pages to this room ");return;}

		message_array=(message_settings+"|||||").split("|");
		chat_link=message_array[0];

		// Feb 2nd I broke the html into separate words as the long string of HTML is still causing a problem somewhere 
		chat_message='';
		book_title=message_array[2];
		chat_message=chat_message+'<div class="green">Page from a library book - '+book_title+'</div>';
		chat_message=chat_message+'<a href="javascript:CH_load_html(\''+chat_link+'|toggle_lesson|'+book_title+'\')" >';
		chat_message=chat_message+' <img class="icon" src="../buttons/read.jpeg" alt="Read Page">';

		chat_message=chat_message+'</a>';
		// chat_message=addslashes(chat_message);

		//	Use teachers ID for room number 
		classroom_number=message_array[1];
		if(classroom_number=='') {classroom_number='0';} // Default room is the school hall = main chat

		//	Post the current book page.	Get page sets up a post button to run this function 	
		//lert("function ET_postchat() STARTED ");
		access_allowed=true;

		//lert("function ET_postchat() midstream ");

		if (access_allowed==1) {
			chat_msg_type='t';
			ET_postchat_message(chat_message,classroom_number,chat_msg_type);
		} else {
			please_login='To post messages you must first ';
			please_login+='<a href="http://www.englishtap.com/moodle/login/index.php"><b>Sign in</b></a>';
			ET_error("Your message: <b>" + postmsg_text+"</b><br />"+please_login);
			//lert("Login to post messages");
		}
		//lert("function ET_postchat() COMPLETED ");
		return;
	}

	function ET_postchat_message(msg_text,classroom_number,chat_msg_type) {

		// replace @dquote and @squote
		msg_text=msg_text.replace(/\@dquote/g,'"');
		msg_text=msg_text.replace(/\@squote/g,"'");

		system='0'; 
		if(chat_msg_type=='h') {system='2';}
		if(chat_msg_type=='c') {system='2';}

		postmsg_htmlok='1';
		// groupid >> determines who can read it - ZERO = everyone in the room
		$("#load").load(window.regress+"chat/live/post_message.php",
		{'allow_html':[postmsg_htmlok]
		,'userid': [window.userid]
		,'poster': [window.userid]
		, 'message': [msg_text]
		,'groupid': ['0']
		,'chatid': [classroom_number]
		, 'type': [chat_msg_type]
		, 'system': [system]
		,'roles':[window.roles]});
		return;
	}

	function ET_post_contact(pc_string) {

		//lert("function ET_post_contact() started ");

		//	Format the message here in js into one text string so that
		//	it can be posted to admins using ET_load() with window.params

		msg_text='';

		contact_name=$("#cf_name").val();
		contact_phone=$("#cf_phone").val();
		contact_email=$("#cf_email").val();
		contact_skype=$("#cf_skype").val();
		contact_country=$("#cf_country").val();
		contact_text=$("#cf_text").val();

		//	M A N D A T O R Y        F I E L D S 
		form_ok=true;

		$("#cf_error_message").html(''); 

		if(contact_email=='') {
			$("#cf_email_marker").html('*');
			$("#cf_error_message").html('You must enter a valid contact email address'); 
			form_ok=false;
		} else {$("#cf_email_marker").html('');}

		if(contact_text=='') {
			$("#cf_text_marker").html('*');
			$("#cf_error_message").html('You must enter a text message in the text area'); 
			form_ok=false;
		} else {$("#cf_text_marker").html('');}

		if(contact_name=='') {
			$("#cf_name_marker").html('*');
			$("#cf_error_message").html('You must enter your name'); 
			form_ok=false;
		} else {$("#cf_name_marker").html('*');}

		if(contact_name!='') {	msg_text=msg_text+"<br/>My name is : "+contact_name;}
		if(contact_phone!='') {	msg_text=msg_text+"<br/>My phone : "+contact_phone;}
		if(contact_email!='') {	msg_text=msg_text+"<br/ Email : "+contact_email;}
		if(contact_skype!='') {	msg_text=msg_text+"<br/> Skype : "+contact_skype;}

		msg_text=msg_text+'<br/>'+contact_text;

		if(form_ok==true) {

			classroom_number='0';
			chat_msg_type='c';

			// Send a chat message about the contact request. 
			ET_postchat_message(msg_text,classroom_number,chat_msg_type);

			//	contact_submit.php to load
			window.params=msg_text;
			ET_load('/chat/php_@version/contact_submit.php');

		}

		//lert("function ET_post_contact() complete ");
		return false;
	}


	function ET_get_profile() {
		//	U S E R      P R O F I L E 	>> <div id=profile_data> in the page !!! 
		// use jQuery callback C A L L B A C K  function to set the js vars 
		//lert("function ET_get_profile() STARTED ");

		$("#profile_data").load(window.php+"user_show.php",{'action':['data']
		,'regress': [window.regress]
		,'etpage': ['x']
		,'userid': ['@userid']
		,'my_userid': ['@userid']
		,'admin': [window.admin]
		, 'my_skype': [window.skype]
		,'groupid': ['0']
		, 'system': ['0']
		,'roles':[window.roles]}, function (){ET_set_profile_jsvars("");});

		//lert("function ET_get_profile() completed - ");

		return true;
	}

	function ET_set_profile_jsvars(sp_pars) {

		//lert("function ET_set_profile_jsvars() STARTED ");

		UserProfile=$('#profile_data').html();
		//lert("function ET_set_profile_jsvars() : setting window vars from profile: >> "+UserProfile);

			//	Profile data should be in the format of URL data
			//	Extract the user profile information from the report_rdata
			//	The assign to the window object	

			// Save the whole profile url string as this needs to be passed back into some server side scripts 
		UserProfile=UserProfile.substr(UserProfile.indexOf("?"));
		window.profile=UserProfile;
			//lert("window.profile= " + window.profile);

		window.userid=url_fld('id|'+UserProfile);
		window.username=url_fld('username|'+UserProfile);

		//lert("user name from profile data is '"+window.username+"' ");

		window.ipa=url_fld('ipa|'+UserProfile);
		window.ipa_name=url_fld('ipa_name|'+UserProfile);
		window.ipa_status=url_fld('ipa_status|'+UserProfile);

		//lert("Your ipa status is "+window.ipa_status);

		window.firstname=url_fld('firstname|'+UserProfile);
		window.lastname=url_fld('lastname|'+UserProfile);

		if(url_fld('site_admin|'+UserProfile)=='1') {window.admin=true;} else {window.admin=false;}
		if(url_fld('course_admin|'+UserProfile)=='1') {window.course_admin=true;} else {window.course_admin=false;}
		if(url_fld('teacher|'+UserProfile)=='1') {window.teacher=true;} else {window.teacher=false;}
		if(url_fld('helper|'+UserProfile)=='1') {window.helper=true;} else {window.helper=false;}
		if(url_fld('student|'+UserProfile)=='1') {window.student=true;} else {window.student=false;}

		// Essential student info 

		window.phone=url_fld('phone|'+UserProfile);
		window.mobile=url_fld('mobile|'+UserProfile);
		window.skype=url_fld('skype|'+UserProfile);
		window.country=url_fld('country|'+UserProfile);
		window.et_teacher=url_fld('et_teacher|'+UserProfile);
		window.et_classroom=url_fld('et_classroom|'+UserProfile);

		if (window.skype=='') {$('.noskype').show();$('.skype').hide();} else  {$('.skype').show();$('.noskype').hide();}

		window.msn=url_fld('msn|'+UserProfile);
		window.qq=url_fld('idnumber|'+UserProfile);	// idnumber used for qq account
		window.yahoo=url_fld('yahoo|'+UserProfile);

		window.email=url_fld('email|'+UserProfile);

		if ((window.userid=='1')||(window.userid=='0')||(window.userid=='')) {
			window.userid='1';
			window.guest=true;
			if(window.ipa_name=='') {window.username="Guest";} else {window.username=window.ipa_name;}
			if (window.redirect!='') {
				//lert("Guests are not allowed into the classrooms. Please create an account next");
				window.location = window.redirect;
			}
		}
		else	{window.guest=false}

		window.roles="";	// Build comma delimited string (REMOVE trailing comma !!)
		if (window.admin==true) {window.roles+="1,"};
		if (window.course_admin==true) {window.roles+="2,"};
		if (window.teacher==true) {window.roles+="3,"};
		if (window.helper==true) {window.roles+="4,"};
		window.roles=window.roles.substr(0,(window.roles.length-1));

		//lert("js script version "+window.et_version+" Roles:"+window.roles+"IP name:"+window.ipa_name+" userid "+window.userid);


			//	Set all links depending on the userid 
		my_profile_page="/moodle/user/view.php?id="+window.userid+"course=1";
		$(".my_profile").attr({href : my_profile_page});

		window.profile_ready=true;ET_user_text();

		//lert("Function ET_set_profile_jsvars() COMPLETE  site roles:"+window.roles+" user name "+window.username);

		return;
	}

	function ET_user_text() {

		if(window.profile_ready==false) {
			ET_error("javascript error function ET_user_text() called before profile loaded ");
			return;
		}

		//lert("function ET_user_text() started : window.username = '"+window.username+"' Ready? : "+window.profile_ready);

		if ((window.userid=='1')||(window.userid=='0')||(window.userid=='')) {window.guest=true;} else {window.guest=false;}

			//	CONTAINS ALL CODE FOR Toggling ( guest member lang or site_roll TEXT !!! )

			//	Change all string tokens 
			//	This function should be executed only once
			//	on page load to replace @userid @username

			//		NOTE: getElementsByClassName() is a defined function here NOT part of normal javascript.

			//		C H A N G E  L A N G U A G E  
			//	- Separate function as users may toggle this again with flags 
			//	- This is where the headers and footers are first displayed		

			//lert("function ET_user_text() window.guest="+window.guest+" userid:"+window.userid);


			// Any classes marked 'tokens' should be be replaced too.

		ET_tokens_class('tokens');
		ET_Show_English('');

			//lert("ET_user_text Show_English() ");

			//	= is exactly equal
			//	!= is not equal
			//	^= is starts with
			//	$= is ends with
			//	*= is contains	

			//	TOKEN STRING REPLACEMENTS IN TAGS

		var UserAnchors = document.getElementsByTagName('a')
		elm_count=UserAnchors.length;
		//evlert("There are "+elm_count+" anchor tags on this page  ");
		for (elm=0; elm<(elm_count); elm++) {
			orig_href=UserAnchors[elm].href;
			new_href=orig_href.replace(/@userid/g,window.userid);
			if(orig_href!=new_href) {
				UserAnchors[elm].href=new_href;
				//evlert("Changed link FROM: " + orig_href + " TO " + new_href);
			}
		}

		//lert("ET_user_text() anchor tags changed ");

			//	Check all h1 tags

		var UserHeaders = document.getElementsByTagName('h1')
		elm_count=UserHeaders.length;
			//evlert("There are "+elm_count+" h1 tags on this page  ");
		for (elm=0; elm<(elm_count); elm++) {
			paragraph_text=UserHeaders[elm].innerHTML;
			paragraph_text=paragraph_text.replace(/@userid/g,window.userid);
			paragraph_text=paragraph_text.replace(/@username/g,window.username);
			if(paragraph_text!=paragraph_text) {
				UserHeaders[elm].innerHTML=paragraph_text;
			}
		}

		//lert("ET_user_text headers changed ");

			//	S H O W - MENU CLASSES  not for this class of user - Default set to HIDE for each class in CSS

		if ((window.teacher==true)||(window.admin==true)||(window.course_admin==true)) {$('.teacher').show();}
		if ((window.course_admin==true)||(window.admin==true)) {$('.course_admin').show();}
		if (window.admin==true) {$('.admin').show();}
		if ((window.student==true)||(window.admin==true)) {$('.student').show();}

		//lert("Changing all @vars in this page ");

		// E X C H A N G E 	A L L   user @VARS
		$(".user").each( function() {
			paragraph_old=$(this).text();paragraph_text=paragraph_old;

			paragraph_text=paragraph_text.replace(/@userid/g,window.userid);
				//lert("Found paragraph = "+paragraph_text+" to change ");

			paragraph_text=paragraph_text.replace(/@username/g,window.username);
			paragraph_text=paragraph_text.replace(/@firstname/g,window.firstname);
			paragraph_text=paragraph_text.replace(/@lastname/g,window.lastname);

			paragraph_text=paragraph_text.replace(/@admin/g,window.admin);
			paragraph_text=paragraph_text.replace(/@course_admin/g,window.course_admin);
			paragraph_text=paragraph_text.replace(/@teacher/g,window.teacher);
			paragraph_text=paragraph_text.replace(/@student/g,window.student);
			paragraph_text=paragraph_text.replace(/@phone/g,window.phone);
			paragraph_text=paragraph_text.replace(/@mobile/g,window.mobile);
			paragraph_text=paragraph_text.replace(/@email/g,window.email);
			paragraph_text=paragraph_text.replace(/@skype/g,window.skype);

			// string tokens not related to the user's profile
			paragraph_text=paragraph_text.replace(/@login/g,'Sign off');
		
			if(paragraph_text!=paragraph_text) {$(this).text(paragraph_text);}
			//lert("one done!!+ ");
		});

		//lert("function ET_user_text() comleted !!");

		return true;
	}

	function ET_stop_Int() {
		if(window.interval!="") {
			clearInterval(window.interval);
			window.interval='';
			window.count=0;
		}
	}

	function report_expand(rep_div,rep_text) {

		// This function is for displaying more details about a table row by showing the hidden EXPAND VIEW row
		//lert("function report_expand() ");
		// If the text is already there expanded then hide it else put it there and show it

		if ( $('#'+rep_div).html()==rep_text ) {
			$('#'+rep_div).hide();
			$('#'+rep_div).html()=='';
		} else { 
			$('#'+rep_div).show();
			$('#'+rep_div).html(rep_text);
		}	
		return true;	
	}

	// DOM Class function
	/*
		a	-	defines the action you want the function to perform.
		o	-	the object in question.
		c1	-	the name of the first class
		c2	-	the name of the second class

		Possible actions are:
			swap	-	replaces class c1 with class c2 in object o.
			add	-	adds class c1 to the object o.
			remove	-	removes class c1 from the object o.
			check	-	test if class c1 is already applied to object o and returns true or false. 
	*/

	function jscss(a,o,c1,c2) {
		switch (a) {
		case 'swap':
			o.className=!jscss('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
			break;
		case 'add':
			if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
			break;
		case 'remove':
			var rep=o.className.match(' '+c1)?' '+c1:c1;
			o.className=o.className.replace(rep,'');
			break;
		case 'check':
			return new RegExp('\\b'+c1+'\\b').test(o.className)
			break;
		}
	}

	function getElmsByClassName(searchClass, domNode, tagName) {
		if (domNode == null) domNode = document;
		if (tagName == null) tagName = '*';
		var el = new Array();
		var tags = domNode.getElementsByTagName(tagName);
		var tcl = " "+searchClass+" ";
		for(i=0,j=0; i<tags.length; i++) {
			var test = " " + tags[i].className + " ";
			if (test.indexOf(tcl) != -1)
			el[j++] = tags[i];
		}
		return el;
	}

	function devlert(dev_message) {
		//lert("function devlert(msg) starting ");
		if ((window.userid=='41')||(window.live==false)) {alert(dev_message);}
	}

	interval_ID='';
	other_userid='';

	//	JS Calendar - used from the ET home page events and availabilty bookings etc.,
	//	2010-Dec-9th - Added default selections from homepage into this script	

	//lert("English Tap calendar.js script ");

	//	C A L E N D A R 
	//	Set the default drop down to the current year for the calendar 

	var turnOffYearSpan = false;     // true = Only show This Year and Next, false = show +/- 5 years
	var weekStartsOnSunday = false;  // true = Start the week on Sunday, false = start the week on Monday
	var showWeekNumber = true;  // true = show week number,  false = do not show week number

	var languageCode = 'en';
	// Possible values: 	en,ge,no,nl,es,pt-br,fr
	// en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, 
	// fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian)

	var calendar_display_time = true;

	// Format of current day at the bottom of the calendar
	// [todayString] = the value of todayString
	// [dayString] = day of week (examle: mon, tue, wed...)
	// [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase)
	// [day] = Day of month, 1..31
	// [monthString] = Name of current month
	// [year] = Current year

	var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]';
	var pathToImages = 'media_library/images/calendar/';	// Relative to your HTML file

	var speedOfSelectBoxSliding = 200;
	// Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster

	var intervalSelectBox_minutes = 5;
	// Minute select box - interval between each option (5 = default)

	var calendar_offsetTop = 0;		
	// Offset - calendar placement - You probably have to modify this value if you're not using a strict 	doctype

	var calendar_offsetLeft = 0;
	// Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype

	var calendarDiv = false;

	var MSIE = false;
	var Opera = false;
	if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
	if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;

	switch(languageCode){
	case "en":	/* English */
		var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
		var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
		var weekString = 'Week';
		var todayString = '';
		break;
	case "ge":	/* German */
		var monthArray = ['Januar','Februar','M�rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
		var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];
		var weekString = 'Woche';
		var todayString = 'Heute';
		break;
	case "no":	/* Norwegian */
		var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
		var dayArray = ['Man','Tir','Ons','Tor','Fre','L&oslash;r','S&oslash;n'];
		var weekString = 'Uke';
		var todayString = 'Dagen i dag er';
		break;
	case "nl":	/* Dutch */
		var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
		var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
		var weekString = 'Week';
		var todayString = 'Vandaag';
		break;
	case "es": /* Spanish */
		var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
		var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
		var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom'];
		var weekString = 'Semana';
		var todayString = 'Hoy es';
		break;
	case "pt-br":  /* Brazilian portuguese (pt-br) */
		var monthArray = ['Janeiro','Fevereiro','Mar&ccedil;o','Abril'
		,'Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
		var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
		var dayArray = ['Seg','Ter','Qua','Qui','Sex','S&aacute;b','Dom'];
		var weekString = 'Sem.';
		var todayString = 'Hoje &eacute;';
		break;
	case "fr":      /* French */
		var monthArray = ['Janvier','F�vrier','Mars','Avril','Mai','Juin','Juillet','Ao�t','Septembre','Octobre','Novembre','D�cembre'];
		var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec'];
		var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
		var weekString = 'Sem';
		var todayString = "Aujourd'hui";
		break;
	case "da": /*Danish*/
		var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];
		var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
		var dayArray = ['man','tirs','ons','tors','fre','l&oslash;r','s&oslash;n'];
		var weekString = 'Uge';
		var todayString = 'I dag er den';
		break;
	case "hu":	/* Hungarian  - Remember to use UTF-8 encoding, i.e. the <meta> tag */
		var monthArray = ['Január','Február','Március'
		,'Aprilis','Május','Június','Július','Augusztus','Szeptember','Október','November','December'];
		var monthArrayShort = ['Jan','Feb','Márc','Apr','Máj','Jún','Júl','Aug','Szep','Okt','Nov','Dec'];
		var dayArray = ['Hé','Ke','Sze','Cs','Pé','Szo','Vas'];
		var weekString = 'Hét';
		var todayString = 'Mai nap';
		break;
	case "it":	/* Italian*/
		var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio'
		,'Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
		var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic'];
		var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom'];
		var weekString = 'Settimana';
		var todayString = 'Oggi &egrave; il';
		break;
	case "sv":	/* Swedish */
		var monthArray = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
		var monthArrayShort = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
		var dayArray = ['M&aring;n','Tis','Ons','Tor','Fre','L&ouml;r','S&ouml;n'];
		var weekString = 'Vecka';
		var todayString = 'Idag &auml;r det den';
		break;
	case "cz":	/* Czech */
		var monthArray =['leden','&#250;nor','b&#345;ezen','duben','kv&#283;ten'
		,'&#269;erven','&#269;ervenec'
		,'srpen','z&#225;&#345;&#237;','&#345;&#237;jen','listopad','prosinec'];
		var monthArrayShort = ['led','&#250;n','b&#345;','dub','kv&#283;','&#269;er'
		,'&#269;er-ec','srp','z&#225;&#345;','&#345;&#237;j','list','pros'];
		var dayArray = ['Pon','&#218;t','St','&#268;t','P&#225;','So','Ne'];
		var weekString = 't&#253;den';
		var todayString = '';
		break;	
	}

	if (weekStartsOnSunday) {
		var tempDayName = dayArray[6];
		for(var theIx = 6; theIx > 0; theIx--) {
			dayArray[theIx] = dayArray[theIx-1];
		}
		dayArray[0] = tempDayName;
	}

	var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
	var currentMonth;
	var currentYear;
	var currentHour;
	var currentMinute;
	var calendarContentDiv;
	var returnDateTo;
	var returnFormat;
	var activeSelectBoxMonth;
	var activeSelectBoxYear;
	var activeSelectBoxHour;
	var activeSelectBoxMinute;

	var iframeObj = false;
	//// fix for EI frame problem on time dropdowns 09/30/2006
	var iframeObj2 =false;

	function AD_admin(ap) {

		ap_array=(ap+"|||").split("|");
		ap_sid=ap_array[0];	if(ap_sid!='') {window.sid=ap_sid;}	// Sets the student id that we are working on
	
		ap_div=ap_array[1];
		ap_tab=ap_array[2];	// No tabs in some pages
		if(ap_div=='') {ap_div='toggle_external';}
		ET_load(window.php+"admin.php|"+ap_div+"||||"+ap_tab);

		return;
	}

	function AD_admin_access(toggle_request) {
		if(window.admin==true) {
			setActive(toggle_request);
		} else {
			$('.toggle').hide();
			ET_error("You must be an admin to enter this form on English Tap");
			ET_url_page('about_admin','toggle');
		}
	}

	function AD_month_balances(cm) {

		// All balances - One line per student showing first and last payments with balances

		ma_year=$("#ma_year").val();
		ma_month=$("#ma_month").val();
		window.params=ma_year+"|"+ma_month;
		ET_load(window.php+"cash_balances.php|||||");

		return false;
	}

	function AD_month(mr) {

		// First time load - No previous form values

		ET_load(window.php+"cash_month_report.php|||||");
		return;
	}

	function AD_month_show(mr) {

		// Run the query from AD_month_show()s selection values

		ma_year=$("#ma_year").val();
		ma_month=$("#ma_month").val();

		window.params=ma_year+"|"+ma_month;
		ET_load(window.php+"cash_month_report.php|||||");
		return false;
	}

	function AD_timezones(time_string) {

		// World Time Zones display NOTE: load call back to start the clocks in the loaded page
		ET_load(window.php+"time_zones.php||||clocks");
	}

	function AD_user_account(ustring) {
		// old name for this function - redirect
		AD_cash_show_account(ustring);
	}

	function AD_cash_enter(ustring) {
		ET_load(window.php+"cash_enter.php");
	}

	function AD_cash_show_account(ustring) {

		// 	T H E   P A Y M E N T   A C C O U N T    L I S T 
		//	U S E     POST  M E T H O D  for improved security  MUST HAVE DIV id=report_data

		udata=(ustring+"|||").split("|");
		account=udata[0];
		ET_sid(account);
		ET_load(window.php+"cash_show_account.php");
		return;
	}
 
	function ET_sid(uid) {

		//	Set up the selected userid in all parts of the page (sid)

		window.sid=uid;
		if(window.sid=='') {window.sid=window.userid;}
		$('.sid').html(uid);

		return;
	}

	function AD_user_actions(udata_string) {

		// Admin user find >>> 
		//lert("function AD_user_actions() STARTING  with udata : "+udata_string);

		udata=(udata_string+"||||||").split("|");
		sel_userid=udata[0];
		window.sid=sel_userid;

		user_action=udata[1];
		user_action=user_action.toLowerCase();	// FORM or just URL data string for now

		if ((window.admin==false) && (sel_userid!=window.userid) && (user_action=='form') ) {
			//lert("AD_user_actions() NOT ADMIN  >>  ");
			ET_error("Only admins can access user information.");
			return;
		}

		// get_member contains a form 
		//lert("Setting up student form ");
		setActive('toggle_external');
		$("#toggle_external").load(window.php+"user_show.php"
		,{'userid':[sel_userid]
		,'regress':[window.regress]
		,'admin':[window.admin]
		,'course_admin':[window.course_admin]
		,'my_skype':[window.skype]
		,'my_userid':[window.userid]
		,'action':[user_action]
		,'version':[window.et_version]
		,'roles':[window.roles]});
		//lert("AD_user_actions COMPLETE action : " +user_action);
	}

	function AD_user_search(search_string) {

		//	This comes after the FORM submission for member search
		//	Pick up fields from specific search form ids

		skype=$('#us_skype').val();
		partname=$('#us_name').val();
		part_email=$('#us_email').val();
		part_username=$('#us_username').val();
		country='';
		confirmed=$('input:radio[name=member_confirmed]:checked').val();	// RADIO EXAMPLE !!
		search_string="admin|"+country+"|"+partname+"|"+part_username+"|"+skype+"|"+part_email+"|"+confirmed;

		// Now decide what to do with this 
		AD_user_list(search_string);
		return false;
	}

	function AD_user_list(search_string) {
		// General member list by select values
		//lert("function AD_user_list() start");
		if(window.userid=='1') {
			ET_error("Guests are not allowed to list users. To find a teacher use the report. List teachers.");
			return;
		}

		$('report_data').html("");
		setActive('report_data');

		search_array=(search_string+"||||||||").split("|");
		country=search_array[1];
		search_teacher=search_array[2];
		part_username=search_array[3];
		skype=search_array[4];
		part_email=search_array[5];
		$("#report_data").load(window.php+"user_list.php",{'userid':[window.userid]
		,'teacher':[search_teacher]
		,'roles':[window.roles]
		,'name':[search_array[2]]
		,'username':[part_username]
		,'skype':[skype]
		,'email':[part_email]
		,'confirmed':[search_array[6]]
		,'country':[country]
		,'lang':[window.lang]
		,'etpage':[search_array[0]]
		,'version':[window.et_version]});
		//lert("function AD_user_list() complete. country: '"+country+"'");
		return;
	}

	function AD_user_update() {

		// POST routine from 
		//lert("Function AD_user_update() STARTED ");

		$('#report_data').html("");
		setActive('report_data');

		sid=$('#uf_userid').html();
		uf_username=$('#uf_username').val();

		firstname=$('#uf_firstname').val();
		skype=$('#uf_skype').val();

		lastname=$('#uf_lastname').val();
		email=$('#uf_email').val();
		phone1=$('#uf_phone1').val();
		phone2=$('#uf_phone2').val();

		institution=$('#uf_institution').val();
		department=$('#uf_department').val();
		address=$('#uf_address').val();
		city=$('#uf_city').val();
		country=$('#uf_country').val();
		lang=$('#uf_lang').val();
		timezone=$('#uf_timezone').val();

		// picture==$('#uf_picture').val();

		et_teacher=$('#uf_et_teacher').val();
		et_cost_centre=$('#uf_et_cost_centre').val();
		et_paymethod=$('#uf_et_paymethod').val();
		et_classroom=$('#uf_et_classroom').val();
		et_currency=$('#uf_et_currency').val();

		//	R A D I O 	B U T T O N S
		et_active=$('input:radio[name=uf_et_active]:checked').val();
		if(et_active=='false') {et_active='0';} else {et_active='1';}

		et_accounts=$('input:radio[name=uf_et_accounts]:checked').val();
		if(et_accounts=='false') {et_accounts='0';} else {et_accounts='1';}

		//lert("Function AD_user_update() MIDway  et_accounts: "+et_accounts+" et_active:"+et_active);

		// sid = OTHER ID being updated 	userid=> window.userid THE UPDATERs ID

		//	R A D I O 	B U T T O N S
		et_active=$('input:radio[name=uf_et_active]:checked').val();
		et_accounts=$('input:radio[name=uf_et_accounts]:checked').val();

		query=" UPDATE mdl_user SET ";
		query=query+'  username = "'+uf_username+'" ';
		query=query+'  ,et_teacher = "'+et_teacher+'" ';
		query=query+'  ,et_paymethod = "'+et_paymethod+'" ';
		query=query+'  ,et_classroom = "'+et_classroom+'" ';
		query=query+'  ,et_currency = "'+et_currency+'" ';
		query=query+'  ,et_active = "'+et_active+'" ';

		query=query+' WHERE id = "'+sid+'" ';

		ET_sql_interface(query);

		//lert("function AD_user_update() COMPLETE "+query);

		//	Back to admin menu
		AD_admin('');

		return false;
	}

	function AD_cash_post(cp) {

		//	the POST routine from admin/cash_enter.php
		//	P O S T 	C a s h     received 

		//	cash_post.php onsubmit script for admin/index.html form id='cash_received'

		//lert("function AD_cash_post("+cp+") START ");

		teacher='41';	//	To be included in the <FORM>

		if(window.admin!=true) {
			ET_error("You must log in as an admin to enter cash received.");
		} else {

			amount=$('#cash_enter_amount').val();
			balance=$('#cash_enter_balance').val();
			notes=$('#cash_enter_notes').val();
			student=$('#cash_enter_sid').val();

			//	F I R S T   C H E C K  we have all the validated data 

			post_error='';
			if(amount=='') {ET_error("You must enter an amount paid");return false;}

			// C O L L E C T - date data

			pay_cash_date=$('#cash_enter_date').val();


			// A L T E R N A T I V E 	date separator characters

			pay_cash_date=pay_cash_date.replace(/\./g,"|"); 
			pay_cash_date=pay_cash_date.replace(/\//g,"|"); 
			pay_cash_date=pay_cash_date.replace(/ /g,"|"); 

			date_array=(pay_cash_date+"|||").split("|");

			pay_cash_year=date_array[0];
			pay_cash_month=date_array[1];
			pay_cash_day=date_array[2];

			pay_cash_description=$('#cash_enter_description').val();
		
			//	No time for cash payments - only a date 
			//	payment_hour=$('#'+dom_prefix+'payment_hour').val();
			//	payment_minute=$('#'+dom_prefix+'payment_minute').val();

				//	yyyy,NNN,dd,HH,mm

			date_string=pay_cash_year+pay_cash_month+pay_cash_day;
			payment_time=getDateFromFormat(date_string,"yyyyMMdd");
			paytime_ms=payment_time.getTime();
			paytime_secs=Math.round(paytime_ms/1000)+(3600*12);
			if(paytime_secs=='') {ET_error("You must enter a date when the cash was paid");return false;}

			now=new Date();
			if ((payment_time>=now)||(payment_time=='')) {
				ET_error("Payment date must be a date in the past");
				return false;
			}

			$("#right_bottom").html("");
			$("#right_bottom").show();

			$("#right_bottom").load(window.php+"cash_post.php",{'teacher':[teacher]
			,'student':[student]
			,'amount':[amount]
			,'version':[window.et_version]
			,'balance':[balance]
			,'notes':[notes]
			,'paydate':[paytime_secs]
			,'paydesc':[pay_cash_description]
			,'roles':[window.roles]});

		}

		//lert("function AD_cash_post() COMPLETE ");

		return false;
	}

	function AD_student_list(report_string) {

		report_params=(report_string+"||||").split("|");
		teacher_id=report_params[0];
		module=report_params[1];
		if(module=='') {module='admin';}

		//lert("AD_student_list() started  for teacher id: "+teacher_id);

		if(window.guest==true) {ET_error(window.mustlogin+" List students ");return;}

		student_report=window.php+'user_list.php';
		$('report_data').html("");
		setActive('report_data');
		window.stack='students|'+teacher_id;
		$("#report_data").load(student_report,{'userid':[window.userid]
		,'admin':[window.admin]
		,'etpage':[module]
		,'teacher':[teacher_id]
		,'regress':[window.regress]
		,'version':[window.et_version]
		,'roles':[window.roles]});

		//lert("AD_student_list() complete ");
		return;
	}

	function AD_backbutton() {
		//lert("function AD_backbutton() " + window.stack);
		back_data=window.stack;
		back_array=(back_data+"||||").split("|");
		place=back_array[0];

		switch(place)
		{
		case('students'):
			AD_student_list(back_array[1]);
			break;
		default:
			AD_student_list(back_array[1]);
			break;
		}
	}

	function AD_ask_for_help_update() {
		// Post the text entered in the ASK FOR HELP form 
		new_text=$("#afh_help_text").val();
		ET_sql_interface("UPDATE etlw_teacher_requests SET text = '"+new_text+"' ,timestamp = '@timestamp' WHERE id = '"+window.userid+"' ");
		return false;
	}

	function AD_role_report(role_data) {

		// 2011-08-27 Allow guest to try and view blogs to make contact from teachers role reports

		// if(window.userid=='1') {ET_error("You don't have permission to list role reports in this school.");return;}
		// GUESTS must be able to list admins and helpers

		role_array=(role_data+"|||").split("|");
		role_level=role_array[0];

		etpage=role_array[1];
		// Helps set the action after the report or fom within links in the report
		if(etpage=='') {etpage='admin';}
		country=role_array[2]; // Optional filter 

		//lert("function AD_role_report() role="+role_level);

		//	Roles:	1=Administrator, 2=Coordinator,
		//	3=teacher, 4=teacher_helper,  5=Premium student, 6=free student, 7=logged in member

		role_report=window.php+'role_list.php';
		$('report_data').html("");
		setActive('report_data');
		$("#report_data").load(role_report,{'userid':[window.userid]
		,'role':[role_level]
		,'my_roles':[window.roles]
		,'etpage':[etpage]
		,'regress':[window.regress]
		,'version':[window.et_version]
		,'country':[country]});
		//lert("function AD_role_report() COMPLETED for role: "+role_level);
	}

	function AD_courses(course_string) {
		//	C O U R S E      G R A D E S     A N D   P O S I T I O N S  etc., 

		//lert("function AD_courses() starting " + course_string);
		course_array=(course_string+"|||").split("|");
		uid=course_array[0];
		if (uid=='') {uid=window.userid;}

		etpage=course_array[1];
		course_id=course_array[2];
		if(etpage=='') {etpage='chat';}
		if(course_id=='') {course_id='*';}

		course_report=window.php+'courses.php';
		setActive('report_data');
		$("#report_data").load(course_report,{'course':[course_id]
		,'userid':[uid]
		,'admin':[window.admin]
		,'etpage':[etpage]
		,'regress':[window.regress]
		,'roles':[window.roles]});
		//lert("function AD_courses() complete " + course_string);
		return;
	}

	function AD_course_grades(grade_string) {
		// Course grades for a particular student 
		//lert("function AD_course_grades() started " + grade_string);
		grade_array=(grade_string+"|||").split("|");
		course_id=grade_array[0];
		student_id=grade_array[1];
		filter=grade_array[2];  // Used to report on grades for a single unit

		if (student_id=='undefined') {student_id=window.userid;}
		etpage=grade_array[2];
		if(etpage=="") {etpage="chat"}

		setActive('toggle_external');
		$("#toggle_external").html("");
		$("#toggle_external").load(window.php+'quiz_grades.php',{'course':[course_id]
		,'admin':[window.admin]
		,'student':[student_id]
		,'userid':[window.userid]
		,'filter':[filter]
		,'etpage':[etpage],'regress':[window.regress]
		,'roles':[window.roles]});
		//lert("function AD_course_grades() complete " + grade_string);
	}

	function AD_course_position(grade_string) {

		//	Course position in the grades for a particular student 
		//	Show all the others but highlight 'student'	

		//lert("function AD_course_grades() started " + grade_string);
		grade_array=(grade_string+"|||").split("|");
		course_id=grade_array[0];
		student_id=grade_array[1];
		if (student_id=='undefined') {student_id=window.userid;}
		etpage=grade_array[2];
		rebuild=true;
		bycountry='';
		if(etpage=="") {etpage="chat"}
		setActive('report_data');
		$("#report_data").load(window.php+'course_position.php',{'course':[course_id]
		,'admin':[window.admin]
		,'userid':[window.userid]
		,'student':[student_id]
		,'etpage':[etpage]
		,'rebuild':[rebuild]
		,'regress':[window.regress]
		,'countries':[bycountry]
		,'roles':[window.roles]});
		//lert("function AD_course_grades() complete " + grade_string);
	}

	function AD_top_countries(grade_string) {
		//lert("function AD_course_grades() started " + grade_string);
		grade_array=(grade_string+"|||").split("|");
		course_id=grade_array[0];
		student_id=grade_array[1];
		etpage=grade_array[2];
		if(etpage=="") {etpage="chat"}
		rebuild=true;
		bycountry='1';
		position_report=window.php+'course_position.php';
		setActive('report_data');
		$("#report_data").load(position_report,{'course':[course_id]
		,'admin':[window.admin]
		,'userid':[window.userid]
		,'student':[student_id]
		,'etpage':[etpage],'rebuild':[rebuild]
		,'countries':[bycountry],'regress':[window.regress]
		,'roles':[window.roles]});
		//lert("function AD_course_grades() complete " + grade_string);
	}

	function AD_course_work(work_string) {
		// Course grades for a particular student 
		//lert("function AD_course_work() started " + work_string);
		work_array=(work_string+"|||").split("|");
		course_id=work_array[0];
		student_id=work_array[1];
		filter=work_array[2];

		if (student_id=='undefined') {student_id=window.userid;}
		etpage=work_array[2];
		if(etpage=="") {etpage="chat"}

		position_report=window.php+'quiz.php';

		setActive('report_data');
		$("#report_data").load(position_report,{'course':[course_id],
                'admin':[window.admin],
                'student':[student_id],
                'etpage':[etpage],
                'filter':[filter],
                'regress':[window.regress]
		,'roles':[window.roles]});
		//lert("function AD_course_work() complete " + work_string);
	}

	function EIS_FIX_EI1(where2fixit)	{
		if(!iframeObj2)return;
		iframeObj2.style.display = 'block';
		iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1;
		iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth;
		iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft;
		iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop;
	}

	function EIS_Hide_Frame() {
		if(iframeObj2)iframeObj2.style.display = 'none';
	}

	//// fix for EI frame problem on time dropdowns 09/30/2006
	var returnDateToYear;
	var returnDateToMonth;
	var returnDateToDay;
	var returnDateToHour;
	var returnDateToMinute;

	var inputYear;
	var inputMonth;
	var inputDay;
	var inputHour;
	var inputMinute;
	var calendarDisplayTime = false;

	var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
	var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)

	var selectBoxMovementInProgress = false;
	var activeSelectBox = false;

	function cancelCalendarEvent() {
		return false;
	}

	function isLeapYear(inputYear) {
		if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
		return false;
	}

	var activeSelectBoxMonth = false;
	var activeSelectBoxDirection = false;

	function highlightMonthYear() {
		if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
		activeSelectBox = this;

		if(this.className=='monthYearActive'){
			this.className='';
		}else{
			this.className = 'monthYearActive';
			activeSelectBoxMonth = this;
		}

		if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0){
			if(this.className=='monthYearActive')
				selectBoxMovementInProgress = true;
			else
				selectBoxMovementInProgress = false;
			if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1;

		}else selectBoxMovementInProgress = false;

	}

	function showMonthDropDown() {
		if(document.getElementById('monthDropDown').style.display=='block'){
			document.getElementById('monthDropDown').style.display='none';
			//// fix for EI frame problem on time dropdowns 09/30/2006
			EIS_Hide_Frame();
		}else{
			document.getElementById('monthDropDown').style.display='block';
			document.getElementById('yearDropDown').style.display='none';
			document.getElementById('hourDropDown').style.display='none';
			document.getElementById('minuteDropDown').style.display='none';
				if (MSIE)
			{ EIS_FIX_EI1('monthDropDown')}
			//// fix for EI frame problem on time dropdowns 09/30/2006

		}
	}

	function showYearDropDown() {
		if(document.getElementById('yearDropDown').style.display=='block'){
			document.getElementById('yearDropDown').style.display='none';
			//// fix for EI frame problem on time dropdowns 09/30/2006
			EIS_Hide_Frame();
		}else{
			document.getElementById('yearDropDown').style.display='block';
			document.getElementById('monthDropDown').style.display='none';
			document.getElementById('hourDropDown').style.display='none';
			document.getElementById('minuteDropDown').style.display='none';
				if (MSIE)
			{ EIS_FIX_EI1('yearDropDown')}
			//// fix for EI frame problem on time dropdowns 09/30/2006
		}
	}

	function showHourDropDown() {
		if(document.getElementById('hourDropDown').style.display=='block'){
			document.getElementById('hourDropDown').style.display='none';
			//// fix for EI frame problem on time dropdowns 09/30/2006
					EIS_Hide_Frame();
		}else{
			document.getElementById('hourDropDown').style.display='block';
			document.getElementById('monthDropDown').style.display='none';
			document.getElementById('yearDropDown').style.display='none';
			document.getElementById('minuteDropDown').style.display='none';
					if (MSIE)
			{ EIS_FIX_EI1('hourDropDown')}
			//// fix for EI frame problem on time dropdowns 09/30/2006
		}

	}

	function showMinuteDropDown() {
		if(document.getElementById('minuteDropDown').style.display=='block'){
			document.getElementById('minuteDropDown').style.display='none';
			//// fix for EI frame problem on time dropdowns 09/30/2006
				EIS_Hide_Frame();
		}else{
			document.getElementById('minuteDropDown').style.display='block';
			document.getElementById('monthDropDown').style.display='none';
			document.getElementById('yearDropDown').style.display='none';
			document.getElementById('hourDropDown').style.display='none';
				if (MSIE)
			{ EIS_FIX_EI1('minuteDropDown')}
			//// fix for EI frame problem on time dropdowns 09/30/2006
		}

	}

	function selectMonth() {

		document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
		currentMonth = this.id.replace(/[^\d]/g,'');

		document.getElementById('monthDropDown').style.display='none';
		//// fix for EI frame problem on time dropdowns 09/30/2006
				EIS_Hide_Frame();
		for(var no=0;no<monthArray.length;no++){
			document.getElementById('monthDiv_'+no).style.color='';
		}
		this.style.color = selectBoxHighlightColor;
		activeSelectBoxMonth = this;
		writeCalendarContent();
	}

	function selectHour() {
		document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML
		currentHour = this.innerHTML.replace(/[^\d]/g,'');
		document.getElementById('hourDropDown').style.display='none';
		//// fix for EI frame problem on time dropdowns 09/30/2006
		EIS_Hide_Frame();
		if(activeSelectBoxHour){
			activeSelectBoxHour.style.color='';
		}
		activeSelectBoxHour=this;
		this.style.color = selectBoxHighlightColor;
	}

	function selectMinute() {
		document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML
		currentMinute = this.innerHTML.replace(/[^\d]/g,'');
		document.getElementById('minuteDropDown').style.display='none';
		//// fix for EI frame problem on time dropdowns 09/30/2006
					EIS_Hide_Frame();
		if(activeSelectBoxMinute){
			activeSelectBoxMinute.style.color='';
		}
		activeSelectBoxMinute=this;
		this.style.color = selectBoxHighlightColor;
	}

	function selectYear() {
		document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
		currentYear = this.innerHTML.replace(/[^\d]/g,'');
		document.getElementById('yearDropDown').style.display='none';
		//// fix for EI frame problem on time dropdowns 09/30/2006
					EIS_Hide_Frame();
		if(activeSelectBoxYear){
			activeSelectBoxYear.style.color='';
		}
		activeSelectBoxYear=this;
		this.style.color = selectBoxHighlightColor;
		writeCalendarContent();
	}

	function switchMonth() {
		if(this.src.indexOf('left')>=0){
			currentMonth=currentMonth-1;;
			if(currentMonth<0){
				currentMonth=11;
				currentYear=currentYear-1;
			}
		}else{
			currentMonth=currentMonth+1;;
			if(currentMonth>11){
				currentMonth=0;
				currentYear=currentYear/1+1;
			}
		}
		writeCalendarContent();
	}

	function createMonthDiv(){
		var div = document.createElement('DIV');
		div.className='monthYearPicker';
		div.id = 'monthPicker';

		for(var no=0;no<monthArray.length;no++){
			var subDiv = document.createElement('DIV');
			subDiv.innerHTML = monthArray[no];
			subDiv.onmouseover = highlightMonthYear;
			subDiv.onmouseout = highlightMonthYear;
			subDiv.onclick = selectMonth;
			subDiv.id = 'monthDiv_' + no;
			subDiv.style.width = '56px';
			subDiv.onselectstart = cancelCalendarEvent;
			div.appendChild(subDiv);
			if(currentMonth && currentMonth==no){
				subDiv.style.color = selectBoxHighlightColor;
				activeSelectBoxMonth = subDiv;
			}
		}
		return div;
	}

	function changeSelectBoxYear(e,inputObj) {
		if(!inputObj)inputObj =this;
		var yearItems = inputObj.parentNode.getElementsByTagName('DIV');
		if(inputObj.innerHTML.indexOf('-')>=0){
			var startYear = yearItems[1].innerHTML/1 -1;
			if(activeSelectBoxYear){
				activeSelectBoxYear.style.color='';
			}
		}else{
			var startYear = yearItems[1].innerHTML/1 +1;
			if(activeSelectBoxYear){
				activeSelectBoxYear.style.color='';
			}
		}

		for(var no=1;no<yearItems.length-1;no++){
			yearItems[no].innerHTML = startYear+no-1;
			yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);
		}
		if(activeSelectBoxYear){
			activeSelectBoxYear.style.color='';
			if(document.getElementById('yearDiv'+currentYear)){
				activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
				activeSelectBoxYear.style.color=selectBoxHighlightColor;;
			}
		}
	}

	function changeSelectBoxHour(e,inputObj) {
		if(!inputObj)inputObj = this;

		var hourItems = inputObj.parentNode.getElementsByTagName('DIV');
		if(inputObj.innerHTML.indexOf('-')>=0){
			var startHour = hourItems[1].innerHTML/1 -1;
			if(startHour<0)startHour=0;
			if(activeSelectBoxHour){
				activeSelectBoxHour.style.color='';
			}
		}else{
			var startHour = hourItems[1].innerHTML/1 +1;
			if(startHour>14)startHour = 14;
			if(activeSelectBoxHour){
				activeSelectBoxHour.style.color='';
			}
		}
		var prefix = '';
		for(var no=1;no<hourItems.length-1;no++){
			if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = '';
			hourItems[no].innerHTML = prefix + (startHour+no-1);
			hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1);
		}
	
		if(activeSelectBoxHour){
			activeSelectBoxHour.style.color='';
			if(document.getElementById('hourDiv'+currentHour)){
				activeSelectBoxHour = document.getElementById('hourDiv'+currentHour);
				activeSelectBoxHour.style.color=selectBoxHighlightColor;;
			}
		}
	}

	function updateYearDiv() {
		var yearSpan = 5;
		if (turnOffYearSpan) {
			yearSpan = 0;
		}
		var div = document.getElementById('yearDropDown');
		var yearItems = div.getElementsByTagName('DIV');
		for(var no=1;no<yearItems.length-1;no++){
			yearItems[no].innerHTML = currentYear/1 -yearSpan + no;
			if(currentYear==(currentYear/1 -yearSpan + no)){
				yearItems[no].style.color = selectBoxHighlightColor;
				activeSelectBoxYear = yearItems[no];
			}else{
				yearItems[no].style.color = '';
			}
		}
	}

	function updateMonthDiv() {
		for(no=0;no<12;no++){
			document.getElementById('monthDiv_' + no).style.color = '';
		}
		document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
		activeSelectBoxMonth = 	document.getElementById('monthDiv_' + currentMonth);
	}

	function updateHourDiv() {
		var div = document.getElementById('hourDropDown');
		var hourItems = div.getElementsByTagName('DIV');

		var addHours = 0;
		if((currentHour/1 -6 + 1)<0){
			addHours = 	(currentHour/1 -6 + 1)*-1;
		}
		for(var no=1;no<hourItems.length-1;no++){
			var prefix='';
			if((currentHour/1 -6 + no + addHours) < 10)prefix='0';
			hourItems[no].innerHTML = prefix +  (currentHour/1 -6 + no + addHours);
			if(currentHour==(currentHour/1 -6 + no)){
				hourItems[no].style.color = selectBoxHighlightColor;
				activeSelectBoxHour = hourItems[no];
			}else{
				hourItems[no].style.color = '';
			}
		}
	}

	function updateMinuteDiv() {
		for(no=0;no<60;no+=intervalSelectBox_minutes){
			var prefix = '';
			if(no<10)prefix = '0';

			document.getElementById('minuteDiv_' + prefix + no).style.color = '';
		}
		if(document.getElementById('minuteDiv_' + currentMinute)){
			document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor;
			activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute);
		}
	}

	function createYearDiv() {

	if(!document.getElementById('yearDropDown')){
		var div = document.createElement('DIV');
		div.className='monthYearPicker';
	}else{
		var div = document.getElementById('yearDropDown');
		var subDivs = div.getElementsByTagName('DIV');
		for(var no=0;no<subDivs.length;no++){
			subDivs[no].parentNode.removeChild(subDivs[no]);
		}
	}


	var d = new Date();
	if(currentYear){
		d.setFullYear(currentYear);
	}

	var startYear = d.getFullYear()/1 - 5;

	var yearSpan = 10;
	if (! turnOffYearSpan) {
	    	var subDiv = document.createElement('DIV');
	    	subDiv.innerHTML = '&nbsp;&nbsp;- ';
	    	subDiv.onclick = changeSelectBoxYear;
	    	subDiv.onmouseover = highlightMonthYear;
	    	subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
	    	subDiv.onselectstart = cancelCalendarEvent;
	    	div.appendChild(subDiv);
	} else {
		startYear = d.getFullYear()/1 - 0;
		yearSpan = 2;
	}

	for(var no=startYear;no<(startYear+yearSpan);no++){
		var subDiv = document.createElement('DIV');
		subDiv.innerHTML = no;
		subDiv.onmouseover = highlightMonthYear;
		subDiv.onmouseout = highlightMonthYear;
		subDiv.onclick = selectYear;
		subDiv.id = 'yearDiv' + no;
		subDiv.onselectstart = cancelCalendarEvent;
		div.appendChild(subDiv);
		if(currentYear && currentYear==no){
			subDiv.style.color = selectBoxHighlightColor;
			activeSelectBoxYear = subDiv;
		}
	}
	if (! turnOffYearSpan) {
    	var subDiv = document.createElement('DIV');
    	subDiv.innerHTML = '&nbsp;&nbsp;+ ';
    	subDiv.onclick = changeSelectBoxYear;
    	subDiv.onmouseover = highlightMonthYear;
    	subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
    	subDiv.onselectstart = cancelCalendarEvent;
    	div.appendChild(subDiv);
	}
	return div;
}

	// This function creates the hour div at the bottom bar 

	function slideCalendarSelectBox() {
	if(selectBoxMovementInProgress){
		if(activeSelectBox.parentNode.id=='hourDropDown'){
			changeSelectBoxHour(false,activeSelectBox);
		}
		if(activeSelectBox.parentNode.id=='yearDropDown'){
			changeSelectBoxYear(false,activeSelectBox);
		}

	}
	setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding);

	}

	function createHourDiv() {
	if(!document.getElementById('hourDropDown')){
		var div = document.createElement('DIV');
		div.className='monthYearPicker';
	}else{
		var div = document.getElementById('hourDropDown');
		var subDivs = div.getElementsByTagName('DIV');
		for(var no=0;no<subDivs.length;no++){
			subDivs[no].parentNode.removeChild(subDivs[no]);
		}
	}

	if(!currentHour)currentHour=0;
	var startHour = currentHour/1;
	if(startHour>14)startHour=14;

	var subDiv = document.createElement('DIV');
	subDiv.innerHTML = '&nbsp;&nbsp;- ';
	subDiv.onclick = changeSelectBoxHour;
	subDiv.onmouseover = highlightMonthYear;
	subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
	subDiv.onselectstart = cancelCalendarEvent;
	div.appendChild(subDiv);

	for(var no=startHour;no<startHour+10;no++){
		var prefix = '';
		if(no/1<10)prefix='0';
		var subDiv = document.createElement('DIV');
		subDiv.innerHTML = prefix + no;
		subDiv.onmouseover = highlightMonthYear;
		subDiv.onmouseout = highlightMonthYear;
		subDiv.onclick = selectHour;
		subDiv.id = 'hourDiv' + no;
		subDiv.onselectstart = cancelCalendarEvent;
		div.appendChild(subDiv);
		if(currentYear && currentYear==no){
			subDiv.style.color = selectBoxHighlightColor;
			activeSelectBoxYear = subDiv;
		}
	}
	var subDiv = document.createElement('DIV');
	subDiv.innerHTML = '&nbsp;&nbsp;+ ';
	subDiv.onclick = changeSelectBoxHour;
	subDiv.onmouseover = highlightMonthYear;
	subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
	subDiv.onselectstart = cancelCalendarEvent;
	div.appendChild(subDiv);

	return div;
	}

	// This function creates the minute div at the bottom bar 

	function createMinuteDiv() {
	if(!document.getElementById('minuteDropDown')){
		var div = document.createElement('DIV');
		div.className='monthYearPicker';
	}else{
		var div = document.getElementById('minuteDropDown');
		var subDivs = div.getElementsByTagName('DIV');
		for(var no=0;no<subDivs.length;no++){
			subDivs[no].parentNode.removeChild(subDivs[no]);
		}
	}
	var startMinute = 0;
	var prefix = '';
	for(var no=startMinute;no<60;no+=intervalSelectBox_minutes){




		if(no<10)prefix='0'; else prefix = '';
		var subDiv = document.createElement('DIV');
		subDiv.innerHTML = prefix + no;
		subDiv.onmouseover = highlightMonthYear;
		subDiv.onmouseout = highlightMonthYear;
		subDiv.onclick = selectMinute;
		subDiv.id = 'minuteDiv_' + prefix +  no;
		subDiv.onselectstart = cancelCalendarEvent;
		div.appendChild(subDiv);
		if(currentYear && currentYear==no){
			subDiv.style.color = selectBoxHighlightColor;
			activeSelectBoxYear = subDiv;
		}
	}
	return div;
	}

	function highlightSelect() {
		if(this.className=='selectBoxTime'){
			this.className = 'selectBoxTimeOver';
			this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_over.gif';
		}else if(this.className=='selectBoxTimeOver'){
			this.className = 'selectBoxTime';
			this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time.gif';
		}

		if(this.className=='selectBox'){
			this.className = 'selectBoxOver';
			this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over.gif';
		}else if(this.className=='selectBoxOver'){
			this.className = 'selectBox';
			this.getElementsByTagName('IMG')[0].src = pathToImages + 'down.gif';
		}
	}

	function highlightArrow() {
		if(this.src.indexOf('over')>=0){
			if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left.gif';
			if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right.gif';
		}else{
			if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over.gif';
			if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over.gif';
		}
	}

	function highlightClose() {
		if(this.src.indexOf('over')>=0){
			this.src = pathToImages + 'close.gif';
		}else{
			this.src = pathToImages + 'close_over.gif';
		}

	}

	function closeCalendar(){

		document.getElementById('yearDropDown').style.display='none';
		document.getElementById('monthDropDown').style.display='none';
		document.getElementById('hourDropDown').style.display='none';
		document.getElementById('minuteDropDown').style.display='none';

		calendarDiv.style.display='none';
		if(iframeObj){
			iframeObj.style.display='none';
			 //// //// fix for EI frame problem on time dropdowns 09/30/2006
				EIS_Hide_Frame();}
		if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
		if(activeSelectBoxYear)activeSelectBoxYear.className='';

	}

	function writeTopBar() {

		var topBar = document.createElement('DIV');
		topBar.className = 'topBar';
		topBar.id = 'topBar';
		calendarDiv.appendChild(topBar);

		// Left arrow
		var leftDiv = document.createElement('DIV');
		leftDiv.style.marginRight = '1px';
		var img = document.createElement('IMG');
		img.src = pathToImages + 'left.gif';
		img.onmouseover = highlightArrow;
		img.onclick = switchMonth;
		img.onmouseout = highlightArrow;
		leftDiv.appendChild(img);
		topBar.appendChild(leftDiv);
		if(Opera)leftDiv.style.width = '16px';

		// Right arrow
		var rightDiv = document.createElement('DIV');
		rightDiv.style.marginRight = '1px';
		var img = document.createElement('IMG');
		img.src = pathToImages + 'right.gif';
		img.onclick = switchMonth;
		img.onmouseover = highlightArrow;
		img.onmouseout = highlightArrow;
		rightDiv.appendChild(img);
		if(Opera)rightDiv.style.width = '16px';
		topBar.appendChild(rightDiv);

		// Month selector
		var monthDiv = document.createElement('DIV');
		monthDiv.id = 'monthSelect';
		monthDiv.onmouseover = highlightSelect;
		monthDiv.onmouseout = highlightSelect;
		monthDiv.onclick = showMonthDropDown;
		var span = document.createElement('SPAN');
		span.innerHTML = monthArray[currentMonth];
		span.id = 'calendar_month_txt';
		monthDiv.appendChild(span);

		var img = document.createElement('IMG');
		img.src = pathToImages + 'down.gif';
		img.style.position = 'absolute';
		img.style.right = '0px';
		monthDiv.appendChild(img);
		monthDiv.className = 'selectBox';
		if(Opera){
			img.style.cssText = 'float:right;position:relative';
			img.style.position = 'relative';
			img.style.styleFloat = 'right';
		}
		topBar.appendChild(monthDiv);

		var monthPicker = createMonthDiv();
		monthPicker.style.left = '37px';
		monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
		monthPicker.style.width ='60px';
		monthPicker.id = 'monthDropDown';

		calendarDiv.appendChild(monthPicker);

		// Year selector
		var yearDiv = document.createElement('DIV');
		yearDiv.onmouseover = highlightSelect;
		yearDiv.onmouseout = highlightSelect;
		yearDiv.onclick = showYearDropDown;
		var span = document.createElement('SPAN');
		span.innerHTML = currentYear;
		span.id = 'calendar_year_txt';
		yearDiv.appendChild(span);
		topBar.appendChild(yearDiv);

		var img = document.createElement('IMG');
		img.src = pathToImages + 'down.gif';
		yearDiv.appendChild(img);
		yearDiv.className = 'selectBox';

		if(Opera){
			yearDiv.style.width = '50px';
			img.style.cssText = 'float:right';
			img.style.position = 'relative';
			img.style.styleFloat = 'right';
		}

		var yearPicker = createYearDiv();
		yearPicker.style.left = '113px';
		yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
		yearPicker.style.width = '35px';
		yearPicker.id = 'yearDropDown';
		calendarDiv.appendChild(yearPicker);

		var img = document.createElement('IMG');
		img.src = pathToImages + 'close.gif';
		img.style.styleFloat = 'right';
		img.onmouseover = highlightClose;
		img.onmouseout = highlightClose;
		img.onclick = closeCalendar;
		topBar.appendChild(img);
		if(!document.all){
			img.style.position = 'absolute';
			img.style.right = '2px';
		}
	
	}

	function writeCalendarContent() {
		var calendarContentDivExists = true;
		if(!calendarContentDiv){
			calendarContentDiv = document.createElement('DIV');
			calendarDiv.appendChild(calendarContentDiv);
			calendarContentDivExists = false;
		}
		currentMonth = currentMonth/1;
		var d = new Date();

		d.setFullYear(currentYear);
		d.setDate(1);
		d.setMonth(currentMonth);

		var dayStartOfMonth = d.getDay();
		if (! weekStartsOnSunday) {
		if(dayStartOfMonth==0)dayStartOfMonth=7;
		dayStartOfMonth--;
	}

	document.getElementById('calendar_year_txt').innerHTML = currentYear;
	document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
	document.getElementById('calendar_hour_txt').innerHTML = currentHour/1 > 9 ? currentHour : '0' + currentHour;
	document.getElementById('calendar_minute_txt').innerHTML = currentMinute/1 >9 ? currentMinute : '0' + currentMinute;

	var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
	if(existingTable.length>0){
		calendarContentDiv.removeChild(existingTable[0]);
	}

	var calTable = document.createElement('TABLE');
	calTable.width = '100%';
	calTable.cellSpacing = '0';
	calendarContentDiv.appendChild(calTable);

	var calTBody = document.createElement('TBODY');
	calTable.appendChild(calTBody);
	var row = calTBody.insertRow(-1);
	row.className = 'calendar_week_row';

	if (showWeekNumber) {
		var cell = row.insertCell(-1);
		cell.innerHTML = weekString;
		cell.className = 'calendar_week_column';
		cell.style.backgroundColor = selectBoxRolloverBgColor;
	}

	for(var no=0;no<dayArray.length;no++){
		var cell = row.insertCell(-1);
		cell.innerHTML = dayArray[no];
	}

	var row = calTBody.insertRow(-1);

	if (showWeekNumber) {
		var cell = row.insertCell(-1);
		cell.className = 'calendar_week_column';
		cell.style.backgroundColor = selectBoxRolloverBgColor;
		var week = getWeek(currentYear,currentMonth,1);
		cell.innerHTML = week;		// Week
	}
	for(var no=0;no<dayStartOfMonth;no++){
		var cell = row.insertCell(-1);
		cell.innerHTML = '&nbsp;';
	}

	var colCounter = dayStartOfMonth;
	var daysInMonth = daysInMonthArray[currentMonth];
	if(daysInMonth==28){
		if(isLeapYear(currentYear))daysInMonth=29;
	}

	for(var no=1;no<=daysInMonth;no++){
		d.setDate(no-1);
		if(colCounter>0 && colCounter%7==0){
			var row = calTBody.insertRow(-1);
			if (showWeekNumber) {
				var cell = row.insertCell(-1);
				cell.className = 'calendar_week_column';
				var week = getWeek(currentYear,currentMonth,no);
				cell.innerHTML = week;		// Week
				cell.style.backgroundColor = selectBoxRolloverBgColor;
			}
		}
		var cell = row.insertCell(-1);
		if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
			cell.className='activeDay';
		}
		cell.innerHTML = no;
		cell.onclick = pickDate;
		colCounter++;
	}

	if(!document.all){
		if(calendarContentDiv.offsetHeight)
			document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
		else{
			document.getElementById('topBar').style.top = '';
			document.getElementById('topBar').style.bottom = '0px';
		}

	}

	if(iframeObj){
		if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
	}

}

	function resizeIframe() {
		iframeObj.style.width = calendarDiv.offsetWidth + 'px';
		iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;
	}

	function pickTodaysDate() {
		var d = new Date();
		currentMonth = d.getMonth();
		currentYear = d.getFullYear();
		pickDate(false,d.getDate());
	}

	function pickDate(e,inputDay) {
		var month = currentMonth/1 +1;
		if(month<10)month = '0' + month;
		var day;
		if(!inputDay && this)day = this.innerHTML; else day = inputDay;

		if(day/1<10)day = '0' + day;
		if(returnFormat){
			returnFormat = returnFormat.replace('dd',day);
			returnFormat = returnFormat.replace('mm',month);
			returnFormat = returnFormat.replace('yyyy',currentYear);
			returnFormat = returnFormat.replace('hh',currentHour);
			returnFormat = returnFormat.replace('ii',currentMinute);
			returnFormat = returnFormat.replace('d',day/1);
			returnFormat = returnFormat.replace('m',month/1);
			returnDateTo.value = returnFormat;
			try{
				returnDateTo.onchange();
			}catch(e){
			}
		}else{
			for(var no=0;no<returnDateToYear.options.length;no++){
				if(returnDateToYear.options[no].value==currentYear){
					returnDateToYear.selectedIndex=no;
					break;
				}
			}
			for(var no=0;no<returnDateToMonth.options.length;no++){
				if(returnDateToMonth.options[no].value==parseFloat(month)){
					returnDateToMonth.selectedIndex=no;
					break;
				}
			}
			for(var no=0;no<returnDateToDay.options.length;no++){
				if(returnDateToDay.options[no].value==parseFloat(day)){
					returnDateToDay.selectedIndex=no;
					break;
				}
			}
			if(calendarDisplayTime){
				for(var no=0;no<returnDateToHour.options.length;no++){
					if(returnDateToHour.options[no].value==parseFloat(currentHour)){
						returnDateToHour.selectedIndex=no;
						break;
					}
				}
				for(var no=0;no<returnDateToMinute.options.length;no++){
					if(returnDateToMinute.options[no].value==parseFloat(currentMinute)){
						returnDateToMinute.selectedIndex=no;
						break;
					}
				}
			}
		}
		closeCalendar();
	}

// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add

	function getWeek(year,month,day) { 
		if (! weekStartsOnSunday) {
			day = (day/1);
		} else {
			day = (day/1)+1;
		}
		year = year /1;
		month = month/1 + 1; //use 1-12
		var a = Math.floor((14-(month))/12);
		var y = year+4800-a;
		var m = (month)+(12*a)-3;
		var jd = day + Math.floor(((153*m)+2)/5) +
		(365*y) + Math.floor(y/4) - Math.floor(y/100) +
		Math.floor(y/400) - 32045;      // (gregorian calendar)
		var d4 = (jd+31741-(jd%7))%146097%36524%1461;
		var L = Math.floor(d4/1460);
		var d1 = ((d4-L)%365)+L;
		NumberOfWeek = Math.floor(d1/7) + 1;
		return NumberOfWeek;
	}

	function writeTimeBar() {
		var timeBar = document.createElement('DIV');
		timeBar.id = 'timeBar';
		timeBar.className = 'timeBar';

		var subDiv = document.createElement('DIV');
		subDiv.innerHTML = 'Time:';

		// hour selector
		var hourDiv = document.createElement('DIV');
		hourDiv.onmouseover = highlightSelect;
		hourDiv.onmouseout = highlightSelect;
		hourDiv.onclick = showHourDropDown;
		hourDiv.style.width = '30px';
		var span = document.createElement('SPAN');
		span.innerHTML = currentHour;
		span.id = 'calendar_hour_txt';
		hourDiv.appendChild(span);
		timeBar.appendChild(hourDiv);

		var img = document.createElement('IMG');
		img.src = pathToImages + 'down_time.gif';
		hourDiv.appendChild(img);
		hourDiv.className = 'selectBoxTime';

		if(Opera){
			hourDiv.style.width = '30px';
			img.style.cssText = 'float:right';
			img.style.position = 'relative';
			img.style.styleFloat = 'right';
		}

		var hourPicker = createHourDiv();
		hourPicker.style.left = '130px';
		//hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
		hourPicker.style.width = '35px';
		hourPicker.id = 'hourDropDown';
		calendarDiv.appendChild(hourPicker);

		// Add Minute picker

		// Year selector
		var minuteDiv = document.createElement('DIV');
		minuteDiv.onmouseover = highlightSelect;
		minuteDiv.onmouseout = highlightSelect;
		minuteDiv.onclick = showMinuteDropDown;
		minuteDiv.style.width = '30px';
		var span = document.createElement('SPAN');
		span.innerHTML = currentMinute;

		span.id = 'calendar_minute_txt';
		minuteDiv.appendChild(span);
		timeBar.appendChild(minuteDiv);

		var img = document.createElement('IMG');
		img.src = pathToImages + 'down_time.gif';
		minuteDiv.appendChild(img);
		minuteDiv.className = 'selectBoxTime';

		if(Opera){
			minuteDiv.style.width = '30px';
			img.style.cssText = 'float:right';
			img.style.position = 'relative';
			img.style.styleFloat = 'right';
		}

		var minutePicker = createMinuteDiv();
		minutePicker.style.left = '167px';
		//minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
		minutePicker.style.width = '35px';
		minutePicker.id = 'minuteDropDown';
		calendarDiv.appendChild(minutePicker);

		return timeBar;
	}

	function writeBottomBar() {
		var d = new Date();
		var bottomBar = document.createElement('DIV');

		bottomBar.id = 'bottomBar';

		bottomBar.style.cursor = 'pointer';
		bottomBar.className = 'todaysDate';
		// var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]';	;;

		var subDiv = document.createElement('DIV');
		subDiv.onclick = pickTodaysDate;
		subDiv.id = 'todaysDateString';
		subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px';
		var day = d.getDay();
		if (! weekStartsOnSunday) {
			if(day==0)day = 7;
			day--;
		}

		var bottomString = todayStringFormat;
		bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
		bottomString = bottomString.replace('[day]',d.getDate());
		bottomString = bottomString.replace('[year]',d.getFullYear());
		bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
		bottomString = bottomString.replace('[UCFdayString]',dayArray[day]);
		bottomString = bottomString.replace('[todayString]',todayString);

		subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' +  d.getFullYear() ;
		subDiv.innerHTML = bottomString ;
		bottomBar.appendChild(subDiv);

		var timeDiv = writeTimeBar();
		bottomBar.appendChild(timeDiv);

		calendarDiv.appendChild(bottomBar);

	}

	function getTopPos(inputObj) {
		var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
		while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
		return returnValue + calendar_offsetTop;
	}

	function getleftPos(inputObj) {
		var returnValue = inputObj.offsetLeft;
		while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
		return returnValue + calendar_offsetLeft;
	}

	function positionCalendar(inputObj) {
		calendarDiv.style.left = getleftPos(inputObj) + 'px';
		calendarDiv.style.top = getTopPos(inputObj) + 'px';
		if(iframeObj){
			iframeObj.style.left = calendarDiv.style.left;
			iframeObj.style.top =  calendarDiv.style.top;
			//// fix for EI frame problem on time dropdowns 09/30/2006
			iframeObj2.style.left = calendarDiv.style.left;
			iframeObj2.style.top =  calendarDiv.style.top;
		}

	}

	function initCalendar() {
		//lert("function initCalendar() START ");
		if(MSIE){
			iframeObj = document.createElement('IFRAME');
			iframeObj.style.filter = 'alpha(opacity=0)';
			iframeObj.style.position = 'absolute';
			iframeObj.border='0px';
			iframeObj.style.border = '0px';
			iframeObj.style.backgroundColor = '#FF0000';
			//// fix for EI frame problem on time dropdowns 09/30/2006
			iframeObj2 = document.createElement('IFRAME');
			iframeObj2.style.position = 'absolute';
			iframeObj2.border='0px';
			iframeObj2.style.border = '0px';
			iframeObj2.style.height = '1px';
			iframeObj2.style.width = '1px';
			//// fix for EI frame problem on time dropdowns 09/30/2006
			// Added fixed for HTTPS
			iframeObj2.src = 'blank.html';
			iframeObj.src = 'blank.html';
			document.body.appendChild(iframeObj2);  // gfb move this down AFTER the .src is set
			document.body.appendChild(iframeObj);
		}

		calendarDiv = document.createElement('DIV');
		calendarDiv.id = 'calendarDiv';
		calendarDiv.style.zIndex = 1000;
		slideCalendarSelectBox();

		document.body.appendChild(calendarDiv);
		writeBottomBar();
		writeTopBar();

		if(!currentYear){
			var d = new Date();
			currentMonth = d.getMonth();
			currentYear = d.getFullYear();
		}
		writeCalendarContent();

	}

function setTimeProperties()
{
	if(!calendarDisplayTime){
		document.getElementById('timeBar').style.display='none';
		document.getElementById('timeBar').style.visibility='hidden';
		document.getElementById('todaysDateString').style.width = '100%';


	}else{
		document.getElementById('timeBar').style.display='block';
		document.getElementById('timeBar').style.visibility='visible';
		document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
		document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
		document.getElementById('minuteDropDown').style.right = '50px';
		document.getElementById('hourDropDown').style.right = '50px';
		document.getElementById('todaysDateString').style.width = '115px';
	}
}

	function calendarSortItems(a,b) {
		return a/1 - b/1;
	}

	function displayCalendar(inputField,format,buttonObj,displayTime,timeInput) {

	//lert("function displayCalendar() START ");


		if(displayTime) calendarDisplayTime=true; else calendarDisplayTime = false;

		//lert("calendarDisplayTime " + calendarDisplayTime);

		if(inputField.value.length>6){ 
			//dates must have at least 6 digits...
			if(!inputField.value.match(/^[0-9]*?$/gi)){
				var items = inputField.value.split(/[^0-9]/gi);
				var positionArray = new Object();
				positionArray.m = format.indexOf('mm');
				if(positionArray.m==-1)positionArray.m = format.indexOf('m');
				positionArray.d = format.indexOf('dd');
				if(positionArray.d==-1)positionArray.d = format.indexOf('d');
				positionArray.y = format.indexOf('yyyy');
				positionArray.h = format.indexOf('hh');
				positionArray.i = format.indexOf('ii');
			
				this.initialHour = '00';
				this.initialMinute = '00';				
				var elements = ['y','m','d','h','i'];
				var properties = ['currentYear','currentMonth','inputDay','currentHour','currentMinute'];
				var propertyLength = [4,2,2,2,2];
				for(var i=0;i<elements.length;i++) {
					if(positionArray[elements[i]]>=0) {
						window[properties[i]] = inputField.value.substr(positionArray[elements[i]],propertyLength[i])/1;
					}					
				}			
				currentMonth--;
			}else{
				var monthPos = format.indexOf('mm');
				currentMonth = inputField.value.substr(monthPos,2)/1 -1;
				var yearPos = format.indexOf('yyyy');
				currentYear = inputField.value.substr(yearPos,4);
				var dayPos = format.indexOf('dd');
				tmpDay = inputField.value.substr(dayPos,2);

				var hourPos = format.indexOf('hh');
				if(hourPos>=0){
					tmpHour = inputField.value.substr(hourPos,2);
					currentHour = tmpHour;
					if(currentHour.length==1) currentHour = '0'
				}else{
					currentHour = '00';
				}
				var minutePos = format.indexOf('ii');
				if(minutePos>=0){
					tmpMinute = inputField.value.substr(minutePos,2);
					currentMinute = tmpMinute;
				}else{
					currentMinute = '00';
				}
			}
		}else{
			var d = new Date();
			currentMonth = d.getMonth();
			currentYear = d.getFullYear();
			currentHour = '08';
			currentMinute = '00';
			inputDay = d.getDate()/1;
		}

		inputYear = currentYear;
		inputMonth = currentMonth;

		if(!calendarDiv){
			initCalendar();
		}else{
			if(calendarDiv.style.display=='block'){
				closeCalendar();
				return false;
			}
			writeCalendarContent();
		}

		returnFormat = format;
		returnDateTo = inputField;
		positionCalendar(buttonObj);
		calendarDiv.style.visibility = 'visible';
		calendarDiv.style.display = 'block';

		if(iframeObj){
			iframeObj.style.display = '';
			iframeObj.style.height = '140px';
			iframeObj.style.width = '195px';
					iframeObj2.style.display = '';
			iframeObj2.style.height = '140px';
			iframeObj2.style.width = '195px';
		}

		setTimeProperties();
		updateYearDiv();
		updateMonthDiv();
		updateMinuteDiv();
		updateHourDiv();
	}

	function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj) {

		//lert("function displayCalendarSelectBox START");

		if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true;

		currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
		currentYear = yearInput.options[yearInput.selectedIndex].value;
		if(hourInput){
			currentHour = hourInput.options[hourInput.selectedIndex].value;
			inputHour = currentHour/1;
		}

		if(minuteInput){
			currentMinute = minuteInput.options[minuteInput.selectedIndex].value;
			inputMinute = currentMinute/1;
		}

		inputYear = yearInput.options[yearInput.selectedIndex].value;
		inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
		inputDay = dayInput.options[dayInput.selectedIndex].value/1;


		if(!calendarDiv){
			initCalendar();
		}else{
			writeCalendarContent();
		}

	//lert("Leon E");

		returnDateToYear = yearInput;
		returnDateToMonth = monthInput;
		returnDateToDay = dayInput;
		returnDateToHour = hourInput;
		returnDateToMinute = minuteInput;
	
		returnFormat = false;
		returnDateTo = false;
		positionCalendar(buttonObj);
		calendarDiv.style.visibility = 'visible';
		calendarDiv.style.display = 'block';
		if(iframeObj){
			iframeObj.style.display = '';
			iframeObj.style.height = calendarDiv.offsetHeight + 'px';
			iframeObj.style.width = calendarDiv.offsetWidth + 'px';
			//// fix for EI frame problem on time dropdowns 09/30/2006
			iframeObj2.style.display = '';
			iframeObj2.style.height = calendarDiv.offsetHeight + 'px';
			iframeObj2.style.width = calendarDiv.offsetWidth + 'px'
		}
		setTimeProperties();
		updateYearDiv();
		updateMonthDiv();
		updateHourDiv();
		updateMinuteDiv();
	}

	//	E N G L I S H     T A P    A D D I T I O N A L  js ()		English Tap additional functions	

	function ET_clocks() {

		//	This function requires a set of DIVs on the page with specific IDs  for the times to be shown
		//lert("function show_clock() START  zone_offset ");
		// other_date=new Date();

		Date.prototype.addHours = function (n) {this.setHours (this.getHours () + n)}

		now=new Date();
		gmt=new Date();

		gmt.setMinutes(now.getMinutes() - (gmt_diff * 60) );

		ext_gmt=formatDate(gmt,"MMdd");
		time_o_year=parseFloat(ext_gmt);

		out_time=formatDate(gmt,"NNN dd yyyy HH:mm:ss");
		$('.gmt_time').html(out_time);

			//	L O N D O N Add 1 hour for London time if DST else add nothing 
		var london_time=new Date();
		london_time.setMinutes(now.getMinutes() - (gmt_diff * 60) );

			// D:S:T test may be wrong each year as the clocks go back on Saturday not a specific day.

		if ((time_o_year>326) && (time_o_year<1031)) {dst=1;} else {dst=0;}

		if (dst==true) { 
			london_time.addHours(1);
			gmt_plus="GMT+1";
		} else {
			///// london_tme.setMinutes(gmt.getMinutes());
			gmt_plus="GMT+0";
		} 
		out_time=formatDate(london_time,"HH:mm:ss");
		$('.london_time').html(out_time);
		$('.london_gmt').html(gmt_plus);

			//	N E W    Y O R K
		var ny_time=new Date();
		if (dst==true) {
			ny_time.addHours(0-gmt_diff-6);
			gmt_plus="GMT-6";
		} else {
			ny_time.addHours(1-gmt_diff-5);
			gmt_plus="GMT-5";
		} 
		out_time=formatDate(ny_time,"HH:mm:ss");
		$('.newyork_time').html(out_time);
		$('.newyork_gmt').html(gmt_plus);

			//	O T T A W A   C A N A D A   subtract 4 hours fromo GMT for Ottawa time if DST else add 1 
		var ottawa_time=new Date();
		if (dst==true) {
			ottawa_time.addHours(0-gmt_diff-4);
			gmt_plus="GMT-4";
		} else {
			ottawa_time.addHours(1-gmt_diff-4);
			gmt_plus="GMT-3";
		} 
		out_time=formatDate(ottawa_time,"HH:mm:ss");
		$('.ottawa_time').html(out_time);
		$('.ottawa_gmt').html(gmt_plus);


			//	C E N T R A L  E U R O P E A N   T I M E Add 2 hours to GMT for CET time if DST else add 1 
		var cet_time=new Date();
		if (dst==true) {
			cet_time.addHours(2-gmt_diff);
			gmt_plus="GMT+2";
		} else {
			cet_time.addHours(1-gmt_diff);
			gmt_plus="GMT+1";
		} 
		out_time=formatDate(cet_time,"HH:mm:ss");
		$('.cet_time').html(out_time);
		$('.cet_gmt').html(gmt_plus);

			//	M O S C O W  T I M E Add 3 hours to GMT for Moscow time if DST else add 2 
		var moscow_time=new Date();
		if (dst==true) {
			moscow_time.addHours(4-gmt_diff);
			gmt_plus="GMT+4";
		} else {
			moscow_time.addHours(3-gmt_diff);
			gmt_plus="GMT+3";
		} 
		out_time=formatDate(moscow_time,"HH:mm:ss");
		$('.moscow_time').html(out_time);
		$('.moscow_gmt').html(gmt_plus);

			//	V I E T N A M   T I M E  Add SEVEN 7 hours to GMT for Vietnam with no DST 
		var vn_time=new Date();
		vn_time.addHours(7-gmt_diff);
		out_time=formatDate(vn_time,"HH:mm:ss");
		$('.vietnam_time').html(out_time);
		$('.vietnam_gmt').html("GMT+7");

			//	T H A I L A N D   T I M E Add SEVEN 7 hours to GMT for Thailand with no DST 
		var th_time=new Date();
		th_time.addHours(7-gmt_diff);
		out_time=formatDate(th_time,"HH:mm:ss");
		$('.thai_time').html(out_time);
		$('.thai_gmt').html("GMT+7");

			//		C H I N A	T I M E 
			// Add EIGHT 8 hours to GMT for China Time with no DST
		var cn_time=new Date();
		cn_time.addHours(8-gmt_diff);
		out_time=formatDate(cn_time,"HH:mm:ss");
		$('.china_time').html(out_time);
		$('.china_gmt').html("GMT+8");

			//		B R A T S K  I R K U T Z   - Same as China except when +1 due to DST
			//	Add 8 hours to GMT if DST add 1 more
		var bratsk_time=new Date();
		if (dst==true) {
			bratsk_time.addHours(9-gmt_diff);
			gmt_plus="GMT+9";
		} else {
			bratsk_time.addHours(8-gmt_diff);
			gmt_plus="GMT+8";
		} 
		out_time=formatDate(bratsk_time,"HH:mm:ss");
		$('.bratsk_time').html(out_time);
		$('.bratsk_gmt').html(gmt_plus);

		//		J A P A N 	T I M E 
		// Add NINE 9 hours to GMT for Japan Time with no DST  
		var jp_time=new Date();
		jp_time.addHours(9-gmt_diff);
		out_time=formatDate(jp_time,"HH:mm:ss");
		$('.japan_time').html(out_time);
		$('.japan_gmt').html(" GMT+9");

		//	A U S T R A L I A N   - Standard time  Add NINE 10 hours to GMT for Aus Brisbane, Sydney  
		//	Australia observes DST but it occurs at different times of the year to European DST 

		var jp_time=new Date();
		jp_time.addHours(10-gmt_diff);
		out_time=formatDate(jp_time,"HH:mm:ss");
		$('.australia_time').html(out_time);
		$('.australia_gmt').html(" GMT+10");

		//lert("function ET_clocks() COMPLETE ");

	}

		//	C A L E N D A R 	F U N C T I O N S 
		//	===============		=================

	function AD_events_menu(menu_opts) {

		$('#toggle_external').html("");
		setActive("toggle_external");

		//lert("AD_events_menu() ");
		menu_array=(menu_opts+"||||").split("|");
		etpage=menu_array[0];

		$('#toggle_external').load(window.php+"events_menu.php",{'etpage':[etpage]
		,'gmt_diff':[window.gmt_diff]
		,'roles':[window.roles]});
		//lert("AD_events_menu() ");
		return;
	}

	function AD_event_form(event_string)  {

		// This shows the toggle only when it's ready. Using the call back function. 
		// Could even show a gif to show that the page is loading

		if (window.userid=='1') {
			ET_error("Guests are not allowed to create events. Sign on to create a lesson request or event.");
			return;
		}
		
		event_settings=(event_string+"|||||||||").split("|");
		event_id=event_settings[0];
		etpage=event_settings[1];
		$('#toggle_external').load(window.php+"event_form.php",{'etpage':[etpage]
		,'event_id':[event_id]
		,'regress':[window.regress]
		,'roles':[window.roles]
		,'gmt_diff':[window.gmt_diff]}, function (){setActive("toggle_external");});
		return;
	}

	function AD_event_help(keyword) {
		switch(keyword) {
		case('students'):
			message_text="You can enter a single student user id here if this event is a one-to-one ";
			message_text+=" or leave it blank if you are entering a group event ";
			message_text+=" Hover your mouse over their name in moodle or in the chat to see their id. ";
			break;
		case("type"):
			message_text="The calendar <b>event type</b> determines who can view this event and what this event is.";
			message_text+=" Conference events may be seen by anybody. Your availability can only be seen by your students and admin. ";
			break;
		default:
			message_text="No help for "+keyword;
			break;
		}
		$('#event_message').html(message_text);
	}

	function AD_event_update(event_string)  {

		// This function must match up with the ids in /php_@version/event_form.php 

		//lert("function AD_event_update() started ");

		$("#event_error").html("");	// Start with a clear red error message 
		$("#event_message").html("");	// Start with a clear green message 

		event_array=(event_string+"||||").split("|");

		// All mdl_event columns with default values
		event_id=event_array[0]; // If an id is passed in, we Any id 
		event_name='';
		event_format='1';
		event_courseid='';
		event_groupid=$("#event_groupid").val();
		event_userid=$("#event_teacher").val();

		event_repeatid='';
		event_modulename='English';
		event_instance='';
		event_eventtype='';
		event_timestart='';
		event_visible='0';
		event_uuid='';
		event_sequence='';
		event_timemodified='@timestamp';

		// C O L L E C T - D A T E     from simple ddmmyy 
		currentTime = new Date();
		month = currentTime.getMonth() + 1;
		day = currentTime.getDate();
		year = currentTime.getFullYear();
		yy='20';

		event_date_string=$('#event_date').val();
		event_array=(event_date_string+"....").split(".");

		event_day=event_array[0];
		event_year=event_array[2];
		event_month=event_array[1].lpad("0",2);

//		NO DEFAULT DAY - default year and month ok ONLY if day has been entered to avoid mistakes
		if(event_year=='') {event_year=year;}
		if(event_year.length==2) {event_year=yy+event_year;}
		if(event_month=='') {event_month=month;}

		// C O L L E C T - T I M E      from simple hh:mm
		event_time=$('#event_time').val();
		event_time=event_time.replace(/\./g,":"); // Allow input delimiter DOT

		time_array=(event_time+"::").split(":");
		event_hour=time_array[0];
		event_minute=time_array[1];

		// THIS IS FOR DATE SELECTIONS 

		// event_year=$('#event_year').val();
		// event_month=$('#event_month').val();
		// event_day=$('#event_day').val();
		// event_hour=$('#event_hour').val();
		// event_minute=$('#event_minute').val();

		event_timeduration=$('#event_duration').val();

		//   NOT NEEDED in php form 
		// db_row_id=$('#event_row_id').val();

		repeats=0;	// removed from php_@version/event_form.php !!!

/*

			// repeats=getCheckedValue('repeats')
		repeats_no=document.getElementById("repeats_no").checked;
		repeats_daily=document.getElementById("repeats_daily").checked;
		repeats_weekly=document.getElementById("repeats_weekly").checked;

		if(repeats_no==true) {
			repeats=0;
		} else {
			if(repeats_daily==true) {
				repeats=1;
			} else {
				repeats=2;
			}
		}
*/

		//yyyy,NNN,dd,HH,mm

		// P A D D I N G s

		date_string=event_year+event_month.lpad("0",2)+event_day.lpad("0",2)+event_hour.lpad("0",2)+event_minute.lpad("0",2);
		event_timestart=getDateFromFormat(date_string,"yyyyMMddHHmm");

		if(event_timestart=='') {
			ET_error("Invalid date entered : "+date_string);
			return false;
		}

		event_milliseconds=event_timestart.getTime();
		event_timestart=Math.round(event_milliseconds/1000);	// unix timestamp in seconds

		//lert("date string: "+date_string+" unix time stamp : "+event_timestart);

		event_description=$('#event_description').val();
		event_description=fix_quotes(event_description);

		if (event_description.length<5) {
			ET_error("Event description must be longer");
			return false;
		}

		// V A L I D A T E 	The 	F O R M 	D A T A 	
		// O N L Y - F U T U R E - (Unless Repeating)

		//	N O W 	W E     A L L O W      C R E A T I O N     O F    E V E N T S    I N    T H E    P A S T !!!
		//	Perhaps admins only shoul dbe able to do this.
		//		if (event_time<=now) {
		//			$("#"+dom_prefix+"error").html("Must not be in the past");
		//			return false;
		//		}

		// D U R A T I O N - Must exceed 15 minutes

		// C L I E N T   S I D E   V A L I D A T I O N     P A S S E D  
		//	Sending to the server. FIRST put the data into the hidden divs 
		//	so that the php function can pick it up pre-formatted

		event_name=$('#event_name').val();
		event_name=fix_quotes(event_name);

		single_student_id=$('#single_student').val();
		event_uuid=single_student_id;

		sql_query='';
		if(event_id=='') {
			sql_query=sql_query+"INSERT ";
			sql_query=sql_query+"";
			sql_query=sql_query+"INTO mdl_event (name ";
			sql_query=sql_query+",description ";
			sql_query=sql_query+",format";
			sql_query=sql_query+",courseid";
			sql_query=sql_query+",groupid";
			sql_query=sql_query+",userid";
			sql_query=sql_query+",repeatid";
			sql_query=sql_query+",modulename";
			sql_query=sql_query+",instance";
			sql_query=sql_query+",eventtype";
			sql_query=sql_query+",timestart";
			sql_query=sql_query+",timeduration";
			sql_query=sql_query+",visible";
			sql_query=sql_query+",uuid";
			sql_query=sql_query+",sequence";
			sql_query=sql_query+",timemodified)";

			sql_query=sql_query+" VALUES ('"+event_name+"' ";
			sql_query=sql_query+",'"+event_description+"' ";
			sql_query=sql_query+",'"+event_format+"' ";
			sql_query=sql_query+",'"+event_courseid+"' ";
			sql_query=sql_query+",'"+event_groupid+"' ";
			sql_query=sql_query+",'"+event_userid+"' ";
			sql_query=sql_query+",'"+event_repeatid+"' ";
			sql_query=sql_query+",'"+event_modulename+"' ";
			sql_query=sql_query+",'"+event_instance+"' ";
			sql_query=sql_query+",'"+event_eventtype+"' ";
			sql_query=sql_query+",'"+event_timestart+"' ";
			sql_query=sql_query+",'"+event_timeduration+"' ";
			sql_query=sql_query+",'"+event_visible+"' ";
			sql_query=sql_query+",'"+event_uuid+"' ";
			sql_query=sql_query+",'"+event_sequence+"' ";
			sql_query=sql_query+",'"+event_timemodified+"') ";
			// INSERT INTO example (name, age) VALUES("Timmy Mellowman", "23" ) 
		}  else {

			//	O N L Y     I N C L U D E   C O L U M N S   F R O M    T H E   S C R E E N 
			//	F O R    UPDATE 
			//	or they will be nulled out!! 

			sql_query=sql_query+"UPDATE mdl_event SET ";
			sql_query=sql_query+" name = '"+event_name+"' ";
			sql_query=sql_query+" , description = '"+event_description+"' " ;
			sql_query=sql_query+" , timestart = '"+event_timestart+"' " ;
			sql_query=sql_query+" , timeduration = '"+event_timeduration+"' " ;
			sql_query=sql_query+" , repeatid = '"+event_repeatid+"' " ;
			sql_query=sql_query+" , uuid = '"+event_uuid+"' " ;
			sql_query=sql_query+" , userid = '"+event_userid+"' ";
			sql_query=sql_query+" , eventtype = '"+event_eventtype+"' " ;
			sql_query=sql_query+" , timemodified = '"+event_timemodified+"' " ;
			sql_query=sql_query+" WHERE id  = '"+event_id+"' ";
		}
		//lert("QUERY "+sql_query);
		ET_sql_interface(sql_query);
		//lert("function AD_event_update() completed the query "+sql_query);
		return false;
	}

		//	F A U L T	R E C O R D I N G	Functions 
		//	=========	=================	=========
	
	function ET_fault_update(fault_defn)  {

		//	Adds to the etlw_problem TABLE
		//	the DOMs DIV IDs with a dom_label 

		$("#fault_error").html(""); // Start with a clear error message 

		// C O L L E C T - data and 	
		fault_id=$('#fault_id').val();
		fault_name=$('#fault_name').val();
		fault_webpage=$('#fault_page').val();
		fault_type=$('#fault_type').val();
		fault_description=$('#fault_description').val();
		
		// RADIO BUTTON EXAMPLE 
		// repeats_no=document.getElementById(dom_prefix+"repeats_no").checked;

		//lert("Preparing to update fault : " + fault_id);

		if (fault_description.length<5) {
			$("#fault_error").html("Fault description must be entered missing");
			return false;
		}

		// V A L I D A T E 	The 	F O R M 	D A T A 

		// O N L Y - F U T U R E - (Unless Repeating)

		// C L I E N T   S I D E   V A L I D A T I O N     P A S S E D  
		//	Sending to the server. FIRST put the data into the hidden divs 
		//	so that the php function can pick it up pre-formatted


		sql_query='';
		if(fault_id=='') {
			sql_query=sql_query+"INSERT ";
			sql_query=sql_query+"";
			sql_query=sql_query+"INTO etlw_faults (name ";
			sql_query=sql_query+",description ";
			sql_query=sql_query+",webpage";
			sql_query=sql_query+",userid";
			sql_query=sql_query+",type";
			sql_query=sql_query+",timecreated";
			sql_query=sql_query+",timemodified)";

			sql_query=sql_query+" VALUES ('"+fault_name+"' ";
			sql_query=sql_query+",'"+escape(fault_description)+"' ";
			sql_query=sql_query+",'"+fault_webpage+"' ";
			sql_query=sql_query+",'"+window.userid+"' ";
			sql_query=sql_query+",'"+fault_type+"' ";
			sql_query=sql_query+",'@timestamp' ";
			sql_query=sql_query+",'@timestamp') ";
			// INSERT INTO example (name, age) VALUES("Timmy Mellowman", "23" ) 
		}  else {

			//	O N L Y     I N C L U D E   C O L U M N S   F R O M    T H E   S C R E E N 
			//	F O R    UPDATE 
			//	or they will be nulled out!! 

			sql_query=sql_query+"UPDATE etlw_fault SET ";
			sql_query=sql_query+" name = '"+fault_name+"' ";
			sql_query=sql_query+" , description = '"+fault_description+"' " ;
			sql_query=sql_query+" , webpage = '"+fault_webpage+"' " ;
			sql_query=sql_query+" , userid = '"+window.userid+"' " ;
			sql_query=sql_query+" , type = '"+fault_repeatid+"' " ;
			sql_query=sql_query+" , timecreated = '@timestamp' " ;
			sql_query=sql_query+" , timemodified = '@timestamp' " ;
			sql_query=sql_query+" WHERE id  = '"+fault_id+"' ";
		}

		//lert("QUERY "+sql_query);
		ET_sql_interface(sql_query);

		$("#fault_message").html("This problem has been added to the database.");

		// Clear the form ready for creating a new problem record
		//lert("Clearing problem form  ");
		$("#fault_work").html('');
		$("#fault_id").val('');
		$("#fault_name").val('');
		$("#fault_page").val('');
		$("#fault_description").val('');

		//lert("function ET_fault_update() COMPLETE ");
		return false;
	}

	function display_errmsg(text) {
		setActive('user_message');
		$('#user_message_text').html(text);
	}


	//	S Q L      I N T E R F A C E
	function ET_sql_interface(update_string) {

		//lert("function ET_sql_interface() started ");
		//	JS escape() >> PHP urldecode() to pass all the slashes etc.,

		sql_defn=(update_string+"||||").split("|");

			//	1st The query
		sql_query=sql_defn[0];
		sql_query=ET_trim(sql_query);

			//2nd the load div
		sql_div=sql_defn[1]; if(sql_div=='') {sql_div='report_data';}

			//3rd the main heading h1
		sql_heading=sql_defn[2]; 
		sqldata=sql_div+"|"+sql_heading;

		// 4th wrappers for data formatting etc.,
		// FORWARD SLASH deimiter as these are inside the PIPE delimiter and art pre-determined codes eg. 'timestamp' 'chatuser' , ..
		wrappers=sql_defn[3];
		message_supress=sql_defn[4];
		afm=sql_defn[5];	// ALTERNATIVE Query FAILURE MESSAGE	

		$(".toggle").hide();
		setActive(sql_div);

		$('#'+sql_div).html("");
		$('#'+sql_div).load(window.php+"sql_interface.php",{'regress':[window.regress]
		,'query':[sql_query]
		,'userid':[window.userid]
		,'wrappers':[wrappers]
		,'header':[sql_heading]
		,'message_supress':[message_supress]
		,'afm':[afm]
		,'gmt_diff':[window.gmt_diff]
		,'roles':[window.roles]});
		//lert("function ET_sql_interface() completed query "+sql_query);
		return;
	}

	function AD_event_search(search_string) {

		//	This comes after the FORM submission for member search
		//	Pick up fields from specific search form ids	

		part_student_name=$('#es_student_username').val();

		// Build A L L	user selection criteria into a string of AND conditions
		special_select=' AND u2.username LIKE "%'+part_student_name+'%" ';
		search_string="admin|5000000000|B|"+special_select;

		//lert("Listing events for user name LIKE "+part_student_name);
		// Now decide what to do with this 
		AD_event_list(search_string);
		return false;
	}

	function AD_event_list(calopts) {

		//lert("function AD_show_calendar() start ");

		//	pass userid > show :
		//		a) Events where the event groupid+userid matches a row from mdl_group_members
		//		b) 
		//	Get the group list in PHP and not from Session from js
		
		maxrows=7;
		calendar_array=(calopts+"||||").split("|");
		etpage=calendar_array[0];		//	Was this called from the 'admin' page or the 'chat' ?
		navi_timestamp=calendar_array[1];	//	Optional timestamp marker for place in the report

		navi_direction=calendar_array[2];	//	(F)orward or (B)ack 

		calendar_load_div=calendar_array[3];
		if(calendar_load_div=='') {calendar_load_div='report_data';}
	 	//	Default (B)ack from the last timestamped row on the table	
		if(navi_direction=='') {
			navi_timestamp="5000000000";
			navi_direction='B';
		}
		selection_criteria=calendar_array[4];	//	Selection criteria entered by report user
		
		setActive(calendar_load_div);

		$('#'+calendar_load_div).load(window.php+"event_list.php",{'userid':[window.userid]
		,'navi_timestamp':[navi_timestamp]
		,'navi_direction':[navi_direction]
		,'maxrows':[maxrows]
		,'lang':[window.lang]
		,'roles':[window.roles]
		,'etpage':[etpage]
		,'regress':[window.regress]
		,'selection_criteria':[escape(selection_criteria)]
		,'gmt_diff':[window.gmt_diff]});

		//lert("function AD_event_list() complete "+php);
		return;
	}

	// mdl_groups 

	function AD_group_list(string)  {

		if(window.userid=='1') {
			ET_error("Groups are for members only. Please sign up. ");
			return;
		}

		group_array=(string+"||||").split("|");
		sel_user=group_array[0];	// optional user that must be a member of the listed groups
		if(sel_user!=window.userid) {window.sid=sel_user;}

		ET_load(window.php+"groups_list.php");

		//lert("function AD_group_list() complete ");
		return;
	}

	function AD_group_members(string)  {

		if(ET_role_check('1,2,3')==false) {
			ET_error("You don't have permission to list group members. Only admins and course admins can list group members.");
			return;
		}

		group_array=(string+"||||").split("|");
		group_id=group_array[0];
		$('#report_data').html("");
		setActive('report_data');
		$('#report_data').load(window.php+"group_members_list.php",{'userid':[window.userid]
		,'admin':[window.admin]
		,'teacher':[window.teacher]
		,'course_admin':[window.course_admin]
		,'group_id':[group_id]
		,'regress':[window.regress]
		,'roles':[window.roles]
		,'gmt_diff':[window.gmt_diff]});
		//lert("function AD_group_members() complete ");
		return;
	}

	//
	//	English Tap COOKIE FUNCTIONS
	//	S A V E      F O R M      F I E L D     
	//	S E L E C T I O N S   I N   C O O K I E S 
	//	instructions:

	//	All values to be saved are marked up with a class. EG my_class
	//	Change <body>
	//		<body onload="ET_getit('my_class');" onunload="ET_saveit('my_class');">


	function ET_saveit(param_string){

		// Get all values class="saveit"
		et_settings=(param_string+"||||").split("|");
		element_class=et_settings[0];
		//lert("saving all element values where class = "+element_class);

		elems=$('.' + element_class);
		em_count=elems.length;

		for (en=0; en<em_count; en++) {
			element_id=elems[en].id;
			// Name the cookie after the class with a sequence suffix _
			cookieName=element_class+"_"+en;
			fieldValue=$('#'+element_id).val();
			// Now save it
			// Expire cookie in 50 days.
			var today=new Date();
			var expires=new Date(today.getTime()+50*24*60*60*1000);
			setCookie(cookieName,fieldValue,expires);
		}

	 }

	function ET_getit(param_string) {

		// Get all COOKIES values class="saveit"

		et_settings=(param_string+"||||").split("|");
		element_class=et_settings[0];
		//lert("getting class : "+element_class);

		elems=$('.' + element_class);
		em_count=elems.length;

		for (en=0; en<em_count; en++) {
			element_id=elems[en].id;
			// Name the cookie after the class with a sequence suffix _
			cookieName=element_class+"_"+en;
			fieldValue=getCookie(cookieName);
			//lert("getting id "+element_id+" cookie value loaded = '"+fieldValue+"' ");
			$('#'+element_id).val(fieldValue);
		}

	}	

	function setCookie(name, value, expires, path, domain, secure) {

		//	USED WHEN SAVING A COOKIE
		//lert("Leon setCookie value=" + value);

		document.cookie= name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	}

	function getCookie(name) {

		var dc = document.cookie;

		//lert("function getcookie!! dc=[" + dc + "]");

		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);

		if (begin == -1) {
			begin = dc.indexOf(prefix);
			if (begin != 0)	{
				//lert("Cookie not found ");
				return null;
			}
		} else {
			begin += 2;
		}

		var end = document.cookie.indexOf(";", begin);

		if (end == -1)	{end = dc.length;}

		cookiechunk= unescape(dc.substring(begin + prefix.length, end));
		//lert("Found cookie " + cookiechunk);
		return cookiechunk;
	}

	//	D A T E  A N D    T I M E
	months='January,February,March,April,May,June,';
	months+='July,August,September,October,November,December,';
	months+='Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
	MONTH_NAMES=months.split(',');

	days='Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sun,Mon,Tue,Wed,Thu,Fri,Sat';
	DAY_NAMES=days.split(',');

	curDateTime = new Date();
	window.gmt_diff=(-curDateTime.getTimezoneOffset()/60);

	function ET_milliseconds_Hms(d) {
		dsecs = Number(d/1000);
		var h = Math.floor(dsecs / 3600);
		var m = Math.floor(dsecs % 3600 / 60);
		var s = Math.floor(dsecs % 3600 % 60);
		return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s);
	}

	if (!Array.prototype.indexOf) {
		Array.prototype.indexOf = function(elt /*, from*/) {
			var len = this.length;
			var from = Number(arguments[1]) || 0;
			from = (from < 0)
			? Math.ceil(from)
			: Math.floor(from);
			if (from < 0)
			from += len;
			for (; from < len; from++){
				if (from in this &&
				this[from] === elt)
				return from;
			}
			return -1;
		};
	}

	function array(items) {
		try {
			return Array.prototype.concat.call(items);
		} catch (ex) {
			var i       = 0,
			len     = items.length,
			result  = Array(len);

			while (i < len) {
				result[i] = items[i];
				i++;
			}
			return result;
		}
	}

var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

	var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

	};

	var arrayOfRolloverClasses = new Array();
	var arrayOfClickClasses = new Array();
	var activeRow = false;
	var activeRowClickArray = new Array();

	BrowserDetect.init();

	if(BrowserDetect.OS.indexOf("iPhone/iPod")>=0) {iPod=true;} else {iPod==false;}

	function fix_quotes(string) {
		string=string.replace(/"/g,"&#34;");
		string=string.replace(/'/g,"&#39;");
		return string;
	}

	function random_letters(parameter_string) {
		random_array=(parameter_string+"|||").split("|");
		output_id=random_array[0];
		string_length=random_array[1];

		//lert("function random_letters() started. Will output letters to "+output_id);

		var chars = "aaaaaaaaabbbbccccccddddddddeeeeeeeeeeeeffggggghhiiiiiiiiikllllmmnnnnnooooooooppqrrrrrrssssttttttuuuuvvwwxyyz";
		if (string_length=='') {string_length = 9;}

		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			// var rnum = Math.floor(Math.random() * chars.length);
			min=1;max=chars.length;
			rnum=getRandomInt(min, max);
			randomstring += chars.substring(rnum,rnum+1);
		}
		//lert("function random_letters() complete. Generated "+randomstring);
		$('#'+output_id).html(randomstring);

	}

	function getRandomInt(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}


//	T H E 	E N D 	



