$(document).ready(function() {
	// Code for the voucher-selector
	$('table.Products.Selector tr.ProductEdition').each(function() { // foreach ProductEdition
		var peID = parseInt($(this).attr('id').substr(2)); // get the productedition id
		var amountChanger = $(this).find('select.AmountChanger');
		var price = $(this).find('td.Price');
		var vouchers = $(this).find('td.Vouchers');
		
		
		// Is called whenever we click on a button to purchase a voucher
		var voucherClick = function(jEv) {
			jEv.preventDefault();
			// $(this) == a element
			var amount = amountChanger.find('option:selected').attr('value');
			var pevID = parseInt($(this).attr('id').substr(3));
			var result = PurchaseVoucher(pevID, amount);
			//amountChanger.change(); // do an ajax update
			// instead of an ajax update, do a page refresh (for the basket refreshment)
			//window.location.reload();
			window.location= AbsPath + 'winkelmand/';
			return false;
		};
		
		// Is called whenever we click on the reservation button
		var reservationClick = function(jEv) {
			jEv.preventDefault();
			// Do: open overlay object (where we can reserve the productedition
			var amount = amountChanger.find('option:selected').attr('value');
			OverlayObject.open( peID, amount );
			return false;
		};
		
		amountChanger.bind('change', function() {
			// Update the price
			var amount = amountChanger.find('option:selected').attr('value');
			var value = ShoppingCartGetPrice(peID, amount, true);
			price.html('&euro; ' + value);
			
			// Update the vouchers
			var html = GetVouchers(peID, amount);
			vouchers.html(html);
			
			vouchers.find('a.Bon.Purchase').each(function() {
				if ( $(this).data('old') == undefined ) {
					$(this).data('old', true);
					$(this).bind('click', voucherClick);
				}
			});
			
			vouchers.find('a.Bon.Reserve').each(function() {
				if ( $(this).data('old') == undefined ) {
					$(this).data('old', true);
					$(this).bind('click', reservationClick);
				}
			});
		});
		
		vouchers.find('a.Bon.Purchase').bind('click', voucherClick).each(function() {
			$(this).data('old',true); // set this var to true so we'll no we already had it
		});
		vouchers.find('a.Bon.Reserve').bind('click', reservationClick).each(function() {
			$(this).data('old',true); // set this var to true so we'll no we already had it
		});
		
	});
});

function doPayment() {
	var elems = document.getElementsByName('paymenttype');
	for ( var i = 0; i < elems.length; i++ ) {
		if (elems[i].checked == true ) {
			var id = elems[i].id.substr(4);
			var value = elems[i].value;
			var req = jQuery.ajax({
				async: false,
				cache: false,
				url: AbsPath + "includes/SpecialPages/Order/Ajax.php",
				data: {cls:value,id:id},
				dataType: 'text'
			});
			if ( req.responseText != 'succes' ) {
				alert('Er is een onbekende fout opgetreden: ' + req.responseText);
			} else {
				$('#' + value).submit(); // submit the correct form.
			}
			return;
		}
	}
	alert('Kies eerst een betaalmethode!');
}

function AddToShoppingCart(pe, count)
{
	vars="op=add" + "&pe=" + pe + "&count=" + count;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}

function RemoveFromShoppingCart(idx)
{
	vars="op=del" + "&index=" + idx;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}

// Remove a specific voucher from a specific orderline (combi only)
function RemoveVoucherFromProduct(idx)
{
	vars="op=removevoucher" + "&idx=" + idx;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}

function AddVoucherToShoppingCart(voucher, count)
{
	vars="op=addvoucher" + "&voucher=" + voucher + "&count=" + count;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}

function PurchaseVoucher(voucher, amount)
{
	vars="op=purchasevoucher" + "&voucher=" + voucher + "&count=" + amount;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}

function GetVoucherValue2(voucher, amount)
{
	vars="op=getvouchervalue2" + "&voucher=" + voucher + "&count=" + amount;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}

//returns all vouchers (or reservation button) in HTML markup
function GetVouchers(pe, amount) 
{ 
	vars="op=getvouchers" + "&pe=" + pe + "&amount=" + amount;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
  	return response;	
}

function ShoppingCartAddExtra(idx, extra)
{
	vars="op=extra" + "&index=" + idx + "&extra=" + extra;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;
}

