// xajax loader
if(typeof xajax != 'undefined')
{
	xajax.callback.global.onRequest = function() {
		xajax.$('cartLoading').style.display = 'inline';
	};
	xajax.callback.global.beforeResponseProcessing = function() {
		xajax.$('cartLoading').style.display = 'none';
	};
}


$(document).ready(function () {
	checkRequiredVisual();
	$(".required").blur(checkRequiredVisual);
	$(".valinta").change(calcSum);
	$('#view_delivery').click(function(){
		if($(this).is(':checked'))
		{
			$('#delivery_address').show();
		}
		else
			$('#delivery_address').hide();
	});

	$(".hilight").hover(
		function(){
			$(this).css("background-position", "0 -" + $(this).height() + "px");
		},
		function(){
			$(this).css("background-position", "0 0");
		}
	);

	$("div#scrollable").smoothDivScroll({
		scrollingSpeed: 1,
		mouseDownSpeedBooster: 3,
		visibleHotSpots: "always",
		startAtElementId: "startAtMe"
	});

	$('#social').css('display', 'none');
	$('select[name=pay_method]').change(function(){
		if($(this).val() == 4)
			$('#social').css('display', 'block').children('input').addClass("required");
		else
			$('#social').css('display', 'none').children('input').removeClass("required");

		checkRequiredVisual();
	});

	$('input[name=social]').change(function(){
		var reg = /^(\d{7}\-\d|\d{6}\-\d{3}.)$/i;
		if(!reg.test($(this).val()))
		{
			alert("Y-tunnus / Henkilötunnus on väärää muotoa. Väärän tunnisteen antaminen estää tilaamisen laskulla.");
		}
	});
	
});

function orderDone()
{
	$('#orderDone:visible').fadeOut('fast');
	$('#orderDone .amount_info').text($('#cart_placeholder').text() + '.');
	$('#orderDone').fadeIn('fast');
	return false;
}

function calcSum()
{
	xajax_updateSum(xajax.getFormValues('orderForm'));
}

function quickAddToCart(id, _type, elm)
{
	xajax_updateCart(id, {order_amount:document.getElementById("p" + id).value, type: _type, product_id:id});
	$(elm).replaceWith('<strong>Lisätty!</strong>');
	return false;
}

function removeFromCart(id)
{
	xajax.call( "removeCart",  {parameters: [ id ], mode: "synchronous"} );
	location.reload(true);
	return false;
}

function checkRequiredVisual()
{
	$(".required").each(function(){
		if(this.value == undefined || this.value == ''){
			$(this).removeClass("required_ok");
			$(this).addClass("required_wrong");
		}
		else
		{
			$(this).removeClass("required_wrong");
			$(this).addClass("required_ok");
		}
	});
}

function checkRequired()
{
	var valid;
	valid = false;

	$(".required").each(function(){
		if(this.type == "checkbox")
		{
			if(!this.checked)
			{
				valid = false;
				alert("Arvo puuttuu: " + $(this).attr('rel'));
				return false;
			}
		}
		else
		{

			if(this.value == undefined || this.value == ''){
				valid = false;
				alert("Arvo puuttuu: " + $(this).attr('rel'));
				return false;
			}
		}

		valid = true;
		return true;
	});

	return valid;
}
