var $ = function(s){
	return document.getElementById(s);
};
	
function getWindowDimensions(){
	
	var height, width;
	
	if (typeof window.innerWidth != 'undefined'){
		
		width = window.innerWidth;
		height = window.innerHeight;

	} else if ((typeof document.documentElement != 'undefined') && (typeof document.documentElement.clientWidth != 'undefined') && (document.documentElement.clientWidth)){

		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	
	} else {
		
		width = document.getElementsByTagName('body')[0].clientWidth;
		height = document.getElementsByTagName('body')[0].clientHeight;
	}
	
	return {width:width-2, height:height };
}

var flickr = {
	url: 		"http://api.flickr.com/services/rest/",
	api_key:	"9b629a5deea5f5e9423ddab9eebca3be",
	search: {
		bbox:				"-180,-90,180,90",
		accuracy:			1,
		page:				0,
		per_page:			50,
		extras:				"geo",
		min_upload_date:	1,
		sort:				"date-posted-desc"
	},
	photoset: {
		method:				"flickr.photosets.getList"
	}
};


var hashes = document.location.hash.split("/");
var params = {};

for (var all in hashes){
	var param = hashes[all].split(":");
	params[param[0]] = param[1];
}

if (params.bbox){
	flickr.search.bbox = params.bbox;
}

var loc = {alize:{}};

