
var isIE;
var compatible = false;
var base_url = "/tools/domain_check.php";
var xmlrpc_url = "/tools/xmlrpc.php";
var sDomainOnClose = "";
var domainFldVal = "";
var xmlrpc;

window.onload = initForm;

// Checks for browser compatibility with this script

function isCompatible() {
	return compatible;
}

// Prepares the elements needed for the script to run

function initForm() {
	//init();
	
	if (document.getElementById) {
		if (window.XMLHttpRequest) {
			isIE = false;
			compatible = true;
		} else if (window.ActiveXObject) {
			isIE = true;
			compatible = true;
		}
		
		xmlrpc = XMLRPC.getService(xmlrpc_url);
		XMLRPC.onerror = function(error){
			alert(error);
			return true;
		}
		xmlrpc.add("pdl.isDomainAvailable", "isDomainAvailable");
		
		document.getElementById("domain-checker").className = "domain-checker";
		document.getElementById("whoisForm").onsubmit = liveCheck;
		
		var domainFld = document.getElementById("domainFld");
		domainFldVal = domainFld.value;
		domainFld.onfocus = function () {
			if (domainFld.value == domainFldVal) {
				domainFld.style.color = "black";
				domainFld.value = "";
			}
		}
		domainFld.onblur = function () {
			if (domainFld.value == "") {
				domainFld.style.color = "gray";
				domainFld.value = domainFldVal;
			}
		}
		
		var loadingImg = document.createElement("img");
		loadingImg.setAttribute("src", "/images/loading.gif");
		loadingImg.setAttribute("width", "20");
		loadingImg.setAttribute("height", "20");
		loadingImg.setAttribute("alt", "");
		
		var loading = document.createElement("p");
		loading.id = "loading-msg";
		loading.appendChild(document.createTextNode("Fetching results ... please wait "));
		loading.appendChild(loadingImg);
		
		var permalink = document.createElement("a");
		permalink.id = "permalink";
		permalink.setAttribute("href", "#");
		permalink.appendChild(document.createTextNode("Permanent link for these results"));
		
		var permalinkMsg = document.createElement("p");
		permalinkMsg.id = "permalink-msg";
		permalinkMsg.appendChild(permalink);
		
		var results = document.createElement("ul");
		results.id = "results-list";
		
		var closeBtn = document.createElement("button");
		closeBtn.id = "close-btn";
		closeBtn.appendChild(document.createTextNode("Close [x]"));
		closeBtn.onclick = function () {
			toggleResults(false);
			return false;
		}
		
		var controlsDiv = document.createElement("div");
		controlsDiv.id = "controls";
		controlsDiv.appendChild(closeBtn);
		
		var canvasDiv = document.createElement("div");
		canvasDiv.id = "canvas";
		canvasDiv.appendChild(loading);
		canvasDiv.appendChild(results);
		canvasDiv.appendChild(permalinkMsg);
		canvasDiv.appendChild(controlsDiv);
		
		var resDiv = document.createElement("div");
		resDiv.id = "results";
		resDiv.appendChild(canvasDiv);
		resDiv.style.visibility = "hidden";
		
		document.forms[0].appendChild(resDiv);
		
		toggleLoadingMsg(true);
		toggleList(false);
	}
}

// Runs the check if browser is compatible or returns false if not

function liveCheck() {
	if (isCompatible()) {
		var oDomainField = document.getElementById("domainFld");
		var oSuffixField = document.getElementById("tldFld");
		var sDomain = oDomainField.value;
		var sSuffix = oSuffixField.value;
		var iPeriodIndex = sDomain.indexOf(".");
		
		// If domain/suffix is same as last check, just re-open the results
		if (sDomainOnClose == sDomain + sSuffix) {
			toggleResults(true);
			toggleList(true);
			return false;
		}
		
		if (iPeriodIndex > 0 && iPeriodIndex < (sDomain.length - 1)) {
			var aDomainElements = new Array(2);
			aDomainElements[0] = sDomain.substr(0, iPeriodIndex);
			aDomainElements[1] = sDomain.substr(iPeriodIndex + 1, sDomain.length);
			
			for (var i = 0; i < oSuffixField.options.length; i ++) {
				if (oSuffixField.options[i].value == aDomainElements[1]) {
					sDomain = aDomainElements[0];
					oDomainField.value = sDomain;
					sSuffix = oSuffixField.options[i].value;
					oSuffixField.options[i].selected = true;
				}
			}
		}
		
		if (isValidDomain(sDomain, sSuffix)) {
			if (sSuffix == "." || sSuffix != "") {
				loadData(sDomain, sSuffix);
			}
		} else {
			alert("Sorry, the domain you want to check doesn't appear to be valid.\nPlease choose another and try again.\n\nYour domain should:\n- Be between 2 and 63 characters\n- Only contain letters, numbers and hyphens (-)\n- Not start or end with a hyphen (-)");
		}
		
		return false;
	} else {
		return true;
	}
}

// Checks if a domain and suffix combination is valid and should be checked

