$(function() {
    
    // @TODO - why have I wrapped all of these in a doc ready shorthand.
	
    //Make external links open in new tab:
    $('a').filter(function() {
        return !this.href.match(/^mailto\:/)
        && (this.hostname != location.hostname);
    }).attr('target','_blank');
     
    // Dirty product helper
    
 var origHeadHeight;
    
    $('header li.services').on('mouseenter', function(e){
       
       $('header > div.subnav').stop(true, true).fadeIn();
        
    }).on('mouseleave', function(e){
        
       
        
        if(e.pageY > 70){
           return;  
        }
        
         $('header > div.subnav').stop(true, true).fadeOut();
        
    });
    
    $('header nav li:not(.services) a').on('hover', function(){
         $('header > div.subnav').stop(true, true).fadeOut();
    });
   
   
    
    $('header > div.subnav').on('mouseleave', function(){
       
            $(this).stop(true, true).fadeOut();
        
    });
    
    
    // hero 
    (function(){
	
        var heroUL = $('#hero').find('ul:first'),
        heroLI = heroUL.find('li'),
        heroItems = heroLI.length,
        heroNav = $('#hero').find('ul.nav'),
        heroPrev = heroNav.find('li:first'),
        heroNext = heroNav.find('li:last'),
        heroPages = heroNav.find('a.page'),
        moveDirection = 'next',
        navType = 'standard',
        currentIndex = 0,
        targetIndex = 1,
        init = function(){
			
            heroNav.css({
                'width': heroLI.length * 40
            }); 
            var counter = 1;
				
            while(counter <= heroItems){
				
                var heroNavItem = $('<li><a href="#" class="page">' + counter + '</a></li>').insertBefore(heroNext).find('a').on('click', function(e){
                    e.preventDefault();
                    navType = 'standard';
                    targetIndex = $(this).parent('li').index();
                    switchHero();
                });
				
                counter ++;
            }
			
            heroPrev.on('click', function(e){
                e.preventDefault();
                navType = 'nextprev';
                moveDirection = 'prev';
                targetIndex = 0;
                switchHero();
            });
            heroNext.on('click', function(e){
                e.preventDefault();
                navType = 'nextprev';
                moveDirection = 'next';
                targetIndex = 0;
                switchHero();
            });
            targetIndex = 0;
            heroNav.find('li:eq(1) a').addClass('current');
            heroUL.find('.opener').fadeIn('fast');
            /*
            setInterval(function(){
               navType = 'nextprev';
               moveDirection = 'next';
               targetIndex = 0;
               switchHero();  
            }, '10000');
            */
            //switchHero();

			
        },
        switchHero = function(){
				
            targetIndex = (targetIndex == 0 ? 0 : targetIndex -= 1);
            /*
            if(currentIndex == targetIndex){
                
                if(heroUL.find('li:eq(' + currentIndex + ')').next().length){
                    targetIndex = currentIndex + 1;
                }else{
                    targetIndex = 0;
                }
            }
            */
            var heroHiding = heroUL.find('li:eq(' + currentIndex + ')');
            var heroShow = heroUL.find('li:eq(' + targetIndex + ')');
            
            
				
            if(navType == 'nextprev'){
			
                switch(moveDirection){
				
                    case "prev" :
                        heroShow = heroUL.find('li:last');
                        if(heroHiding.prev().length){
                            heroShow = heroHiding.prev();
                        }
                        break;
                    case "next" :
                        heroShow = heroUL.find('li:first');
                        if(heroHiding.next().length){
                            heroShow = heroHiding.next();
                        }
                        break;
                }
					
                targetIndex = heroShow.index();
					
					
					
            }

				
            heroHiding.fadeOut();
            heroShow.fadeIn();

            currentIndex = targetIndex;
				
            actualNavIndex = currentIndex + 1;
            heroNav.find('li:eq(' + actualNavIndex + ') a').addClass('current').parent().siblings().find('a').removeClass('current');
			
        };	
        init();
        
    })();
	
   
	
    // Estimation Total
    (function(){
	
        var amount = 0,
        deducted = 0,
        calculatable = $('#BookingDetailEstimateForm'),
        calculator = $('.calculator'),
        totalHolder = calculator.find('#etotal'),
        franchiseMinimum = calculator.find('#fminimum').html(),
        discountAmount = calculator.find('#promo_amount').html(),
        discountType = (calculator.find('#promo_type').html() == '%' ? 'percentage' : 'pound');
			
        if(calculatable.length){

            calculateTotal = function(){
			
                amount = 0;
			
                var selected = calculatable.find('input[type=radio]:checked');

                selected.each(function(){
                    amount += $(this).parent().data('price') * $(this).parent().parent().find('.multiplier option:selected').val();
                });
			
                if(discountAmount > 0){
				
                    switch(discountType){
                        case 'percentage':
                            deducted = (amount * (1 - (discountAmount / 100)));
                            amount -= amount - deducted;
                            break;
                        default:
                            amount -= discountAmount;
                            break;
				
                    }
				
                }
			
                updateTotal(amount.toFixed(2));
		
            }
		
            updateTotal = function(amount){
                
		if(Number(amount) > Number(franchiseMinimum).toFixed(2)){
                        calculator.removeClass('belowmin');
                }else{
                        calculator.addClass('belowmin');
                        amount = franchiseMinimum;
                }
                totalHolder.html('&pound;' + amount);
                
                    
               
            }
		
            calculateTotal();
		
            calculatable.find('select').on('change', function(){
		
                calculateTotal();
		
            });
		
            calculatable.find('input[type=radio]').on('click', function(){
		if($(this).parent().parent().find('.multiplier option:selected').val() == ""){
                    $(this).parent().parent().find('.multiplier option:eq(1)').attr('selected', 'selected');
                }
                calculateTotal();
		
            });
		
        }
	
    })();
        
    // Show find nearest
    (function(){
            
        var nearestPanel =  $('#nearest');
           
        if(nearestPanel.length){
            nearestPanel.css('opacity', 0);
            $('#find').on('click', function(e){
                e.preventDefault();
                nearestPanel.animate({
                    top:-8,
                    height:275,
                    opacity:1
                }, 1000);   
               
            });
                    
            nearestPanel.find('a').on('click', function(e){
                e.preventDefault();
                nearestPanel.animate({
                    height:0, 
                    top:-48,
                    opacity:0
                }, 1000);      
            });
                    
        }
           
    })();
        
    // Banner Overlay Helper
    (function(){
           
        var bannerOverlay = $('.banneroverlay');
           
        if(bannerOverlay.length){
            
            /*
                alert(bannerOverlay.prev().find('img').offset().top);
                var distance = bannerOverlay.prev().offset().top + bannerOverlay.outerHeight();
                 */
                
            var height = 0 - (bannerOverlay.outerHeight() + 20);
            bannerOverlay.css('marginTop', height);
            
        }
            
    })();
        
    // Logo fade effect
    (function(){
            
        $('header h1').on('mouseenter', function(){
                
            $(this).animate({
                'top':14, 
                'opacity':0.8
            }, 250);
                
        }).on('mouseleave', function(){
             
            $(this).animate({
                'top':18, 
                'opacity':1
            }, 250);
             
        });
            
    })();
        
    // tabbed boxes
    (function(){
           
        var tabbed = $('.tabbed');
           
        if(tabbed.length){
               
            var tabbedNav, tabbedListings, activeIndex = 0;
             
            init = function(tabbed){
                 
                tabbedNav = tabbed.find('nav');
                tabbedListings = $('div > ul', tabbed);
                 
                tabbedNav.find('ul li:first').addClass('active');
                tabbedNav.find('ul li').on('click', function(e){
                    e.preventDefault();
                    $(this).siblings().removeClass('active').end().addClass('active');
                    switchTabbed($(this).index());
                     
                });
                 
            },
             
            switchTabbed = function(sIndex){
               
               
                tabbedListings.eq(activeIndex).fadeOut('fast', function(){
                
                    tabbedListings.eq(sIndex).fadeIn('fast');
                    activeIndex = sIndex;
                   
                });
               
                 
            },
             
            tabbed.each(function(){
                 
                init($(this));
                 
            });
               
        };
           
    })();
    
    
    // Basket
    (function(){
        
        var shippingMethods = $('form.shipping');
        
        if(shippingMethods.length){
                
            var shippingOptions = shippingMethods.find('input[type=radio]'),
            deliveryTotal = $('#delivery'),
            orderTotalHolder = $('#total'),
            orderTotalAmount = Number(parseFloat(orderTotalHolder.html().replace('£', '').replace(',', ''))),
            orderSubTotalAmount = Number(parseFloat($('#subtotal').html().replace('£', '').replace(',', ''))),
            changedID,
            shippingAmount;
            
            if($('#promotionamount').length){
                var promotionAmount = Number(parseFloat($('#promotionamount').html().replace('£', '').replace(',', '')));
            }else{
                var promotionAmount = 0;
            }
                
            shippingOptions.on('change', function(){
                        
                changedID = $(this).attr('id');
                shippingAmount = shippingMethods.find('label[for=' + changedID + ']').find('span').html();
                deliveryTotal.html(shippingAmount);
                shippingAmount = Number(shippingAmount.replace('£', ''));
                orderTotalHolder.html('£' + ((orderSubTotalAmount + shippingAmount) - promotionAmount).toFixed(2));
                        
            });
                
        }
        
        
    })();
       
	
    if($('#prefered_date').length){
        var minidate = new Date();
        minidate.setDate(minidate.getDate() + 2);
        $('#prefered_date').datepicker({
            defaultDate : $('#BookingPreferedDate').val(),
            minDate : minidate,
            changeMonth: true,
            changeYear: true,
            altField: "#BookingPreferedDate",
            dateFormat: "yy-mm-dd 00:00:00",
            altFormat: "yy-mm-dd 00:00:00",
            firstDay : 1,
            dayNamesMin: ["Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"],
            monthNamesShort: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
                    
        });
    }
          
    (function(){
              
        var calculatorcontinue = $('.calculator .continue');
              
        if(calculatorcontinue.length){
                  
            calculatorcontinue.on('click', function(e){
                     
                e.preventDefault();
                    
                $('form[data-triggerable=1]').submit();
                      
            });
                  
        }
              
    })();
          
    if(!Modernizr.input.placeholder){





        $('[placeholder]').focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        }).blur(function() {
            var input = $(this);
            if (input.val() == '' || input.val() == input.attr('placeholder')) {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }
        }).blur();


        $('[placeholder]').parents('form').submit(function() {
            $(this).find('[placeholder]').each(function() {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                }
            })
        });
    }
    
    // Checkout Panels
    (function(){
        
        var checkoutPanels = $('.panel');
        
        // Check that panels actually exist
        if(checkoutPanels.length){
            
            var checkoutHolder = $('#checkoutdetails'),
            currentPanel = checkoutHolder.find('.panel:first'),
            completeOrder = $('#completeOrder'),
            existingSelectors = checkoutHolder.find('fieldset.selectexisting select');
            
            // Init function
            init = function(){
            
                // Enable 'ketchup' validation on main form
                checkoutHolder.parent('form').bind('fieldIsInvalid', function(event, form, el) {
                    el.parents('.panel').slideDown('fast');
                }).ketchup();

                // Loop each checkout panel
                checkoutPanels.each(function(i){
                   
                    $(this).data('oh', $(this).outerHeight());
                   
                    if(i > 0){
                        $(this).slideUp('fast');
                    }
                    
                    $(this).find('.next').css('display', 'block').on('click', function(e){
                        
                        e.preventDefault();
                        switchPanel(currentPanel.next().next('div.panel'));

                    });
                
                    $(this).prepend($('<ul/>', {
                        'class':'error js'
                    }));

                });
                
                $('.panelhead').on('click', function(e){
                    e.preventDefault();
                    switchPanel($(this).next());
                        
                });
                
                completeOrder.css('display', 'none');
                
                existingSelectors.on('change', function(){
                   
                    if($(this).val() != ""){
                        $(this).parent().siblings(':not(.next)').slideUp('fast').find('input');
                        $(this).parents('div.panel').addClass('usingexisting');
                    }else{
                        $(this).parent().siblings(':not(ul.error)').slideDown('fast');
                        $(this).parents('div.panel').removeClass('usingexisting');
                    }
                   
                   
                   
                });
                
            },
            
            switchPanel = function(goTo){
               
                var toHide = currentPanel;
                var toShow = goTo;
               
               
                if(validatePanel()){
                    currentPanel.find('ul').hide();
                    $('.ketchup-error').hide();
                    currentPanel = goTo;
                    toHide.slideUp(500);
                    toShow.slideDown(500, panelExtra());
                   
                }

            },
            
            // Validate individual panels
            validatePanel = function(){
                
                if(currentPanel.hasClass('usingexisting')){
                    return true;
                }
                
                var toValidate = currentPanel.find('input[data-validate]'),
                amountToValidate = (toValidate.length - 1),
                error = false,
                passed = true,
                amountOfErrors = 0,
                errorHolder = currentPanel.find('ul');

                toValidate.each(function(index){
                    
                   
                    // Check if the given field is valid
                    var valid = $(this).ketchup('isValid') ? 'valid' : 'invalid';

                    // Check if an error message already exists for this field
                    var existingError = errorHolder.find('li.' + $(this).attr('id'));
                    
                    if(valid == 'invalid'){
                        
                        
                        errorHolder.show('fast');
                        
                        if(!existingError.length){
                            
                            $('<li/>', {
                                'class': valid + ' ' + $(this).attr('id'),
                                text   : $(this).prev('label').html() + ' is required and must be valid'
                            }).appendTo(errorHolder);
                            
                            $('.ketchup-error').hide();
                        }

                        amountOfErrors ++;
                        
                    }else{
                        if(existingError.length){
                            
                            existingError.remove();
                        }
                    }
                   
                    if(index == amountToValidate && amountOfErrors > 0){
                        passed = false;
                    }else if(index == amountToValidate && amountOfErrors == 0){
                        passed = true;
                    }   
  
                    
                   
                });
               
                return passed;
               
                
            }
            
            panelExtra = function(){
                
                // special functions for individual panels
                
                if(currentPanel.hasClass('billing')){
                    
                    $('input#BillingAddressAddressPhone').val($('input#DeliveryAddressAddressPhone').val());
                    $('input#BillingAddressAddressEmail').val($('input#DeliveryAddressAddressEmail').val()).parents('fieldset').hide();
                    

                    if(!$('.panel.delivery').hasClass('usingexisting')){
                        
                   
                        $('#usesame').show('fast').on('click', function(e){
                        
                            e.preventDefault();
                        
                            $(this).addClass('alt');
                        
                            $('.delivery input').each(function(){
                            
                                var nameMatch = $(this).attr('id').replace('Delivery', 'Billing');
                                $('#' + nameMatch).val($(this).val());
                            
                            
                            });
                        
                        });
                    
                    }
                    
                }
                 
                if(currentPanel.hasClass('complete')){
                     
                    completeOrder.css('display', 'block');
                     
                }
                
                
                
            }

            init();
        
        }
        
    })();
    
    if($('#payment-envelope').length){
        
        setTimeout(function(){
            
            $('#payment-envelope').trigger('submit');
            
        }, 1000);
        
    }
    
    if($('.portalvideo').length){
        
        var vidurl = $('.portalvideo').data('vid');

        jwplayer("vid").setup({
            flashplayer: "/flash/player.swf",
            file: "/videos/portal/" + vidurl,
            height: 600,
            width: 990
        });
        
    }

    if($('.equipment_images').length){
        
        $('.equipment_images').find(".fancybox").fancybox({
                openEffect	: 'none',
                closeEffect	: 'none'
        });
        
    }
    if($('ul.equipment').length){
        $('ul.equipment').find('.fancybox').fancybox({
                    openEffect	: 'none',
                    closeEffect	: 'none'
        });
    }
    
    if($('textarea.richtext').length) {
		tinyMCE.init({
                       
			// General options
			mode : "specific_textareas",
			editor_selector : 'richtext',
			theme : "advanced",
			plugins : "gateauimage,table,advlink,inlinepopups,media,searchreplace,contextmenu,paste,fullscreen,noneditable,visualchars,xhtmlxtras",
		
			// Theme options
			theme_advanced_buttons1 : 'bold,italic,removeformat,|,bullist,numlist,|,undo,redo',
			theme_advanced_buttons2 : '',
			theme_advanced_buttons3 : '',
			theme_advanced_buttons4 : '',
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			theme_advanced_resize_horizontal : false,
			
			convert_urls: false,
                        extended_valid_elements: "iframe[class|src|frameborder=0|alt|title|width|height|align|name]"
                        
		
		});
	}
        
        // ajax accordions & search
        if($('body').hasClass('portal_products')){
            
            // list
            var list;
            
            // Click event for accordion headers
            $('.catheader a').on('click', function(e){
               
               e.preventDefault();
               
               // If already loading
               if($(this).hasClass('loading')){
                   return;
               }
               
               $(this).addClass('loading');
               
               // Get the cat id being searched for
               var catid = $(this).data('catid');
               
               // Get the targeted category list holder
               list = $('ul.products').filter(function(){
                       return $(this).data('catid') == catid
               });
               
               // If open just close
               if(list.hasClass('open')){
                   closePanel(list);
                   return;
               }
               
               // If opened previously don't do another call, just open what's already there
               if(list.hasClass('opened')){
                    openPanel(list);
                    return;
               }
               
               // The ajax call
               $.ajax({
                  url:'/portal/portal_products/getcat/' + catid
                  
               }).success(function(data){
                   
                   // On success append the results and open the list
                   list.append(data);
                   openPanel(list);
                   
               }).error(function(){
                   
                   // There's been a problem!
                   alert('There was a problem, please try again');
                   
               });
               
            });
            
            // Open panel function
            function openPanel(list){
                
                var noOfRooms = Math.ceil(list.find('li').length / 4);
                var listHeight = 151 * noOfRooms;
               
                list.animate({'height': listHeight}, 500).addClass('open').addClass('opened');
                list.prev('h3').find('a').html('Hide Products').removeClass('loading');
                   
            }
            
            // Close Panel
            function closePanel(list){
                list.animate({'height': 0}, 500).removeClass('open');
                list.prev('h3').find('a').html('Show Products').removeClass('loading');
            }
            
            // Search
            var searchForm = $('#productsearch');
            
            searchForm.on('submit', function(e){
                
                e.preventDefault();
                
                // Add loading class
                var form = $(this);
                    form.addClass('loading');
                
                // Get the query
                var query = $(this).find('input').val();
                
                // Check that the query is at least 3 characters long
                if(query.length < 3){
                    alert('Search terms too broad, please ensure search contains at least 3 characters.');
                    return;
                }
                
                // Don't bother making any calls if the query is empty
                if(query != ''){
                    
                    // Call
                    $.ajax({

                        url:'/portal/portal_products/search/' + query

                   }).success(function(data){
                    
                        // Hide no results message
                        $('#noresults').hide('fast');

                        // Check if the results list already exists, if it does then just append the data to this rather than creating the whole thing again.
                        if($('ul.products.results').length){
                            list = $('ul.products.results').find('li').hide().end().append(data);
                        }else{
                            list = $('<ul />', {
                            'class':"products results"
                            }).append(data);
                            $('#PortalProductIndexForm').prepend(list);
                            $('<h3 />', {html:'Search Results', 'class':"catheader"}).insertBefore(list);
                        }

                        // Number of rows/height calulations
                        var noOfRows = Math.ceil(list.find('li:visible').length / 4);
                        var listHeight = 125 * noOfRows;

                        list.css('height', listHeight);

                        // No results mesaage
                        if(noOfRows == 0){

                            $('<p />', {html:'<strong>No results for your search terms, please try again.</strong>', id:'noresults'}).insertAfter(list);

                        }
                        
                        // Remove the loading message
                        form.removeClass('loading');
                        
                    }).error(function(){
                        
                        // There's was a problem!
                        alert('There was a problem, please try again');
                        form.removeClass('loading');

                    }); 
                    
                }
                
            })
            
        }
	
});


