String.prototype.linkify = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
		return "<a href='"+m+"' target='_blank'>"+m+"</a>";
	});
}

function relativeTime(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
	    r = 'a minute ago';
	  } else if(delta < 120) {
	    r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
	    r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  } else if(delta < (90*60)) {
	    r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
	    r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  } else if(delta < (48*60*60)) {
	    r = '1 day ago';
	  } else {
	    r = (parseInt(delta / 86400)).toString() + ' days ago';
	  }
	  
	  return r;
}

function capitalise (s) {
	if (typeof s != 'string') {
		return s;
	}
	var fL = s.substr(0,1);
	return (fL.toUpperCase() + s.substr(1));
}

function capitaliseField (element) {
	$(element).val(capitalise($(element).val()));
}

/**
 * Shows the trip specified by start and stop in a map
 * @author
 */
function MRShowTripInMap(locationFrom_id, locationTo_id) {
	var locationFrom = $('#' + locationFrom_id);
	var locationTo = $('#' + locationTo_id);

	if (locationFrom.val() > 0 && locationTo.val() > 0) {
		initializeMap();

		// add start and stop to stopoverlocations
		stopOverLocations = new Array();
		stopOverLocations.push(locationFrom.val());
		stopOverLocations.push(locationTo.val());

		// holds the waypoints
		var waypoints = new Array();

		// get start location data
		var ajaxCall = ajaxUrl + 'ajaxGetLocation=' + stopOverLocations[0];
		$.getJSON(ajaxCall, function(json) {
			// add start location to waypoints
			waypoints.push(new GLatLng(parseFloat(json['lat']), parseFloat(json['lng'])));

			ajaxCall = ajaxUrl + 'ajaxGetLocation=' + stopOverLocations[1];
			$.getJSON(ajaxCall, function(json) {
				// add start location to waypoints
				waypoints.push(new GLatLng(parseFloat(json['lat']), parseFloat(json['lng'])));

				// load waypoints
				directions.loadFromWaypoints(waypoints);
			});
		});
	}
}

function MROnGDirectionsLoad() {
	var distance = directions.getDistance();
	var duration = directions.getDuration();
	var polyline = directions.getPolyline();
	$("#showdistance").html(distance['html']);
	document.getElementById("distance").value = distance['meters'];
	$("#showduration").html(duration['html']);
	document.getElementById("duration").value = duration['seconds'];

	computeStartTime($('#starttime').get(), $("#destinationtime").get(), duration['seconds']);

	// build latlon-string of points to check for stopoverlocations
	// the number of verticies we group for stopoversearch
	// we may have max 25 waypoints
	var maxWaypoints = 20;
	var verticiesPerGroup = Math.ceil((polyline.getVertexCount()-1) / maxWaypoints); // each 30 vertices in the polyline
	var totalVertexCount = polyline.getVertexCount()-1;
	var groupCount = Math.ceil(totalVertexCount / verticiesPerGroup)-1;
	var latLngs = new Array();
	var ambit = Math.ceil(distance['meters'] / 1000 / maxWaypoints);
	// we need the bias, because we do not want to look to close to the start/destination
	var bias = verticiesPerGroup;
	//$('#debug').html($('#debug').html() + "VC: " + polyline.getVertexCount() + " / GC: " + groupCount + " / AMB: " + ambit + " / Bias: " + bias);
	for (v = 0;v < groupCount;v++) {
		// we only need the bias for the first location
		if (v > 0) bias = 0;
		// compute index of vertices, where to get the lat/lng from
		var index = Math.floor(Math.min(v * verticiesPerGroup + (verticiesPerGroup/2) + bias, totalVertexCount-verticiesPerGroup));
		//$('#debug').html($('#debug').html() + "<br/>Idx: " + index);
		var latLng = polyline.getVertex(index);
		// build array with lat,lon entries
		latLngs.push(latLng.y + "," + latLng.x);
		//$('#debug').html($('#debug').html() + "<br/>Idx: " + index + " - LL: " + latLng);
	}

	// build lat,lng|... string
	var latLngString = latLngs.join("|");

	MRGetStopoverLocations(latLngString, ambit);
}

function MRGetStopoverLocations (latLons, ambit) {
	var startLocationId = stopOverLocations[0];
	var destinationLocationId = stopOverLocations[stopOverLocations.length-1];

	var jsonCall = ajaxUrl + "ajaxGetStopoverLocations="+latLons+"&startLocationId="+startLocationId+"&destinationLocationId="+destinationLocationId+"&ambit="+ambit;

	var stopoverHTML = "";
	var isStopover = false;

	$.getJSON(jsonCall, function(stopoverLocations) {
		var so = new Array();
		for (var i = 0;i < stopoverLocations.length;i++) {
			isStopover = false;
			if (stopOverLocations.exists(stopoverLocations[i]["location_id"])) {
				isStopover = true;
				so.push(stopoverLocations[i]["location_id"]);
			}
			if (isStopover) {
				stopoverHTML += "<div class=\"smaller stopover stopoverselected\"><a href=\"javascript: removeStopover(" + stopoverLocations[i]["location_id"] + ");\">" + stopoverLocations[i]["name"] + "</a></div>";
			}
			else {
				stopoverHTML += "<div class=\"smaller stopover\"><a href=\"javascript: addStopover(" + stopoverLocations[i]["location_id"] + ");\">" + stopoverLocations[i]["name"] + "</a></div>";
			}
		}

		$('#stopoverLocationIds').val(so.join(','));
		$('#stopovers').html(stopoverHTML);
		$('#additionalstopoverdiv').show();
	});
}

