/* ______________________________________________________
 *
 *	URL:		www.ardzdfundsie.de
 *	AUTHOR: 	Christian Schiffler @ feedback media design
 *	DATE:		October 20th, 2011
 * ______________________________________________________
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -80;
  this.offsetHorizontal_ = -80;
  this.height_ = 60;
  this.width_ = 160;
  this.text = opts.text;
  var me = this;
  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}
InfoBox.prototype = new google.maps.OverlayView();
InfoBox.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};
InfoBox.prototype.draw = function() {
  this.createElement();
  if (!this.div_) return;
  var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (!pixPosition) return;
  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = this.width_ + "px";
  this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
  this.div_.style.height = this.height_ + "px";
  this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
  this.div_.style.display = 'block';
};
InfoBox.prototype.createElement = function() {
  var panes = this.getPanes();
  var div = this.div_;
  if (!div) {
    // This does not handle changing panes.  You can set the map to be null and
    // then reset the map to move the div.
    div = this.div_ = document.createElement("div");
    div.style.border = "0px none";
    div.style.position = "absolute";
    if($.browser.msie && $.browser.version=="6.0")
    {
	    div.style.background = "url('img/base/tt-trans.gif') no-repeat top left";
    } else {
	    div.style.background = "url('img/base/tt-trans.png') no-repeat top left";
    }
    div.style.width = this.width_ + "px";
    div.style.height = this.height_ + "px";
    var contentDiv = document.createElement("div");
    contentDiv.style.padding = "10px"
    contentDiv.innerHTML = this.text;
    $(contentDiv).css({
    	'color': '#fff',
    	'font-size': '10px',
    	'padding-top': '20px',
    	'text-align': 'center'
    });

    div.appendChild(contentDiv);
    div.style.display = 'none';
    panes.floatPane.appendChild(div);
  } else if (div.parentNode != panes.floatPane) {
    // The panes have changed.  Move the div.
    div.parentNode.removeChild(div);
    panes.floatPane.appendChild(div);
  } else {
    // The panes have not changed, so no need to create or move the div.
  }
}

var map=null;
$(document).ready(function(){

/**
 * Calculates the distance between "this" latlng and another point in km.
 * @see http://www.movable-type.co.uk/scripts/latlong.html
 *
 * @param {google.maps.LatLng} p The second lat lng point.
 * @return {number} The distance between the two points in km.
 * @private
*/
if(!google.maps.LatLng.prototype.distanceTo)
	google.maps.LatLng.prototype.distanceTo = function(p)
	{
		if (!this || !p)return 0;
		var R = 6371; // Radius of the Earth in km
		var dLat = (p.lat() - this.lat()) * Math.PI / 180;
		var dLon = (p.lng() - this.lng()) * Math.PI / 180;
		var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(this.lat() * Math.PI / 180) * Math.cos(p.lat() * Math.PI / 180) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		var d = R * c;
		return d;
	};

	map = new AZUSMap({
		mapcenter: new google.maps.LatLng(36.92154367997194,-39.38268419999997),
		mappoints: [
		{
			latlng: [40.71149877735118,-74.01330692936097],
			name:'Einsturz World Trade Center',
			text:'Der Einsturz des World Trace Centers war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [48.17312711352372,11.546558510589648],
			name:'Sommermärchen',
			text:'Das Fußball Sommermärchen 2006 war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [52.53523,13.389429999999948],
			name:'Mauerfall',
			text:'Der Fall der Berliner Mauer war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [51.49941992112336,-0.1272114585831332],
			name:'Royal Wedding Kate & William',
			text:'Die Hochzeit von William und Kate war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [30.044422,31.235696],
			name:'Sturz von Mubarak',
			text:'Die Revolution in Ägypten war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [47.7985268,13.0417624],
			name:'Salzburger Festspiele',
			text:'Die Eröffnung der Salzburger Festspiele war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [47.5414162,7.6201630],
			name:'EM 2008',
			text:'Die EM 2008 war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD undZDF.'
		},
		{
			latlng: [-26.1981602,28.0593491],
			name:'WM 2010',
			text:'Die WM 2010 war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD undZDF.'
		},
		{
			latlng: [5.5461822,95.3190536],
			name:'Tsunami 2004',
			text:'Der Tsunami 2004 war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [38.8897705,-77.0088348],
			name:'Vereidigung Obamas',
			text:'Die Vereidigung Obamas war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [59.9031372,10.6239176],
			name:'Lenas ESC-Sieg',
			text:'Lenas ESC-Sieg war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [51.5560188,-0.2795958],
			name:'Live Aid 1985',
			text:'Der Live Aid 1985 war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [41.9023018,12.4572563],
			name:'Ratzinger wird Papst',
			text:'Die Papstkrönung von Josef Ratzinger war [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		},
		{
			latlng: [39.9841499,116.3945923],
			name:'Olympische Spiele 2008',
			text:'Die Olympischen Spiele 2008 waren [realdist]m von mir entfernt. Erlebt habe ich es aus [mydist]m. Mit ARD und ZDF.'
		}
		]
	});
});


function prettyFloat(flt, prec)
{
	var floatprec=Math.pow(10, prec);
	var k=(Math.floor(flt*floatprec)/floatprec).toString();
	if(k.indexOf('.') == -1)
		k += '.00';
	var p = k.indexOf('.'), m = k.indexOf('-.');
	var f = (p == 0 || m == 0)? '0,' : ',';
	var pre=k.substring(0, p), pl=pre.length, div=Math.ceil(pre.length/3);
	for(var i=1;i<div;i++)
		pre=pre.substring(0,pl-(i*3)) + '.' + pre.substring(pl-(i*3), pre.length)
	return pre + f + k.substring(p+1, p+3);
}

