var n_reg = /[^0-9\.\,]/g

function init_shop(cat) {
	
	$('#webshop').delegate('aside .navigation-bar a','click',function(e){
		e.preventDefault()
		var $index = $(this).parents('nav:first').find('li a:not(.crud-link)'),
		index = $index.index($(this));
		$index.filter('.active').removeClass('active');
		$(this).addClass('active');
		$('#category-overview').wrap('<div></div>')
		$('#category-overview').parent().loadShiv($(this).attr('href'),function(){
			$(this).children().eq(0).unwrap()
			$('#webshop figure a').fancybox({showNavArrows:false,overlayColor:'#000'})
			$(window).scrollTop($('h1:first').offset().top-100)
		})	
	}).delegate('a.filter','click',function(e){
		$(this).toggleClass('activated')
	}).delegate('.next-prod-cat,.prev-prod-cat','click',function(e){
		e.preventDefault()
		show_loader('Loading, please wait.')
		var $links = $('.filter-block a.brand'),
		$active=$links.filter('.active'),
		index=$links.index($active),
		no=(index+1)<$links.length?index+1:0;
		
		if($(this).hasClass('prev-prod-cat')) {
			no=index>0?index-1:$links.length-1;
		}
		
		$links.eq(no).trigger('click')
		
	}).delegate('button.my-order','click',function(e){
		e.preventDefault()
		shopOverlay('order-overlay','shop/checkout')
	}).delegate('button.add-to-cart','click',function(e){
		e.preventDefault()
		
		var $article = $(this).parents('article[itemid*=]:first'),
		options = {},
		qty=parseInt($article.find('[itemprop=qty]').val());
		
		if(qty>0) {
		
			$('.terms input:checked').each(function(){
				options[$(this).attr('data-facet')] = $(this).val()
			})

			var data = {
				item : {
					id : $article.attr('data-productid'),
					qty : qty,
					options : options
				}
			}
			$.post('shop/insert_cart',data,function(r){
				$('.cart-total').text('('+r.order_amount+')');
				$article.find('figure').prepend('<span class="in-cart" title="'+r.qty+' in order.">'+r.qty+'</span>');
				$('#webshop').find('article[data-productid*='+$article.attr('data-productid')+'] figure .in-cart').remove()

				if(r.qty) {
					$('#webshop').find('article[data-productid*='+$article.attr('data-productid')+'] figure').prepend('<span class="in-cart" title="'+r.qty+' in order.">'+r.qty+'</span>');
				}
			},"json")

		}else{
			flashmessage('Choose at least 1.')
		}

	}).delegate('button.add-to-cart-direct','click',function(e){
		e.preventDefault()
		
		var $article = $(this).parents('article[itemid*=]:first'),
		options = {},
		qty=parseInt($article.find('[itemprop=qty]').val()),
		data = {
			item : {
				id : $article.attr('data-productid'),
				qty : qty,
				options : options
			}
		};
		$.post('shop/insert_cart',data,function(r){
//			shopOverlay('order-overlay','shop/checkout')
//			$('.cart-total').text('('+r.order_amount+')');
			$article.find('figure').prepend('<span class="in-cart" title="'+r.qty+' in order.">'+r.qty+'</span>');
			$('#webshop').find('article[data-productid*='+$article.attr('data-productid')+'] figure .in-cart').remove()

			if(r.qty) {
				$('#webshop').find('article[data-productid*='+$article.attr('data-productid')+'] figure').prepend('<span class="in-cart" title="'+r.qty+' in order.">'+r.qty+'</span>');
			}
			
//			$('.minicart').load('shop/minicart')
			
		},"json")
	}).delegate('.next-button','click',function(e){
		e.preventDefault()
		if($(this).attr('href').match(/\/overview/)) {
			if(validate_form($('#order form'))) {
				var postdata = $('#order form').serializeArray()
				shopOverlay('order-overlay',$(this).attr('href'),postdata)
			}
		}else{
			shopOverlay('order-overlay',$(this).attr('href'))
		}
	}).delegate('.back-button','click',function(e){
		e.preventDefault()
		shopOverlay('order-overlay',$(this).attr('href'))
	}).delegate('.goto-payment-link','click',function(e){

		e.preventDefault()

		$('.payment-active').removeClass('payment-active')
		$(this).parent().addClass('payment-active')
		$('section#payment-method').addClass('payment-completed')

	}).delegate('.overlay-the-page','click',function(e){
		e.preventDefault()
		shopOverlay('page-overlay',$(this).attr('href'))
	}).delegate('.overlay-the-product','click',function(e){
		e.preventDefault()
		var $a=$(this),
		$c = $a.parents('li:first'),
		$cc=$c.clone()
		if($('.ie6,.ie7').length===0) {
			$c.after($cc);
			$cc.css({position:'absolute',left:$c.position().left,top:$c.position().top,zIndex:100}).addClass('prod-clone')
		}
		shopOverlay('product-overlay',$a.attr('href'),{},function($overlay){
			$overlay.css({
				left : $c.position().left,
				top : $c.position().top+$c.height()+102,
				width:372+'px',
				height:'auto',
				minHeight:'inherit'
			}).show()
			$overlay.find('.close').click(function(){
				$('.prod-clone').remove()
			})
//			$(window).scrollTo($cc,{duration:1000,offset:-100})
		})
	})
	
	$('#checkout-button').click(function(e){
		e.preventDefault()
		shopOverlay('order-overlay','shop/checkout')
	})
	
	$('#personal-details .shipping h3').live('click',function(){
		$(this).nextAll('p').toggle()
		if(!$(this).nextAll('p').is(':hidden')) {
			$(this).removeClass('collapsed')
		}else{
			$(this).addClass('collapsed')
		}
	})
	$('#input-bank').live('change',function(){
		var val = $(this).val().toLowerCase(),
		$pi = $('#personal-details .screen-info div.payment');
		if(val!=="") {
			$('#personal-details h3').addClass('collapsed').nextAll().hide()
			$pi.loadShiv('page/payment-'+val)
		}
	})
	
	if(!cat) {
		$('#webshop > aside .navigation-bar a:first').addClass('active')
	}else{
		$('#webshop > aside .navigation-bar a').filter('[href*="'+cat+'"]').addClass('active')
	}
	
	$('#webshop figure a').fancybox({showNavArrows:false,overlayColor:'#000'})
}
function bind_qty_listener() {
	
	$('#webshop .qty input[itemprop=qty]').unbind('blur').bind('blur',function(e){
		e.preventDefault()
		$(this).trigger('renew')
	})
	$('#webshop').undelegate('.qty .add,.qty .substract','click').delegate('.qty .add,.qty .substract','click',function(){

		var $qty = $(this).parent().find('input[itemprop=qty]'),qty=0;
		if($(this).hasClass('substract')) {
			qty = parseInt($qty.val())-1
		}else{
			qty = parseInt($qty.val())+1
		}
		$qty.val(qty>=0?qty:0);
		
		var $prod= $(this).parents('*[data-productid*=]:first');
		$qty.trigger('renew')
	})
	
	$('#webshop .qty input[itemprop=qty]').unbind('renew').bind('renew',function(e){
		e.preventDefault()

		var $inp = $(this),
		$prod=$inp.parents('*[data-productid*=]:first'),
		$prods=$('*[data-productid='+$prod.attr('data-productid')+']'),
		qty=$inp.val();
		
		$('*[data-productid='+$prod.attr('data-productid')+'] input[itemprop=qty]').val(qty)
		
		$prod.find('.add-to-cart').css({
			opacity : .3
		})
		
		if(!$('#order').length) {
			$prod.find('.price-range-active').removeClass('price-range-active').find('td').css({
				color:'#fff'
			})
			$prod.find('.price-table tr').each(function(i){
				if(i==0)return true;
				var $td = $(this).find('td:first')
				if(qty>=parseInt($td.attr('data-from')) && (qty<=parseInt($td.attr('data-to'))||$td.attr('data-to')=='+')) {
					$(this).addClass('price-range-active')
				}
			})
		}
		
		if(!$prod.find('.in-cart').length&&!$('#order').length) {
			$prod.find('button.add-to-cart').trigger('click')
			$('.add-to-cart').css({
				opacity : 1
			})
		}else{
			$.post('shop/update_cart',{
				item : {
					rowid : $prod.attr('data-productid'),
					qty: $inp.val()
				}
			},function(r){
				flashmessage(r)
				$('.add-to-cart').css({
					opacity : 1
				})
				if(r.qty) {
					if($prods.find('.in-cart').length) {
						$prods.find('.in-cart').text(r.qty)
					}else{
						$prods.find('figure').prepend('<span class="in-cart" title="'+r.qty+' in bestellig.">'+r.qty+'</span>');
					}
				}else{
					$prods.find('.in-cart').remove()
					if($('#order').length) {
						$prod.remove('slow')
					}
				}

				if($('#order').length) {
					if(r.shipping_applied) {
						$('tr.shipping').hide()
						$('tr.shipping-applied').show().find('.price.shipping').html('&euro; '+r.shipping_applied.toFixed(2).toString().replace('.',','))
					}else{
						$('tr.shipping').show()
						$('tr.shipping-applied').hide().find('.price.shipping').html('&euro; 0')
					}
					if($inp.val()>0) {
						var price = parseFloat($prod.find('.price:first').text().replace(n_reg,'').replace(',','.'))
						$prod.find('.subtotal').html('&euro; '+($inp.val()*price).toFixed(2).toString().replace('.',','))
						calcTotals()
					}else{
						$prod.fadeOut(500,function(){
							calcTotals()
						})
					}
					
				}

			})
		}
	})
}
function calcTotals() {
	var nstotal = 0;
	$('#order tbody .subtotal:visible').each(function(){
		var $prod = $(this).parents('tr[data-rowid]:first'),
		price = parseFloat($prod.find('.subtotal:last').text().replace(n_reg,'').toString().replace(',','.'))
		nstotal += price
	})
	
	nstotal = parseFloat(nstotal);
		
	if(nstotal>0) {
		$('#order tfoot').find('.grand-subtotal').html('&euro; '+(nstotal).toFixed(2).toString().replace('.',','))
		if($('#order .shipping-applied').is(':visible')) {
			nstotal += parseFloat($('#order tfoot').find('.shipping:last:visible').text().replace(n_reg,'').toString().replace(',','.'))
		}
		$('#order tfoot').find('.price.btw-total').html('&euro; '+(parseFloat((nstotal*19)/119)).toFixed(2).toString().replace('.',','))
		$('#order tfoot').find('.price.grand-total').html('&euro; '+(parseFloat(nstotal)).toFixed(2).toString().replace('.',','))
	}else{
		$('.shop-overlay:last .close').trigger('click')
		flashmessage(l('De order is leeg.'))
	}
}
function CurrencyFormatted(amount){
	var i = amount+''.replace(n_reg,'');
	i = parseFloat(amount);
	if(isNaN(i)) {
		i = 0.00;
	}
	var minus = '';
	if(i < 0) {
		minus = '-';
	}
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	var s = new String(i);
	if(s.indexOf('.') < 0) {
		s += '.00';
	}
	if(s.indexOf('.') == (s.length - 2)) {
		s += '0';
	}
	s = minus + s;
	return s;
}
function shopOverlay(id,href,postdata,callback) {
		
	var $parent = $('#webshop'),$overlay=$('#'+id+''),
	$modal = $('.ui-widget-overlay');
	
	postdata = postdata||{};
	
	if(!$modal.length) {
		$modal = $('<div class="ui-widget-overlay" style="z-index:99;"></div>').appendTo('body')
		$parent.append($modal.css({
			width:$('#main').width(),
			height:$('#container').height(),
			top:0,
			left:0
		}));
		$modal.click(function(){
			$('.shop-overlay:last .close').click()
		})
	}else{
		$modal.css({
			width:$('#main').width(),
			height:$('#container').height(),
			top:0,
			left:0
		})
	}
		
	if(!$overlay.length) {
			
		$('.shop-overlay').hide()
		
		$overlay = $('<div id="'+id+'" class="shop-overlay" data-url="'+href+'"><a class="close button" title="Sluiten"><span>x</span><strong>sluiten</strong></a><div></div></div>');
		
		$overlay.css({
			top : $(document).scrollTop()+$('#main-header').height(),
			left:0
		})
		if(callback) {
			$overlay.data('callback',callback)
		}
		$parent.append($overlay)
			
		$overlay.find('div:first').loadShiv(href,postdata,function(){

			var $overlay=$(this).parents('.shop-overlay:first'),
			$close = $overlay.find('.close')
			$close.click(function(){
				if($('.shop-overlay').length===1) {
					$('.ui-widget-overlay:last').remove()
				}
				$('.shop-overlay:last').remove()
				$('.shop-overlay:last').show()
			})
			if($overlay.data('callback')) {
				var cb = $overlay.data('callback');
				cb($overlay)
			}
			$overlay.find('div:first').children().eq(0).removeClass('hidden')
		})	

	}else{
		$overlay.attr('data-url',href)
		if(callback) {
			$overlay.data('callback',callback)
		}
		$overlay.find('div:first').loadShiv(href,postdata,function(){
			
			var $overlay=$(this).parents('.shop-overlay:first')
				
			if($overlay.data('callback')) {
				var cb = $overlay.data('callback');
				cb($overlay)
			}
			$overlay.find('div:first').children().eq(0).removeClass('hidden')
		})
	}
}