function MRAddStopoverLocations(stopoverLocationIdsString) {
	if (stopoverLocationIdsString != "") {
		var ids = stopoverLocationIdsString.split(",");
		for (var l = 0;l < ids.length;l++) {
			if (l == (ids.length - 1)) {
				addStopover(ids[l]);
			}
			else {
				stopOverLocations.push(ids[l]);
			}
		}
	}
}

function MRGetEventsForLocation (location_id, selectedValue) {
	var locationField = $('#' + location_id); //dateField.form.elements[document.getElementById(location_id + '_select').name].value;
	var dateField = $('#date');

	if (locationField.val() > 0 && dateField.val() != '') {
		$('#' + location_id + '_events').hide();

		var jsonCall = ajaxUrl + "ajaxGetEventsForLocation="+locationField.val()+"&date="+dateField.val();
		$.getJSON(jsonCall, function(res) {
			if (isError(res)) {
				alert(res['message']);
			}
			else {
				// populate event dropdown
				var locationEvents = $("#" + location_id + "_eventid");
				if (selectedValue == undefined && locationEvents.val() >= 0) {
					selectedValue = locationEvents.val(); //options[locationEvents.selectedIndex].value;
				}
				if (res.length > 0) {
					var options = "<option value=''>" + getTranslation('no_event', 'trip') + "</option>";
					for (var e = 0;e < res.length;e++) {
						// check for selected value
						var selected = false;
						if (selectedValue != undefined && selectedValue == res[e]['event_id']) {
							selected = true;
						}
						options += "<option " + ((selected) ? 'selected' : '') + " value='" + res[e]['event_id'] + "'>" + res[e]['name'] + "</option>";
					}
					locationEvents.html(options);
					// show event-dropdown
					$('#' + location_id + '_events').show();
				}
			}
		});
	}
}

function MRGetMeetingpointsForLocation(location_id, selectedValue) {
	var locationField = $('#' + location_id);

	if (locationField.val() > 0) {
		var ajaxCall = ajaxUrl + 'ajaxGetMeetingpointsForLocation=' + locationField.val();
		$.getJSON(ajaxCall, function(res) {
			if (isError(res)) {
				alert(res['message']);
			}
			else {
				// populate event dropdown
				var locationMeetingpoints = $("#" + location_id + "_meetingpoint");
				if (res.length > 0) {
					var selected = false;
					var options = "<option value=''>" + getTranslation('pleaseSelect') + "</option>";
					for (var e = 0;e < res.length;e++) {
						selected = false;
						if (selectedValue == res[e]['meetingpoint_id'] || selectedValue == res[e]['name']) {
							selected = true;
						}
						options += "<option " + ((selected) ? 'selected' : '') + " value='" + res[e]['meetingpoint_id'] + "'>" + res[e]['name'] + "</option>";
					}
					locationMeetingpoints.html(options);
				}
				// show create new entry link
				$('#' + location_id + '_meetingpoint_newlink').show();
			}
		});
	}
}

function MRCreateNewMeetingpoint(location_id) {
	var locationField = $('#' + location_id);
	var locationFieldSearch = $('#' + location_id + '_search');
	var newMeetingpointNameField = $('#' + location_id + '_meetingpoint_new');
	var newMeetingpointZIPField = $('#' + location_id + '_meetingpoint_new_zip');
	var newMeetingpointAddressField = $('#' + location_id + '_meetingpoint_new_address');

	// try to geocode the address
	var zip = newMeetingpointZIPField.val();
	//var locationParser = /^[A-Z]{2}, [0-9\.]{0,5} ?([a-z\(\) -]+)/i;
	var locationParser = /^[A-Z]{2}, [0-9\.]{0,5} ?(.+)/i;
  	locationParser.exec(locationFieldSearch.val());
	// replace ( and )
	var city = RegExp.$1.replace(/\(|\)/g, "");
	var address = newMeetingpointAddressField.val();

	var locationDetail = (address == "") ? newMeetingpointNameField.val() : address;
	var locationToGeocode = zip + " " + city + " " + locationDetail;

	var coordinate = '';

	// get geocode
	var gcg = new GClientGeocoder();
	gcg.getLatLng(locationToGeocode, function (point) {
		if (point != null) {
			coordinate = "(" + point.y + "," + point.x + ")";
		}

		// update meetingpoint data
		var ajaxCall = ajaxUrl + 'ajaxCreateNewMeetingpoint=' + locationField.val() + '&name=' + newMeetingpointNameField.val() + '&zip=' + newMeetingpointZIPField.val() + '&address=' + newMeetingpointAddressField.val() + '&coordinate=' + coordinate;
		$.getJSON(encodeURI(ajaxCall), function(res) {
			if (isError(res)) {
				alert(res['message']);
				newMeetingpointNameField.focus();
			}
			else {
				// hide new field
				locationField = $('#tr' + location_id + '_meetingpoint_new').hide();
				// update dropdown
				MRGetMeetingpointsForLocation(location_id, newMeetingpointNameField.val());
				newMeetingpointNameField.val('');
				newMeetingpointZIPField.val('');
				newMeetingpointAddressField.val('');
				$("#" + location_id + "_meetingpoint").focus();
			}
			return false;
		});
		return false;
	});

	return false;
}

