// global vars
var $results;
var $inventory;
var $inventorylist;
var $spinner;
var primaryDomain;
var $messages;
var $btnregister;
var $noinventory;
var $noresults;
var $resultscontainer;
var $inventorycost;
var domainInventory = [];
var domainResults = [];
var maxDomainYears = 5;

jQuery.preloadImages = function()
{
	for(var i = 0; i<arguments.length; i++)
	{
		jQuery("<img>").attr("src", arguments[i]);
	}
};

$.preloadImages("/images/domain-yearup.gif", "/images/domain-yeardown.gif", "/images/domain-add.gif", "/images/domain-remove.gif", "/images/searchbutton-pressed.jpg");


function doSearch(domainName){
	if (domainName.split(".").length < 2){
		domainName = domainName +  ".com";
	}
	
	// action consolidated to lookup
	var action = "lookup";
	
	var qs = "?domain=" + domainName + "&action=" + action;
	
	if ($("input[name$=radiosearchoptions]:checked").val() == "common"){ 
		qs += "&tlds=common";
	}

	$.ajax({
		type: "GET",
		url: "/domains/" + qs,
		cache: false,
		dataType: "json",
		beforeSend: beginRequest,
		complete: endRequest,
		success: 
			function(reply){
		
				if (reply.result.count > 0){
					$.each(reply.result.domains.domain, function(i, domain){
						var available = (domain.status == "taken") ? false : true;

						(domain.name == domainName) ? showLookup(domain.name, available, true) : showLookup(domain.name, available, false);

					});
				}else{
					// no results - we shouldn't be here
					showMessage("Oops, looks like trouble on our end. Please try again.");
				}
			}
		}
	);
	
}

function beginRequest(){
	// swap the image button and disable it
	$("input[name$='searchdomain']")
		.attr("src", "/images/searchbutton-pressed.jpg")
		.attr("disabled", "true")
		.css("cursor", "wait");
		
		
	// hide the legend
	$("#legend").hide();
		
	// show the results
	$("#resultscontainer").show();

	// show the spinner
	$spinner.show();
	
	// reset the results
	resetResults();
	
	// hide any messages
	hideMessages();
	
	//$("#results").height("");
}

function endRequest(){
	// swap the image button back and enable
		$("input[name$='searchdomain']")
		.attr("src", "/images/searchbutton.jpg")
		.removeAttr("disabled")
		.css("cursor", "default");
		
	// hide the spinner
	$spinner.hide();
	
	// show the legend
	$("#legend").show();

	
	// resize the results div to be the height it is after the
	// search to prevent grow/shrink when moving domains around
	//console.log($("#results").height());
	//$("#results").height($("#results").height());
}

function showLookup(domain, available, primary){
	//console.log(domain + "," + available + "," + primary);
	
	// if the domain is in the results or inventory, bail out
	if (inResults(domain) || inInventory(domain)){
		return false;
	}
	
	// add to results array
	domainResults.push(domain);
	
	// hide no results msg.
	$noresults.hide();
	
	$row = getResultRow(domain, available, primary);
	$row.hide();
	
	if (primary && $results.find("div.domaininfo").length > 0){
		// prepend so it shows at the top
		$results.find("div.domaininfo").prepend($row);
		//console.log("prepending: " + domain);
	}else{
		$results.append($row);
		//console.log("appending: " + domain);
	}
	
	$row.fadeIn("fast");
}

function getResultRow(domain, available, primary){
		
	$row = $('<div class="domaininfo"/>').attr("id", domain);
	$status = $('<div class="status"/>');
	$domain = $('<div class="domain" />').html(domain);
	var price = getPrice(domain);
	$price = $('<div class="price">')
		.html("$" + price + "/year")
		.attr("rel", price);
	
	var $icon;
		
	if (available){
		$icon = $('<img src="/images/domain-add.gif" />');
		$icon.attr("title", "available");
		$status.css("cursor", "pointer");
		$row.click(function(){
			//remove from results and add to inventory
			addToInventory($(this), domain, available, null);
		});
	}else{
		$icon = $('<img src="/images/domain-taken.gif" />');
		$icon.attr("title", "taken");
	}
	
	$status.append($icon);
	
	$row.append($status).append($domain).append($price);

	return $row;
}

