﻿$(document).ready(function() {
    setupAutoClears();
    setupForms();
    setupCarousels();
    setupTabs();
    setupHomeBanner();
    setupFancyBox();
    setupMultiImage();
    setupAddToBasket();
    setupCurrencyConverter();
    setInterval('runNewsTicker()', 5000);

    $('.crumbtrail a').each(function() {
       var prodInd = $(this).attr('href').indexOf('/product/');
       if(prodInd > -1)
           $(this).attr('href',$(this).attr('href').substr(prodInd));
    });
});

function setupCurrencyConverter() {
    $('#showCurrencyConverter').click(function () {
        $('#currencyConverter iframe').attr('src', 'http://www.foreignexchangeresource.com/currency-converter.php?curr1=GBP&amt=0&expressedas=EUR&size=250');
        $('#currencyConverter').slideDown();
        return false;
    });
}

function setupMultiImage() {
    $('.multiImage a').click(function () {
        $('#chosenImage .fancyZoom img').attr('src', '');
        $('#chosenImage .fancyZoom img').attr('src', $(this).attr('href'));
        $('#chosenImage .fancyZoom').attr('href', $(this).attr('href').replace('Full', 'Zoom'));
        return false;
    });
}

function setupFancyBox() {
    if (typeof ($('.fancyZoom').fancybox) == 'function') {
        $('a[target="_parent"]').addClass('fancyZoom').attr('target','_self');
        
        $('.fancyZoom').fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'overlayColor': '#bcdcf1'
        });
    }
}

function setupHomeBanner() {
    $('.banner').each(function() {
        var thisBanner = $(this);
        var maxHeight = 0;

        $(this).children('img, a').each(function() {
            if ($(this).height() > maxHeight)
                maxHeight = $(this).height();
        });

        $(this).children('img, a').wrap('<div class="item" />'); //added this so it is easier for them to put in images

        $(this).append('<div class="bannerControl" style="position: relative; width: 100%; height: ' + $(this).children('.item:first').height() + 'px;"><ul style="z-index:3"></ul></div>');
        $(this).children('.item').appendTo('.banner > .bannerControl');
        $(this).children('br').remove();

        var i = 1; 
        $(this).children('.bannerControl').children('.item').each(function() {
            $(this).parent().children('ul').append('<li><a rel="' + i + '">' + i + '</a></li>');
            $(this).parent().children('ul').children('li').children('a[rel="' + i + '"]').click(function() {
                clearInterval(bannerInterval);
                changeBanner(thisBanner, $(this).attr('rel'));
                bannerInterval = setInterval(function() { changeBanner(thisBanner, null); }, 4000);
            });
            $(this).css({
                'position': 'absolute',
                'top': '0px',
                'left': '0px',
                'width': '100%',
                //'width': $(this).parent().width() + 'px',
                'height:': $(this).parent().height() + 'px'
            }).fadeOut(0).attr('rel', i++);
        });

        $(this).children('.bannerControl').children('ul').children('li').children('a:first').attr('class', 'selected');

        $(this).children('.bannerControl').children('.item:first').fadeIn(0).css('zIndex', 1);
        $(this).attr('currentItem', 1);

        bannerInterval = setInterval(function() { changeBanner(thisBanner, null); }, 4000);
    });
}

function changeBanner(thisBanner, nextItem) {
    var prevItem = $(thisBanner).children('.bannerControl').children('.item[rel="' + $(thisBanner).attr('currentItem') + '"]');

    if (nextItem == null) {
        if ($(thisBanner).attr('currentItem') == $(thisBanner).children('.bannerControl').children('.item:last').attr('rel'))
            $(thisBanner).attr('currentItem', 1);
        else
            $(thisBanner).attr('currentItem', parseInt($(thisBanner).attr('currentItem')) + 1);
    }
    else {
        if (nextItem > parseInt($(thisBanner).children('.bannerControl').children('.item:last').attr('rel')) || nextItem < 1)
            return;
        else
            $(thisBanner).attr('currentItem', nextItem);
    }

    $(thisBanner).children('.bannerControl').children('ul').children('li').children('a.selected').removeAttr('class');
    $(thisBanner).children('.bannerControl').children('ul').children('li').children('a[rel="' + $(thisBanner).attr('currentItem') + '"]').attr('class', 'selected');
    $(prevItem).fadeOut(1000);
    $(thisBanner).children('.bannerControl').children('.item[rel="' + $(thisBanner).attr('currentItem') + '"]').css('zIndex', 2).fadeIn(1000, function() {
        $(thisBanner).css('zIndex', 1);
    });
}

