/**
 * 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 RadioplayerOverlayManager
 * @description Manages the irreducible core overlays
 *
 * @param container : {radioplayer.models.RadioplayerOverlayContainer} container object for the overlays
 * @param overlays : {radioplayer.models.RadioplayerOverlay} object literal that contains the overlays for the container
 * @param mystations : {Object} instance of MyStations
 * @param crossdomain : {Object} instance of CrossDomain
 *
 * @authors Cathy Bartlett <cathy.bartlett@bbc.co.uk>
 * @authors Sergejs Vaskevics <sergejs.vaskevics@ubcmedia.com>
 */

radioplayer.controllers.RadioplayerOverlayManager = function(container, overlays, mystations, crossdomain) {
	this._overlayContainer = container;
	this._overlays = overlays;
	this._mystations = mystations;
	this._crossdomain = crossdomain;
	
	this._currentOverlay = null; // keeps in mind which overlay is currently shown
	this._visibleOverlay = null; // overlay that is currently visible
	this._isMoving = false; // flag that is set while the overlay is being changed
	
	// get the triggers that slide toggle the overlays
	this._$formTriggers = glow.dom.get(".components #quickfind-form > input");
	this._$linkTriggers = glow.dom.get(".components .overlaytrigger");
	this._$triggers = glow.dom.get(this._$formTriggers, this._$linkTriggers);
	
	// get the selected filter
	this._$selected = this._$triggers.filter(function(){
		return glow.dom.get(this).hasClass('selected');
	});
	
	//keypress event container 
	this._timeoutContainer = {};
	
	//timer to close tipbox after 5 secs
	this._tipboxTimer = {};
	
	//preferences 
	this._preferences = [];
	this._tipbox = true; 
	
	//tipboxes
	this._searchTipBox = null;
	this._searchTipBoxRef;
	this._resultsTipBox = null;
	this._resultsTipBoxRef;
	
	// search box message
	this._SEARCH_INPUT_BOX_MSG = "Search Radioplayer";
	
	//current trigger
	this._$t = null;
	
	//current method
	this._fn = null;
	
	//current search parameter
	this._searchparameter = '';
	
	this.bind();	
};

