$(document).ready(function(){
    documentReady();   
});

   function startLoading() {
        $('.loadingItems').show();
    }                         

    function stopLoading() {            
        $('.loadingItems').fadeOut('fast');
    }          

function documentReady() {
    if ($.browser.msie) {
        $('.productGridImage').each(function(){
             $(this).click(function(){               
                window.location.href = $(this).closest('a').attr('href');
                
                return false;
             });
        });
    }    
    
    $('.specificationsList input[type=checkbox]').click(function(){
        window.location.href = $(this).closest('a').attr('href'); 
    });
          
    $('.variationSelect').click(function(){
        $.fancybox($('#productCombinations').html(), {   
            'autoScale'     : false,
            'padding'       : '1px',
            'onComplete'    : function() {
                initVariations()
            }
        });
        
        return false;
    });
    
    
    $('a[rel=fancybox]').fancybox();
    
    $('.addQuotationsRow').click(function(){
       var tr = $('tr[rel=emptyRow]:first').clone().appendTo('#productsSelection').fadeIn(100);
       
       $('input', tr).each(function(){
           $(this).attr('name', $(this).attr('name').replace('products[i]', 'products[' +  $('#productsSelection tr').length + ']'));
       });
       
       return false; 
    });
    
    $("a[rel^='prettyPhoto']").prettyPhoto();
	// Product Static Buybox
	if($('#buyBox').length > 0) {
		var buyBox	= $('#buyBox'),
			buyBoxPositionY	= buyBox.offset().top*1;
			
		$(window).scroll (function(event) {
			if ($(window).scrollTop()>buyBoxPositionY) {
				buyBox.addClass('fixed');     
			} else {
				buyBox.removeClass('fixed');
			}
		});
	}
    
    
    $('.filterContainer input[type=checkbox]').change(function(){
        $(this).parent().children('label').toggleClass('strong');
        
        // Go to url
        location.href = $(this).attr('rel');         
    });
    
    // 'More' url
    $('.filterContainer a.more').click(function(){
        $(this).fadeOut()
               .closest('ul')
               .children()
               .slideDown();
    });
    
    $('a.submit').click(function(){
       $(this).closest('form').submit();
       
       return false;        
    });  
    
    $('.productPointer').hover(function(){
        $(this).attr('src','/images/designkranenshop/inspiration/inspirationPointerHover.png');
    }, function(){
        $(this).attr('src','/images/designkranenshop/inspiration/inspirationPointer.png');
    });    
    
    $('.shoppingCartControl').click(function(){
       // Split Vars
       vars = $(this).attr('rel').split('|');
       
       if (vars[0] == 'plus') {
           $('input[rel=quantity' + vars[1] + ']').val(($('input[rel=quantity' + vars[1] + ']').val()*1)+1);
       } else if (vars[0] == 'minus') {                                
           $('input[rel=quantity' + vars[1] + ']').val((($('input[rel=quantity' + vars[1] + ']').val()*1)-1));
       }
       
       // Check if quantity = 0 or below       
       if ($('input[rel=quantity' + vars[1] + ']').val() <= 0) {
            $('input[rel=quantity' + vars[1] + ']').closest('tr').fadeOut(400);
       }
       
       // Call change function
       $('input[rel=quantity' + vars[1] + ']').trigger('change');
       
       return false;
    });
    
    
    $("input.inputQnt[type='text']").change(function(){
       vars = $(this).attr('rel').split('quantity');
       
       $.post(
            "shop/shoppingcart/update-quantity", 
            { 
                productsId         : vars[1],
                quantity           : $(this).val()
            }, function(output) {
                $('td[rel=total' + vars[1] + ']').html(output.totalPrice);
                $('td.price dl').html(output.totals);
            }, "json"
       );
       
       if ($(this).val() <= 0) {
            $('input[rel=quantity' + vars[1] + ']').closest('tr').fadeOut(400, function(){
                $(this).remove();
            });       
            
                 
       }
           
       return true;
    });    
    
    $('.jquerySlider').each(function(e){
        var values = $(this).attr('rel').split('|');  
        var fieldId = $(this).attr('id');        
         
        $('#' + fieldId).slider({
            range: true,
            min: ((values[0]*1)),
            max: ((values[1]*1)),
            values: [ $('#sliderMin' + fieldId.substr(12)).html(), $('#sliderMax' + fieldId.substr(12)).html() ],
            slide: function( event, ui ) {                      
                $('#sliderMin' + fieldId.substr(12)).html(ui.values[0]);
                $('#sliderMax' + fieldId.substr(12)).html(ui.values[1]);            
            },
            stop: function(event, ui) {
                $('.productoverviewContainer .productoverviewOverlay').fadeIn(500);
                $('.productoverviewContainer li').fadeOut(500);
                
                // Fetch Url
                var url = values[2];
                
                // Replace placeholders
                url= url.replace('[MIN]', ui.values[0]).replace('[MAX]', ui.values[1]);
                window.location.href=url;
                return true;
                // Post to get Content
                $.post(
                    url,
                    {                                 
                        ajax            : true
                    }, function(output) {              
                        // Replace output
                        $('.content.categoriePage').html(output);                                          
                        
                        // Reinitialize DOM
                        documentReady();                                                         
                    }
               );
            }
        });                                     
    });                          
                        
    // Hide overlay when visible
    $('.productoverviewContainer .productoverviewOverlay.visible').fadeOut(500);      
    
    // Xsell
    initXsell();
    
    $('.checkDelivery').click(function(){
        startLoading();     
        var productsHash = $(this).attr('rel'),
            placeholder = $(this);
            placeholderSmall = $('.deliveryIndication.Large');
            
        $.post(
            '/shop/ajax/delivery-indication',
            {                                 
                'productHash'  : productsHash,
                'ajax'         : true
            }, function(output) {              
                // Replace output
                //placeholder.html(output.large);                                                   
                placeholderSmall.html(output.small);
                stopLoading();                                                          
            }, "json"
       );       
       
       return false; 
    });      
};

