/***************************************************\
|***** Version detection
\***************************************************/

var iN = navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();
var iDB = (document.compatMode && document.compatMode.toLowerCase() != "backcompat")?document.documentElement:(document.body || null);
var iOP = !!(window.opera && document.getElementById);
var isIE = !!(iN.indexOf("msie") >= 0 && document.all && iDB && !iOP);
var isIE7 = !!(isIE && appVer.indexOf("msie 7.") >= 0);
var isIEmac = !!(isIE && iN.indexOf("mac") >= 0);

/***************************************************\
|***** Main settings & functions
\***************************************************/

function IsEmpty(aText) {
    if ((aText.length==0) || (aText==null)) { return true; }
    else { return false; }
}

function findObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/***************************************************\
|***** Menu & site functions
\***************************************************/

function checkFields () {
	if (
		document.getElementById("feedbackForm").name.value != "" && 
		document.getElementById("feedbackForm").email.value != "" && 
		document.getElementById("feedbackForm").phone.value != "" && 
		document.getElementById("feedbackForm").qType.selectedIndex > 0
	) {
		document.getElementById("additional-fields").style.display = "block";
		document.getElementById("info_message").style.display = "none";
		document.getElementById("req_message").style.display = "none";
	} else {
		document.getElementById("additional-fields").style.display = "none";
		document.getElementById("info_message").style.display = "block";
		document.getElementById("req_message").style.display = "block";
	}
}

function clearFeedback() {
	document.getElementById("feedbackForm").name.value = "";
	document.getElementById("feedbackForm").email.value = "";
	document.getElementById("feedbackForm").phone.value = "";
	document.getElementById("feedbackForm").qType.selectedIndex = 0;
	
	document.getElementById("additional-fields").style.display = "none";
	document.getElementById("info_message").style.display = "block";
	document.getElementById("req_message").style.display = "block";
	
	var obj = findObj("message_window")
	if(obj!=null) {
		obj.style.display = "none";
	}
	
	return false;
}

var activeInfo = 0;
var feedbackObj;
var lastfinishedObj;
var infoViewObj;


function showInfo (text, active) {
	if (!feedbackObj) {
		feedbackObj = findObj("feedbackForm");
	}
	if (!lastfinishedObj) {
		lastfinishedObj = findObj("last-finished");
	}
	if (!infoViewObj) {
		infoViewObj = findObj("infoView");
	}
	
	try {
		window.document.body.focus();
	} catch (e) {
		
	}
	
	if (activeInfo && activeInfo == active) {
		activeInfo = 0;
		hideInfo();
	}
	else if (infoViewObj!=null) {

		infoViewObj.innerHTML= '<div style="margin-bottom:15px;border-top:1px solid #fff;"><a href="#" onclick="return hideInfo();" title="Sulge vaade" class="closeInfoView"><span>Sulge</span></a></div>';
		infoViewObj.innerHTML+= text;
		infoViewObj.style.display = "block";
		
		for (var i = 1; i < 7; i++) {
			var tObj=findObj("s" + i);
			if (i == active) {
				feedbackObj.style.display = "none";
				lastfinishedObj.style.display = "none";
				tObj.className = "";
			} else {
				tObj.className = "inactive";
			}
		}
		
		if (activeInfo && activeInfo != active) {
			var vObj=findObj("p" + activeInfo);
			if(vObj!=null) {
				vObj.className = "flash-animation hidden";
			}
		}
		
		activeInfo = active;
	}
	return false;
}

function hideInfo () {
	if(infoViewObj!=null) {
		infoViewObj.innerHTML = "";
		infoViewObj.style.display = "none";
		activeInfo = 0;
		
		for (var i = 1; i < 7; i++) {
			var tObj=findObj("s" + i);
			if(tObj!=null) {
				tObj.className = "";
			}
			var vObj=findObj("p" + i);
			if(vObj!=null) {
				vObj.className = "flash-animation hidden";
			}
		}
	}
	if (feedbackObj) {
		feedbackObj.style.display = "block";
	}
	if (lastfinishedObj) {
		lastfinishedObj.style.display = "block";
	}
	return false;
}

