$(function(){
		
	//Blur zoekveld
	$('#id_search').blur(function() {
        if($(this).attr('value') == '')
            $(this).attr('value', "Zoek een product...");
    });
    
    $('#id_search').focus(function() {
        if($(this).attr('value') == "Zoek een product...")
            $(this).attr('value','');
    });
    
	//post voor zoekformulier
	var submit_form = function(){
	    var word = $("#id_search").val();
		if( word )
		    window.location='/shop/search_products/' + word;
	}
	
	$('#submit_search')
	    .bind( 'click', function(){
	        submit_form();
	    });
	    
    $('#id_search').
        keyup(function(e) {
            if(e.keyCode == 13) {
               submit_form();
            }
        });
    
    // 'Toevoegen' knop
	$('.add_to_cart')
	    .bind( 'click', function(){            
    		
    		var product_id = $(this)
    		    .find("input[name=product_id]")
    		    .val();
            
            var items = $(this).closest('a').find('.items').val();
            if( !items )
                items = 1;
                
    	    add_cart_ajax( product_id, 'add', null, items, false )

    		return false;
    		
    	});
    
    // 'Combi' knop
    $(".add_combi")
        .tipsy({
            // opacity: 0.9,
            title: function() {
                return 'Klik om deze actie in winkelwagen te stoppen!';
            }
        })
        .bind('click', function(e){
            
            e.preventDefault();
                        
            $(this)
                .closest('a')
                .find('.art-container .art') 
                .each(function(){
                   
                    var product_id = $(this).find('.product_id').val();
                    var items = $(this).find('.items').val();
                    var category_id = $(this).find('.category_id').val();
                                      
                    add_cart_ajax( product_id, 'add', category_id, items, false );
                    
                });
        });
    
    // + en - knopjes
    // en add to cart knopje categorie
    $(".cart_change.add")
        .not('.no_tipsy')
        .tipsy({
            title: function() {
                return 'Klik om dit artikel in winkelwagen te plaatsen.';
            }
        });
    
    $(".cart_change")
        .live('click', function(e){
                
            e.preventDefault();
                    
            var product_id = 
                $(this)
                    .attr('class')
                    .split(/\s+/)[0]
                    .split("_")[1]
            
            var show_cart = $(this).closest('ul').attr('id') == 'cart_list';
            
            
            var items = $(this).closest('a').find('.items').val();
            if( !items )
                items = 1;
            
            if( $(this).hasClass('add') )
                var type = 'add';
            else
                var type = 'remove';
            
            var cat_id = null;
                        
            // kijken of er voor dit product een gewoon product_id is ingesteld
            if( category_id )
            {
                cat_id = category_id;
            }
            else
            {            
                // Voor search pagina
                var product_category_id = $(this).closest('span').find('.category_id').val();
                if( product_category_id )
                    cat_id = product_category_id;
            }
                                    
            return add_cart_ajax( product_id, type, cat_id, items, show_cart );
        });

    function nice_price( price )
    {
        var euro = price.substring( 0, price.length-2 );
        var cent = price.substring( price.length-2 );
        
        if( !euro )
        {
            euro = 0;
        }
        
        return euro + "," + cent;
    }
        
    function add_cart_ajax( product_id, $type, cat_id, items, show_cart )
    {
        
        if( !cat_id )
            cat_id = category_id;
        
        if( !items )
            items = 1;
        else
            items = parseInt(items);
        
        //TODO: WAAROM GAAT DIT TYFUS HOMO DING NIET AAAN?
        $("#ajax_loader").show();

        if( cat_id )
            var url = "/shop/add_to_cart/" + product_id + "/" + $type + "/" + cat_id + "/" + items ;
        else 
            var url = "/shop/add_to_cart/" + product_id + "/" + $type + "/";
        
        $.ajax({
			url : url,
			//dataType : "json",
			async : false,
			success : function( data )
				{	
				    
				    if( data != 'False' )
				    {
				        $("#cart")
				            .replaceWith(data);
				        
				        // Counter omhoog of omlaag schoppen
				        var $counter = $(".in_cart_" + product_id);
				        if( $counter.length )
				        {
				            var count = parseInt($counter.html());
				            if( $type == 'add' )
				                count += items;
				            else
				                count -= items;
    				        $counter.html(count);
				        }
				        
				        //console.info('show', show_cart);
				        
				        if( show_cart )
				        {
				            $("#cart ul")
				                .show()
				        }
				        	        
				        $("#cart ul")
				            .mouseleave(function(){
                                $("#cart ul")
                                    .hide();
                            })
                        
                        $("#cart")
                            .mouseenter(function(){
                                $("#cart ul")
                                    .show();
                            });
                                                
				    }
				    else
				    {
				        //Niet op voorraad
					    $("." + product_id + '_wel_voorraad').hide();
					    $("." + product_id + '_geen_voorraad').show();
					    $("#" + product_id + "_add_to_cart").hide();
				    }
				    
				    /*
				    console.info( data );				    
				    			    
				    var prijs = data['total_price'].toString(),
				        bedrag = prijs.substr(0, (prijs.length-2)) + ',' + prijs.substr(-2,2),
				        str = data.total + ' producten - &euro; ' + bedrag;
				    
					$("#total_products").html( str );					
					$(".in_cart_" + product_id).html(data['product_count']);
										
					if( data['product_count'] == 0 )
					{
					    //Regel uit cart verwijderen bij 0 artikelen
					    $(".o_" + product_id).remove();
					}
					
					$(data.order_list).each(function(){
					    					    
					    //Cart bijwerken
					    if( this['product']['id'] == product_id )
					    {
        					if( data['product_count'] == 1 && $(".o_" + product_id).size() == 0 )
        					{      
        					    //Regel toevoegen als deze nog niet bestond
                                var titel = this['product']['titel'].toLowerCase();
                                var price = this['product']['prijs'].toString();
    					        
        					    $("#cart_list")
        					        .append("\
        					        <li class='o_" + product_id + "'> \
                                        <span class='amount'>&euro; " + nice_price( price ) + "</span> \
                                        <span class='name'> \
                                            <span class='quantity'> \
                                                <a class='p_" + product_id + " cart_change add' href='#more'><img alt='Meer' src='/media/images/cart_add.png' /></a> \
                                                <a class='p_" + product_id + " cart_change remove' href='#less'><img alt='Minder' src='/media/images/cart_remove.png' /></a> \
                                            </span> \
                                            <span class='value'>1</span> × " + titel + " \
                                        </span> \
                                    </li>");
        					}
        					else
        					{
        					   //Bestaande regel updaten 
        					   $(".o_" + product_id + " .value").html(data.product_count);
   					           var price = this['total_price'].toString();
           					   $(".o_" + product_id + " .amount").html("&euro; " + nice_price( price ) );
        					}
        					
        					//Voorraad beschikbaar? -> beschikbaarheid melding en bestelknop verbergen of juist tonen?
        					if( this['product']['voorraad'] > data['product_count'] )
        					{
        					    //Op voorraad
        					    $("." + product_id + '_wel_voorraad').show();
        					    $("." + product_id + '_geen_voorraad').hide();
        					    $("#" + product_id + "_add_to_cart").show();
        					}
        					else
        					{
        					    //Niet op voorraad
        					    $("." + product_id + '_wel_voorraad').hide();
        					    $("." + product_id + '_geen_voorraad').show();
        					    $("#" + product_id + "_add_to_cart").hide();
        					}
				        }
					    
					});
					*/
					
					$("#ajax_loader").hide();
					
					return true;
				}
		});
    }
    
});