function isValidDomain(sDomain, sSuffix) {
	// We check for '.' before the regex as it was crashing Safari
	if (sDomain.indexOf(".") >= 0) {
		return false;
	}
	
	var domainRegex = /^[A-Za-z0-9]+(\-?[A-za-z0-9]*){1,63}$/;
	var bSuccess = domainRegex.test(sDomain);
	return bSuccess;
}

// Toggle visibility of the results layer

function toggleResults(state) {
	var res = document.getElementById("results");
	var permalink = document.getElementById("permalink");
	var permalinkMsg = document.getElementById("permalink-msg");
	var sDomain = document.getElementById("domainFld").value;
	var sSuffix = document.getElementById("tldFld").value;
	
	if (state) {
		sDomainOnClose = "";
		permalink.setAttribute("href", base_url + "?domain=" + sDomain + "&tld=" + sSuffix);
		res.style.visibility = "visible";
		permalinkMsg.style.visibility = "visible";
	} else {
		toggleList(false);
		toggleLoadingMsg(false);
		sDomainOnClose = sDomain + sSuffix;
		res.style.visibility = "hidden";
		permalinkMsg.style.visibility = "hidden";
	}
}

// Toggle visibility of the results list

function toggleList(state) {
	var res = document.getElementById("results-list");
	
	if (state) {
		res.style.display = "block";
	} else {
		res.style.display = "none";
	}
}

// Toggle visibility of the loading message

function toggleLoadingMsg(state) {
	var loadingMsg = document.getElementById("loading-msg");
	
	if (state) {
		loadingMsg.style.display = "block";
	} else {
		loadingMsg.style.display = "none";
	}
}

// Set the disabled state of the submit button

function enableSubmitBtn(state) {
	document.getElementById("submit_btn").disabled = !state;
}

// Clear the whois results list

function clearList() {
	var list = document.getElementById("results-list");
	var items = list.getElementsByTagName("li");
	
	for (var i = items.length - 1; i >= 0; i --) {
		list.removeChild(items.item(i));
	}
}

// Do the actual remote query

function loadData(domain, suffix) {
	toggleLoadingMsg(true);
	toggleList(false);
	toggleResults(true);
	enableSubmitBtn(false);
	
	if (suffix == ".") {
		if (!confirm("You have selected 'All' domains\nThis request may take over a minute.\n\nAre you sure you want to continue?")) {
			toggleLoadingMsg(false);
			toggleList(false);
			toggleResults(false);
			enableSubmitBtn(true);
			sDomainOnClose = "";
			return;
		}
	}
	
	clearList();
	
	if (suffix != ".") {
		myDomain = domain + '.' + suffix;
		av = xmlrpc.isDomainAvailable(myDomain);
		addResult(myDomain, domain, suffix, av);
	} else {
		var tldFld = document.getElementById("tldFld");
		
		for (var i=2; i<tldFld.options.length; i++) {
			var myTld = tldFld.options[i].value;
			myDomain = domain + '.' + myTld;
			av = xmlrpc.isDomainAvailable(myDomain);
			addResult(myDomain, domain, myTld, av);
		}
	}
	
	toggleLoadingMsg(false);
	toggleList(true);
	enableSubmitBtn(true);
}

// Return the text value of a given node

function getNodeValue(parent, element) {
	var nodes = parent.getElementsByTagName(element);
	
	if (nodes.length > 0 && nodes.item(0).hasChildNodes() && nodes.item(0).childNodes.item(0).nodeValue.length > 0) {
		return nodes.item(0).childNodes.item(0).nodeValue;
	} else {
		return "";
	}
}

// Add a row of data to the results list

function addResult(domain, name, tld, available) {
	var list = document.getElementById("results-list");
	var label = document.createTextNode(domain);
	var item = document.createElement("li");
	
	if (!available) {
		var link = document.createElement("a");
		link.setAttribute("href", "http://www." + domain + "/");
		link.title = "Visit " + domain;
		link.appendChild(label);
		link.onclick = function() {
			if (confirm("You are about to visit an external web site.\nPassenger Design cannot be held responsible for its content.\n\nAre you sure you want to proceed?")) {
				window.open("http://www." + domain + "/");
			}
			
			return false;
		}
		
		//
		
		var whoisLink = document.createElement("a");
		whoisLink.setAttribute("href", base_url + "?domain=" + name + "&tld=" + tld);
		whoisLink.title = "View whois data";
		whoisLink.appendChild(document.createTextNode("Whois?"));
		
		item.className = "av-no";
		item.title = domain + " is not available";
		
		item.appendChild(link)
		item.appendChild(document.createTextNode(" "));
		
		var smallText = document.createElement("small");
		smallText.appendChild(document.createTextNode("("));
		smallText.appendChild(whoisLink);
		smallText.appendChild(document.createTextNode(")"));
		
		item.appendChild(smallText);
	} else {
		item.className = "av-yes";
		item.title = domain + " is available";
		item.appendChild(label);
	}
	
	list.appendChild(item);
}


