var flashPreview = null;
var updateTimer = null;
var priceInfo = null;
var priceTotal = 0.0;
var surchargeInfo = null;
var surchargeTotal = 0.0;

function flashPreviewReady() {
	flashPreview = document.getElementById("preview");
	clearTimeout(updateTimer);
	populateText();
}

function formatInt(num) {
	var re = /(\d+)(\d{3})/;
	var rv = num.toFixed(0);
	while (re.test(rv)) rv = rv.replace(re, "$1.$2");
	return rv;
}

function formatPrice(num) {
	return num.toFixed(2).replace(/\./, ",");
}

function interpolate(text) {
	return text.replace(/\[(.*)\]/g, function(match, expr) {
		var e = $(expr);
		if (!e.length) return "";
		if (e.is(":checkbox") && !e.is(":checked")) return "";
		return $(expr).val();
	});
}

function populateText() {
	var parts = [];
	$("tbody.content tr.guided :input").each(function() {
		var field = $(this);
		if (field.attr("data-omit") != null) return;
		if (field.is(":checkbox") && !this.checked) return;
		var val = "";
		val = field.val() || "";
		if (val.length) {
			if (field.attr("data-type") == "int") {
				var ival = parseInt(val.replace(".", ""));
				if (!isNaN(ival)) val = formatInt(ival);
			}
			if (field.attr("data-prefix")) val = interpolate(field.attr("data-prefix")) + val;
			if (field.attr("data-suffix")) val = val + interpolate(field.attr("data-suffix"));
			parts.push(val);
		}
	});
	$("#textbuf").val(parts.join(", "));
	updatePreview();
}

function updatePreview() {
	var text = $("#textbuf").val();
	var cipher = parseInt($("tbody.options tr.cipher td input:checked").val());
	var layout = parseInt($("tbody.options tr.layout td input:checked").val());
	$("#id_text").val("");
	if (flashPreview) {
		$("#preview").attr("height", "73px");
		flashPreview.reset(layout);
	}
	var buf = [];
	hyphenate(text, layout > 0 ? 40 : 45, layout == 0, function(line, lineNo, hyphen, isLast) {
		if (lineNo >= 30) return;
		if (hyphen && /-$/.test(line)) line = line.substr(0, line.length - 1);
		buf.push(line + "\n");
		if (flashPreview) {
			flashPreview.addLine(lineNo, (line.length > 0 ? line : "\u00A0") + (hyphen ? "-" : ""), cipher == 0 ? isLast : false);
		}
		$("#preview").attr("height", Math.max(1 + 20 * (lineNo + 1), 70) + "px");
		if (isLast) {
			$("#id_text").val(buf.join(""));
			if (cipher > 0) {
				if (flashPreview) {
					flashPreview.addLine(lineNo + 1, "Zuschrift Chiffre " + {2: "A", 3: "Z"}[cipher] + "12345678/x", true);
				}
				$("#preview").attr("height", Math.max(1 + 20 * (lineNo + 2), 70) + "px");
				$("#id_num_lines").val(lineNo + 2);
			} else {
				$("#id_num_lines").val(lineNo + 1);
			}
			updatePriceDisplay();
		}
	});
	updateHtmlPreview(text);
	updateTimer = null;
}

function updateHtmlPreview(text) {
	var params = {
		text: text,
		link_urls: $("#id_link_urls:checked").length,
		cipher: $("tbody.options tr.cipher td input:checked").val()
	};
	$.getJSON("/kleinanzeigen/vorschau/", params, function(data) {
		$("#htmlpreview p").html(data.text);
		$("#linktarget").find("input").val(data.link || "").end().show();
		updateSurchargeDisplay();
	});
}

function updatePriceDisplay() {
	if (priceInfo === null) {
		updatePriceInfo();
		return;
	}
	var pricePerLine = [];
	for (var i = 0; i < 30; i++) pricePerLine[i] = 0;
	var linesPrice = 0;
	var numLines = parseInt($("#id_num_lines").val(), 10);
	var combi = $("#id_combi:checked").length > 0;
	if (combi) {
		var times = Math.max(1, parseInt($("#id_saturday_times").val(), 10));
	}
	for (var weekday in priceInfo) {
		if (!combi) {
			var times = Math.max(1, parseInt($("#id_" + weekday + "_times").val(), 10));
		}
		for (var i = 0; i < 30; i++) {
			var linePrice = priceInfo[weekday].base;
			if (i >= priceInfo[weekday].lines) {
				linePrice += priceInfo[weekday].extra * (i + 1 - priceInfo[weekday].lines);
			}
			linePrice *= times;
			pricePerLine[i] += linePrice;
			if (i == numLines - 1) linesPrice += linePrice;
		}
	}
	priceTotal = pricePerLine[numLines - 1];
	updateTotalPrice();
	if (flashPreview) {
		for (i = 0; i < 30; i++) {
			pricePerLine[i] = "€ " + pricePerLine[i].toFixed(2).replace(".", ",");
		}
		flashPreview.setPricing(pricePerLine);
	}
}