function ShoppingCartGetExtraPrice(pe, extra, count)
{
	vars="op=extraprice" + "&pe=" + pe + "&extra=" + extra + "&count=" + count;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}

	response = response.replace(/["\\]/g,'');

  	return response;
}

function ShoppingCartGetPrice(pe, count, formatted)
{
	vars="op=getprice" + "&pe=" + pe + "&count=" + count + "&formatted="+(formatted?'true':'false');
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}

	response = response.replace(/["\\]/g,'');

  	return response;
}

function getVoucherValue(pe, voucher, count)
{
	vars="op=getvouchervalue" + "&pe=" + pe + "&voucher=" + voucher + "&count=" + count;
	url= AbsPath + 'winkelmand/ops.php';

	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}
	response = response.replace(/["\\]/g,'');

  	return response;	
}
function ShoppingCartGetProductEditionPrice(pe)
{
	vars="op=extraprice" + "&pe=" + pe + "&extra=" + extra + "&count=" + count;
	url= AbsPath + 'winkelmand/ops.php';

	alert('FIXME ShoppingCartGetProductEditionPrice');
	xmlhttp = getHTTPObject();

	xmlhttp.open("POST", url, false);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(vars);
	response = xmlhttp.responseText;
	if (typeof(response) == "undefined" || response == 'null') {
		return false;
	}

	response = response.replace(/["\\]/g,'');

  	return response;
}

function ToggleVisibility(id)
{
	var elem = document.getElementById(id);
	if (elem == null)
		return;
	elem.style.display = (elem.style.display == "none") ? "block" : "none";
}

function ToggleVisibilityCancel(id,id2) {
	var elem = document.getElementById(id);
	if (elem == null)
		return;
	elem.style.display = (elem.style.display == "none") ? "block" : "none";
	
	var elem2 = document.getElementById(id2);
	if (elem2 == null)
		return;
	elem2.style.display = (elem2.style.display == "none") ? "block" : "none";
}

function toggleBlock( BlockName ) {
	var Head = document.getElementById( BlockName + 'Header' );
	var Content = document.getElementById( BlockName + 'Content' );
	
	if ( Content && Head ) {
		Head.className = ( Head.className == 'Open' ) ? 'Closed' : 'Open';
		Content.className = ( Content.className == 'Show' ) ? 'Hide' : 'Show';
	}
}

function number_format(number, decimals, dec_point, thousands_sep)
{
	 var n = !isFinite(+number) ? 0 : +number, 
		        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
		        s = '',
		        toFixedFix = function (n, prec) {
		            var k = Math.pow(10, prec);
		            return '' + Math.round(n * k) / k;        };
		    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
		    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
		    if (s[0].length > 3) {
		        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
		    if ((s[1] || '').length < prec) {
		        s[1] = s[1] || '';
		        s[1] += new Array(prec - s[1].length + 1).join('0');
		    }    return s.join(dec);

}

function UpdateProductEditionPrice(pe, count, idname)
{
	var itemvalue = 0.00;
	var extras = document.getElementById(idname);
	var itemvalue = parseFloat(ShoppingCartGetPrice(pe, count));

	if (extras == null)
		return itemvalue;
	
	var boxes = extras.getElementsByTagName('input');	
	
	for (i = 0; i < boxes.length; i++) {
		var box = boxes[i];
		if (box.getAttribute('type') != 'checkbox')
			continue;

		elems = extras.getElementsByTagName('*');
			
		var extra;
		var id;
		for (j = 0; j < elems.length; j++) {
			if (elems[j].getAttribute('name') != box.getAttribute('name'))
				continue;
			if (elems[j].getAttribute('type') == 'checkbox')
				extra = elems[j].name;
			if (elems[j].getAttribute('type') == 'text')
				id = elems[j].getAttribute('id'); 				
		}
		var elem = document.getElementById(id);
		var extra_price = ShoppingCartGetExtraPrice(pe, extra, count);
		elem.value = number_format(extra_price, 2, ',', '.' );
			
		if (box.checked) {
			itemvalue = itemvalue + parseFloat(extra_price);
		}
	}
		
	return itemvalue;
}

function UpdateTotalPrice( ItemPriceID, Price ) {
	itemprice = document.getElementById( ItemPriceID );
	itemprice.innerHTML = '&euro; ' + number_format( Price, 2, ',', '.' );
}

function RemoveUpload( UploadID ) {
	$('#UploadInput' + UploadID ).html('');
	$('#DeleteLink' + UploadID ).html('');
}