function MRUpdateMeetingpointCoordinates(form) {
	$('#adjust_coordinates').show();
	initializeMapById('meetingpointmap');
	var map = maps['meetingpointmap'];

	if (form.elements['coordinate'].value == '') {
		// get coordinate from address
		var gcg = new GClientGeocoder();

		// extract cityname form location name in format e.g.: DE, 761... Karlsruhe
//		var locationParser = /^[A-Z]{2}, [0-9\.]{0,5} ?([a-z\(\) -]+)/i;
		var locationParser = /, [0-9\.]* ?(.+)/i;
  		locationParser.exec(form.elements['locationSearch'].value);
		// replace ( and )
		var city = RegExp.$1.replace(/\(|\)/g, "");
		var locationDetail = (form.elements['address'].value == "") ? form.elements['name'].value : form.elements['address'].value;
		var locationToGeocode = form.elements['zip'].value + " " + city + " " + locationDetail;

		gcg.getLatLng(locationToGeocode,
			function (point) {
				if (point != null) {
					form.elements['coordinate'].value = "(" + point.y + "," + point.x + ")";
					MRUpdateMeetingpointCoordinates(form);
				}
				else {
					alert("Keine Koordinaten gefunden");
				}
			}
		);
	}
	else {
		var latLng = getLatLngFromCoordinates(form.elements['coordinate'].value);
		map.setCenter(new GLatLng(latLng[0], latLng[1]), 14);
		var marker = new GMarker(new GLatLng(latLng[0], latLng[1]), {draggable: true});
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		GEvent.addListener(marker, "dragend", function() {
			form.elements['coordinate'].value = "(" + marker.getPoint().lat() + "," + marker.getPoint().lng() + ")";
			map.setCenter(marker.getPoint());
		});

		map.addOverlay(marker);
		map.setMapType(G_HYBRID_MAP);
	}
}

function MRAskDeleteRecord (text) {
	return confirm("Soll der Datensatz mit der Kennung [ " + text + " ] gelöscht werden?");
}

function MRCheckWomenMenExclusive(field) {
	var checked = $(field).is(':checked');
	$("input[name='womenonly_01']").attr('checked', false);
	$("input[name='menonly_01']").attr('checked', false);
	$(field).attr('checked', checked);
}

function MRUnsetPrice() {
	if ($("input[name='askingprice_01']").is(':checked')) {
		$("input[name='price']").val('');
	}
}

function MRUnsetAskingPrice() {
	if ($("input[name='price']").val() != '') {
		$("input[name='askingprice_01']").attr('checked', false);
	}
}

function MRSelectEvent(event_id) {
	var eventField = $('#' + event_id);

	// get event record and prefill add-form
	var eventId = eventField.val();
	var ajaxCall = ajaxUrl + 'ajaxGetEvent=' + eventId;
	$.getJSON(encodeURI(ajaxCall), function(res) {
		$('#date').val(res['date_start']);
		$('#trip_location_to_search').val(res['location']);
		$('#trip_location_to').val(res['locationid']);

		MRGetMeetingpointsForLocation('trip_location_to');
		$('#trip_location_to_meetingpoint_newlink').show();
		MRShowTripInMap('trip_location_from', 'trip_location_to');
		MRGetEventsForLocation('trip_location_to', eventId);

		$('#trip_location_from_search').focus();
	});
}

function MRUpdateLocationCoordinates(form) {
	$('#adjust_coordinates').show();
	initializeMapById('locationmap');
	var map = maps['locationmap'];

	if (form.elements['coordinate'].value == '') {
		// get coordinate from address
		var gcg = new GClientGeocoder();

		// extract cityname form location name in format e.g.: 761... Karlsruhe
		//var locationParser = /^[0-9\.]{0,5} ?([a-z\(\) -]+)/i;
		var locationParser = /^[0-9\.]{0,5} ?(.+)/i;
  		locationParser.exec(form.elements['location'].value);
		// replace ( and )
		var city = RegExp.$1.replace(/\(|\)/g, "");
		//var locationDetail = (form.elements['address'].value == "") ? form.elements['name'].value : form.elements['address'].value;
		//var locationToGeocode = form.elements['zip'].value + " " + city + " " + locationDetail;
		var locationToGeocode = form.elements['zip'].value + " " + city;

		gcg.getLatLng(locationToGeocode,
			function (point) {
				if (point != null) {
					form.elements['coordinate'].value = "(" + point.y + "," + point.x + ")";
					MRUpdateLocationCoordinates(form);
				}
				else {
					alert("Keine Koordinaten gefunden");
				}
			}
		);
	}
	else {
		var latLng = getLatLngFromCoordinates(form.elements['coordinate'].value);
		map.setCenter(new GLatLng(latLng[0], latLng[1]), 14);
		var marker = new GMarker(new GLatLng(latLng[0], latLng[1]), {draggable: true});
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		GEvent.addListener(marker, "dragend", function() {
			form.elements['coordinate'].value = "(" + marker.getPoint().lat() + "," + marker.getPoint().lng() + ")";
			map.setCenter(marker.getPoint());
		});

		map.addOverlay(marker);
		map.setMapType(G_HYBRID_MAP);
	}
}

function MRUpdateEventCoordinates(form) {
	$('#adjust_coordinates').show();
	initializeMapById('locationmap');
	var map = maps['locationmap'];

	if (form.elements['coordinate'].value == '') {
		// get coordinate from address
		var gcg = new GClientGeocoder();

		// extract cityname form location name in format e.g.: DE, 761... Karlsruhe
		//var locationParser = /, [0-9\.]* ?([A-Za-zäöüß\(\) -]+)/i;
		var locationParser = /, [0-9\.]* ?(.+)/i;
  		locationParser.exec(form.elements['locationSearch'].value);
		// replace ( and )
		var city = RegExp.$1.replace(/\(|\)/g, "");
		//var locationDetail = (form.elements['address'].value == "") ? form.elements['name'].value : form.elements['address'].value;
		//var locationToGeocode = form.elements['zip'].value + " " + city + " " + locationDetail;
		var locationToGeocode = city + ", " + form.elements['locationdetail'].value;

		gcg.getLatLng(locationToGeocode,
			function (point) {
				if (point != null) {
					form.elements['coordinate'].value = "(" + point.y + "," + point.x + ")";
					MRUpdateEventCoordinates(form);
				}
				else {
					alert("Keine Koordinaten gefunden");
				}
			}
		);
	}
	else {
		var latLng = getLatLngFromCoordinates(form.elements['coordinate'].value);
		map.setCenter(new GLatLng(latLng[0], latLng[1]), 14);
		var marker = new GMarker(new GLatLng(latLng[0], latLng[1]), {draggable: true});
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		GEvent.addListener(marker, "dragend", function() {
			form.elements['coordinate'].value = "(" + marker.getPoint().lat() + "," + marker.getPoint().lng() + ")";
			map.setCenter(marker.getPoint());
		});

		map.addOverlay(marker);
		map.setMapType(G_HYBRID_MAP);
	}
}

