var scoreArray = new Array();
var scoreObjArray = new Array();
var aResultsText = new Array();
var aWeOfferText = new Array();
var atitlesText = new Array();
var aAllSectionText = new Array();
var aThisSectionText = new Array();


function printresults() {
	window.print();
}


function createRequest(request) {
	try{
		request=new XMLHttpRequest();
	}
	catch(trymicrosoft){
		try{
			request=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(othermicrosoft){
			try{
				request=new ActiveXObject("Microsoft.XMLHTTP");
			}
		catch(failed){
		request=null;
		}
		}
	}
	
	return request;
	
if(!request)
alert("Error initializing XMLHttpRequest!");
}


	var txtFile = createRequest(txtFile);
	//txtFile.open("GET", "http://demo.ambrit.co.uk/leyhill/oec/results_data.txt", true);
	txtFile.open("GET", "results_data.txt", true);
	txtFile.onreadystatechange = function() {
 	 if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
 	   if (txtFile.status === 200) {  // Makes sure it's found the file.
 	     allText = txtFile.responseText;
 	     aResultsText = txtFile.responseText.split("\r\n|\r\n"); // Will separate each line into an array
 	   }
 	 }
	}
	txtFile.send(null);



	//var txtFileOffer = new XMLHttpRequest();
	var txtFileOffer = createRequest(txtFileOffer);

	txtFileOffer.open("GET", "results_text_weoffer.txt", true);
	txtFileOffer.onreadystatechange = function() {
 	 if (txtFileOffer.readyState === 4) {  // Makes sure the document is ready to parse.
 	   if (txtFileOffer.status === 200) {  // Makes sure it's found the file.
	     allTextOffer = txtFileOffer.responseText;
 	   	 aWeOfferText = txtFileOffer.responseText.split("|\r"); // Will separate each block into an array
 	   }
	 }
	}
	txtFileOffer.send(null);
	
	
		
	//var txtFiletitles = new XMLHttpRequest();
	var txtFiletitles = createRequest(txtFiletitles);
	
	txtFiletitles.open("GET", "results_section_titles.txt", true);
	txtFiletitles.onreadystatechange = function() {
 	 if (txtFiletitles.readyState === 4) {  // Makes sure the document is ready to parse.
 	   if (txtFiletitles.status === 200) {  // Makes sure it's found the file.
	     allTexttitles = txtFiletitles.responseText;
 	   	 atitlesText = txtFiletitles.responseText.split("\r\n"); // Will separate each line into an array
 	   }
	 }
	}
	txtFiletitles.send(null);
	
	

	function toggle_visibility(id) {
		var e = document.getElementById(id);
		if(e.style.display == 'none')
			e.style.display = 'block';
		else
			e.style.display = 'none';
	}


function readScores(){
	var allcookies = document.cookie;
	var pos = allcookies.indexOf("selfAnalysisScore=");
	var pairName, pairValue, b;
	
	if(pos != -1) {
		var start = pos + 18; // chop 'selfAnalysisScore=' off of the front of the cookie
		var end = allcookies.indexOf(";", start);
		if(end == -1) end = allcookies.length;
		var value = allcookies.substring(start, end);
		value = decodeURIComponent(value);
	
		a = value.split('&');

		for(var i = 0; i < a.length; i++){
			b = a[i].split(':');
			pairName = b[0];
			pairValue = b[1];
			scoreArray[pairName] = pairValue;
		}
	}
}

function setScores(){

	readScores(); //read the existing scores into the scoreArray

	var cookieValue = '';
	var objValue, obj;


	for(var i = 0; i < scoreObjArray.length; i++){
		obj = scoreObjArray[i];
		objValue = '';
		
		if(!obj.valuePtr.type){		//collections of radio buttons/checkboxes don't have a type property set
			for(var j = 0; j < obj.valuePtr.length; j++){
				if(obj.valuePtr[j].checked) objValue += obj.valuePtr[j].value+', ';
			}
			if(objValue.length > 0) objValue = objValue.substring(0, objValue.length - 2);  //lose the final comma and space
		}
		else{
			switch(obj.valuePtr.type){
				case 'checkbox':
					objValue = obj.valuePtr.checked ? obj.trueString : obj.falseString;  //checkbox if truestring and falsestring defined
				 break;
				
				case 'select':
					objValue = obj.valuePtr[obj.valuePtr.selectedIndex].value;
					break;

				default:
					objValue = obj.valuePtr.value;	//this works for text, textarea
			}
		}
		
		scoreArray[obj.name] = objValue;	//add to this array so that cookie data from other pages is not lost
	}
	
	for(var name in scoreArray){
		if(name) cookieValue += name+ ":" + scoreArray[name] + "&"
	}

	cookieValue = cookieValue.substring(0, cookieValue.length - 1); // cut the trailing '&'
	cookieValue = encodeURIComponent(cookieValue);
	
	cookieValue = "selfAnalysisScore="+cookieValue;
	//cookieValue += cookieValue+"; max-age="+(60*60*24*365*5)+""; //set the expires time for roughly 5 years
	document.cookie = cookieValue;
}

