﻿var received     = 0;
var expected     = 0;
var checkedTLDs  = new Array();
var chosenTLD    = "";
var chosenTLDId  = "";
var chosenState  = "";
var domainName   = "";
var tlds         = new Array();
var tldIds       = new Array();
var checked      = 0;
var error        = false;
var sidebar 	 = false;

// creates an XMLHttpRequest instance
function createXHR() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    
    // try every id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {} // ignore potential error
    }
  }
  // return the created object
  return xmlHttp;
}


/**
    checks if a given domain is valid 
    for the esarch!

    it basically strips the tld and then checks if the entered values are valid
**/
function validateDomain(url) {
    
	url = (url.indexOf(".") != -1)? url.substring(0, url.indexOf(".")): url;
	
	var pattern=/^[a-zA-Z0-9äöüÄÖÜ]{1}([-a-zA-Z0-9äöüÄÖÜ_]){0,62}?$/;
    if(pattern.test(url)){         
		return true;
    } else{   
		return false;
    }
}


/**
    checks if a given domain is valid, full qualified domainname

    it basically strips the tld and then checks if the entered values are valid
**/
function isValidDomain(url) {
    
	var pattern=/^[a-zA-Z0-9äöüÄÖÜ]{1}([-a-zA-Z0-9äöüÄÖÜ_/.]){0,62}[a-zA-Z0-9]{2-6}.?$/;
    if(pattern.test(url)){         
		return true;
    } else{   
		return false;
    }
}



/**
    checks if a given domain is valid 

    it basically strips the tld and then checks if the entered values are valid
**/
function validateSideBarSearch() {
    
	domain = document.getElementById('domain_search').value;
	
	if (!validateDomain(domain)) {
		alert ('Der Domainname enthält ungültige Zeichen');
		return false;
	}
	
	return true;
}




/**
checks if a given nameserver is valid 

it basically strips the tld and then checks if the entered values are valid
**/
function validateNameserver(nameserver) {


var pattern=/^([-a-zA-Z0-9äöüÄÖÜ_.]{2,62}\.[a-zA-Z]{2,6})$/;
if(pattern.test(nameserver)){         
	return true;
} else{   
	return false;
}
}


/**
*
* checks if a given domain is valid, and then asks noc if the domains area 
* also available
*
*/
function checkDomain(priorityCount) 
{

    received = 0;
	chosenTLD      = "";
	chosenTLDId	   = "";
	chosenState    = "";
	domainName     = "";
	checkedTLDs    = new Array();
	
	var output=document.getElementById("otherdomains");

	//Löschen
	var children=output.childNodes;
	
	var count=children.length;
	
	for(var i=0;i<count;i++) {
		output.removeChild(children[0]);
	}
	
	output=document.getElementById("chosendomain");
	
	//Löschen
	output.innerHTML = "";
	
	var inputs = document.getElementsByTagName("input");
	tlds   = new Array();
	tldIds = new Array();
	
	for(i = 0; i < available_domains.length; i++) {
		tldIds.push(available_domains[i].id);
		tlds.push(available_domains[i].name);
	}
	var url = document.getElementById("domain_search").value;
	
	url = trim(url);

	// check if the tld is available for this customer
	if(url.indexOf(".") != -1) {
	    
	    var tmp = url.substring(url.indexOf(".") + 1, url.length);

		if(!array_contains(tlds, tmp)) {
	        document.getElementById('chosendomain').innerHTML = 'Eine Domain mit dieser Top Level Domain darf von Ihnen nicht angelegt werden';
			return;
		}
		else {
			chosenTLDId = tldIds[array_indexOf(tlds, tmp)];
			url         = url.substring(0, url.indexOf("."));
		}
	}
	// validate the url, and then start the request
	if(validateDomain(url)) {
		
		var requestTlds = new Array();
		
		for(i = 0; i < priorityCount; i++) {
			requestTlds.push(tldIds[i]);
		}
		
		if (chosenTLDId != "" && !array_contains(requestTlds, chosenTLDId)) {
			requestTlds[requestTlds.length] = chosenTLDId;
		}
		expected = requestTlds.length;
		
		try {
			
			document.getElementById("domain_search").disabled = true;
			document.getElementById("check").disabled = true;
			if(document.getElementById("details") != undefined) {
			     document.getElementById("details").className = "myhidden";
			}
			document.getElementById("chosendomain").innerHTML = "Ihre Anfrage wird bearbeitet...";
			if(document.getElementById("loadimage") != undefined) {
			     document.getElementById("loadimage").className = "visible";
			}
			
			if(expected == 0) {
			   var txt = "Es ist ein Fehler aufgetreten. Bitte kontaktieren Sie unseren technischen Support.(TLD missing)";
			    document.getElementById("chosendomain").innerHTML = txt;
			}
			
			for(i = 0; i < expected; i++) {
				handleRequest(url, requestTlds[i]);
			}
		}
		catch(failure) {
			document.getElementById("otherdomains").innerHTML = "";
			
			var ul = document.createElement("ul");
			var li = document.createElement("li");				
							
			ul.name = "errorlist";
			ul.id   = "errorlist";	
					
			li.name = "error";
			li.id   = "error";
				
			li.innerHTML = failure;
				
			ul.appendChild(li);
			
			document.getElementById("otherdomains").appendChild(ul);
		}
	}
}

