var cart = new Array();
var coupons = new Array();
var shipping = new Array();
var promo;
var chequesValue = 0;
var maxCartItems = 5;
var freeShipping = 120;


function showCategory(id)
{	
	
	if($('#category'+id).length<1)
		return true;

	if(active_category!=undefined)
	{
		if(active_category.attr('id')==$('#category'+id).attr('id'))
			return false;
			
		active_category.slideUp('fast');
	}

	active_category = $('#category'+id)
	active_category.slideDown('fast');
	return false;
}





// Shopping cart functions

function addToCart(article_id, variation_id, measure_id, listitem_id)
{
	cartItem = getCartItemByArticle(article_id, variation_id, measure_id, listitem_id);

	if(cartItem!=false && !checkStock(cartItem.id, cartItem.amount+1))
		return false;
		
	$.getJSON('/webshop.php', {site: sitedata.id, obj:'cart', a:'add', article_id:article_id, variation_id:variation_id, measure_id:measure_id, listitem_id:listitem_id, language_code:active_language_code}, cartCallback);
	return false;
}

function removeFromCart(id)
{
	$.getJSON('/webshop.php', {site: sitedata.id, obj:'cart', a:'remove', id:id, language_code:active_language_code}, cartCallback);
	return false;
}

function cartAmountPlus(id)
{
	if(!checkStock(id, getCartItem(cart, id).amount+1))
		return false;
		
	cartChangeAmount(id, getCartItem(cart, id).amount+1);
	return false;
}

function cartAmountMin(id)
{
	if(getCartItem(cart, id).amount<2)
		return false;
		
	cartChangeAmount(id, getCartItem(cart, id).amount-1);	
	return false;
}

function cartChangeAmount(id, amount)
{
	$.getJSON('/webshop.php', {site: sitedata.id, obj:'cart', a:'amount', id:id, language_code:active_language_code, amount:amount}, cartCallback);
	return false;
}

function checkStock(id, amount)
{
	var cartItem = getCartItem(cart, id);
	if(amount>cartItem.stock)
	{
		alert(text.error_maxamount.replace('[x]', cartItem.stock));
		return false;
	}

	return true;
}

function cartCallback(data, textstatus)
{
	updateCart(data);
}

