/**
 * 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 Handles the editing of a user's stations preset
 *
 * @param currentStation : {String} id of active station
 *
 * @authors Mike Colley <michael.colley@bbc.co.uk>
 * @authors Sergejs Vaskevics <sergejs.vaskevics@ubcmedia.com>
 * 
 */

radioplayer.controllers.MyStations = function (currentStation) {
	this._editMode = false;
	this._hasChanged = false;
	this._currentProgrammeOverlay = null;
	
	this._currentStation = currentStation;
   
	this._model;
	
	this._isIe6 = (glow.env.ie==6); 
	this._view = new radioplayer.views.MyStations(this._isIe6);
	
	this._errorTimer; 
	this._errorState = false;
	
	this._ondrag = false;

	this._overlay;

	this.bind();
};


radioplayer.controllers.MyStations.prototype = {		
	_errorLoadingPresets: function(errorObj) {
		if (!this._errorState) {
			this._errorState = true;		
			this._view.displayErrorState(errorObj.displayMessage);
		}
	},
	
	resetErrorState: function() {
		this._errorState = false;
		this._view.removeErrorState();
	},	
	
	startErrorTimer: function() {
		var self = this;
		// Display error screen if the server hasn't responded in 10 seconds.
		var errorObj = {
				displayMessage: "Sorry, we couldn't load your stations",
				logMessage: "Server iframe timed out whilst loading"
			};
		
		this._errorTimer = setTimeout(function() { self._errorLoadingPresets(errorObj); }, 10000);
	},	
	
	anErrorHasOccured: function() {
		return this._errorState;
	},	
	
	resetErrorTimeOut: function() {
		if (this._errorTimer) {
			clearTimeout(this._errorTimer);
		}
	},

	_createIconLink: function() {
		if(radioplayer.services.store.get(this._currentStation)) {
			currentStationData = radioplayer.services.store.get(this._currentStation);
			glow.dom.get('#station-logo-link').attr('href', currentStationData.playerUrl);
		}
	},
	
	displayFreshRows: function() {
		this.display(true);
	},
	
	display: function (createFreshRows) {
		this._createIconLink();

		if (!this._errorState) {
			if (createFreshRows == undefined) {
				createFreshRows = false;
			}

			this._view.display(this._model, createFreshRows);				
			this._view.deactivateEditControls();

			if (this._model.isInPresets() || (this._model.getPresetCount() >=15)) {
				this._view.deactivateAddButton();
			} else {
				this._view.activateAddButton();
			}

			this._view.setPresetCount(this._model.getPresetCount());

			this.rebind();
		}
	},		

	//create draggable objects on station icons
	createDraggables: function () {
		var mystationsController = this,
			presets = this._model.getPresets(),
			presetLength = presets.length,
			stationDraggables = [],
			i;

		for ( i=0; i<presetLength; i++ ){
			stationPid = presets[i].data('stationID');			
			stationDraggables[stationPid] = mystationsController._createSingleDraggable(presets[i]);
		}
		
		return stationDraggables;		
	},
	
	_createSingleDraggable: function ( draggableIcon ) {
		var mystationsController = this,
			draggable,
			draggableElement,
			droppableElement,
			hasMoved;

	    draggable = new glow.dragdrop.Draggable(draggableIcon, {
			dropTargets: this._dropTargets,
			dragPrevention: ['span'],
			container: '#overlay-container',	
			handle: '.station-object-handle',
			
			onDrag: function (e) {
				if(mystationsController._ondrag) {
					e.preventDefault();
				}
				else {
	    			mystationsController._ondrag = true;
					e.attachedTo.element.addClass('current-draggable');
				}				
	    	},
	    	
		    onDrop : function (e) {	
	    		draggableElement = e.attachedTo.element;
	    		
				if (this.activeTarget) {
					e.preventDefault();	
					droppableElement = this.activeTarget.element;
					hasMoved = mystationsController._model.reorderPresets(draggableElement, droppableElement, this);
					if (hasMoved) {						
						mystationsController._hasChanged = true;
					} else {			
						this.endDrag();
						glow.dom.get(draggableElement).css( {
							left:'',
							top : '',
							position : '',
							'z-index' : ''
						});						
					}	
						
				}		
				mystationsController._ondrag = false;		
				draggableElement.removeClass('current-draggable');		   
			}			
		});
		return draggable;
	},	

	createDropTargets: function () {
		var dropTargetDivs = glow.dom.get('.my-station-list .drop-target'),
			mystationsController = this,
			stationDropTargets = [];
		dropTargetDivs.each(function(i){		
			stationDropTargets[i] = mystationsController._createSingleDropTarget(glow.dom.get(this));
		});

		return stationDropTargets;
	},

	_createSingleDropTarget: function ( dropTargetDiv ) {
		var dropTarget = new glow.dragdrop.DropTarget(dropTargetDiv, {
			onEnter: function() {
				this.element.addClass('drop-candidate');
			},
			
			onLeave: function() {
				this.element.removeClass('drop-candidate');
			},
			
			onDrop: function(e) {
				this.element.removeClass('drop-candidate');
			},
			tolerance:'cursor'			
		});
		return dropTarget;
	},	
	
	removePreset: function ( preset ) {
		// Find the ID of the preset from the button's ID attribute
		var presetPid = preset.attr('id').split('_').pop();
		this._hasChanged = true;
		this._ondrag = true;
		
		if(!this._isIe6) {
			delete this._draggables[presetPid];
		}
		
		if(presetPid == this._currentStation) {
			this._view.activateAddButton();
			this.rebind();
		}
		this._model.removePreset(preset);
		this._view.adjustNumberOfBlankRows(this._model);
		this._view.setPresetCount(this._model.getPresetCount());
		this.rebind();		
	},
	
	setEditMode: function () {
		this._view.activateEditControls();
		this._editMode = true;
		if(!this._isIe6) {
			if(!this._dropTargets) {
				this._dropTargets = this.createDropTargets();
			}
			if(!this._draggables) {
				this._draggables = this.createDraggables(this._dropTargets);
			}
			
			this._view.addDraggableClass(this._model.getPresets());
		}
		
	},
	
	unsetEditMode: function () {		
		if(this._isIe6) {
			return;
		}
		this._editMode = false;
		this._view.removeDraggableClass(this._model.getPresets());
		this._view.deactivateEditControls();
		this._view.setPresetCount(this._model.getPresetCount());		
	},	
	

	_showCurrentProgrammeInformation: function(preset,nowPlaying) {
		var myStationsController = this;
		if(!this._currentProgrammeOverlay) {
			this._currentProgrammeOverlay = this._model.getCurrentProgrammeInformationForPreset(preset,nowPlaying);
			myStationsController._view.showCurrentProgrammeInformation(myStationsController._currentProgrammeOverlay);
		}		
	},	

	_hideCurrentProgrammeInformation: function(preset) {
		if(this._currentProgrammeOverlay) {
			this._view.hideCurrentProgrammeInformation(this._currentProgrammeOverlay);
			this._currentProgrammeOverlay=null;
		}
	},

	_revertChanges: function () {
		this._hasChanged = false;
		this._model.revertChanges();
		delete this._dropTargets;
		delete this._draggables;
		this.displayFreshRows();
		this.unsetEditMode();	
		this.rebind();
		
	},
	
	saveChanges: function() {
		this._hasChanged = false;
		var cookiedata = this._model.saveChanges();

		this.unsetEditMode();
		this.rebind();
	
		try {
			radioplayer.controllers.CrossDomain.prototype.save('presets', cookiedata);
		} catch(err) {
			this._overlay = new radioplayer.models.modal(
				'cookieSaveError',
				'Sorry, an error has occured',
				'Radioplayer could not save your settings.',
				'OK'
			);
			this._overlay.show();
		}
	},
	
	addStation: function (id) {
		return this._model.addStation(id);
	},
	
	'addstation:data subscribe': function(obj) {
		var preset = obj.p,
			stationID = preset.data('stationID');
		
		this._view.addPreset(preset);
		this._view.setPresetCount(this._model.getPresetCount());
		
		if (this._editMode) {
			this._view.activateEditControls();
			this._hasChanged = true;
			this._view.addDraggableClass(new Array(preset));
			this._draggables[stationID] = this._createSingleDraggable(preset);
		} else {
			
			this.saveChanges();
			this._view.deactivateEditControls();
			if(this._draggables) {
				this._draggables[stationID] = this._createSingleDraggable(preset);
			}
		}			
		
		if (this._model.hasCurrentStation(stationID) || (this._model.getPresetCount() >= 15)) {
			this._view.deactivateAddButton();
		}
		this._view.adjustNumberOfBlankRows(this._model);
		this.rebind();
	},
	"presets:processWebServiceResponse subscribe": function(obj) {
		if(obj.preset){
			glow.events.fire(document, 'addstation:data', {p: obj.preset});
			isStationAdded = true;
		}else{
			this._model._presetIsNotAvailable.push(obj.id);
		}
	},
	
	'ondrag:false subscribe': function() {
		this._ondrag = false;
	},
	
	'crossdomain:error subscribe': function(e) {
		this._errorLoadingPresets(e);
	},
	
	//presets data received from cookie and data successfully loaded from webservice
	'presets:data subscribe': function(obj) {
		this.resetErrorTimeOut();
		var presets;
		var self = this;

		//if there are presets (ie not null (NB null is a string as returned from the cookie))
		//parse the cookiedata ids with the datastore
		obj.d == 'null' ? presets = {} : presets = radioplayer.utils.parseData(obj.d);
		
		if (typeof this._model === 'object') {
		    this._model._presetData = presets;
			//_init() and display() called here to ensure that BOTH lastplayed and presets data have been registered
			//and functions are only called once
			this._model._init();
			this.display();
		} else {
		    this._model = new radioplayer.models.RadioplayerPresets(this._currentStation);
			this._model._presetData = presets;
		}		
	},
	
	//lastplayed data received from cookie and data successfully loaded from webservice
	'lastplayed:data subscribe': function(obj) {
		var lastplayed = {},
			currentstation = [this._currentStation];

		//if there isn't a lastplayed station (ie is null (NB null is a string as returned from the cookie)) 
		//use the current station (this._currentStation (hardcoded)) as the id
		//and parse the id with the datastore
		//if last played station was deleted from database use current as lastplayed 
		if (obj.d == 'null') {
			lastplayed = radioplayer.services.store.get(this._currentStation);
			lastplayed.stationID = this._currentStation;
		} else {
			lastplayed = radioplayer.services.store.get(obj.d);			
			if(lastplayed){
				lastplayed.stationID = obj.d;
			}else{
				lastplayed = radioplayer.services.store.get(this._currentStation);
				lastplayed.stationID = this._currentStation;
			}
			
		}	
		
		if (typeof this._model === 'object') {
		    this._model._lastPlayedData = lastplayed;
			//_init() and display() called here to ensure that BOTH lastplayed and presets data have been registered
			//and functions are only called once
			this._model._init();
			this.display();
		} else {
		    this._model = new radioplayer.models.RadioplayerPresets(this._currentStation);
			this._model._lastPlayedData = lastplayed;
		}
		
		//save the current station as the lastplayed in the cookie
		radioplayer.controllers.CrossDomain.prototype.save('lastplayed', currentstation);
	},
	
	'presets:rebind subscribe': function() {
		this.rebind();
	},
	
	//Adds the currently-playing station to 
	"#my-station-controls .add .not-already-added click": function( event ) {
		event.preventDefault();
		this._model.addStation(this._currentStation);
		this.rebind();
		if(this._isIe6) {
			this.setEditMode();
		}
		
	},
	"#my-station-controls .add .add-station click": function( event ) {
		
	},
	
	"#my-station-controls .edit-stations click": function( event ) {
		event.preventDefault();
		this.setEditMode();		
	},	

	".my-station-list .station-row .station-close-button click": function( event ) { 
        if (!this._ondrag) { 
                event.preventDefault(); 
                var presetIcon = glow.dom.get(event.attachedTo).parent(); 
                this.removePreset(presetIcon); 
                event.stopPropagation(); 
        } 
	},
	
	"#my-station-controls  .save-changes click": function( event ) {
		event.preventDefault();
		this.saveChanges();
	},
	
	".my-station-list .station-row .station-icon mouseenter": function( event ) {
		event.source = radioplayer.utils.rebase(event.source,".my-station-list .station-row .station-icon");
		event.preventDefault();
		var preset = glow.dom.get(event.attachedTo);
		var el = glow.dom.get(event.source);
		var anchor = el.get('a.station-link');		

		if(!this._editMode && !preset.hasClass('station-placeholder')) {
			var that = this;
			var callback = {
					onLoad: function(nowPlaying){
						that._showCurrentProgrammeInformation(preset,nowPlaying);
					}
			};
			glow.events.fire(document, 'presets:getNowPlayingInfo', {preset:preset,callback:callback});
		}
		if (this._editMode  ) {
			if(!preset.parent().parent().hasClass('last-played')&& !preset.hasClass('station-placeholder')){
				var title = anchor.attr('title');	
				if (title.indexOf('Play') != -1) {
					title = title.replace('Play', 'Delete or Move');	
					anchor.attr('title', title);
				}
			}
		}else{
			if(!preset.parent().parent().hasClass('last-played')&& !preset.hasClass('station-placeholder')){
				var title = anchor.attr('title');	
				if (title.indexOf('Delete or Move') != -1) {
					title = title.replace('Delete or Move','Play');	
					anchor.attr('title', title);
				}
			}
		}
	},

	".my-station-list .station-row .station-icon mouseleave": function( event ) {
		event.source = radioplayer.utils.rebase(event.source,".my-station-list .station-row .station-icon");
		event.preventDefault();
		var preset = glow.dom.get(event.attachedTo);
		var el = glow.dom.get(event.source);
		var anchor = el.get('a.station-link');
		
		if (this._editMode && !preset.hasClass('station-placeholder')) {
			var title = anchor.attr('title');	
			
			if (title.indexOf('Remove') != -1) {
				title = title.replace('Remove', 'Play');	
				anchor.attr('title', title);
			}			
		}
		
		this._hideCurrentProgrammeInformation(preset);
	},
	
	"#my-station-controls .discard-changes click": function( event ) {
		event.preventDefault();
		this._revertChanges();
	},
	
	//if in edit mode then disable the anchor tag href
	".my-station-list .station-row .station-link click": function(event) {
		if (this._editMode) {
            event.preventDefault();
            event.stopPropagation()
		}
	}

};


