var ajaxCache = new Array();
var ajaxJSONCache = new Array();

var scriptChunks = document.location.pathname.match(/([a-z0-9\/]*\/scripts\/)/i);
var ajaxUrl = scriptChunks[1] + "ajax_json.php?";

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;
}

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

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 (identifier, pageId) {
	if (pageId == undefined) pageId = "";
	var call = "ajaxGetTranslation="+identifier+"&pageid="+pageId;
	return unescape(ajaxCall(call));
}

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) {
	if (ajaxJSONCache[call] == undefined) {
		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;
	$.getJSON(ajaxUrl + call, function (res) {
		selectCountryId.options.length = 0;
		if (res.length == 0) {
			// show nothing found
			selectCountryId.options[0] = new Option(getTranslation("nothingFound"), "", false, false);
		}
		else {
			var itemCount = 0;
			if (!hideSelectItem) {
				selectCountryId.options[itemCount] = new Option(emptyText, "", false, false);
				itemCount++;
			}
			for (var o = 0;o < res.length;o++) {
				var selected = false;
				if ((markSelectedCountries && selectedCountryIds.exists(res[o]['country_id'])) || (res[o]['country_id'] == preselectedCountryId)) {
					selected = true;
				}
				selectCountryId.options[o+itemCount] = new Option(res[o]['name'], res[o]['country_id'], selected, selected);
			}
		}
	});

	//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;
	$.getJSON(ajaxUrl + call, function(json) {
		if (!isError(json)) {
			// split path of res = new relative image path. [0] holds the first pathname
			var resChunks = json['imageLarge']['filename'].split("/");
			// build dynamic regexp which get all before the first path
			var regExp = new RegExp("^([a-z0-9\.:\/]*\/)" + resChunks[0]);
			var chunks = $('#image' + oid).attr('src').match(regExp);
			$('#image' + oid).attr('src', chunks[1] + json['imageLarge']['filename']);
		}
	});
}

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");
}

function setSelectedCountryIds(selectedCountryIdsElement) {
	selectedCountryIds = selectedCountryIdsElement.value.split(",");
}

// 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 call = "ajaxGetQuantityScale="+offerId+"&offerType="+offerType;
	$.getJSON(ajaxUrl + call, function(res) {
		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);
	});

	/*
	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/>";
		optionHTML += "<a href=\"javascript: accountInvoice(" + invoiceId + ");\">... Rechnung abschließen</a><br/>";
	}
	optionHTML += "<a href=\"javascript: exportInvoice(" + invoiceId + ");\">... Rechnung exportieren</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 accountInvoice(invoiceId) {
	var url = document.location.pathname + ((document.location.search != "") ? document.location.search + "&" : "?");
	document.location.href = url + "btn_markInvoiceAsAccounted=" + invoiceId;
}

function exportInvoice(invoiceId) {
	var url = document.location.pathname + ((document.location.search != "") ? document.location.search + "&" : "?");
	document.location.href = url + "btn_exportInvoice=" + 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 gotoPage () {
	var pageNumber = prompt("Gehe zu Seite: ", 1);
	if (pageNumber != null && pageNumber > 0) {
		var pageId = document.location.href.match(/(pageID=[0-9]+)/i);
		if (pageId == null) {
			document.location.href = document.location.pathname + ((document.location.search != "") ? document.location.search + "&" : "?") + 'pageID=' + pageNumber;
		}
		else {
			document.location.href = document.location.href.replace(pageId[1], 'pageID='+pageNumber);
		}
	}
}

function generateMyOfferLink (form) {
	var chunks = document.location.href.match(/([a-z0-9\/:\.-]*\/scripts\/)/i);
	var link = chunks[1] + "offers/customeroffers.php?restrict=1";
	var fields = new Array("creatorid", "continentid", "countryid", "facevalue", "currencyid", "cointypeid", "coinqualityid", "year", "endyear", "subject");

	for (var f = 0;f < fields.length;f++) {
		if (form.elements[fields[f]].value != "") {
			link += "&" + fields[f] + "=" + form.elements[fields[f]].value;
		}
	}

	form.myofferlink.value = link;
	return false;
}

function tinyMCEInitUser() {
	tinyMCE.init({
		mode : "specific_textareas",
		editor_selector : "mce",
		theme : "advanced",
		plugins : "",
		theme_advanced_disable : "formatselect,styleselect,justifyfull",
		theme_advanced_buttons1_add : "bullist,numlist,sup,forecolor,backcolor,separator,fontsizeselect",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_toolbar_align : "left",
		language : "de"
	});
}

function tinyMCEInitAdmin() {
	tinyMCE.init({
		mode : "specific_textareas",
		editor_selector : "mce",
		theme : "advanced",
		plugins : "",
		theme_advanced_disable : "formatselect,styleselect,justifyfull",
		theme_advanced_buttons1_add : "bullist,numlist,sup,forecolor,backcolor,separator,fontsizeselect,link,unlink",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_toolbar_align : "left",
		language : "de"
	});
}

function normalizePrice(pricefield) {
	var priceValue = pricefield.value;
	var call = "ajaxNormalizePrice=" + priceValue;
	$.getJSON(ajaxUrl + call, function(res) {
		pricefield.value = res.replace(".", ",");
		$('#inputCorrected').remove();
		if (priceValue != res) {
			$(pricefield).after("&nbsp;<span id='inputCorrected' class='red smaller'>Eingabe korrigiert</span>");
		}
	});
}