$(window).load(function() {
     $('#featured').orbit({
         captions: false,
         pauseOnHover: true,
         bullets: false,
         startClockOnMouseOut: true
     });
 });
 
 function calculateQuantity(e)
 {                        
     $.post(
            '/shop/product/calculate',
            {                                 
                'productHash'       : $('input[name=productsHash]').val(),
                'quantityNeeded'    : $('input[name=quantityNeeded]').val(),
                'ajax'              : true
            }, function(output) {              
                // Replace output
                $(e).closest('div#calculateResult').html(output);                                                   
            }
       );
     
     return false;
 }
 
function initXsell()
{
     rebuildProductsXsellList();
     
     $('.chooseAlternatives').unbind();
     $('.chooseAlternatives').click(function(){
            $('.xsellalternatives').slideUp(100);
            var alternativeDropdown = $('.xsellalternatives[rel=' + $(this).attr('rel') + ']');
            if ($('.xsellalternatives[rel=' + $(this).attr('rel') + ']').is(':visible')) {
                $('.xsellalternatives[rel=' + $(this).attr('rel') + ']').hide();
            } else {
                $('.xsellalternatives[rel=' + $(this).attr('rel') + ']').show();
                    $('.modal').css('position', 'fixed').css('zIndex', 1).fadeTo('slow', 0.00001, function() {
                        $('.modal').click(function(){
                           alternativeDropdown.hide();
                            $('.modal').fadeOut();
                        })
                    })
            }
        
        return false;
    });
    
    
    $('.xsellalternatives li').unbind();
    $('.xsellalternatives li').click(function(){
        checkbox = $('input[type="checkbox"][rel=' + $(this).closest('ul').attr('rel') + ']');
        checkbox.attr('name', 'addToCart[' + $(this).attr('rel') + ']');                      
        
        var image, image2;
        var row =  $(this).closest('ul.row > li');
        image = $(this).closest('ul.row > li').children('.imgWrapper').children('img');
        image2 = $('img', this);
                                                 
        image.fadeOut(300, function(){
            image.attr('src',   image2.attr('src'))   
                 .attr('title', image2.attr('title'));   
                 
            image.fadeIn(300);
        })
        
        // Slide Up
        $('.xsellalternatives').slideUp(100);
            
        // Recalculate
        var productsArray=new Array();
        
        var form = $(this).closest('form');
        
        if ($(this).closest('ul').attr('rel') != '') {
            $('li[rel=' + $(this).closest('ul').attr('rel') + '_productlist]').remove();
        }   
        
        i=0;
        $('ul.row input[type="checkbox"]:visible', form).each(function(){
            checkbox = $(this);
            productsId = checkbox.attr('name').replace(']', '').replace('addToCart[', '');            
            if (checkbox.attr('checked') != '') {
                productsArray[i] = productsId + '|' + checkbox.val();
            }
            i++;
        });
                
        if ($(this).closest('ul').parent('li').attr('rel') == '') {
            $.post(
                '/shop/ajax/calculate-accessories', {
                    products  : productsArray,
                    reload    : true,
                    reloadId  : $(this).attr('rel'),
                    groups    : $(this).closest('ul').attr('rel').replace('alternatives_', '')
                }, function(data) {
                    row.after(data.newitems);
                    
                    $('div.placeholder', form).fadeOut(100, function(){
                        $(this).html(data.totals).fadeIn(100); 
                    });
                    
                    initXsell();
                }, 'json'
            );
        } else {
             $.post(
                '/shop/ajax/calculate-accessories', {
                    products  : productsArray
                }, function(data) {                    
                    $('div.placeholder', form).fadeOut(100, function(){
                        $(this).html(data.totals).fadeIn(100); 
                    });
                    
                    initXsell();
                }, 'json'
            );
        }
        
        return false;
    });
    
    $('.productAccessories input').unbind();
    $('.productAccessories input').click(function(){
        //if ($(this).not(':animated')) {
            // Recalculate
            var productsArray=new Array();
            
            var form = $(this).closest('form');
            
            i=0;
            $('ul.row input[type="checkbox"]', form).each(function(){
                checkbox = $(this);
                productsId = checkbox.attr('name').replace(']', '').replace('addToCart[', '');
                if (checkbox.attr('checked') != '') {
                    productsArray[i] = productsId + '|' + checkbox.val();
                }
                i++;
            });
            
            $.post(
                '/shop/ajax/calculate-accessories', {
                    products  : productsArray
                }, function(data) {
                    $('div.placeholder', form).fadeOut(100, function(){
                        $(this).html(data.totals).fadeIn(100); 
                    });
                }, 'json'
            );
            
            rebuildProductsXsellList();
        //}
    });
    
    function rebuildProductsXsellList() {
        var productsList = '';
        
        $('.productAccessories ul.row > li > .imgWrapper > img').each(function()
        {       
            if ($('input[type=checkbox]', $(this).closest('.imgWrapper')).is(':checked')) {
                productsList = productsList +  '- ' + $(this).attr('title') + '<br />';
            }
        });
        
        $('.productsList').html(productsList);
    }
}

