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

function isError(error) {
	if (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");
}

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 + " wirklich 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 convertOunceToGram (ounceField, gramField) {
	if (ounceField.value == "") {
		return "";
	}
	var value = ounceField.value.replace(/,/, ".");
	
	var fractionChunks = ounceField.value.split("/");
	if (fractionChunks.length == 2) {
		value = fractionChunks[0] / fractionChunks[1];
	}
	
	var factor = 31.1034768;
	
	var gramValue = round(parseFloat(value) * factor, 3);
	
	if (isNaN(gramValue)) {
		gramValue = "";
	}
	
	gramField.value = gramValue; 
}

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 hideSearchresults (fieldname) {
	document.getElementById(fieldname + "_searchresult").innerHTML = "";
 	document.getElementById(fieldname + "_searchresult").style.border = "0px";
 	document.getElementById(fieldname + "_searchresult").style.display = "none";
}

function searchLocation (inputField) {
	var fieldname = inputField.name;
	if (document.getElementById(fieldname + "_searchresult") == null) {
		/*
		var resultDiv = document.createElement("div");
		resultDiv.setAttribute("id", fieldname + "_searchresult");
		resultDiv.setAttribute("class", "searchResultDiv");
		inputField.appendChild(resultDiv);
		*/
	}
	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=" + 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 = "";
 		document.getElementById(fieldname + "_radius").style.display = "none";
 		return;
	}
}

function ShowLocations (fieldname) {
	this.fieldname = fieldname;
	var me = this;
	var searchResultDivId = me.fieldname + "_searchresult";
	
	this.invoke = function (results) {
		var locations = "<div class=\"caption\">Gefundene Städte | <a href=\"javascript: hideSearchresults('" + fieldname + "');\">X</a></div><div style=\"overflow: auto;height: 80px;\">";
		results = eval("(" + results + ")");
		for (var i = 0;i < results.length;i++) {
			locations += "&raquo; <a href=\"javascript: setLocation(" + results[i]["location_id"] + ", '" + me.fieldname + "');\">" + results[i]["name"] + "</a><br/>";
		}
		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 == 0) {
			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 setLocation (locationId, 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"];
	document.getElementById(searchFieldId + "_radius").style.display = "block";
	// get radius locations
	//showRadiusLocations(locationId, searchFieldId);
	
	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);

		var pointsArray = [fromLatLng,toLatLng];
		directions.loadFromWaypoints(pointsArray);
	} 
}

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 addStopover(locationId) {
	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 = "ajaxGetOrderedStopoverLocations="+stopOverLocations[0]+"&locations="+stopoverArray.join(",");
	var res = ajaxJSONCall(jsonCall);

	// build new array with ordered stopovers
	var temp = new Array();
	var pointsArray = 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"]));
		//document.getElementById("stopOverLocationIds").value += 
	}
	temp.push(stopOverLocations[stopOverLocations.length-1]);
	pointsArray.push(directions.getRoute(directions.getNumRoutes()-1).getEndLatLng());
	
	stopOverLocations = temp;
	// repaint
	directions.loadFromWaypoints(pointsArray);
}

function onGDirectionsLoad() {
	var distance = directions.getDistance();
	var duration = directions.getDuration();
	var polyline = directions.getPolyline();
	document.getElementById("distance").innerHTML = distance['html'];
	document.getElementById("duration").innerHTML = duration['html'];
	
	//var scope = 25;
	//var waypoints = distance['meters'] / 1000 / scope;
	//var vertexOffset = polyline.getVertexCount() / waypoints;
	//alert(vertexOffset);
	// get stopover locations
	getStopoverLocations(document.getElementById("location_from_select").form.elements['locationFromId'].value, document.getElementById("location_to_select").form.elements['locationToId'].value, distance['meters']);
}

function initializeMap() {
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(45.120053, 6.943359), 5);
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());	
}

function getStopoverLocations (locationFromId, locationToId, distance) {
	var jsonCall = "ajaxGetStopoverLocations="+locationFromId+"|"+locationToId+"|"+distance;
	var stopoverLocations = ajaxJSONCall(jsonCall);
	var stopoverHTML = "";
	var isStopover = false;
	document.getElementById("stopoverLocationIds").value = "";
	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"];
		}
		if (isStopover) {
			stopoverHTML += "<div class=\"stopover stopoverselected\">&raquo; <a href=\"javascript: removeStopover(" + stopoverLocations[i]["location_id"] + ");\">" + stopoverLocations[i]["name"] + "</a></div>";
		}
		else {
			stopoverHTML += "<div class=\"stopover\"><a href=\"javascript: addStopover(" + stopoverLocations[i]["location_id"] + ");\">" + stopoverLocations[i]["name"] + "</a></div>";
		}
	}
	document.getElementById("stopovers").innerHTML = stopoverHTML;
}

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 showRadiusLocations(locationId, fieldname) {
	var chunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
	var baseUrl = chunks[1] + "ajax_json.php?";
	var callUrl = baseUrl + "ajaxGetRadiusLocations=" + locationId;

	var showLocations = new ShowLocations(fieldname);
	HTML_AJAX.grab(callUrl, showLocations.invoke);
}

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

function configureResourceForm(form) {
	var trDisplay = "block";
	// IE/FF switch:
	if (document.all == undefined) {
		trDisplay = "table-row";
	}
	
	// 1 = url
	// 2 = file
	var resourceTypeElement = form.elements["resourcetypeid"];
	if (resourceTypeElement.value == 1) {
		document.getElementById("file").style.display = 'none';
		document.getElementById("url").style.display = trDisplay;
	}
	else if (resourceTypeElement.value == 2) {
		document.getElementById("file").style.display = trDisplay;
		document.getElementById("url").style.display = 'none';
	}
	else {
		// nothing is selected
		document.getElementById("file").style.display = 'none';
		document.getElementById("url").style.display = 'none';
	}
}
