/*********************************/
/**   APPLIKATIONSFUNKTIONER    **/
/*********************************/
var drillArray;
var drills;
var theDrill;
var res;

function showHide(specState){
	if(specState == "hide"){
		document.getElementById("searchArea").style.display = "none";
		document.getElementById("drillArea").className = "";
		document.getElementById("searchResult").className = ""
		document.getElementById("forMyFriend").className = ""
	}
	else if(specState == "show"){
		document.getElementById("searchArea").style.display = "block";
		document.getElementById("drillArea").className = "hidden"
		//document.getElementById("searchingForDrillArea").className = "hidden";
		document.getElementById("searchResult").className = "hidden"
		document.getElementById("forMyFriend").className = "hidden"
	}
	else {
		document.getElementById("searchArea").style.display = document.getElementById("searchArea").style.display == "block" ? "none" : "block";
		document.getElementById("drillArea").className == "hidden" ? document.getElementById("drillArea").className = "" : document.getElementById("drillArea").className = "hidden";
		document.getElementById("searchResult").className == "hidden" ? document.getElementById("searchResult").className = "" : document.getElementById("searchResult").className = "hidden";
		document.getElementById("forMyFriend").className == "hidden" ? document.getElementById("forMyFriend").className = "" : document.getElementById("forMyFriend").className = "hidden";
	}
}
function printIt(){
	showHide("hide");
	window.print();
}
function helpStartHide(){
	document.getElementById('helpStart').style.display = "none";
}
function createSearch(){
	sa = document.getElementById("searchArea");
	inps = sa.getElementsByTagName("input");
	numChks = inps.length;
	query = "";
	for(i = 0; i < numChks; i++){
		if(inps[i].getAttribute("type") == "checkbox"){
			if(inps[i].checked == true){
				query += inps[i].id.substr(3) + "=Y" + "&";
			}
		}
		else if(inps[i].getAttribute("type") == "text"){
			if(inps[i].value != ""){
				query += inps[i].id + "=" + inps[i].value + "&";
			}
		}
	}
	return query.substr(0, query.length - 1);
}
function doSearch(){
	//searchAnimation("searchingForResult", "searchResult", "start");
	query = createSearch();
	responseFuntion = function(){ searchResult(); }
	makeRequest("script/xmlSearch.php", responseFuntion, query);
}
function searchResult() {
	drillArray = null;
	if(http_request.readyState == 4) {
		if (http_request.status == 200) {
			// Bearbeta XML-svaret
			xmldoc = http_request.responseXML;
			root_node = xmldoc.getElementsByTagName("root").item(0);
			res = root_node.getElementsByTagName("numresults").item(0).firstChild.nodeValue;
			drillList = root_node.getElementsByTagName("drillist").item(0);
			drills = drillList.getElementsByTagName("drill");
			document.getElementById("num").replaceChild(document.createTextNode(res), document.getElementById("num").firstChild);
			document.getElementById("num2").replaceChild(document.createTextNode(res), document.getElementById("num2").firstChild);
			if(res == 0){
				//noResult();
			}
			showResult();
		}
		else {
			alert('There was a problem with the request.');
		}
    }
}
function noResult(state){
	//document.getElementById("drillArea").className = "hidden";
	if(! document.getElementById("searchingForDrillArea").hasChildNodes()){
		holder = document.createElement("div");
		holder.style.textAlign = "center";
		txt = document.createElement("p");
		txt.appendChild(document.createTextNode(lan['NO_RESULTS']));
		holder.appendChild(txt);

		document.getElementById("searchingForDrillArea").appendChild(holder);
	}
	sda = document.getElementById("searchingForDrillArea");
	if(state == true){
		sda.className = "";
		document.getElementById("doTipFriend").disabled = true;
	}
	else {
		sda.className = "hidden";
		document.getElementById("doTipFriend").disabled = false;
	}
	//document.getElementById("searchingForDrillArea").style.display = "block";
}
function showResult(from, startAt){
	atEnd = false;
	resultArea = document.getElementById("searchResult");
	if(! from){
		from = 0;
	}
	to = 20 + from;

	numDrills = drills.length;
	theTable = document.createElement("table");
	theTable.setAttribute("id", "searchTable");
	tblBody = document.createElement("tbody");
	if(to >= numDrills){
		to = numDrills;
		atEnd = true;
	}

	aTr = document.createElement("tr");
	aTr.setAttribute("id", "srHeader");
	aTh = document.createElement("th");
	aTh.setAttribute("id", "nbr");
	thText = document.createTextNode("#");
	aTh.appendChild(thText);
	aTr.appendChild(aTh);
	aTh = document.createElement("th");
	thText = document.createTextNode(lan['DESCRIPTION']);
	aTh.appendChild(thText);
	aTr.appendChild(aTh);


	tblBody.appendChild(aTr);

	if(numDrills == 0){
		aTr = document.createElement("tr");
		aTd = document.createElement("td");
		aTd.colSpan = 2;
		text = document.createElement("span");
		text.appendChild(document.createTextNode(lan['NO_RESULTS']));
		aTd.appendChild(text);
	}
	else {
		for(i = from; i < to; i++){
			theTr = document.createElement("tr");
			theTr.onclick = new Function("getDrill("+ drills[i].getAttribute("id") +"); markDrill(this);");
			if(i == startAt || (i == from && ! startAt)){
				theTr.className = "selected";
			}

			nbrTd = document.createElement("td");
			descTd = document.createElement("td");

			nbrText = document.createTextNode(drills[i].getAttribute("id"));
			descText = document.createTextNode(unescape(drills[i].getElementsByTagName("description").item(0).firstChild.nodeValue));

			nbrTd.appendChild(nbrText);
			descTd.appendChild(descText);

			theTr.appendChild(nbrTd);
			theTr.appendChild(descTd);

			tblBody.appendChild(theTr);
		}

		aTr = document.createElement("tr");
		aTr.setAttribute("id", "srPager");
		aTd = document.createElement("th");
		aTd.colSpan = 2;
		if(from > 0){
			backLink = document.createElement("span");
			backLink.setAttribute("id", "backLink");
			backLink.onclick = new Function("showResult("+ (from - 20) +");");
			theImg = document.createElement("img");
			theImg.src = "./img/arrow_left.gif";
			theImg.setAttribute("title",lan["PREVIOUS"]);
			backLink.appendChild(theImg);
			aTd.appendChild(backLink);
		}
		if(! atEnd){
			nextLink = document.createElement("span");
			nextLink.setAttribute("id", "nextLink");
			nextLink.onclick = new Function("showResult("+ (from + 20) +");");
			theImg = document.createElement("img");
			theImg.src = "./img/arrow_right.gif";
			theImg.setAttribute("title",lan["NEXT"]);
			nextLink.appendChild(theImg);
			aTd.appendChild(nextLink);
		}
	}

	aTr.appendChild(aTd);

	tblBody.appendChild(aTr);

	theTable.appendChild(tblBody);
	resultArea.replaceChild(theTable, document.getElementById('searchTable'));
	//searchAnimation("searchingForResult", "searchResult", "stop");
	if(startAt){
		noResult(false);
		getDrill(drills[startAt].getAttribute("id"));
	}
	else if(numDrills != 0) {
		noResult(false);
		getDrill(drills[from].getAttribute("id"));
	}
	else {
		noResult(true);
	}
}
function markDrill(obj){
	theTable = document.getElementById("searchTable");
	trs = theTable.getElementsByTagName("tr");
	numTrs = trs.length;
	for(a = 0; a < numTrs; a++){
		if(trs[a].className == "selected"){
			trs[a].className = "";
		}
	}
	obj.className = "selected";
}
function goNextDrill(){
	theTable = document.getElementById("searchTable");
	trs = theTable.getElementsByTagName("tr");
	numTrs = trs.length;
	for(a = 0; a < numTrs; a++){
		if(trs[a].className == "selected" && trs[a].nextSibling.id != "srPager"){
			matchStr = trs[a].nextSibling.onclick.toString().match(/getDrill\((\d+)\)/i);
			getDrill(matchStr[1]);
			markDrill(trs[a].nextSibling);
		}
		else if(trs[a].className == "selected" && trs[a].nextSibling.id == "srPager"){
			matchStr = document.getElementById("nextLink").onclick.toString().match(/showResult\((\d+)\)/i);
			showResult(parseInt(matchStr[1]));
		}
	}
}

