/**
 * Attach Event listeners to the Luisterpaal
 */ 
var LUISTERPAAL;
var FLICKRURL = "http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=live,";
var FLICKRLOADER;
var FLICKRITEMS = 5; 
var CANIFEED = false;
var EVENT;

google.load("feeds", "1");
google.setOnLoadCallback(function(){
	CANIFEED = true;	
});

$(function(){	
	var s1 = new SWFObject("http://download.omroep.nl/vpro/luisterpaal/widgets/LuisterpaalEvents.swf?oninit=Luisterpaal.inited&environment=frenkietest&luisterpaal=http://download.omroep.nl/vpro/luisterpaal/widgets/luisterpaal.swf","luisterpaal","240","320","8");
		s1.addParam("allowScriptAccess", "always");
		s1.write("luisterpaalevents");

 /** position loaders */
	FLICKRLOADER = $('div.bezigmetladen.grey');
	FLICKRLOADER.css({
		left: ($('div.imageColumn').offset().left) +"px",
		top: ($('div.imageColumn').offset().top + 10) +"px"
	}); 

});

var Luisterpaal = {
	
	images: null,
	youtube:null,
	
	inited : function(){	
		
		Luisterpaal.images = $('div.imageColumn').eq(0);
		Luisterpaal.youtube = $('#youtube');
		
		LUISTERPAAL = (typeof window["luisterpaal"] !="undefined")? window["luisterpaal"] : document["luisterpaal"];	
		LUISTERPAAL.addLPEventListener("START", "Luisterpaal.start");
		LUISTERPAAL.addLPEventListener("PAUSE", "Luisterpaal.pause");
		LUISTERPAAL.addLPEventListener("RESUME", "Luisterpaal.resume");
		LUISTERPAAL.addLPEventListener("STOP", "Luisterpaal.stop");
	},
	
	start: function(e){

		/** get extra info artist */
		if(CANIFEED){

			/** Flickr for the artist */
			if(typeof EVENT == "undefined" || (typeof EVENT != "undefined" && EVENT.track.artist != e.track.artist)){
				
				EVENT = e;	/* for a sure data feed */	
				
				
				FLICKRLOADER.show();	
				
				$.getScript(FLICKRURL+ e.track.artist.replace(/%20/ig, ','));
				
				
				//***/
				
				$(GeoEvents).bind(GeoEvents.FINISHED_SEARCHING, function(){
					
					Luisterpaal.showEvents();
				});
				
				//GeoEvents.addSearchEngine(new LastfmGeoSearch());
				GeoEvents.addSearchEngine(new SongKickGeoSearch());				
				
				
				GeoEvents.search(decodeURIComponent(e.track.artist.replace(/%20/ig, ' ')));
			}
			

		}
		EVENT = e;	
		
		/* metadata */
		Luisterpaal.showMeta(e);
	},
	
	pause : function(){	
		$('#metadata').html("<p>The Luisterpaal is paused.</p>");
	},
	
	resume : function(){	
		Luisterpaal.showMeta(EVENT);
	},
	
	stop : function(){	
		$('#metadata').html("<p>The Luisterpaal has stopped</p>");
	},

	showMeta : function(e){
		$('#metadata').html("<p>You're listening to <em>"+ unescape(e.track.name) +"</em> by <em>"+ unescape(e.track.artist) +"</em></p>"+
		"<p><a href='"+ e.track.albumUrl +"'>Listen to this album on 3VOOR12.nl</a></p>");
	},
	
	
	showEvents: function(){
		
		
		
		var events = GeoEvents.getEvents();
		var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
		var days = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];
		
		$("#events").empty().append("<h3>"+ events.length +" concert"+ ((events.length == 1)? "": "s") +" found near you!</h3>");
		
		if(events.length > 0){
			
			$("#events").append("<ol>");
			
			$.each(events, function(i, event){
				
				var html = "<li class='"+ event.provider.name +"'><a href=\""+ event.provider.source +"\"><span class='date'>"+ days[event.date.getDay()] +", "+
							months[event.date.getMonth()] +" "+ event.date.getDate() +"</span> | "+
							
							"<span class='time'>"+ Luisterpaal.padTime(event.date.getHours()) +":"+
							Luisterpaal.padTime(event.date.getMinutes()) +"</span>"+
							
							" in <span class='venue'>"+ event.venue +" | "+ event.city +"</span></a></li>";
				
				$("#events ol").append(html);
			});
		}
	},

	/**
	 * @return date in seconds from 1-1-1970
	 * Google Format = Fri, 12 Sep 2008 12:34:19 -0700
	 */	
	parseGoogleDate : function(date){		
		var 	dt = new Date(($.browser.msie)? Luisterpaal.fixDate(date) : date);
		return 	dt.getTime()/1000;
	},

	/** Make date parseable in IE [Jon Aquino 2007-03-29] */
	fixDate : function(d) {
		var a = d.split(' ');
		var year = a.pop();
		return a.slice(0, 3).concat([year]).concat(a.slice(3)).join(' ');
	},

	padTime : function(int) {
		if(int < 10){ return '0'+ int; }
		return int;
	}
}
 

