$(document).ready(function(){

	function getTotals(href)
	{
		var price_total 		= $('.col_price_total.price_total span');
		var price_total_num 	= 0.00;
		//var shippingcosts		= parseFloat($('#shippingcosts span').html().replace(',','.'));
		
		for(var i = 0; i < price_total.length; i++)
		{
			var price_total_part = $(price_total[i]).html().replace('&euro; ', '');
			
			price_total_num += parseFloat(price_total_part.replace(',','.'));
		}
		price_total_num = roundNumber(price_total_num, 2);
		
		
		//Ajax request for the shipping costs
		var content   = $.ajax({
							url: href,
							data: 'request=ajax&action=GetShippingCosts&coststotal='+price_total_num,
							type: 'GET',
							dataType: 'html',
							async:false,
							success: function(){
								
								$('#basket_amount_'+articleId).val(num);
							}
						}).responseText;
						
		var priceShippingCosts = roundNumber(parseFloat(content), 2);
		
		var taxcosts = (parseFloat(content)+price_total_num)*0.19;
		
		$('#shippingcosts').html('&euro; '+priceShippingCosts.toFixed(2).toString().replace('.',','));
		$('#subtotal').html('&euro; '+price_total_num.toString().replace('.',','));
		
		//Plus shipping costs
		price_total_num = roundNumber(priceShippingCosts+price_total_num, 2);
		$('#coststotal').html('&euro; '+price_total_num.toFixed(2).toString().replace('.',','));
		
		
		$('#taxcosts').html('&euro; '+taxcosts.toFixed(2).toString().replace('.',','));
	}

	function roundNumber(num, dec)
	{
		var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
		return result;
	}

	$('.order').live('click', function(e){
	
		e.preventDefault();
		
		var href 	  		= $(this).attr('href');
		var properties		= $('.properties_select');
		var str_properties 	= '';
		var error 			= false;
		
		if(properties.length > 0)
		{
			for( var i = 0; i < properties.length; i++)
			{
				str_properties = str_properties+'&key['+i+']='+$(properties[i]).attr('name').replace('properties_','')+'&value['+i+']='+$(properties[i]).val();
			}
			
			$('#product_properties select').each( function() {  
	       		//console.log($(this));
			    var value = $(this).val();
			    
			    if(value == ''){
			    	//console.log("Add class");
			    	$(this).addClass('select_error');
			    	error = true;	
			    }else{
			    	$(this).removeClass('select_error');
			    }  
			})
		}
		
		if(error == true){
			//$(".form_error").slideToggle("fast");
			$('.form_error').remove();
			$('.product').before('<div id="error" class="form_error">Niet alle verplichte keuzes zijn gemaakt </div>');
			return false;	
		}
		
		var content   = $.ajax({
							url: href,
							data: 'request=ajax'+str_properties,
							type: 'GET',
							dataType: 'html',
							async:false
						}).responseText;
		
		var array	  = content.split(';');
		
		$.jGrowl("Uw product is toegevoegd aan de winkelwagen", { life: 4000, speed:'fast', position: 'bottom-right' });
		
		$('#totalitems').html(array[0]);
		$('#coststotal').html('&euro; '+array[1]);
		
	});
	
	$('.basket_amount_more').live('click', function(e){
	
		e.preventDefault();
		
		var href 	  = $(this).attr('href');
		var articleId = $(this).attr('rel');
		var num		  = parseInt($('#basket_amount_'+articleId).val())+1;
		
		var content   = $.ajax({
							url: href,
							data: 'request=ajax',
							type: 'GET',
							dataType: 'html',
							async:false,
							success: function(){
							
								$('#basket_amount_'+articleId).val(num);
							}
						}).responseText;
		
		var priceTotal = roundNumber(parseFloat(content)*parseFloat($('#basket_amount_'+articleId).val()), 2);
		
		$('#price_'+articleId).html('&euro; '+content.replace('.',','));
		$('#price_total_'+articleId+' span').html(priceTotal.toFixed(2).toString().replace('.',','));
		
		getTotals(href);
	});
	
	$('.basket_amount').live('change', function(e){
		
		var id = $(this).attr('id').split('basket_amount_');
		
		var articleId = id[1];
		var href = ROOT_PATH+'winkelwagen/'+articleId+'/?action=setamount';
		
		var amount		  = parseInt($(this).val());
		
		var content   = $.ajax({
					url: href,
					data: 'request=ajax&amount='+amount+'',
					type: 'GET',
					dataType: 'html',
					async:false,
					success: function(){
					
						$('#basket_amount_'+articleId).val(num);
					}
				}).responseText;
		
		var priceTotal = roundNumber(parseFloat(content)*parseFloat($('#basket_amount_'+articleId).val()), 2);
		
		$('#price_'+articleId).html('&euro; '+content.replace('.',','));
		$('#price_total_'+articleId+' span').html(priceTotal.toFixed(2).toString().replace('.',','));
		
		getTotals(href);
		
	});
	
	$('#div_product_properties select').live('change', function(e){
	
		e.preventDefault();
		
		var href 	  = $(this).attr('href');
		var id = $(this).attr('value');
		var line_itemId = $(this).attr('id');
		var select_id = $(this).attr('id');
		var name = $(this).attr('name');
		var theclass = $(this).attr('class');
		
		var content   = $.ajax({
							url: window.location,
							data: 'request=ajax&update_propery=true&id='+id+'&line_itemid='+line_itemId+'&name='+name+'',
							type: 'GET',
							dataType: 'html',
							async:false,
							success: function(){
								/*
								//Animate
								$("#"+id+"").animate({
								    borderColor: "green"
								  }, 1500 );
								  */
								var found = false;
								
								//console.log("Remove the class");
								
								$('[id='+line_itemId+']').removeClass('select_error');
								
								//if(theclass == 'basket_properties_select select_error'){
									
									$('#basket select').each( function() { 
										//console.log("search");
										if($(this).attr('class') == 'basket_properties_select select_error'){
											found = true;
											//console.log("found");
										}
										
									})
								//}
								
								if(found == false){
									$('.form_error').slideUp(100, function(){ $('.form_error').remove(); });	
								}
								
								
							}
						}).responseText;
	
	});
		
	
	$('.basket_amount_less').live('click', function(e){
		
		e.preventDefault();
		
		var href 	  = $(this).attr('href');
		var articleId = $(this).attr('rel');
		var num		  = parseInt($('#basket_amount_'+articleId).val())-1;
		
		if(parseInt($('#basket_amount_'+articleId).val()) <= 1)
		{
			return false;
		}
		
		var content   = $.ajax({
							url: href,
							data: 'request=ajax',
							type: 'GET',
							dataType: 'html',
							async:false,
							success: function(){
							
								$('#basket_amount_'+articleId).val(num);
							}
						}).responseText;
		
		var priceTotal = roundNumber(parseFloat(content)*parseFloat($('#basket_amount_'+articleId).val()), 2);
		
		
		$('#price_'+articleId).html('&euro; '+content.replace('.',','));
		$('#price_total_'+articleId+' span').html(priceTotal.toFixed(2).toString().replace('.',','));
		
		getTotals(href);
	});
	
	$('.remove_item').live('click', function(e){
		
		 
		e.preventDefault();
		
		var answer = confirm('Product wissen?');
		if(answer == true){
			var href 	  = $(this).attr('href');
			var articleId = $(this).attr('rel');
			
			$.ajax({
				url: href,
				data: 'request=ajax',
				type: 'GET',
				dataType: 'html',
				async:false,
				success: function(){
				
					$('#row_'+articleId).fadeOut();
					$('#row_'+articleId).remove();
				}
			})
			getTotals(href);
			
			//Get aantal dropdown lists
			var count_properies = $('#basket select').length;
			if(count_properies <= 0){
				$(".basket_detail").html("<h2>Uw winkelwagen</h2>Uw winkelwagen is leeg.<div class=\"submit\"><a href=\"/prosonshop_gtcms/\" class=\"continue_shopping\">Verder winkelen</a></div>");	
			}
		}
	});
	
/* Step 2 submit validate */	
$("#order_step_2").submit(function() 
    { 
        var error = false;
        var deliverymethod = $("input[@name=deliverymethod]:checked").val();
        
        if(deliverymethod == 1){
	        $('#order_step_2 input').each( function() {  
	            //console.log($(this));
	            var value = $(this).val();
	            var name = $(this).attr("name");
	           // console.log(name);
	            //console.log($(this));
	            if(name != 'i_companyname'){
		            if(value == ''){
		                $(this).css("border-color", "red");
		                error = true;   
		            }else{
		                $(this).css("border-color", "green");
		            }
	            } 
	        })
       }
       
        if(error == false){
         return true;
        }else{
            return false;   
        }
    });
    
	 $("#delivery_1").change(function () {
	      $("#delivery_address_column").slideToggle("fast");
	   });
    
	 $("#delivery_2").change(function () {
	      $("#delivery_address_column").slideToggle("fast");
	    });
    
	$("#issuerID").change(function () {
	      $('#issuerID').removeClass('select_error');
	    });
    
	$(".properties_select").change(function() {
		$('.form_error').slideUp(100, function(){ $('.form_error').remove(); });
		//$(".form_error").slideToggle("fast");
		$(this).removeClass('select_error');
	});

});

 
