var GoogleMap = new Object();
GoogleMap.button = new Object();
GoogleMap.doneButton = {'image' : 'images/btn_done_geotagging.gif', 'text' : 'Done Geo-Tagging'};

GoogleMap.button.setButton = function(object){
	if(!GoogleMap.useImageButton)
	{
		$('a', object).click(function(e){
			GoogleMap.clickButton();
			e.preventDefault();
			return false;
		});
	}
	else
	{	
		object.click(function(e){
			GoogleMap.clickButton();
			e.preventDefault();
			return false;
		});
	}
	this._object = object;
}

GoogleMap.button.changeTo = function(buttonType){
	if(GoogleMap.useImageButton )
	{
	
		this.defaultSrc = this._object.attr('src');
		this._object.attr('src', buttonType.image);
	}
	else{
		this.defaultSrc = $('a', this._object).text();
		$('span', this._object).text(buttonType.text);
	}
}

GoogleMap.button.restore  = function(){
	if(GoogleMap.useImageButton )
	{
		this._object.attr('src', this.defaultSrc);
	}
	else
	{
		$('span', this._object).text(this.defaultSrc);
	}
}

GoogleMap.initialize = function() {
	GoogleMap.mapped = $('#mapped').val() == 1?true:false;
	if($('#geotag'))
	{
		if($('a', this._object).length == 0)
		{
			GoogleMap.useImageButton = true;
		}
		else
		{
			GoogleMap.useImageButton = false;
		}
		GoogleMap.button.setButton($('#geotag').show());
	}
	
	if (GBrowserIsCompatible()) {
		//setup limits
		GoogleMap.minZoom = 8;
		GoogleMap.maxZoom = 18;
		GoogleMap.defaultZoom = 15;
		GoogleMap.aberration = 0.2;

		if($('#info_window').length == 1)
		{
			GoogleMap.description = $('#info_window').html();
		}
		else
		{
			GoogleMap.description = false;
		}

		if((typeof gmaps_country_id != 'undefined') && (gmaps_country_id == 51)) {
			var countryMapSW = new GLatLng(33.68321092658007 , 31.6571044921875);
			var countryMapNE = new GLatLng(36.58024660149866 , 35.2001953125);
			GoogleMap.allowedCountryBounds = new GLatLngBounds(countryMapSW, countryMapNE);
		}
		//setup map
		var map = new GMap2(document.getElementById("google_map"));

		//move interest point to center
		var latitude = $('#latitude').val();
		var longitude = $('#longitude').val();
		
		GoogleMap.defaultCenter = new GLatLng(latitude, longitude);
		
		map.setCenter(GoogleMap.defaultCenter, GoogleMap.defaultZoom);

		GoogleMap.map = map;
			
		for(var i=0;i<G_MAPMAKER_MAP_TYPES.length;i++)
		{
			G_MAPMAKER_MAP_TYPES[i].getMinimumResolution = function() {return GoogleMap.minZoom}
			G_MAPMAKER_MAP_TYPES[i].getMaximumResolution = function() {return GoogleMap.maxZoom}
			map.addMapType(G_MAPMAKER_MAP_TYPES[i]);
		}

		for(var i=0;i<G_DEFAULT_MAP_TYPES.length;i++)
		{
			map.removeMapType(G_DEFAULT_MAP_TYPES[i]);
		}

		
		map.addMapType(G_SATELLITE_MAP);
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());
		
		// setup map events
//		GEvent.addListener(map, "zoomend", function(oldLevel, newLevel){
//			GLog.write(newLevel);
//			map.setCenter(GoogleMap.centerCyprus);
//			var currentBounds = map.getBounds();
//			var sw = currentBounds.getSouthWest();
//			var ne = currentBounds.getNorthEast();
//			GLog.write('SW lat: ' + sw.lat() + ' ; long: ' + sw.lng());
//			GLog.write('NE lat: ' + ne.lat() + ' ; long: ' + ne.lng());
//		});
		
		if((typeof gmaps_country_id != 'undefined') && (gmaps_country_id == 51)) {
			GEvent.addListener(map, "move", function() {
				GoogleMap.checkBounds();
			});
		}
		map.setMapType(G_MAPMAKER_NORMAL_MAP);

		
		// Create our "tiny" marker icon
		var kyprosIcon = new GIcon(G_DEFAULT_ICON);
		
		kyprosIcon.image = "images/pushpin.png";
		kyprosIcon.shadow = "";
		kyprosIcon.iconSize = new GSize(50, 50);
		kyprosIcon.shadowSize = new GSize(25, 25);
		kyprosIcon.iconAnchor = new GPoint(23, 34);
		kyprosIcon.infoWindowAnchor = new GPoint(25, 2);
		kyprosIcon.imageMap = [0,0,49,0,49,49,0,49];
		//create and setup marker
		var marker = new GMarker(new GLatLng(latitude, longitude), {draggable: true, title: $('#title').val(), icon:kyprosIcon});

		GoogleMap.marker = marker;
		GEvent.addListener(marker, "drag", function() {
				var location = marker.getLatLng();
				$( '#longitude' ).val(location.lng());
				$( '#latitude' ).val(location.lat());
		});

		GEvent.addListener(marker, "dragstart", function() {
				marker.closeInfoWindow();
		});
		
		GEvent.addListener(marker, "dragend", function() {
				marker.openInfoWindowHtml('Please pinpoint the new position');
				map.panTo(marker.getLatLng());
		});

		marker.disableDragging();

		if(GoogleMap.mapped)
		{
			map.addOverlay(marker);
			if(GoogleMap.description)
			{
				marker.openInfoWindowHtml(GoogleMap.description);
			}
		}
		
		//additional setups		

	}
}