loc.alize.me = {

	map: null,
	items: null,
	bounds: new GLatLngBounds(new GLatLng(-15,-60),new GLatLng(45,60)),
	flickrPreview: null,
	flickrBackground: null,
	pinkIcon: new GIcon(),
	markerUrl: "../images/",
	size: getWindowDimensions(),
	
	zoomControl: null,
	typeControl: null,
	scaleControl: null,

	init: function(){
	
		if (GBrowserIsCompatible()) {
		
			$("map").style.width = this.size.width + "px";
			$("map").style.height = (this.size.height - 18) + "px";
		
			this.initMap();
			
			this.pinkIcon.shadow = this.markerUrl + "marker/shadow.png";
			this.pinkIcon.image = this.markerUrl + "marker/blue.png";
			this.pinkIcon.transparent = this.markerUrl + "marker/transparent.png";
			this.pinkIcon.iconSize = new GSize(14, 18);
			this.pinkIcon.iconAnchor = new GPoint(6, 18);
			this.pinkIcon.infoWindowAnchor = new GPoint(5, 1);
			this.pinkIcon.shadowSize = new GSize(32, 18);

			var bg = new GIcon();
			bg.image = this.markerUrl + "flickr.gif";
			bg.iconSize = new GSize(80, 85);
			bg.iconAnchor = new GPoint(38, 85);
			
			this.flickrBackground = new GMarker(new GLatLng(0, 0), {
				icon:bg,
				zIndexProcess: function(){return 100000000;},
				clickable: false
			});
			
			var preview = new GIcon();
			preview.iconSize = new GSize(75, 75);
			preview.iconAnchor = new GPoint(36, 83);
			
			this.flickrPreview = new GMarker(new GLatLng(0, 0), {
				icon:preview,
				zIndexProcess: function(){return 100000001;}
			});
			
			GEvent.bind(this.flickrPreview, 'mouseout', this, function(evt) {
				this.flickrPreview.hide();
				this.flickrBackground.hide();
			});				
			
			if (this.items){
				this.draw();
			}
		}
	},
	
	initMap: function(){
		
		this.map = new GMap2(document.getElementById("map"));

		this.map.enableDoubleClickZoom();
		this.map.enableContinuousZoom();
		this.map.enableScrollWheelZoom();
		
		this.map.setCenter(new GLatLng(0,0),0);
		
		GEvent.bind(this.map, 'moveend', this, this.link);
		GEvent.bind(this.map, 'zoomend', this, this.link);
		GEvent.bind(this.map, 'dragend', this, this.link);
		
		var b = flickr.search.bbox.split(",");
		var bounds = new GLatLngBounds(
			new GLatLng((b[1]),Number(b[0])),
			new GLatLng(Number(b[3]),Number(b[2]))
		);
	
		this.map.setZoom(this.map.getBoundsZoomLevel(bounds));
		this.map.setCenter(bounds.getCenter());
		this.checkBounds();	
		
	},
	
	
	load: function(){
		
		var url = "";
		
		for (var i in flickr.search){
			url += i + "=" + flickr.search[i] + "&";
		}
		
		url += (params.user ? "user_id=" + params.user : "" );
		url += (params.tag ? "&tags=" + params.tag: "");
		
		if (params.set){
			url += "&photoset_id=" + params.set;
			url += "&method=" +  "flickr.photosets.getPhotos";
		} else {
			url +="&method=" +  "flickr.photos.search";
		}
		
		var jsr = new JSONscriptRequest(flickr.url + "?api_key=" +  flickr.api_key + "&format=json&" + url);
	},
	
	
	createMarker: function(point, item){
		
		var marker = new GMarker(point, {
			
			icon: this.pinkIcon,
			title: item.title
		});
		
		var markerUrl = this.markerUrl;
		
		GEvent.addListener(marker, 'click', function() {
			
			window.open("http://loc.alize.us/#/flickr:" + item.id);
		});
		
		var fp = this.flickrPreview;
		var bg = this.flickrBackground;
		
		GEvent.addListener(marker, 'mouseover', function() {
			
			fp.setImage("");
			fp.setPoint(point);
			bg.setPoint(point);
			fp.show();
			bg.show();				
			fp.setImage("http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg");
		});
		
		return marker;	
	},
	
	draw: function(){
		
		if (this.items.photo && this.items.photo.length > 0) {

			this.map.clearOverlays();
			
			this.bounds = new GLatLngBounds();
			
			this.map.addOverlay(this.flickrBackground);
			this.map.addOverlay(this.flickrPreview);
			
			var count = this.items.total;
			
			$("map-status").innerHTML = count + " photos";
		
			for (var i=0; i < this.items.photo.length; i++){
				
				var photo = this.items.photo[i];
				var point = new GLatLng(photo.latitude, photo.longitude); 
				this.bounds.extend(point);
				var marker = this.createMarker(point, photo);
				this.map.addOverlay(marker);
			}
			
			this.flickrBackground.hide();
			this.flickrPreview.hide();
		}
	},
	
	checkBounds:function(){
		
		var zoom = this.map.getBoundsZoomLevel(this.bounds);
		var sw = this.bounds.getSouthWest();
		var ne = this.bounds.getNorthEast();
		var center = new GLatLng((sw.lat() + ne.lat())/2, (sw.lng() + ne.lng())/2);
		if (this.zoomControl){
			this.map.removeControl(this.zoomControl);
		}
		if (this.size.width > 400){
			this.zoomControl = new GMapTypeControl();
			this.map.addControl(this.zoomControl);
		}
		if (this.scaleControl){
			this.map.removeControl(this.scaleControl);
		}
		if (this.size.height > 350){
			this.scaleControl = new GScaleControl(); 
			this.map.addControl(this.scaleControl);
		}			
		if (this.typeControl){
			this.map.removeControl(this.typeControl);
		}	
		if (this.size.height > 150){
			this.typeControl = this.size.height < 300 ? new GSmallZoomControl() : new GLargeMapControl(); 
			this.map.addControl(this.typeControl);
		}
		
		$("map-footer").style.width = this.size.width + "px";
		this.link();
	},
	onData: function(data){
		this.items = data;
		if (this.map){
			this.draw();
		}
	},
	link: function(){
		var center = this.map.getCenter();
		var zoom = this.map.getZoom();
		$("link-localizeus").href = "http://loc.alize.us/#/geo:" + center.lat() + "," + center.lng() + "," + zoom + "," + this.map.getCurrentMapType().getUrlArg();		
	}
};


var jsonFlickrApi = function(response){
	loc.alize.me.onData(response.photoset || response.photos);
};

loc.alize.me.load();