function getInventoryRow(domain, years){
	var yearIncrement = getYearIncrement(domain);
	var years = (years || yearIncrement);

	

	$row = $('<div class="domaininfo"/>').attr("rel", domain);
	
	$status = $('<div class="status"/>')
		.attr("cursor", "pointer")
		.click(function(){
			removeFromInventory(domain);
		});
	
	$domain = $('<div class="domain" />').html(domain);
	
	var price = getPrice(domain);
	$price = $('<div class="price">')
		.html("$" + price * years)
		.attr("rel", price);
		
	$yearchanger = $('<div class="yearchanger"/>');
	$years = $('<div class="years" />').html(years + " year(s)");
	
	
	$yearup = $('<img src="/images/domain-yearup.gif" />')
		.attr("title", "add a year")
		.attr("cursor", "pointer")
		.click(function(){
			$(domainInventory).each(function(i){
				var yrs = domainInventory[i].years;

				if (domainInventory[i].domain == domain){
					// add a increment up to max
					if (yrs < maxDomainYears) domainInventory[i].years = yrs + yearIncrement;
					var price = domainInventory[i].price * domainInventory[i].years;
					$("div.domaininfo[rel=" + domain + "] div.price")
						.html("$" + price)
						.attr("rel", price);
						//console.log(domain);
					
					$("div.domaininfo[rel=" + domain + "] div.years")
						.html(domainInventory[i].years + " year(s)");

					// update inventory cost
					updateInventoryCost();
				}
			});
		});

	$yeardown = $('<img src="/images/domain-yeardown.gif" />')
		.attr("title", "remove a year")
		.attr("cursor", "pointer")
		.click(function(){
			$(domainInventory).each(function(i){
				var yrs = domainInventory[i].years;

				if (domainInventory[i].domain == domain){
					// remove an increment
					if (yrs > yearIncrement){
						domainInventory[i].years = yrs - yearIncrement;
						if (domainInventory[i].years < yearIncrement) domainInventory[i].years = yearIncrement;
					} 
					var price = domainInventory[i].price * domainInventory[i].years;
					$("div.domaininfo[rel=" + domain + "] div.price")
						.html("$" + price)
						.attr("rel", price);
						//console.log(domain);

					$("div.domaininfo[rel=" + domain + "] div.years")
						.html(domainInventory[i].years + " year(s)");
						
					// update inventory cost
					updateInventoryCost();
				}
			});
		});
	
	
	var $icon = $('<img src="/images/domain-remove.gif" />');
	
	$yearchanger.append($yearup).append($yeardown);
	
	$status.append($icon);
	
	$row.append($status).append($domain).append($price).append($years)
	.append($yearchanger);

	return $row;
}

function addToInventory($row, domain, available, years){
	years = (years || getYearIncrement(domain));
	// hide any messages
	hideMessages();
	
	// show the register button
	$btnregister.show();
	
	// check to see if we're already in inventory
	if (inInventory(domain)){
		showMessage(domain + " is already in your inventory");
		return;
	}
	
	// add to inventory array
	//console.log("saving to inventory: " + domain);
	domainInventory.push(
		new InventoryItem(
			domain, 
			getPrice(domain), 
			years
		)
	);
	//console.log("inventory array after add...");
	//console.dir(domainInventory);
	
	// remove from result array
	$(domainResults).each(function(i){
		if (domainResults[i] == domain)
		{
			//console.log("removing from result array: " + domain);
			domainResults.splice(i, 1);
		}
	});
	//console.log("results array after inv. add...");
	//console.dir(domainResults);
	
	// hide no inventory div
	$noinventory.hide();
	
	if ($row){
		// remove from results
		$row.fadeOut("fast", function(){
			$row.remove();
		});

		// if last result show msg
		if ($("#results div.domaininfo").length == 0){
			$noresults.show();
		}
	}
		
	$newrow = getInventoryRow(domain, years);
	
	// hide it and add to inventory div
	$newrow.hide();
	$inventorylist.append($newrow);
	$inventorylist.show();
		
	// show it
	$newrow.fadeIn('fast');
	
	// update inventory total
	updateInventoryCost();
	
	// update cookie
	serializeInventoryToCookie();
}

