var ApartmentsController = new Class({
	
	Extends: WindowController,
	
	active : false,
	
	options: {
		resultsContainer	: "results",
		favoritesContainer	: "favorites",
		mapContainer		: "mapContainer",
		mapCanvas			: "canvas"
	},
	
	ajaxProperties: {
		AJAX_KEY_CRS_ID : "CRS_ID",
		AJAX_KEY_APARTMENT_ID : "APARTMENT_ID",
		AJAX_KEY_CURRENT_OFFSET : "CURRENT_OFFSET",
		AJAX_KEY_NUMBER_OF_RESULTS : "NUMBER_OF_RESULTS",
		AJAX_KEY_TOTAL_RESULTS : "totalResults"
	},
	
	currentOffset : 0,
	numberOfResults : 5,
	totalResults:0,
	
	stepNumber 	: 3,
	stepTitle	: "Resultados",
	
	initialize: function(container, options)
	{
		this.parent(container);
		this.setOptions(options);
		this.bus = new SearchBus();
		this.registerEvents();
		
		this.mapContainer 		= $(this.options.mapContainer);
		this.favoritesContainer = $(this.options.favoritesContainer)
			
		this.resetOffset();	
			
		this.header.dispose();	
		this.hideChildren();
		//this.compareNShare			= new CompareNShare();
	},
	
	resetOffset: function()
	{
		this.currentOffset = 0;
		this.numberOfResults = 5;
		this.totalResults = 0;
	},
	
	setUp: function()
	{
		this.parent();
		
		this.map = new PublicMap(this.options.mapCanvas);
		this.map.hideMap();
		this.apartmentsPanel 	= new ApartmentsPanel(this.options.resultsContainer);
		
		this.info.removeEvents("click");
		
		this.blankStateElement = new Element("div", {"class":"blankState"});
		
		this.searchButton = new Element("a", {"id":"searchButton", "class":"disabled", "text":"Buscar apartamentos", "href":"#"}).inject(this.container, "top");
		this.searchButton.addEvent("click", function(e){if(e)e.stop()});
		this.searchButton.addEvent("click", this.showButtonDisabledInfo.bind(this));
		
		this.getMoreApartmentslink = new Element("a", {id:"getMoreApartments", href:"#", text:"test"});
		this.getMoreApartmentslink.addEvent("click", function(e){if(e)e.stop()});
		this.getMoreApartmentslink.addEvent("click", this.moreResults.bind(this));
		this.feedbackTextAfter = new Element("span", {"class" : "feedbackText"});
		this.feedbackTextBefore = new Element("span", {"class" : "feedbackText"});
		this.feedbackTextAfter.inject($(this.options.resultsContainer), 'after');
		this.feedbackTextBefore.inject($(this.options.mapCanvas), 'before');
		
		this.moreApartmentsLoader = new Element("div",{"class" : "moreApartmentsLoader"});
		
		this.createMapButtons();
	},
	
	showButtonDisabledInfo: function()
	{
		if($defined(this.searchFeedback))
		{
			this.searchFeedback.destroy();
		}
		
		this.searchFeedback = new Element("div", {id:'searchFeedback', text:"Para poder realizar una búsqueda es necesario seleccionar unas fechas de estancia"}).inject(this.searchButton, "after");
	},
	
	resetSearch: function()
	{
		this.loading();
		new Request.JSON({url:"public/searchcontroller/resetsearch", onComplete: function(response){
			
			document.location.href = document.location.protocol + "//" + document.location.hostname + document.location.pathname;
		}.bind(this)}).send();
	},
	
	injectMinimizedInfo: function()
	{
		if(!$defined(this.infoContent))
		{
			this.createInfoContent();
		}
		
		this.info.inject(this.container, "top");
		this.maximizeButton.inject(this.info);
	},
	
	createInfoContent: function()
	{
		this.infoContent = new Element("h1" ,{"class":"stepTitle"}).inject(this.info)
		this.info.inject(this.container, "top");
		this.firstNumber = new Element("span", {"class":"number", text:"3"}).inject(this.infoContent);
		this.firstTitle = new Element("span", {"class":"title", text:"Resultados"}).inject(this.infoContent);
		
		this.firstTitle.addEvent("click", function(){
			this.apartmentsPanel.returnToApartmentsList();
			this.maximize();
		}.bind(this));
	},
	
	createHeader: function()
	{
		this.header 		= new Element("h1", {"class":"stepTitle"}).inject(this.container, "top");
		this.titleHeader	= new Element("span", {"class":"title", "html":""+this.stepTitle+""}).inject(this.header);
	},
	
	getBlankStateHTML: function()
	{
		this.loading();
		new Request.JSON({url:"public/apartmentselectioncontroller/getblankstate", onComplete: function(response){
			this.loaded();
			var blankStateHTML = "";
			
			var falseResponse 	= ($defined(response.ANSWER.result) && response.ANSWER.result === false);
			if(falseResponse)
			{
				this.maximize();
			}
			
			blankStateHTML = response.ANSWER.result;
			this.blankStateElement.set("html", blankStateHTML);
			this.blankState();
		}.bind(this)}).send();
	},
	
	done: function()
	{
		this.bus.trigger("apartmentSelectionDone", this.selectedApartment);
	},
	
	recoverData: function()
	{
		this.loading();
		new Request.JSON({url:"public/apartmentselectioncontroller/getselectedapartment", onComplete: function(response){
			

			this.loaded();
			var falseResponse 	= ($defined(response.ANSWER.result) && response.ANSWER.result === false);
			if(falseResponse)
			{
				this.maximize();
				return false;
			}
			this.blankStateElement.dispose();
			
			this.header.inject(this.searchButton, "after");
			
			if($defined(this.apartmentsPanel.apartments[response.ANSWER.result]))
			{
				this.selectedApartment = this.apartmentsPanel.apartments[response.ANSWER.result];
				this.minimize();
				this.done();
			}
			else
			{
				this.getApartment(response.ANSWER.result, function(response){
					this.selectedApartment = new Apartment(response.ANSWER.result);
					this.minimize();
					this.done();
				}.bind(this))
			}
			
		}.bind(this)}).send();
	},
	
	registerEvents: function()
	{
		//this.bus.registerCallback(this.toFavorites.bind(this)			, "apartmentAddedToFavorites");
		this.bus.registerCallback(this.removedFavorite.bind(this)		, "favoriteRemoved");
		this.bus.registerCallback(this.addResults.bind(this) 			, "secondControllerDone");
		//this.bus.registerCallback(this.firstControllerDone.bind(this) 	, "firstControllerDone");
		//this.bus.registerCallback(this.apartmentLoaded.bind(this)		, "apartmentLoaded");
		this.bus.registerCallback(this.ApartmentCommentSend.bind(this)	, "ApartmentCommentSend");
		this.bus.registerCallback(this.show.bind(this)					, "returnToList");
		this.bus.registerCallback(this.resetMap.bind(this)				, "returnToApartmentList");
		this.bus.registerCallback(this.apartmentReservation.bind(this)	, "apartmentReservation");
		this.bus.registerCallback(this.formFriendSent.bind(this)		, "formFriendSent");
		this.bus.registerCallback(this.showFormFriend.bind(this)		, "showFormFriend");
		this.bus.registerCallback(this.setUpNewSearch.bind(this)		, "setUpNewSearch");
		this.bus.registerCallback(this.enableSearchButton.bind(this)	, "rangeSelection");
		this.bus.registerCallback(this.showFavorites.bind(this)			, "showFavorites");
	},
	
	show:function()
	{
		this.map.hideMap();
		this.header.setStyle('display', 'block');
		this.apartmentsPanel.show();
		this.listButton.setStyle('display', 'none');
		this.mapButton.setStyle('display', 'block');
		this.feedbackTextAfter.setStyle('display', 'inline');
		this.feedbackTextBefore.setStyle('display', 'inline');
		this.getMoreApartmentslink.setStyle('display', 'block');
		this.mapButton.setStyle('display', 'inline');
		
	},
	
	showFavorites: function()
	{
		this.apartmentsPanel.hide()
		this.map.hideMap();
		this.feedbackTextAfter.setStyle('display', 'none');
		this.feedbackTextBefore.setStyle('display', 'none');
		this.mapButton.setStyle('display', 'none');
		this.listButton.setStyle('display', 'none');
	},
	
	enableSearchButton: function()
	{
		if($defined(this.searchfeedback))
		{
			this.searchFeedback.destroy();
		}
		
		this.searchButton.removeEvents();
		this.searchButton.addEvent("click", function(e){if(e)e.stop()});
		this.searchButton.addEvent("click", this.addResults.bind(this));
		this.searchButton.removeClass("disabled");
	},
	
	setUpNewSearch: function()
	{
		this.apartmentsPanel.reset();
		this.container.setStyle("display","none");
	},
	
	firstControllerDone: function()
	{
		if(this.active)
		{
			//this.addResults(true);
		}
	},
	
	showFormFriend: function(form)
	{
		form.inject($(this.options.resultsContainer), "before");
	},
	
	apartmentReservation: function(apartment)
	{
		var data = apartment.getIdObject();
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/setselectedapartment" ,data:{"QUERY":JSON.encode(data)}, onComplete:function(response){
		}}).send();
		
		this.selectedApartment = apartment;
		this.minimize();
		this.done();
		this.apartmentsPanel.hide();
		this.map.hideMap();
		this.header.dispose();
		this.feedbackTextAfter.setStyle('display', 'none');
		this.feedbackTextBefore.setStyle('display', 'none');
		this.getMoreApartmentslink.setStyle('display', 'none');
		this.listButton.setStyle('display', 'none');
		this.mapButton.setStyle('display', 'none');
	},
	
	showResults: function()
	{
		this.apartmentsPanel.show();
	},
	
	formFriendSent: function(data)
	{
		this.favoritePanel.form.loading();
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/sendemail" ,data:{"QUERY":JSON.encode(data)}, onComplete:function(response){
			this.favoritePanel.form.loaded();
			this.favoritePanel.formFriendFeedback(response);
		}.bind(this)}).send();
	},
	
	resetMap: function()
	{
		this.map.hideMarkers();
		this.map.hideMap();
	},
	
	ApartmentCommentSend: function(params)
	{
		data = params[0];
		data[this.ajaxProperties.apartmentId] = params[1];
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/setusercomment" ,data:{"QUERY":JSON.encode(data)}, onComplete:function(response){
			//console.log(response);
		}}).send();
	},
	
	toFavorites: function(apartment)
	{
		data = {};
		data[this.ajaxProperties.apartmentId] = apartment.getId();
		
		/*if ($defined(this.gmaps.markers[apartment.getId()])) 
		{
			this.gmaps.markers[apartment.getId()].setIcon("http://www.unapartamentoenfallas.com/public/images/mapsFavoriteMarker.png");
		}*/
		
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/setprefered" ,data:{"QUERY":JSON.encode(data)}, onComplete:function(response){
			//console.log(response);
		}}).send();
	},
	
	removedFavorite: function(apartment)
	{
		this.apartmentsPanel.removedFromFavorite(apartment)	
	},
	setUpGmaps: function()
	{
		if($defined(this.gmaps))
		{
			return false;
		}
		this.gmaps = new MooMap(this.map, "Valencia");
	},
	
	mapsMarkClick: function(data)
	{
		this.apartmentsPanel.apartments[data.id].addToFavorites();
	},
	
	mapsMarkHover: function(data)
	{
		this.apartmentsPanel.highlightApartment(data.id);
	},
	
	mapsMarkOut: function(data)
	{
		this.apartmentsPanel.unHighlightApartment(data.id);
	},
	
	addResults: function(withoutRecoverData)
	{
		this.active = true;
		this.apartmentsPanel.loading();
		this.apartmentsPanel.reset();
		this.resetMap();
		this.bus.trigger("returnToList");
		this.feedbackTextAfter.setStyle('display', 'none');
		this.feedbackTextBefore.setStyle('display', 'none');
		this.getMoreApartmentslink.dispose();
		this.header.dispose();
		this.blankStateElement.dispose();
		this.resetOffset();
		this.disposeMapButtons();
		
		if($defined(this.searchFeedback))
		{
			this.searchFeedback.destroy();
		}
		
		this.bus.trigger("searchStart");
		
		if($defined(this.listRequest))
		{
			this.listRequest.cancel();
		}
		
		this.loading();
		
		var data = {};
		data[this.ajaxProperties.AJAX_KEY_CURRENT_OFFSET] = this.currentOffset;
		data[this.ajaxProperties.AJAX_KEY_NUMBER_OF_RESULTS] = this.numberOfResults;
		
		this.calculateOffsets();
		
		this.listRequest = new Request.JSON({url:"public/multicrsapartmentselectioncontroller/getapartmentlist"
			, data:{"QUERY":JSON.encode(data)}
		, onComplete:function(response){
		
		
			
			this.header.inject(this.searchButton, "after");
			this.apartmentsPanel.show();
			this.loaded();
			if(response.ANSWER.result === false || response.ANSWER.result.collection.length == 0)
			{
				this.getBlankStateHTML();
				return false;
			}
			
			this.feedbackTextAfter.setStyle('display', 'inline');
			this.feedbackTextBefore.setStyle('display', 'inline');
			
			this.feedbackTextAfter.set("html", response.ANSWER.result.feedbackText);
			this.feedbackTextBefore.set("html", response.ANSWER.result.feedbackText);
						
			if($defined(response.ANSWER.result[this.ajaxProperties.AJAX_KEY_TOTAL_RESULTS]))
			{
				this.totalResults = response.ANSWER.result[this.ajaxProperties.AJAX_KEY_TOTAL_RESULTS];			
			}
			
			this.blankStateElement.dispose();
			var apartments		= response.ANSWER.result.collection;
			this.addApartments(apartments);
			
			if(this.totalResults > this.currentOffset)
			{
				var buttonText = response.ANSWER.result.buttonText;
				this.getMoreApartmentslink.set("text", buttonText);
				this.getMoreApartmentslink.inject(this.container, "bottom");
			}
			
			this.getComments();
			if(!$defined(withoutRecoverData))
				this.recoverData();
			
			this.maximize();
			this.container.setStyle("display","block");
			this.injectMapButtons();
		}.bind(this)}).send();
	},
	
	moreResults: function()
	{
		var data = {};
		data[this.ajaxProperties.AJAX_KEY_CURRENT_OFFSET] = this.currentOffset;
		data[this.ajaxProperties.AJAX_KEY_NUMBER_OF_RESULTS] = this.numberOfResults;
		
		this.calculateOffsets();
		
		this.moreApartmentsLoader.inject(this.getMoreApartmentslink);
		this.moreResultsRequest = new Request.JSON({url:"public/multicrsapartmentselectioncontroller/getapartmentlist", data:{"QUERY":JSON.encode(data)}
		, onComplete:function(response){

			this.feedbackTextAfter.set("html", response.ANSWER.result.feedbackText);
			this.feedbackTextBefore.set("html", response.ANSWER.result.feedbackText);
			
			this.getMoreApartmentslink.set("text", response.ANSWER.result.buttonText);
			
			if(this.totalResults <= this.currentOffset)
			{
				this.getMoreApartmentslink.dispose(); 	
			}
			
			var apartments		= response.ANSWER.result.collection;
			this.addApartments(apartments);
			this.moreApartmentsLoader.dispose();
			
		}.bind(this)}).send();
	},
	
	calculateOffsets: function()
	{
		this.currentOffset += this.numberOfResults;
	},
	
	addApartments: function(apartments)
	{
		$H(apartments).each(function(apartmentData){
			this.addApartmentToPanel(apartmentData)
			this.map.addApartment(apartmentData)
		}.bind(this));
		if(this.map.mapShowed == true)
		{
			this.apartmentsPanel.hide();
		}
		this.map.zoomToMarkers();
		
	},
	
	addApartmentToPanel: function(apartmentData)
	{
		var apartment = new Apartment(apartmentData);
		/*var isfavorite = this.compareNShare.checkFavorite(apartment)
		if(isfavorite)
		{
			apartment.markFavorite()
		}*/
		this.apartmentsPanel.addApartment(apartment);
	},
	
	blankState: function()
	{
		this.loaded();
		this.maximize();
		this.blankStateElement.inject(this.container);
	},
	
	getPrefered: function(comments)
	{
		
		/*new Request.JSON({url:"public/multicrsapartmentselectioncontroller/getprefered", onComplete:function(response){
			
			if(response.ANSWER.result === false)
			{
				return false;
			}
			var idList = response.ANSWER.result.apartmentIdList;
			
			if($type(idList) == "object")
			{
				idList = new Hash(idList);
			}
			
			idList.each(function(id){
				
				
				var thisComments = undefined;
				if($defined(comments[id]))
				{
					var thisComments = comments[id]
				}
				
				if($defined(this.apartmentsPanel.apartments[id]) && this.apartmentsPanel.apartments[id].favorite == false)
				{
					this.apartmentsPanel.apartments[id].data.comments = thisComments;
					this.apartmentsPanel.apartments[id].addToFavorites();
				}
				else
				{
					this.getFavorite(id);
				}
				
			}.bind(this));
			
		}.bind(this)}).send();*/
	},
	
	getApartment: function(id, method)
	{
		var data = {};
		data[this.ajaxProperties.apartmentId] = id;
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/getapartment", data:{"QUERY":JSON.encode(data)}, onComplete:method}).send();
	},
	
	getFavorite: function(id)
	{
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/getapartment", data:{"QUERY":JSON.encode({apartmentId:id})}, onComplete:function(response){
			this.favoritePanel.addApartment(new Apartment(response.ANSWER.result));
		}.bind(this)}).send();
	},
	
	getComments: function()
	{
		new Request.JSON({url:"public/multicrsapartmentselectioncontroller/getusercomments", onComplete:function(response){
			this.getPrefered(response.ANSWER.result);
		}.bind(this)}).send();
	},
	
	apartmentLoaded: function(apartmentData)
	{
		//this.gmaps.addMarker(apartmentData);
	},
	
	createLoader: function()
	{
		this.loader = new Element("div", {"class":"loaderContainer"});
		this.loader.set("tween", {onComplete:function(){this.loader.dispose()}.bind(this)})
		this.progress = new Element("div", {"class":"stepLoader"}).inject(this.loader);
		this.message = new Element("div", {"class":"message", text:"Buscando apartamentos..."}).inject(this.loader);
	},
	
	//////
	
	loading: function()
	{
		this.searchButton.setStyle("opacity", ".5");
		this.searchButton.set("text", "Buscando apartamentos");
		this.searchButton.addClass("loading");
		//this.dotter.start();
	},
	
	loaded: function()
	{
		this.searchButton.setStyle("opacity", "1");
		this.searchButton.set("text", "Buscar apartamentos");
		this.searchButton.removeClass("loading");
		//this.dotter.stop();
	},
	
	minimize: function()
	{
		/*this.parent();
		this.setOncompleteMorph(this.minimizeComplete.bind(this));
		this.container.morph(".apartmentsMinimized");*/
	},
	
	maximize: function()
	{
		/*this.parent();
		this.setOncompleteMorph(this.maximizeComplete.bind(this));
		this.container.morph(".apartmentsMaximized");
		this.container.set("tween", {onComplete: function(){this.container.setStyle("height", "auto")}.bind(this), duration:200, transition:"Quint:out"});
		this.container.tween("height", this.container.getScrollSize().y);
		this.minimizeButton.inject(this.container, "top");*/
	},
	
	createMapButtons: function()
	{
		this.mapButton = new Element('a', {'href':'#', 'html': '<span>Mostrar mapa</span>', 'class':'mapButton' });
		this.listButton = new Element('a', {'href':'#', 'html': '<span>Mostrar listado</span>', 'class':'listButton' });
		
		this.mapButton.addEvent('click', function(e){e.stop()});
		this.mapButton.addEvent('click', this.map.showMap.bind(this.map));
		this.mapButton.addEvent('click', this.apartmentsPanel.hide.bind(this.apartmentsPanel));
		this.mapButton.addEvent('click', function(){
			this.mapButton.setStyle('display', 'none');
			this.listButton.setStyle('display', 'block');
		}.bind(this));
		
		this.listButton.addEvent('click', function(e){e.stop()})
		this.listButton.addEvent('click', this.apartmentsPanel.show.bind(this.apartmentsPanel))
		this.listButton.addEvent('click', this.map.hideMap.bind(this.map));
		this.listButton.addEvent('click', function(){
			this.listButton.setStyle('display', 'none');
			this.mapButton.setStyle('display', 'block');
		}.bind(this));

	},
	
	
	injectMapButtons: function()
	{
		this.mapButton.inject(this.header, "after");
		this.listButton.inject(this.header, "after");
		this.listButton.setStyle('display', 'none');
		this.mapButton.setStyle('display', 'block');
	},
	
	disposeMapButtons: function()
	{
		this.mapButton.dispose();
		this.listButton.dispose();
	}
	
})