var ajaxCache = new Array();
var ajaxJSONCache = new Array();
var map = null;
var mapVS = null;
var maps = new Array();
var directions = null;
var stopOverLocations = new Array();

var searchRootUrl = /([a-z\/]+)scripts/;
searchRootUrl.exec(location.pathname);
var rootUrl = RegExp.$1;
var ajaxUrl = rootUrl + 'scripts/ajax_json.php?';

//var vsStartMarkers = new Array();
//var vsStopMarkers = new Array();
//var vsStartStopMarkers = new Array();
var vsStartStop = new Array();
var vsLocations = new Array();

// format overlib
ol_bgcolor = '#0CC1E3';
ol_fgcolor = '#ffffff';
ol_closecolor = '#ffffff';

function isError(error) {
	if (error != null && error['PEARError'] != undefined && error['PEARError'] == true) {
		return true;
	}
	return false;
}

Array.prototype.remove = function(s) {
	for (var i = 0;i < this.length;i++) {
		if (s == this[i]) this.splice(i, 1);
	}
}

Array.prototype.exists = function(s) {
	var exists = false;
	for (var i = 0;i < this.length;i++) {
		if (s == this[i]) exists = true;
	}
	return exists;
}

function sprintf() {
	if(sprintf.arguments.length < 2 ) {
		return;
	}

	var data = sprintf.arguments[ 0 ];
	for (var k = 1;k < sprintf.arguments.length; ++k ) {
		switch( typeof( sprintf.arguments[ k ] ) ) {
			case 'string':
				data = data.replace( /%s/, sprintf.arguments[ k ] );
				break;
			case 'number':
				data = data.replace( /%d/, sprintf.arguments[ k ] );
				break;
			case 'boolean':
				data = data.replace( /%b/, sprintf.arguments[ k ] ? 'true' : 'false' );
				break;
			default:
				/// function | object | undefined
				break;
		}
	}
	return(data);
}
if (!String.sprintf ) {
	String.sprintf = sprintf;
}

var orderByItems = new Array();
var selectedCountryIds = new Array();

function new_window (file) {
	win = window.open(file, "NewWindow","width=600,height=500,scrollbars=yes,resizable=no,screenX=100,screenY=50");
}

function ask(id, replacement) {
	var translation = getTranslation(id);
	if (replacement != 'undefined') {
		translation = String.sprintf(translation, replacement);
	}
	return confirm(translation);
}

function askDelete (text, id) {
	return confirm("Soll " + text + " gelöscht werden?");
}

/**
 * Adds an order column to the order request
 * New since [jug, 21.09.2006]
 */
function addOrder(sourceElement) {
	var thElement = sourceElement;
	while (thElement.nodeName != "TH") {
		thElement = thElement.parentNode;
	}

	var field = thElement.id;

	// parse image-src
	var image = sourceElement;
	var res = image.src.match(/^(.*)\/(sort-)(asc|desc)-?(selected|)\.(png|gif)/i);
	var dir = res[3];

	// check if the orderby field is selected
	if (res[4] == 'selected') {
		// unselect this field
		// and remove it from the order-by-string
		image.src = res[1] + "/" + res[2] + res[3] + "." + res[5];
		addOrderByItem(field, "");
	}
	else {
		// select the current field
		// unselect the other (asc|desc) image
		image.src = res[1] + "/" + res[2] + res[3] + "-selected." + res[5];
		var inverse = 'asc';
		if (res[3] == 'asc') {
			inverse = 'desc';
		}
		var inversesort = 'sort-'+inverse;
		var parentNode = image.parentNode;
		parentNode.getElementsByTagName('img')[inversesort].setAttribute('src', res[1] + "/" + res[2] + inverse + "." + res[5]);
		addOrderByItem(field, dir);
	}
}

/**
 * Adds an item to the above defined oderByItems-Array, which holds all the
 * items (field) including their sort-direction. the position is the position
 * used for the SQL-oderby clause.
 *
 * Format: <field1>|<dir1>,<field2>|<dir2>,...
 */
function addOrderByItem (field, dir) {
	var inverseOrder = new Array();
	inverseOrder['asc'] = 'desc';
	inverseOrder['desc'] = 'asc';
	var found = false;
	for (var nr = 0;nr < orderByItems.length;nr++) {
		itemChunks = orderByItems[nr].split("|");
		if (itemChunks[0] == field) {
			// found field
			if (dir == "") {
				// dir is empty, so set this element to idle
				orderByItems[nr] = field + "|-";
			}
			else {
				if (itemChunks[1] == "-") {
					itemChunks[1] = inverseOrder[dir];
				}
				orderByItems[nr] = field + "|" + inverseOrder[itemChunks[1]];
			}
			found = true;
		}
	}

	if (!found) {
		orderByItems.push(field + "|" + dir);
	}
}


/**
 * Finalizes an order request
 * New since [jug, 21.09.2006]
 */
function finalizeOrder (sourceElement) {
	var chunks = document.location.pathname.match(/([a-z0-9\/]*\.php)/i);
	var baseUrl = chunks[1] + "?orderby=";

	var thElement = sourceElement;
	var image = sourceElement;
	while (thElement.nodeName != "TH") {
		thElement = thElement.parentNode;
	}

	var field = thElement.id;

	addOrder(sourceElement);

	var string = "";
	for (var j = 0;j < orderByItems.length;j++) {
		chunks = orderByItems[j].split("|");
		if (chunks[1] != '-') {
			// only use non-empty = not a - fields
			string += ((string == "") ? "" : ",") + orderByItems[j];
		}
	}

	// reload page with orderby=... as get parameter
	window.location.href = baseUrl + string;
}

/**
 * selects the orders for the selected columns
 * New since [jug, 21.09.2006]
 */
function selectOrder (selectedColumns) {
	var bereich = document.getElementById("results");
	var ths = bereich.getElementsByTagName("th");

	var columns = selectedColumns.split(",");

	for (var h = 0;h < ths.length;h++) {
		for (var c = 0;c < columns.length;c++) {
			var chunks = columns[c].split("|");
			if (ths[h].id == chunks[0]) {
				markColumnOrder(ths[h], chunks[1], c+1);
			}
		}
	}
}

/**
 * New since [jug, 21.09.2006]
 */
function markColumnOrder (parentElement, dir, position) {
	if (dir) {
		var image = parentElement.getElementsByTagName("img")["sort-" + dir];
		var res = image.src.match(/^(.*)\/(sort-)(asc|desc)-?(selected|)\.(png|gif)/i);
		image.src = res[1] + "/" + res[2] + res[3] + "-selected." + res[5];
	}
}

function getTranslation (id, pageId) {
	var jsonCall = "ajaxGetTranslation="+id;
	if (pageId != undefined) {
		jsonCall += "&pageId="+pageId;
	}
	return ajaxJSONCall(jsonCall);
}

function ajaxCall(call) {
	if (ajaxCache[call] == undefined) {
		var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
		var baseUrl = chunks[1] + "ajax.php?";
		var callUrl = baseUrl + call;
		ajaxCache[call] = decodeURI(HTML_AJAX.grab(callUrl));
	}

	return ajaxCache[call];
}

function ajaxJSONCall(call, noCache) {
	if (ajaxJSONCache[call] == undefined || noCache == true) {
		var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
		var baseUrl = chunks[1] + "ajax_json.php?";
		var callUrl = baseUrl + call;
		ajaxJSONCache[call] = eval("(" + HTML_AJAX.grab(callUrl) + ")");
	}
	return ajaxJSONCache[call];
}

function ajaxUpdateCountriesForContinent(selectContinentId, selectCountryId, markSelectedCountries, hideSelectItem, deliveryOnly) {
	if (typeof selectContinentId == "string") {
		var call = "ajaxUpdateCountriesForContinent="+selectContinentId;
	}
	else {
		var call = "ajaxUpdateCountriesForContinent="+selectContinentId.value;
	}
	if (deliveryOnly == true) {
		call = call + "&deliveryonly=1";
	}

	if (selectContinentId == undefined || selectContinentId == "") {
		// reset selectedCountryIds
		selectedCountryIds = new Array();
		selectCountryId.form.selectedCountryIds.value = "";
	}

	var emptyText = selectCountryId.options[0].text;
	var preselectedCountryId = selectCountryId.value;
	res = ajaxCall(call);

	if (res != "") {
		selectCountryId.options.length = 0;
		opts = res.split("|");
		var itemCount = 0;
		if (!hideSelectItem) {
			selectCountryId.options[itemCount] = new Option(emptyText, "", false, false);
			itemCount++;
		}
		for (var o = 0;o < opts.length;o++) {
			chunks = opts[o].split(":");
			var selected = false;
			if ((markSelectedCountries && selectedCountryIds.exists(chunks[0])) || (chunks[0] == preselectedCountryId)) {
				selected = true;
			}
			selectCountryId.options[o+itemCount] = new Option(chunks[1], chunks[0], selected, selected);
		}
	}
	else {
		selectCountryId.options.length = 0;
		selectCountryId.options[0] = new Option(getTranslation("nothingFound"), "", false, false);
	}
}

function ajaxUpdateDeliveryCountriesForContinent(selectContinentId, selectCountryId, markSelectedCountries, hideSelectItem) {
	ajaxUpdateCountriesForContinent(selectContinentId, selectCountryId, markSelectedCountries, hideSelectItem, true);
}