function updateCart(newCart)
{
	if(cart.length<1 && newCart.length>0)
	{
		// first item in cart: clear 'no items' content and add container div
		$('#cart > .content').html('<div id="cart_thumbs"></div>'); 
		// add totals container
		$('#cart > .content').append($('<div id="cart_thumbs_total">'));
		// add 'to cart' button
		var toCart = $('<div id="cart_thumbs_checkout">');
		toCart.html('<a class="button" href="/'+urls.cartURL+'"><span>'+text.checkout+'</span></a>');
		/*
var toCartA = $('<a>');
		toCartA.addClass('button');
		toCartA.attr('href', '/'+urls.cartURL);
		toCartA.html(text.checkout);
		toCartA.appendTo(toCart);
*/
		toCart.append($('<div class="clearfix">'));
		toCart.appendTo($('#cart > .content'));
	}
			
	if(newCart.length>maxCartItems)
	{	
		// too many items: show totals instead of thumbs
		
		if($('#cart_thumbs').length>0)
			$('#cart_thumbs').slideUp('slow');
		
		var totalProducts = 0;
			
		for(var i=0;i<newCart.length;i++)
		{
			totalProducts += newCart[i].amount;
		}
		
		if($('#cart_nrItems').length==0)
		{
			var nrItems = $('<div>');
			nrItems.attr('id', 'cart_nrItems');
			$('#cart > .content').prepend(nrItems);	
			$('#cart_thumbs_total').attr('class', 'many_items');
		}

			
		$('#cart_nrItems').text(totalProducts + ' ' + text.itemsincart);
		
	}
	else
	{
		// show thumbs
		var newItem;
		var tag;
		var subtag;
		
		for(var i=0;i<newCart.length;i++)
		{	
			currentCartItem = getCartItem(cart, newCart[i].id);
			
			if(currentCartItem==false)
			{
				//new item
				newItem = $('<div>');
				newItem.attr('class', 'cartitemthumb');
				newItem.attr('id', 'cartitemthumb'+newCart[i].id);
				newItem.css({display:'none'});
				
				//add button to remove item
				removeButton = $('<a>');
				removeButton.attr('href', '');
				removeButton.attr('title', text.removefromcart);
				removeButton.attr('class', 'cartitemthumb_RemoveButton');
				removeButton.click(function(e){return removeFromCart($(e.target).parent().parent().attr('id').substring(13));});
				removeButton.html('<img src="/images/closebutton.gif" width="11" height="11"/>');
				removeButton.appendTo(newItem);
				
				//add image
				tag = $('<img>');
				tag.attr('src', '/skylimit/uploads/' + newCart[i].image);
				tag.attr('class', 'cartitemthumb');
				tag.attr('width', 40);
				tag.attr('height', 40);
				tag.attr('alt',newCart[i].name);
				tag.appendTo(newItem);
				
				//add product description
				tag = $('<div>');
				tag.text(newCart[i].name);
				tag.appendTo(newItem);
				//add amount & price
				tag = $('<div>');
				tag.attr('class', 'amount_price');
				//add amount buttons
				subtag = $('<a href="">');
				subtag.attr('class', 'amountbutton min');
				subtag.text('-');
				subtag.click(function(e){return cartAmountMin($(e.target).parent().parent().attr('id').substring(13));});
				subtag.appendTo(tag);
				subtag = $('<a href="">');
				subtag.attr('class', 'amountbutton plus');
				subtag.text('+');
				subtag.click(function(e){return cartAmountPlus($(e.target).parent().parent().attr('id').substring(13));});
				subtag.appendTo(tag);				
				//add amount
				subtag = $('<div>');
				subtag.attr('class', 'amount');
				subtag.text(newCart[i].amount);
				subtag.appendTo(tag);
				subtag = $('<div>');
				//add price
				subtag.attr('class', 'price');
				subtag.html(' x &euro; ' + newCart[i].price.numberFormat());
				subtag.appendTo(tag);
				tag.appendTo(newItem);
				
				newItem.append('<div class="clearfix">');
				newItem.appendTo('#cart_thumbs');
				
				newItem.slideDown('slow');
				
				
			}
			else if(currentCartItem.amount!=newCart[i].amount)
			{
				// existing item, changed amount
				$('#cartitemthumb'+currentCartItem.id+' > .amount_price > .amount').text(newCart[i].amount);
				
				if($('#cartitem'+currentCartItem.id).length>0)
				{
					$('#amount'+currentCartItem.id).get(0).selectedIndex = newCart[i].amount-1;
					$('#cartitem'+currentCartItem.id+' > .total').html('&euro; ' + (newCart[i].amount*newCart[i].price).numberFormat());
				}
			}
			
			
		}
			
		for(i=0;i<cart.length;i++)
		{
			// remove deleted items
			newCartItem = getCartItem(newCart, cart[i].id);
			
			if(newCartItem==false)
			{
				$('#cartitemthumb'+cart[i].id).slideUp('slow');
				
				$('#cartitem'+cart[i].id).remove();
			}
		}
	}
	
	if(newCart.length<1)
	{
		var empty = $('<div>');
		empty.attr('id', 'cart_thumbs_empty');
		empty.text(text.cartisempty);
		empty.css({display:'none'});
		$('#cart > .content').append(empty);
		empty.slideDown('slow');
		$('#cart_thumbs_total').hide();
		$('#cart_thumbs_checkout').remove();
		
		$('#ubercart').html('<p>'+text.cartisempty+'</p>');
		
	}
	
	cart = newCart;
	
	processTotals();
}

function getCartItem(cartArray, id)
{
	for(var i=0;i<cartArray.length;i++)
	{
		if(cartArray[i].id==id)
			return cartArray[i];
	}
	
	return false;
}

function getCartItemByArticle(article_id, variation_id)
{
	for(var i=0;i<cart.length;i++)
	{
		if(cart[i].article_id==article_id && cart[i].variation_id==variation_id)
			return cart[i];
	}
	
	return false;
}

function getCartSubtotal()
{
	var subtotal = 0;
	var subtotal_discount = 0;
	
	for(i=0;i<cart.length;i++)
	{
		price = Number(cart[i].price) * Number(cart[i].amount);
		subtotal += price;
		
		if(Number(cart[i].no_discount)!=1)
			subtotal_discount += price;
	}
	
	if(promo != undefined)
	{
		promo.amount = subtotal_discount * Number(promo.discount)/100;
		subtotal -= promo.amount;
	}
	
	return subtotal;
}





//coupons

