var tldList = new Array();
getTlds();

$(document).ready(function(){
	$('#whoisres').hide();
	$('#wclose').click(function() {
		$('#whoisres').hide();
	});
	
	$("#domsearch").keypress(function (e) {  
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
            $('#sbtn').click();  
            return false;  
        } else {  
            return true;  
        }  
    });
	
	$('#sbtn').click(function() {
		var commonDom = new Array();
		commonDom = ['dk','com','net','org','eu'];
		
		var d = $('#domsearch').val();
		
		// Split domain into sld / tld
		var domObj = parseDom(d.toLowerCase());
		
		// Validate syntax of domainname
		if (validateDomainName(domObj.sld) == false) {
			$('#sbtn > img').attr({ src: "/images/gul_trekant2.png" });
			return false;
		} else {
			$('#sbtn > img').attr({ src: "/images/search_knap.png" });
		}
		
    	//Disable Input
    	$('#domsearch').attr('disabled','true');

		// Er Tld iblandt vores commonDom
		var fdom = false;
		
		for (d in commonDom) {
			// Show Spinner
			$('#' + commonDom[d]).empty().append(domObj.sld + '.' + commonDom[d]).removeClass('ta').addClass('td');
			$('#' + commonDom[d] + 'status').empty().addClass('spinner').append('...........................');
			
			// Show cust or not?
			if (commonDom[d] == domObj.tld)
				fdom = true;
		}
	
		if (isEmpty(domObj.tld))
			fdom = true;		


		// Position and Show result div
		var iloc = $('#domsearch').position();
		var offset = $('#domsearch').width() - $('#whoisres').width();

		$('#whoisres').css({
			top: (iloc.top + 30),
			left: iloc.left + offset
		});
		$('#whoisres').show();

		
		if (fdom) {
			// Domain found
			$('#custtr').hide();
		} else {
			// Domain not found in list, show cust
			$('#custtr').show();
			$('#cust').empty();
			queryDom('domain=' + domObj.domain + '&id=cust', domObj.sld, domObj.tld);
		}
		
		// Loop over common domains
		for (d in commonDom) {
			queryDom('domain=' + domObj.sld + '.' + commonDom[d] + '&id=' + commonDom[d], domObj.sld, commonDom[d]);
		}
		
		$(':input').removeAttr('disabled');
	});
	
	    
    // Fold pristabel ud
    //$('#pristabel').hide();


    $('#prisheader').toggle(
    	function(){
          $('#prisheader img').attr({ src: "/images/pris_knap_over.png" });
          $('#pristabel').slideDown('fast');  
        },
        function(){
          $('#prisheader img').attr({ src: "/images/pris_knap.png" });
          $('#pristabel').slideUp('fast');  
        }
    );
});

function queryDom(params,sld,tld){
	jQuery.ajax({
      data: params,
      url: 'http://danhost.dk/whoisapi/remote.php',
      type: 'post',
      timeout: 8000,
      dataType: 'json',
      error: function(result) {
       	errTxt = "Timeout";
		$('#' + result.id).empty().append(errTxt);
		$('#' + result.id).css('background-color','#00f');
      },
      success: function(result) {
        if (result.free == 'Avail') {
			// Set Text
			$('#' + result.id).empty().append(result.domain);
        	errTxt = '<img width="16" height="16" align="absmiddle" src="/images/available.png"/>';
			errTxt = errTxt + '<a href="http://danhost.dk/bestil/?dof='+ sld +'&tldof='+ tld +'&hotel=6">Bestil</a>';
			$('#' + result.id + 'status').empty().append(errTxt);
			
			// Set Classes
			$('#' + result.id + 'status').removeClass('ocupat').removeClass('spinner');
			$('#' + result.id).removeClass('ta').addClass('td');	
        } else if (result.free == 'Taken') {
			// Set Text
			$('#' + result.id).empty().append(result.domain);
        	errTxt = '<img width="16" height="16" align="absmiddle" src="/images/taken.png"/>';
			errTxt = errTxt + '<a href="http://danhost.dk/bestil/?dof='+ sld +'&tldof='+ tld +'&hotel=6&action=1">Flyt</a>';
			$('#' + result.id + 'status').empty().append(errTxt);
			
			// Set Classes
			$('#' + result.id + 'status').addClass('ocupat').removeClass('spinner');
			$('#' + result.id).removeClass('td').addClass('ta');
        } else {
			$('#' + result.id).empty().append(result.domain);
        	errTxt = '<img width="16" height="16" align="absmiddle" src="/images/taken.png"/>Fejl';
			$('#' + result.id + 'status').empty().append(errTxt);
			
			// Set Classes
			$('#' + result.id + 'status').addClass('ocupat').removeClass('spinner');
			$('#' + result.id).removeClass('td').addClass('ta');
		}
      }
    });
}

// Return list of Tlds from server
function getTlds(){	
	jQuery.ajax({
      data: 'func=getTlds',
      url: 'http://danhost.dk/whoisapi/remote.php',
      type: 'post',
      timeout: 4000,
      dataType: 'json',
      error: function(result) {
       	errTxt = "Timeout";
      },
      success: function(result) {
		for (var i in result) {
		 	tldList[result[i]] = 1;
		}
      }
    });
}

function parseDom(domain){
	var rdom;
	var rtld;
	var r = {};
	var tld = tldList;
	
	var parts = domain.split(".",3);

	// If no tld is specified return only sld
	if (isEmpty(parts[1])) {
		r['domain']	= domain;
		r['tld']	= false;
		r['sld']	= domain;
		return r;
	}

	if (parts[2]) {
		if (tld[parts[1] + '.' + parts[2]]) {
			rtld = parts[1] + '.' + parts[2];
			rdom = parts[0];
		} else if (tld[parts[2]]) {
			rdom = parts[0] + '.' + parts[1];
			rtld = parts[2];			
		} else {
			rdom = false;
			rtld = false;
		}
	} else {
		if (tld[parts[1]]) {
			rdom = parts[0];
			rtld = parts[1];			
		} else {
			rdom = parts[0];
			rtld = false;
		}
	}
	
	r['domain']	= domain;
	r['tld']	= rtld;
	r['sld']	= rdom;
	return r;
}

function isEmpty( inputStr ) { if ( null == inputStr || "" == inputStr ) { return true; } return false;}


function validateDomainName(domain) {
	if(domain.length >= 2 && domain.length <= 57) {
		for(var i=0; i<domain.length; i++) {
			var c = domain.charAt(i);
			var h = c.charCodeAt(0);
			if((h > 47 && h<58) || (h > 96 && h<123) || h==45 || h==46 || h==229 || h==230 || h==248) {
				if((i==0 || i==domain.length-1) && h == 45) {	
					// Domain must not start or end with -
					return false;
				}
			} else {
				// Domain contains invalid characters
				return false;
			}
		}
	} else {
		// Domain too short or too long
		return false;
	}

	// Domain validates
	return true;
}