radioplayer.controllers.RadioplayerOverlayManager.prototype = {
	".overlaytrigger click": function(e) {
		e.preventDefault();
		this._$t = glow.dom.get(e.source);
		this._fn = 'toggleOverlay';	
		
		if (this._mystations._hasChanged) {
			//send event to open modal dialogue box prompting user to save their changes
			this._triggerConfirmationDialogCall();
		} else if (this._mystations._editMode) { //in edit mode but no changes made
				this._mystations.unsetEditMode();
				this._startToggle();
		} else {
			this._startToggle();
		}
	},
	
	"presets:discard subscribe": function() {
		this._mystations._revertChanges();
		this._mystations._hasChanged = false;
		
	//	this._setOverlayState();
		
		if (this._fn == 'quickfindFocus') {
			document.getElementById('quickfind-input').focus();
		}
	},

	".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");
	},

	".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-controls .close a click": function(e) {
		e.preventDefault();
		this._fn = 'closeOverlay';
		
		if (this._mystations._hasChanged) {
			//send event to open modal dialogue box prompting user to save their changes
				this._triggerConfirmationDialogCall();
		} else if (this._mystations._editMode) { //in edit mode but no changes made
				this._mystations.unsetEditMode();
				this._startToggle();
		} else {
			this._startToggle();
		}
	},
		
	"#quickfind-form submit": function(e) {
		e.preventDefault();	
		
		this._searchparameter = glow.dom.get('#quickfind-form input#quickfind-input').val();
		
		this._$t = glow.dom.get(e.source);
		this._fn = 'quickfindSubmit';
		
		if (this._mystations._hasChanged) {		
			//send event to open modal dialogue box prompting user to save their changes
			this._triggerConfirmationDialogCall();
		}else if (this._mystations._editMode) { //in edit mode but no changes made
			this._mystations.unsetEditMode();
			if(this._isSearchStringAllowed()){
				this._startToggle();		
			}
		} else  {
			if(this._isSearchStringAllowed()){
				this._startToggle();		
			}
		}
		//glow.dom.get('#quickfind-form input#quickfind-input').val(this._SEARCH_INPUT_BOX_MSG);
	},
	_isSearchStringAllowed: function(){
		var str = this._searchparameter;
		var restricted = true;
		
		if (!(/\S/.test(str))) {
		    // string is empty or consists just of whitespace
			restricted = false;
		}
		if(this._searchparameter == this._SEARCH_INPUT_BOX_MSG){
			restricted = false;
		}
		
		return restricted;
	},
	
	"#quickfind-form input#quickfind-input focus": function(e) {
		var el = glow.dom.get(e.source);
		this._$t = glow.dom.get(e.source);
		this._fn = 'quickfindFocus';	
		
		el.val('');	
		/*
		//has mystations been edited?
		if(this._mystations._hasChanged) {		
			alert("here is confirmation dialog call");
			//this._triggerConfirmationDialogCall();
			//this._mystations._view.showSaveConfirmPanel();
		} else {
			el.val('');	
		}		
		*/
	},
	
	"#quickfind-form input#quickfind-input keypress": function(e) {
		var self = this;
		var frame = glow.dom.get('.radioplayer');

		this._searchTipBoxRef = glow.dom.get('#search-tipbox');		

		glow.dom.get('#results-tipbox').css('display','none');
		
		//check tipbox preference HERE	
		//if it IS in the array then DON'T show it
		if(this._preferences.join().indexOf('search') == -1) {	
			//only capture the first keypress event
			if (this._timeoutContainer[e]) {
				clearTimeout(this._timeoutContainer[e]);
			}
			this._timeoutContainer[e] = setTimeout(function() { 
				if (self._searchTipBox == null) {
					self._searchTipBox = self._tipbox ? radioplayer.views.tipbox.getTipbox('search') : null;
					frame.append(self._searchTipBox);
					self.rebind();
				}				
					self._showTipbox('search');
				}, 10);	
			}
		
	},
	
	"#quickfind-form input#quickfind-input blur": function(e) {
	//	glow.dom.get(e.source).val('Search Radioplayer');
	},
	
	"#quickfind-form input#quickfind-button mousedown": function(e) {
		var el = glow.dom.get(e.source);
		el.css('background-position', '0 -24px');
	},
	
	"#quickfind-form input#quickfind-button mouseup": function(e) {
		var el = glow.dom.get(e.source);
		el.css('background-position', '0 0');
	},
	
	"#quickfind-form input#quickfind-button mouseleave": function(e) {
		var el = glow.dom.get(e.source);
		el.css('background-position', '0 0');
	},
	
	"#quickfind-form input#quickfind-button mouseenter": function(e) {
		var el = glow.dom.get(e.source);
		el.css('background-position', '0 -48px');
	},

	
	".tipbox-container .close a click": function(e) {
		e.preventDefault();			
		var el = glow.dom.get(e.source);
		var id = el.attr('id').split('-').shift();
		
		this._preferences.push(id);		
		
		//register users tipbox preference here
		radioplayer.controllers.CrossDomain.prototype.save('preferences', this._preferences);
		
		this._closeTipbox();
	},
	
	'preferences:data subscribe': function(obj) {
		obj.d == 'null' ? this._preferences = [] : this._preferences = obj.d;
	},
	
	"#overlay-wrap click": function(e) {
	//	e.preventDefault();		
		this._closeTipbox();
	},
	_startToggle: function() {
		if (this._isMoving) {
			return;
		} else {
			this._isMoving = true;
			this._closeTipbox();			
			this._setOverlayAction();
		}
	},
	
	_setOverlayAction: function() {
		switch (this._fn) {
			case 'toggleOverlay':
				this.toggleOverlay(this._$t);
			  break;
			case 'quickfindFocus':
				this.closeOverlay();
			  break;
			case 'quickfindSubmit':
			    this.requestSearch();			   
			  break;
			default:
			  this.closeOverlay();			  
		}
	},
	
	requestSearch: function() {
		var that = this;
		var resultsContainer = glow.dom.get('#quickfind #overlay-content');
		glow.anim.fadeOut(resultsContainer, 0.1);
		resultsContainer.html("");
		
		this._closeTipbox();
		var callback = { 
			requestData :function() {
				glow.events.fire(document, 'quickfind:results', {parameter:that._searchparameter});
			//	that._showSearchTipBox();
			}
		}
		this.toggleOverlay(this._$t,callback);
	},
	_showSearchTipBox: function (){
		
		var self = this;
		var frame = glow.dom.get('.radioplayer');
		this._resultsTipBoxRef = glow.dom.get('#results-tipbox');
		
		//check tipbox preference HERE	
		//if it IS in the array then DON'T show it
		if(this._preferences.join().indexOf('results') == -1) {		
			//only capture the first submit event
			if (this._timeoutContainer['submit']) {
				clearTimeout(this._timeoutContainer['submit']);
			}
			this._timeoutContainer['submit'] = setTimeout(function() { 
				if (self._resultsTipBox == null) {
					self._resultsTipBox = self._tipbox ? radioplayer.views.tipbox.getTipbox('results', self._searchparameter) : null;
					frame.append(self._resultsTipBox);
					self.rebind();
				}				
			}, 10);
			
			setTimeout(function() { self._showTipbox('results'); }, 2000);
		}
	},
	
	_checkForChanges: function($t) {
		var overlayName = $t.attr('id').split('-').shift();

		if(overlayName != 'mystations') {
			return false;
		}
		else {
			return this._mystationsController.hasChanged();
		}		
	},
	
	_showTipbox: function(tipbox) {
		var self = this;
		var tip;
		
		if (tipbox == 'search') {
			tip = glow.dom.get('#search-tipbox');
			tip.css({
				'display':'',
				'top':'135px',
				'left':'200px'
			});
		} else {
			tip = glow.dom.get('#results-tipbox');
			tip.css({
				'display':'',
				'top':'165px',
				'left':'60px'
			});
		}
		
		this._tipboxTimer[tip] = setTimeout(function() { self._closeTipbox(tip); }, 5000);		
	},
	
	_closeTipbox: function(tipbox) {
		var search = glow.dom.get('#search-tipbox');
		var results = glow.dom.get('#results-tipbox');
	
		if (this._searchTipBox != null) {
			search.css('display', 'none');			
		}
		
		if (this._resultsTipBox != null) {
			results.css('display', 'none');			
		}
		
		if (this._tipboxTimer[tipbox]) {
			clearTimeout(this._tipboxTimer[tipbox]);
		}
	},
	
	_getOverlayId: function(id) {
		var idElements = id.split('-');
		idElements.pop();
		return idElements;
	},
	
	_setCurrentOverlay: function(id) {
		this._currentOverlay = this._overlays[id];
	},
	
	_isOverlay: function(id) {
		return id in this._overlays;
	},
	
	_isUnselectedFilter: function($trigger) {
		return !this._isSelected($trigger);
	},
	
	_isSelected: function($element) {
		return $element.hasClass('selected');
	},
	
	_setSelected: function($filter) {
		this._$selected.removeClass('selected'); // remove the selected class
		this._$selected = $filter;
		this._$selected.addClass('selected');
	},
	
	_unsetSelected: function() {
		this._$selected.removeClass('selected');
	},
	
	/**
	 * toggles overlay
	 * This method opens and closes the overlay and builds up the timelines necessary
	 * for the animation.
	 * @param {glow.dom.NodeList} $trigger trigger that was clicked
	 */
	toggleOverlay: function($trigger,callback) {
		var that = this,
			channels = [],
			actions = [],
			animation = null,
			animationDuration = 0.3,
			animationStaggering = 0.3,			
			overlayId = null,
			id = glow.dom.get($trigger).attr('id').split('-'),
			containerHeight = 0;
		
		//playing overlay is different height, affects toggle animation	
		id[0] == 'playing' ? containerHeight = 130 : containerHeight = 530;
		
		// If we're loading mystations and an error occured, reload presets data from central repository		
		if(id[0] == 'mystations' && this._mystations.anErrorHasOccured()) {
			this._mystations.resetErrorState();
			this._crossdomain.load();
		}
		if (this._isUnselectedFilter($trigger)) {
			this._setSelected($trigger); // set the selected filter
			overlayId = this._getOverlayId(this._$selected.item(0).id);
			if (this._overlayContainer.isOpen()) {		
				this._setCurrentOverlay(overlayId); // set the new current overlay
				channels = this._getChannelArrayToReloadOverlay(animationDuration,containerHeight);
			}
			else {
				this._setCurrentOverlay(overlayId); // set the new current overlay
				this._visibleOverlay = this._currentOverlay;
				
				channels = this._getChannelArrayToOpenOverlay(animationDuration,containerHeight);
			}
		} 
		else {
			if (!this._visibleOverlay) {
				this._visibleOverlay = this._currentOverlay;
			}			
			//if quickfind/search, toggle overlay up AND down to show NEW search results
			if (id[0] == 'quickfind') {				
				channels = this._getChannelArrayToReloadOverlay(animationDuration,containerHeight);				
			} else {			
				channels = this._getChannelArrayToToggleOverlay(animationDuration,containerHeight);
				this._unsetSelected();
			}
		}

		animation = new glow.anim.Timeline(channels, {
			'destroyOnComplete': true,
			'onComplete': function() {
				that._visibleOverlay = that._currentOverlay;
				that._isMoving = false;
				if(callback){
					if(callback.requestData){
						callback.requestData();
					}
				}
			}
		});
		glow.events.addListener(animation, "start", function(event) {
		    var now = new Date();
		});
		
		
		animation.start();
	},
	_getChannelArrayToReloadOverlay: function(animationDuration,containerHeight){
		var actions = [];
		actions.push(radioplayer.models.RadioplayerOverlayContainer.prototype.slideup);
		actions.push(radioplayer.models.RadioplayerOverlay.prototype.hide);
		actions.push(radioplayer.models.RadioplayerOverlay.prototype.show);
		actions.push(radioplayer.models.RadioplayerOverlayContainer.prototype.slidedown);
		var channels = [];
		
		channels.push( [
		                actions[0].call(this._overlayContainer),
						actions[1].call(this._visibleOverlay, animationDuration),
						actions[2].call(this._currentOverlay, animationDuration),					
						actions[3].call(this._overlayContainer, containerHeight)
	                ] );
		
		return channels;
	},
	_getChannelArrayToOpenOverlay: function(animationDuration,containerHeight){
		var actions = [];
		actions.push(radioplayer.models.RadioplayerOverlay.prototype.show);
		actions.push(radioplayer.models.RadioplayerOverlayContainer.prototype.slidedown);
		
		var channels = [];
		
		channels.push( [actions[0].call(this._visibleOverlay, animationDuration)] );
		channels.push( [actions[1].call(this._overlayContainer, containerHeight)] );
		return channels;
	},
	_getChannelArrayToToggleOverlay: function(animationDuration,containerHeight){
		var actions = [];
		actions.push(radioplayer.models.RadioplayerOverlay.prototype.toggle);
		actions.push(radioplayer.models.RadioplayerOverlayContainer.prototype.toggleContainer);
		
		var channels = [];		
		channels.push( [actions[0].call(this._visibleOverlay, animationDuration)] );
		channels.push( [actions[1].call(this._overlayContainer, containerHeight)] );
		return channels;
	},
	
	/**
	 * Closes overlay
	 * This method closes the overlay
	 */
	closeOverlay: function() {
		var that = this,
			channels = [],
			actions = [];

		if(this._overlayContainer.isOpen()) {
			actions.push(radioplayer.models.RadioplayerOverlay.prototype.toggle);
			actions.push(radioplayer.models.RadioplayerOverlayContainer.prototype.toggleContainer);

			channels.push( [actions[0].call(this._visibleOverlay, 0.2)] );
			channels.push( [actions[1].call(this._overlayContainer, 530)] );

			var animation = new glow.anim.Timeline(channels, {
				'destroyOnComplete': true,
				'onComplete': function() {
					that._visibleOverlay = that._currentOverlay;
					that._isMoving = false;
				}
			});

			this._isMoving = true;
			this._unsetSelected();
			animation.start();
		}
	},
	_triggerConfirmationDialogCall: function(){
		if (glow.env.ie < 7) {
			this._mystations._revertChanges();
			this._mystations._hasChanged = false;
			this._mystations.unsetEditMode();
			this._startToggle();
		}else{
			this._mystations._view.showSaveConfirmPanel();
		}
	}
		
};