function checkCoupon()
{
	$('#couponform').hideError();
	$.post(document.location.toString()+'/a/check_couponcode', {code:$('#input_couponcode').attr('value')}, couponCallback, "json");
}

function couponCallback(data, textstatus)
{
	if(data!=0)
	{
		switch(data.type)
		{
			case 'coupon':
				processCoupon(data);
				break;
			case 'promo':
				processPromo(data);
				break;
		}		
		
		$('#input_couponcode').attr('value', '');
		processTotals();
	}
	else
	{
		$('#couponform').addError(text.error_coupon);
		$('#input_couponcode').attr('value', '');
	}
}

function processCoupon(data)
{
	coupons.push(data);
		
	if($('#coupon').length==0)
	{
		var tr_coupon = $('<tr class="totals">');
		tr_coupon.append($('<th colspan="4">').html(text.coupon+':'));
		tr_coupon.append(coupon = $('<th class="total" id="coupon">'));
		tr_coupon.append($('<th colspan="2">'))
		tr_coupon.css({display:'none'});
		$('tr.totals:last').before(tr_coupon);
		tr_coupon.fadeIn();
	}
		
	$('#form_cart').append($('<input type="hidden" name="coupon[]">').attr('value', data.code));
}

function getTotalCouponValue()
{
	var cartSubtotal = Number(getCartSubtotal()) + Number(getShippingCost());
	var couponTotal=0;
	var couponValue;
	
	for(var i=0;i<coupons.length;i++)
	{
		couponTotal += Number(coupons[i].value);
	}

	if(couponTotal > cartSubtotal)
	{
		couponValue = cartSubtotal;
		$('#couponform').hide();
		$('#couponform').after($('<p id="couponinfo">').html(text.couponcredit.replace('[x]', (couponTotal-couponValue).numberFormat())));
	}
	else
	{
		couponValue = couponTotal;
		
		if(couponTotal==cartSubtotal)
			$('#couponform').hide();
		else
		{
			$('#couponform').show();
			$('#couponinfo').remove();	
		}
	}
	
	
	return couponValue;
	
}

function processPromo(data)
{
	promo = data;
			
	if($('#promo').length==0)
	{
		var tr = $('<tr class="totals">');
		tr.append($('<th colspan="4">').html(text.discount+' ('+promo.discount+'%):'));
		tr.append($('<th class="total" id="promo">'));
		tr.append($('<th colspan="2">'))
		tr.css({display:'none'});
		$('tr.totals:first').after(tr);
		tr.fadeIn();
		
		$('#form_cart').append($('<input type="hidden" name="promo">').attr('value', data.code));
	}
		
	
}



// (eco)cheques

function addCheques()
{
	$('#chequesform').hideError();
	$.post(document.location.toString()+'/a/add_cheques', {value:$('#input_cheques_value').attr('value')}, chequesCallback, "json");
}


function chequesCallback(data)
{
	if(data.error!=undefined)
	{
		$('#chequesform').addError(data.error);
		$('#input_cheques_value').attr('value', '');
	}
	else
	{
		chequesValue = data.value;
		position = Math.floor($('tr.totals').length/2)-1;
		
		if($('#cheques').length==0)
		{
			var tr = $('<tr class="totals">');
			tr.append($('<th colspan="4">').html(text.cheques+':'));
			tr.append($('<th class="total" id="cheques">'));
			tr.append($('<th colspan="2">'))
			tr.css({display:'none'});
			$('tr.totals:eq('+position+')').after(tr);
			tr.fadeIn();
		}
		
		$('#chequesform').hide();
			
		$('#form_cart').append($('<input type="hidden" name="cheques[]">').attr('value', data.value));
		
		processTotals();
	}
}


// Shipping

function updateShipping()
{
	$.post(document.location.toString()+'/a/get_shippingcosts', {country:$('#select_shippingcountry option:selected').val()}, shippingCallback, 'json');
}

function shippingCallback(data, textstatus)
{
	shipping = data;
	
	processTotals();
}

function getShippingCost()
{	
	var country = $('#select_shippingcountry option:selected').val();
		
	if(($('#check_pickup').length>0 && $('#check_pickup').get(0).checked) 
		|| ((country=='be'||country=='nl'||country=='lu') && getCartSubtotal()>=freeShipping)
		|| ($('#list_deliver').length && $('#list_deliver').get(0).checked && cartHasListItems() && !cartHasNonListItems()))
		return 0;
		
	var weight = getWeight();
		
	for(var i=0;i<shipping.length;i++)
	{
		if(weight <= shipping[i].weight)
		{
			return shipping[i].cost;
		}
	}
}