function ajaxUpdateCountriesForEpochFilter (selectEpochFilterId, selectCountryId, markSelectedCountries, hideSelectItem) {
	if (typeof selectEpochFilterId == "string") {
		var call = "ajaxUpdateCountriesForEpochFilter="+selectEpochFilterId;
	}
	else {
		var call = "ajaxUpdateCountriesForEpochFilter="+selectEpochFilterId.value;
	}

	var emptyText = selectCountryId.options[0].text;
	var preselectedCountryId = selectCountryId.value;
	res = ajaxCall(call);

	if (res != "") {
		selectCountryId.options.length = 0;
		opts = res.split("|");
		var itemCount = 0;
		if (!hideSelectItem) {
			selectCountryId.options[itemCount] = new Option(emptyText, "", false, false);
			itemCount++;
		}
		for (var o = 0;o < opts.length;o++) {
			chunks = opts[o].split(":");
			var selected = false;
			if ((markSelectedCountries && selectedCountryIds.exists(chunks[0])) || (chunks[0] == preselectedCountryId)) {
				selected = true;
			}
			selectCountryId.options[o+itemCount] = new Option(chunks[1], chunks[0], selected, selected);
		}
	}
	else {
		selectCountryId.options.length = 0;
		selectCountryId.options[0] = new Option(getTranslation("nothingFound"), "", false, false);
	}
}

function showLargeImage (oid, position, type) {
	var call = "ajaxGetLargeImage="+oid+"&position="+position+"&ot="+type;
	res = ajaxCall(call);
	if (res.match(/-[0-9]+/)) {
		alert(getTranslation(res, 'offer'));
	}
	else {
		var image = document.getElementById("image"+oid);
		// split path of res = new relative image path. [0] holds the first pathname
		var resChunks = res.split("/");
		// build dynamic regexp which get all before the first path
		var regExp = new RegExp("^([a-z0-9\.:\/]*\/)" + resChunks[0]);
		var chunks = image.src.match(regExp);
		image.src = chunks[1] + res;
	}
}

function popup (key) {
	var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
	var baseUrl = chunks[1] + "popup.php?key="+key;
	win = window.open(baseUrl, "popup", "width=600, height=500, scrollbars=yes, resizable=no");
}

// uses the global Array selectedCountryIds for remembering the selected country ids
function markCountryAsSelected (countryListElement, selectedCountryListElement) {
	// read selected items from selectedCountryListElement
	if (selectedCountryListElement.value != "") {
		selectedCountryIds = selectedCountryListElement.value.split(",");
	}
	for (var o = 0;o < countryListElement.options.length;o++) {
		if (countryListElement.options[o].value > 0) {
			selectedCountryIds.remove(countryListElement.options[o].value);
			if (countryListElement.options[o].selected) {
				selectedCountryIds.push(countryListElement.options[o].value);
			}
		}
	}
	selectedCountryListElement.value = selectedCountryIds.join(",");
}

function selectAllItems (selectElement, deselectOnAll) {
	var selectedItems = 0;
	for (var o = 0;o < selectElement.options.length;o++) {
		selectElement.options[o].selected = true;
		selectedItems++;
	}

	if (deselectOnAll && selectedItems == selectElement.options.length) {
		for (var o = 0;o < selectElement.options.length;o++) {
			selectElement.options[o].selected = false;
		}
	}
}

function checkQuantityZero (quantityElement) {
	if (quantityElement.value == 0) {
		return confirm(getTranslation("js_text_checkQuantityZero"));
	}
	return true;
}

function setHover (row) {
	if (row.className == 'rowhover') {
		row.className = row.id;
	} else {
		row.id = row.className;
		row.className = 'rowhover';
	}
}

function setClickHover (row) {
	if (row.className == 'rowclickhover') {
		row.className = row.id;
	} else {
		row.id = row.className;
		row.className = 'rowclickhover';
	}
}

function round (number, decimals) {
    return (Math.round(number * Math.pow(10, decimals))) / Math.pow(10, decimals);
}

function cleanQueryString(clean) {
	var url = document.location.pathname;

	if (document.location.search != "") {
		// extract filtername and filtervalue params
		var newParams = "";
		var expression = new RegExp(clean);
		var params = document.location.search.substring(1).split("&");
		for (var c = 0;c < params.length;c++) {
			if (params[c].match(expression) == null) {
				newParams += params[c] + "&";
			}
		}
		url += "?" + newParams;
	}
	else {
		url += "?";
	}

	return url;
}

function setFilter(filtername, filtervalue) {
	var url = cleanQueryString("filtername|filtervalue");

	redirectTo = url + "filtername=" + filtername + "&filtervalue=" + escape(filtervalue);
	window.location.href = redirectTo;
}

function setExtendedFilter (filtername, filtervalue) {
	if (filtervalue.nodeName == 'TD') {
		filtervalue = filtervalue.innerHTML;
	}
	setInputFilter(filtername, filtervalue);
}