GoogleMap.cancelGeoTag = function(){
	$('#cancel').hide();
	GoogleMap.button.restore();
	GoogleMap.marker.disableDragging();
	GoogleMap.map.removeOverlay(GoogleMap.marker);
	return false;
}

GoogleMap.clickButton = function() {
			if($('#logged_in').val() != 1)
			{
				$('a#login').trigger('click');
				return false;
			}
			if(GoogleMap.marker.draggingEnabled())
			{
				GoogleMap.marker.disableDragging();
				GoogleMap.marker.closeInfoWindow();
				GoogleMap.marker.openInfoWindowHtml('<strong>Saving data...</strong>');
				GoogleMap.sendInfo();
			}
			else
			{
				GoogleMap.marker.setLatLng(GoogleMap.map.getCenter());
				GoogleMap.map.addOverlay(GoogleMap.marker);
				GoogleMap.marker.enableDragging();
				GoogleMap.marker.closeInfoWindow();
				GoogleMap.marker.openInfoWindowHtml("Please pinpoint the new position.");
//				this.button.changeTo('images/b_save_geotag.gif');
				this.button.changeTo(GoogleMap.doneButton);
				$('#cancel').show();
			}
};

// If the map position is out of range, move it back
GoogleMap.checkBounds = function() {
	// Perform the check and return if OK
	var currentBounds = GoogleMap.map.getBounds();
	var cSpan = currentBounds.toSpan(); // width and height of the bounds
	var offsetX = cSpan.lng() / (2+GoogleMap.aberration); // we need a little border
	var offsetY = cSpan.lat() / (2+GoogleMap.aberration);
	var C = GoogleMap.map.getCenter(); // current center coords
	var X = C.lng();
	var Y = C.lat();

	// now check if the current rectangle in the allowed area
	var checkSW = new GLatLng(C.lat()-offsetY,C.lng()-offsetX);
	var checkNE = new GLatLng(C.lat()+offsetY,C.lng()+offsetX);
	
	if (GoogleMap.allowedCountryBounds.containsLatLng(checkSW) &&
		GoogleMap.allowedCountryBounds.containsLatLng(checkNE)) {
		return; // nothing to do
	}

	var AmaxX = GoogleMap.allowedCountryBounds.getNorthEast().lng();
	var AmaxY = GoogleMap.allowedCountryBounds.getNorthEast().lat();
	var AminX = GoogleMap.allowedCountryBounds.getSouthWest().lng();
	var AminY = GoogleMap.allowedCountryBounds.getSouthWest().lat();

	if (X < (AminX+offsetX)) {X = AminX + offsetX;}
	if (X > (AmaxX-offsetX)) {X = AmaxX - offsetX;}
	if (Y < (AminY+offsetY)) {Y = AminY + offsetY;}
	if (Y > (AmaxY-offsetY)) {Y = AmaxY - offsetY;}

	GoogleMap.map.setCenter(new GLatLng(Y,X));
	return;
}



GoogleMap.verifyResponse = function(data)
{
	if(data.message == 'saved')
	{
		window.location.reload(true)
	}
	else if(data.status == 'publish_facebook')
	{
		var facebookPublish = function(id, error) {
			window.location.reload(true);
		}
		
		FB.ui(data.facebook_event, facebookPublish);
	}	
	else{
		
		GoogleMap.cancelGeoTag();
	}
}

GoogleMap.sendInfo = function()
{
	var postData = {latitude:$('#latitude').val(),longitude:$('#longitude').val(),X_AJAX_INFO:$('#x_ajax_info').val(), ajax_key:$('#ajax_key').val(), ajax_id:$('#ajax_id').val()};
	var url = 'http://' + location.hostname;
	$.post(url, postData, GoogleMap.verifyResponse, "json");

}
$(document).ready(
	function(){
		GoogleMap.initialize();
	});
	