function updatePriceInfo() {
	var params = $("tbody.category select, #combi input, tbody.publication input").serialize();
	$.getJSON("/kleinanzeigen/preis/", params, function(data) {
		priceInfo = data;
		updatePriceDisplay();
	});
}

function updateSurchargeDisplay() {
	if (surchargeInfo === null) {
		updateSurchargeInfo();
		return;
	}
	surchargeTotal = 0.0;

	var combi = $("#id_combi:checked").length > 0;
	var times = combi ? Math.max(1, parseInt($("#id_saturday_times").val(), 10)) : null;
	var layoutCell = $("tbody.options tr.layout td");
	var layout = $("input:checked", layoutCell).val();
	var layoutPrice = 0;
	for (var weekday in surchargeInfo) {
		if (!combi) {
			times = Math.max(1, parseInt($("#id_" + weekday + "_times").val(), 10));
		}
		layoutPrice += surchargeInfo[weekday].layout[layout] * times;
	}
	layoutCell.next().text(layoutPrice ? "+ € " + formatPrice(layoutPrice) : "");
	surchargeTotal += layoutPrice || 0;

	var linkurlsCell = $("tbody.options tr.link_urls td");
	var linkurls = $("input:checked", linkurlsCell).length != 0;
	var linkTarget = $("#id_link_target");
	var linkurlsPrice = 0;
	if (linkurls && linkTarget.val().length) {
		for (var weekday in surchargeInfo) {
			if (!combi) {
				times = Math.max(1, parseInt($("#id_" + weekday + "_times").val(), 10));
			}
			linkurlsPrice += surchargeInfo[weekday].link_urls * times;
		}
		linkTarget.get(0).disabled = false;
	} else if (linkTarget.length) {
		linkTarget.get(0).disabled = true;
	}
	linkurlsCell.next().text(linkurlsPrice ? "+ € " + formatPrice(linkurlsPrice) : "");
	surchargeTotal += linkurlsPrice || 0;

	var cipherCell = $("tbody.options tr.cipher td");
	var cipher = $("input:checked", cipherCell).val();
	var cipherPrice = 0;
	for (var weekday in surchargeInfo) {
		if (!combi) {
			times = Math.max(1, parseInt($("#id_" + weekday + "_times").val(), 10));
		}
		cipherPrice += surchargeInfo[weekday].cipher[cipher] * times;
	}
	cipherCell.next().text(cipherPrice ? "+ € " + formatPrice(cipherPrice) : "");
	surchargeTotal += cipherPrice || 0;

	var imageCell = $("tbody.options tr.image td");
	var image = $("#id_upload", imageCell).val();
	var imageMode = $("input[name=image_mode]:checked", imageCell).val();
	var imagePrice = 0;
	if (image && image.length) {
		for (var weekday in surchargeInfo) {
			if (!combi) {
				times = Math.max(1, parseInt($("#id_" + weekday + "_times").val(), 10));
			}
			imagePrice += surchargeInfo[weekday].image[imageMode] * times;
		}
	}
	imageCell.next().text(imagePrice ? "+ € " + formatPrice(imagePrice) : "");
	surchargeTotal += imagePrice || 0;

	var placeCell = $("tbody.options tr.place td");
	var street = $("#id_place_street", placeCell).val();
	var placePrice = 0;
	if (street && street.length) {
		for (var weekday in surchargeInfo) {
			if (!combi) {
				times = Math.max(1, parseInt($("#id_" + weekday + "_times").val(), 10));
			}
			placePrice += surchargeInfo[weekday].place * times;
		}
	}
	placeCell.next().text(placePrice ? "+ € " + formatPrice(placePrice) : "");
	surchargeTotal += placePrice || 0;

	updateTotalPrice();
}

function updateSurchargeInfo() {
	var params = $("tbody.category select, #combi input, tbody.publication input").serialize();
	$.getJSON("/kleinanzeigen/zuschlag/", params, function(data) {
		surchargeInfo = data;
		updateSurchargeDisplay();
	});
}

function updateTotalPrice() {
	var total = priceTotal + surchargeTotal;
	if (!isNaN(total) && total != 0) {
	  $("#total").text("€ " + (total).toFixed(2).replace(".", ","));
	} else {
	  $("#total").text();
	}
}

