$(function () {
    // Detects double lines and adds a class
    $('.tabbed .tabs li a').find('br').parent().addClass('dl');
    // Removes the pipe ('|') on the last element on the sub navigation
    var subNavLastLink = $('#header .nav .subNav li').last().find('a');
    $('#header .nav .subNav li').last().html(subNavLastLink);
    // Finds all selected inputs with default text and removes it on focus
    function initVal(obj) {
        obj = $(obj).find('input[type="text"]');
        obj.each(function (i, el) {
            var defaultTxt = $(el).val();
            $(el)
                .data('defaultTxt', defaultTxt)
                .focus(function () {
                    if ($(this).val() == $(el).data('defaultTxt')) $(this).val('');
                })
                .blur(function () {
                    if ($(this).val() == '') $(this).val($(el).data('defaultTxt'));
                });
                // hack alert : This is a (dirty) workaround because of strange behaviour with ga click handlers not firing.
                // Handler *will* fire if we remove focus from text input just before user clicks submit.
                $(el).parent().find('input.btn-purpleShort').mousemove(function () {
                    $(el).blur();
                });
        });
    }
    /* The list of items which have default text */
    initVal('.searchBox');
    initVal('.homePageFourUp');
    initVal('#rightColumn .rightPod');
    initVal('#content .quickSearchDiv');

    var inp = $(".postcodeSF");
    if (inp.length) {
        var defaultTxt = inp.val();
        inp.data('defaultTxt', defaultTxt);
        var onBlurFn = function () {
            (inp.val() == inp.data('defaultTxt')) ? inp.removeClass('uppercase') : inp.addClass('uppercase');
        }
        onBlurFn();
        inp.focus(function () { $(this).addClass('uppercase'); }).blur(onBlurFn);
    }

    //add focus animation for search box
    $('.searchBox').find('select, input').focus(function () {
        $(this).parent().css("backgroundPosition", "right");
    });
    $('.searchBox').find('select, input').blur(function () {
        $(this).parent().css("backgroundPosition", "left");
    });

    // Add Striping to User generated tables
    $('.infoTable .freeText table').find('tr:even').addClass('alt');


    // The 'Email a Friend' lightbox
    //$("#content").append($('#eafLightBox'));  // move EAF to bottom of page so we can absolutely position off body as parent
    var closeBtn = $('<span class="btn-close">Close</span>').appendTo('#eafLightBox');
    $(closeBtn).click(function (e) {
        e.preventDefault();
        $('#eafLightBox').toggle();
    });
    $('.eafLink').click(function (e) {
        e.preventDefault();
        var eafPos = $("a.eafLink").position();
        $('#eafLightBox')
            //.css({ 'top': eafPos.top - 166, 'left': eafPos.left - 8 })
            .toggle();
    });
    $("#eafLightBox input.emailAddress").keyup(function () {
        var trimmed = $(this).val().trim();
        $(this).val(trimmed);
    });

    // Adds functionality to tabbed boxes (use postback for fallback)
    function tabify(obj) {
        obj = $(obj);
        var tab = obj.find('.tabs > li a')
        var content = obj.find('.content > div')
        //Counts how many tabs there are and compares with how many content boxes there are, if they are mismatched, log an error
        var tabCount = tab.length;
        var contentCount = content.length;
        //if (tabCount != contentCount) console.info('The number of tabs does not match the content - errors may occur');
        tab.click(function (e) {
            e.preventDefault();
            if ($(e.target).closest('li').hasClass('active')) return false;     // do nothing if already open
            tab.parents('li').removeClass('active')
            content.hide();
            var currentTab = $(this).parents('li')
            var tabNo = currentTab.attr('class').replace('tab', '');
            content.parent().find('.content' + tabNo).show();
            currentTab.addClass('active')
        });

    }
    tabify('.homePageGreyPod');
    tabify('.infoTable');

    // Product page
    function showProductImage(n) {
        $(".product-images img").hide();
        $(".product-images img:nth-child(" + n + ")").fadeIn();
    }
    showProductImage(1);

    $(".productDetailContainer #product-thumbnails li").each(function (i, el) {
        $(el).click(function (e) {
            e.preventDefault();
            var index = $(this).index();
            showProductImage(index + 1);
        });
    });

    if ($(".ourProducts .prodPod").length) {
        var tallest = 0;    // set height of all pods to height of tallest prodPod at top of page
        $(".ourProducts .prodPod .inner").each(function () {
            if ($(this).height() > tallest) tallest = $(this).height();
        });
        $(".ourProducts .prodPod .inner").height(tallest);
    }

    // FAQ Accordion
    var faq = $('.faq');
    var dt = faq.find('dt').css('cursor', 'pointer');
    var dd = faq.find('dd').hide();
    dt.hover(
		function () {
		    if ($(this).next('dd').is(':hidden')) {
		        $(this).addClass('active');
		    }
		},
		function () {
		    if ($(this).next('dd').is(':hidden')) {
		        $(this).removeClass();
		    }
		});
    dt.click(function () {
        if ($(this).next('dd').is(':visible')) {
            dd.slideUp();
            dt.removeClass();
        } else {
            dd.slideUp();
            dt.removeClass();
            $(this).addClass('active');
            $(this).next('dd').slideDown();
        }
    })

    // Equalises the heights of the divs on the contact form
    var setInfoHeight = $('.form .formCol').height();
    $('.form .infoCol').css('height', setInfoHeight + 'px');

    // Range slider
    function initRangeOptions() {
        if (!$('.minSpend').length) return;

        var select1 = $('.minSpend');
        var selectedOpt1 = $('option:selected', select1).val();
        var select2 = $('.maxSpend');
        var selectedOpt2 = $('option:selected', select2).val();
        $('option', select1).add('option', select2).remove();   // remove all options from the DOM

        for (var x = 0; x < 31; x++) {
            var opt = $('<option value="' + x + '">' + x + '</option>');
            if (selectedOpt1 == x) opt.attr('selected', 'selected');
            opt.appendTo(select1);

            var opt2 = $('<option value="' + x + '">' + x + '</option>');
            if (selectedOpt2 == x) opt2.attr('selected', 'selected');
            opt2.appendTo(select2);

            if ((x == 30) && (!$("#UpdatePanel1 .slider-range").length)) {
                addRangeSlider();
            } 

        }

        // re-attach range slider
        //if (!$("#UpdatePanel1 .slider-range").length) addRangeSlider();
    }
    initRangeOptions();

    function addRangeSlider() {
        if ($('.slider-range').length) return;

        $('<div class="slider-range"></div>').prependTo('.rangeSlider');
        var select1 = $('.minSpend');
        var select2 = $('.maxSpend');
        if (select1.length >= 1) {
            var slider = $(".slider-range");
            slider.slider({
                range: true,
                animate: true,
                //min: 1,
                min: 0,
                max: 30,
                //values: [select1[0].selectedIndex + 1, select2[0].selectedIndex + 1],
                values: [select1[0].selectedIndex, select2[0].selectedIndex],
                stop: function (event, ui) {
                   //__doPostBack('UpdatePanel1', ''); // edit this to change the name of the UpdatePanel
                },
                slide: function (event, ui) {
                    //select1[0].selectedIndex = ui.values[0] - 1;
                    //select2[0].selectedIndex = ui.values[1] - 1;
                    select1[0].selectedIndex = ui.values[0];
                    select2[0].selectedIndex = ui.values[1];
                },
                change: function (event, ui) {
                    var minValue = $(".slider-range").slider("values", 0);
                    var maxValue = $(".slider-range").slider("values", 1);

                    if ((lastHandle == "leftHandle") && (minValue == maxValue)) {
                        $(".slider-range").slider("option", "values", [minValue - 1, maxValue]);
                        select1[0].selectedIndex = (minValue-1);
                    } else if ((lastHandle == "rightHandle") && (minValue == maxValue)) {
                        $(".slider-range").slider("option", "values", [minValue, maxValue + 1]);
                        select2[0].selectedIndex = (maxValue + 1);
                    }

                    //$(".slider-range").slider("destroy"); // explicitly destroys the slider object before re-creating it
                    __doPostBack('UpdatePanel1', ''); // edit this to change the name of the UpdatePanel
                }
            });

            $(".slider-range a:eq(0)").attr("id", "leftHandle");
            $(".slider-range a:eq(1)").attr("id", "rightHandle");

            var lastHandle = null;
            $(".slider-range a").focus(function () {
                lastHandle = $(this).attr("id");
                //console.log(lastHandle);
            });

            $('.minSpend').change(function (e) {
                //if ($(this).val() >= select2[0].selectedIndex + 1) {        // validation - can't set to more than max val
                if ($(this).val() >= select2[0].selectedIndex) {
                    //select1[0].selectedIndex = select1.data('minVal') - 1;
                    select1[0].selectedIndex = select1.data('minVal');
                    return;
                }
                slider.slider({
                    animate: true,
                    values: [$(this).val(), select2.val()]
                });
            });
            $('.maxSpend').change(function (e) {
                //if ($(this).val() <= select1[0].selectedIndex + 1) {        // validation - can't set to less than min val
                if ($(this).val() <= select1[0].selectedIndex ) {
                    //select2[0].selectedIndex = select2.data('maxVal') - 1;
                    select2[0].selectedIndex = select2.data('maxVal');
                    return;
                }
                slider.slider({
                    animate: true,
                    values: [select1.val(), $(this).val()]
                });
            });

            // store current values to use when resetting if validation fails
            var minVal = $('option:selected', select1).val();
            select1.data('minVal', minVal);
            var maxVal = $('option:selected', select2).val();
            select2.data('maxVal', maxVal);
        }
    }

    addRangeSlider();

    // add listener for completed __doPostBack and re-attach slider if required
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_pageLoaded(initRangeOptions);
});

