/**
 * parseInput function.
 *
 * @desc splits user input to "domain-name" & "extension". Deletes invalid characters
 * 
 * @access public
 *
 * @param mixed input
 * @param mixed extension
 *
 * @return void
 */
function parseInput(input, extension) 
{
	input = input.toLowerCase();
	input = clearChars(input);
	
	//Check if syntax of input includes possible extensions (.xyz)
	if(input.indexOf('.') == -1)
	{
		urlCheckKeyUp(input, input)
	}

	else
	{
		if(input.lastIndexOf('.')+1 == input.length)
		{
			urlCheckKeyUp(input.substr(0,input.length-1),input);
		}
		else
		{
			domain = input.substr(0,input.lastIndexOf('.'));
			domain = domain.replace(/[.]/g,'');
			
			if(!extension)
			{
				extension = input.substr(input.lastIndexOf('.')+1);
				document.getElementById("checkbox"+extension).checked = 'checked';
				document.getElementById(extension).className = 'visible active';
			}
			
			if(isValidExtension(extension) == false)
			{
				urlCheckKeyUp(domain, domain + '.' + extension);
			}
			else
			{
				urlCheckKeyUp(domain, domain + '.' + extension, extension);
			}
		}
	}	
}


/**
 * urlCheckKeyUp function.
 * 
 * @desc Post output in textfield and call domain check after delay.
 * @access public
 * @param mixed domain
 * @param mixed output
 * @param mixed extension
 * @return void
 */
function urlCheckKeyUp(domain, output, extension)
{
	//put user corrected user search to textfield
	$('#domainInput').val(output);

	
	if (typeof(timeout) != 'undefined') {
        	window.clearTimeout(timeout);
    	}
    	
	if(domain.length > 2) {
		if(typeof(extension) == 'undefined')
		{
			timeout = window.setTimeout('urlCheck("'+domain+'")', 500);
		}
		else
		{
			timeout = window.setTimeout('urlCheck("'+domain+'","'+extension+'")', 500);
		}
	}
}


/**
 * urlCheck function.
 * 
 * @desc call Ajax-Request and build html content (resultstable)
 * @access public
 * @param mixed domain_name
 * @param mixed extension
 * @return void
 */
function urlCheck(domain_name, extension)
{	
	//get Array of configured extensions
	/*
	if(typeof(extension) == 'undefined')
	{
		extensions = getCheckboxExtensions(true);
	}
	else
	{
		extensions = new Array;
		extensions[0] = extension;
	}
	*/
	extensions = getCheckboxExtensions(true);
	
	//join extensions array for post
	extensionsPost = extensions.join(";");
	//build content for xml data
	if(typeof(extension) == 'undefined')
	{
		buildTbodyContent();
	}
	else
	{
		buildTbodyContent(extension);
	}
	
	//set gif loading picture
	for(extensionsCounter = 0;extensionsCounter < extensions.length;extensionsCounter++) {
		extension = extensions[extensionsCounter];
		//set name
		//set domain from input and extension
		domain = htmlentities(domain_name+'.'+extension);
		domain_short = stripText(domain_name)+'.'+extension;
		$("#"+extension+"Name").html('<a href="http://www.'+domain+'" title="'+domain+' besuchen" target="_blank">'+domain_short+'</a>');
		$('#domainresults').css('display','block');
		
		//set picture
		$("#"+extension+"IsAvailable").html('<img src="images/indicator.gif" title="Laden..." alt="Laden..." />');
		
		//unset whois
		$("#"+extension+"Whois").html('');
		
		//output booking checkbox, check if domain is already selected
		if($.cookie('cart') && $.cookie('cart').indexOf(domain) != -1)
		{
			var checked = 'checked="checked"';
		}
		else
		{
			var checked = '';
		}
	    $("#"+extension+"Book").html('<input id="'+domain+'" class="hidden" type="checkbox" value="'+domain+'" onClick="javascript: doCart(this.value)" '+checked+'/>');
	}
	
	execAjaxRequests(domain_name, extensions);
}