function cartHasListItems()
{
	for(var i=0;i<cart.length;i++)
	{
		if(cart[i].listitem_id>0)
			return true;
	}
	
	return false;
}

function cartHasNonListItems()
{
	for(var i=0;i<cart.length;i++)
	{
		if(cart[i].listitem_id==0)
			return true;
	}
	
	return false;
}

function getWeight()
{
	var weight = 0;
	
	for(i=0;i<cart.length;i++)
	{
		weight += cart[i].weight * cart[i].amount;
	}
	
	return weight;
}




// Cart totals calculation

function processTotals()
{
	var subtotal = Number(getCartSubtotal());
	var shipping = Number(getShippingCost());
	var coupon = Number(getTotalCouponValue());
	
	var total = subtotal + shipping - coupon - chequesValue;
	
	$('#cart_thumbs_total').html(text.total + ': &euro; ' + subtotal.numberFormat());
	$('#subtotal').html('&euro; ' + subtotal.numberFormat());
	$('#shipping').html('&euro; ' + shipping.numberFormat());
	$('#coupon').html('&euro; -' + coupon.numberFormat());
	if(promo!=undefined)
		$('#promo').html('&euro; -' + promo.amount.numberFormat());
	$('#cheques').html('&euro; -' + chequesValue.numberFormat());
	$('#total').html('&euro; ' + total.numberFormat());

}






// Login 'n stuff

function loginBox(frm)
{
	$('#loginbox > .content').load('/webshop.php?' + $(frm).serialize()+'&site='+sitedata.id+'&obj=user&a=loginbox_login&language_code='+active_language_code);

	return false;
}

function logoff()
{
	
	$('#loginbox > .content').load('/webshop.php?site='+sitedata.id+'&obj=user&a=loginbox_logoff&language_code='+active_language_code);

	return false;
}


function loginCheckout(frm)
{
	$('#contactdata_login .error').hide();
	$.post('/webshop.php?site='+sitedata.id+'&obj=user&a=login', $(frm).serialize(), loginCallback, "json");

	return false;
}

function loginCallback(data, textstatus)
{
	if(data==0)
	{
		// not logged in
		$('#contactdata_login .error').slideDown();
	}
	else
	{
		//logged in
		
		$('#input_firstname').attr('value', data.firstname.value);
		$('#input_lastname').attr('value', data.lastname.value);
		$('#input_email').attr('value', data.email.value);
		$('#input_street').attr('value', data.street.value);
		$('#input_nr').attr('value', data.nr.value);
		$('#input_box').attr('value', data.box.value);
		$('#input_zip').attr('value', data.zip.value);
		$('#input_city').attr('value', data.city.value);
		$('#input_tel').attr('value', data.tel.value);
		
		$('#select_country option').each(function(){
			if(this.value==data.country.value)
				this.selected = 'selected';
		});
		
		$('#contactdata_login').slideUp('fast');
		$('#newpassword').remove();
		$('#contactdata legend.yourcontactdata').remove();
		
		$('#loginbox > .content').load('/webshop.php?site='+sitedata.id+'&obj=user&a=loginbox_html&language_code='+active_language_code);
	}
	
	
}

function validateContactdata(frm, url)
{
	$('.img_warning').remove();
	
	$.post('/'+url+'/a/ajax_validate_contactdata', $(frm).serialize(), validateContactdataCallback, 'json');
	$('input:submit', frm).attr('disabled', 'disabled');
	
	return false;
}

function validateContactdataCallback(data, textstatus)
{
	if(data.length==0)
	{
		$('#form_contactdata').unbind('submit');
		$('#form_contactdata').submit();
		return;
	}
	else
	{
		var error_required = false;
		var error_passcheckfailed = false;
		
		for(var i=0;i<data.length;i++)
		{
			switch(data[i].error)
			{
				case 'passcheckfailed':
					error_passcheckfailed = true;
					break;
				case 'required':
					error_required = true;
					break;
			}
			
			$('#input_'+data[i].field).after($('<img src="/images/icon_warning.gif" class="img_warning" alt=" !" />').css({margin: '5px 0 6px 6px', float:'left'}));
		}
				
		if(error_required)
			$('#contactdata').addError(text.error_validatecontactdata);		
		if(error_passcheckfailed)
			$('#contactdata').addError(text.error_passcheckfailed);	
		
		$('#form_contactdata input:submit').attr('disabled', '');
		location = '#contactdata';
	}
	
}