function setInputFilter(filtername, filtervalue) {
	chunks = filtervalue.split("::");
	var op = " = ";
	// check if an operator was specified, default is "="
	if (chunks.length == 2) {
		op = " " + chunks[0] + " ";
		filtervalue = chunks[1];
	}

	operator = window.prompt("Bitte geben Sie die Bedingung für die Spalte " + filtername.toUpperCase() + " im SQL-Format ein. Mögliche Operatoren: <, >, =, <=, >=, !=, IN, NOT IN, (NOT )LIKE, (NOT )ILIKE, (NOT )BETWEEN, IS\nWeitere Beispiele finden sich in der Hilfe.", filtername + op + filtervalue);
	// user pressed ESC/cancel
	if (operator == null) {
		return;
	}
	whereMatch = /^([0-9a-z_\.]+)\s*(<|>|=|<=|>=|!=|IN|NOT IN|LIKE|ILIKE|NOT BETWEEN|BETWEEN|IS|NOT ILIKE|NOT LIKE)\s*([:a-z0-9\s,'"\(\)%_\*\.\-\\/]+)$/i;
	result = whereMatch.exec(operator);
	if (result == null) {
		alert("Der Filter wurde nicht erkannt!");
	}
	else {
		if (result != null && result[1] == filtername) {
			filtervalue = result[2] + "::" + result[3].replace(/\*/g, "%").replace(/\"/g, "'");
		}
		if (operator != null && result[3].match(/^\s*$/) == null) {
			setFilter(filtername, filtervalue);
		}
	}
}

function editInputFilter(filtername, filtervalue) {
	chunks = filtervalue.split("::");
	operator = chunks[0];
	filtervalue = chunks[1];
	filter = window.prompt("Bitte geben Sie die neue Filterbedingung für den folgenden Filter ein:\n" + filtername + " " + operator.toUpperCase() + " " + filtervalue, filtername + " " + operator + " " + filtervalue);
	whereMatch = /^([0-9a-z_\.]+)\s*(<|>|=|<=|>=|!=|IN|NOT IN|LIKE|ILIKE|NOT BETWEEN|BETWEEN|IS|NOT ILIKE|NOT LIKE)\s*([:a-z0-9\s,'"\(\)%_\*\.\-\\/]+)$/i;
	result = whereMatch.exec(filter);
	if (result != null && result[1] == filtername) {
		filtervalue = result[2] + "::" + result[3].replace(/\*/g, "%").replace(/\"/g, "'");
	}
	if (filter != null && result[3].match(/^\s*$/) == null) {
		setFilter(filtername, filtervalue);
	}
}

function removeFilter (filtername) {
	var url = cleanQueryString("filtername|filtervalue");

	window.location.href = url + "filtername=" + filtername;
}

function updateCharsLeftCount (maxCharCount, textfieldElement, charcountNode) {
	var textfieldContent = textfieldElement.value;
	var charsLeft = maxCharCount - textfieldContent.length;

	if (charsLeft <= 0) {
		textfieldElement.value = textfieldContent.substr(0, maxCharCount);
		charsLeft = 0;
	}
	charcountNode.innerHTML = charsLeft;
}

function ajaxAddToSelectedTraderSearches (checkbox) {
	var traderSearchlistId = checkbox.value;
	var selectedItems = parseInt(document.getElementById('selectedItems').innerHTML);
	if (checkbox.checked == true) {
		// remove from selected searches
		var call = "ajaxAddToSelectedTraderSearches="+traderSearchlistId;
		document.getElementById('selectedItems').innerHTML = selectedItems + 1;
	} else {
		// add from selected searches
		var call = "ajaxRemoveFromSelectedTraderSearches="+traderSearchlistId;
		document.getElementById('selectedItems').innerHTML = selectedItems - 1;
	}
	res = ajaxCall(call);
}

function getOffer(offerId, offerType) {
	var call = "ajaxGetOffer="+offerId+"&offerType="+offerType;
	return ajaxJSONCall(call);
}

function showPostage(offerId, offerType) {
	var res = getOffer(offerId, offerType);
	var packagingpostage = res['packagingpostage'];
	overlib(packagingpostage, CAPTION, " " + getTranslation("label_packagingpostage") + " ID [ " + offerId + " ]", WRAP, CELLPAD, 5, HAUTO, VAUTO);
}

function getQuantityScale(offerId, offerType) {
	var call = "ajaxGetQuantityScale="+offerId+"&offerType="+offerType;
	return ajaxJSONCall(call);
}


function showQuantityScale (offerId, offerType) {
	// currently we only have a quantityScale for traderoffers
	offerType = "traderoffer";
	var offerData = getOffer(offerId, offerType);
	var unitPrice = offerData["price"];
	var quantityScale = "<table class=list2><tr><th>" + getTranslation("label_quantityfrom") + "</th><th>" + getTranslation("label_unitpricenet") + "</th><tr>";
	quantityScale += "<tr><td class=center>1</td><td class=\"rightalign lastcolumn nobr\">&euro; " + (new Number(unitPrice)).numberFormat("#,#.00") + "</td></tr>";
	var res = getQuantityScale(offerId, offerType);
	for (var i = 0;i < res.length;i++) {
		quantityScale += "<tr><td class=center>" + (new Number(res[i]["quantity"])).numberFormat("#,#") + "</td><td class=\"rightalign lastcolumn nobr\">&euro; " + (new Number(res[i]["price"])).numberFormat("#,#.00") + "</td></tr>";
	}
	quantityScale += "</table>";

	overlib(quantityScale, CAPTION, " " + getTranslation("label_quantityscale") + " ID [ " + offerId + " ]", WRAP, CELLPAD, 5, HAUTO, VAUTO);
}

function setAccountholder (accountholderField) {
	if (accountholderField.value == "") {
		accountholderField.value = accountholderField.form.firstname.value + " " + accountholderField.form.lastname.value;
	}
}

function getRatingCommentTemplate(ratingId) {
	var commentForm = document.getElementById("r_" + ratingId);
	if (commentForm.innerHTML == "") {
		var call = "ajaxGetRatingCommentTemplate";
		template = ajaxJSONCall(call);
		template = template.replace(/%RID%/i, ratingId);
		commentForm.innerHTML = template;
	} else {
		commentForm.innerHTML = "";
	}
}

function addQuantityScaleRecord (tbl) {
	var lastRow = tbl.rows.length;
	// if there's no header row in the table, then iteration = lastRow + 1
	var iteration = lastRow;
	var row = tbl.insertRow(lastRow);

	// quantity cell
	var quantityCell = row.insertCell(0);
	var quantity = document.createElement('input');
	quantity.type = 'text';
	quantity.name = 'quantityscale[' + (iteration-1) + '][quantity]';
	quantity.value = '';
	quantity.size = 8;
	quantityCell.appendChild(quantity);

	// price cell
	var priceCell = row.insertCell(1);
	var price = document.createElement('input');
	price.type = 'text';
	price.name = 'quantityscale[' + (iteration-1) + '][price]';
	price.value = '';
	price.size = 10;
	priceCell.appendChild(price);
}

function sortColumn (thElement) {
	var orderBy = thElement.id;
	var orderByDir = "ASC";
	var res = document.location.search.match(/orderBy=[a-z0-9_\.]+\|(ASC|DESC)/i);
	if (res != undefined && res[1] != undefined) {
		orderByDir = (res[1].toLowerCase() == 'asc') ? 'DESC' : 'ASC';
	}
	var orderByLocation = document.location.pathname + ((document.location.search == "") ? "?" : document.location.search+"&");
	if (document.location.search != "") {
		orderByLocation = cleanQueryString("orderBy");
	}
	orderByLocation += "orderBy="+orderBy+"|"+orderByDir;
	document.location.href = orderByLocation;
}

function showSort(orderBy) {
	var chunks = orderBy.split("|");
	if (orderBy != "" && chunks != undefined && chunks[0] != undefined && chunks[1] != undefined) {
		var dirSign = (chunks[1].toLowerCase() == "desc") ? "&darr;" : "&uarr;";
		document.getElementById(chunks[0]).innerHTML += " " + dirSign;
		document.getElementById(chunks[0]).className += " nobr";
	}
}

function getInvoice (invoiceId) {
	var call = "ajaxGetInvoice="+invoiceId;
	return ajaxJSONCall(call);
}

function invoiceOptions(invoiceId) {
	var invoiceData = getInvoice(invoiceId);
	var optionHTML = "";

	if (invoiceData['payed_01'] == 'f') {
		optionHTML += "<a href=\"javascript: markInvoiceAsPayed(" + invoiceId + ");\">... als bezahlt markieren</a><br/>";
	}
	if (invoiceData['userhistoryRecord']['paperbill_01'] == 't' && invoiceData['paperbill_01'] == 'f') {
		optionHTML += "<a href=\"javascript: markInvoiceAsPaperbillSent(" + invoiceId + ");\">... als per Post verschickt markieren</a><br/>";
	}
	if (invoiceData['accounted_01'] == 'f') {
		optionHTML += "<a href=\"javascript: addCreditToInvoice(" + invoiceId + ");\">... Wertgutschrift</a><br/>";
	}

	if (optionHTML == "") {
		alert("Keine weiteren Optionen");
	}
	else {
		overlib(optionHTML, CAPTION, "Rechnungsoptionen [ " + invoiceId + " ]", WRAP, CELLPAD, 5, HAUTO, VAUTO, STICKY);
	}
}

function markInvoiceAsPayed (invoiceId) {
	var url = document.location.pathname + ((document.location.search != "") ? document.location.search + "&" : "?");
	document.location.href = url + "btn_markInvoiceAsPayed=" + invoiceId;
}

function markInvoiceAsPaperbillSent (invoiceId) {
	var url = document.location.pathname + ((document.location.search != "") ? document.location.search + "&" : "?");
	document.location.href = url + "btn_markInvoiceAsPaperbillSent=" + invoiceId;
}

function addCreditToInvoice(invoiceId) {
	var res = prompt("Wertgutschrift Rechnung [ " + invoiceId + " ]", 0);
	if (res != null) {
		res = res.replace(",", ".");
		if (res > 0) {
			var call = "ajaxAddCreditToInvoice="+invoiceId+"&amount=" + res;
			var res = ajaxJSONCall(call);
			var chunks = res.split("|");
			if (chunks[0] < 0) {
				alert(getTranslation(chunks[0], chunks[1]));
			}
			else {
				alert(res);
				document.location.href = document.location.href;
			}
		}
	}
}

function emptyFields(form, fieldString) {
	var fields = fieldString.split("|");
	for (var i = 0;i < fields.length;i++) {
		form.elements[fields[i]].value = '';
	}
}

function emptyFieldById(id) {
	document.getElementById(id).value = '';
}

function emptyField(field) {
	field.value = '';
}

function hideSearchresults (fieldname) {
	document.getElementById(fieldname + "_searchresult").innerHTML = "";
 	document.getElementById(fieldname + "_searchresult").style.border = "0px";
 	document.getElementById(fieldname + "_searchresult").style.display = "none";
}

function createSearchResultDiv(fieldname) {
	if (document.getElementById(fieldname + "_searchresult") == null) {
		var resultDiv = document.createElement("div");
		resultDiv.setAttribute("id", fieldname + "_searchresult");
		var resultClass = document.createAttribute("class");
		resultClass.nodeValue = "searchResultDiv";
		resultDiv.setAttributeNode(resultClass);

		if (document.getElementById(fieldname).nodeName != "div") {
			// this node is NOT a DIV-element, append resultDiv to parentNode (this must be a DIV)
			var divNode = document.getElementById(fieldname).parentNode.parentNode;
			// we need nextSibling twice, because there is a textnode, too
			divNode.insertBefore(resultDiv, document.getElementById(fieldname).parentNode.nextSibling.nextSibling)
		}
		else {
			// this node is a DIV, appendChild to this div
			document.getElementById(fieldname).appendChild(resultDiv);
		}
	}
}

function searchStartLocations(inputField) {
	var fieldname = inputField.name;
	createSearchResultDiv(fieldname);
	if (inputField.value.length >= 3 && inputField.value.search(/^[A-Z]{2},/) == -1) {
		var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
		var baseUrl = chunks[1] + "ajax_json.php?";
		var callUrl = baseUrl + "ajaxSearchStartLocations=" + encodeURI(inputField.value);
		var showLocations = new ShowLocations(fieldname);
		HTML_AJAX.grab(callUrl, showLocations.invoke);
	}
	else {
		document.getElementById(fieldname + "_searchresult").innerHTML = "";
 		document.getElementById(fieldname + "_searchresult").style.border = "0px";
 		document.getElementById(fieldname + "_searchresult").style.display = "none";
 		document.getElementById(fieldname + "_select").value = "";
 		return;
	}
}

function searchDestinationLocations(inputField) {
	var fieldname = inputField.name;
	createSearchResultDiv(fieldname);
	if (inputField.value.length >= 3 && inputField.value.search(/^[A-Z]{2},/) == -1) {
		startLocationId = document.getElementById('search_location_from_select').value;
		var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
		var baseUrl = chunks[1] + "ajax_json.php?";
		var callUrl = baseUrl + "ajaxSearchDestinationLocations=" + encodeURI(inputField.value) + "&startLocationId=" + startLocationId;

		var showLocations = new ShowLocations(fieldname);
		HTML_AJAX.grab(callUrl, showLocations.invoke);
	}
	else {
		document.getElementById(fieldname + "_searchresult").innerHTML = "";
 		document.getElementById(fieldname + "_searchresult").style.border = "0px";
 		document.getElementById(fieldname + "_searchresult").style.display = "none";
 		document.getElementById(fieldname + "_select").value = "";
 		return;
	}
}

function searchLocation (inputField, showInMap) {
	var fieldname = inputField.name;
	createSearchResultDiv(fieldname);
	if (inputField.value.length > 2) {
		var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
		var baseUrl = chunks[1] + "ajax_json.php?";
		var callUrl = baseUrl + "ajaxSearchLocation=" + encodeURI(inputField.value);

		var showLocations = new ShowLocations(fieldname, showInMap);
		HTML_AJAX.grab(callUrl, showLocations.invoke);
	}
	else {
		document.getElementById(fieldname + "_searchresult").innerHTML = "";
 		document.getElementById(fieldname + "_searchresult").style.border = "0px";
 		document.getElementById(fieldname + "_searchresult").style.display = "none";
 		document.getElementById(fieldname + "_select").value = "";
 		if (document.getElementById(fieldname + "_radius") != undefined) {
 			document.getElementById(fieldname + "_radius").style.display = "none";
 		}
 		return;
	}
}

function ShowLocations (fieldname, showInMap) {
	this.fieldname = fieldname;
	var me = this;
	var searchResultDivId = me.fieldname + "_searchresult";

	this.invoke = function (results) {
		if (document.getElementById(fieldname).value.search(/^[a-z]{2},/i) == 0) {return;}

		results = eval("(" + results + ")");
		var cityCount = results.length;
		var locations = "<div class=\"caption\"><div class=\"floatleft\">" + cityCount + " Städte gefunden</div> <div class=\"floatright\"><a href=\"javascript: hideSearchresults('" + fieldname + "');\"> " + ol_close + "</a></div><div class=\"clearfloat\"></div></div><div style=\"padding: 2px; overflow: auto; height: 100px;\">";
		for (var i = 0;i < results.length;i++) {
			locations += "<div style=\"padding: 1px;\" class=\"" + ((i % 2 == 0) ? 'shadow' : '') + "\"><a href=\"javascript: setLocation(" + results[i]["location_id"] + ", '" + me.fieldname + "', " + showInMap + ");\">" + results[i]["name"] + "</a></div>";
		}
		if (results.length == 0) {
			locations += "<div class=\"bold\">Es wurden keine Städte gefunden. Versuch es mit einer Stadt in der Nähe</div>";
		}

		locations += "</div>";
		document.getElementById(searchResultDivId).innerHTML = locations;
		document.getElementById(searchResultDivId).style.border = "1px solid #336699";
		document.getElementById(searchResultDivId).style.height = "";
		document.getElementById(searchResultDivId).style.display = "block";

		/*
		if (results.length == -1) {
			document.getElementById(searchResultDivId).style.display = "none";
		}
		else if (results.length > 5) {
			//document.getElementById(searchResultDivId).style.height = "80px";
			//document.getElementById(searchResultDivId).style.overflow = "auto";
		}
		*/
	}
}

function getLocation (locationId, noCache) {
	var jsonCall = "ajaxGetLocation="+locationId;
	return ajaxJSONCall(jsonCall, noCache);
}

function closeSearchfield(fieldId) {
	if (document.getElementById(fieldId + "_searchresult") != undefined) {
		document.getElementById(fieldId + "_searchresult").style.display = "none";
		// also remove input if it was not properly selected (locationId is empty)
		if (document.getElementById(fieldId + "_select").value == "") {
			document.getElementById(fieldId).value = "";
		}
	}
}


function setLocation (locationId, searchFieldId, showInMap) {
	if (document.getElementById(searchFieldId + "_searchresult") == undefined) {
		createSearchResultDiv(searchFieldId);
	}
	document.getElementById(searchFieldId + "_searchresult").style.display = "none";
	document.getElementById(searchFieldId + "_select").value = locationId;

	var locationRecord = getLocation(locationId);
	var noCache = false;
	if (locationRecord['lat'] == null || !(locationRecord['lat'] > 0) || locationRecord['lng'] == null || !(locationRecord['lng'] > 0)) {
		updateLocationLatLng(locationId);
		locationRecord = getLocation(locationId, true);
		noCache = true;
	}
	document.getElementById(searchFieldId).value = locationRecord["name"];
	if (document.getElementById(searchFieldId + "_radius") != undefined) {
		document.getElementById(searchFieldId + "_radius").style.display = "block";
	}
	if (document.getElementById(searchFieldId + "_detail") != undefined) {
		// unset readonly flag for detail field
		document.getElementById(searchFieldId + "_detail").readOnly = false;
	}

	if (showInMap != undefined) {
		if (document.getElementById(searchFieldId).form.elements['locationFromId'].value > 0 && document.getElementById(searchFieldId).form.elements['locationToId'].value > 0) {
			initializeMap();
			stopOverLocations = new Array();
			if (stopOverLocations.length == 0) {
				stopOverLocations.push(document.getElementById(searchFieldId).form.elements['locationFromId'].value);
				stopOverLocations.push(document.getElementById(searchFieldId).form.elements['locationToId'].value);
			}

			var locationFromRecord = getLocation(document.getElementById(searchFieldId).form.elements['locationFromId'].value, noCache);
			var locationToRecord = getLocation(document.getElementById(searchFieldId).form.elements['locationToId'].value, noCache);

			var fromLatLng = new GLatLng(parseFloat(locationFromRecord['lat']), parseFloat(locationFromRecord['lng']));
			var toLatLng = new GLatLng(parseFloat(locationToRecord['lat']), parseFloat(locationToRecord['lng']));

			directions = new GDirections(map);
			//GEvent.addListener(directions, "load", onGDirectionsLoad);
			GEvent.addListener(directions, "load", function () {onGDirectionsLoad();});

			var pointsArray = [fromLatLng,toLatLng];
			directions.loadFromWaypoints(pointsArray);
		}
	}
	// set focus to "TO" field, if exists
	if (searchFieldId.search(/from/) != -1) {
		var toSearchFieldId = searchFieldId.replace(/from/, "to");
		if (document.getElementById(toSearchFieldId) != undefined) {
			if (document.getElementById(searchFieldId + "_detail") != undefined) {
				// focus on detail field if it exists
				document.getElementById(searchFieldId + '_detail').focus();
			}
			else {
				// focus to TO-field
				document.getElementById(toSearchFieldId).focus();
			}
		}
	}

	// set focus to TO-details field of exists
	if (searchFieldId.search(/_to/) != -1) {
		if (document.getElementById(searchFieldId + '_detail') != undefined) {
			// focus on detail field if it exists
			document.getElementById(searchFieldId + '_detail').focus();
		}
	}
}

function removeStopover (locationId) {
	stopOverLocations.remove(locationId);

	var pointsArray = new Array();
	//pointsArray.push(directions.getRoute(0).getStep(0).getLatLng());
	for (var i = 0;i < stopOverLocations.length;i++) {
		var locationRecord = getLocation(stopOverLocations[i]);
		pointsArray.push(new GLatLng(locationRecord["lat"], locationRecord["lng"]));
	}
	//pointsArray.push(directions.getRoute(directions.getNumRoutes()-1).getEndLatLng());

	// repaint
	directions.loadFromWaypoints(pointsArray);
}

function addStopoverLocations(stopoverLocationIdsString) {
	if (stopoverLocationIdsString != "") {
		var ids = stopoverLocationIdsString.split(",");
		for (var l = 0;l < ids.length;l++) {
			addStopover(ids[l]);
		}
	}
}

function addStopover(locationId, callingId) {
	// empty callinf field
	$('#' + callingId).val('');

	var stopoverArray = stopOverLocations.slice(1, -1);
	// get stopovers from allstopOvers[1...n-1]
	// 0 = from, n = to
	// add new location to stopover array
	stopoverArray.push(locationId);
	// get ordered stopover locations
	var jsonCall = ajaxUrl + "ajaxGetOrderedStopoverLocations="+stopOverLocations[0]+"&locations="+stopoverArray.join(",");

	$.getJSON(jsonCall, function(res) {
		var temp = new Array();
		var pointsArray = new Array();
		var pa = new Array();
		temp.push(stopOverLocations[0]);
		pointsArray.push(directions.getRoute(0).getStep(0).getLatLng());
		for (var i = 0;i < res.length;i++) {
			temp.push(res[i]['location_id']);
			pointsArray.push(new GLatLng(res[i]["lat"], res[i]["lng"]));
		}
		temp.push(stopOverLocations[stopOverLocations.length-1]);
		pointsArray.push(directions.getRoute(directions.getNumRoutes()-1).getEndLatLng());

		stopOverLocations = temp;

		// repaint
		directions.loadFromWaypoints(pointsArray);
	});
}

function computeStartTime (startTimeField, destinationTimeField, durationInSeconds) {
	if (destinationTimeField.value != "" && durationInSeconds > 0 && startTimeField.value == "") {
		var durationInMinutes = Math.floor(durationInSeconds / 60);

		var chunks = destinationTimeField.value.split(":");
		if (chunks.length == 1) {
			chunks[1] = "00";
			destinationTimeField.value = chunks[0] + ":" + chunks[1];
		}
		var destHourPart = parseInt(chunks[0]);
		var destMinutePart = parseInt(chunks[1]);

		var destInMinutes = destHourPart * 60 + destMinutePart;
		var startTimeMinutes = destInMinutes - durationInMinutes;
		if (startTimeMinutes < 0) {
			// we need to start the day before
			startTimeMinutes = 1440 + startTimeMinutes;
		}
		// REMINDER check the day after!!!

		// floor starttime to 10-minute grid
		var startTimeRounded = Math.floor(startTimeMinutes / 10) * 10;

		var startHourPart = Math.floor(startTimeRounded / 60);
		var startMinutePart = startTimeRounded - (startHourPart * 60);

		startTimeField.value = startHourPart + ":" + (startMinutePart + "0").substr(0,2);
		startTimeField.className = 'changed';
	}
}

function onGDirectionsLoad() {
	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(document.getElementById("starttime"), document.getElementById("destinationtime"), 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;
	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.min(v * verticiesPerGroup + (verticiesPerGroup/2) + bias, totalVertexCount-verticiesPerGroup);
		var latLng = polyline.getVertex(index);
		// build array with lat,lon entries
		latLngs.push(latLng.y + "," + latLng.x);
	}

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

	// get stopover locations

	var startId = stopOverLocations[0];
	var stopId = stopOverLocations[stopOverLocations.length-1];
	//getStopoverLocations(document.getElementById("location_from_select").form.elements['locationFromId'].value, document.getElementById("location_to_select").form.elements['locationToId'].value, latLngString, ambit);
	setTimeout(function() {getStopoverLocations(startId, stopId, latLngString, ambit);}, 2000);
}

function initializeMap() {
	var mapDiv = document.getElementById("map");
	mapDiv.style.display = 'block';
	//mapDiv.show();

	// hide norouteinfo if specified
	var noRouteInfoSpan = document.getElementById("norouteinfo");
	if (noRouteInfoSpan != undefined) noRouteInfoSpan.style.display = 'none';

	map = new GMap2(mapDiv);
	map.setCenter(new GLatLng(45.120053, 6.943359), 5);
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());

	directions = new GDirections(map);
	// after load, show stopovers
	GEvent.addListener(directions, "addoverlay", function () {MROnGDirectionsLoad();});
}

function initializeVisualSearchMap() {
	var mapDiv = document.getElementById("visualSearchMap");
	mapDiv.style.display = 'block';

	mapVS = new GMap2(mapDiv);
	mapVS.setCenter(new GLatLng(51.651786, 10.115039), 5);
	mapVS.addControl(new GLargeMapControl());
	mapVS.addControl(new GScaleControl());
	mapVS.addControl(new GMapTypeControl());
}

function initializeMapById(mapId) {
	var mapDiv = document.getElementById(mapId);
	if (mapDiv != null) {
		mapDiv.style.display = 'block';

		maps[mapId] = new GMap2(mapDiv);
		maps[mapId].setCenter(new GLatLng(51.651786, 10.115039), 6);
		maps[mapId].addControl(new GSmallMapControl());
		maps[mapId].addControl(new GScaleControl());
		maps[mapId].addControl(new GMapTypeControl());
		//maps[mapId].addControl(new GOverviewMapControl());
	}
}

function getStopoverLocations (startLocationId, destinationLocationId, latLons, ambit) {
	var jsonCall = ajaxUrl + "ajaxGetStopoverLocations="+latLons+"&startLocationId="+startLocationId+"&destinationLocationId="+destinationLocationId+"&ambit="+ambit;

	document.getElementById("stopoverLocationIds").value = "";
	var stopoverHTML = "";
	var isStopover = false;

	$.getJSON(jsonCall, function(stopoverLocations) {
		//var s = new Array();
		for (var i = 0;i < stopoverLocations.length;i++) {
			isStopover = false;
			if (stopOverLocations.exists(stopoverLocations[i]["location_id"])) {
				isStopover = true;
				document.getElementById("stopoverLocationIds").value += ((document.getElementById("stopoverLocationIds").value == "") ? "" : ",") + stopoverLocations[i]["location_id"];
				//s.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>";
			}
		}
		$('#stopovers').html(stopoverHTML);
	});

	$('#additionalstopoverdiv').show();
}

function updateLocationLatLng (locationId) {
	var locationRecord = getLocation(locationId);
	var address = locationRecord["country"] + " " + locationRecord["location"];

	var gcg = new GClientGeocoder();
	gcg.getLatLng(address,
		function (point) {
			if (point == null) {
				alert("Fehler");
			} else {
				var jsonCall = "ajaxUpdateLocationLatLng="+locationId+"&lat="+point.y+"&lng="+point.x;
				var res = ajaxJSONCall(jsonCall, true);
				if (isError(res)) {
					alert(getTranslation(res['errorCode'], res['errorClass']));
				}
			}
		}
	);
}

function geocodeAddress (form, coordinateId) {
	var country = form.countryid.options[form.countryid.selectedIndex].text;
	var zip = form.zip.value;
	var city = form.city.value;
	var address = form.street.value + " " + form.streetnumber.value;

	var locationToGeocode = country + " " + zip + " " + city + " " + address;

	var gcg = new GClientGeocoder();
	gcg.getLatLng(locationToGeocode,
		function (point) {
			if (point != null) {
				if (document.getElementById(coordinateId) != undefined) {
					document.getElementById(coordinateId).value = "(" + point.y + "," + point.x + ")";
				}
			}
		}
	);
}

function geocodeLocation (locationId) {
	var locationRecord = getLocation(locationId);
	var locationToGeocode = locationRecord['country'] + ', ' + ((locationRecord['zip'] == null) ? '' : locationRecord['zip'] + ' ') + locationRecord['location'];

	var gcg = new GClientGeocoder();
	gcg.getLatLng(locationToGeocode,
		function (point) {
			if (point != null) {
				var jsonCall = "ajaxUpdateLocationLatLng="+locationId+"&lat="+point.y+"&lng="+point.x;
				var res = ajaxJSONCall(jsonCall, true);
				if (isError(res)) {
					document.getElementById('coordinates_' + locationId).innerHTML = 'Fehler: ' + res['message'];
				}
				else {
					document.getElementById('coordinates_' + locationId).innerHTML = '(' + point.y + ',' + point.x + ')';
				}
			}
			else {
				document.getElementById('coordinates_' + locationId).innerHTML = 'Fehler: ' + point;
			}
		}
	);
	return false;
}

function getSeatsForCar (carIdField, seatsFieldName) {
	if (carIdField.value > 0 && carIdField.form.elements[seatsFieldName] != undefined) {
		var jsonCall = "ajaxGetSeatsForCar="+carIdField.value;
		var res = ajaxJSONCall(jsonCall);
		carIdField.form.elements[seatsFieldName].value = res['seats'];
	}
}

function showPersonFields(field) {
	if (field.checked) {
		$("#person").show();
	}
	else {
		$("#person").hide();
	}
}

function showObjectFields(field) {
	if (field.checked) {
		$("#object").show();
	}
	else {
		$("#object").hide();
	}
}

function postFeedback(form) {
	if (form.feedback.value != "") {
		var res = !HTML_AJAX.formSubmit(form, 'feedbackreturn1');
		$('#feedbackreturn').html('Vielen Dank für Dein Feedback');
		$('#feedbackreturn').show(200);
		setTimeout("$('#feedbackreturn').hide(200);", 2500);
		form.feedback.value = '';
	}
	return false;
}

function setStopovers(stopOverIdString) {
	var stopoverArray = stopOverLocations.slice(1, -1);

	var ids = stopOverIdString.split(",");
	for (var i = 0;i < ids.length;i++) {
		addStopover(ids[i]);
	}
}

function showNewCarFields(field) {
	if (field.options[field.selectedIndex].value == "") {
		$("#trnewcar").show();
		// set some default if empty
		if (field.form.elements['car_consumption'].value == "") {
			field.form.elements['car_consumption'].value = "8,0";
		}
		if (field.form.elements['car_seats'].value == "") {
			field.form.elements['car_seats'].value = 3;
		}
		field.form.elements['car_licencenumber'].focus();
	}
	else {
		$("#trnewcar").hide();
	}
}

function getPriceProposal (form, priceField, overWrite) {
	if (form.elements[priceField].value == "" || overWrite == true) {
		var distanceInMeters = document.getElementById("distance").value;
		var carId = form.carid.value;
		if (carId > 0) {
			var jsonCall = "ajaxGetPriceProposal="+carId+"&distance="+distanceInMeters;
		}
		else {
			var carConsumption = form.elements['car_consumption'].value;
			var jsonCall = "ajaxGetPriceProposal=-1&distance="+distanceInMeters+"&cc="+carConsumption;
		}
		var res = ajaxJSONCall(jsonCall, true);
		if (isError(res)) {
			alert(res['message']);
		}
		else {
			form.elements[priceField].value = res;
			$("input[name='askingprice_01']").attr('checked', false);
		}
	}
}

function configureTripForm(form) {
	var tripType = $('#'+form.id+" input[name='type']:checked").val();
	
	if (tripType == 'offer') {
		// configure offer
		$("#trstopovers").show();
		$("#trcarid").show();
		showNewCarFields(form.elements["carid"]);
		MRCheckRailway(form.elements["railway_01"]);
		document.getElementById('td-distance').className = 'subsection';
		if (form.frequency[1].checked == true) {
			// show frequency table
			$("#trfrequency").show();
			//form.elements['date'].value = (new Date()).format("yyyy-mm-dd");
		}
		else {
			$('#trfrequency').hide();
		}
	}
	else {
		// configure request
		MRCheckRailway(form.elements["railway_01"]);
		$("#trcarid").hide();
		$("#trnewcar").hide();
		$("#trstopovers").hide();
		document.getElementById('td-distance').className = '';
		if (tripType == 'request') {
			if (form.frequency[1].checked == true) {
				// show frequency table
				$("#trfrequency").show();
			}
			else {
				$('#trfrequency').hide();
			}
		}
	}
}

function showHelp(element) {
	var helpId = element.id;
	var call = "ajaxGetHelpRecord=" + helpId;
	var res = ajaxJSONCall(call);
	if (isError(res)) {
		alert(res['message']);
	}
	else {
		var help = res['help'];
		var field = res['field'];
		overlib(help, CAPTION, field, WIDTH, 200, CELLPAD, 5, HAUTO, VAUTO, STICKY);
	}
}

function getEventsForLocation (locationFieldname, dateField, selectedValue) {
	var trDisplay = "block";
	// IE/FF switch:
	if (document.all == undefined) {
		trDisplay = "table-row";
	}

	// get events and update dropdown if there are any events
	//var locationId = document.getElementById(locationFieldname + '_select').value;
	//var locationId = dateField.form.elements[document.getElementById(locationFieldname + '_select').name].value;
	var locationId = $('#' + locationFieldname).val(); //dateField.form.elements[document.getElementById(locationFieldname + '_select').name].value;
	if (locationId > 0 && dateField.value != "") {
		//document.getElementById(locationFieldname + '_events').style.display = 'none';
		$('#' + locationFieldname + '_events').hide();
		var call = "ajaxGetEventsForLocation="+locationId+"&date="+dateField.value;
		var res = ajaxJSONCall(call);
		if (isError(res)) {
			alert(res['message']);
		}
		else {
			// populate event dropdown
			var locationEvents = dateField.form.elements[locationFieldname + '_eventid'];
			if (selectedValue == undefined && locationEvents.selectedIndex >= 0) {
				selectedValue = locationEvents.options[locationEvents.selectedIndex].value;
			}
			locationEvents.length = 0;
			if (res.length > 0) {
				locationEvents.options[0] = new Option(getTranslation('no_event', 'trip'), '', false, false);
				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;
					}

					locationEvents.options[e+1] = new Option(res[e].name, res[e].event_id, selected, selected);
				}
				// show event-dropdown
				document.getElementById(locationFieldname + '_events').style.display = trDisplay;
			}
		}
	}
}

function showPassengers(tripId) {
	var call = "ajaxGetBookings="+tripId;
	var res = ajaxJSONCall(call);
	if (isError(res)) {
		alert(res['message']);
	}
	else {
		if (res.length > 0) {
			var overlibHtml = "<table class=\"list\"><tr><th colspan=3 class=\"nobr\">Vor- & Nachname</th><th>Telefon</th><th>Handy</th><th>E-Mail</th><th>Plätze</th></tr>";
			for (b = 0;b < res.length;b++) {
				overlibHtml += "<tr>";
				overlibHtml += " <td><img src='" + rootUrl + "/icons/confirmed_" + res[b]['confirmed_01'] + ".png' alt='status'/></td><td><a href=\"skype:" + res[b]['skype'] + "\"><img src=\"" + rootUrl + "/icons/skypeme.png\" alt=\"Skype\"/></a></td><td class=\"nobr\">" + res[b]['firstname'] + " " + res[b]['lastname'] + "</td><td>" + ((res[b]['phone'] == null) ? '-' : "<a href=\"callto:" + res[b]['phone_international'] + "\">" + res[b]['phone_international'] + "</a>") + "</td><td><a href=\"callto:" + res[b]['mobile_international'] + "\">" + res[b]['mobile_international'] + "</a></td><td><a href=\"mailto:" + res[b]['email'] + "\">" + res[b]['email'] + "</a></td><td class=\"center\">" + res[b]['seats']+ "</td>";
				overlibHtml += "</tr>";
			}
			overlibHtml += "</table>";
		}
		else {
			overlibHtml = "Für dieses Inserat wurden noch keine Reservierungen eingetragen";
		}
		overlib(overlibHtml, CAPTION, "Reservierungen", STICKY, WIDTH, 450, HAUTO, VAUTO);
	}
}

/**
 * Converts a date in format YYYY-MM-DD in an array with
 * 0 => YYYY, 1 => MM, 2 => DD
 *
 * @author GANTNER IT-Lösungen | Julian Gantner | gantner@itloesungen.com | 25.06.2008
 */
function date2Array(date) {
	if (date == null) {
		return null;
	}
	var chunks = date.split("-");
	return new Array(chunks[0], chunks[1], chunks[2]);
}

/**
 * Shows an overlib with the next maxEvents events
 * @author GANTNER IT-Lösungen | Julian Gantner | gantner@itloesungen.com | 25.06.2008
 */
function showUpcomingEvents(type) {
	var maxEvents = 8;
	if (type == 1) {
		var call = "ajaxGetUpcomingEvents=" + maxEvents + "&withTripsOnly=0";
	}
	else {
		var call = "ajaxGetUpcomingEvents=" + maxEvents + "&withTripsOnly=1";
	}
	var res = ajaxJSONCall(call);
	if (isError(res)) {
		alert(res['message']);
	}
	else {
		if (type == 1) {
			var scriptUrl = rootUrl + "scripts/trip/add.php";
		}
		else {
			var scriptUrl = rootUrl + "scripts/trip/trips2event.php";
		}
		var overlibHtml = "<table class=\"list\"><tr><th>Datum</th><th>Art</th><th>Event</th><th>Ort</th><th><img src='"+rootUrl+"icons/toevent.png' alt='Mitfahrgelegenheiten zum Event'/></th><th class=\"lastcolumn\"><img src='"+rootUrl+"icons/fromevent.png' alt='Mitfahrgelegenheiten nach Hause'/></th></tr>";
		for (e = 0;e < res.length;e++) {
			res[e]['trips_to_event'] = (res[e]['trips_to_event'] == null) ? 0 : res[e]['trips_to_event'];
			res[e]['trips_from_event'] = (res[e]['trips_from_event'] == null) ? 0 : res[e]['trips_from_event'];
			overlibHtml += "<tr>";
			var dateArray = date2Array(res[e]['date_start']);
			overlibHtml += " <td>" + (new Date(dateArray[0], dateArray[1]-1, dateArray[2])).format("dd.mm.yy") + "</td><td class=center>" + res[e]['eventcategory'] + "</td><td class='nobr'><a href=\"" + scriptUrl + "?eid=" + res[e]['event_id'] + "\">" + res[e]['name'] + "</a></td><td class=\"nobr\">" + res[e]['location'] + "</td><td class=\"center\">" + res[e]['trips_to_event'] + "</td><td class=\"center lastcolumn\">" + res[e]['trips_from_event'] + "</td>";
			overlibHtml += "</tr>";
		}
		overlibHtml += "</table>";
		overlib(overlibHtml, CAPTION, "Nächste Events", STICKY, HAUTO, VAUTO, WIDTH, 450);
	}
}

function computeCosts (kmField, showDetail) {
	var ajaxCall = ajaxUrl + "ajaxGetFuelData=1";
	$.getJSON(ajaxCall, function(fuelData) {
		var consumption = 8;
		var pricePerLiter = fuelData['pricePerLiter'];
		var lastUpdate = new Date(fuelData['lastUpdate'] * 1000);
		var distanceKm = kmField.value;
		var maxPassengers = 3;

		if (!isNaN(kmField.value)) {
			if (kmField.value >= 0 && kmField.value <= 42000) {
				if (over) cClick();
				var costs = '<table class=\"list\"><tr><th class=center>Mitfahrer</th><th class=\'center nobr\'>Kosten (in &euro;)<br/>pro Person</th><th class=center>Ersparnis</th></tr>';
				for (var p = 0; p <= maxPassengers;p++) {
					var cost = (distanceKm * (consumption / 100) * pricePerLiter) / (p + 1);
					if (p == 0) maxPrice = cost;
					if (p == maxPassengers) minPrice = cost;
					var saving = (maxPrice - cost) / maxPrice * 100;
					costs += '<tr class=' + ((p % 2 == 0) ? 'shadow' : '') + '><td class=center>' + p + '</td><td class=center>' + (new Number(cost)).numberFormat("#,#.00") + '</td><td class=\'red bold center\'>- ' + (new Number(saving)).numberFormat("#,#.0") + ' %</td></tr>';
				}
				costs += '</table>';
				if (showDetail != undefined) {
					overlib(costs, CAPTION, 'Fahrtkosten für ' + distanceKm + ' Km', STICKY, VAUTO);
				}

				$('#costcalculatorMinPrice').html((new Number(minPrice)).numberFormat("#,#.00"));
				$('#costcalculatorMaxPrice').html((new Number(maxPrice)).numberFormat("#,#.00"));
				$('#costcalculatorPricePerLiter').html((new Number(pricePerLiter)).numberFormat("#,#.00"));
				$('#costcalculatorLastUpdate').html((lastUpdate.format("dd.mm.yy, HH:MM")));
			}
		}
	});
}

function getUserInfo (userId) {
	var call = "ajaxGetUserInfo=" + userId;
	var res = ajaxJSONCall(call);
	if (isError(res)) {
		alert(res['message']);
	}
	else {
		var userInfo = "<table class=\"list\">";
		userInfo += "<tr class=shadow><td class=label>Name</td><td class=\"lastcolumn nobr\">" + res['firstname'] + " " + res['lastname'] + "</td></tr>";
		userInfo += "<tr><td class=label>E-Mail</td><td class=\"lastcolumn nobr\"><a href=\"mailto:" + res['email'] + "\">" + res['email'] + "</a></td></tr>";
		if (res['phone'] != "" && res['phone'] != null) {
			userInfo += "<tr class=shadow><td class=label>Telefon</td><td class=\"lastcolumn nobr\"><a href=\"callto:" + res['phone_international'] + "\">" + res['phone_international'] + "</a></td></tr>";
		}
		if (res['mobile'] != "" && res['mobile'] != null) {
			userInfo += "<tr><td class=label>Handy</td><td class=\"lastcolumn nobr\"><a href=\"callto:" + res['mobile_international'] + "\">" + res['mobile_international'] + "</a></td></tr>";
		}
		userInfo += "</table>";
		overlib(userInfo, CAPTION, 'Benutzer [ ' + res['loginname'] + ' ]', STICKY, HAUTO, VAUTO);
	}
}

function showCounternotice(userratingId) {
	var counterratingDiv = document.getElementById("counternotice_" + userratingId);
	var counterratingButton = document.getElementById("writecounternotice_" + userratingId);

	counterratingDiv.style.display="inline";
	counterratingButton.style.display="none";
}

function updateFreeSeats(carSeatsField) {
	carSeatsField.form.elements['freeseats'].value = carSeatsField.value;
}

function createMarker(point, myIcon, html) {
	var popuphtml = "<div class=\"gpopup\">" + html + "<\/div>";
//	var marker = new GMarker(point, {icon: myIcon});
	var marker = new PdMarker(point, {icon: myIcon});
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(popuphtml);
	});
	return marker;
}

function showVisualSearch() {
	$("#visualSearch").toggle();
	if ($("#visualSearch:visible")) {
		initializeVisualSearchMap();

		showStartStopPoints();
		vsStartStop = new Array();
	}
}

function hideVisualSearch() {
	document.getElementById('visualSearch').style.display = 'none';
}

function showStartStopPoints() {
	// get startloccations
	var call = "ajaxGetVSData=1";
	var res = ajaxJSONCall(call);

	var maxCount = res['maxCount'];
	var maxPixel = 25;
	var minPixel = 15;

	var showAllText = "Neue visuelle Suche";

	// show locations
	var locations = res['locations'];
	for (var i = 0;i < locations.length;i++) {
		var point = new GPoint(locations[i]['lng'], locations[i]['lat']);
		var dim = Math.max(minPixel, Math.ceil(locations[i]['locationcount'] / maxCount * maxPixel));

		var html = "";

		var iconOptions = {};
		iconOptions.width = dim;
		iconOptions.height = dim;
		iconOptions.label = locations[i]['locationcount'];
		iconOptions.labelSize = 0;

		if (locations[i]['startonly'] == 't') {
			// we have a start-only location
			iconOptions.primaryColor = "#B3FF07";
			iconOptions.labelColor = "#000000";
			iconOptions.shape = "circle"; // roundrect
			html = "<h2 class=\"black\">" + locations[i]['name'] + "</h2>";
			html += "<div class=\"vsstartlocation\">&raquo; <a href=\"javascript: setStartLocation(" + locations[i]['location_id'] + ", '" + locations[i]['name'] +"');\">Hier will ich starten (<span class=\"green\">von A</span>)</a></div>";
			html += "<br/>&raquo; <a href=\"javascript: vsShowAllMarkers();\">" + showAllText + "</a>";
		}
		else if (locations[i]['stoponly'] == 't') {
			// we have a stop-only location
			iconOptions.primaryColor = "#0DC1E4";
			iconOptions.labelColor = "#000000";
			iconOptions.shape = "circle"; // roundrect
			html = "<h2 class=\"black\">" + locations[i]['name'] + "</h2>";
			html += "<div class=\"vsstoplocation\">&raquo; <a href=\"javascript: setStopLocation(" + locations[i]['location_id'] + ", '" + locations[i]['name'] +"');\">Hier will ich hin (<span class=\"blue\">nach B</span>)</a></div>";
			html += "<br/>&raquo; <a href=\"javascript: vsShowAllMarkers();\">" + showAllText + "</a>";
		}
		else {
			// we have a start/stop location
			iconOptions.primaryColor = "#FF0000";
			iconOptions.labelColor = "#ffffff";
			iconOptions.shape = "roundrect"; // roundrect
			html = "<h2 class=\"black\">" + locations[i]['name'] + "</h2>";
			html += "<div class=\"vsstartlocation\">&raquo; <a href=\"javascript: setStartLocation(" + locations[i]['location_id'] + ", '" + locations[i]['name'] +"');\">Hier will ich starten (<span class=\"green\">von A</span>)</a></div>";
			html += "<div class=\"vsstoplocation\">&raquo; <a href=\"javascript: setStopLocation(" + locations[i]['location_id'] + ", '" + locations[i]['name'] +"');\">Hier will ich hin (<span class=\"blue\">nach B</span>)</a></div>";
			html += "<br/>&raquo; <a href=\"javascript: vsShowAllMarkers();\">" + showAllText + "</a>";
		}
		var newIcon = MapIconMaker.createFlatIcon(iconOptions);

		//var html = "<b class=\"green\">Start (von A)</b>: " + starts[i]['name'] + "<br/>&raquo; <a href=\"javascript: setStartLocation(" + starts[i]['location_id'] + ", '" + starts[i]['name'] +"');\">Als <b>Startpunkt</b> setzen</a></p>";
		var marker = createMarker(point, newIcon, html);
		GEvent.addListener(marker, "click",
			function(e) {
				if (vsStartStop[0] > 0) {
					$("div.vsstartlocation").hide();
				}
				else {
					$("div.vsstartlocation").show();
				}
				if (vsStartStop[1] > 0) {
					$("div.vsstoplocation").hide();
				}
				else {
					$("div.vsstoplocation").show();
				}
			}
		);
		mapVS.addOverlay(marker);
		// save all markers in an array
		vsLocations.push(marker);
	}

/*
	// show starts
	var starts = res['starts'];
	for (var i = 0;i < starts.length;i++) {
		var point = new GPoint(starts[i]['lng'], starts[i]['lat']);
		var dim = Math.max(minPixel, Math.ceil(starts[i]['locationcount'] / maxCount * maxPixel));

		var iconOptions = {};
		iconOptions.width = dim;
		iconOptions.height = dim;
		iconOptions.primaryColor = "#B3FF07";
		iconOptions.label = starts[i]['locationcount'];
		iconOptions.labelSize = 0;
		iconOptions.labelColor = "#000000";
		iconOptions.shape = "circle"; // roundrect
		var newIcon = MapIconMaker.createFlatIcon(iconOptions);

		var html = "<b class=\"green\">Start (von A)</b>: " + starts[i]['name'] + "<br/>&raquo; <a href=\"javascript: setStartLocation(" + starts[i]['location_id'] + ", '" + starts[i]['name'] +"');\">Als <b>Startpunkt</b> setzen</a></p>";
		var marker = createMarker(point, newIcon, html);
		mapVS.addOverlay(marker);
		vsStartMarkers.push(marker);
	}

	// show stops
	var stops = res['stops'];
	for (var i = 0;i < stops.length;i++) {
		var point = new GPoint(stops[i]['lng'], stops[i]['lat']);
		var dim = Math.max(minPixel, Math.ceil(stops[i]['locationcount'] / maxCount * maxPixel));

		var iconOptions = {};
		iconOptions.width = dim;
		iconOptions.height = dim;
		iconOptions.primaryColor = "#0DC1E4";
		iconOptions.label = stops[i]['locationcount'];
		iconOptions.labelSize = 0;
		iconOptions.labelColor = "#000000";
		iconOptions.shape = "circle";
		var newIcon = MapIconMaker.createFlatIcon(iconOptions);

		var html = "<b class=\"blue\">Ziel (nach B)</b>: " + stops[i]['name'] + "<br/>&raquo; <a href=\"javascript: setStopLocation(" + stops[i]['location_id'] + ", '" + stops[i]['name'] +"');\">Als <b>Ziel</b> setzen</a></p>";
		var marker = createMarker(point, newIcon, html);
		mapVS.addOverlay(marker);
		vsStopMarkers.push(marker);
	}

	// show startstops
	var startstops = res['startstops'];
	for (var i = 0;i < startstops.length;i++) {
		var point = new GPoint(startstops[i]['lng'], startstops[i]['lat']);
		var dim = Math.max(minPixel, Math.ceil(startstops[i]['locationcount'] / maxCount * maxPixel));

		var iconOptions = {};
		iconOptions.width = dim;
		iconOptions.height = dim;
		iconOptions.primaryColor = "#FF0000";
		iconOptions.label = startstops[i]['locationcount'];
		iconOptions.labelSize = 0;
		iconOptions.labelColor = "#ffffff";
		iconOptions.shape = "roundrect"; // roundrect
		var newIcon = MapIconMaker.createFlatIcon(iconOptions);

		var html = "<b class=\"green\">Start (von A)</b>: " + startstops[i]['name'] + "<br/>&raquo; <a href=\"javascript: setStartLocation(" + startstops[i]['location_id'] + ", '" + startstops[i]['name'] +"');\">Als <b>Startpunkt</b> setzen</a>";
		html += "<br/><b class=\"blue\">Ziel (nach B)</b>: " + startstops[i]['name'] + "<br/>&raquo; <a href=\"javascript: setStopLocation(" + startstops[i]['location_id'] + ", '" + startstops[i]['name'] +"');\">Als <b>Ziel</b> setzen</a>";

		var marker = createMarker(point, newIcon, html);
		mapVS.addOverlay(marker);
		vsStartStopMarkers.push(marker);
	}
	*/
}

function vsShowAllMarkers() {
	for (var l = 0;l < vsLocations.length;l++) {
		vsLocations[l].show();
	}
	mapVS.closeInfoWindow();
	vsStartStop = new Array();
}

function setStartLocation(locationId, name) {
	$('#search_location_from_search').val(name);
	$('#search_location_from').val(locationId);
	//document.getElementById('search_location_from').value = name;
	//document.getElementById('search_location_from_select').value = locationId;
	mapVS.closeInfoWindow();

	// update stop locations
	var call = "ajaxGetVisualSearchStopLocations=" + locationId;
	var res = ajaxJSONCall(call);

	// get current location
	var locationRecord = getLocation(locationId);

	// walk all markers and remove those which are not reachable
	for (var l = 0;l < vsLocations.length;l++) {
		var markerCoords = vsLocations[l].getLatLng();
		markerFound = false;
		if (locationRecord['lat'] == markerCoords.lat() && locationRecord['lng'] == markerCoords.lng()) {
			markerFound = true;
		}
		else {
			for (var i = 0;i < res.length;i++) {
				if (markerCoords.lat() == res[i]['lat'] && markerCoords.lng() == res[i]['lng']) {
					markerFound = true;
				}
			}
		}

		if (!markerFound) vsLocations[l].hide();
		else vsLocations[l].show();
	}

	/*
	for (var m = 0;m < vsStopMarkers.length;m++) {
		var markerCoords = vsStopMarkers[m].getLatLng();
		markerFound = false;
		for (var i = 0;i < res.length;i++) {
			if (markerCoords.lat() == res[i]['lat'] && markerCoords.lng() == res[i]['lng']) {
				markerFound = true;
			}
		}
		if (!markerFound) vsStopMarkers[m].hide();
		else vsStopMarkers[m].show();
	}

	var locationRecord = getLocation(locationId);
	for (var m = 0;m < vsStartStopMarkers.length;m++) {
		var markerCoords = vsStartStopMarkers[m].getLatLng();
		markerFound = false;
		for (var i = 0;i < res.length;i++) {
			if (markerCoords.lat() == res[i]['lat'] && markerCoords.lng() == res[i]['lng']) {
				markerFound = true;
			}
		}
		if (locationRecord['lat'] == markerCoords.lat() && locationRecord['lng'] == markerCoords.lng()) {
			markerFound = true;
		}

		if (!markerFound) vsStartStopMarkers[m].hide();
		else vsStartStopMarkers[m].show();
	}
	*/

	vsStartStop[0] = locationId;

	// close visual search if start and stop is set
	if (vsStartStop[0] > 0 && vsStartStop[1] > 0 && (vsStartStop[0] != vsStartStop[1])) {
		hideVisualSearch();
	}
}

function setStopLocation(locationId, name) {
	$('#search_location_to_search').val(name);
	$('#search_location_to').val(locationId);
	//document.getElementById('search_location_to').value = name;
	//document.getElementById('search_location_to_select').value = locationId;
	mapVS.closeInfoWindow();

	// update stop locations
	var call = "ajaxGetVisualSearchStartLocations=" + locationId;
	var res = ajaxJSONCall(call);

	// get current location
	var locationRecord = getLocation(locationId);

	// walk all markers and remove those which are not reachable
	for (var l = 0;l < vsLocations.length;l++) {
		var markerCoords = vsLocations[l].getLatLng();
		markerFound = false;
		if (locationRecord['lat'] == markerCoords.lat() && locationRecord['lng'] == markerCoords.lng()) {
			markerFound = true;
		}
		else {
			for (var i = 0;i < res.length;i++) {
				if (markerCoords.lat() == res[i]['lat'] && markerCoords.lng() == res[i]['lng']) {
					markerFound = true;
				}
			}
		}

		if (!markerFound) vsLocations[l].hide();
		else vsLocations[l].show();
	}

	vsStartStop[1] = locationId;

	// close visual search if start and stop is set
	if (vsStartStop[0] > 0 && vsStartStop[1] > 0 && (vsStartStop[0] != vsStartStop[1])) {
		hideVisualSearch();
	}
}

function getLatLngFromCoordinates(coordinates) {
	var temp = coordinates.substring(1, coordinates.length-1);
	return temp.split(",");
}

function checkWeekdays(form, type) {
	if (type == 'daily') {
		for (var d = 0;d <= 6;d++) {
			form.elements['daysofweek[' + d + ']'].checked = true;
		}
	}
	else if (type == 'workdays') {
		for (var d = 1;d <= 5;d++) {
			form.elements['daysofweek[' + d + ']'].checked = true;
		}
		form.elements['daysofweek[6]'].checked = false;
		form.elements['daysofweek[0]'].checked = false;
	}
	else if (type == 'weekend') {
		for (var d = 1;d <= 5;d++) {
			form.elements['daysofweek[' + d + ']'].checked = false;
		}
		form.elements['daysofweek[6]'].checked = true;
		form.elements['daysofweek[0]'].checked = true;
	}
}

function toggleElement(id, focusField) {
	if ($('#' + id).is(':visible')) {
		$('#' + id).hide();
	}
	else {
		$('#' + id).fadeIn(300);
		if (focusField != undefined) {
			$('#'+focusField).focus();
		}
	}
}

function setFeedbackDone (feedbackId) {
	var call = "ajaxSetFeedbackDone=" + feedbackId;
	var res = ajaxJSONCall(call);
	if (isError(res)) {
		alert(res['message']);
	}
	else {
		alert(res['message']);
	}
}

function updateCountryPrefix(countryElement) {
	var countryId = countryElement.value;
	var call = "ajaxGetCountryRecord=" + countryId;
	var res = ajaxJSONCall(call);
	if (!isError(res)) {
		if (countryElement.form.elements['mobile_country_prefix'] != undefined) {
			countryElement.form.elements['mobile_country_prefix'].value = res['phone_prefix'];
			if (countryElement.form.elements['mobile_prefix'] != undefined) {
				countryElement.form.elements['mobile_prefix'].focus();
			}
		}
		if (countryElement.form.elements['phone_country_prefix'] != undefined) {
			countryElement.form.elements['phone_country_prefix'].value = res['phone_prefix'];
		}
	}
}

function hide(id) {
	$('#' + id).hide(200);
}

function createDynSearchDiv(field) {
	var dynDivId = field.name + '_dynsearchdiv';
	if (document.getElementById(dynDivId) == null) {
		$('#' + field.id).after("<div id=\"" + dynDivId + "\" class=\"searchResultDiv\"><div class=\"caption\"><div id=\"captiontext\" class=\"floatleft\"></div><div class=\"floatright\"><a href=\"javascript: hide('" + dynDivId + "');\"><img src=\"/mitreisen/public/icons/close.png\"/></a></div><div class=\"clearfloat\"/></div><div id=\"dynsearchcontent\" style=\"padding: 2px; overflow: auto; height: 100px;\"></div></div>");
		document.getElementById(dynDivId).style.border = "1px solid #336699";
	}
	//$('#' + dynDivId).show();

	return dynDivId;
}

function autoFill(field, table, column) {
	if (field.value.length >= 2) {
		// create dyn search div
		var dynDivId = createDynSearchDiv(field);
		// set caption
		$("#" + dynDivId + " #captiontext").html("Vorschläge");

		var ajaxCall = ajaxUrl + 'ajaxAutoFill=' + field.value + '&table=' + table + '&column=' + column;
		$.getJSON(ajaxCall, function(json) {
			var html = "";
			for (var i = 0;i < json.length;i++) {
				html += "<a href=\"javascript: autoFillSetValue('" + field.name + "', '" + json[i]['autofill'] + "');\">" + json[i]['autofill'] + "</a><br/>";
			}
			if (html != "") {
				$("#" + dynDivId + " #dynsearchcontent").html(html);
				$('#' + dynDivId).show();
			}
			else {
				$('#' + dynDivId).hide();
			}
		});
	}
}

function autoFillSetValue(fieldid, value) {
	$("input[name='" + fieldid + "']").val(value);
	hide(fieldid + '_dynsearchdiv');
}

function checkTimeInput(field) {
	if (field.value == "") {
		return;
	}
	var validTime = /([0-9]{1,2})(:?)([0-9]{1,2})?/;
	var res = validTime.exec(field.value);
	if (res == null) {
		field.value = 'hh:mm';
		return;
	}

	var hours = '00';
	var minutes = '00';
	if (field.value.length == 3 && (res[2] == "" || res[2] == undefined)) {
		hours = field.value.substr(0,1);
		minutes = field.value.substr(1,2);
	}
	else {
		hours = res[1];
		minutes = res[3];
	}
	if (hours == undefined || hours == "") {
		hours = '00';
	}
	if (minutes == undefined || minutes == "") {
		minutes = '00';
	}
	if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
		field.value = 'hh:mm';
	}
	else {
		if (hours.length == 1) hours = '0' + hours;
		if (minutes.length == 1) minutes = '0' + minutes;
		field.value = hours + ':' + minutes;
	}
}