/**
 * setExtensions function.
 * 
 * set configured extensions
 * @desc set extensions
 * @access public
 * @param mixed extensions
 * @return void
 */
function setExtensions(extensions) {
	extensionsInputArray = extensions;
	extensionsInputArray = extensionsInputArray.split(',');
}


/**
 * getCheckboxExtensions function.
 * 
 * @desc get checkboxes from sidebarbox (all or selected) and put in Array
 * @access public
 * @param mixed selected
 * @return void
 */
function getCheckboxExtensions(selected) {
	extensionsArray = new Array();
	
	extensionsCounter = 0;
	if(selected == true)
	{
		for(i = 1; i <= extensionsInputArray.length; i++) {
			if($("#checkbox"+extensionsInputArray[i-1]).attr('checked')) {
				extensionsArray[extensionsCounter] = extensionsInputArray[i-1];
				extensionsCounter++;
			}
		}
	}
	else
	{
		extensionsArray = extensionsInputArray;
	}
	
	return extensionsArray;
}


/**
 * buildTbodyContent function.
 * 
 * @desc build table-rows for extensions, show selected, hide unselected, highlight if extension was given by user
 * @access public
 * @param mixed highlight
 * @return void
 */
function buildTbodyContent(highlight) {
	for(i = 0; i < extensionsInputArray.length; i++) {
		extension = extensionsInputArray[i];
		if($("#checkbox"+extension).attr('checked')) {
			//make row visible
			document.getElementById(extension+"Row").className = 'results_row';
			if(extension == highlight)
			{
				document.getElementById(extension+"Row").className = 'results_row highlight';
			}
		}
		else
		{
			//dont show row
			document.getElementById(extension+"Row").className = 'hidden';
		}
	}
}


/**
 * htmlentities function.
 * 
 * @desc equivalent to php-function "htmlentities"
 * @access public
 * @param mixed str
 * @param mixed typ
 * @return void
 */
function htmlentities(str,typ) {
if(typeof str=="undefined") str="";
if(typeof typ!="number") typ=2;
typ=Math.max(0,Math.min(3,parseInt(typ)));
var html=new Array();
html[38]="&amp;"; html[60]="&lt;"; html[62]="&gt;";
if(typ==1 || typ==3) html[39]="&#039;";
if(typ==2 || typ==3) html[34]="&quot;";
	for(var i in html) eval("str=str.replace(/"+String.fromCharCode(i)+"/g,\""+html[i]+"\");");
		var entity=new Array(
		"&nbsp;","&iexcl;","&cent;","&pound;","&curren;","&yen;","&brvbar;","&sect;",
		"&uml;","&copy;","&ordf;","&laquo;","&not;","&shy;","&reg;","&macr;",
		"&deg;","&plusmn;","&sup2;","&sup3;","&acute;","&micro;","&para;","&middot;",
		"&cedil;","&sup1;","&ordm;","&raquo;","&frac14;","&frac12;","&frac34;","&iquest;",
		"&Agrave;","&Aacute;","&Acirc;","&Atilde;","&Auml;","&Aring;","&AElig;","&Ccedil;",
		"&Egrave;","&Eacute;","&Ecirc;","&Euml;","&Igrave;","&Iacute;","&Icirc;","&Iuml;",
		"&ETH;","&Ntilde;","&Ograve;","&Oacute;","&Ocirc;","&Otilde;","&Ouml;","&times;",
		"&Oslash;","&Ugrave;","&Uacute;","&Ucirc;","&Uuml;","&Yacute;","&THORN;","&szlig;",
		"&agrave;","&aacute;","&acirc;","&atilde;","&auml;","&aring;","&aelig;","&ccedil;",
		"&egrave;","&eacute;","&ecirc;","&euml;","&igrave;","&iacute;","&icirc;","&iuml;",
		"&eth;","&ntilde;","&ograve;","&oacute;","&ocirc;","&otilde;","&ouml;","&divide;",
		"&oslash;","&ugrave;","&uacute;","&ucirc;","&uuml;","&yacute;","&thorn;","&yuml;"
		);
		for(var i in entity) eval("str=str.replace(/"+String.fromCharCode(i*1+160)+"/g,\""+entity[i]+"\");");
			return str;
		
}