function initVariations()
{
    $('.productCombinationsPopup .productsControl').click(function(){   
        if ($(this).attr('rel') == 'prev') {
            $('#fancybox-content .productCombinationsPopup .products ul li:first').fadeOut(100, function(){
                $('#fancybox-content .productCombinationsPopup .products ul li:eq(4)').fadeIn(100);
                $(this).appendTo('#fancybox-content .productCombinationsPopup .products ul');
            });
        } else {
            $('#fancybox-content .productCombinationsPopup .products ul li:eq(3)').fadeOut(100,function(){
                $('#fancybox-content .productCombinationsPopup .products ul li:last').prependTo('#fancybox-content .productCombinationsPopup .products ul').fadeIn(400);
            });
        }
        
        return false;
    });
    
    var inputs=new Array;
    var i=0;
    
    $('.updateOptions').change(function(){        
        if ($('#currentItem').length == 0) {
            $('<input type="hidden" name="currentItem" class="updateOptions" id="currentItem" />').appendTo('#fancybox-content');    
        }
        
        $('#currentItem').val($(this).closest('select').attr('name'));       
        
        $.post('/shop/ajax/handle-variations', $('.updateOptions').serialize(), function(data){
            $('#currentItem').remove();
            $('#fancybox-content').html(data);
            initVariations();
        }); 
    });
}