function ScoreObject(name, valuePtr, trueString, falseString){

	this.name = name;
	this.valuePtr = valuePtr;
	this.trueString = trueString;
	this.falseString = falseString;

}

function registerScoreObject(name, valuePtr, trueString, falseString){
	
	scoreObjArray.push(new ScoreObject(name, valuePtr, trueString, falseString));

}

function totalScore(start, end){

	var score = 0;
	var factor = [,10, 10, 10, 10, 10, 15, 10, 10, 15];
	
	readScores();
	
	for(var i = start; i <= end; i++){
			if(scoreArray["step"+i]) score += (parseInt(scoreArray["step"+i]) * factor[i]);
	}
	return score;

}


function openCertificatePage(){

	var score = totalScore(1,9);

	//sendDetails();
		
	if(score < 50)
		document.location = 'result0.html';
	else if ((score >= 50) && (score <= 99))
		document.location = 'result1.html';
	else if ((score >= 100) && (score <= 149))
		document.location = 'result2.html';
	else if ((score >= 150) && (score <= 200))
		document.location = 'result3.html';
		
		
	else if ((score >= 200) && (score <= 249))
		document.location = 'result4.html';
	else if ((score >= 250) && (score <= 299))
		document.location = 'result5.html';
		
		
	else if ((score >= 300) && (score <= 349))
		document.location = 'result6.html';
	else if ((score >= 350) && (score <= 399))
		document.location = 'result7.html';
		
		
	else if ((score >= 400) && (score <= 449))
		document.location = 'result8.html';
	else if ((score >= 450) && (score <= 499))
		document.location = 'result9.html';
		
		
	else if ((score >= 500) && (score <= 525))
		document.location = 'result10.html';
		
		
	else if ((score >= 526) && (score <= 549))
		document.location = 'result11.html';
		
		
	else if ((score >= 550) && (score <= 599))
		document.location = 'result12.html';
	else if ((score >= 600) && (score <= 649))
		document.location = 'result13.html';
		
		
	else if ((score >= 650) && (score <= 699))
		document.location = 'result14.html';
	else if ((score >= 700) && (score <= 749))
		document.location = 'result15.html';
	else if ((score >= 750) && (score <= 799))
		document.location = 'result16.html';
		
		
	else if ((score >= 800) && (score <= 849))
		document.location = 'result17.html';
	else if ((score >= 850) && (score <= 899))
		document.location = 'result18.html';
	else if ((score >= 900) && (score <= 949))
		document.location = 'result19.html';
	else if ((score >= 950) && (score <= 1001))
		document.location = 'result20.html';
	
}

function sendDetails(){

	var form=document.getElementById("results");
	form.total.value = totalScore(1, 9);
	form.total1to5.value = totalScore(1, 5);
	form.total6to9.value = totalScore(6, 9);
	for(var i = 1; i <= 9; i++)
		form["step"+i].value = scoreArray["step"+i]+" (factored: "+totalScore(i,i)+")";
	form.name.value = scoreArray["name"];
	form.industry.value = scoreArray["sector"];
	form.employees.value = scoreArray["employees"];
	form.years.value = scoreArray["years"];
	form.email.value = scoreArray["email"];
	form.newsletter.value = scoreArray["newsletter"];
	form.managementsystems.value = scoreArray["managementsystems"];
	form.othermanagementsystems.value = scoreArray["othermanagementsystems"];
	form.submit();
	
}

// which text block we are using given the score
function scoreToTextBlockNo(value){
	if(value == 0) value=1;
	if (value%2 == 0)
		return (value/2)-1;
	else
		return ((value+1)/2)-1;
}

//exceptions to the rules - all references are zero indeded

function showThisItem(sectionIndex,currentBlockNo,item){

	if((scoreArray["managementsystems"].match("ISO 9001") != null) && (sectionIndex == 4) && (currentBlockNo == 1) && (item == 0)){
	return false;
	}
	if((scoreArray["managementsystems"].match("ISO 9001") != null) && (sectionIndex == 4) && (currentBlockNo == 2) && (item == 0)){
	return false;
	}
	if((scoreArray["managementsystems"].match("ISO 14001") != null) && (sectionIndex == 3) && (currentBlockNo == 2) && (item == 4)){
	return false;
	}
	if((scoreArray["managementsystems"].match("Investors in People") != null) && (sectionIndex == 0) && (currentBlockNo == 1) && (item == 5)){
	return false;
	}
	if((scoreArray["managementsystems"].match("Investors in People") != null) && (sectionIndex == 2) && (currentBlockNo == 1) && (item == 4)){
	return false;
	}
	return true;
}

