/**
 * @author Ed Slocombe
 */
var thepetname="";
var Diagnose = {
	
	baseUrl : "/AJAXphp/diagnosis.php",
	petId : null,
	sympId : null,
	areaId : null,
	routeId : null,
	stageId : null,
	questionNo : 1,
	a : false,
	answers : new Object(),
	
	AUTO_GO_TO : true,
	
	init : function(a, baseUrl) {
		
		if (a) {
			this.a = a;
			this.baseUrl = "../" + this.baseUrl;
		}
		
		if (baseUrl) {
			this.baseUrl = baseUrl + this.baseUrl;
		}
		
		// If the url contains the pet id
		if (shg_petName) {
			thepetname=shg_petName;
			// Replace title 'Pet' with pet name
			var title = document.getElementById('title');
			var newTitleTxt = title.innerHTML.replace("Pet", shg_petName);
			title.innerHTML = newTitleTxt;
			googletrigger(shg_petName,'Select pet');
			// Add symptoms to dropdown box
			Diagnose.populateSelectBox(shg_petSymptoms, document.getElementById('selectSymptom'), "selectSymp_");
			
			this.petId = shg_petId;
			
		}
		
		// Otherwise we need to get them to select it
		else {
			
			// Show choose pet box
			var selectPetBox = document.getElementById('step1_selectPet');
			selectPetBox.style.display = "inline";
			
			// Add pets to dropdown box
			var dropDown = document.getElementById('selectPet');
			
			for(petId in shg_pets) {
				if (typeof shg_pets[petId] == "function") break;
				var newOption = document.createElement("option");
				newOption.innerHTML = shg_pets[petId];
				newOption.setAttribute("value", petId);
				newOption.setAttribute("id", "selectPet_"+petId);
				dropDown.appendChild(newOption);
			}
			
			addListener(dropDown, Diagnose.onDropDownChange, "change");
			
			// Disable other box
			var selectSympBox = document.getElementById('step1_selectSymptom');
			selectSympBox.style.color = "#999999";
			var dropDownSymp = document.getElementById('selectSymptom');
			dropDownSymp.disabled = true;
			
		}
			
	},
	
	setPet : function (arg) {
		
		if (typeof arg == "string") {
			
			if (arg == "") {
				this.emptySelectBox(document.getElementById('selectSymptom'));
				return;
			}
			
			var id = arg;
			this.petId = id;
			
			// Populate sym box for this pet
			callAJAX(this.baseUrl+"?getSymptoms=1&petId="+id, Diagnose.setPet, true);
		} else {
			
			// Handle AJAX response
			var xml = arg;
			var symps = new Object();
			var sympNodes = xml.getElementsByTagName('symptoms')[0];
			for (var i=0; i<sympNodes.childNodes.length; i++) {
				if (sympNodes.childNodes[i].nodeType == 1) {
					symps[sympNodes.childNodes[i].getAttribute("id")] = sympNodes.childNodes[i].firstChild.nodeValue;	
				} 
			}
			
			var sympBox = document.getElementById('selectSymptom');
			if (!Diagnose.a) {
				Diagnose.populateSelectBox(symps, sympBox, "selectSymp_");
			}
			else {
				Diagnose.populateSelectBox(symps, sympBox, "selectSymp_", false);
				if (i != 1) DiagnoseA.setSymptom(sympBox.value);
			}
			
			// Enable symp box
			var selectSympBox = document.getElementById('step1_selectSymptom');
			selectSympBox.style.color = "#006D9E";
			var dropDownSymp = document.getElementById('selectSymptom');
			dropDownSymp.disabled = false;
			
		}
			
	},
	
	setSymptom : function (arg) {
		
		if (typeof arg == "string") {
		
			var id = arg;
			if (id == "") return;
			
			this.sympId = id;
			
			// Get first question for this pet and symtom
			callAJAX(this.baseUrl + "?petId=" + this.petId + "&sympId=" + id, Diagnose.setSymptom, true);
			
		} else {
			
			// Handle AJAX response
			var xml = arg;
			
			if (xml.getElementsByTagName("route")[0]) {
				// No areas are applicable, move to questions (by setting area)
				if (!Diagnose.a) document.getElementById('step1_selectArea').style.display = "none";
				else Diagnose.populateSelectBox(new Object(), document.getElementById('selectArea'), "", false);
				try { 
					var routeId = xml.getElementsByTagName("route")[0].firstChild.nodeValue;
					Diagnose.setRoute(routeId, 'route'); 
				} catch (e) { 
					Diagnose.routeId = null;
					if (!Diagnose.a) alert("Sorry! An error has occoured. We'll try and fix it as soon as possible.\n\nDetails: ERROR 1 : No route defined"); 
					else DiagnoseA.noRouteAction("symptoms");
				}
			} else {
				
				// Display areas dropbox
				var areas = new Object();
				var areaNodes = xml.getElementsByTagName('areas')[0];
				for (var i=0; i<areaNodes.childNodes.length; i++) {
					if (areaNodes.childNodes[i].nodeType == 1) {
						areas[areaNodes.childNodes[i].getAttribute("id")] = areaNodes.childNodes[i].firstChild.nodeValue;	
					} 
				}
				
				// Populate dropbox
				var areaBox = document.getElementById('selectArea');
				Diagnose.populateSelectBox(areas, areaBox, "selectArea_");
				if (Diagnose.a) {
					Diagnose.populateSelectBox(areas, areaBox, "selectArea_", false);
					if (i != 1) DiagnoseA.setRoute(areaBox.value, 'area');
				}
		
				// Show area select box
				document.getElementById('step1_selectArea').style.display = "inline";
				
			}
			
		}
		
	},
	
	setRoute : function (id, typeOfId) {
		
		var url = this.baseUrl + "?petId=" + this.petId + "&sympId=" + this.sympId;
		
		if (typeOfId == "area") {
			this.areaId = id;
			url += "&areaId="+id;
		}
		else if (typeOfId == "route") {
			this.routeId = id;
			url += "&routeId="+id;
		}	
		
		if (!Diagnose.a) callAJAX(url, Diagnose.setResponse, true);
		else callAJAX(url, DiagnoseA.setResponse, true);
		
	},
	
	getResponse : function (btnObj, link, questionPos) {

		if (questionPos < (this.questionNo-1)) {
			this.deleteQuestionsFrom((questionPos-0)+1);			
			this.questionNo = (questionPos/1)+1;
		}

		if (btnObj.className.indexOf("longButton") != -1) btnObj.className = "ansClicked button longButton";
		else btnObj.className = "ansClicked button";
		callAJAX(this.baseUrl+link, Diagnose.setResponse);
	
	},
	
	setResponse : function (xml) {
		
		try { this.routeId = xml.getElementsByTagName("route")[0].firstChild.nodeValue; } 
		catch (e) { this.routeId = null; }
		
		try {
			
			var stageId = xml.getElementsByTagName("response")[0].getAttribute("id");
			this.stageId = stageId;
			var responseType = xml.getElementsByTagName("type")[0].firstChild.nodeValue
			var responseId;
			
			if (responseType == "question") {
				
				document.getElementById('step2').style.display = "inline";
				
				var step2box = document.getElementById("step2_content");
				
				var quAnsHolder = document.createElement("div");
				quAnsHolder.setAttribute("id", "quAndAns"+Diagnose.questionNo);
				
				var quDivId = "qus"+stageId;//Diagnose.questionNo;
				var questionBox;
				var answerBox;
					
				// Create question (and 'next qu' bit and ans div)
				
				questionBox = document.createElement("div");
				questionBox.className = "question";
				questionBox.setAttribute("id", quDivId);
				responseId = quDivId;
				
				answerBox = document.createElement("div");
				answerBox.className = "answers";
				answerBox.setAttribute("id", "ans"+stageId);//Diagnose.questionNo);
				
				if (Diagnose.questionNo != 1) {
					var nextStepSec = document.createElement("div");
					nextStepSec.className = "nextQuestion";
					nextStepSec.setAttribute("id", "nxtQu" + Diagnose.questionNo)
					nextStepSec.innerHTML = "NEXT QUESTION";
					quAnsHolder.appendChild(nextStepSec);
				}
				else document.getElementById("step12_nextStep").style.display = "block";
				
				quAnsHolder.appendChild(questionBox);
				quAnsHolder.appendChild(answerBox);
				step2box.appendChild(quAnsHolder);
				
				var questionNode = xml.getElementsByTagName('question')[0];
				var ansNodes;
				answerBox.innerHTML = "";
				
				// Extract question
				for (var k=0; k<questionNode.childNodes.length; k++) {
					if (questionNode.childNodes[k].nodeType == 1) {
						if (questionNode.childNodes[k].tagName == "text") questionBox.innerHTML = questionNode.childNodes[k].firstChild.nodeValue;
						else if (questionNode.childNodes[k].tagName == "answers") ansNodes = questionNode.childNodes[k];
					}
				}		
				
				var someAnswers = false;
				
				// Extract answers
				for (var i=0, btnId=1; i<ansNodes.childNodes.length; i++) {
					
					if (ansNodes.childNodes[i].nodeType == 1) {
						
						someAnswers = true;
						
						var answer = ansNodes.childNodes[i];
						var txt;
						var link;
						var route;
						var ansElem;
						
						for (var j=0; j<answer.childNodes.length; j++) {
							if (answer.childNodes[j].nodeType == 1) {
								if (answer.childNodes[j].tagName == "link") link = answer.childNodes[j].firstChild.nodeValue;
								else if (answer.childNodes[j].tagName == "text") txt = answer.childNodes[j].firstChild.nodeValue;
								else if (answer.childNodes[j].tagName == "route") route = answer.childNodes[j].firstChild.nodeValue;
							}
						}
						
						Diagnose.addAnswer(answerBox, btnId, link, txt);
						
						btnId++;
						
					}
				}
				
				if (Diagnose.a) {
					if (!someAnswers) DiagnoseA.noResponseAnswers(answerBox);
					DiagnoseA.addResponseOptions(quAnsHolder, stageId);
				} 
			
				
			} else if (responseType == "result") {
				
				document.getElementById("step23_nextStep").style.display = "block";
				responseId = "step3";
				
				// Extract what user needs to do
				var resultNodes = xml.getElementsByTagName("result")[0];
				var actionClass;
				var actionTxt;
				var advice;
				var image;
				var text;
				
				for (var k=0; k<resultNodes.childNodes.length; k++) {
					if (resultNodes.childNodes[k].nodeType == 1) {
						if (resultNodes.childNodes[k].tagName == "class") actionClass = resultNodes.childNodes[k].firstChild.nodeValue;
						else if (resultNodes.childNodes[k].tagName == "action") actionTxt = resultNodes.childNodes[k].firstChild.nodeValue;
						else if (resultNodes.childNodes[k].tagName == "text") text = resultNodes.childNodes[k].firstChild.nodeValue;
						else if (resultNodes.childNodes[k].tagName == "advice") advice = resultNodes.childNodes[k].firstChild.nodeValue;
						else if (resultNodes.childNodes[k].tagName == "image") image = resultNodes.childNodes[k].firstChild.nodeValue;
					}
				}
				
				Diagnose.addResult(actionClass, actionTxt, advice, image, text);			
				
				if (Diagnose.a) {
					var holder = document.getElementById('responseOpts_stage3');
					// Remove any old response answers
					for (var k = 0; k < holder.childNodes.length; k++) {
						if (holder.childNodes[k].nodeType == 1) {
							holder.removeChild(holder.childNodes[k]);
							k--;
						}
					}
					// Add the new btns
					DiagnoseA.addResponseOptions(holder, stageId, true);
				}
			}

			if (window.scrollToQuestion === undefined || scrollToQuestion == true || (scrollToQuestion == false && Diagnose.questionNo != 1)) {
				Diagnose.goTo(responseId);
			}

			Diagnose.questionNo++;
			/*if(responseType == "question")
			{
				if(scrollToQuestion == true)
				{
					Diagnose.goTo(responseId);
				}
			}
			else
			{
				Diagnose.goTo(responseId);
			}*/
			//Diagnose.goTo(responseId);
			
		} catch (e) {
			if (!Diagnose.a) alert("Sorry! An error has occoured. We'll try and fix it as soon as possible.\n\nDetails: ERROR 2 : No response type defined");
			else { DiagnoseA.noRouteAction('response'); }
		}
				
	},
	
	deleteQuestionsFrom : function(quRowId) {
		var step2box = document.getElementById("step2_content");
		var pos = quRowId;
		
		// Remove qus, ans, nextQu break after this button
		while(document.getElementById("quAndAns"+pos)) {
			step2box.removeChild(document.getElementById("quAndAns"+pos));
			pos++;
		}
		
		document.getElementById("step3").style.display = "none"; 
		if (!Diagnose.a) document.getElementById("contactingVet").style.display = "none"; 
		if (!Diagnose.a) document.getElementById("disclaimer").style.display = "none";
		if (!Diagnose.a) document.getElementById("navbuttons").style.display = "none";
		document.getElementById("step23_nextStep").style.display = "none";
			
	},
	
	addAnswer : function(answerBox, btnId, link, txt, questionNo) {
		
		questionNo = (questionNo)? questionNo : Diagnose.questionNo;
		
		if (!Diagnose.answers[questionNo]) Diagnose.answers[questionNo] = new Object();
		Diagnose.answers[questionNo][btnId] = new Object();
		Diagnose.answers[questionNo][btnId]["link"] = link;
		Diagnose.answers[questionNo][btnId]["text"] = txt;
	
		ansElem = document.createElement("span");
		ansElem.setAttribute("id", questionNo+"_ans"+btnId);
		addListener(ansElem, Diagnose.onAnsClick, "click");
		ansElem.innerHTML = txt;
		if (txt.length > 10) ansElem.className = "ans button longButton";
		else ansElem.className = "ans button";
		answerBox.appendChild(ansElem);
	},
	
	addResult : function(actionClass, actionTxt, advice, image, text) {
		var priorityCon = document.getElementById("priorityContainer");
		var priorityInfo = document.getElementById("step3_priorityInfo");
		var priorityAdvice = document.getElementById("step3_advice");
		var priorityActionTitle = document.getElementById('step3_actionClass');
		responseId = "step3";
		
		priorityCon.className = "priority step3_"+actionClass;
		priorityInfo.innerHTML = actionTxt;
		
		priorityActionTitle.innerHTML = "Priority Rating - "+actionClass.replace("_", " ");
		if (Diagnose.a) priorityActionTitle.style.backgroundImage = "url("+image.replace("./img", "../images/diagnosis")+")";
		else priorityActionTitle.style.backgroundImage = "url("+image.replace("./img", "../images/diagnosis")+")";
		priorityAdvice.innerHTML = text;
		
		document.getElementById("step3").style.display = "block";
		 
		if (!Diagnose.a) {
			if (advice && (advice.indexOf("Contacting your vet out of office hours") != -1 || advice.indexOf("When calling a vet you should always") != -1)) document.getElementById("contactingVet").style.display = "block";
			document.getElementById("disclaimer").style.display = "block";
			document.getElementById("navbuttons").style.display = "block";
		}
	},
	
	startOver : function() {
		
		this.deleteQuestionsFrom(1);
		this.questionNo = 1;
		document.getElementById("step2").style.display = "none";
		document.getElementById("step12_nextStep").style.display = "none";
		
	},
	
	populateSelectBox : function (optionObj, dropDown, selectBoxId, addDefault) {
		
		this.emptySelectBox(dropDown);
		
		if (addDefault !== false) {
			var pleaseSelect = document.createElement("option");
			pleaseSelect.innerHTML = "Please select";
			pleaseSelect.setAttribute("value", "-1");
			dropDown.appendChild(pleaseSelect);
		}
		var someOptions	= false;
		for(id in optionObj) {
			if (typeof optionObj[id] == "function") break;
			someOptions = true;
			var newOption = document.createElement("option");
			newOption.innerHTML = optionObj[id];
			newOption.setAttribute("value", id);
			if (selectBoxId) newOption.setAttribute("id", selectBoxId+id);
			dropDown.appendChild(newOption);
		}
		
		if (!someOptions && Diagnose.a) {
			var newOption = document.createElement("option");
			if (dropDown == document.getElementById("selectArea")) newOption.innerHTML = "-- NONE (or only 1) --";
			else newOption.innerHTML = "-- NONE --";
			newOption.setAttribute("value", "-1");
			dropDown.appendChild(newOption);
		}
		
		addListener(dropDown, Diagnose.onDropDownChange, "change");
		
	},
	
	emptySelectBox : function(dropDown) {
		
		for(var i=dropDown.options.length-1;i>=0;i--) {
			dropDown.remove(i);
		}
		
	},
	
	onDropDownChange : function(evt) {
		
		var elem = (evt.target)? evt.target : evt.srcElement;
		if (Diagnose.a && DiagnoseA.working == true) return;
		var obj = (Diagnose.a)? DiagnoseA : Diagnose;
		
		if (elem.value == "-1") return;
		
		switch (elem.id) {
			
			case "selectPet": {
				obj.startOver(); 
				obj.setPet(elem.value);
				var num = elem.selectedIndex;
				googletrigger(elem.options[num].text,'Select pet');
			    //alert(elm.options[num].text);
				break;
			}
			
			case "selectSymptom": {
				obj.startOver('symptoms'); 
				obj.setSymptom(elem.value);
				var num = elem.selectedIndex;
				googletrigger(thepetname,'Select symptom > '+elem.options[num].text);
				break;
			}
			
			case "selectArea": {
				obj.startOver('areas'); 		
				obj.setRoute(elem.value, 'area');
				var num = elem.selectedIndex;
				googletrigger(thepetname,'Select area > '+elem.options[num].text);
				break;
			}
			
		}

		// Force focus away from drop-down to deal with double requests in Safari.
		elem.blur();
		
		// Remove any "Please select" type options from box (any with value -1)
		for (i=0; i<elem.options.length; i++) {
			if (elem.options[i].value == "-1" || elem.options[i].value == "") elem.removeChild(elem.options[i]);
		}

	},
	
	onAnsClick : function(evt) {
		
		var elem = (evt.target)? evt.target : evt.srcElement;
		if (elem.className.indexOf("ansClicked") != -1) return;
		if (Diagnose.a && DiagnoseA.working == true) return;
		
		var questionNo = elem.id.substring(0, elem.id.indexOf("_"));
		var ansNo = elem.id.substring(elem.id.indexOf("_ans")+4);
		var obj = (Diagnose.a)? DiagnoseA : Diagnose;
		
		
		// Set all buttons for ans to unclicked
		Diagnose.unclickAllBtns(questionNo);
		
		obj.getResponse(elem, Diagnose.answers[questionNo][ansNo]["link"], questionNo);
		
	},
	
	unclickAllBtns : function(questionNo) {
		var i = 1;
		while(document.getElementById(questionNo+"_ans"+i)) {
			var tmpBtn = document.getElementById(questionNo+"_ans"+i);
			if (tmpBtn.className.indexOf("longButton") != -1) tmpBtn.className = "ans button longButton";
			else tmpBtn.className = "ans button";
			i++;				
		}
	},
	
	getNextBtnNo : function(questionNo) {
		var i = 1;
		while(document.getElementById(questionNo+"_ans"+i)) i++;
		return i;
	},
	
	goTo : function(id) {
		if (Diagnose.AUTO_GO_TO && document.getElementById(id)) {
			if((obj = document.getElementById(id)) && obj != null){
				  window.scrollTo(0, obj.offsetTop);
				  location.href = "#"+id;
			  }
			//location.href = "#"+id;
		}
	}	
}