$(window).load( function(){

    // Shop Product Gallery - @todo tidy
    (function(){
           
        var gallery = $('#gallery');
           
        if(gallery.length){
            $('.description').children().css('opacity', 0).end().slideUp('fast', function(){
                   
                $('#gallery').css({
                    'top': $('#gallery').position().top, 
                    'bottom':'auto'
                });
                $('.addthis_toolbox').css({
                    'top': $('#gallery').position().top, 
                    'bottom':'auto'
                });
                   
            });
            //zoom position helper
            $('.zoom').css({ 
                'bottom':'auto'
            }).on('click', function(e){
                   
                e.preventDefault();
                var galStart = gallery.find('li:first a.fancybox')
                galStart.trigger('click');
            }); 
               
               
               
            gallery.find(".fancybox").fancybox({
                openEffect	: 'none',
                closeEffect	: 'none'
            });
               
            $('a.moreinfo').on('click', function(e){
                e.preventDefault();
                var clicked = $(this);
                if($(this).html() == 'Less Info'){
                    $('.description').slideUp().animate({
                        'paddingTop' : '-=60'
                    }, 150, function(){
                        
                        $(this).children().css('opacity', 0);
                        clicked.html('More Info');
                        
                    });
                    
                    return;    
                }
                 
                $('.description').slideDown().animate({
                    'paddingTop' : '+=60'
                }, 150, function(){
                     
                    $(this).children().delay(200).animate({
                        'opacity': 1
                    }, 500);
                    clicked.html('Less Info');
                });
                

                 
                  
            }); 
               
        }
           
           
           
    })();

});