function showFlash (active) {
	var obj=findObj("p" + active);
	if(obj!=null) {
		obj.className = "flash-animation";
	}
	return false;
}

function hideFlash (active) {
	if (active != activeInfo) {
		var obj=findObj("p" + active);
		if(obj!=null) {
			obj.className = "flash-animation hidden";
		}
	}
	return false;
}

var hideTimer=false;
function show_hide (cur, mid, act) {
	var obj,oid,i=0;
	if(hideTimer){clearTimeout(hideTimer);}
	do{
		oid="subMenu" + i;
		obj=findObj(oid);
		if(obj!=null) {
			if(i==cur){
				if(act=="show"){
					obj.style.display="";
				}else{
					hideTimer=setTimeout("hide_all()", 500);
				}
			}else{
				obj.style.display="none";
			}
		}
	}while (++i&&obj!=null);
}

function hide_all () {
	var obj,oid,i=0;
	do{
		oid="subMenu" + i;
		obj=findObj(oid);
		if(obj!=null) {
			obj.style.display="none";
		}
	}while (++i&&obj!=null);
}

/***************************************************\
|***** Ajax engine
\***************************************************/

function ajaxRequest (url, data, callback, dType, cApply) {
	resXML = (dType == "XML" ? true : false);
	
	function ajaxBindCallback() {
		if (xRequest.readyState == 4) {
			if (xRequest.status == 200) {
				if (ajaxCallback) {
					if (resXML) {
						eval(ajaxCallback + "(xRequest.responseXML.documentElement, ajaxApply)");
					} else {
						eval(ajaxCallback + "(xRequest.responseText, ajaxApply)");
					}
				} else {
					alert("No callback defined!");
				}
			} else {
				alert("There was a problem retrieving the XML data!\n\nStatus: " + xRequest.statusText + " (" + xRequest.status + ")\n\nResponse:\n" + xRequest.responseText);
			}
		}
	}
	
	var xRequest = false;
	var ajaxCallback = callback;
	var ajaxApply = cApply;
	
	if (!(xRequest = getHTTPObject(resXML))) {
		return false;
	} else {
		xRequest.onreadystatechange = ajaxBindCallback;
		try {
			xRequest.open("POST", url, true);
		} catch (e) {
			return false;
		}
		xRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		xRequest.setRequestHeader("X-Prototype-Version", "2.5");
		xRequest.setRequestHeader("Connection", "close");
		xRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		xRequest.send(data);
		return true;
	}
	return false;
}

function getHTTPObject (resXML) {
	var xO = false;
	if (typeof XMLHttpRequest != "undefined") {
		try {
			xO = new XMLHttpRequest();
			if (resXML) {
				xO.overrideMimeType("text/xml");
			} else {
				xO.overrideMimeType("text/html");
			}
			return xO;
		} catch (e) {
			if (isIE7) {
				xO = new XMLHttpRequest();
				return xO;
			} else {
				xO = false;
			}
		}
	} else {
		var msxmls = new Array(
			"Msxml2.XMLHTTP",
			"Msxml2.XMLHTTP.5.0",
			"Msxml2.XMLHTTP.4.0",
			"Msxml2.XMLHTTP.3.0",
			"Microsoft.XMLHTTP"
		);
		for (var i = 0; i < msxmls.length; i++) {
			var msxml = msxmls[i]; 
			try { xO = new ActiveXObject(msxml); return xO; } catch(e) { xO = false; }
		}
	}
	return xO;
}

/***************************************************\
|***** Search specific functions
\***************************************************/

function removeProtection (fID) {
	var rs = fID + "Results";
	var wi = fID + "Waitimage";
	
	var rsm = document.getElementById(rs);
	rsm.className = "";
	
	var wim = document.getElementById(wi);
	wim.style.display = "none";
}

function protectElement (fID) {
	var rs = fID + "Results";
	var wi = fID + "Waitimage";
	
	var rsm = document.getElementById(rs);
	rsm.className = "opacityOn";
	
	var wim = document.getElementById(wi);
	wim.style.display = "block";
}