function addListener (obj, callback, listener, inLoop) {
	// To stop any activity if something is doing something:
	// Not in IE though cos it doesn't work properly of course!
	if (!inLoop && Diagnose.a && navigator.appName.indexOf("Microsoft") == -1) {
		addListener(obj, DiagnoseA.stopOperation, "click", true);
	}
	if (obj.addEventListener) obj.addEventListener(listener, callback, true);
	else obj.attachEvent("on"+listener, callback, true);
}

var AJAX_callback;
var AJAX_done;
var isIE = (navigator.appName.indexOf("Microsoft") != -1);

function callAJAX(url, callback, returnXML, data) {
	AJAX_callback = callback;
	AJAX_done = false;
	var body = document.getElementsByTagName("body")[0];
	try { body.removeChild(document.getElementById("loadingTextBox")) } catch(e) {}
	var loadingText = document.createElement("div");
	loadingText.setAttribute("id", "loadingTextBox");
	loadingText.className = "loadingBox";
	loadingText.innerHTML = "loading...";
	body.appendChild(loadingText);
	loadingText.style.left = "0px";
	loadingText.style.top = "0px";
	centreElem(loadingText);
	if (!isIE) fadeIn("loadingTextBox", 0.8);
	
	AJAX.call(url, callbackAJAX, returnXML, data);
}

