$(document).ready(function(){
	if($('#tcmsLocationsSearchForm').children('form:first').length) {
		$('#tcmsLocationsSearchForm').children('form:first').ajaxForm({  
			        dataType: 'xml',
			        url: '/tcmsLocationsNew.html?ajax',
			        beforeSubmit: showAnimator,
			        success: show_tcms_map,
			        error: showError,
			        ajaxError: showError
		});
	}

	if(typeof edit === 'undefined') {
		$('div.tcmsLocationsSubmitButton').hide(0);
	}
});

if(typeof onMarkerDragStop === 'undefined') {
	function onMarkerDragStop(event) {
		$('#longitude').val(event.latlon.x);
		$('#latitude').val(event.latlon.y);
	}
}

// tcmsLocationsNew
 function ask_tcms_yahoo(ele) {
		$(ele).ajaxForm({  
	        dataType: 'xml',
	        url: '/tcmsLocationsNew.html?ajax',
	        beforeSubmit: showAnimator,
	        success: show_tcms_map,
	        error: showError,
	        ajaxError: showError
	    });
	    
	    return false;
}
function showError(request) {
	$("#ajax_error").append('<p>'+request.responseText+'</p>');
}

function showAnimator() {
	$.blockUI('<h1 style="padding: 5px;"><img src="/images/indicator.gif" style="vertical-align:middle"/> Bitte warten Sie einen Moment...</h1> ',  { width:'300px' });
	$('div.tcmsLocationsSubmitButton').hide();
}

function hideAnimator() {
	$.unblockUI();
}

function show_tcms_map(responseXML) {
	result = {};
	try {
		var childNodes = responseXML.documentElement.childNodes;
		for (var i = 0, child; child = childNodes[i]; i++) {
			if (child.nodeType != 1) {
				continue;
			}
			if(child.firstChild != null) {
				result[child.tagName] = child.firstChild.nodeValue;
			}
		}
	} catch(error) {
		alert('Sie müssen genauere Daten eingeben!');
		hideAnimator();
		return;
	}

	if (use_map == 'google'){
		show_google_map(result);
	}else if (use_map == 'yahoo'){
		show_yahoo_map(result);
	}	
	
	$('div.tcmsLocationsSubmitButton').show();
	hideAnimator();
}

function show_yahoo_map(result){

	var longitude = $('#longitude');
	var latitude = $('#latitude');
	if((latitude.val().length > 0 && latitude.val() != result.latitude) || (longitude.val().length > 0 && longitude.val() != result.longitude)) {
		var check_longlat = confirm(	
								'Die neu ermittelten Werte für Longitude/Latitude '+ 
								'stimmen nicht mit den von Ihnen eingegebenen Werten überein.'+
								'\n\n Klicken Sie auf [OK] umd die neuen Werte zu übernehmen'+ 
								'\n Klicken sie auf [Abbrechen] um die alten Werte zu behalten');
										
		if(check_longlat) {
			longitude.val(result.longitude);
			latitude.val(result.latitude);
		} else {
			result.latitude = latitude.val();
			result.longitude = longitude.val();
		}
	}
	
	if(latitude.val().length == 0 && longitude.val().length == 0) {
		longitude.val(result.longitude);
		latitude.val(result.latitude);	
	}
	
	$('#precision').val(result.precision);

	var latlon = new LatLon(result.latitude, result.longitude);
	var mymap = new Map("mapContainer", application_id, latlon, 3, MapViews.MAP, Languages.de_DE);
	mymap.addTool( new PanTool(), true );
	navWidget = new NavigatorWidget(); 
	mymap.addWidget(navWidget); 
	marker1 = new CustomPOIMarker('A','Informationen', result.infos, '0x0012f0', '0x88CCFF');
	marker1.setDraggable(true);
	
	mymap.addEventListener(Map.EVENT_MARKER_DRAG_STOP, onMarkerDragStop);
	mymap.addMarkerByLatLon(marker1, latlon);
}

function show_google_map(result){
	var marker = new Array();
	marker[0] = new Object();
	marker[0]["address"] = result.address;
	marker[0]["zip"] = result.zip;
	marker[0]["city"] = result.city;
	marker[0]["state"] = result.state;
	marker[0]["country"] = result.country;
	marker[0]["infos"] = result.infos;

	var geocoder = new GClientGeocoder();
	var longitude = "";
	var latitude = "";
	var state = "";
	var country = "";
	if (typeof result.state != "undefined"){
		state = ", "+result.state;
	}
	if (typeof result.country != "undefined"){
		country = ", "+result.country;
	}
	geocoder.getLatLng(result.address+", "+result.zip+" "+result.city+state+country,
						function(point){
								longitude = point.lng();
								latitude = point.lat();

								marker[0]["latitude"] = latitude;
								marker[0]["longitude"] = longitude;

								$('#latitude').val(latitude);	
								$('#longitude').val(longitude);

								Ginitialize(latitude, longitude, marker, 0);
						});

}

function insert_tcms_map() {
	showAnimator();
	var result = $('#tcmsLocationsSearchForm').find(':input').serializeArray();
	if(typeof edit != 'undefined') {
		result.push({name:"edit", value:edit});
	}
	result.push({name:"submit", value:'1'});
	
	$.post('/tcmsLocationsNew.html?submit', result, insert_tcms_map_done);

	return false;
}

function insert_tcms_map_done(data, textStatus) {
	hideAnimator();

	$('#tcmsLocationsAjaxSubmit').hide(0);
	$('#tcmsLocationsAjaxSubmit').show(2000);
	$('#tcmsLocationsAjaxSubmit').html(data);
	
	$('#tcmsLocationsSearchForm').hide(0);

}

// GOOGLE-Maps
//
// Initialisierung der Google-Karte
// param centerlat legt die latitude-Zentrierung fest
// param centerlng legt die longitude-Zentrierung fest
// param array markers js-array mit Markierungspunkten:
// 		var markers = new Array();
// 		markers[0] = new Object();
//		markers[0]["latitude"] = "50.461824";
//		markers[0]["longitude"] = "9.016038";
//		markers[0]["address"] = "Alte Burg 9";
//		markers[0]["zip"] = "63667";
//		markers[0]["city"] = "Nidda/Ulfa";
//		markers[0]["infos"] = 
//"arsmedia
//Alte Burg 9
//63667 Nidda/Ulfa
//
//Telefon: 06043 401389";
//		

function Ginitialize(centerlat, centerlng, markers, zoomlevel) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(centerlat, centerlng), 13);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		if (zoomlevel > 0)
			map.setZoom(zoomlevel);
			
		for (var i = 0; i < markers.length; i++) {
			var latlng = new GLatLng(markers[i]["latitude"], markers[i]["longitude"]);
			var address = markers[i]["address"]+', '+markers[i]["zip"]+' '+markers[i]["city"];
			map.addOverlay(createGMarker(latlng, address, markers[i]["infos"]));
		}
	}
}

// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createGMarker(point, Title, Info) {
	// Set up our GMarkerOptions object
	markerOptions = { title:Title };
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(Info);
	});
	return marker;
}

