/**
 * 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 MyStations
 * @description Displays and handes interactions with the MyStations overlay
 * @author Mike Colley <michael.colley@bbc.co.uk>
 */

radioplayer.views.MyStations = function(isIe6) {
	this._displayingTooltip = false;
	this._container = glow.dom.get('#mystations');
	this._rowContainer = glow.dom.get('.my-station-list');
	this._presetCountSpan = glow.dom.get("#preset-count");
	this._isIe6 = isIe6;

	this._modal = null;
	this._animationTime = 0.2;
	
	this._alreadyAddedButton =  glow.dom.get('#my-station-controls .add .already-added');
	this._notAddedButton =  glow.dom.get('#my-station-controls .add .add-cta-container');
	this._loadingPage = glow.dom.create("<div class='loading'>" +
									"<span class='text'>Loading stations...</span>" +
									"<div class='spinner'>&nbsp;</d>" +
									"</div>");
	this._errorMessage = glow.dom.create("<div class='preset-error'>" +
										"<div class='error-image'>&nbsp;</div>" +
										"<p class='error-detail'></p>" +
										
									"</div>");
	
	this.toggleAddControls();
	
	this._editTooltip = glow.dom.create("<div class='tooltip'><div class='tooltip-text'><strong>Tip: </strong>You can re-order your presets simply by clicking and dragging</div></div>");

	var blankParent = glow.dom.create("<div></div>");
	blankParent.append(this._editTooltip);
	
	this._presetsLoaded = false;
	this._displayLoadingState();
};

