var Controller = ObjClass.extend({
	nicArConnector: null,
	timeredSearch: null,
	cache: null,
	loader: null,
	init: function()
	{
		var $this = this;
		this.nicArConnector = newInstance(NicArConnector,{callbackFunction: function(data){
			$this.callbackFunction(data);
		}});
		
		this.timeredSearch = newInstance(TimeredSearch,{$html: "#searchDomain", controller: this});
		this.resultsDisplay = newInstance(ResultsDisplay,{$html:"#results"});
		this.domainList = newInstance(DomainList,{$html:"#availablesDomains",$cleanBtn:"#clean"});		
		this.cache = newInstance(Cache);
		this.loader = newInstance(Loader,{$html: ".loader"});
	},
	checkDomain: function(name)
	{
		var $this = this, cachedResponse, request = {"name":name};
		if(name == "")
		{
			this.loader.off();
			this.resultsDisplay.clearMsg();
		}
		else if(!request.name.match("^([a-zA-Z0-9áàãéêíóõúüçñ]|[a-zA-Z0-9áàãéêíóõúüçñ]+[-a-zA-Z0-9áàãéêíóõúüçñ]*[a-zA-Z0-9áàãéêíóõúüçñ]+)$"))
		{
			$this.callbackFunction({"disp":"-1","name":request.name});
		}
		else if(request.name.length < 2)
		{
			$this.callbackFunction({"disp":"0","name":name});
		}
		else if(cachedResponse = $this.cache.get(request.name))
		{
			if(cachedResponse.disp != "-9")
				$this.callbackFunction(cachedResponse);
		}
		else
		{
			this.loader.on();
			this.cache.add(request.name,{"disp":"-9","name":request.name});
			this.nicArConnector.doRequest(request);
		}
	},
	callbackFunction: function(data)
	{
		if(data.disp == "0" || data.disp == "-1")
			this.cache.add(data.name,data);
		else
			this.cache.remove(data.name);
			
		if(data.disp == "1")
			this.domainList.addItem(data);

		if(data.name == this.timeredSearch.getValue())
		{
			this.loader.off();
			switch(data.disp)
			{
				case "2":
					this.resultsDisplay.setMsg({"class":"error","text":"En proceso de baja: <strong>" + data.name + ".com.ar</strong>"});
				break;
				case "1":
					this.resultsDisplay.setMsg({"class":"ok","text":"Disponible: <strong>" + data.name + ".com.ar</strong>"});
				break;
				case "0":
					this.resultsDisplay.setMsg({"class":"error","text":"No Diponible: <strong>" + data.name+".com.ar</strong>"});
				break;
				case "-1":
					this.resultsDisplay.setMsg({"class":"error","text":"Dominio inválido: <strong>" + data.name + ".com.ar</strong>"});
				break;
				case "-2":
					this.resultsDisplay.setMsg({"class":"error","text":"Error consultado: <strong>" + data.name + ".com.ar</strong>"});
				break;
				case "-3":
					this.resultsDisplay.setMsg({"class":"error","text":"Error de conexion consultado: <strong>" + data.name + ".com.ar</strong>"});
				break;			
			}
		}
	}
});