/**
 * isValidExtension function.
 * 
 * @desc check, if extension give by user is valid
 * @access public
 * @param mixed extension
 * @return void
 */
function isValidExtension(extension)
{	
	extensionsArray = getCheckboxExtensions(false);
	for(i=0; i<extensionsArray.length; i++)
	{
		if(extension == extensionsArray[i])
		{
			return true;
		}
	}
	return false;
}


/**
 * stripText function.
 * 
 * @desc cut long strings. (for output in results table)
 * @access public
 * @param mixed text
 * @return void
 */
function stripText(text)
{
	if(text.length > 20)
	{
		text = text.substr(0,15) + '[...]';
	}
	return text;
}


/**
 * clearChars function.
 * 
 * @desc deletes invalid characters from input-string
 * @access public
 * @param mixed string
 * @return void
 */
function clearChars(string)
{
	var invChars = new Array (' ',',',':','#','!','"','§','$','%','&','\/','(',')','=','?','^','\\','[',']','|','{','}');
	for(var i=0; i < invChars.length; i++)
	{
		string = string.replace(invChars[i], '');
	};
	
	
	return string;
}


/**
 * execAjaxRequests function.
 * 
 * @desc Do Ajax-Request for each extension
 * @access public
 * @param mixed domain_name
 * @param mixed extensions
 * @return void
 */
function execAjaxRequests(domain_name, extensions)
{
	xmlHttpArr = new Array();
	
	for (i=0;i<extensions.length;i++)
	{
		// create Ajax-Request
		var xmlHttpObj = null;
		try
		{
			xmlHttpObj = new XMLHttpRequest();
		}

		catch (e)
		{
			try
			{
				xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e)
			{
				try
				{
				xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
				} 
				catch (failed)
				{
					xmlHttpObj = null;
				}
			}  
		}
	 
		if(xmlHttpObj == null)
		{
			alert("Dein Browser unterstützt kein AJAX");
		}
		
		if(typeof(xmlHttpArr[i]) != 'undefined')
		{
			if(xmlHttpArr[i].request != null)
			{
				xmlHttpArr[i].request.transport.abort();
				xmlHttpArr[i].request = null;
			}
		}
		
		var domain = domain_name + '.' + extensions[i];
		xmlHttpObj.open("GET","classes/whois.class.php?q="+domain+"&ext="+extensions[i],true);
		xmlHttpObj.onreadystatechange = parseResult;
		xmlHttpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlHttpObj.send(null);
		xmlHttpArr.push(xmlHttpObj);
	}
}


/**
 * parseResult function.
 * 
 * @desc check response of Ajax-Request and edit html-content
 * @access public
 * @return void
 */
function parseResult()
{
	for(i=0;i<xmlHttpArr.length;i++)
	{
		if(xmlHttpArr[i].readyState==4)
		{
			if (xmlHttpArr[i].status==200)
			{
				var responseArray = xmlHttpArr[i].responseText.split(";");
				var isAvailable = responseArray[0];
				var domain = responseArray[1];
				var extension = responseArray[2].replace(/[\s]/g, '');
				if(isAvailable == 'true')
				{
					var isAvailableHtml = '<span class="free">verf&uuml;gbar</span>';
					document.getElementById(domain).className = 'visible';
				}
				else
				{
					var isAvailableHtml = '<span class="busy">belegt</span>';
					$("#"+extension+"Whois").html('<a href="http://www.platinpower.com/wp-content/plugins/domaincheck/whois.php?d='+domain+'" onclick="return GB_showCenter(\'Whois Abfrage\', this.href,500,500)">Whois</a>');
				}
			
				//output in table
				$("#"+extension+"IsAvailable").html(isAvailableHtml);
			}
		}
	}
}

