var cart = new Array();

$(document).ready(function() {
	updateCartDisplay();
});

function addToCart(id,price)
{
	if (typeof(id) == 'string')
	{
		id = parseInt(id);
	}
	if (typeof(price) == 'string')
	{
		price = parseFloat(price);
	}
	
	var obj = new Object();
	obj.id = id;
	obj.price = price;
	cart.push(obj);
	
	updateCartDisplay();
	updateForm();
}

function getTotal()
{
	var total = 0;
	for (var i = 0; i < cart.length; i++)
	{
		total += cart[i].price;
	}
	return total;
}

function updateCartDisplay()
{
	if (cart.length > 0) {
		var total = getTotal();
		var str = cart.length + ' Artikel, Gesamt: ' + number_format(total, 2, ",", ".") + ' EUR';
	} else {
		var str = "Ihr Warenkorb ist noch leer.";
	}
	$('#SpnCart').html(str);
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function updateForm()
{
	$('#count').val(cart.length);
	for (var i = 0; i < cart.length; i++)
	{
		$("#cartform").append("<input type='hidden' name='tx_mlshop_pi1[id"+i+"]' value='"+cart[i].id+"'>");
		$("#cartform").append("<input type='hidden' name='tx_mlshop_pi1[price"+i+"]' value='"+cart[i].price+"'>");
	}
}

function updateCheckout(pid) 
{ 
	$('#mainform').attr('action','index.php?id=' + pid + '&no_cache=1&tx_mlshop_pi1[action]=updatecheckout'); 
	document.mainform.submit(); 
}

function removeItem(pid, id)
{
	$("#mainform").attr("action","index.php?id=" + pid + "&no_cache=1&tx_mlshop_pi1[action]=removeitem&tx_mlshop_pi1[id]=" + id);
	document.mainform.submit();
}
function overview(pid)
{
	$('#mainform').attr('action','index.php?id=' + pid + '&no_cache=1&tx_mlshop_pi1[action]=overview'); 
	document.mainform.submit(); 
}
function validate(pid)
{
	validated = true;
	
  	$(':input', $('#mainform')).each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		var elclass = $(this).attr('class');
		if ((type == 'text' || tag == 'textarea') && elclass.indexOf('required') >= 0 && this.value.length == 0 && validated)
		{
			$(this).addClass("invalid");
			$('#validation-summary').html("Fehler! Bitte füllen Sie alle Pflichfelder (*) aus.");
			//alert(this.name + ": " + $(this).attr('class'));
			validated = false;
		}
		else if (validated && elclass.indexOf('invalid') >= 0)
		{
			$(this).removeClass("invalid");
		}
	});
	
	// Check Specific Fields
	// Email
	if (validated)
	{
		var value = $("input[name=tx_mlshop_pi1[InvEmail]]").val();
		if (!isValidEmailAddress(value))
		{
			$('#validation-summary').html("Fehler! Bitte tragen Sie eine gültige Email-Adresse ein.");
			validated = false;
		}
	}
	// EmailValidate
	if (validated)
	{
		if ($("input[name=tx_mlshop_pi1[InvEmail]]").val() != $("input[name=tx_mlshop_pi1[InvEmailValidate]]").val())
		{
			$('#validation-summary').html("Fehler! Ihre Email-Adressen stimmen nicht überein.");
			validated = false;
		}
	}
	
	if (validated)
	{
		$('#mainform').attr('action','index.php?id=' + pid + '&no_cache=1&tx_mlshop_pi1[action]=summary'); 
		document.mainform.submit(); 
	}
	else
	{
	}
	
}
function checkout()
{
	if (cart.length > 0)
	{
		updateForm();
		document.cartform.submit();
	}
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function finish(pid)
{
	var value = $("input[name=tx_mlshop_pi1[AcceptTC]]:checked").val();
	if (value == null)
	{
		$('#validation-summary').html("Fehler! Bitte stimmen Sie unseren allgemeinen Geschäftsbedingungen zu, um die Bestellung abzuschließen.");
	}
	else
	{
		document.mainform.submit();
	}
}