function callbackAJAX(data) {
	AJAX_done = true;
	var body = document.getElementsByTagName("body")[0];
	var loadingText = document.getElementById("loadingTextBox");
	if (!isIE) fadeOut("loadingTextBox");
	else body.removeChild(loadingText);
	AJAX_callback(data);
}

function fadeIn(objId, limit) {
	if (AJAX_done == true) return;
	var obj = document.getElementById(objId);
	var opacity = (obj.style.opacity)? obj.style.opacity : 0;
	if (!limit) limit = 1;
	if (opacity > (limit/1)-0.1) {
		opacity = limit;
		return;
	}
	obj.style.opacity = (opacity/1)+0.2; 
	setTimeout("fadeIn('"+objId+"', "+limit+")", 100);
}

function fadeOut(objId) {
	try { 
		var obj = document.getElementById(objId); 
		var opacity = obj.style.opacity;
		if (!opacity) return;
		if (opacity < 0.1) {
			opacity = 0;
			var body = document.getElementsByTagName("body")[0];
			body.removeChild(obj);
			return;
		}
		obj.style.opacity = (opacity/1)-0.2; 
		setTimeout("fadeOut('"+objId+"')", 100);
	} catch(e) { return; }
}

function centreElem(obj) {
	var scrollX = 0, scrollY = 0;
	var windowW = 0, windowH = 0;
	
	if (document.body && typeof document.body.scrollTop != "undefined") {
		scrollX += document.body.scrollLeft;
		scrollY += document.body.scrollTop;
		if (document.body.parentNode && typeof document.body.parentNode.scrollTop != "undefined" && document.body.scrollTop != document.body.parentNode.scrollTop) {
			scrollX += document.body.parentNode.scrollLeft;
			scrollY += document.body.parentNode.scrollTop;
		}
	} else if (typeof window.pageXOffset != "undefined") {
		scrollX += window.pageXOffset;
		scrollY += window.pageYOffset;
	}
	
	if (window.innerHeight) {
		windowH = window.innerHeight;
		windowW = window.innerWidth;
	} else {
		windowH = document.body.clientHeight;
		windowW = document.body.clientWidth;
	}
	
	// IE throws an error here but still seems to work fine, so...
	try {
		var offsetHeight = obj.offsetHeight;			
		var x = Math.round(windowW/2 - obj.offsetWidth/2) + scrollX;
		var y = Math.round(windowH/2 - offsetHeight/2) + scrollY;
		obj.style.left = x+"px";
		obj.style.top = y+"px";			
	} catch (e) { }	
}

function googletrigger(petname,action) {
if ( typeof( window[ 'practice' ] ) != "undefined" ) {	
	practiceinfo='Practice id:'+practice; 
} else {
	practiceinfo="VHD"; 
}
	_gaq.push(['_trackEvent', practiceinfo, petname, action]);
}