/*********************** Large Slider ***********************************/
(function($){
			$.fn.slideshow = function(options){
				var opts = $.extend({}, $.fn.slideshow.defaults, options);
				
				return this.each(function(){
					
					var holder = $(this);
					
					//A wrapper class is used to hold the images and make animating them easier.
					var wrapper = $('<div class="wrapper" />').appendTo(holder);
					
					if (opts.arrows){
						var arrowLeft = $('<a href="#" class="arrow aleft" title="Previous slide" />').click(function(){ slide(-1); return false; }).appendTo(holder);
						var arrowRight = $('<a href="#" class="arrow aright" title="Next slide" />').click(function(){ slide(1); return false; }).appendTo(holder);
					}
					var imageCount = $('.imageWrap').length;
					if (imageCount > 1) var dots = $('<ul class="dots" />').appendTo(holder);
					
					var width = holder.width();
					
					// Slide function, works by finding the active dot and click the next or previous one
					var slide = function(dir){
						if (dir > 0){
                            if(dots && dots != null) {
							    var nextDot = dots.find('.active').parent().next();
							    if (nextDot.length == 0) nextDot = dots.find('li:first-child');
                            }
						}
						else {
							if(dots && dots != null) {
                                var nextDot = dots.find('.active').parent().prev();
							    if (nextDot.length == 0) nextDot = dots.find('li:last-child');
                            }
						}
						if(nextDot != null && nextDot)
                            nextDot.find('a').click();
					}
					
					var count = 0;
					holder.find('.imageWrap').each(
						function(){
							// Move the image into the wrapper
							var image = $(this).appendTo(wrapper);
								count++;
							// Add the dots
							$('<a href="#" title="Go to slide '+count+'"><img src="/images/blank.gif" /></a>')
								.data('left', (count - 1) * -width) // Store new left for each dot
								.click(function(){
									//Clear and restart timer
									clearInterval(interval);
									interval = setInterval(function(){ slide(1); }, opts.interval);
								
									// Reassign the active class on the dots
									dots.find('.active').removeClass('active');
									var dot = $(this).addClass('active');
									// Slide the slides to the corrext position
									// Different easing options can be used, easeOutBounce, easeOutElastic, etc...
									wrapper
										.stop(true,true)
										.animate({left: dot.data('left') },1000,'easeInOutQuint');
									return false;
								})
								.appendTo(dots)
								// Wrap the <a>'s in <li>'s so the can go in the <ul>
								.wrap('<li />');
						}
					);
				
					// Set the first dot to active
					if(dots) { dots.find('li:first-child a').addClass('active'); }
                        
				
					// Make wrapper fit the images
					wrapper.css({width : width * count + 1});
					
					// Start the interval
					var interval = setInterval(function(){ slide(1); }, opts.interval);
					
					// find the button and show it
					$('.slideShow .btnRounded').show();
					
					//remove the default link around the main image
					$('.noJs').find('img').unwrap();
				});
			}
			$.fn.slideshow.defaults = {
				interval : 8000,
				arrows : true
			}
		})(jQuery);

		$(function(){
			$('.slideShow').slideshow();
		});
	

