/**
 * All intellectual property rights in this Software throughout the world belong to UK Radioplayer, 
 * rights in the Software are licensed (not sold) to subscriber stations, and subscriber stations 
 * have no rights in, or to, the Software other than the right to use it in accordance with the 
 * Terms and Conditions at www.radioplayer.co.uk/terms. You shall not produce any derivate works 
 * based on whole or part of the Software, including the source code, for any other purpose other 
 * than for usage associated with connecting to the UK Radioplayer Service in accordance with these 
 * Terms and Conditions, and you shall not convey nor sublicense the Software, including the source 
 * code, for any other purpose or to any third party, without the prior written consent of UK Radioplayer.
 *
 * @name Quickfind
 * @description Handles search result items
 *
 * @param mystations : {Object} instance of MyStations
 *
 * @authors Sergejs Vaskevics <sergejs.vaskevics@ubcmedia.com>
 * @authors Cathy Bartlett <cathy.bartlett@bbc.co.uk>
 * 
 */

radioplayer.controllers.Quickfind = function(mystations) {	
	this._model = new radioplayer.models.RadioplayerQuickfind();
	this._results = null;
	this._mystations = mystations;
	
	this._parameterContainer = glow.dom.get('.result-parameters');
	this.loadingSpiner = glow.dom.get('.overlay-controls span#loader');	
	
	this._resultsContainer = glow.dom.get('#quickfind #overlay-content');	
	
	this.moreButton = glow.dom.create('<a href="#" id="more-button">More Results</a>');
	this.results = glow.dom.get('#overlay-content .overlay-item');
	this._resultsLength = 0;
	
	this.container = glow.dom.get('#overlay-wrap');	
	this._addButtonLock = false;
	
	this.bind('#quickfind');
	this.gotSearchResponseError = false;
	this.searchResponseErrorTimeout = {};
	
};

