$(document).ready(function()
{
	getShopcart()
});

var shopcartSummaryExpireCookie;

function getShopcart()
{
	setShopcartBusy(true);
	if(getCookie('shopcart')&&shopcartSummaryExpireCookie!=true)
		displayShopcart($.parseXML(getCookie('shopcart')));
	else
		getAJAXData(getTranslatedString('ctxtPath')+'/shopcartSummary.do', 'getShopcartSuccess');
}
function addShopcart(art_id, attr1_id, attr2_id, attr3_id, qty)
{
	if($('#headershopcart').data('busy'))
		return;
	setShopcartBusy(true);
	$('#headershopcart').data('isadding', true);

	postAJAXData(getTranslatedString('ctxtPath')+'/modules/articleShopcartAdd.do', 'getShopcartSuccess', 'art_id='+art_id+'&attr1_id='+attr1_id+'&attr2_id='+attr2_id+'&attr3_id='+attr3_id+'&qty='+qty);
	$('#artdetailaddtocart').html('Köp')
}

function getShopcartSuccess(xml)
{
	if($(xml).find('shopcart').find('error').length>0)
		alert($(xml).find('shopcart').find('error').text());
	delCookie('shopcart');
	setCookie('shopcart', xml.xml ? xml.xml : (new XMLSerializer()).serializeToString(xml), getTranslatedString('shopcartSummaryExpireCookieMinutes'));
	displayShopcart(xml);
}

function displayShopcart(xml)
{

	$('#headershopcart').html($(xml).find('shopcart').find('message').text()!=''?$(xml).find('shopcart').find('message').text():'<!--v:message code="TRANSLATION"/-->Kundkorg ('+$(xml).find('shopcart').find('summary').find('qty').text()+') '+$(xml).find('shopcart').find('summary').find('tot_rowsum_to_pay').text());
	if($('#headershopcart').data('isadding')===true)
	{
		displayShopcartAdded(xml);
		return;
	}
	setShopcartBusy(false);
}
function displayShopcartAdded(xml)
{
	$('#headershopcart').data('isadding', false);
	if(!$(xml).find('shopcart').find('contents').find('justadded').text()=='true')
	{
		setShopcartBusy(false);
		return;
	}
	$(xml).find('shopcart').find('contents').find('justadded').text()

	$('<div></div>')
		.attr('id', 'headershopcartadded')
		.html('Lade '+$(xml).find('shopcart').find('contents').find('justadded').first().find('qty').text()+' st '+$(xml).find('shopcart').find('contents').find('justadded').first().parent().find('artname').text()+' i Korgen')
		.appendTo('#headershopcart')
		.fadeIn(200).delay(3000).fadeOut(100, function()
		{
			$(this).remove();
			setShopcartBusy(false);
		});

		
	
	
	
}

function setShopcartBusy(val)
{
	if($('#headershopcart').data('busy')===val)
		return;

	$('#headershopcart').data('busy', val);
	if(val)
		$('#headershopcart').addClass('headershopcartbusy');
	else
		$('#headershopcart').removeClass('headershopcartbusy');

}

//TODO: Expire cookies after X minutes

