/**
 * @author a
 */

var coupon_container_id = "couponmsg";

jQuery(document).ready(function(){
	
	if(jQuery('#set_coupon').length == 1){
		
		
	
	jQuery('#set_coupon').click(function(e){
		
		e.preventDefault();
		
		
		
			var form = jQuery('form[name*=cart]');
			var action = protocolfilter(form.attr('action'));
			
			jQuery.ajax({
				url : action,
				data : {formvalues:form.serialize() + "&ajax=true&json=true"},
				type : 'POST',
				dataType : 'json',
				success: function(data){
				
				// ermitteln den letzten produckt sowie die anzahl von produkten
				var tr_length = jQuery('tr.base').length;
					
				var last_obj, index, produkt_length = 0;
				for(index in data.cart_data){
					last_obj = data.cart_data[index];
					produkt_length++;
				}
				
				if(produkt_length>tr_length){
						
					jQuery('.freeproduct').css('display', 'table-row');	
					jQuery('.freeproduct').addClass('base');
					var row_class = tr_length%2==0?"contentrow1":"contentrow2";
					jQuery('.freeproduct').addClass(row_class);
					
					// full with data
					jQuery('.freeproduct td.left td.img img').attr({'src':last_obj.src, 'alt':last_obj.products_name});
					jQuery('.freeproduct td.left td.descr .title').text(last_obj.products_name);
					jQuery('.freeproduct td.left td.descr .shipping_time').text(last_obj.shipping_status);
					jQuery('.freeproduct td.itemnumber input').attr({'value':last_obj.products_quantity});
					jQuery('.freeproduct td.delete input[type=hidden]').attr({'value':last_obj.products_key});
					jQuery('.freeproduct td.delete input[type=checkbox]').attr({'value':last_obj.products_key});
					jQuery('.freeproduct td.price').html(last_obj.products_price.formated);
					jQuery('.freeproduct td.final_price').html(last_obj.products_final_price.formated);
				   
				}
					
					
				
				
				
				
				if (typeof(data.couponed.formated) !== "undefined") {
					var cart_tax = [];					
					for (var i in data.cart_tax) {
						cart_tax.push(data.cart_tax[i]);
					}					
					jQuery('.final_price .tax').html(cart_tax[0].tax_value.formated);
					jQuery('.final_price .cart_total').html(data.cart_total);
					jQuery('.final_price .couponed').html(data.couponed.formated );
					jQuery('.couponedlabel').html(data.couponed.label);
					jQuery('.final_price .cart_total_weight').html(data.cart_total_weight + " KG");				
				}else if(typeof(data.couponed.label)!=='undefined'){
					jQuery('.couponedlabel').html(data.couponed.label);
					jQuery('.couponed').html("<br/>");
				}
				
				jQuery('#' + coupon_container_id).html(data.couponed.msg);					
				
				
				jQuery('.couponcode').val("");	
				
					
					
				}
				
				
			});
		
		
	});
	
	}
});