function MRShowEventsInMap(mapId) {
	var eventmap = null;
	if ($('#'+mapId).is(":visible")) {
		$('#'+mapId).hide();
	}
	else {
		$('#'+mapId).show();
		if (eventmap == null) {
			initializeMapById(mapId);
			var eventmap = maps[mapId];
		}

		var iconOptions = {};
		iconOptions.width = 20;
		iconOptions.height = 20;
		iconOptions.primaryColor = "#0DC1E4";
		iconOptions.labelSize = 0;
		iconOptions.labelColor = "#ffffff";
		iconOptions.shape = "circle"; // roundrect

		// get all future events with coordinates and tripcount
		var ajaxCall = ajaxUrl + 'ajaxGetFutureEventsForMap=1';
		$.getJSON(encodeURI(ajaxCall), function(json) {
			if (!isError(json)) {
				for (var i = 0; i < json.length;i++) {
					iconOptions.label = json[i]['tripcount']; //json[i]['']
					var newIcon = MapIconMaker.createFlatIcon(iconOptions);
					// build marker HTML
					html = "<div>" + ((json[i]['date_end'] == null) ? Date.parse(json[i]['date_start']).toString("dd.MM.yyyy") : Date.parse(json[i]['date_start']).toString("dd.MM") + " - " + Date.parse(json[i]['date_end']).toString("dd.MM.yyyy")) + ", " + json[i]['location'] + "</div>";
					html += "<h2 class=\"black\" style=\"margin-top: 4px;\">" + json[i]['event'] + "</h2>";
					html += "<div class=\"vsstartlocation\">&raquo; <a href=\"" + rootUrl + "scripts/trip/trips2event.php?eid=" + json[i]['event_id'] +"\">Hier will ich hin</a></div>";

					var point = new GPoint(+json[i]['lng'], +json[i]['lat']);
					var marker = createMarker(point, newIcon, html);
					eventmap.addOverlay(marker);
				}
				eventmap.zoomToMarkers(5,2);
			}
		});
	}
}

function MRTranslate(element) {
	var id = element.id;
	var ajaxCall = ajaxUrl + 'ajaxGetTranslationForm=' + id;
	$.getJSON(encodeURI(ajaxCall), function(json) {
		overlib(json, STICKY);
		$('#toBeTranslated').html($('#'+id).html());
	});
}

function MRSubmitTranslation(form) {
	var trans = $(form).serialize();
	var ajaxCall = ajaxUrl + 'ajaxSubmitTranslation=1';
	$.post(ajaxCall, trans);
	cClick();
	return false;
}

function MRSetEnddate(endDate, startDateId) {
	if ($(endDate).val() == "") {
		$(endDate).val($('#'+startDateId).val());
	}
}

function MRCheckUsernameAvialable(usernameField) {
	var username = usernameField.value;
	var availableInfoFieldId = usernameField.name + '_available';

	$('#'+availableInfoFieldId).hide();
	if (username != undefined && username != "") {
		var ajaxCall = ajaxUrl + 'ajaxCheckUsernameAvialable=' + encodeURI(username);
		$.getJSON(encodeURI(ajaxCall), function(res) {
			$('#'+availableInfoFieldId).show(300);
			if (!isError(res)) {
				$('#'+availableInfoFieldId).html(res['message']);
				$('#'+availableInfoFieldId).removeClass('red');
				$('#'+availableInfoFieldId).addClass('green');
			}
			else {
				$('#'+availableInfoFieldId).html(res['message']);
				$('#'+availableInfoFieldId).removeClass('green');
				$('#'+availableInfoFieldId).addClass('red');
			}
		});
	}
}

function MRAdjustTextarea(element) {
	// get length
	var length = ($(element).val().length + 1) - (element.cols / 2);
	var maxChars = element.rows * element.cols;

	if (length > maxChars) {
		// adjust height
		element.rows = Math.ceil(+length/element.cols);
	}
	if (length < maxChars) {
		element.rows = Math.ceil(+length/element.cols);
	}
}

function MRShowTweets(twitterId, domId) {
	var url = "http://twitter.com/status/user_timeline/" + twitterId + ".json?count=5&callback=?";
	if ($('#'+domId).is(":visible")) {
		$('#'+domId).fadeOut(500).html('');
	}
	else {
		$.getJSON(url, function(data) { 
			$('#'+domId).html('').fadeIn(1000);
			$.each(data, function(i, item) {
				if (i == 0) {
					$('#'+domId).append("<br/><div style='float: left;'><a href='http://twitter.com/"+twitterId+"' target='_blank'><img style='margin: 0 10px 10px 0;width: 48px; height: 48px;' src='"+item.user["profile_image_url"]+"'/></a></div>");
				}
				$('#'+domId).append("<div style='float: left; width: 420px; margin-bottom: 5px; border-bottom: 1px dotted #e0e0e0;'>" + item.text.linkify() + " <span class='smaller nobr' style='color: #a0a0a0;'>("+relativeTime(item.created_at)+")</span></div>");  
			});
			$('#'+domId).append("<div style='clear: both;'>&raquo; <a href=\"javascript: MRShowTweets('"+twitterId+"', '"+domId+"');\">Tweets ausblenden</a></div>");
		});
	}
}