function disallowDateBefore(date) {
	var ONEDAY = 3600 * 24 * 1000;
	date = date.getTime();

	if (date <= ((new Date()).getTime() - ONEDAY)) {
		return true;
	}
	return false;
}

function fillAdditionalStopovers(json, callingId) {
	var data = '';
	for(i=0; i < json.length; i++) {
		data += '<div class="' + ((i % 2 == 0) ? 'shadow' : '') + '"><a href="javascript: addStopover(' + json[i]['location_id'] + ', \'' + callingId + '\');">' + json[i]['name'] + '</a></div>';
	}

	return data;
}

function stripHTML(oldString) {
	var newString = "";
	var inTag = false;
	for(var i = 0; i < oldString.length; i++) {
		if(oldString.charAt(i) == '<') inTag = true;
		if(oldString.charAt(i) == '>') {
        	if(oldString.charAt(i+1)=="<") {
              		//dont do anything
			}
			else {
				inTag = false;
				i++;
			}
        }
        if(!inTag) newString += oldString.charAt(i);
   }
   return newString;
}

function selectAllCheckboxesInForm(elementId) {
	$('#'+elementId+" input[type='checkbox']").each( function() {
		$(this).attr('checked', !$(this).attr('checked'));
    });
}

function inviteFriend(form, elementId) {
	if (form.message.value != "") {
		var data = { btn_invite : "invite", message : form.message.value, friendid : form.friendid.value };
		$.post(form.action, data, function(res) {
			if (isError(res)) {
				alert(res['message']);
			}
			else {
				$('#'+elementId).html("<p class='bold'>"+res['message']+"</p>");
				if ($('#centeredPopup').is(":visible")) {
					setTimeout("closePopup();", 2000);
				}
			}
		}, "json");
		
//		var res = !HTML_AJAX.formSubmit(form, 'feedbackreturn1');
//		$('#feedbackreturn').html('Vielen Dank für Dein Feedback');
//		$('#feedbackreturn').show(200);
//		setTimeout("$('#feedbackreturn').hide(200);", 2500);
//		form.feedback.value = '';
	}
	return false;
}