function goPreviousDrill(){
	theTable = document.getElementById("searchTable");
	trs = theTable.getElementsByTagName("tr");
	numTrs = trs.length;
	for(a = 0; a < numTrs; a++){
		if(trs[a].className == "selected" && trs[a].previousSibling.id != "srHeader"){
			matchStr = trs[a].previousSibling.onclick.toString().match(/getDrill\((\d+)\)/i);
			getDrill(matchStr[1]);
			markDrill(trs[a].previousSibling);
		}
		else if(trs[a].className == "selected" && trs[a].previousSibling.id == "srHeader"){
			if(document.getElementById("backLink")){
				matchStr = document.getElementById("backLink").onclick.toString().match(/showResult\((\d+)\)/i);
				showResult(parseInt(matchStr[1]), parseInt(matchStr[1]) + 19);
			}
		}
	}
}

function getDrill(drillID){
	if(! isNaN(drillID)){
		//searchAnimation("searchingForDrillArea", "drillArea", "start");
		query = "d=" + drillID;
		responseFuntion = function(){ showDrill(); }
		makeRequest("script/xmlGetDrill.php", responseFuntion, query);
	}
}
function showDrill(){
	if(http_request.readyState == 4) {
		if (http_request.status == 200) {
			// Bearbeta XML-svaret
			xmldoc = http_request.responseXML;
			root_node = xmldoc.getElementsByTagName("root").item(0);
			theDrill = root_node.getElementsByTagName("drill").item(0);
				//Modellbild
				document.getElementById("drillImage").src = "drillImage.php?i=" + theDrill.getAttribute("id");
				//Modellbild utskrift
				document.getElementById("drillImagePrint").src = "drillImage.php?print&i=" + theDrill.getAttribute("id");
				//Modellnummer
				document.getElementById("drillNbr").replaceChild(document.createTextNode("- "+ lan['DRILL_NUMBER'] +": "+ theDrill.getAttribute("id")), document.getElementById("drillNbr").firstChild);
				//Beskrivning
				document.getElementById("description").replaceChild(document.createTextNode(theDrill.getElementsByTagName("description").item(0).firstChild.nodeValue), document.getElementById("description").firstChild);
				//Syfte
				theText = theDrill.getElementsByTagName("cause").item(0).hasChildNodes() ? theDrill.getElementsByTagName("cause").item(0).firstChild.nodeValue : "";
				document.getElementById("cause").replaceChild(document.createTextNode(theText), document.getElementById("cause").firstChild);
				//Förberedelser
				theText = theDrill.getElementsByTagName("preparation").item(0).hasChildNodes() ? theDrill.getElementsByTagName("preparation").item(0).firstChild.nodeValue : "";
				document.getElementById("preparations").replaceChild(document.createTextNode(theText), document.getElementById("preparations").firstChild);

				//Spelarkategorier
				cat = theDrill.getElementsByTagName("playercategory");
				numCat = cat.length;
				catList = document.createElement("ul");
				for(i = 0; i < numCat; i++){
					catItem = document.createElement("li");
					catItem.appendChild(document.createTextNode(cat[i].firstChild.nodeValue));
					catList.appendChild(catItem);
				}
				catList.setAttribute("id", "playercategories");
				document.getElementById("playercategories").parentNode.replaceChild(catList, document.getElementById("playercategories"));

				//Träningskategorier
				cat = theDrill.getElementsByTagName("practicecategory");
				numCat = cat.length;
				catList = document.createElement("ul");
				for(i = 0; i < numCat; i++){
					catItem = document.createElement("li");
					catItem.appendChild(document.createTextNode(cat[i].firstChild.nodeValue));
					catList.appendChild(catItem);
				}
				catList.setAttribute("id", "practicecategories");
				document.getElementById("practicecategories").parentNode.replaceChild(catList, document.getElementById("practicecategories"));

				//Träningsplatser
				cat = theDrill.getElementsByTagName("practicearea");
				numCat = cat.length;
				catList = document.createElement("ul");
				for(i = 0; i < numCat; i++){
					catItem = document.createElement("li");
					catItem.appendChild(document.createTextNode(cat[i].firstChild.nodeValue));
					catList.appendChild(catItem);
				}
				catList.setAttribute("id", "practiceareas");
				document.getElementById("practiceareas").parentNode.replaceChild(catList, document.getElementById("practiceareas"));

				//Distans
				if(theDrill.getElementsByTagName("distancefrom").item(0).firstChild.nodeValue == theDrill.getElementsByTagName("distanceto").item(0).firstChild.nodeValue){
					numText = theDrill.getElementsByTagName("distancefrom").item(0).firstChild.nodeValue;
				}
				else {
					numText = theDrill.getElementsByTagName("distancefrom").item(0).firstChild.nodeValue + " - " + theDrill.getElementsByTagName("distanceto").item(0).firstChild.nodeValue;
				}
				document.getElementById("distanceNbr").replaceChild(document.createTextNode(numText), document.getElementById("distanceNbr").firstChild);

				cat = theDrill.getElementsByTagName("distance");
				numCat = cat.length;
				catList = document.createElement("ul");
				for(i = 0; i < numCat; i++){
					catItem = document.createElement("li");
					catItem.appendChild(document.createTextNode(cat[i].firstChild.nodeValue));
					catList.appendChild(catItem);
				}
				catList.setAttribute("id", "distance");
				document.getElementById("distance").parentNode.replaceChild(catList, document.getElementById("distance"));


				//Antal bollar
				if(theDrill.getElementsByTagName("ballsfrom").item(0).firstChild.nodeValue == theDrill.getElementsByTagName("ballsto").item(0).firstChild.nodeValue){
					numText = theDrill.getElementsByTagName("ballsfrom").item(0).firstChild.nodeValue;
				}
				else {
					numText = theDrill.getElementsByTagName("ballsfrom").item(0).firstChild.nodeValue + " - " + theDrill.getElementsByTagName("ballsto").item(0).firstChild.nodeValue;
				}
				document.getElementById("numBalls").replaceChild(document.createTextNode(numText), document.getElementById("numBalls").firstChild);
				//searchAnimation("searchingForDrillArea", "drillArea", "stop");
		}
		else {
			alert('There was a problem with the request.');
		}
    }
}
function setMaxMin(){
	min = document.getElementById('selMinPlayers');
	max = document.getElementById('selMaxPlayers');
	if (min.value > max.value){
		max.options[min.value].selected = true;
	}
}
function searchAnimation(searchObj, resultObj, action){
	if(action == "start"){
		document.getElementById(resultObj).className = "hidden";
		if(! document.getElementById(searchObj).hasChildNodes()){
			holder = document.createElement("div");
			holder.style.textAlign = "center";
			theImg = document.createElement("img");
			theImg.src = "./img/animation.gif";
			theImg.setAttribute("id", "drillAnimation");
			txt = document.createElement("p");
			txt.appendChild(document.createTextNode(lan['SEARCHING']));
			holder.appendChild(theImg);
			holder.appendChild(txt);

			document.getElementById(searchObj).appendChild(holder);
		}
		document.getElementById(searchObj).style.display = "block";
	}
	else if(action == "stop"){
		document.getElementById(searchObj).style.display = "none";
		//Vi vill ta bort animationen så den inte ligger i bakgrunden och tar processorkraft
		if(document.getElementById(searchObj).hasChildNodes()){
			document.getElementById(searchObj).removeChild(document.getElementById(searchObj).firstChild);
		}
		document.getElementById(resultObj).className = "shown";
	}

}
function tipFriend(){
	if(document.getElementById("friendEmail").value != "" && validEmail(document.getElementById("friendEmail").value)){
		query = "e="+ document.getElementById("friendEmail").value + "&d="+ theDrill.getAttribute("id");
		responseFuntion = function(){ tipFriendResult(); }
		makeRequest("script/xmlTipFriend.php", responseFuntion, query);
	}
	else {
		alert(lan['EMAIL_ERROR']);
	}
}
function tipFriendResult(){
	if(http_request.readyState == 4) {
		if (http_request.status == 200) {
			// Bearbeta XML-svaret
			xmldoc = http_request.responseXML;
			if(xmldoc.getElementsByTagName("status").item(0).firstChild.nodeValue == "OK"){
				alert(lan['TIP_FRIEND_OK']);
			}
			else {
				alert(lan['TIP_FRIEND_FAILED']);
			}
		}
	}
}
function validEmail(email){
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	return (!reg1.test(email) && reg2.test(email)) ? true : false;
}
function checkEmail(obj){
	if(obj.value != ""){
		allMails = document.getElementsByTagName("input");
		for(i = 0; i < allMails.length; i++){
			if(allMails[i].value == obj.value && allMails[i].id != obj.id){
				obj.previousSibling.style.color = "#F00";
				obj.style.color = "#F00";
				break;
			}
		}
		if(i == allMails.length) {
			if(! validEmail(obj.value)){
				obj.previousSibling.style.color = "#F00";
				obj.style.color = "#F00";
			}
			else {
				obj.previousSibling.style.color = "";
				obj.style.color = "";
			}
		}
	}
	else {
		obj.previousSibling.style.color = "";
		obj.style.color = "";
	}
}
function makeRequest(url, retFunction, data) {
	http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}

	if (!http_request) {
		//alert('Giving up :( Cannot create an XMLHTTP instance');
		alert('AJAX-magic doesn\'t work with your browser. Please use the most recent version of Internet Explorer or Mozilla Firefox');
		return false;
	}
	http_request.onreadystatechange = retFunction;
	http_request.open('POST', url, true);
	if(data){
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}
	else {
		data = null;
	}
	http_request.send(data);

}
