/*
*         ________           __   __                     __
*        / ____/ /___  _____/ /__/ /   ____  _________ _/ /
*       / /_  / / __ \/ ___/ //_/ /   / __ \/ ___/ __ `/ / 
*      / __/ / / /_/ / /__/ ,< / /___/ /_/ / /__/ /_/ / /  
*     /_/   /_/\____/\___/_/|_/_____/\____/\___/\__,_/_/   
*                                                          
*     Do good. Fast.                      
*/


function showYourLocationMap() {
    if ($('YourLocationMap')) {
	$('YourLocationMap').update('<img alt="Staticmap?center=55" src="http://maps.google.com/staticmap?center='+Cookie.get('lattitude')+','+Cookie.get('longitude')+'&amp;zoom=8&amp;size=200x70&amp;maptype=mobile&amp;markers='+Cookie.get('lattitude')+','+Cookie.get('longitude')+',greena&amp;key=ABQIAAAAetD5ZoEWBnjjt_tdVu_wXxQ6Q70nDL4VGIKG0lZ3HFEpUiBs0hQipxegGqZO_1dD2FVLb3WDz33WnQ&amp;sensor=false" />');
    }
}

document.observe("dom:loaded", function() {
    // Get location and store in Cookies for future use.
    var loc = Cookie.get('lattitude');
    if(!loc) {
        Cookie.set('lattitude', geoip_latitude(), 60*60);
        Cookie.set('longitude', geoip_longitude(), 60*60);
        Cookie.set('location', geoip_city(), 60*60);
        showYourLocationMap();
    } else {
        showYourLocationMap();
    }



});




var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}

var divElementID;
var lat;
var lng;
function staticGoogleMapClick(imageElement, lat, lng) {
    divElementID = imageElement.up().identify();
    imageElement.up().update("Loading, please wait ...");
    lat = lat;
    lng = lng;
    google.load("maps", "2.x", {callback:function() {
        map = new google.maps.Map2(document.getElementById(divElementID));
        map.setCenter(new google.maps.LatLng(lat,lng), 10);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        map.addOverlay( new GMarker(new GLatLng(lat,lng)));
				var myLat = Cookie.get("lattitude");
				var myLng = Cookie.get("longitude");
				if (myLat && parseFloat(myLat) != lat &&  myLng && parseFloat(myLng) != lng) {
					var youIcon = new GIcon(G_DEFAULT_ICON);
					youIcon.image = "/images/gmapsmarker-you.png";
					pointer = new GMarker(new GLatLng(parseFloat(myLat),parseFloat(myLng)), youIcon);
					map.addOverlay(pointer);
				}
    }});
}