var AZUSMap = function(options)
{
	this.init(options);
};

AZUSMap.prototype={
	display:{
		postcode: null,
		latlng: null,
		point: null,
		tvdist: null,
		realdist:null
	},
	map:null,
	init: function(options)
	{
		this.options=options;
		var me=this;
		var mapoptions = {
			aviews: [google.maps.MapTypeId.SATELLITE],
			center: this.options.mapcenter,
			disableDefaultUI: true,
			mapTypeControl: false,
			mapTypeId: google.maps.MapTypeId.HYBRID,
			navigationControl: true,
			navigationControloptions: {style:3},
			zoom: 2,
			zoomcontrol: 'large'
		};
		var map = this.map = new google.maps.Map($('#googlemaps')[0], mapoptions);
		// build markers now.
		var img = new google.maps.MarkerImage(
					/*url*/'http://www.google.com/mapfiles/marker_yellow.png'
					/*size*/ //new google.maps.Size(, ),
					/*origin*/ //new google.maps.Point(0,0),
					/*anchor*/ //new google.maps.Point(, )
					/*scaledsize*/
				);
		$.each(options.mappoints, function(i, e)
		{
				var options = {
					position : new google.maps.LatLng(e.latlng[0], e.latlng[1]),
					map : map,
					icon : img
				};
				e.latlng=options.position;
				var marker = new google.maps.Marker(options);
				google.maps.event.addListener(marker, 'click', function(){
					if(me.display.linePath)
						return;
					me.display.point=e;
					me.map.panTo(marker.getPosition());
					$('#mappoint')[0].value=e.name;
					if(me.infowindow)
						me.infowindow.setMap(null);
					me.infowindow=new InfoBox({latlng: marker.getPosition(), map: map, text: e.name});
				});
		});
		$('#submit-1').click(function()
		{
			me.updateDistance();
			return false;
		});
		$('#submit-2').click(function()
		{
			$('#map-content-1').removeClass('hide');
			$('#map-content-2').addClass('hide');
			if(me.display.linePath)
				me.display.linePath.setMap(null);
			if(me.infowindow)
				me.infowindow.setMap(null);
			me.display={};
			$('#mappoint')[0].value='';
			return false;
		});
		$('#facebook-share-button-map').click(function(){
			postToFacebook(me.socialtext, window.location.href);
			return false;
		});
	},
	resize: function(){
		$('#googlemaps').delay(100, "mapQueue").queue("mapQueue", function(){ 
			google.maps.event.trigger(map.map, 'resize');
			map.map.panTo(map.options.mapcenter);
		}).dequeue("mapQueue");
	},
	lookupPostcode: function(postcode)
	{
		var coder = new google.maps.Geocoder();
		this.display.postcode=postcode;
		var me=this;
		coder.geocode({address:postcode+', Deutschland'}, function(results, status)
		{
			if (status == google.maps.GeocoderStatus.OK)
			{
				var data = results[0];
				me.display.latlng=data.geometry.location;
				me.updateDistance();
			}
			else
			{
				$('#postcode').addClass('error');
			}
		});
	},
	checkInput: function(selector){
		if($(selector)[0].value=='')
		{
			$(selector).addClass('error');
			return false;
		} else {
			$(selector).removeClass('error');
			return true;
		}
	},
	convertText: function(text, my, real){
		var mytext=text;
		mytext=mytext.replace( /\[realdist\]/, real);
		mytext=mytext.replace( /\[mydist\]/, my);
		return mytext;
	},
	updateDistance: function()
	{
		// strip non numeric chars from distance
		$('#distance')[0].value = $('#distance')[0].value.replace(/[^0-9,.]/g,'');
		// all mandatory fields provided?
		// watch out! order matches here as we are changing the input fields, the boolean condition must be kept at the end.
		var ok=this.checkInput('#postcode');
		ok=this.checkInput('#distance') && ok;
		ok=this.checkInput('#mappoint') && ok;
		if(!ok)return false;

		if(!this.display.latlng)
		{
			this.lookupPostcode($('#postcode')[0].value);
			return;
		}
		if(this.display.point)
		{
			// perform work here...
			$('#map-content-1').addClass('hide');
			$('#map-content-2').removeClass('hide');
			this.display.linePath = new google.maps.Polyline({
				geodesic: true,
				path: [this.display.latlng, this.display.point.latlng],
				strokeColor: "#FF0000",
				strokeOpacity: 1.0,
				strokeWeight: 2
			});
			this.display.linePath.setMap(this.map);
			var realdist=prettyFloat(this.display.latlng.distanceTo(this.display.point.latlng)*1000, 2);
			$('#realdistance')[0].value=realdist+' Meter';
			$('#distanceardzdf')[0].value=$('#distance')[0].value+' Meter';
			var btn=$('#twitter-share-button-map')[0];
			this.socialtext=this.convertText(this.display.point.text, $('#distance')[0].value, realdist);
//			btn.href='http://twitter.com/home?status='+encodeURIComponent(this.socialtext+' '+window.location.href);
			btn.href='http://twitter.com/home?status='+encodeURIComponent(this.socialtext+' '+pageRoot+'w');
		} else {
			$('#realdistance')[0].value='';
			$('#distanceardzdf')[0].value='';
		}
	}
}
