var questionsObj = [];
var answerArray = [null,null,null,null,null,null];
var correctTotal = 0;
var timerSecs = 0; // count of timer in swf
var allAsnswersComplete = false;
var quizPostHasBeenMade = false;
var quizSlide = null;
var gTimeObj = []; // time object
var gDST_trigger; // state of daylight saving time


	function init(){
	var flashvars = {};
	var params = {loop: "false"};
	var attributes = {};
	swfobject.embedSWF("swf/animated_minute_timer.swf", "timerDiv", "400", "12", "9.0.0", false, flashvars, params, attributes, loadQuestions);
	}
	
	function loadQuestions(e){
	document.getElementById("startButton").disabled = true;
	document.getElementById("content_wrapper").style.position = "relative";	
	// set-up questions grid skeleton which is initially blank
	for(var i=0; i<6; i++){
	var thisBlock = ["","","",""];
	questionsObj.push(new makeQuestionsObjs(thisBlock, i)); // make blank table
	document.getElementById("questionsDiv").appendChild(questionsObj[questionsObj.length-1].DOM);
	}
	if(isItMonday()){document.getElementById("nudgeDiv").style.display="block"};
	getwinner();
	// check for Flash at this point now as page should look decent
	if (!e.success){
	document.getElementById("noFlashMessageDiv").innerHTML = "<h3>Sorry, your browser's Flash plug-in is not installed\nYou won't be able to do the Quiz!</h3>"
	return;
	}
	document.getElementById("startButton").disabled = false; // all OK so enable start button
	}
	
	
	
	function callActionscriptStop() {
		if (document.getElementById("timerDiv")) { 
			document.getElementById("timerDiv").triggerStop();
		}
	}
	
	function getwinner(){
	var ajaxRequest = setupAJAX();
	signup_email = document.getElementById("email").value;
	ajaxRequest.open("GET","php/quiz_get_winner_data.php", true);
	//read returned data from server and place it in div
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			document.getElementById("quiz_winner").innerHTML=ajaxRequest.responseText;
			}else{
			document.getElementById("quiz_winner").value= "Error in get winner info";
			}
	      }
	    }
	   ajaxRequest.send(null); 
	  }
	
	
	function startQuiz(){
	if( !cookieTest() ){
	document.getElementById("messageDiv").innerHTML = "<p style='color:red;'>Sorry, you need Cookies enabled in this browser to complete the quiz<p>";	
	return;	
	}
	var savedDate = readCookie("ziuq__");
	//registerWithDatabase();
	var today = getUKdate();
	var dateNow = getDayPlusMonth(today);
	if (savedDate != dateNow) {
	get_questions("php/get_quiz_questions.php", "questionsDiv"); // get questions and start timer
	document.getElementById("messageDiv").innerHTML = "";
	document.getElementById("startButton").disabled = true;
	try {
	quizSlide = new quizSlideObj();
	quizSlide.slideup("quizHideDiv");
	if(!quizSlide) document.getElementById("quizSubmitForm").style.display = "none"; // force close
	}catch(e){
	document.getElementById("quizSubmitForm").style.display = "none"; // force close in the face of any slide error
	document.getElementById("messageDiv").innerHTML = "<p>Sorry, there was an error</p>";
	}
	
	}else{
	document.getElementById("messageDiv").innerHTML = "<p style='color:red;'>Sorry, you have already completed today's quiz<p>";	
	}
	}
	
	function registerWithDatabase(){
		
		
		
	}
	
	function get_questions(url, div_id){
	allAsnswersComplete = false;
	quizPostHasBeenMade = false; // reset anti-bounce device
	questionsObj = []; // reset
	answerArray = [null,null,null,null,null,null];// reset
	correctTotal = 0;// reset
	timerSecs = 0; // reset
	var questionsDiv = document.getElementById("questionsDiv"); 
	if(div_id == null) return; // safety net
	var ajaxRequest = setupAJAX();
  	var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	ajaxRequest.open("GET",url+bustcacheparameter, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var returned_data = ajaxRequest.responseText;
			try{
			deleteprior(questionsDiv);
			var questionsBlocks = returned_data.split("**");
			for(var i=0; i<6; i++){
			var thisBlock = questionsBlocks[i].split("|");
		  	questionsObj.push(new makeQuestionsObjs(thisBlock, i));
			questionsDiv.appendChild(questionsObj[questionsObj.length-1].DOM);
	 		 }
			document.getElementById("timerDiv").triggerStart(); // call to start timer in Actionscript
			}catch(e){
			// trap but ignore error
			alert("Oops an error has occured - please close your browser and try again. If the error persists please report it to us.");
			}
			}else{
			document.getElementById(div_id).innerHTML= "<p style='color: #99ccff; text-align:center; font-family: Arial, Helvetica, sans-serif; font-size: 16px;'>Sorry &#150; this content appears to be missing or there was a problem with your Internet connection<br />Please try again.</p>";
			}
	      }
	    }
	   ajaxRequest.send(null); 
	  }
	  
	  function makeQuestionsObjs(thisBlock, qnum){
		var wrapperDiv = document.createElement("div");
		//wrapperDiv.style.cssText = "font-size: 1.1em;"
		var question = thisBlock[0];
		var questionPara = document.createElement("p");
		questionPara.style.cssText = "font-size: 1.1em; font-weight: bold; margin-bottom: 3px;";
		questionPara.innerHTML = (qnum+1) + ". " +question;
		wrapperDiv.appendChild(questionPara);
		var myTable = document.createElement("table");
		myTable.style.cssText = "width: 100%;  border-collapse:collapse; background-color:#ddd; border: 1px solid #ccc; margin-bottom: 12px;";
		myTable.setAttribute("class","questionBlock");
		var myTableBody = document.createElement("tbody");
		for(var i=1; i<4; i++){
		var row = document.createElement("tr");
		if (i % 2 == 0){
		row.style.cssText = "background-color: #eee; padding: 4px;";
		}else{
		row.style.cssText = "background-color: #ddd; padding: 4px;";	
		}	
		// create cell for answer
		//var text = document.createTextNode(thisBlock[i]);
		var mynewcell = document.createElement("td");
		//mynewcell.style.cssText = "padding: 4px; ";
		var answerPara = document.createElement("p");
		answerPara.style.cssText = "margin: 0; padding: 0px 0px 0px 3px; ";
		answerPara.innerHTML = thisBlock[i]; // to allow styling from db
		mynewcell.appendChild(answerPara);
		//mynewcell.appendChild(text);
		if(i == thisBlock[4]) this.mynewcell = mynewcell; // cell containing correct answer
		row.appendChild(mynewcell);
		// create cell for radio button
		var mynewcell = document.createElement("td");
		mynewcell.setAttribute("align","right");
		// create radio button allowing for IE quirks
		try {
    	// This seems the only way you can set the "name" attribute in IE
   		radioBut = document.createElement("<input name='radioBut" + qnum + "' type='radio' />");
		} catch(e) {
		radioBut = document.createElement("input");
		radioBut.setAttribute("type","radio");
		radioBut.setAttribute("name","radioBut"+qnum); // radio button name must be identical for each in its group
		}
		radioBut.answerNum = i;
		if(question != "") radioBut.onclick = function(){regAnswer(this.answerNum, thisBlock[4], qnum)}; // answer number (1-3), correct answer number, question number (1-6)
		mynewcell.appendChild(radioBut);
		row.appendChild(mynewcell);
		myTableBody.appendChild(row);
		}
		myTable.appendChild(myTableBody);
		wrapperDiv.appendChild(myTable);
		this.DOM = wrapperDiv;
		this.highlightCorrectAnswer = function(){
		this.mynewcell.style.color = "red";
		}
	  }
		
		
	  function regAnswer(answerNum, correctanswerNum, qnum){
		  if (allAsnswersComplete) return; // block changing answers after timer is stopped
		  if(answerNum == correctanswerNum){
			answerArray[qnum] = true ; 
		  }else{
			answerArray[qnum] = false;  
		  }
		// need to check if all answers have been given and if they are correct!
		correctTotal = 0;
		var totup = 0;
		for(var i=0; i<6; i++){
		if(answerArray[i] != null)	totup++;
		if(answerArray[i] == true)	correctTotal++;
		}
	  if (totup == 6) callActionscriptStop(); // all completed by user
	  }
	  
	  // this is triggered from ActionScript in swf animation
	  function quizComplete(timer){
		for(var i=0; i<6; i++){
		questionsObj[i].highlightCorrectAnswer();
		}
		timerSecs = timer; // pass to global
		switch(correctTotal){
			case 0:
			var message = "No correct answers. Oh dear - are you sure you are trying?";
			break;
			case 1:
			var message = correctTotal+" correct answer. Sorry, you'll have to do much better than that!";
			break;
			case 2:
			var message = correctTotal+" correct answers. Sorry, you'll have to do better than that!";
			break;
			case 3:
			var message = correctTotal+" correct answers. Sorry, only half right - some room for improvement.";
			break;
			case 4:
			var message = correctTotal+" correct answers. Not bad - you got most right.";
			break;
			case 5:
			var message = correctTotal+" correct answers. Well done, you just fell short of perfection.";
			break;
			case 6:
			var message = correctTotal+" correct answers. Well done, you must have eaten an encyclopedia!";
			setTimeout(togglequizSubmitForm,500); // slide down winners form panel after half a second (for effect!)
			break;
		}
		document.getElementById("endMessageDiv").innerHTML = "<p>You completed the quiz in "+timerSecs+" seconds with "+message+"</p>";
		
		/*  set today's day and month and save to cookie. We just want to be able to test for "same UK day" so it 
			will work across time zones
		*/
		var today = getUKdate();
		var dateToSave = getDayPlusMonth(today);
		createCookie("ziuq__",dateToSave,1); // set cookie to block further attempts at quiz. The clever dick's will delete it of course but no matter...
		allAsnswersComplete = true; // used to block answers being changed by still live radio buttons
	  }
	  
	 function endMessage(){
	 document.getElementById("messageDiv").innerHTML = "<h3>Time's Up!<h3>";
	 quizComplete(60);
	}
	
	function togglequizSubmitForm(){
	try {
	quizSlide = new quizSlideObj();
	quizSlide.slidedown("quizSubmitForm");
	if(!quizSlide) document.getElementById("quizSubmitForm").style.display = "block"; // force open anyway
	}catch(e){
	document.getElementById("quizSubmitForm").style.display = "block"; // force open in the face of any slide error
	}
	}
	
	function quizSubmit(){
	if (quizPostHasBeenMade) return; // prevents 'already submitted' masking 'Thank you' message if button is accidently hit twice
	var name = encodeURIComponent(document.getElementById("quiz_name").value);
	var location = encodeURIComponent(document.getElementById("quiz_location").value);
	var email = document.getElementById("quiz_email").value;
	if(name == "" || location == "" || email == ""){
	document.getElementById("entry_received_messageDiv").innerHTML = "Sorry, some fields are empty";
	return;
	}
	if(valid_email_check(email) == false){
	document.getElementById("entry_received_messageDiv").innerHTML = "Sorry, your email address appears to be malformed";
	return;
	}
	var cookieData = readCookie("ziuq__");
	if(cookieData == null || !cookieTest() ) {
	document.getElementById("entry_received_messageDiv").innerHTML = "Sorry, your cookie has been mysteriously disabled or deleted!";
	return;
	}
	email = encodeURIComponent(email);
	var poststring = "name="+name+"&email="+email+"&time="+timerSecs+"&location="+location+"&date="+cookieData;
	post_quiz_entry(poststring, "php/submit_quiz.php","entry_received_messageDiv"); // send entry data
	post_quiz_entry("email="+email,"php/quiz_entry_autoresponse_letter.php",false); // send 'thank you' email
	}
	
	function nudge_random(){
	var randomNum = Math.floor(Math.random()*9999);
	var poststring = "randomNum="+randomNum;
	post_data(poststring, "php/submit_quiz_random_num.php", "randomNumDiv");
	}
	
	function getUKdate(){
	var today = getUKTime();
	if (typeof today != "object") today = new Date(); // else get date from users computer as we need something
	return today;
	}
	
	// UK time calculations
	
	function getUKTime(){
	gTimeObj.dateobj = new Date();
   	var dst = EUSummer(gTimeObj.dateobj); // are we in dst?
    if (dst) {
        with (gTimeObj.dateobj) {
            setUTCHours(getUTCHours() + 1);
        }
    }
	if(dst != gDST_trigger){
	// detected change in DST	
	gDST_trigger = dst; // in the unlikely even it's still running in 6 months time
	}
	return toUKTime(gTimeObj.dateobj);
	};
	
	
	function EUch(Y, M) {
    var J = Date.UTC(Y, M - 1, 31);
    return J - 86400000 * ((4 + J / 86400000) % 7) + 3600000;
	};

	function EUSummer(obj) {
	var T = obj.valueOf();
	var Y = obj.getUTCFullYear();
	return T >= EUch(Y, 3) && T < EUch(Y, 10);
	};
	
	function toUKTime(obj){
	var year = obj.getUTCFullYear();
	var month = obj.getUTCMonth();
	var day = obj.getUTCDate();
	var hour = obj.getUTCHours();
	var minute = obj.getUTCMinutes();
	var second = obj.getUTCSeconds();
	return new Date(year,month,day,hour,minute,second);
	};
	
	
	function getDayPlusMonth(dateObj){
	var thisday = dateObj.getDate();
	var thismonth = dateObj.getMonth()+1;
	return thisday+"/"+thismonth;
	}
	
	function isItMonday(){
	// only show 'Nudge' button if it's between 10-12 a.m. on a Monday 'cos that's when the draw is
	var today = getUKdate(); // date obj
	if(today.getDay() == 1 && today.getHours() >= 10 && today.getHours() < 12){
		 return true;
		}else{
		return false;
		}
	}
	
	
	
	function cookieTest(){
	var cookieEnabled = (navigator.cookieEnabled)? true : false
	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled){ 
	document.cookie = "testcookie"
	cookieEnabled = (document.cookie.indexOf("testcookie")!=-1)? true : false
	}
	return cookieEnabled;
	}
	
	function slideInputPanel(){
	document.getElementById("question").onfocus = function(){document.getElementById("quizReturnedMessageDiv").innerHTML = ""};
	try {
	//quizSlide = new quizSlideObj();
	$("#questionsWrapperDiv").slideUp(300);
	//quizSlide.slideup("questionsWrapperDiv");
	}catch(e){
	document.getElementById("questionsWrapperDiv").style.display = "none"; // force open in the face of any slide error
	}
	getExamples();
	document.getElementById("sendtoQuizDB").onclick = function(){send_to_public_quiz_DB()};
	}
	
	function getExamples(){
	var questionsExamplesDiv = document.getElementById("questionsExamplesDiv"); 
	var ajaxRequest = setupAJAX();
	var url = "php/get_quiz_examples.php";
  	var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	ajaxRequest.open("GET",url+bustcacheparameter, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var returned_data = ajaxRequest.responseText;
			try{
			deleteprior(questionsExamplesDiv);
			var questionsBlocks = returned_data.split("**");
			for(var i=0; i<3; i++){
			var thisBlock = questionsBlocks[i].split("|");
		  	questionsObj.push(new makeQuestionsObjs(thisBlock, i));
			questionsExamplesDiv.appendChild(questionsObj[questionsObj.length-1].DOM);
	 		 }
			}catch(e){
			// trap but ignore error
			//alert("Oops an error has occured "+e);
			}
			}else{
			document.getElementById(div_id).innerHTML= "<p style='color: #99ccff; text-align:center; font-family: Arial, Helvetica, sans-serif; font-size: 16px;'>Sorry &#150; this content appears to be missing or there was a problem with your Internet connection<br />Please try again.</p>";
			}
	      }
	    }
	   ajaxRequest.send(null); 
	   
		
	}
	
	function post_quiz_entry(poststring, php_url, messageDiv){
	quizPostHasBeenMade = true;
	var ajaxRequest = setupAJAX();
	ajaxRequest.open("POST", php_url, true);
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var returned_message = ajaxRequest.responseText;
			if(messageDiv){
				document.getElementById(messageDiv).innerHTML = returned_message;
			}
			
			}else{
            document.getElementById(messageDiv).innerHTML = "Sorry, there was a server problem, please try again later.";
			quizPostHasBeenMade = false; // unset in the case of an error
            }
	      }
	    }
	ajaxRequest.send(poststring);

	}
	
	
	function send_to_public_quiz_DB(){
	var correct = 0;
	var question = 	document.getElementById("question").value;
	var a1 = 	document.getElementById("a1").value;
	var a2 = 	document.getElementById("a2").value;
	var a3 = 	document.getElementById("a3").value;
	if (document.getElementById("correct1").checked) correct = 1;
	if (document.getElementById("correct2").checked) correct = 2;
	if (document.getElementById("correct3").checked) correct = 3;
	if (a1 == "" || a2 == "" || a3 == "") {
	document.getElementById("quizReturnedMessageDiv").innerHTML ="Sorry, some fields are not filled in!";
	return;	
	}
	if(!correct){
	document.getElementById("quizReturnedMessageDiv").innerHTML = "Sorry, you need to select an answer!";
	return;
	}
	var poststring = 'question='+encodeURIComponent(question)+'&a1='+encodeURIComponent(a1)+'&a2='+encodeURIComponent(a2)+'&a3='+encodeURIComponent(a3)+'&correct='+correct;
	post_data(poststring, "php/send_quiz_data_to_public_DB.php", "quizReturnedMessageDiv");
	// reset fields
	document.getElementById("question").value = "";
	var a1 = 	document.getElementById("a1").value = "";
	var a2 = 	document.getElementById("a2").value = "";
	var a3 = 	document.getElementById("a3").value = "";
	// reset radio buttons
	document.getElementById("correct1").checked = false;
	document.getElementById("correct2").checked = false;
	document.getElementById("correct3").checked = false;
	}
	
	
	/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function valid_email_check(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
		}

	
	
