jQuery(function($) {
	//var $ = jQuery;
	var totalRow = $("<tr></tr>").addClass('total-row');
	var totalCol = $("<td colspan='4' class='total-col' />").appendTo(totalRow);
	var totalHolder = $("<span />").addClass('total-holder').text(gettext("Total: ")).appendTo(totalCol);
	var total = $("<span id='ordertotal' />").appendTo(totalHolder);
	var newBtn = $("<a href='#' />").addClass('new-row').text(gettext("New order row...")).appendTo(totalCol);
	
	var items = $(".frmset-order_row_formset .fld-item select");
	var counts = $(".frmset-order_row_formset .fld-count select");
	var sizes = $(".frmset-order_row_formset .fld-size select");
	var oldTotal = 0;
	var totalMoney = 0;
	var failedMoney = false;
	var validator;
	var info = $("#id_info-info");
	var FILL_THE_ADDITIONAL = gettext("FILL THE ADDITIONAL DETAILS FROM MENU HERE");
	
	function calculateTotal() {
		totalMoney = 0;
		items.each(function (i, item) {
			var id = $(item).val();
			var count = parseInt($(counts[i]).val());
			var size = parseInt($(sizes[i]).val());
			var money = 0;
			if (!count) {
				count = 0;
			}
			if (ORDER_PRICES[id] && ORDER_PRICES[id][size]) {
				money = ORDER_PRICES[id][size];
			}
			totalMoney += money * count;
		});
		return totalMoney;
	}
	
	function setCounts(countEl, min, max) {
		if (countEl.find('option').eq(1).text() == min &&
			countEl.find('option').eq(-1).text() == max) {
			return;
		}
		var oldVal = countEl.val();
		
		countEl.find('option').remove();
		$("<option value='0'>0</option>").appendTo(countEl);
		for (var i=min; i<=max; i++) {
			$("<option value='"+i+"'>"+i+"</option>").appendTo(countEl);
		}
		
		if (countEl.find('option[value='+oldVal+']').length) {
			countEl.val(oldVal);
		} else {
			countEl.val(countEl.find('option').eq(1).val()); // First option
			animateOutline(countEl);
		}
	}
	
	function setSizes(sizeEl, prices) {
		var oldVal = sizeEl.val();
		sizeEl.find('option').remove();
		
		if (!prices || prices[0]) {
			$("<option value='0'>"+gettext('Normal')+"</option>").appendTo(sizeEl);
		}
		if (!prices || prices[1]) {
			$("<option value='1'>"+gettext('Big')+"</option>").appendTo(sizeEl);
		}
		if (!prices || prices[2]) {
			$("<option value='2'>"+gettext("Kids")+"</option>").appendTo(sizeEl);
		}
		
		if (sizeEl.find('option[value=' + oldVal + ']').length) {
			sizeEl.val(oldVal);
		} else {
			sizeEl.val(sizeEl.find('option').eq(0).val()); // First option
			if (prices) {
				animateOutline(sizeEl);
			}
		}
		if (sizeEl.find('option').length == 1 || !prices) {
			sizeEl.attr('disabled', 'disabled');
		} else {
			sizeEl.attr('disabled', '');
		}
	}
	
	function animateOutline(el) {
		el.css({
			outline: '0px solid #B90715'
		});

		el.animate({
			outlineWidth: '5px'
		}, 300, 'linear');
		
		setTimeout(function () {
			el.stop().animate({
				outlineWidth: '0px'
			}, 600, 'linear', 
			function () {
				el.css({outline: ''});
			});
		}, 300);
	}
	
	function updateTotals() {
		var moneyTotal = calculateTotal();
		var moneyTotalText = ("" + moneyTotal.toFixed(2)).replace(".", ",");
		total.html(moneyTotalText + "&nbsp;&euro;");
		if (oldTotal != moneyTotal) {
			if (validator && failedMoney) {
				validator.reset();
				validator.checkValidity();
			}
		}
		oldTotal = moneyTotal;
		return false;
	}
	
	function itemChange(i, item) {
		var countEl = counts.eq(i);
		var sizeEl = sizes.eq(i);
		var count = countEl.val();
		var menuitemid = null;
		var itemid = $(item).val();
		var match = itemid.match(/(\d+)-?/);
		if (match) {
			menuitemid = match[1];	
		}
		
		if (ORDER_INFOS[menuitemid]) {
			var oldText = info.val();
			if (oldText) {
				oldText = info.val() + "\n\n";	
			}
			
			var itemText = $(item).find(":selected").text().match("(.*) -")[1];
			info.val(oldText + itemText + ":\n"+FILL_THE_ADDITIONAL)
			animateOutline(info);
		}
		
		var order_min = ORDER_MIN;
		if (ORDER_MINS[menuitemid]) {
			order_min = ORDER_MINS[menuitemid];
		}
		
		var order_max = ORDER_MAX;
		if (ORDER_MAXES[menuitemid]) {
			order_max = ORDER_MAXES[menuitemid];
		}
		
		setCounts(countEl, order_min, order_max);
		setSizes(sizeEl, ORDER_PRICES[itemid]);
		
		if (menuitemid) {
			if (count == '0') {
				countEl.val(countEl.find('option').eq(1).val()); // Set as first option
				animateOutline(countEl);					
			}
		} else {
			countEl.val("0");
		}
	}
	
	function countChange(i, countEl) {

		var count = countEl.val();
		if (count == '0') {
			setCounts(countEl, ORDER_MIN, ORDER_MAX);
			$(items[i]).val('').change();
		}
	}
	
	function nowChanges() {
		if ($("#id_info-now:checked").length) {
			$("#id_info-time").val('');
			$("#id_info-time").attr('disabled', 'disabled');
		} else {
			$("#id_info-time").attr('disabled', '');
		}
	}
	
	$("#id_info-now").change(nowChanges).click(nowChanges);

	items.each(function (i, item) {
		$(item).change(function () {
			itemChange(i, item);
		});
	});
	
	counts.each(function(i, countEl) {
		var countEl = $(countEl);
		countEl.change(function () {
			countChange(i, countEl);
		});
	});
		
	// There is a bug in webkit chrome:
	// 
	// If you have select box with multiple values, and after sending the form
	// the webkit remembers the *relative* position of selected value (not the 
	// value itself!) and thus when you click back button and the select box 
	// item count differs then the back function in webkit cannot replicate sent 
	// form.
	counts.change();
	items.change();
	
	nowChanges();
	
	
	function hookRow(jqElement) {
		jqElement.change(updateTotals).click(updateTotals).keyup(updateTotals);
	}
	
	$(".frmset-order_row_formset .row:last-child").after(totalRow);
	hookRow($(".frmset-order_row_formset select"));
	
	updateTotals(true);
	
	var newRows = 0;
	newBtn.click(function () {
		newRows++;
		var newRow = $(".frmset-order_row_formset .row:last").stop(true, true).clone();
		var newRowHtml = newRow.html();
		var numberMatch = newRowHtml.match(/rows-(\d+)-/);
		if (numberMatch) {
			var number = parseInt(numberMatch[1]) + 1;
			
			newRowHtml = newRowHtml.replace(/rows-(\d+)-/g, "rows-" + number + "-");
			newRowHtml = newRowHtml.replace(number + ".", number+1 + ".");
			newRow.html(newRowHtml);
			$(".frmset-order_row_formset .row:last").after(newRow);
			
			hookRow(newRow.find('select'));
			items = $(".frmset-order_row_formset .fld-item select");
			counts = $(".frmset-order_row_formset .fld-count select");
			sizes = $(".frmset-order_row_formset .fld-size select");

			newRow.find('.fld-count select').change(function () {
				countChange(number, $(this));
			});
			newRow.find('.fld-item select').change(function () {
				itemChange(number, $(this));
			});
			newRow.find('option:selected').attr('selected', '');
			newRow.find('.fld-item select').val('').change();
			
			$("#id_rows-TOTAL_FORMS").val(number+1);
			
			if (number == 19) {
				newBtn.hide(0);
			}
		}
		
		return false;
	});
	
	// Firefox bug/feature: browser refresh tries to remember the value which is
	// a rather annoying behavior for dynamically created form fields.
	var actualRowCount = $(".frmset-order_row_formset .row").length
	var sentRowCount = $("#id_rows-TOTAL_FORMS").val();
	if (sentRowCount > actualRowCount) {
		for (var i = 0; i < sentRowCount - actualRowCount; i++) {
			newBtn.click();
		}
	}
	
	function var_(str) {
		return str.replace("__", "$"); // $ sign causes error for makemessages
	}
	
	// Form specific validators:
	$.tools.validator.fn("#id_info-time", function(el, value) {
		return (/^\d\d:\d\d$/.test(value) || value === "") ? true : gettext("Invalid time format, must be HH:MM");
	});
	
	var checkValidityRadio = function () {
		validator.reset();
		validator.checkValidity();
	}
	
	$.tools.validator.fn("[name=info-take_away]", function(el, value) {
		var checkvalue = $("input[name=info-take_away]:checked").val();
		$("input[name=info-take_away]").unbind('click', checkValidityRadio);
		$("input[name=info-take_away]").click(checkValidityRadio);
		
		if ((value == "0") && (checkvalue == "0") && (totalMoney < ORDER_DELIVERY_MIN_PRICE)) {
			failedMoney = true;
			return gettext('Minimum price for home delivery is __1 eur.')
				.replace("__1", ORDER_DELIVERY_MIN_PRICE);
		}
		if ((value == "0") && (checkvalue == "0")) {
			failedMoney = false;
		}
		return true;
	});
	
	$.tools.validator.fn("#id_info-info", function(el, value) {
		return !value.match(FILL_THE_ADDITIONAL) ? true : gettext("Fill the field appropriately");
	});
	
	// General validation
	$.tools.validator.localize("django", {
		'*' : gettext("Please correct this value"),
		':email' : gettext("Please enter a valid email address"),
		':number' : gettext("Please enter a numeric value."),
		':url' : gettext("Please enter a valid URL"),
		'[max]' : var_(gettext("Please enter a value smaller than __1")),
		'[min]' : var_(gettext("Please enter a value larger than __1")), 
		'[required]' : gettext("Please complete this mandatory field.")  
	});
	$(".form-row.required input").attr('required', 'required');
	
	validator = $("#orderform").attr('novalidate', '1').validator({
		'lang' : 'django', 
		'message' : '<div><em /></div>',
		'position': 'top center', 
		'messageClass' : 'jq-error'
	}).data('validator');
	
	
	$("#popuporder a").click(function () {
		window.open(''+$(this).attr('href'),'mywin','width=470,height=600,toolbar=0,resizable=1,scrollbars=1')
		return false;
	});
	
	$(".cat-lounaat a").click(function () {
		window.open(''+$(this).attr('href'),'mywin2','toolbar=0,resizable=1,scrollbars=1')
		return false;
	});
	
});