function showShortInfoMessage(message, type) {
	if (type == undefined) type = 'infos';
	$('#shortInfoMessage').html("<div class='"+type+"'>"+message+"</div>");
	$('#shortInfoMessage').show(500);
	setTimeout("hideShortInfoMessage()", 5000);
}

function hideShortInfoMessage() {
	$('#shortInfoMessage').hide(500).html("");
}

function assignToEvent(eventId, obj) {
	if (eventId > 0) {
		var ajaxCall = ajaxUrl + 'ajaxAssignToEvent=' + eventId;
		$.getJSON(ajaxCall, function(res) {
			if (isError(res)) {
				showShortInfoMessage(res['message'], 'errors');
			}
			else {
				$(obj).removeClass('event_unassigned');
				$(obj).addClass('event_assigned');
				if ($(obj).html() != "&nbsp;") {
					$(obj).html("Nein, ich gehe doch nicht hin");	
				}
				$(obj).attr("onclick", "");
				$(obj).unbind('click');
				$(obj).click(function () {unassignFromEvent(eventId, obj);});
				$(obj).blur();
				showShortInfoMessage(res['message']);
			}
		});
	}
}

function unassignFromEvent(eventId, obj) {
	if (eventId > 0) {
		var ajaxCall = ajaxUrl + 'ajaxUnassignFromEvent=' + eventId;
		$.getJSON(ajaxCall, function(res) {
			if (isError(res)) {
				showShortInfoMessage(res['message'], 'errors');
			}
			else {
				$(obj).removeClass('event_assigned');
				$(obj).addClass('event_unassigned');
				if ($(obj).html() != "&nbsp;") {
					$(obj).html("Da geh' ich hin");	
				}
				$(obj).attr("onclick", "");
				$(obj).unbind('click');
				$(obj).click(function () {assignToEvent(eventId, obj);});
				$(obj).blur();
				showShortInfoMessage(res['message']);
			}
		});
	}
}

function inviteFriendForm(userId) {
	var offsetX = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
	var ajaxCall = ajaxUrl + 'ajaxGetInvitePopup='+userId;
	$.getJSON(ajaxCall, function(res) {
		$('#centeredPopup').show().html(res);
		$('#centeredPopup').css("top", Math.round((document.documentElement.clientHeight/2)-($('#centeredPopup').height()/2)+offsetX)+'px');
		$('#centeredPopup').css("left", Math.round((document.documentElement.clientWidth/2)-($('#centeredPopup').width()/2))+"px");
	});
}

function closePopup() {
	$('#centeredPopup').hide().html('');
}