var qk = function(){
	var r = {},
	$ = glow.dom.get,
	addListener = glow.events.addListener;

	//Cookie functions - thanks to quirksmode.org
	var setCookie = function(name,value,days) {
		var expires,date;
		if(days){
			date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = ["; expires=",date.toGMTString()].join('');
		}
		else{
			expires = "";
		}
		document.cookie = [name,"=",value,expires,"; path=/"].join('');
	};

	var getCookie = function(name) {
		var nameEQ = [name,"="].join('');
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while(c.charAt(0)==' '){
				c = c.substring(1,c.length);
			}
			if(c.indexOf(nameEQ)===0){
				return c.substring(nameEQ.length,c.length);
			}
		}
		return null;
	};

	var deleteCookie = function(name) {
		identity.util.setCookie(name,"",-1);
	};
	
	openPDFsInANewWindow = function(){
		$('a').each(function(e){
			var href = $(this).attr('href');
			if(href.substr(href.lastIndexOf('.')+1)=='pdf'){
				addListener($(this),'click',function(e){
					e.preventDefault();
					window.open(href,'pdf');
				});
			}
		});
	};
	
	setupExamTimetableControls = function(){
		var tables = $('table.timetable');
		if(!tables.length){
			return;
		}
		var dates = [];
		tables.each(function(e){
			var week = $(tables[e]); //this is a table
			var dateElements = week.get('.date');
			dates[dates.length] = $(dateElements[0]).text()+' - '+$(dateElements[dateElements.length-1]).text();
		});

		var controls = 
		'<form action="javascript:false" class="controls">'+
			'<div class="formline">'+
				'<label for="week">Select week:</label>'+
				'<select name="week">'+
					'<option value="0">Show all</option>';
		for(d in dates){
			controls += 
					'<option value="'+(Number(d)+1)+'"'+((d==0)?' selected="selected"':'')+'>'+dates[d]+'</option>';
		}
		controls +=
				'</select>'+
			'</div>'+
		'</form>';
		
		//insert the controls
		var controlsElement = glow.dom.create(controls);
		$('#week1').before(controlsElement).css('clear','both');
		
		var switchTable = function(thisTable){
			for(var i=0;i<tables.length;i++){
				var table = $(tables[i]);
				if(thisTable==0 || thisTable==i+1){
					table.css('display','block');
				}
				else{
					table.css('display','none');
				}
			}
		};
		
		//set up listener for controls
		addListener(controlsElement.get('select'),'change',function(){
			var week = $(this).val();
			switchTable(week);
		});
		
		switchTable(1);
	};
	
	var setupStore = function(){
		var storeCookieName = 'QK-STORE';
		
		// look for all studentname-container divs. Store them for later.
		var studentNameContainers = $('.studentname-container');
		
		//definte a function to update all the name fields with a new value and update the cookie also
		var updateAllNameFields = function(e){
			var name = $(this).val();
			
			studentNameContainers.each(function(){
				$(this).get('input').val(name);
			});
			
			setCookie(storeCookieName,name);
		};
		
		//define a quick validation function for the student name field
		var validateStudentName = function(name,opts){
			if(name.match(/^\s*$/)){
				if('onSuccess' in opts){
					opts.onFailure();
					return false;
				}
			}
			else{
				if('onSuccess' in opts){
					opts.onSuccess();
					return true;
				}
			}
		}
		
		// check for the QK-STORE cookie.
		var cookie = getCookie(storeCookieName);
		
		//crate an InfoPanel in case we need to show one
		var panel = new glow.widgets.InfoPanel(glow.dom.create('<p>Please enter the student\'s name!</p>'),{
			'id': 'infoPanelFormError',
			'width': 200
		});
		
		studentNameContainers.each(function(){
			var field = $(this).get('input');
			
			// If the cookie exists, populate the appropriate fields with the value.
			if(cookie != null){
				field.val(cookie);
			}
		
			// Then add a listener to the field to update all the other fields & set the cookie on blur
			addListener(field,'blur',function(){
				updateAllNameFields.call(this);
				validateStudentName(field.val(),{
					'onSuccess': function(){ //on success submit.
						panel.hide();
					},
					'onFailure': function(){ // on fail, show an info panel
						panel.setContext(field).show();
					}
				});
			},field);
		
			// Finally, add validation to prevent submitting without it.
			var form = $(this).parent().parent();
			addListener(form,'submit',function(e){
				e.preventDefault();
				var field = $(e.attachedTo).get('.studentname-container input');
				validateStudentName(field.val(),{
					'onSuccess': function(){ //on success submit.
						panel.hide();
						$(e.attachedTo)[0].submit();
					},
					'onFailure': function(){ // on fail, show an info panel
						panel.setContext(field).show();
					}
				});
			});
		});
	};
	
	r.init = function(){
		//parse for PDF links and set to open in new window, also fronter form.
		if(acrobatReaderInstalled()){
			openPDFsInANewWindow();
		}
		setupExamTimetableControls();
		setupStore();
	};
	
	return r;
}();









/* Function to detect the presence of Adobe Acrobat Reader plugin */
function acrobatReaderInstalled(){
	var acrobat=new Object();

	acrobat.installed=false;
	acrobat.version='0.0';

	if (navigator.plugins && navigator.plugins.length){
		for (x=0; x<navigator.plugins.length; x++){
			if (navigator.plugins[x].description.indexOf('Adobe Acrobat') != -1){
				
				acrobat.version=parseFloat(navigator.plugins[x].description.split('Version ')[1]);
				
				if (acrobat.version.toString().length == 1){
					acrobat.version+='.0';
				}

				acrobat.installed=true;
				break;
			}
		}
	}
	else if (window.ActiveXObject){
		for (x=2; x<10; x++){
			try{
				oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
				if (oAcro){
					acrobat.installed=true;
					acrobat.version=x+'.0';
				}
			}
			catch(e) {}
		}
		try{
			oAcro4=new ActiveXObject('PDF.PdfCtrl.1');
			if (oAcro4){
				acrobat.installed=true;
				acrobat.version='4.0';
			}
		}
		catch(e) {}
		try{
			oAcro7=new ActiveXObject('AcroPDF.PDF.1');
			if (oAcro7){
				acrobat.installed=true;
				acrobat.version='7.0';
			}
		}
		catch(e) {}
	}
	
	return acrobat.installed;
}

//QK object above this function!