function MRShowTripsFromLocation(lat, lng, locationId, radius) {
	if (lat == null || lng == null) {
		//var latLng = $('#tripsFromLocation_coords').html().split(",");
		var latLng = $('#tripsFromLocation_coords').val().split(",");
		lat = latLng[0];
		lng = latLng[1];
	}
	$('.LOADERICON').show();
	$('#locationAwareBrowsing').hide();
	var ajaxCall = ajaxUrl + 'ajaxGetTripsFromLocation=1&lat='+lat+'&lng='+lng+'&lid='+locationId+'&r='+radius;
	$.getJSON(encodeURI(ajaxCall), function(res) {
		$('.tripsFromLocationRadius').html(radius);
		//$('#tripsFromLocation_coords').html(lat+","+lng);
		$('#tripsFromLocation_coords').val(lat+","+lng);
		$('#tripsFromLocationTable > tbody tr.dynitem').remove();
		$('#tripsFromLocationTable').hide();
		if (res.length > 0) {
			$('#tripsFromLocationTable').show();
			$('#tripsFromLocationNothingFound').hide();
		}
		else {
			$('#tripsFromLocationTable').hide();
			$('#tripsFromLocationNothingFound').show();
		}
		for (var r = 0;r < res.length;r++) {
			var dateArray = date2Array(res[r]['date']);
			if (res[r]['frequency'] == 'onetime') {
				var fDate = (new Date(dateArray[0], dateArray[1]-1, dateArray[2])).format("dd.mm.yy");
			}
			else {
				var fDate = res[r]['daysofweek'];
			}
			fDate += ", "+res[r]['time'].substring(0,5);
			var typeHtml = "<img src='"+rootUrl+"icons/"+res[r]['type']+".png' alt='Typ'/>";
			var whatforHtml = '';
			if (res[r]['whatfor_person'] != null) {
				whatforHtml += "<img src='"+rootUrl+"icons/"+res[r]['whatfor_person']+".png' alt='Wofür'/> ";
			}
			if (res[r]['whatfor_object'] != null) {
				whatforHtml += "<img src='"+rootUrl+"icons/"+res[r]['whatfor_object']+".png' alt='Wofür'/> ";
			}
			var frequencyHtml = "<img align='absmiddle' src='"+rootUrl+"icons/"+res[r]['frequency']+".png' alt='Frequenz'/>";
			var priceHtml = (res[r]['askingprice_01']=='t') ? "VHB" : (+res[r]['price']).numberFormat("0.00");
			var row = "<tr class='dynitem'><td class='center'><a href='"+rootUrl+"scripts/trip/tripdetail.php?tid="+res[r]['trip_id']+"&slid="+res[r]['startlocationid']+"&dlid="+res[r]['destlocationid']+"'>"+res[r]['trip_id']+"</a></td><td>"+typeHtml+"</td><td>"+whatforHtml+"</td><td>"+(res[r]['start'].replace(/^DE, [0-9\.]*/, ""))+"</td><td>"+(res[r]['dest'].replace(/^DE, [0-9\.]*/, ""))+"</td><td class='nobr'>"+frequencyHtml+" "+fDate+"</td><td class='rightalign lastcolumn'>"+priceHtml+"</td></tr>";
			$('#tripsFromLocationTable > tbody').append(row);
		}
		
		$('#tripsFromLocation').show();
		// initialize map
		var addMarker = false;
		if (maps['tripsFromLocation_map'] == undefined) {
			initializeMapById('tripsFromLocation_map');
			addMarker = true;
		}
		var map = maps['tripsFromLocation_map'];
		
		var marker = new GMarker(new GLatLng(lat, lng), {draggable: true});
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		GEvent.addListener(marker, "dragend", function() {
			var radius = $('.tripsFromLocationRadius:first').html();
			MRShowTripsFromLocation(marker.getPoint().lat(), marker.getPoint().lng(), '', radius);
		});
		if (addMarker) {
			map.addOverlay(marker);
			// add click-listener to map only once
			GEvent.addListener(map, "click", function(overlay, latLng) {
				var radius = $('.tripsFromLocationRadius:first').html();
				marker.setLatLng(latLng);
				MRShowTripsFromLocation(latLng.lat(), latLng.lng(), '', radius);
			});
		}
		map.setCenter(new GLatLng(lat, lng));
		
		$('.LOADERICON').hide();
	});
}

function MRShowTripsFromHere(radius) {
	$('#tripsFromLocation').hide();
	
	if ($('#tripsFromLocation').length) {
		// set default radius to 10
		if (radius == undefined) radius = 10;
		if (navigator.geolocation != undefined) {
			// get location from navigator.geolocation an show trips
			navigator.geolocation.getCurrentPosition(function(position) {
				MRShowTripsFromLocation(position.coords.latitude, position.coords.longitude, '', radius);
			}, function(error) { $('#locationAwareBrowsing').show(); });
		}
		// try to get location from google.loader.ClientLocation
		else if (google.loader.ClientLocation) {
			var loc = google.loader.ClientLocation;
			MRShowTripsFromLocation(loc.latitude, loc.longitude, '', radius);			
		}
	}
	else {
		if (navigator.geolocation == undefined) {
			$('#locationAwareBrowsing').show();
		}
	}
}

function MREmptyOnSameStartDate(endDate, startDateId) {
	if ($(endDate).val() == $('#'+startDateId).val()) {
		$(endDate).val('');
	}
}