radioplayer.controllers.Quickfind.prototype = {	
	NO_OF_RESULTS_TO_DISPLAY : 11,
	MIN_NO_OF_RESULTS : 4,
	SEARCH_STRING_LENGTH : 27,
	curDisplayedSearchStr : "",
	loadingSpiner : "",
		
	"quickfind:results subscribe": function(obj) {		
		var self = this;	
		var searchStr = obj.parameter;
		this.curDisplayedSearchStr = glow.data.escapeHTML(this._model.truncate(searchStr,this.SEARCH_STRING_LENGTH));
		
		this._displayLoadingMsg();
		glow.anim.fadeIn(self._parameterContainer, 0.7); 
		this.loadingSpiner.addClass('loading');
		
		this.gotSearchResponseError = true;
		
		this._model.getData(searchStr);
		this.searchResponseErrorTimeout = setTimeout(function() { glow.events.fire(document, 'quickfind:checkErrorState', {}); }, 15000);
	},
	"quickfind:processResults subscribe": function(obj) {		
		clearTimeout(this.searchResponseErrorTimeout);
		this.gotSearchResponseError = false;
		var data = obj.data;
		this._resultsLength = data.total;
		this.loadingSpiner.removeClass('loading');	
		
		this._displayResultCount();
		glow.anim.fadeIn(this._parameterContainer, 1.1); 
		
		if(this._resultsLength != 0){
			this._results = this._getDisplay(data, this.curDisplayedSearchStr);
			this._resultsContainer.html(this._results);		
			this._showMoreResultsButton();
		}else{
			this._displayNoResultsMsg(this.curDisplayedSearchStr);
		}
		glow.anim.fadeIn(this._resultsContainer, 1.5);
		this.rebind('#quickfind');
	},
	"quickfind:checkErrorState subscribe": function(obj) {		
		if(this.gotSearchResponseError){
			this._displaySearchErrorMsg();			
			this.loadingSpiner.removeClass('loading');	
			glow.anim.fadeIn(this._parameterContainer, 1.1); 
			glow.anim.fadeIn(this._resultsContainer, 1.5);
			this.rebind('#quickfind');
		}		
	},
	"#quickfind #overlay-subwrap .overlay-item .not-already-added a click": function(e) {
		e.preventDefault();
		if(!this._addButtonLock){
			this._addButtonLock = true;	
			setTimeout(function() { glow.events.fire(document, 'quickfind:releaseAddButtonLock', {}); }, 5000);
			
			var added = glow.dom.create('<span class="already-added" title="Station Added">Added to My Stations</span>'),
				addedInstance,
				isStationAdded,
				el = glow.dom.get(e.source);
			var elementClass = el.attr('class');
			
			var id = elementClass.split('_').pop(),
				containers, 
				container,
				parent;
			isStationAdded = this._mystations.addStation(id);
			if(isStationAdded){
				containers = glow.dom.get('ul.add-station-'+id);
				
				containers.each(function() {
					container = glow.dom.get(this);
					parent = container.parent();
					container.remove();
					addedInstance = added.clone();
					addedInstance.insertBefore(parent.get('a.overlay-item-link'));	
				});
			}
			this._addButtonLock = false;
		}
		e.stopPropagation();
	},
	"quickfind:releaseAddButtonLock subscribe": function() {		
		this._addButtonLock = false;
	},
	
	"#overlay-subwrap #more-button click": function(e) {
		e.preventDefault();	

		//hide 'more' button
		// => store reference to this element in class instance
		
		if(e.source.id !== "more-button"){
			e.stopPropagation();
			return;
		}
		var button = glow.dom.get(e.source);
		button.hide();
		var items = glow.dom.get('#overlay-content .overlay-item');
		var item = '';
		//show remaining items
		for (var i = this.NO_OF_RESULTS_TO_DISPLAY; i < this._resultsLength; i++) {
			item = items[i];			
			glow.dom.get(item).css('display', ''); 
			glow.anim.fadeIn(item, 0.1);			
		}
		e.stopPropagation();
	},
	".overlay-item .add-cta-container mouseenter": function (e) {
		e.source = radioplayer.utils.rebase(e.source, ".add-cta-container");
		var el = glow.dom.get(e.source);
		el.get("li").addClass("selected");
	},

	".overlay-item .add-cta-container mouseleave": function (e) {
		e.source = radioplayer.utils.rebase(e.source, ".add-cta-container");
		var el = glow.dom.get(e.source);
		el.get("li").removeClass("selected");
	},
    ".overlay-item mouseenter": function(event) {
    	event.source = radioplayer.utils.rebase(event.source,".overlay-item");
		this.setHoverState(event);
    },
    ".overlay-item mouseleave": function(event) {
		event.source = radioplayer.utils.rebase(event.source,".overlay-item");		
		this.unsetHoverState(event);
    },
    _showMoreResultsButton: function (){
		//if more than 11 results: hide excess items and show 'more' button 
		if (this._resultsLength > this.NO_OF_RESULTS_TO_DISPLAY) {		
			this._resultsContainer.append(this.moreButton);
			this._resultsContainer.append("<div id=\"quickfind-blank-space-under-poweredBy\"></div>");
			// => store reference to this element in class instance
			glow.dom.get('#more-button').show();
		}else{
			this._resultsContainer.append("<div id=\"quickfind-blank-space-under-poweredBy\"></div>");
		}	
	},
    setHoverState: function(event) {
		var thisEl = glow.dom.get(event.source); 
		thisEl.addClass('hover');
	},
	
	unsetHoverState: function(event) {
		var thisEl = glow.dom.get(event.source); 
		thisEl.removeClass('hover');
	},	
	_getDisplay: function(data) {		
		var results = '',
			resultInPresets;
		var isResultVisible = true;
		for (i in data.results) {
			i > this.NO_OF_RESULTS_TO_DISPLAY ? isResultVisible = false : isResultVisible = true;
			try {
				resultInPresets = this._mystations._model.isStationAddedToPresets(data.results[i].stationID);
			}
			catch ( e ) {
				resultInPresets = null;
			}
			if(resultInPresets !== null){
				results += radioplayer.views.quickfind.getResult(data.results[i], resultInPresets, isResultVisible);
			}
		}
		return results;
	},
	_displayResultCount: function() {
		var search = glow.lang.interpolate('<span>Results for </span>' +
				'<span class="quickfind-parameter">{parameter} </span>' + 
				'<span class="no-of-results">({total})</span>', {
				parameter: this.curDisplayedSearchStr,
				total: this._resultsLength
			});
		this._parameterContainer.html(search); 
	},
	_displayNoResultsMsg: function(displayedSearchStr) {		
		this._resultsContainer.html(radioplayer.views.quickfind._getNoResultsFoundMsg(displayedSearchStr));
	},	
	_displaySearchErrorMsg: function() {		
		this._resultsContainer.html(radioplayer.views.quickfind._getSearchErrorResponseMsg());
	},
	_displayLoadingMsg: function() {		
		var search = '<span>Results for </span>' +
					'<span class="quickfind-parameter">'+this.curDisplayedSearchStr+'</span>';
		this._parameterContainer.html(search); 
	}
};