function validateConfirm(frm)
{
	if($('#check_confirm').attr('checked')=='')
	{
		alert(text.error_agree_conditions);
		return false;	
	}
	
	return true;
}

function forgotPasswordOrder(_this, context)
{
	if(context=='order')
		var container = $('#contactdata_login');
	else
		var container = $('#loginbox .content');
		
	var url = '/'+active_language_code+'/users/a/resetpass_form';
	container.html('<p><img src="/images/ajax-loader.gif"/></p>').load(url, {context:context});

	return false;
}

function forgotPasswordSubmit(_this, context)
{
	if(context=='order')
		var container = $('#contactdata_login');
	else
		var container = $('#loginbox .content');

	var url = '/'+active_language_code+'/users/a/resetpass_sendmail';
	
	container.html('<p><img src="/images/ajax-loader.gif"/></p>').load(url, {email:$('input:text[@name="email"]', _this).val(),context:context});
			
	return false;
}



// newsletter subscribe

function newsletterSubscribe(frm)
{
	$.post('/webshop.php', $(frm).serialize()+'&site='+sitedata.id+'&obj=user&a=newsletter_subscribe&language_code='+active_language_code, newsletterSubscribeCallback, 'text');
	
	return false;
}

function newsletterSubscribeCallback(data, textstatus)
{
	if(data=='ok')
	{
		$('#newsletter .content').html('<p>'+text.newsletter_subscribe_confirm+'</p>');
	}
	else
	{
		$('#newsletter .content').addError(text.error_newsletter_subscribe);
	}
}




// Stock reminder

function stock_reminder(frm)
{
	$.post('/webshop.php', $(frm).serialize()+'&site='+sitedata.id+'&obj=user&a=stock_reminder&language_code='+active_language_code, stock_reminderCallback, 'text');

	return false;
}

function stock_reminderCallback(data, textstatus)
{
	if(data=='ok')
	{
		$('#stock_reminder').html('<p>'+text.stock_reminder_confirm+'</p>');
	}
	else
	{
		$('#stock_reminder').addError(text.error_newsletter_subscribe);
	}
}


// Lists

var list = new Object();
list.add = function(product_id, variation_id, measure_id)
{
	$.post('/'+active_language_code+'/lists/a/add', {product_id:product_id,variation_id:variation_id,measure_id:measure_id}, function(data)
	{
		if(data.error!=undefined)
			alert(data.error);
		else
			$('#add2list').html(data.confirm);
	}, 'json');
}
list.changeAmount = function(item_id, amount)
{
	if(amount==0)
	{
		list.removeItem(item_id);
		return;
	}
	
	$.post('/'+active_language_code+'/lists/a/changeAmount', {listitem_id:item_id,amount:amount}, function(data)
	{
		if(data.error!=undefined)
			alert(data.error);
	}, 'json');
}
list.removeItem = function(item_id)
{
	$.post('/'+active_language_code+'/lists/a/remove', {listitem_id:item_id}, function(data)
	{
		if(data.error!=undefined)
			alert(data.error);
		else
			$('#item'+item_id).remove();
	}, 'json');
}



// jQuery plugins

jQuery.fn.addError = function(text) {
	var errordiv;
	
	return this.each(function(){
		errordiv = $('.error', this);
		if(errordiv.length==0)
		{
			errordiv = $('<div class="error">');
			errordiv.html(text);
			$(this).prepend(errordiv);
		}
		
		errordiv.css({display:'none'});
		errordiv.slideDown();
	});
};

jQuery.fn.hideError = function() {
	var errordiv;
	
	return this.each(function(){
		errordiv = $('.error', this);
		if(errordiv.length>0)
		{
			errordiv.remove();
		}
	});
};




// Stuff

function checkEnter(e, func){
	var characterCode;
	
	if(e && e.which){ 
		e = e;
		characterCode = e.which;
	}
	else{
		e = event;
		characterCode = e.keyCode;
	}
	
	if(characterCode == 13){
		func();
		return false;
	}
	else{
		return true; 
	}
}

Number.prototype.numberFormat = String.prototype.numberFormat = function()
{
	return Number(this).toFixed(2).toString().replace('.', ',');
}