if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function(){};

var thing = new Class({

	initialize: function(){
		this.getLocation();
	},
	
	getLocation: function(){
		
		var self = this;
		
		if (navigator.geolocation){
			console.log('finding location...');
			navigator.geolocation.getCurrentPosition(function(position){
				coords = position.coords;
				if (!coords.latitude){
					alert('did not find coords');
				} else {
					console.log('location found');
				}
				self.createMap();
			}, function(){
				console.log('failed');
			});
		} else {
			alert('geolocation not implemented in this browser');
		}
	},
	
	createMap: function(){
		var size = $('map').getSize();
		$('map').setStyles({
			'width': size.x,
			'height': size.y
		});
		this.map = new GMap2($("map"));
		var mapControl = new GMapTypeControl();
		this.map.addControl(mapControl);
		this.map.addControl(new GLargeMapControl());
		this.centerMap();
	},
	
	centerMap: function(){
	  	this.map.setCenter(new GLatLng(coords.latitude, coords.longitude), 13);
		$('map').removeClass('loading');
		new Request.JSONP({
			url: 'http://api.gigjunkie.net/v0.7/events?callback=this.process',
			data: {
				'consumerkey': '0CDEA591-11A6-4EED-9ECE-A57F8E66C76F',
				'latitude': coords.latitude,
				'longitude': coords.longitude,
				'distance': '15',
				'pageSize': '100',
				'format': 'json'
			},
			onComplete: this.process.bind(this)
		}).send();		
	},
	
	process: function(response){
		$each(response.ApiResponse.Events, function(evt){
			var point = new GLatLng(evt.Venue.Latitude, evt.Venue.Longitude);
			this.map.addOverlay(this.createMarker(point, evt));
		}, this);
	},
	
	createMarker: function(point, evt){
		var self = this;
		var marker = new GMarker(point);
		marker.value = evt.Id;
		GEvent.addListener(marker, "click", function() {
			var content = "<h1>" + evt.Name + "</h1>";
			content += "<ul>";
			$each(evt.Artists.Artists, function(artist){
				content += "<li>" + artist.Name + "</li>";
			});
			content += "</ul>";
			content += "<iframe src='iframe.php?name=" + evt.Artists.Artists[0].Name + "' style='width: 500px;' frameborder='0'></iframe>"
			self.map.openInfoWindowHtml(point, content);
			self.populateTicketInformation(evt, evt.Tickets.Tickets, evt.Artists.Artists);
			self.populateArtistInformation(evt.Artists.Artists);
			self.populatePurchaseInformation(evt.Artists.Artists[0].Name);
			self.populateListenInformation(evt.Artists.Artists[0].Name);
			self.populateVideoInformation(evt.Artists.Artists[0].Name);
		});
		GEvent.addListener(marker, "mouseover", function(){
			
		});
		GEvent.addListener(marker, "mouseout", function(){
			
		});
		return marker;
	},
	
	populateTicketInformation: function(evt, tickets, artists){
		var timestamp = evt.DoorDateTime.match(/\((.*)\)/)[1];
		var date = new Date().parse('01/01/1970');
		date.set('ms', timestamp);
		var details = new Element('div.details');
		new Element('div.when', {
			'html': '<span class="month">' + date.format("%b") + '</span><span class="day">' + date.get('date') + '</span><span class="year">' + date.get('year') + '</span>'
		}).inject(details);
		$('gigdetails').empty().adopt(details);
		
		new Element('h3', {
			text: evt.Name
		}).inject(details);
		
		new Element('h4', {
			text: '@' + evt.Venue.Name
		}).inject(details);
		
		var title = new Element('h2', {
			text: 'Buy Tickets from GigJunkie'
		}).inject(details, 'after');
		
		var list = new Element('ul.tickets');
		$each(tickets, function(ticket){
			var ticketprice = ticket.Price ? ticket.Price : "???";
			new Element('li.' + ticket.Provider.toLowerCase(), {
				html: '<a href="' + ticket.Url + '" target="_blank"><span>' + ticketprice + "</span></a>"
			}).inject(list);
		});
		list.inject(title, 'after');

	},
	
	populateArtistInformation: function(artists){
		var self = this;
		new Request({
			url: 'feeds/aboutartist.php',
			data: {
				query: artists[0].Name
			},
			onComplete: function(response, tree){
				if (tree){
					var biography = tree.getElement('biography').getElement('text').get('text');
					$('artistdetails').set('html', '<h2>Biography from Echo Nest</h2><p>' + biography + "</p>");
				} else {
					$('artistdetails').set('html', '<p class="boo">Boooooo! We couldn\'t find any info about ' + artists[0].Name);
				}
				self.getImages(artists);
			}
		}).send();
	},
	
	getImages: function(artists){
		new Request({
			url: 'feeds/images.php',
			data: {
				query: artists[0].Name
			},
			onComplete: function(response, tree){
				if (tree){
					var gallery = new Element('div.gallery').adopt(new Element('ul')).inject($('artistdetails'));
					
					gallery.getElement('ul').setStyle('width', tree.getElements('results url').length * 100);
					//var biography = tree.getElement('artist biography text').get('text');
					//$('artistdetails').set('html', '<h2>Biography from Echo Nest</h2><p>' + biography + "</p>");
					tree.getElements('results url').each(function(item){
						new Element('li', {
							html: '<a href="' + item.get('text') + '" rel="milkbox[gall1]"><img src="' + item.get('text') + '" /></a>'
						}).inject(gallery.getElement('ul'));
					});
					
					milkbox.reloadGalleries();
					
				    gallery.getElements('a').each(function(element) {
				      /*  new ReMooz(element, {
				            //centered: true, 
				            origin: element.getElement('img'),
							resize: true,
							resizeLimit: {x: 300, y: 300},
							resizeTo: {
								x: 300,
								y: 300
							}
				        });*/

				    });

				    
				} else {
					$('artistdetails').set('html', '<p class="boo">Boooooo! We couldn\'t find any info about ' + artists[0].Name);
				}
			}
		}).send();
	},
	
	populatePurchaseInformation: function(name){
		new Request({
			url: 'feeds/buycds.php',
			data: {
				query: name
			},
			onComplete: function(response, tree){
				var id = tree.getElements('artist')[0].getProperty('id');
				new Request({
					url: 'feeds/buycds.php',
					data: {
						id: id
					},
					onComplete: function(response, tree){
						$('purchasedetails').empty();
						
						$('purchasedetails').adopt(new Element('h2', {
							text: 'Buy from 7digital'
						}))
						
						var list = new Element('ul').inject($('purchasedetails'));
						tree.getElements('release').each(function(release){
							
							var html = "";
							
							var img = release.getElement('image');
							html += "<a href='" + release.getElement('url').get('html') + "'>";
							if (img){
								html += "<img src='" + release.getElement('image').get('text') + "' />";
							}
							html += "<span>";
							html += release.getElement('title').get('text');
							html += " (" + release.getElement('formattedPrice').get('text')  + ")</a></span>";
							
							new Element('li', {
								html: html
							}).inject(list);
						});
					}
				}).send();
			}
		}).send();
		new Request({
			url: 'feeds/reviews.php',
			data: {
				query: name
			},
			onComplete: function(response, tree){
				if (tree){
					console.log(tree.getElement('*').get('html'));
				}
			}
		}).send();
	},
	
	populateListenInformation: function(name){
		new Request({
			url: 'feeds/listen.php',
			data: {
				query: name
			},
			onComplete: function(response, tree){
				if (tree){
					var listen = $('listen').empty();
					listen.adopt(new Element('h2', {
						text: 'Tracks from Spotify'
					}));
					var list = new Element('ul');
					tree.getElements('album').each(function(album){
						new Element('li', {
							html: '<a href="' + album.getProperty('href') + '">' + album.getElement('name').get('text') + '</a>'
						}).inject(list);
					});
					list.inject(listen);
				} else {
					$('listen').set('html', '<p class="boo">Boooooo! We couldn\'t find any tracks for ' + artists[0].Name);
				}
			}
		}).send();
	},
	
	populateVideoInformation: function(name){
		new Request({
			url: 'feeds/video.php',
			data: {
				query: name
			},
			onComplete: function(response, tree){
				if (tree){
					$('videos').empty();
					var list = new Element('ul');
					tree.getElements('doc').each(function(item){
						var src = item.getElement('url').get('text').split('=')[1];
						new Element('li', {
							html: '<object width="380" height="285"><param name="movie" value="http://www.youtube.com/v/' + src + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + src + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="380" height="285"></embed></object>'
						}).inject(list);
					});
					list.inject($('videos'));
				} else {
					$('listen').set('html', '<p class="boo">Boooooo! We couldn\'t find any videos for ' + name);
				}
			}
		}).send();
	}
	
});


function usePointFromPostcode(address, callbackFunction) {
	localSearch.setSearchCompleteCallback(null, function() {
      if (localSearch.results[0]) {    
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        var point = new GLatLng(resultLat,resultLng);
        callbackFunction(point);
      }else{
        alert("Address not found!");
      }
    });  
	localSearch.execute(address);
};


$$('form').addEvent('submit', function(evt){
	evt.stop();
	usePointFromPostcode(this.getElement('input').get('value'), function(details){
		delete coords;
		window.coords = {};
		coords.latitude = details.y;
		coords.longitude = details.x;
		interface.centerMap();
	});
});