function setupTabs() {
    if (typeof $('.tabs').tabs == 'function') {
        $(".tabs li a").click(function() {
            window.location.hash = $(this).attr('href');
        });
        
        $(".tabs").tabs();
    }
}

function runNewsTicker() {
    $('#newsContent ul').animate({
        'marginLeft': (-$('#newsContent ul').width() / 2) + 'px'
    },
    1000,
    'easeInOutQuad',
    function() {
        $(this).children('li:first').appendTo($(this));
        $(this).css('marginLeft', 0);
    });
}

function setupForms() {
    $(window).keypress(function(e) {
        if (e.which == 13)
            return false;
        else
            return true;
    });
    $('.form').find('input').keydown(function(e) {
        if (e.which == 13) {
            if ($(this).parents('.form').find('.formEnter')[0].tagName.toLowerCase() == 'a')
                window.location = $(this).parents('.form').find('.formEnter').attr('href');
            $(this).parents('.form').find('.formEnter').trigger('click');
            return false;
        }
    });
}

function setupAutoClears() {
    $(".autoClear").focus(function() {
        if (!$(this).attr('originalVal')) {
            $(this).attr('originalVal', $(this).val());
            $(this).val('');
        }
    }).blur(function() {
        if ($.trim($(this).val()).length == 0) {
            $(this).val($(this).attr('originalVal'));
            $(this).removeAttr('originalVal');
        }
    });
}

function setupCarousels() {
    if (typeof $(".carousel").children("ul").jcarousel == 'function') {
        if ($('.carousel').children("ul").children('li').length > 9) {
            $('.carousel').children("ul").each(function() {
                $(this).jcarousel({
                    wrap: 'circular',
                    scroll: 5,
                    initCallback: mycarousel_initCallback,
                    buttonNextHTML: null,
                    buttonPrevHTML: null,
                    animation: 1000,
                    easing: 'easeInOutCubic'
                });
            });
        }
        else
            $('.carousel .prevBut, .carousel .nextBut').remove();

        $('.carousel li img').tooltip({
            track: true,
            delay: 0,
            showURL: false,
            bodyHandler: function() {
                return $(this).attr("tooltip");
            }
        }); 
    }
}

function mycarousel_initCallback(carousel) {
    var container = $(carousel.container).parent();
    $(container).children('.nextBut').bind('click', function() {
        carousel.next();
        return false;
    });

    $(container).children('.prevBut').bind('click', function() {
        carousel.prev();
        return false;
    });
};

function setupAddToBasket() {
    $('.addToBasket').click(function() {
        var gtZero = 0;
        var broke = false;
        $('input.qty').each(function() {
            var val = parseInt($(this).val());
            if (isNaN(val) || val < 0) {
                broke = true;
                return false;
            }
            else if (val > 0) {
                gtZero++;
            }
        });

        if (broke) {
            alert('Error adding items to basket. Please make sure any quantities you have entered are in the correct format.');
            return false;
        }

        if (gtZero == 0) {
            alert('Error adding items to basket. Please make sure at least one item has a quantity of more than 0.');
            return false;
        }
    });
}
function compare(productid, val) {
    cookiejar(productid, val, 'productcompare');
}

function cookiejar(productid, val, cookiename) {
    var pitems = '';
    if ($.cookie(cookiename) != null) { pitems = $.cookie(cookiename); }
    if (val) {
        if (pitems != '') {
            $.cookie(cookiename, pitems + ',' + productid, { path: '/', expires: 365 });
        } else {
            $.cookie(cookiename, productid, { path: '/', expires: 365 });
        }
    } else {
        if (pitems != '') {
            var plist = pitems.split(',');
            var nplist = '';
            for (i = 0; i < plist.length; i++) {
                if (plist[i] != productid) {
                    if (nplist != '') { nplist = nplist + ','; }
                    nplist = nplist + plist[i];
                }
            }
            $.cookie(cookiename, nplist, { path: '/', expires: 365 });
        }
    }
}

