// DOM load
$(function()
	{
		$('table.productList input').change(costChange).keyup(costChange);
	}
);

function submitOrder(form, listid)
{
	return validateHonnunarsafn(form, listid);
}


function placeOrder()
{
	var products = '';
	$('table.productList input[value!=]').each(function()
	{
		products +=  +' '+ $(this).val() +' '+ $(this).parent().next().next().next().text() + '| ';
	});

	$('#6cc57e3b-efcb-40f3-873d-7897aef483d2').val( products );
}

function costChange()
{
	var costArea = $(this).parent().next().next().next().next();
	if( typeof($(this).attr('cost'))==='undefined' ) $(this).attr('cost',costArea.text());
                                     
	costArea.text( $(this).attr('cost')*$(this).val() );
}

/* General form-validation */

function validateHonnunarsafn(form, listid) {
	var isValid = true;

	if( listid == '567be450-7a62-4c31-bbce-16d7cb8c85c2' ) 
	{
		placeOrder();
	}
	for (var i = 0; i < form.elements.length; i++) {
		var elem = form.elements[i];
		if (elem.className.indexOf('reqd') > 0) {
			
			/* input, select og textarea er höndlað á sama hátt .... */
			if ((elem.tagName == "INPUT") || (elem.tagName == "TEXTAREA") || (elem.tagName == "SELECT")) {			
				if (elem.className.indexOf('emailval') > 0) {
					isValid = isValidEmail(elem.value);
				} else {
					isValid = (elem.value != '');
				}
				
				if (!isValid) {
					alert(elem.title + ' er ekki rétt útfyllt!');
					elem.focus();
					elem.style.borderColor = '#FF4A4A';
					elem.style.backgroundColor = '#FDFAD0';
					return false;
				} else {
					elem.style.borderColor = '';
					elem.style.backgroundColor = '';
				}
			}			
		}
	}

	return true;
}

function isValidEmail(value) {
	return (value.indexOf(".") > 2) && (value.indexOf("@") > 0);
}

function isValidNumber(value, number) {
	var elemIsValid = true;
	var stripped = value.replace(/[\(\)\.\-\ ]/g, '');
	
	if (!(stripped.length == number)) {
		elemIsValid = false;
	}

	if(isNaN(stripped)) {
	     elemIsValid = false;
   	}

	if (stripped.length == 0) {
		elemIsValid = true;
	}
	
	return elemIsValid;
}