function MRCheckRailway(railwayCheckbox) {
	if ($(railwayCheckbox).is(":checked")) {
		// hide trcarid and trnewcar
		$('#trcarid').hide();
		$('#trnewcar').hide();
	}
	else {
		var offerType = $('#'+railwayCheckbox.form.id+" input[name='type']:checked").val();
		if (offerType == 'offer') {
			$('#trcarid').show();
			$('#trnewcar').show();
			showNewCarFields(railwayCheckbox.form.carid);
		}
	}
}

function Location () {
	this.timeout = new Array();
	this.res = null;
	this.resultId = new Array();
	this.loaderId = new Array();
	this.field = new Array();
	this.idField = new Array();
	this.oldvalue = new Array();
	this.typeWaitTime = 800;
	this.minLength = 2;
	this.originalInput = new Array();
	
	this.search = function(field, obj, event) {
		// ISSUES
		// Dropdown - Getipptes nie ersetzen, most recent FETT und als 1. in Liste - per Klick auswahl
		// - zu langsames tippen bringt zu schnell einen ort und man kann immer noch reintippen
		var fieldId = field.attr("id");
		this.field[fieldId] = field;
		this.idField[fieldId] = $('#'+fieldId+"_id");
		
		var input = field.val();
		if (this.idField[fieldId].val() > 0) {
			// a location was set but the user types again
			// get last char from this input and past to original (= last) input
			var lastChar = field.val().charAt(field.val().length-1);
			if (event.keyCode <= 46) {
				// special treatment for BACKSPACE
				lastChar = '';
				if (event.keyCode == 8) {
					this.originalInput[fieldId] = this.originalInput[fieldId].substring(0, this.originalInput[fieldId].length-1);
				}
			}
			input = this.originalInput[fieldId] + lastChar;
			field.val(input);
//			this.idField[fieldId].val('');
		}
		// save new original (= current) input
		this.originalInput[fieldId] = field.val();
		
		this.resultId[fieldId] = field.attr("id")+"_result";
		this.loaderId[fieldId] = field.attr("id")+"_loader";
		
		// add loader image if not exists
		if ($('#'+this.loaderId[fieldId]).length == 0) {
			field.after("<img src=\""+rootUrl+"icons/smallloader.gif\" alt=\"+\" id=\""+this.loaderId[fieldId]+"\"/>");
		}
		
		// show loader image on minlength input size
		if (input.length > this.minLength) {
			$('#'+this.loaderId[fieldId]).show();
		}
		else {
			$('#'+this.loaderId[fieldId]).hide();
		}
		
		// add result-div if not exists
		if ($('#'+this.resultId[fieldId]).length > 0) {
			// empty result field
			$('#'+this.resultId[fieldId]).html("").hide();
		}
		else {
			// create result field if not exists
			field.after("<div class=\"sResults\" id=\""+this.resultId[fieldId]+"\"></div>");			
		}
		
		var ok = true;
		$('#julian').html(this.oldvalue[fieldId] + " => " + input + " :: " + ok);
		if (this.oldvalue[fieldId] == input) {
			// if oldvalue = current value => no update
			ok = false;
			$('#'+this.loaderId[fieldId]).hide();
		}
		this.oldvalue[fieldId] = input;
		
		if (this.timeout[fieldId] != undefined) {
			// currently a timeout is activ, kill it
			clearTimeout(this.timeout[fieldId]);
		}
		
		this.timeout = new Array();
		this.timeout[fieldId] = setTimeout(function() {
			this.timeout = undefined;
			
			// start if min input length and OK
			if (input.length > obj.minLength && ok) {
				//do it
				if (this.res == undefined) this.res = new Array();
				this.res[fieldId] = new Array();
				
				var ajaxCall = ajaxUrl + 'ajaxSearchLocation2=' + input;
				$.getJSON(encodeURI(ajaxCall), function(res) {
					var html = "";
					if (res.length == 0) {
						// nothing found
						html = "Es wurde keine Stadt gefunden";
					}
					else if (res.length == 1) {
						// found 1 city => do nothing, see below
//						html = "Du meinst sicher <b onclick=\"$('#"+obj.resultId+"').hide();\">" + res[0]['name'] + "</b>";
					}
					else {
//						html = "Du meinst sicher <b onclick=\"$('#"+obj.resultId+"').hide();\">" + res[0]['name'] + "</b>";
						html = "Oder doch eine dieser <a href=\"javascript: loc.showAlternativeLocations('"+fieldId+"');\">"+res.length+" Städte</a>?";
					}
					
					if (res.length > 0) {
						field.val(res[0]['name']);
						obj.idField[fieldId].val(res[0]['location_id']);
						if (obj.res == null) obj.res = new Array();
						obj.res[fieldId] = res;
						obj.confirm(field);
						obj.oldvalue[fieldId] = obj.originalInput[fieldId];
					}
					
					// hide loader
					$('#'+obj.loaderId[fieldId]).hide();
					
					if (html != "" && field.hasClass('focusedfield')) {
						$('#'+obj.resultId[fieldId]).html(html).show();
					}
					else {
						$('#'+obj.resultId[fieldId]).html(html).hide();
					}
					
				});
			}
		}, this.typeWaitTime);
	};
	
	this.search2 = function(field, obj, event) {
		// ISSUES
		// Dropdown - Getipptes nie ersetzen, most recent FETT und als 1. in Liste - per Klick auswahl
		// bei BLUR den Top-Wert setzen
		// - zu langsames tippen bringt zu schnell einen ort und man kann immer noch reintippen
		var fieldId = field.attr("id");
		this.field[fieldId] = field;
		this.idField[fieldId] = $('#'+fieldId+"_id");
		
		var input = field.val();
//		if (this.idField[fieldId].val() > 0) {
//			// a location was set but the user types again
//			// get last char from this input and past to original (= last) input
//			var lastChar = field.val().charAt(field.val().length-1);
//			if (event.keyCode <= 46) {
//				// special treatment for BACKSPACE
//				lastChar = '';
//				if (event.keyCode == 8) {
//					this.originalInput[fieldId] = this.originalInput[fieldId].substring(0, this.originalInput[fieldId].length-1);
//				}
//			}
//			input = this.originalInput[fieldId] + lastChar;
//			field.val(input);
////			this.idField[fieldId].val('');
//		}
		// save new original (= current) input
//		this.originalInput[fieldId] = field.val();
		
		this.resultId[fieldId] = field.attr("id")+"_result";
		this.loaderId[fieldId] = field.attr("id")+"_loader";
		
		// add loader image if not exists
		if ($('#'+this.loaderId[fieldId]).length == 0) {
			field.after("<img src=\""+rootUrl+"icons/smallloader.gif\" alt=\"+\" id=\""+this.loaderId[fieldId]+"\"/>");
		}
		
		var ok = true;
		if (event.keyCode >= 16 && event.keyCode <= 46) {
			ok = false;
		}

		// show loader image on minlength input size
		if (input.length > this.minLength && ok) {
			$('#'+this.loaderId[fieldId]).show();
		}
		else {
			$('#'+this.loaderId[fieldId]).hide();
		}
		
		// add result-div if not exists
		if ($('#'+this.resultId[fieldId]).length > 0) {
			// empty result field
			//$('#'+this.resultId[fieldId]).html("").hide();
		}
		else {
			// create result field if not exists
			field.after("<div class=\"sResults\" id=\""+this.resultId[fieldId]+"\"></div>");			
		}
		
//		$('#julian').html(this.oldvalue[fieldId] + " => " + input + " :: " + ok);
//		if (this.oldvalue[fieldId] == input) {
//			// if oldvalue = current value => no update
//			ok = false;
//			$('#'+this.loaderId[fieldId]).hide();
//		}
//		this.oldvalue[fieldId] = input;
		
		if (this.timeout[fieldId] != undefined) {
			// currently a timeout is activ, kill it
			clearTimeout(this.timeout[fieldId]);
		}
		
		this.timeout = new Array();
		this.timeout[fieldId] = setTimeout(function() {
			this.timeout = undefined;
			
			// start if min input length and OK
			if (input.length > obj.minLength && ok) {
				//do it
				if (this.res == undefined) this.res = new Array();
				this.res[fieldId] = new Array();
				
				var ajaxCall = ajaxUrl + 'ajaxSearchLocation2=' + input;
				$.getJSON(encodeURI(ajaxCall), function(res) {
//					var html = "";
//					if (res.length == 0) {
//						// nothing found
//						html = "Es wurde keine Stadt gefunden";
//					}
//					else if (res.length == 1) {
//						// found 1 city => do nothing, see below
////						html = "Du meinst sicher <b onclick=\"$('#"+obj.resultId+"').hide();\">" + res[0]['name'] + "</b>";
//					}
//					else {
////						html = "Du meinst sicher <b onclick=\"$('#"+obj.resultId+"').hide();\">" + res[0]['name'] + "</b>";
//						html = "Oder doch eine dieser <a href=\"javascript: loc.showAlternativeLocations('"+fieldId+"');\">"+res.length+" Städte</a>?";
//					}
					
					if (res.length > 0) {
//						field.val(res[0]['name']);
						obj.idField[fieldId].val(res[0]['location_id']);
						if (obj.res == null) obj.res = new Array();
						obj.res[fieldId] = res;
//						obj.confirm(field);
						//obj.oldvalue[fieldId] = obj.originalInput[fieldId];
						loc.showAlternativeLocations(fieldId);
					}
					
					// hide loader
					$('#'+obj.loaderId[fieldId]).hide();
					
//					if (html != "" && field.hasClass('focusedfield')) {
//						$('#'+obj.resultId[fieldId]).html(html).show();
//					}
//					else {
//						$('#'+obj.resultId[fieldId]).html(html).hide();
//					}
					
				});
			}
		}, this.typeWaitTime);
	};

	this.showAlternativeLocations = function (fieldId) {
		var html = "";
		for (var l = 0;l < this.res[fieldId].length;l++) {
			html += "<a class=\""+((l == 0) ? 'bold' : '')+"\" href=\"javascript: loc.setLocation("+this.res[fieldId][l]['location_id']+", '"+fieldId+"');\">"+this.res[fieldId][l]['name'].replace(this.field[fieldId].val(), "<b></b>")+"</a><br/>";
		}
		$('#'+this.resultId[fieldId]).html(html).show();
	};
	
	this.setLocation = function(locationId, fieldId) {
		for (var i = 0;i < this.res[fieldId].length;i++) {
			if (this.res[fieldId][i]['location_id'] == locationId) {
				this.field[fieldId].val(this.res[fieldId][i]['name']);
				this.idField[fieldId].val(this.res[fieldId][i]['location_id']);
				$('#'+this.resultId[fieldId]).html("").hide();
				this.confirm(this.field[fieldId]);
				break;
			}
		}
	};
	
	this.confirm = function (field) {
		field.addClass('confirm');
		setTimeout(function () {
			field.removeClass('confirm');
		}, 500);
	};
}