function updatePublicationOptions() {
	var combi = $("#id_combi")[0].checked;
	var num = $("tr.publication").length;
	$("tr.publication td").each(function(idx) {
		var checked = $(":checked", this).length > 0;
		var ignored = combi && idx + 1 < num;
		var p = $("p", this);
		$("select:first", p).each(function() {
			var recurring = this.selectedIndex > 0;
			this.disabled = !checked || ignored;
			$(this).next().each(function() {
				this.disabled = !checked || !recurring;
			});
		});
		if (ignored) {
			$("p", this).fadeOut(200);
		} else if (!p.is(":visible")) {
			$("p", this).fadeIn(200);
		}
	});
}

$(document).ready(function() {
	if ($("#flashpreview").length) {
		var qs = $.browser.msie ? "?delayed=1" : "";
		var so = new SWFObject("/media/preview.swf" + qs, "preview", "315", "140", "8", "#ffffff");
		so.useExpressInstall("/media/expressinstall.swf");
		so.addParam("wmode", "transparent");
		so.write("flashpreview");
	}

	$("#id_group, #id_category").change(function() { this.form.submit() });
	$("#id_combi").click(function() {
		updatePublicationOptions();
	});
	$("tbody.publication input").click(function() {
		updatePriceInfo(); updateSurchargeInfo(); updatePublicationOptions();
	});
	$("tbody.publication select").change(function() {
		updatePriceInfo(); updateSurchargeInfo(); updatePublicationOptions();
	});

	try {
		$("tbody.content tr.scripted").css("display", "table-row");
	} catch (e) { // IE
		$("tbody.content tr.scripted").css("display", "block");
	}
	$("#g_freitext_label").text("Zusätzlicher Text/Freitext");
	$("tbody.content tr.guided input.date").datePicker();

	$("tbody.options :checkbox, tbody.options :radio").click(function() {
		updateSurchargeDisplay();
	});
	$("tbody.options tr.layout :radio, tbody.options tr.cipher :radio").click(function() {
		updatePreview();
	});
	$("#id_link_urls").click(function() {
		updateHtmlPreview($("#textbuf").val());
	});
	$("#id_image").change(function() {
		var thumb = $("#thumbnail");
		$("form.submit").ajaxSubmit({url: "/kleinanzeigen/upload/", type: "POST",
			iframe: true,
			success: function(response) {
				if (!/^<img/i.test(response)) {
					alert($(response).text());
					$("#id_image").val("");
					return;
				}
				var img = $(response);
				thumb.find("img, span").remove().end().prepend(img);
				$("#id_upload").val(img.attr("src"));
				$("#id_image").val("");
				$("#clear_image").get(0).disabled = false;
				updateSurchargeDisplay();
			}
		});
	});
	$("#clear_image").click(function() {
		$("#id_image").val("");
		$("form.submit").ajaxSubmit({url: "/kleinanzeigen/upload/", type: "POST",
			success: function(response) {
				$("#thumbnail img").fadeOut("fast", function() {
					$("#thumbnail span").text("Kein Bild");
					$(this).remove();
				});
				$("#id_upload").val("");
				this.disabled = true;
				updateSurchargeDisplay();
			}
		});
		return false;
	});
	$("tbody.options tr.place input").change(function() {
		updateSurchargeInfo();
	});

	var previousValues = {};
	function enqueueTextUpdate(ident, value) {
		if (value != previousValues[ident]) {
			previousValues[ident] = value;
			clearTimeout(updateTimer);
			updateTimer = setTimeout("populateText()", 500);
		}
	}
	$("tbody.content tr.guided")
		.find(":text, textarea").keyup(function() {
			enqueueTextUpdate(this.name, this.value);
		}).end()
		.find(":text, textarea").bind("dragend", function() {
			enqueueTextUpdate(this.name, this.value);
		}).end()
		.find(":text, textarea").bind("paste", function() {
			enqueueTextUpdate(this.name, this.value);
		}).end()
		.find(":text, textarea").bind("input", function() {
			enqueueTextUpdate(this.name, this.value);
		}).end()
		.find("input.date, :text, textarea").change(function() {
			enqueueTextUpdate(this.name, this.value);
		}).end()
		.find("select").change(function() {
			enqueueTextUpdate(this.name, this.selectedIndex);
		}).end()
		.find(":checkbox, :radio").click(function() {
			enqueueTextUpdate(this.name + this.value, this.checked);
		});

	updateSurchargeDisplay();
	updatePublicationOptions();
	updateTimer = setTimeout(populateText, 500);
});
