var mylocation = {};

mylocation.maps_loaded = false;
mylocation.maps_fashion = 'new';
mylocation.geocoder = null;
mylocation.countrycodes = [];
mylocation.countrynames = [];

// Diese Funktion wird aufgerufen, wenn auf einen Resultat-Link geklickt wird
mylocation.onclick = function() {}
mylocation.ondelete = function() {}

mylocation.checkMapsLoaded = function() {
	if(window.GClientGeocoder) {
		this.maps_loaded = true;
		this.maps_fashion = 'old';

		return true;
	}

	if(!window.google)
		return false;

	if(!window.google.maps)
		return false;

	if(window.google.maps.ClientGeocoder) {
		this.maps_loaded = true;
		this.maps_fashion = 'new';

		return true;
	}

	return false;
}

mylocation.startLocSearch = function() {
	if($('startLoc').value.length == 0 || $('startLoc').value == $('startLoc').title) {
		var c = getCookie('mylocation');
		if(c == null) {
			alert('Bitte einen Ort oder eine Adresse angeben.');
			return;
		}

		var values = decodeURIComponent(c).replace('+', ' ', 'g').split('|');

		mylocation.ondelete(values[0]);

		return;
	}

	display('startLocResults', 'none');
	display('startLocThrobber', '');
	display('startLocBox', '');

	$('startLocSubmit').disabled = true;

	this.maps_loaded = this.checkMapsLoaded();

	if(this.maps_loaded == false) {
		google.load("maps", "2", {'language': 'de', 'callback' : function() {
			mylocation.maps_loaded = true;
			mylocation.maps_fashion = 'new';
			mylocation.startLocSearch();
		}});

		return;
	}

	if(this.geocoder == null) {
		if(this.maps_fashion == 'new')
			this.geocoder = new google.maps.ClientGeocoder();
		else
			this.geocoder = new GClientGeocoder();
	}

	this.geocoder.getLocations($('startLoc').value, mylocation.startLocSearchResults);
}

mylocation.startLocSearchResults = function(response) {
	$('startLocSubmit').disabled = false;

	if(!response || response.Status.code != 200) {
		display('startLocBox', 'none');

		alert('Der Ort "' + $('startLoc').value + '" wurde nicht gefunden.');

		return;
	}

	var nresults = 0;
	clear('startLocResults');

	var places = [];

	for(var i = 0; i < response.Placemark.length; i++) {
		var place = response.Placemark[i];

		if(place.AddressDetails.Accuracy < 4)
			continue;

		var cc = null;
		try {
			cc = place.AddressDetails.Country.CountryNameCode;
		}
		catch(e) {};

		if(cc == null)
			continue;

		if(mylocation.countrycodes.length != 0 && mylocation.countrycodes.indexOf(cc) == -1)
			continue;

		var locality = null;
		try {
			locality = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality;
		}
		catch(e) {
			try {
				locality = place.AddressDetails.Country.AdministrativeArea.Locality;
			}
			catch(e) {
				locality = null;
			}
		}

		if(locality == null)
			continue;

		var ort = '';
		var plz = '';

		var ort = locality.LocalityName;

		if(place.AddressDetails.Accuracy > 4) {
			try {
				plz = locality.PostalCode.PostalCodeNumber;
			}
			catch(e) {
				try {
					plz = locality.DependentLocality.PostalCode.PostalCodeNumber;
				}
				catch(e) {
					plz = '';
				}
			}
		}

		var coordinates = place.Point.coordinates[1] + ';' + place.Point.coordinates[0];

		var location = {
			address: place.address,
			cc: cc,
			plz: plz,
			ort: ort,
			lat: place.Point.coordinates[1],
			lng: place.Point.coordinates[0]
		};

		places.push(location);
	}

	nresults = places.length;

	if(nresults == 0) {
		display('startLocBox', 'none');

		var text = 'Der Ort "' + $('startLoc').value + '" wurde nicht gefunden.';

		if(mylocation.countrycodes.length != 0) {
			text = text + '\n\nEs werden nur folgende Länder durchsucht:\n';

			for(var i = 0; i < mylocation.countrynames.length; i++)
				text = text + mylocation.countrynames[i] + '\n';
		}

		alert(text);

		return;
	}

	if(nresults == 1) {
		var p = places[0];

		var ml = [];
		ml.push(encodeURIComponent(p.address));
		ml.push(encodeURIComponent(p.cc));
		ml.push(encodeURIComponent(p.plz));
		ml.push(encodeURIComponent(p.ort));
		ml.push(p.lat);
		ml.push(p.lng);

		Cookies.set('mylocation', ml.join('|'), 2);
		Cookies.set('sortby', 'distanz', 2);

		mylocation.onclick(ml.join(';'), p.cc.toLowerCase() + '-' + p.ort.toLowerCase());

		return;
	}

	for(var i = 0; i < nresults; i++) {
		var li = $Element('li');

		var a = $Link('#', places[i].address);
		a.setAttribute('ml-address', places[i].address);
		a.setAttribute('ml-cc', places[i].cc);
		a.setAttribute('ml-plz', places[i].plz);
		a.setAttribute('ml-ort', places[i].ort);
		a.setAttribute('ml-lat', places[i].lat);
		a.setAttribute('ml-lng', places[i].lng);
		a.onclick = function() {
			var ml = [];
			ml.push(encodeURIComponent(this.getAttribute('ml-address')));
			ml.push(encodeURIComponent(this.getAttribute('ml-cc')));
			ml.push(encodeURIComponent(this.getAttribute('ml-plz')));
			ml.push(encodeURIComponent(this.getAttribute('ml-ort')));
			ml.push(this.getAttribute('ml-lat'));
			ml.push(this.getAttribute('ml-lng'));

			Cookies.set('mylocation', ml.join('|'), 2);
			Cookies.set('sortby', 'distanz', 2);

			mylocation.onclick(ml.join(';'), this.getAttribute('ml-cc').toLowerCase() + '-' + this.getAttribute('ml-ort').toLowerCase());

			return false;
		}

		li.appendChild(a);

		$('startLocResults').appendChild(li);
	}

	display('startLocThrobber', 'none');
	display('startLocResults', '');
}

mylocation.resetCountry = function() {
	this.countrycodes = [];
	this.countrynames = [];
}

mylocation.setCountry = function(countrycode, name) {
	this.countrycodes.push(countrycode);
	this.countrynames.push(name);
}