function advanceSearchPage (itemID, page, resContainerID) {
	window.status = "Palun oodake...";
	protectElement(resContainerID);
	
	if (IsEmpty(resContainerID)) {
        return false;
    }
	
	var Data = "id=" + itemID + "&post[onlySearchResults]=1&post[page]=" + page + "&post[searchType]=" + resContainerID;
    
	return ajaxRequest(pathToIndex, Data, "advanceSearchPageResults", "TEXT", resContainerID);
}

function advanceSearchPageResults (res, fID) {
	window.status = "Done";
	removeProtection(fID);
	
	document.getElementById(fID + "Results").innerHTML = res;
}

function switchObjectImage (id, iSrc) {
    document.getElementById(id).src = iSrc;
}

/***************************************************\
|***** Domain check
\***************************************************/

var intervalToCheckForChange = 250; // in milliseconds, 300 = 0.3sec
var request;
var	statusDivJS;
var	isAvailableDivJS;
var isUsedDivJS;
var	domainInput;
var	extensionSelect;
//var domainsAvailableInput;
var isInProgress = false;
var prevCheckValue = ".ee";
//var whatDomainDivJS;
var intStartCheck;
var isLoaded = false;
var intFailedResponse;
var timesError = 0;

var originalUrl = "";

function checkDomain()
{
	if (isInProgress) return;
	isInProgress = true;
	
	if (extensionSelect == null) {
		isInProgress = false;
		return;
	} else {
		prevCheckValue = domainInput.value + "." + extensionSelect.options[extensionSelect.selectedIndex].value;
	}
	
	re = new RegExp("^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$");
	if (prevCheckValue.match(re) == null)
	{
		setDomainStatus("Invalid Domain (Letters, numbers and hypens only)");
//		statusDivJS.innerHTML = "<span style='color:red;'>Invalid Domain (Letters, numbers and hypens only) <\/span>";
		isInProgress = false;
		return;
	}
	
	setDomainStatus("process", "<div id='domain-processbar'></div><strong>{LNG:inner_domain_check}</strong><br />"+prevCheckValue); // ( <a href='#' onClick='abortRequest();return false;'>Abort<\/a> / <a href='#' onClick='retryRequest();return false;'>Retry<\/a> )
//	statusDivJS.innerHTML = "<span style='color:green;'><img src='prg.gif' height='16' width='16' alt='in progress'>Checking "+prevCheckValue+" ( <a href='#' onClick='abortRequest();return false;'>Abort<\/a> / <a href='#' onClick='retryRequest();return false;'>Retry<\/a> )<\/span>";
	
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		request = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}
	var requestUrl = "dom_check/index.php?aj=&ma="+Math.random()+"&domain="+prevCheckValue;
	request.open("GET", requestUrl, true);
	request.onreadystatechange = processResponse;
	intFailedResponse = setTimeout("failedResponse()",15000);
	
	try {
		request.send(null);
	} catch (e) {
		timesError++;
		setDomainStatus("Error connecting to server ("+timesError+"x)");
//		statusDivJS.innerHTML = "<span style='color:red;'>Error connecting to server ("+timesError+"x)<\/span>";
	}
}
function failedResponse()
{
	if (!isInProgress) return;
	isInProgress = false;
	timesError++;
//	statusDivJS.innerHTML = "<span style='color:red;'>Error connecting to server ("+timesError+"x)(<a href='#' onClick='checkDomain();return false;'>Retry<\/a>)<\/span>";
	request.abort();
	request = null;
}
function retryRequest()
{
	if (!isInProgress) return;
	request.abort();
	isInProgress = false;
	request = null;
//	statusDivJS.innerHTML = "<span style='color:red;'>Retrying<\/span>";
	checkDomain();
}
function abortRequest()
{
	if (!isInProgress) return;
	request.abort();
	isInProgress = false;
	request = null;
//	statusDivJS.innerHTML = "<span style='color:red;'>Aborted<\/span>";
}
function updateDomainTld(tldBox)
{
//	var domainText = domainInput.value;
//	if (domainText.indexOf(".") == -1) return;
//	domainText = domainText.substr(domainText,domainText.indexOf("."));
//	domainInput.value = domainText + "." + tldBox.value;
	domainInput.focus();
}
function processResponse()
{
//	statusDivJS = document.getElementById("statusDiv");
	if (request.readyState == 4)
	{
		clearTimeout(intFailedResponse);
		var requestXML = request.responseXML;
		if ((requestXML != null) && (typeof(requestXML) == "object") && (requestXML.getElementsByTagName("domainname")[0] != null))
		{
//			statusDivJS.innerHTML = "Done (<a href='#' onClick='checkDomain();return false;'>Force Check<\/a>)";
			isInProgress = false;
			var domain = requestXML.getElementsByTagName("domainname")[0].firstChild.data;
			var available = requestXML.getElementsByTagName("available")[0].firstChild.data;
			var errorMsg = "";
			if (requestXML.getElementsByTagName("errorMsg")[0].firstChild != null) {
				errorMsg = requestXML.getElementsByTagName("errorMsg")[0].firstChild.data;
			}
			
			if (originalUrl == "") {
				originalUrl = isAvailableDivJS.href;
			}
			
			if (available == "true")
			{
//				statusDivJS.innerHTML = "<span style='color:green;'>Domain is available!</span>";
//				available = "<span style='color:green;'><b>YES<\/b><\/span>	";
//				if (domainsAvailableInput.value.indexOf(domain +" ") == -1)
//					domainsAvailableInput.value = domainsAvailableInput.value + domain +" \n";
				setDomainStatus("true");
				isAvailableDivJS.href = originalUrl + "&domain=" + domain;
			}
			else
			{
//				statusDivJS.innerHTML = "Domain is not available.";
//				available = "<span style='color:red;'>NO<\/span>";
				setDomainStatus("false");
			}
			if (errorMsg != "")
			{
				setDomainStatus("<strong>"+errorMsg+"</strong>"); // <br />(<a href='#' onClick='checkDomain();return false;'>Retry<\/a>)
//				statusDivJS.innerHTML = "<span style='color:red;'>"+errorMsg+"</span> (<a href='#' onClick='checkDomain();return false;'>Retry<\/a>)";
			}
//			whatDomainDivJS.innerHTML = domain;
//			isAvailableDivJS.innerHTML = available;
		}
		else
		{
			failedResponse();
			return;
		}
	}
	else if (request.readyState == 3)
	{
//		statusDivJS.innerHTML = "Request sent...";
	}
}