function jsonFlickrFeed(f){

	FLICKRLOADER.hide();	
	var count = 0;
	if(typeof f.items != "undefined" && f.items.constructor == Array && f.items.length > 0){
		if(f.items.length > FLICKRITEMS){
			f.items.splice(FLICKRITEMS, f.items.length-FLICKRITEMS);
		}
		Luisterpaal.images.empty();
		$(f.items).each(function(i){
			Luisterpaal.images.append("<a href=\""+ this.link +"\"><img src=\""+ this.media["m"] +"\" width=\"120\" alt=\""+ this.title +"\" title=\""+ this.title +"\" class=\"flickr"+ ((i == f.items.length-1)? ' last' : '') +"\" /></a><br />");		
		});		
	}else{
		Luisterpaal.images.html("Geen Flickr foto's gevonden voor "+ unescape(EVENT.track.artist) +" live");
	}
}

/** class FeedMe */
var FeedMe = {
	
	fetch :function(url, callback){
			
		/** Use Google + DATA API */
		var feed = new google.feeds.Feed(url);
			/*feed.setResultFormat(google.feeds.Feed.XML_FORMAT);*/
			feed.setNumEntries(1);			
			feed.load(function(result){				
				callback(result);					
			});			
	}
};


/***************************************************************************************

**/

	var GeoLocation = function(){
		
		var that=this;
		var lat;
		var long;
		
		this.setLatLong = function(lat, long){
			that.lat = lat;
			that.long = long;
		};
		
		this.getLatitude = function(){
			return that.lat;
		}
		
		this.getLongitude = function(){
			return that.long;
		};
		
		this.parseFromString = function(location){
		
		};
		
		this.toString = function(){
			return "lat: "+ that.lat + ", long: "+ that.long;
		}
	};

	var GeoEvents = {
		
		 FINISHED_SEARCHING: "finished"
		
		,searchEngines: {}
	
		,addSearchEngine : function(se){
			
			if(typeof GeoEvents.searchEngines[se.name] == "undefined"){
				GeoEvents.searchEngines[se.name] = se;
				$(se).bind(GeoEvents.FINISHED_SEARCHING, function(){
				
					GeoEvents.found();
				});
			}
		}
		
		,search : function(query){
			
			//remove old markers
			
			$.each(GeoEvents.searchEngines, function(v, searchEngine){
				searchEngine.search(query);			
			});
		}
		
		,found : function(se){
			
			var done = true;
			
			$.each(GeoEvents.searchEngines, function(v, searchEngine){
				
				if(!searchEngine.searched){
					done = false;
				}	
			});
			
			if(done){
				$(GeoEvents).trigger(GeoEvents.FINISHED_SEARCHING);
			}
		}
		
		,getEvents : function(){
			
			var events = new Array();
			$.each(GeoEvents.searchEngines, function(v, searchEngine){			
				events = events.concat(searchEngine.getEvents());	
			});			
			if(events.length > 0){
				//sort by date?
				//remove duplicates
			}
			return events;
		}
	}


	var GeoEvent = function(){
	
	};
	GeoEvent.prototype = {
		
		 headliner:""
		,artists:[]
		,venue:""
		,city:""
		,date:null
		,geolocation:null
		
		,gmapmarker:null
		
		,provider: null
		
		,addArtist : function(name){
			this.artists.push(name);
		}
		
		,setProvider: function(name, eventUrl){
			
			this.provider = {
				name: name,
				source: eventUrl
			};
		}
				
		,pad : function(to, padding, upto){
			to = ""+ to;
			while(to.length < upto){
				to = padding + to;
			}
			return to;
		}
	};



	
	var GeoEventSearchEngine = function(){};
		GeoEventSearchEngine.prototype = {
			
			searched: false
			,name:""
			,datastore:""
			,events: []

			,getEvents: function(){
				return this.events;
			}
		};
	

	var SongKickGeoSearch = function(){
		this.name = "songkick";
		this.datastore = "http://api.songkick.com/api/3.0/events.json?apikey=musichackdayamsterdam&location=clientip&artist_name={artist}";
	};
	$.extend(SongKickGeoSearch.prototype, new GeoEventSearchEngine(), 
	{
		search: function(query){
			
			var that = this;
			this.events = new Array();
			
			this.searched = false;
			
			var url = this.getDataStore(query);
					
			$.ajax({
				url: url,
				dataType:"jsonp",
				jsonp:"jsoncallback",
				success:function(data){
					that.parse.apply(that, [data]);
				},
				error: function(){
					console.log(that.name +" error fetching geoevents");
				}
			});
	
		}
		
		,getDataStore: function(query){
			var ds = this.datastore.replace(new RegExp("{artist}"), query);
										
			return ds;
		}
		
		,pad : function(to, padding, upto){
			to = ""+ to;
			while(to.length < upto){
				to = padding + to;
			}
			return to;
		}
		
		,parse : function(data){
			
			var that=this;
			
			if(typeof data.resultsPage != "undefined"){
				
				if(data.resultsPage.totalEntries > 0){
					var results = data.resultsPage.results.event;
				
					$.each(results, function(i, event){
						
						var ev = new GeoEvent();
							ev.headliner = event.displayName;
							
							$.each(event.performance, function(i, artist){
								ev.addArtist(artist.displayName);
							});
							
							ev.venue = event.venue.displayName;
							ev.city = event.location.city;
							ev.date = new Date();
							
							if(typeof event.start != "undefined"){
								ev.date.setTime(Date.parse(event.start.date.replace(/\-/g, ' ') +" "+ event.start.time.split(":").slice(0, -1).join(":")));
							}
							ev.setProvider(that.name, event.uri);
							
							var gl = new GeoLocation()
								gl.setLatLong(event.location.lat, event.location.lng);
							ev.geolocation = gl;
							
						that.events.push(ev);
					});				
				}
			}
			
			this.searched = true;
			$(this).trigger(GeoEvents.FINISHED_SEARCHING);			
		}
	});	