/***** Your Location! ****/
var setMyLocation = {'map':false,'geocoder':false, 'pointer':false, 'newLat':false, 'newLocation':false, 'newLng':false };
function showSetMyLocationBox() {
	$('SetMyLocation').show();
	if (navigator.geolocation) {
		$('LocationFromComputer').show();
		$('LocationFromComputerInstructions').hide();
	}
	$('SearchSelectTextBox').focus();
	google.load("maps", "2.x", {'callback':function() {	
		if (!setMyLocation.map) {
			setMyLocation.map = new google.maps.Map2(document.getElementById("SetMyLocationMap"));			
			setMyLocation.map.addControl(new GLargeMapControl());
			setMyLocation.map.addControl(new GMapTypeControl());
			setMyLocation.map.addControl(new GScaleControl());
			setMyLocation.geocoder = new GClientGeocoder();
			GEvent.addListener(setMyLocation.map, "click", function(overlay, latlng) {
				privateSetMyLocationToPossibleLocation(latlng.lat(),latlng.lng(),'');
				setMyLocation.pointer.setLatLng(latlng);
			});
		} else {
			setMyLocation.map.removeOverlay(setMyLocation.pointer);
		}

		setMyLocation.map.setCenter(new google.maps.LatLng(Cookie.get('lattitude'), Cookie.get('longitude')), 10);

		setMyLocation.pointer = new GMarker(new GLatLng(Cookie.get('lattitude'), Cookie.get('longitude')), {draggable: true});
		setMyLocation.map.addOverlay(setMyLocation.pointer);
		GEvent.addListener(setMyLocation.pointer, "dragend", function() {
			privateSetMyLocationToPossibleLocation(setMyLocation.pointer.getLatLng().lat(),setMyLocation.pointer.getLatLng().lng(),'');
		});

	}});
}
function hideSetMyLocationBox() {
	$('SetMyLocation').hide();
	setMyLocation.newLat = false;
	setMyLocation.newLng = false;
	setMyLocation.newLocation = false;
}
function setMyLocationBoxOKClicked() {
	if (setMyLocation.newLat && setMyLocation.newLng) {
		Cookie.set('lattitude', setMyLocation.newLat, 12*60*60);
    Cookie.set('longitude', setMyLocation.newLng, 12*60*60);
    Cookie.set('location', setMyLocation.newLocation, 12*60*60);
	}
	$('SetMyLocation').hide();
	if ($('YourLocationMap')) {
		$('YourLocationMap').update('<img alt="Staticmap?center=55" src="http://maps.google.com/staticmap?center='+setMyLocation.newLat+','+setMyLocation.newLng+
			'&amp;zoom=8&amp;size=200x70&amp;maptype=mobile&amp;markers='+setMyLocation.newLat+','+setMyLocation.newLng+',greena&amp;key=ABQIAAAAetD5ZoEWBnjjt_tdVu_wXxQ6Q70nDL4VGIKG0lZ3HFEpUiBs0hQipxegGqZO_1dD2FVLb3WDz33WnQ&amp;sensor=false" />');
  }
}
function setMyLocationSearchChanged() {
  if ($('SearchSelectTextBox').value) {
    $('SearchSelectCountry').show();
  } else {
    $('SearchSelectCountry').hide();
  }
}
function setMyLocationSearch() {
	$('SearchLocationIsLoading').show();
	$('SearchLocationWasNotFound').hide();	
	setMyLocation.geocoder.setBaseCountryCode($('SearchSelectCountry').value);
	setMyLocation.geocoder.getLocations($('SearchSelectTextBox').value, function(response) {
		$('SearchLocationIsLoading').hide();
		if (!response || response.Status.code != 200) {
			$('SearchLocationWasNotFound').show();
		} else {
			var place = response.Placemark[0];
			var city = '';
			if (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea
				&& place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea
				&& place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
					city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
			} else if (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea
				&& place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
					city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
			} else if (place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea
				&& place.AddressDetails.Country.AdministrativeArea) {
					city = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
			}
			privateSetMyLocationToPossibleLocation(place.Point.coordinates[1], place.Point.coordinates[0], city);
			setMyLocation.pointer.setLatLng(new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]));
			setMyLocation.map.setCenter(new google.maps.LatLng(place.Point.coordinates[1], place.Point.coordinates[0]));
		}
	});
}
function setMyLocationFromBrowser() {
  $('LocationFromComputer').hide();
  $('LocationFromComputerInstructions').show();
  navigator.geolocation.getCurrentPosition(function(position) {
		$('LocationFromComputerInstructions').hide();
		privateSetMyLocationToPossibleLocation(position.coords.latitude, position.coords.longitude,'');
		setMyLocation.pointer.setLatLng(new GLatLng(position.coords.latitude, position.coords.longitude));
		setMyLocation.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
  },function(error) {
		if (error.code == error.POSITION_UNAVAILABLE) {
			$('LocationFromComputer').update("There was an error when attempting to fetch your position.");
		} else if (error.code == error.TIMEOUT) {
			$('LocationFromComputer').update("There was an Timeout error when attempting to fetch your position.");
		}
		$('LocationFromComputer').show();
		$('LocationFromComputerInstructions').hide();
	});


}
function privateSetMyLocationToPossibleLocation(lat,lng,city) {
			setMyLocation.newLat = lat;
			setMyLocation.newLng = lng;
			setMyLocation.newLocation = city;
}