radioplayer.views.MyStations.prototype = {		
	displayErrorState: function(errorDetail) {
		this._container.children().hide();
		this._errorMessage.get('.error-detail').text(errorDetail);
		this._container.append(this._errorMessage);
	},
	
	removeErrorState: function() {
		this._errorMessage.remove();
		this._container.children().show();
	},
		
	_displayLoadingState: function() {		
		glow.anim.fadeOut(this._rowContainer.children(), 0.1);
		glow.dom.get('.add,.edit').hide();
		this._rowContainer.children().hide();
		this._rowContainer.append(this._loadingPage);
	},
		
	display: function( presetModel, createFreshRows ) {		
		var	self = this;
		if(this._presetsLoaded) {
			this._displayRows( presetModel, createFreshRows );
		}
		else {		
			glow.anim.fadeOut(this._loadingPage, 0.5, {
				onComplete:function() {
					self._loadingPage.destroy();
					self._rowContainer.children().show();
					glow.dom.get('.add').show();
					glow.dom.get('.edit').show();
					glow.anim.fadeIn(self._rowContainer.children(),0.5);
					self._displayRows( presetModel, createFreshRows );
					if(self._isIe6) {
						self.activateEditControls();
					}
					else {
						self.deactivateEditControls();
					}
					
					glow.events.fire(document, 'presets:rebind');
				}
			});
		}
	},	
	
	_displayRows: function( presetModel, createFreshRows ) {		
		var rows = this.createRows(presetModel, createFreshRows),
			rowLength = rows.length,
			i,
			nodelist,
			self = this;
		
		this._rowContainer.empty();
		for ( i = 0 ; i < rowLength ; i++) {	
			nodeList = rows[i].getNodeList();
			
			this._rowContainer.append(nodeList);
		}
		this._editTooltip.insertAfter(this._rowContainer);
		glow.anim.slideUp(this._editTooltip,0.1);
		var position = 0;
		glow.dom.get('.drop-target').each(function(i) {
			glow.dom.get(this).attr('position',i);
		});
	},	
	
	createRows: function( presetModel,createFreshRows ) {
		var rows = [],
			presets = presetModel._presets.slice(),
			position = 1,
			i,
			row,
			presetsForThisRow;
			
		if(createFreshRows) {
			this._rows = false;
		}
		if (!this._rows) {
			for( i=0; i<4; i++) {
				row = new radioplayer.models.StationRow((i+1));
				//1st placeholder in 1st row is the lastplayed station
				if (i===0) {
					//row.addPreset(this.getLastPlayedStation());
					row.addLastPlayed(presetModel.getLastPlayedStation());
					//getNumberOfEmptySpaces -1 to account for lastplayed being the 1st placeholder
					presetsForThisRow = presets.splice(0, (row.getNumberOfEmptySpaces() - 1));
				} else {
					presetsForThisRow = presets.splice(0,row.getNumberOfEmptySpaces());
				}
				for (var j = 0; j<presetsForThisRow.length; j++) {
					presetsForThisRow[j].attr('position',position++);
				}
				row.addPresets(presetsForThisRow);
				row.addEmptyPlaceholders();
				rows.push(row);
			}
			
			this._rows =  rows;
		}
		this.adjustNumberOfBlankRows(presetModel);
		return this._rows;
	},

	
	adjustNumberOfBlankRows: function( presetModel ) {
		var rowCount = this._rows.length,
			presetSpaces = rowCount * 4.0, 
			presetCount = presetModel._presets.length,
			numberOfRowsToDisplay =Math.floor( (presetCount+6)/4.0);
		
		if ( numberOfRowsToDisplay >4) {
			numberOfRowsToDisplay = 4;
		}
		
		for ( i=0; i<numberOfRowsToDisplay; i++) {
			this._rows[i].getNodeList().show();
		}
		
		for( i = numberOfRowsToDisplay; i< rowCount; i++) {
			this._rows[i].getNodeList().hide();
		}
	},
	
	addPreset: function( preset ) {
		var firstEmptyPlaceholder = glow.dom.get(this.findFirstEmptyPlaceholder()),
		i;
		firstEmptyPlaceholder.replaceWith(preset);
	},
	
	findFirstEmptyPlaceholder: function() {
		var placeholders = glow.dom.get('.station-placeholder');
		return placeholders.item(0);
	},	
	
	_showTooltip: function () {
		if (!this._displayingTooltip) {
			glow.anim.slideDown(this._editTooltip);
			this._displayingTooltip = true;
		}	
	},
	
	_hideTooltip: function () {
		if (this._displayingTooltip) {
			glow.anim.slideUp(this._editTooltip);
			this._displayingTooltip = false;
		}	
	},
	
	removePresetIcon: function( presetIcon ) {
		presetIcon.remove();
	},
	
	deactivateAddButton: function() {
		this._alreadyAddedButton.show();
		this._notAddedButton.hide();
	},
	
	activateAddButton: function() {
		this._alreadyAddedButton.hide();
		this._notAddedButton.show();
	},
	
	deactivateEditControls: function() {		
		glow.anim.fadeOut(".show-on-edit",this._animationTime);
		glow.anim.fadeOut(".station-object-handle",this._animationTime);
		glow.dom.get(".station-object-handle").hide();
		glow.dom.get(".show-on-edit").hide();
		glow.dom.get(".hide-on-edit").show();
		glow.anim.fadeIn(".hide-on-edit", this._animationTime);
		glow.anim.fadeIn('.last-played',this._animationTime);		

		this._hideTooltip();
	},

	activateEditControls: function() {		
		glow.anim.fadeOut(".hide-on-edit",this._animationTime);
		glow.dom.get(".hide-on-edit").hide();
		glow.dom.get(".show-on-edit").show();
		glow.anim.fadeIn(".show-on-edit", this._animationTime);	
		if(!this._isIe6) {
			glow.dom.get(".station-object-handle").show();
			glow.anim.fadeTo('.station-object-handle',0.7,this._animationTime);
		}
		glow.anim.fadeTo('.last-played',0.3,this._animationTime);
	
		this._showTooltip();		
	},
	
	addDraggableClass: function(presets) { 
		for ( i=0 ; i < presets.length ; i++) { 
	    	presets[i].addClass('draggable');                         
	    } 
	}, 

	removeDraggableClass: function(presets) { 
		for ( i=0 ; i < presets.length ; i++) { 
			presets[i].removeClass('draggable');                              
		} 
	},
	
	setPresetCount: function( presetCount ) {
		this._presetCountSpan.html("("+presetCount+")");
	},
	
	toggleAddControls: function( presetCount ) {
		addButton = glow.dom.get("#my-station-controls .add");
		if (presetCount >= this._maximumPresetCount)  {
			addButton.hide();
		}
		else {
			addButton.show();
		}
	},	
	
	showAddStationsTooltip: function() {
		this._addStationsTooltip.show();
	},
	
	hideAddStationsTooltip: function() {
		this._addStationsTooltip.hide();
	},
	
	showSaveConfirmPanel: function() {
		var self = this;
		if(this._modal == null) {			
			var panelNode = glow.dom.create('<div id="presets-warning-panel" class="presets-panel">'+
					'<p class="warning-heading">You haven\'t saved any of the changes made to your presets.</p>'+
					'<p>Would you like to discard your changes?</p>'+
					'<a title="Discard your changes" class="discard-continue">OK</a>'+
					'<a title="Cancel" class="cancel">Cancel</a>'+
					'</div>');
			var opts = { width: 240, anim: "fade", x:'50%', y:'38%' };
			this._modal = new glow.widgets.Panel(panelNode, opts);
			this._modal.container.addClass("presets-save-confirm-panel");
		
			//overriding GLOW default styling - unable to override within stylesheet
			glow.dom.get('.presets-save-confirm-panel .bars').css('background', 'none');

			//add listener to panel for user to continue journey
			glow.events.addListener('#presets-warning-panel a.discard-continue', 'click', function(e) {
				glow.events.fire(document, 'presets:discard', {});
				self._modal.hide();
			});
			
			//add listener to panel for user to continue journey
			glow.events.addListener('#presets-warning-panel a.cancel', 'click', function(e) {
				self._modal.hide();
			});
		}

		this._modal.show();
	},
	
	hideCurrentProgrammeInformation: function(currentProgrammeNode) {
		currentProgrammeNode.destroy();
	},
	
	showCurrentProgrammeInformation: function(currentProgrammeNode) {
		var tipboxBackgroundImagePath, 
			newTipboxBackgroundImagePath, 
			leftPosition, 
			newLeftPosition;
		
		if(currentProgrammeNode) {
			leftPosition = currentProgrammeNode.position().left;
			if(leftPosition>179) {				
				tipboxBackgroundImagePath = currentProgrammeNode.css('background-image');
				newTipboxBackgroundImagePath = tipboxBackgroundImagePath.replace("tipbox-top-bg-long","tipbox-top-bg-long-rev");
				currentProgrammeNode.css('background-image',newTipboxBackgroundImagePath);
				newLeftPosition = (leftPosition-155)+ 'px';
				currentProgrammeNode.css('left',newLeftPosition);
			}
		}		
	}
};