// old?
function disableCtrlModifer(evt) {
	var disabled = {a:0, c:0, x:0, v:0};
	var ctrlMod = (window.event)? window.event.ctrlKey : evt.ctrlKey;
	var key = (window.event)? window.event.keyCode : evt.which;
	key = String.fromCharCode(key).toLowerCase();
	return (ctrlMod && (key in disabled))? false : true;
}


function Mitreisen () {
	
	this.getLocationBasedEvents = function (count) {
		var ajaxCall = ajaxUrl + 'ajaxGetLocationBasedEvents=1';
		var loc = null;
		if (google.loader.ClientLocation) {
			loc = google.loader.ClientLocation;
		}
		if (loc != null) {
			var data = { count : count, lat : loc.latitude, lng : loc.longitude };
			$.getJSON(encodeURI(ajaxCall), data, function(res) {
				if (!isError(res)) {
					var events = '';
					for (var i = 0;i < res.length;i++) {
						events += "<div class='separator'><b><a href='"+rootUrl+"scripts/trip/trips2event.php?eid="+res[i]['event_id']+"'>"+res[i]['name']+"</a></b><br/>"+dateFormat(res[i]['date_start'], 'dd.mm')+" - "+dateFormat(res[i]['date_end'], 'dd.mm.yy')+", "+res[i]['location']+" ("+res[i]['radius']+" km)</div>";
					}
					$('#widget-locationbasedevents').html(events);
				}
			});
		}
	}
	
	this.getDashboard = function () {
		var ajaxCall = ajaxUrl + 'ajaxGetDashboard=1';
		var loc = null;
		if (google.loader.ClientLocation) {
			loc = google.loader.ClientLocation;
		}
		if (loc != null) {
			var data = { event : { count : 5 }, location : { count : 5 }, locationbased : { radius : 20 }, lat : loc.latitude, lng : loc.longitude };
			$.getJSON(encodeURI(ajaxCall), data, function(res) {
				if (!isError(res)) {
					// show events
					var events = '';
					for (var i = 0;i < res['event'].length;i++) {
						var date = dateFormat(new Date(res['event'][i]['date_start'].replace(/-/g, "/")), 'dd.mm.yyyy');
						if (res['event'][i]['date_end'] != null) {
							date = dateFormat(new Date(res['event'][i]['date_start'].replace(/-/g, "/")), 'dd.mm.yyyy')+" - "+dateFormat(new Date(res['event'][i]['date_end'].replace(/-/g, "/")), 'dd.mm.yy');
						}
						events += "<div class='separator'><b><a href='"+rootUrl+"scripts/trip/trips2event.php?eid="+res['event'][i]['event_id']+"'>"+res['event'][i]['name']+"</a></b><br/>"+date+", "+res['event'][i]['location']+" ("+res['event'][i]['radius']+" km)</div>";
					}
					$('#widget-locationbasedevents').html(events);
					
					// show locations
					var locations = '';
					for (var i = 0;i < res['location'].length;i++) {
						locations += "<div class='separator'><b>"+res['location'][i]['location']+"</b><br/>Entfernung Luftlinie ca. "+res['location'][i]['radius']+" km</div>";
					}
					$('#widget-newlocations').html(locations);
					
					// show location from current lat/lng
					if (res['locationFromLatLng'] != null) {
						$('.currentLocation').html(" (in der Nähe von "+res['locationFromLatLng']['name']+")");
					}
					// show locationbased trips
					var showTrips = false;
					$('#widget-locationbasedtrips').hide();
					$('#widget-locationbasedtrips-table > tbody tr.dynitem').remove();
					for (var r = 0;r < res['locationbased'].length;r++) {
						showTrips = true;
						var dateArray = date2Array(res['locationbased'][r]['date']);
						if (res['locationbased'][r]['frequency'] == 'onetime') {
							var fDate = (new Date(dateArray[0], dateArray[1]-1, dateArray[2])).format("dd.mm.yy");
						}
						else {
							var fDate = res['locationbased'][r]['daysofweek'];
						}
						fDate += ", "+res['locationbased'][r]['time'].substring(0,5);
						var typeHtml = "<img src='"+rootUrl+"icons/"+res['locationbased'][r]['type']+".png' alt='Typ'/>";
						var whatforHtml = '';
						if (res['locationbased'][r]['whatfor_person'] != null) {
							whatforHtml += "<img src='"+rootUrl+"icons/"+res['locationbased'][r]['whatfor_person']+".png' alt='Wofür'/> ";
						}
						if (res['locationbased'][r]['whatfor_object'] != null) {
							whatforHtml += "<img src='"+rootUrl+"icons/"+res['locationbased'][r]['whatfor_object']+".png' alt='Wofür'/> ";
						}
						var frequencyHtml = "<img align='absmiddle' src='"+rootUrl+"icons/"+res['locationbased'][r]['frequency']+".png' alt='Frequenz'/>";
						var priceHtml = (res['locationbased'][r]['askingprice_01']=='t') ? "VHB" : (+res['locationbased'][r]['price']).numberFormat("0.00");
						var row = "<tr class='dynitem'><td class='center'><a href='"+rootUrl+"scripts/trip/tripdetail.php?tid="+res['locationbased'][r]['trip_id']+"&slid="+res['locationbased'][r]['startlocationid']+"&dlid="+res['locationbased'][r]['destlocationid']+"'>Details</a></td><td>"+typeHtml+"</td><td>"+whatforHtml+"</td><td>"+(res['locationbased'][r]['start'].replace(/^DE, [0-9\.]*/, ""))+"</td><td>"+(res['locationbased'][r]['dest'].replace(/^DE, [0-9\.]*/, ""))+"</td><td class='nobr'>"+frequencyHtml+" "+fDate+"</td><td class='rightalign lastcolumn'>"+priceHtml+"</td></tr>";
						$('#widget-locationbasedtrips-table > tbody').append(row);
					}
					if (showTrips) {
						$('#widget-locationbasedtrips').show();
					}
					$.scrollTo(355);
				}
			});
		}
	}		
}

var mitreisen = new Mitreisen();