var frontend = {
    urls: {},

    init: function() {
    
        // Initialize layout
        this.layout.init();
		
		// init cart code
		this.cart.init();
		
        // init basket code
        this.basket.init();
        
        // Initialize forms
        if($('form').length > 0) this.forms.init();

        if($('body').hasClass('ie6')) this.ie6fixes.init();
        
        // Spotlight
        if($('.spotlight').length > 0) this.spotlight.init();
        
        // Init varieties
        if($('.variety').length > 0) this.variety.init();
        
        // Init feedback
        if($('header .feedback').length > 0) this.feedback.init();
    },

    layout: {
    
        init: function() 
        {
            this.hoverable();
            //this.parseImages();
            this.wrapLiElements();

            // Init spotlight
            if($('#spotlight').length > 0) frontend.spotlight.init();
            
            // Init productSlider
            if($('.product-slider').length > 0) frontend.productSlider.init();
            
            if($('.aside').length > 0) this.setMinHeight($('.aside'), $('.cols'));
            if($('.paging').length > 0) this.setMinHeight($('.paging'), $('.results'));

            this.preventImageDownload($('.spotlight .col, .product-img'), $('<span class="block-img"></span>'));
           
            
            if($('.lte7').length > 0) this.preventImageDownload($('.variety .col'), $('<span class="block-img"></span>'));


            $('#country').change(function(){
                $('#geoip').submit();
            })
        },

        /**
         * preventImageDownload
         * some basic image download prevention
         * it places a spacer image in front of the actual image, to prevent the actual image from being clicked
         *
         * @author Davy De Pauw
         * @version 1.0
         */
        
        preventImageDownload: function(target, blocker)
        {
            target.each(function() {
                var $this = $(this);
                var width = $this.width();
                var height = $this.height();
                var $blocker = blocker.clone();
            
                $blocker.css({
                    position: 'absolute',
                    width: width,
                    height: height
                });
            
                $this.append($blocker);
            });
        
        },

        /**
         * wrapLiElements adds a span around the li contents, for different styling of content and li indicator (bullet, number, ...)
         * rich text editor should have class="rte" or ul/ol should have class="wrap" attached
         * class="wrapped" is placed on list element, to address it through CSS
         *
         * @author Davy De Pauw
         * @version 1.1
         */
        
        wrapLiElements: function() 
        {
            $('.static ol, ul.wrap, ol.wrap').addClass('wrapped');
            $('.static li, .wrap li').wrapInner('<span></span>');
        },

        /**
         * Set hoverables.
         * Attach the class="hoverable" to lists, whose items you want to be hoverable
         *
         * @author Davy De Pauw
         * @version 1.1
         */
        
        hoverable: function()
        {
            var hoverIn = function(e) {
                $(this).addClass('hover');
            };
            var hoverOut = function(e) {$(this).removeClass('hover');}
        
            // Generic hoverable function
            if($('.hoverable').length > 0) $('.hoverable li').hover(hoverIn, hoverOut);
        },
        
        /**
         * Set the minimum height
         * Is needed when (eg.) side navigation is positioned absolutely
         * 
         * @author Davy De Pauw
         * @version 1.1
         */
         
        setMinHeight: function($reference, $target)
        {
            // Set min-height of #main div, based on outerheight of target
            $target.css('min-height', ($reference.outerHeight()) + 'px');
        }
    },

    forms: {

        init: function() 
        {
            this.setRequiredIndicators();
            this.setFocusListeners();
            
            this.parseCustomInputs();
            
        },

        /**
         * setRequiredIndicators adds * to elements which have a class="required"
         *
         * @author Davy De Pauw
         * @version 1.0
         */
        
        setRequiredIndicators: function() 
        {
            $('.required label').append('<span class="indicator">*</span>');
        },

        /*
         * Set focus/blur listeners.
         *
         * @author Davy De Pauw
         * @version 1.1
         */
         
        setFocusListeners : function()
        {
            // Field focus/blur
            $('form .field').live('focus', function()
            {
                // Get dd
                $dd = $(this).closest('dd');
            
                // Add focus class to dd
                $dd.addClass('focus');
                
                // Add focus class to dt
                $dd.prev('dt').addClass('focus');
            });
            
            $('form .field').live('blur', function()
            {
                // Get dd
                $dd = $(this).closest('dd');
                
                // Add focus class to dd
                $dd.removeClass('focus');
                                
                // Remove focus class from dt
                $dd.prev('dt').removeClass('focus');
            });
        },
        
        /**
         * Custom radio and/or checkbox input field
         *
         * @author Davy De Pauw
         * @version 1.3
         */
        
        parseCustomInputs: function()
        {
            $('input.checkbox, input.radio').each(function(e) {
            
                // Input
                $this = $(this);
            
                $span = $('<span class="cb"></span>');
            
                // Wrap with class="cb"
                $this.wrap($span);
                
                // Get parent
                $parent = $this.parent();
                                
                // Check if $this:checked
                if($this.attr('checked')) $parent.addClass('checked');
                
                $elements = $this.add($parent);
                
                $this.click(function(e) {                    
                                        
                    $this = $(this);
        
                    $parent = $this.parent();
                    $grandparent = $parent.parent();
                                                            
                    // Check if this is a radio button
                    if($grandparent.hasClass('radio'))
                    {
                        // Get the name group
                        var name = $this.attr('name');
                                                
                        // Reset all radio buttons in the name family
                        $('input[name="' + name + '"]').parent().removeClass('checked');
                    }
                                
                    if($parent.hasClass('checked'))
                    {
                        $parent.removeClass('checked');
                        $this.attr('checked', false);
                    }
                    else
                    {
                        $parent.addClass('checked');
                        $this.attr('checked', true);
                    }
                });
            });
            
            // See if anything is previously checked and reflect that in the view
            $('input.checkbox:checked, input.radio:checked').parent().addClass('checked');
        }              
    },
    
    spotlight: {

        init: function() 
        {
            var hoverIn = function() 
            {
                // Spotlight item
                $this = $(this);
                
                // Info box
                $info = $this.find('.info');
                                
                $info.animate({top: $this.height() - ($info.height())}, 150, 'swing', function() {});
            };
            
            var hoverOut = function() 
            {
                // Spotlight item
                $this = $(this);
                
                // Info box
                $info = $this.find('.info');

                $info.delay(50).animate({top: $this.height() - 40}, 150, 'swing', function() {});            
            };
        
            $('.spotlight .col').each(function(i) {
                $this = $(this);
            
                $this.find('.block-img').live('click', function(e) {
                    
                    // Get link value
                    var href = $(this).parent().find('h2 a').attr('href');
                    
                    // Redirect to category page
                    if(href) window.location = href;
                });
                
                $this.hover(hoverIn, hoverOut);
            });
        }
    },

    productSlider: {
        i: 0,
        current: null,
        timeOut: null,
        
        init: function()
        {
            $('.product-slider .controls a').click(function(e) {
       
                // Get container
                var c = frontend.productSlider;
                
                // Li parent()
                $li = $(this).closest('li');

                // Reset selected states
                $('.controls li').removeClass('selected');
                                
                // Set selected state for current item
                $li.addClass('selected');                      
                                
                // Current index
                var currIndex = $li.index();
                
                // Set index to currentItem
                c.i = currIndex;
                
                // Get target to be scrolled to
                var $target = $($(this).attr('href'));
                

                
                // Hide all text boxes
                $('.product-slider figure img').css('z-index', 1).hide();
                  
                // Show current text box
                $target.show();
                $target.css('z-index', 10);
                
                // Get reference to target                
                c.current = $target;     
                
                // Don't follow the link
                e.preventDefault();
                
                // Clear timeout
                clearTimeout(c.timeOut);
                
                // Calculate next item
                if(currIndex < $li.siblings().length)
                {
                  c.i++;
                }
                else
                {
                  c.i = 0;
                }
                
                // Display next in queue
                $next = $('.product-slider figure img:eq(' + (c.i) + ')');
                
                $next.css('z-index', 5);                
                $next.show();
                
                // Call next spotlight in 5 seconds
                c.timeOut = setTimeout("frontend.productSlider.animate(frontend.productSlider.i)", 4000);
            });
           
            // Select first item
            $('.product-slider .controls a:first').trigger('click');
            
        },
       
        animate: function(i)
        {
            // Reset selected states
            $('.controls li').removeClass('selected');
              
            $li = $('.controls li:eq(' + (frontend.productSlider.i) + ')');
                            
            // Set selected state for current item
            $li.addClass('selected');           
                
            frontend.productSlider.current.fadeOut('slow', function() {
                 $li.find('a').trigger('click');                
            });
        }
    },

    /**
     * Feedback message in header
     *
     */

    feedback: {
    
        init: function() 
        {
            $('.feedback a.remove').click(function(e) {

                // Hide feedback block
                $(this).parent().hide();
                
                // Remove padding on top
                $('body').removeClass('feedback-top');
                
                e.preventDefault();
            });
        }
    },

    variety: {
    
        init: function() 
        {
            // Get number of result items
            var numResults = $('.results li').length;
            
            // Add a span to the title link
            $('.results li').each(function(i) {

                // Cache this
                $this = $(this);

                // Get title link
                $a = $this.find('a:first');
                
                // Append a span to title link
                $a.append('<span></span>');
                
                // Get details element
                $details = $this.find('.details');
                                
                // DL
                $dl = $details.find('dl');                             
                
                // Set z-index
                $this.css('z-index', numResults - i);
                
                // Get heights
                var aHeight = $a.innerHeight();
                var dlHeight = $dl.height();

                $dl.css('padding-top', 140 + aHeight);

                // Save old height and new calculated height in object
                this.detailsHeight = 195;
                this.detailsHeightHover = 195 + dlHeight + aHeight;

                // Change height of details on hover
                $this.hover(function(e) {                                
                
                    $details = $(this).find('.details');                                        
                    $details.css('height', this.detailsHeightHover + 'px');                
                },
                                
                function() {                                        
                    $details = $(this).find('.details');                                        
                    $details.css('height', this.detailsHeight + 'px');                                 
                });
                
                // IE 8 and lower fallback, for hover li within link
                if($('html').hasClass('lte8')) {
                    $target = $this.find('a, a span');
                    
                    $target.hover(function(e) {
                        $(this).closest('li').addClass('hover');
                        
                        e.stopPropagation();
                    }, 
                    function() {});
                }               
            });
        }
    },
    
    ie6fixes: {

        init: function()
        {
            this.overview();
        },

        overview: function()
        {
            $('.overview .more').each(function() {
                $(this).height($(this).parent().height());
            });
        }
    },
    
    /*
    * post form via Ajax
    * update basket
    *
    */
    cart: {
    	init: function()
    	{
    		this.addProduct();
    	},
    	
    	addProduct: function()
    	{
    		var $add = $('.basket-add');
    		
    		pTimeOut = '';
    		
    		$add.each(function() {
    		    var $this = $(this),
    				$form = $this.closest('form'),
    				$details = $this.closest('.details'),
    				$preloader = '<div class="preloader"></div>',
    				$basket = $('#ajax-basket'),
    		    	$action = $form.attr('action');
    		        		    
    		    // get original heights
    		    // we'll need to reset them later
    		    $details.hover(function() {
    		    	detailsOriginalHeight = $details.height();
    		    	formOriginalHeight = 30;
    		    });
    		   
    		    $this.click(function(e) {
    		    	var $this = $(this),
    		    		$quantityField = $form.find('input[name="quantity"]'),
    		    		$productField = $form.find('input[name="product"]'),
    		    		
    		    		$quantity = $quantityField.attr('value'),
    		    		$productId = $productField.attr('value');
    		    	
    		    	var params = {
						quantity: $quantity,
						product: $productId
					}
					
					$form.append($preloader);
	                
	                $.ajax({
	                    url: $action,
	                    type: "POST",
	                    data: params,
	                    success: function(data) {
	                    	                    	
	                    	// remove .empty from basket
	                    	// update amount
	                    	var parsedData = $.parseJSON(data);
    						$basket.html(parsedData.html);
    						$quantityField.val(1);
    						
    						// Remove preloader
    						$form.find('.preloader').remove();
    						
    						// indicate addition of new item
    						// update amount
    						var amount = $basket.find('.more .amount').text(),
							$item = $('.item-new');
    						//$item.find('span').text(amount);
    						$item.slideDown(200).delay(3000).slideUp(200);
    						frontend.cart.itemAdded($item);
    						
    						// add error
    						if ( parsedData.error !== undefined ) {
    							//message
    							var msg = parsedData.error;
    							frontend.cart.productError($form, msg);
    						}
	                    },
	                    error: function(data) {
	                    	//get message
	                    	var parsedData = $.parseJSON(data);
	                    	var msg = parsedData.error;
	                    	// Remove preloader
	                    	$form.find('.preloader').remove();
	                    	// add error
	                    	frontend.cart.productError($form, msg);
	                    }
	                });
			    	
			    	e.preventDefault();
			    	
	    		});
	    	});
    	},
    	
    	productError: function($form, msg) {
    	    			
			if ( pTimeOut !== '' ) {
	    		clearTimeout(pTimeOut);
	    	}
	    	
	    	var $error = $form.find('.product-error'),
	    		$details = $form.closest('.details');
	    	
    		// Remove preloader
    		$form.find('.preloader').remove();
    		
    		// append message
    		if ($error.length) {
    			//
    		} else {
    			$form.append('<div class="product-error"></div>');
    			$error = $form.find('.product-error');
    		}
    		
    		$error.text(msg);
    		
    		// if in .details
    		// stretch .details and add error height to make room
    		
    		if ( $details.length ) {
    			$error.show();
    			
    			// need errorheight to add to .details and form	
    			var	errorHeight = $error.height();
    			
    			// animate heights
    			$form.filter(':not(:animated)').animate({height: formOriginalHeight + errorHeight + 10}, 100);
    			$details.filter(':not(:animated)').animate({height: detailsOriginalHeight + errorHeight + 10}, 100);
    			
    			// hide after delay
    			pTimeOut = setTimeout(function() {
    				$error.hide();
    				$form.height(formOriginalHeight);
    				$details.height(detailsOriginalHeight);
    				//$form.animate({height: formOriginalHeight},100)
    				//$details.animate({height: detailsOriginalHeight},100);
    			}, 2000);
    		
    		// for product detail page it's simpler	
    		} else {
    			$error.slideDown(200);//.delay(3000).slideUp(200);
    			
    			// hide after delay
    			pTimeOut = setTimeout(function() {
    				$error.slideUp(200)
    			}, 2000);
    		}
    	},
    	
    	itemAdded: function($item) {

    		var docViewTop = $(window).scrollTop();
    		
    		// switch to fixed position if bottom of the block is out of view
    		if (docViewTop >= (140) ) {
    			$item.css({'position':'fixed', 'top':'0'});
    		} else {
    			$item.css({'position':'absolute', 'top':'140px'});
    		}
    		
    		$(window).scroll(function(){
    		    		
    			var docViewTop = $(window).scrollTop();
    			
    			// switch to fixed position if bottom of the block is out of view
    			if (docViewTop >= (140) ) {
    				$item.css({'position':'fixed', 'top':'0'});
    			} else {
    				$item.css({'position':'absolute', 'top':'140px'});
    			}
    		});
    		
    		
    	}
    },

    basket: {
        init: function()
        {
            // print stuff
            $('a.print').click(function(e) {
                window.print();
                e.preventDefault();
            });

            //change amount
            $('.change-amount').keyup(function(e) {

                var $input = $(this);
                $result = $('.result');
                $resultTransport = $result.find('#transport');

                $url = $input.attr('basket_link') + '/' + $input.attr('rel') + '/' + $input.val();

                $.post($url, function(data) {
                    var parsedData = $.parseJSON(data);

                    if (parsedData.item != '0,00') {
                        $($input).parent().parent().next().find('.subtotal').html(parsedData.item);
                        // also set quantity in case of stock issues
                        $($input).val(parsedData.quantity);
                    } else {
                        $($input).parent().parent().parent().remove();
                    }
                    $('#basket-total').html(parsedData.total);
					if (parsedData.canBeOrdered) {
						$('.minimum').hide();
					} else {
						$('.minimum').show();
					}

                    $('#basket-itemcount').html(parsedData.totalItems);
                    if (parsedData.transportCost != '0,00') {
                        $resultTransport.find('.amount span').html(parsedData.transportCost);
                        $resultTransport.find('.amount').show();
                    } else {
                        $resultTransport.find('.amount').hide();
                    }

                });
            })

                $(".basket-head").die();
                
                $(".basket-head").live({
					mouseover: function() {
						
						console.log('dqfdqs');
						
						$ul = $(this).find('ul');

						var height = 0;

						// Calculate height for ul
						$ul.find('li').each(function(i) {
							height += $(this).outerHeight();
						});

						// Set height for absolutely postioned ul          
						$ul.height(height);

						// Set height for basket
						$(this).height(height + 50);

						// Attach hover class
						$(this).addClass('hover');
					},
					mouseout: function() {
						// do something on mouseover
	                    // Get ul
	                    $(this).find('ul').height(0);
	                    
	                    // Reset basket height
	                    $(this).height(50);
	                    
	                    // Remove hover class
	                    $(this).removeClass('hover');
					}
				});
            //}
            
            // Transport dropdown
            if($('select#transport').length > 0)
            {
                // Cache checkout header
                $delivery = $('.delivery');
                $result = $('.result');
                $resultTransport = $result.find('#transport');
                $resultFavv = $result.find('#favv');
                $resultTransitCustoms = $result.find('#transit-customs');

                // Listen for changes in dropdown
                $('select#transport').change(function(data) {

                    // change select options
                    $('input#delivery-location').attr('checked','checked');
                    $('input#delivery-location').parent().addClass('checked');
                    $('input#delivery-pickup').removeAttr('checked');
                    $('input#delivery-pickup').parent().removeClass('checked');

                    if($(this).val()) 
                    {
                        // URL needs to be changed, to reflect the dynamic php part
                        $.post(frontend.urls.basket_transport + '/' + $(this).val(), function(data) {
                            var parsedData = $.parseJSON(data);

                            // Remove possible classes
                            $delivery.removeClass('feedback error');
                            
                            // Remove errors
                            $delivery.find('.errors').remove();
                            
                            // Hide form
                            $delivery.find('.options').hide();                   

                            // Parse data to page
                            $resultTransport.find('h2').text(parsedData.transportLabel);

                            $('#basket-total').text(parsedData.total);
							
                            $resultTransport.find('.amount span').html(parsedData.transportCost);
                            $resultTransport.find('.amount').show();

                            if (parsedData.favvCost != '0,00') {
                                $resultFavv.find('span').html(parsedData.favvCost);
                                $resultFavv.show();
                            } else {
                                $resultFavv.hide();
                            }

                            if (parsedData.transitLabel) {
                                $resultTransitCustoms.find('#transit').html(parsedData.transitLabel);
                            }

                            if (parsedData.customsLabel) {
                                $resultTransitCustoms.find('#customs').html(parsedData.customsLabel);
                                $resultTransitCustoms.find('#customs').show();
                            } else {
                                $resultTransitCustoms.find('#customs').hide();
                            }
                            $resultTransport.find('#pickup-note').hide();
                            $resultTransitCustoms.show();
                            $result.show();
                        });
                    }                    
                });

//@Todo: refactor repeated code
                // Listen for changes in radiobuttons
                $('input#delivery-location').click(function(data) {
                    if($(this).val() && $('select#transport').val())
                    {
                        // URL needs to be changed, to reflect the dynamic php part
                        $.post(frontend.urls.basket_transport + '/' + $('select#transport').val(), function(data) {
                            var parsedData = $.parseJSON(data);

                            // Remove possible classes
                            $delivery.removeClass('feedback error');

                            // Remove errors
                            $delivery.find('.errors').remove();

                            // Hide form
                            $delivery.find('.options').hide();

                            // Parse data to page
                            $resultTransport.find('h2').text(parsedData.transportLabel);

                            $('#basket-total').text(parsedData.total);

                            $resultTransport.find('.amount span').html(parsedData.transportCost);
                            $resultTransport.find('.amount').show();

                            if (parsedData.favvCost != '0,00') {
                                $resultFavv.find('span').html(parsedData.favvCost);
                                $resultFavv.show();
                            } else {
                                $resultFavv.hide();
                            }

                            if (parsedData.transitLabel) {
                                $resultTransitCustoms.find('#transit').html(parsedData.transitLabel);
                            }

                            if (parsedData.customsLabel) {
                                $resultTransitCustoms.find('#customs').html(parsedData.customsLabel);
                                $resultTransitCustoms.find('#customs').show();
                            } else {
                                $resultTransitCustoms.find('#customs').hide();
                            }

                            $resultTransport.find('#pickup-note').hide();
                            $resultTransitCustoms.show();
                            $result.show();
                        });
                    }
                });

//@Todo: refactor repeated code
                // Listen for changes in radiobuttons
                $('input#delivery-pickup').click(function(data) {
                    if($(this).val()) 
                    {
                        // URL needs to be changed, to reflect the dynamic php part
                        $.post(frontend.urls.basket_transport + '/' + $(this).val(), function(data) {
                            var parsedData = $.parseJSON(data);

                            // Remove possible classes
                            $delivery.removeClass('feedback error');
                            
                            // Remove errors
                            $delivery.find('.errors').remove();
                            
                            // Hide form
                            $delivery.find('.options').hide();                   
                            
                            // Parse data to page
                            $resultTransport.find('h2').html(parsedData.transportLabel);

                            $('#basket-total').html(parsedData.total);

                            $resultTransport.find('.amount').hide();

                            $resultFavv.hide();
                            $resultTransitCustoms.hide();

                            $resultTransport.find('#pickup-note').show();
                            $result.show();
                        });
                    }                    
                });

                // Change link click listener
                $delivery.find('a.change').live('click', function(e) {
                
                    // Remove result
                    $delivery.find('.result').hide();
                
                    // Show form    
                    $delivery.find('.options').show();
                    
                    e.preventDefault();
                });                
            }
        },


        delay: (function(){
            var timer = 0;
            return function(callback, ms){
                clearTimeout (timer);
                timer = setTimeout(callback, ms);
            };

        })()
    }
}


$(document).ready(function()
{
	// General javascript interaction
	frontend.init();
});