function removeFromInventory(domain){
	// hide any messages
	hideMessages();
	
	// remove from the array
	$(domainInventory).each(function(i){
		//console.log(i);
		if (this.domain == domain)
		{
			domainInventory.splice(i, 1);
		}
	});
	
	// update cookie
	serializeInventoryToCookie();
	//console.log("inventory array after remove...");
	//console.dir(domainInventory);
	
	// check to see if we're already in results
	if (inResults(domain)){
		//console.log("in results, so don't remove from inv.: " + domain);
		return;
	}
	
	// add to results array
	domainResults.push(domain);
	
	// hide no results div
	$noresults.hide();
	
	
	
	// remove from inventory
	$row = $("div[rel='" + domain + "']");
	$row.fadeOut(function(){
		$(this).remove();
		
		// update inventory total
		updateInventoryCost();
		
		// if last inventory item being removed
		if ($inventorylist.find("div.domain").length == 0){
			$noinventory.show();
			$btnregister.hide();
			$inventorycost.hide();
		}
	});

	$newrow = getResultRow(domain, true, false);
	$newrow.hide();
	$results.append($newrow);
	$newrow.fadeIn('fast');

}

function updateInventoryCost(){
	var invTotal = 0;
	
	/*
	$inventory.find("div.domaininfo div.price").each(function(){
		//console.log($(this).attr("rel"));
		invTotal += parseInt($(this).attr("rel"));
	});
	*/
	$(domainInventory).each(function(i){
		var years = domainInventory[i].years;
		var price = domainInventory[i].price;
		invTotal += (years * price);
	});
	
	$inventorycost.html("Total: $" + invTotal);
	$inventorycost.show();
}
	
function showMessage(msg){
	$messages.append($("<p />").html(msg)).fadeIn("fast");
}

function hideMessages(){
	// hide and remove contents
	$messages.hide();
	$messages.empty();
}

function inInventory(domain){
	var inlist = false;
	
	
	$(domainInventory).each(function(i){
		if (domainInventory[i].domain === domain)
		{
			inlist = true;
			return true;
		}
	});
	
	return inlist;
}

function inResults(domain){
	var inlist = false;
	
	
	$(domainResults).each(function(i){
		if (domainResults[i] === domain)
		{
			inlist = true;
			return true;
		}
	});
	
	return inlist;
}

function resetResults() {
	$results.find("div.domaininfo").remove();
	$noresults.show();
	domainResults = [];
	
}

function registerDomains(){
	var qs = '';
	$(domainInventory).each(function(i){
		qs += domainInventory[i].domain + ':' + domainInventory[i].years + ';';
	});
	//console.log(qs);
	qs = qs.slice(0, qs.length - 1);
	location.href = '/domains/?action=register&register=' + qs;
}

$(document).ready(function(){
	
	// if the querystring has nojs=1 then bail out
	if (location.href.match(/nojs\=1/)){
		return;
	}
	
	// common items
	$results = $("#results");
	$inventory = $("#inventory");
	$inventorylist = $("#inventorylist");
	$messages = $("#messages");
	$btnregister = $("#btnregister");
	$noinventory = $("#noinventory");
	$noresults = $("#noresults");
	$spinner = $("#spinner");
	$resultscontainer = $("#resultscontainer");
	$inventorycost = $("#inventorycost");
	

	
	
	// set up click handler for search button
	$("input[name$='searchdomain']").click(function(){
		domainName = $("input[name$='domainname']").val();
		if (domainName !== ''){
			doSearch(domainName);
		}else{
			showMessage('Please enter a domain name to search.');
			$("input[name$='domainname']")[0].select();
		}
		return false;
	});
	

	// set up click handler for register button
	$btnregister.click(function(){
		registerDomains();
		return false;
	});
	
	// add inventory from cookie
	if ($.cookie('DomainInventory') != null){
		var domains = $.cookie('DomainInventory').split(';');
		//console.log($(domains).size());
		$(domains).each(function(i){
			var years = domains[i].split(',')[1];
			var domain = domains[i].split(',')[0];
			//console.log("calling addToInventory for cookie");
			
			addToInventory(
				null,
				domain,
				true,
				years
			);
		});
		updateInventoryCost();
		$resultscontainer.show();
	}

	$("input[name$='domainname']")[0].focus();

});//onready
