/**
 * 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 returns the html view each search result item
 *
 * @param result : {Object} contains result data
 * @param isInPresets : {Boolean} is this station already in the users preset list
 *
 * @authors Cathy Bartlett <cathy.bartlett@bbc.co.uk>
 * @authors Sergejs Vaskevics <sergejs.vaskevics@ubcmedia.com>
 */
radioplayer.views.quickfind = {	
	
	getResult: function(result, isInPresets,isResultVisible) {		
			var stationStatus, timeToBroadcast, styleProperties, playerUrl, now, nowInEpochSeconds, subtitle, imgTag;;
			
			now = new Date();
			nowInEpochSeconds = Math.round(now.getTime()* 0.001);
			
			playerUrl = this._getPlayerUrl(result,nowInEpochSeconds);
			subtitle = this._getSubtitle(result);
					
			stationStatus = this._calculateStationStatus(result,nowInEpochSeconds);
			
			styleProperties = '';
			if(!isResultVisible){
				styleProperties = ' style="display: none; opacity: 0;" ';
			}
	        if(!result.imgUrl) {
	              result.imgUrl = basePath + '/img/station_fallback.png';
	        }
			
			return glow.lang.interpolate( '<div class="overlay-item" '+ styleProperties+'>' +
					( isInPresets === null ? this._getAddOffButton(result.stationID) : (isInPresets ? this._getAddedButton(result.stationID) : this._getAddButton(result.stationID)) ) +
		 				'<a href="{playerUrl}" class="overlay-item-link">' +
							'<span class="play-icon"></span>' +
		    				'<span class="overlay-item-img">' +
								'<img width="86" height="48" src="{imgUrl}" alt="{name}"></img>' +
							'</span>' +
		    				'<span class="title">{name}</span>' +
		    			'</a>' +
		    			'<div class="overlay-item-data">' +
						'<p class="subtitle">{subtitle}</p>' +
						'<p class="description">{description}</p>' +           
						'<p class="broadcast-info"><span class="status">{status}</span> <span class="broadcast-time">{timeToBroadcast}</span></p>' +
		    			'</div>' +
					'</div>' , {
						name:result.stationName,
						playerUrl:playerUrl,
						imgUrl:result.imgUrl,
						stationID: result.stationID,
						subtitle:subtitle,
						description:result.summary,
						status: stationStatus.stationType,
						timeToBroadcast:stationStatus.timeToBroadcast
					});		
	},
	_getAddButton: function(id) {
		var html = '<ul class="add-cta-container add-station-'+id+'">'+
									'<li><button class="add-station"><span class="add-button-content">Add</span></button>'+
										'<ul class="dropdown-container">'+
											'<li class="not-already-added"><a class="add_'+id+'" title="Add to My Stations">to My Stations</a></li>'+
										'</ul>'+
									'</li>'+
								'</ul>';
		return html;
	},
	
	_getAddedButton: function(searchString) {
		var html = '<span class="already-added" title="Station Added">Added to My Stations</span>';
		return html;
	},
	_getNoResultsFoundMsg: function(searchString) {	
		return '<div id="noresults" class="error-container">'+
			'<p class="error-heading"><span class="bold">Sorry,</span> we couldn\'t find anything relating to</p>'+
			'<p class="error-code">'+searchString+'</p>'+
			'<div id="error-description">'+
				'<p class="error-description-large">Try entering the name of a <span class="bold">radio station</span>, <span class="bold">programme</span>, '+
			'<span class="bold">presenter</span>, <span class="bold">topic</span>, or <span class="bold">musical style</span>. For local '+
			'results, enter your postcode, or a town name.</p>'+
			'</div>'+
			'<div class="error-detail">'+
				'<p>To get even more detailed search results, try entering a combination of words. For example:'+
					'<dl class="search-examples">'+
						'<dt>"Manchester Football"</dt>'+
						'<dd>Near the top of the list will be stations and shows which relate to both Manchester and Football</dd>'+
						'<dt>"Music BN1 9RH"</dt>'+
						'<dd>Near the top of the list will be music stations which have particular relevance to your postcode</dd>'+
					'</dl>'+
				'</p>'+
			'</div>'+
		'</div>';
	},
	_getSearchErrorResponseMsg: function() {	
		return '<div id="noresults" class="error-container">'+
			'<p class="error-heading"></p>'+
			'<p class="error-code">Sorry, we can\'t bring you any Radioplayer search results at the moment. We\'re aware of the '+
			'problem, and we\'re working to fix it. Please click \'Close\', and try again later.</p>'+
		'</div>';
	},
	_getAddOffButton: function(id) {
		var html = '<span class="add-off">Add</span>';
		return html;
	},
	_calculateStationStatus: function(result,nowInEpochSeconds){
		
		var stationTypes = new Array('Live','Coming up','Broadcast');
		var returnType = {};
				
		var startTimeMinusNow = result.startTimeEpoch - nowInEpochSeconds ;
		var stopTimeMinusNow = result.stopTimeEpoch - nowInEpochSeconds ;
			
		// if there are no start&stop time in epoch then station status Live
		if((result.startTimeEpoch == ""||result.stopTimeEpoch=="")&&((result.onDemandStartTime == "")&&(result.onDemandEndTime == ""))){
			returnType.stationType = stationTypes[0];
			returnType.timeToBroadcast = "";
			return returnType;
		}
		// if start is in past and stop is in future then station status Live
		if((startTimeMinusNow <= 0)&&(stopTimeMinusNow >= 0)){
			returnType.stationType = stationTypes[0];
			returnType.timeToBroadcast = "";
			return returnType;
		}
		// if start is in the future station status Coming up
		if(startTimeMinusNow > 0){
			returnType.stationType = stationTypes[1];
			returnType.timeToBroadcast = this._getTimeBeforeBroadcast(startTimeMinusNow);
			return returnType;
		}		
		// if stop is in the past station status Broadcast
		if(stopTimeMinusNow < 0){
			returnType.stationType = stationTypes[2];
			var nowMinusStopTime = nowInEpochSeconds - result.stopTimeEpoch ;
			// if off schedule on demand return no time since broadcast
			if(result.startTimeEpoch == ""||result.stopTimeEpoch==""){
				returnType.timeToBroadcast = "";
			}else{
				returnType.timeToBroadcast = this._getTimePastSinceBroadcast(nowMinusStopTime);
			}
			
			return returnType;
		}
		returnType.stationType = stationTypes[0];
		returnType.timeToBroadcast = "";
		return returnType;
	},
	_divideAndRound: function(timeInEpochSeconds, divideBy){
		var result = "";		
		var tempTime;
		timeReturned = timeInEpochSeconds / divideBy ;
		if(timeReturned >= 1){
			timeReturned = Math.round(timeReturned);
			result = timeReturned;
			return result;
		}
		return 1;
	},
	_getTimeBeforeBroadcast: function(timeInEpochSeconds){
		var minutesToBroadcast = timeInEpochSeconds / 60 ;
		minutesToBroadcast = Math.round(minutesToBroadcast);
		(minutesToBroadcast < 1) ? minutesToBroadcast = 1 +" minute": minutesToBroadcast = minutesToBroadcast+" minutes";
		return " in "+minutesToBroadcast;
	},
	_getTimePastSinceBroadcast: function(timeInEpochSeconds){
		
		var timeValue,retString, year, month, week, day, hour, minute ;
		year = 31556926;
		month = 2629743;
		week = 604800;
		day = 86400;
		hour = 3600;
		minute = 60;
		
		if(timeInEpochSeconds >= week){
			if(timeInEpochSeconds >= year){
				timeValue = this._divideAndRound(timeInEpochSeconds, year);
				if(timeValue){
					return retString = this._getTimePastString(timeValue,"year");
				}
			}else if(timeInEpochSeconds >= month){
				timeValue = this._divideAndRound(timeInEpochSeconds, month);
				if(timeValue){
					return retString = timeValue + " month ago";
				}
			}else if(timeInEpochSeconds >= week){	
				timeValue = this._divideAndRound(timeInEpochSeconds, week);
				if(timeValue){
					return retString = this._getTimePastString(timeValue,"week");
				}
			}
		}else{
			if(timeInEpochSeconds >= day){
				timeValue = this._divideAndRound(timeInEpochSeconds, day);
				if(timeValue){
					return retString = this._getTimePastString(timeValue,"day");
				}
			}else if(timeInEpochSeconds >= hour){	
				timeValue = this._divideAndRound(timeInEpochSeconds, hour);
				if(timeValue){
					return retString = this._getTimePastString(timeValue,"hour");
				}
			}else if(timeInEpochSeconds >= minute){			
				timeValue = this._divideAndRound(timeInEpochSeconds, minute);
				if(timeValue){
					return retString = this._getTimePastString(timeValue,"minute");
				}
			}
		}
		return retString = this._getTimePastString(timeInEpochSeconds,"second");
		
	},
	_getTimePastString: function(value,timeUnit){
		var retString;
			retString = value + " "+timeUnit;
			if(value > 1){
				retString = retString + "s";
			}
			return retString = retString + " ago";
			
	},
		
	_getPlayerUrl: function(result, nowInEpochSeconds){
		if(result.onDemandPlayerUrl){
			if(nowInEpochSeconds > result.stopTimeEpoch){
				return result.onDemandPlayerUrl;
			}
		}
		return result.livePlayerUrl;
	},
	_getSubtitle: function(result){
		if(result.eventName){
			if ( result.artist ){
				return result.artist + ", " + result.eventName;
			}
			else return result.eventName;
		}
		return result.programmeName;
	}
	
};

