var latestTimerId = 0;
var resultsOpen = 0;
var existingDomain = 0;

 $(document).ready(function() {
	$('#domainDisposition').change( function() {
		if( $(this).val() == 0 ) {
			existingDomain = 0;
			$('#tld').text( '.com .org .net .name' );
			$('#domainName').attr( 'name', 'domainName' );
			$('#domainSearch').attr( 'name', 'domainSearch' );
		}
		// Changing to existing domain
		else {
			existingDomain = 1;
			$('#tld').text( '< Include Domain Extension' );
			$('#domainName').val( '' );
			$('#domainName').attr( 'name', 'hidden_domainName' );
			$('#domainSearch').attr( 'name', 'domainName' );
			closeAndEmptyResults();
		}
	});
 });

function throbberOn() {
	$('#domain_search_throbber').show();
}

function throbberOff() {
	$('#domain_search_throbber').hide();
}

function stopIdleTimer() {
	if( latestTimerId != 0 ) {
		clearTimeout( latestTimerId );
		latestTimerId = 0;
	}
}

function startIdle() {
	stopIdleTimer();
	// Only start the query timer if this is for a new domain
	if( existingDomain == 0 ) {
		$('#whoisHelpText').hide();
		if( resultsOpen != 0 )
			closeAndEmptyResults();
		$('#domainName').val( '' );
		$('#tld').text( '.com .net .org .name' );
		latestTimerId = setTimeout( 'preformWhoisLookup()', 1400 );
	}
}

function preformWhoisLookup() {
	var searchName = $('#domainSearch').val();
	if( searchName.indexOf( '.' ) != -1 ) {
		$('#whoisHelpText').show();
	}
	else {
		throbberOn();
		 $.post( 'whoislookup.php', { domainName: searchName }, updateResults );
	}
}

function updateResults( data ) {
	resultsOpen = 1;
	$('#whoisresults').empty();
	$('#whoisresults').append( '<BR><strong>Domain Results - Click An Open Domain Listed Below</strong><br />' + data );
	applyFunctions();
	throbberOff();
	$('#whoisresults').slideDown( 'slow' );
}

function closeAndEmptyResults() {
	resultsOpen = 0;
	$('#whoisresults').slideUp( 'slow', function(){ $(this).empty(); } );
}

function applyFunctions() {
	$('li').click(function() {
		if( $(this).find('.registered').text() == '' ) {
			$('#domainSearch').val( $(this).find('.domain').text() );
			$('#tld').text( $(this).find('.tld').text() );
			$('#domainName').val( $(this).find('.domain').text() + $(this).find('.tld').text() );
			closeAndEmptyResults();
		}
	});
}