function handleRequest(domain, tld) {
	var request = createXHR();
	var handleStateChange = function() {
	switch(request.readyState) {
		case 0: break; // uninitialized
		case 1: break; // open
		case 2: break; // sent
		case 3: break; // receiving
		case 4: // loaded
		
				received++;
				if(request.status== 200) { //0 for local destination
					var doc = request.responseXML;
					var state = 'timeout';
					
					// fetch the whois data from the xml
					domainName = doc.getElementsByTagName("domainname")[0].firstChild.nodeValue;
					var tld_id = doc.getElementsByTagName("tld_id")[0].firstChild.nodeValue;
					var price = tldprices[tld_id];
					var tld   = tlds[array_indexOf(tldIds, tld_id)]; 
						
					// if there was nor resterror, and the transfer was ok, check if the domain is free or occupied
					if(doc.getElementsByTagName("resterror").length == 0) {
						if(doc.getElementsByTagName("status")[0].childNodes[0].nodeValue == "ok") {
							
							state = doc.getElementsByTagName("data")[0].getElementsByTagName("status")[0].firstChild.nodeValue;
							state = (state == "free") ? "frei" : "belegt";
						}
					}
					
					// add the domains to the array for displaying later on
					var url = new Array(3);
					url['priority'] = 5;
					url['tld_id']   = tld_id;
					url['tld']      = tld;
					url['price']    = price;
					url['state']    = state;
							
				    // if the current tld is the one the customer searched for (ie: name.at)
				    // then add it to the beginning of the array
					if(chosenTLDId == tld_id) {
					    url['priority'] = 1;
						checkedTLDs.unshift(url);
					}
					// otherwise, at the end
					else {
						checkedTLDs.push(url);
					}
				}
				
				
				// all elements were loaded
				if(received==expected) {
				    
				    if(document.getElementById("loadimage") != undefined) {
					   document.getElementById("loadimage").className = "myhidden";
				    }
					document.getElementById("domain_search").disabled = false;
					document.getElementById("check").disabled 		  = false;
					
					if(document.getElementById("details") != undefined && document.getElementById("details")) {
					   document.getElementById("details").className="btn_next";
					   document.getElementById("details").disabled=true;
				    }
					document.getElementById("chosendomain").innerHTML='';
					
					// replace the domainname in the hiddenfield
					var domainHidden = document.getElementById('domain');
					
					domainHidden.value = domainName;
					
					document.getElementById("choosedomainform").appendChild(domainHidden);
					
					checkedTLDs.sort(tld_sort);
					
					var table  = document.createElement("table");
					var thead  = document.createElement("thead");
					var tbody  = document.createElement("tbody");
					var tr     = document.createElement("tr");
					var td     = document.createElement("th");
					var domain = document.createElement("th");
					var price  = document.createElement("th");
					var state  = document.createElement("th");
					
					domain.innerHTML = "Domain";
					domain.width     = "250px";
					price.innerHTML  = "Preis*";
					price.width      = "100px";
					price.style.textAlign = 'right';
					state.innerHTML  = "Status";
										
					tr.appendChild(td);
					tr.appendChild(domain);
					if (sidebar == false) {
						tr.appendChild(price);
					}
					tr.appendChild(state);
					
					thead.appendChild(tr);
					
					table.appendChild(thead);
					table.appendChild(tbody);
					document.getElementById("otherdomains").appendChild(table);
					
										
					// for all found domains, create a row in the foundtable 
					// to display if a domain is free or not
					for(i = 0; i < checkedTLDs.length; i++) {		
			
					    tr = createDomainStatusRow(checkedTLDs[i]);
					    tbody.appendChild(tr);
					}
					document.getElementById("domain_search").focus();
				}
				break;
	}
}
	
	
	request.onreadystatechange = handleStateChange;
	resturl='resthelper.php?resource=Whois&function=checkDomain';
	request.open('POST',resturl,true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 
	
	request.send("domainname=" + domain + "&tld_id="+tld);
}

function checkDomainName(element) {
    tmp = trim(element.value);
	if(validateDomain(tmp)) {
		triggerDomainClear(element);
	}
	else {
		triggerDomainError(element);
	}
}

function triggerDomainError(element) {
	element.className = 'txt_domainsearch_error';
	
	document.getElementById('error').innerHTML = 'Ung&uuml;ltige Domain (Erlaubt: 0-9, a-z, A-Z und _ ab zweiter Stelle)';
}

function triggerDomainClear(element) {
	element.className = 'txt_domainsearch';
	document.getElementById('error').innerHTML = '&nbsp;';
}

function handleDomainClick(checkbox) {
	if(checkbox.checked) {
		document.getElementById("details").disabled=false;
		document.getElementById("details").className="btn_next";
		checked++;
		
		if(checked > domainsAllowed) {
		    document.getElementById("details").disabled=true;
			document.getElementById("details").className = "btn_next";
			document.getElementById("domain_search").focus();
		}
	}
	else {
		checked--;
		
		if(checked == 0 || checked > domainsAllowed) {
			document.getElementById("details").disabled=true;
			document.getElementById("details").className = "btn_next";
			document.getElementById("domain_search").focus();
		}
		else {
		    document.getElementById("details").disabled=false;
		    document.getElementById("details").className="btn_next";
		}

	}
}

function handleKey(event) {
	if (!event) {
    	event = window.event;
	}
	if(event.keyCode == 13) {
		checkDomain(importantTLDs);
	}
}


function addTableRow(jQtable){
    jQtable.each(function(){
        var $table = $(this);
        // Number of td's in the last table row
        var n = $('tr:last td', this).length;
        var tds = '<tr>';
        for(var i = 0; i < n; i++){
            tds += '<td> </td>';
        }
        tds += '</tr>';
        if($('tbody', this).length > 0){
            $('tbody', this).append(tds);
        }else {
            $(this).append(tds);
        }
    });
}

/**
* create a Domain Status Row for the current TLD
*
* @param array/object checkedDomain  resultset from noc
* 
* @return htmlobject returns a tr (tablerow) element
*/
function  createDomainStatusRow(checkedDomain) {

  // create a new row, and add all elements
	var tr = document.createElement("tr");
	
	var checkTD = document.createElement("td");
	
	// if the domain is free, then create an input box
	if(checkedDomain['state'] == "frei") {
		
		var check   = document.createElement("input");
		
	    check.type      = "checkbox";
	    check.id        = "check"+checkedDomain['tld'];
	    check.className = "domain_chb";
	    check.name      = "check"+checkedDomain['tld'];
	    check.value     = checkedDomain['tld_id'];
	    check.onclick   = function() {handleDomainClick(this);};
	    
	    if(document.getElementById('details') != undefined) {
	      checkTD.appendChild(check);
	    }
	}
	
	tr.appendChild(checkTD);
	
	// assign a classname, depinging if the domain is free (color the lines!)
	if(checkedDomain['state'] == "frei") {
	    tr.className = "free_row";
	}
	else if(checkedDomain['state'] == "belegt") {
	    tr.className = "delegated_row";
	}
	else {
	    tr.className = "error_row";
	}
	
	// assign the details of the table
	var domainTD = document.createElement("td");
	var stateTD  = document.createElement("td");
    var priceTD  = document.createElement("td");
    var trustneeded = '';
    
    for (var j = 0; j < trustonly.length; j++) {
    	if (checkedDomain['tld_id'] == trustonly[j]) {
    		trustneeded = '**';
    	}
    }
    
    stateTD.innerHTML  = checkedDomain['state'];
    domainTD.innerHTML = trim(domainName)+"."+checkedDomain['tld'] + trustneeded;
    
    if(checkedDomain['state'] == "belegt") {
        link = '<a style="text-decoration: none;cursor: pointer" href="http://'+ trim(domainName)+'.'+checkedDomain['tld'] + '" target="_blank">';
        domainname = trim(domainName)+'.'+checkedDomain['tld'] + trustneeded;

        domainTD.innerHTML =  link + domainname + '</a>';  
    }
    
    priceTD.innerHTML  = checkedDomain['price'] + ' € / Jahr';
    priceTD.style.textAlign = 'right';
    
    tr.appendChild(domainTD);
    if (sidebar == false) {
    	tr.appendChild(priceTD);	
    }
    tr.appendChild(stateTD);
    
    return tr;
}



function trim(string) {
    return string.replace (/^\s+/, '').replace(/\s+$/, '');
}