function setDomainStatus (state, extra) {
	isAvailableDivJS.style.display = "none";
	isUsedDivJS.style.display = "none";
	statusDivJS.style.display = "none";
	
	if (state == "true") {
		isAvailableDivJS.style.display = "block";
	} else if (state == "false") {
		isUsedDivJS.style.display = "block";
	} else if (state == "process") {
		statusDivJS.style.display = "block";
		statusDivJS.innerHTML = extra;
	} else {
		
	}
}

function checkForChange() {
	if (
		!isLoaded || 
		domainInput.value == ""
	) {
		return;
	}
	
	if (intStartCheck) {
		clearTimeout(intStartCheck);
	}
	
	if (extensionSelect != null) {
		cDomain = domainInput.value;
		cFull = cDomain + "." + extensionSelect.options[extensionSelect.selectedIndex].value;
		
		if (
			(prevCheckValue != cFull) &&
			(prevCheckValue != cDomain))
		{
			intStartCheck = setTimeout("checkDomain()", intervalToCheckForChange);
		} else {
			return;
		}
	} else if (prevCheckValue != (domainInput.value)) {
		intStartCheck = setTimeout("checkDomain()", intervalToCheckForChange);
	}
}

function externalLinks() {
	if (!document.getElementsByTagName){return;}
	var anchors = document.getElementsByTagName("a");
	var len = anchors.length;
	for (var i=0; i<len; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external"){anchor.target = "_blank";}
	}
}

function bodyonLoad() {
	isLoaded = true;
//	setInterval("checkForChange()", intervalToCheckForChange);
	
//	domainInput =  document.getElementById("domainName");
//	extensionSelect =  document.getElementById("extension");
	
//	statusDivJS = document.getElementById("domainProcess");
//	isAvailableDivJS = document.getElementById("domainVacant");
//	isUsedDivJS = document.getElementById("domainInuse");
	
//	setDomainStatus("");
	externalLinks();
}