function resultsQualifier(){
	
	readScores();
	
	var score = totalScore(1,5);
	
	if(score>250) document.getElementById("qualifier1").innerHTML = "You have sound and integrated approaches in place in your organisation and need to ensure that you have a regular assessment and review process to identify continuing improvement opportunities.";
	else document.getElementById("qualifier1").innerHTML = "You may want to confirm that you have fully deployed all your approaches in all relevant areas of your organisation and build in regular review and assessment of the way your organisation operates";
	
	score = totalScore(6,9);
	if(((scoreArray["years"]=="less than 1 year") || (scoreArray["years"]=="1 to 3 years")) && (score>200))
		document.getElementById("qualifier2").innerHTML = "You need to consider if you really have a full 3 years of trend data as your organisation has not been established that long";	

	score = parseInt(scoreArray["step5"])
	if((scoreArray["managementsystems"].match("ISO 9001") != null) && ( score< 5)){
		var qualifier3 = document.getElementById("qualifier3");
		qualifier3.innerHTML = "You have scored less than 5 in the processes critieria but have indicated you are already certified to ISO9001. You may want to consider if your system is effective in satisfying customer requirements and has a <a href='http://www.ukas.com/business/indirect/why_ukas_accredited_certification.asp'>UKAS</a> accredited certification.";
	}
	
	//document.getElementById("cookieText").innerHTML = cookieText()+'<br>Total Score:'+totalScore(1,9)+'<br>1 to 5 Score:'+totalScore(1,5)+'<br>6 - 9 Score:'+totalScore(6,9); // bit of debug here...


//new stuff START here
	
	readScores();

	var numberOfSections = 8;  //zero indexed
	
	var sections = new Array();
	function section(label, score, index, title, data) {
 	   this.SectionName = label;
 	   this.Score = parseInt(parseFloat(score));
 	   this.Index = parseInt(parseFloat(index));
 	   this.Title = title;
 	   this.Data = data
	}

	for(var i = 0; i <= numberOfSections; i++){
		itemNo = i+1;
		sections[sections.length++] = new section("step"+itemNo, scoreArray["step"+itemNo], i, atitlesText[i], aResultsText[i]);
	}
	
	//sort the arrays into score order
	sections.sort(function(a,b){return a.Score - b.Score});


	
	//populate the Divs
	
	for(var i = 0; i <= numberOfSections; i++){
		
	
	//set the style and display of this section
		
		var thisMainBlock = document.getElementById("main"+i);
		var thisSubBlock = document.getElementById("sub"+i);
		
		if(sections[i].Score <5){
		thisMainBlock.className = 'red';
		thisSubBlock.style.display = 'block';
		}
		else if(sections[i].Score <7){
		thisMainBlock.className = 'orange';
		thisSubBlock.style.display = 'none';
		}
		else{
		thisMainBlock.className = 'green';
		thisSubBlock.style.display = 'none';
		}
	

	//set the what needs to be done section
		
		
			//Title
			var title = document.getElementById("title"+i);
			title.innerHTML = sections[i].Title;
			
			
			//Score
			var score = document.getElementById("score"+i);
			score.innerHTML = "(Your score was "+sections[i].Score+")";
			
			//Key Issues
			var keyissues = document.getElementById("keyissues"+i);
			var requiredBlockNo = scoreToTextBlockNo(sections[i].Score);        //based on the score which text block are we going to use
			aAllSectionText = sections[i].Data.split("\r\n\r\n");               //break up the text for this section into score blocks
			aThisSectionText = aAllSectionText[requiredBlockNo].split("\r\n");  //break the required section into it's lines
	
			for(var j = 0; j <= aThisSectionText.length-1; j++){     //loop through each line checking for exclusions
				if(showThisItem(sections[i].Index,requiredBlockNo,j)){
					keyissues.innerHTML = keyissues.innerHTML + "<li>"+aThisSectionText[j]+"</li>"
				}
			}
	
		
	//set the what we offer section

		var weoffer = document.getElementById("weoffer"+i);
 		weoffer.innerHTML = aWeOfferText[sections[i].Index];
		
	}

//new stuff END here


}

function cookieText(){
	var cookieVal='';
	readScores();	
	for(var name in scoreArray){
		if(name) cookieVal += name + ':' +scoreArray[name]+'<br>';
	}
	
	return(cookieVal);
}

function stepMandatory(){
	var form = document.getElementById("step");
	for(var j = 0; j < form.radio.length; j++){
		if(form.radio[j].checked) return true;
	}
	alert("You did not select a score for this criteria.\n\nPlease select a score and resubmit the form.");
	return false;
}
