// JavaScript Document

$(document).ready(function () {

    // declare easing:
    $.easing.easeOutQuint = function (x, t, b, c, d) {
        return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
    };

    // collapse All filterSelect, and bind hover:

    $('div.filterSelect').find('ul').css('position', 'absolute').hide();
    $('div.filterSelect').hover(function () {
        $(this).find('ul').show();
    }, function () {
        $(this).find('ul').hide();
    });


    // Category listing hover:
    // First, reverse zIndex for IE.
    $('#categoryListing li').each(function () {
        $(this).hover(function () {
            $(this).css('z-index', 99).append('<span class="hover"></span>');
            createLinks($(this));
        }, function () {
            $(this).css('z-index', 0);
            $('span.hover').remove();
        });
    });

    // slide out view/hide shipping options on Cart page
    var shoppingCart = $('#shoppingCart');
    if (shoppingCart.size() > 0) {
        shoppingCart.find('span.viewShippingOptions').toggle(function () {
            shoppingCart.find('div.shippingOptionsInfo').slideDown({ duration: 600, easing: 'easeOutQuint' });
            $(this).addClass('open');
        }, function () {
            shoppingCart.find('div.shippingOptionsInfo').slideUp({ duration: 600, easing: 'easeOutQuint' });
            $(this).removeClass('open');
        });
    }

    // Product Detail Tabs and custom scroll
    if ($('#productDetail').size() > 0) {
        // enable custom scroll
        $('#productDetail div.tabContent').jScrollPane({ scrollbarWidth: 13, showArrows: true });

        // enable tabs
        $('#productDetail div.tabs').tabs({ fx: { opacity: 'toggle', duration: 100} });
        //remove the warranty tab - to be removed it must have the id "tabsWarranty"
        var index = $('#productDetail a[href="#tabsWarranty"]').parent().index();
        if (index != -1) {
            $('#productDetail div.tabs').tabs('remove', index);
        }

        // enable custom scroll on shipping options
        var shipOptions = $('#productDetail').find('div.shippingOptions');
        var shipInfo = shipOptions.find('div.shippingOptionsInfo');

        shipInfo.css('position', 'absolute').hide();
        shipOptions.find('span.toggleShippingOptionsShow').click(function () {
            shipInfo.slideDown({ duration: 400, easing: 'easeOutQuint' });
            $(this).hide();
            $(this).next('span.toggleShippingOptionsHide').show();
        });
        shipOptions.find('span.toggleShippingOptionsHide').click(function () {
            shipInfo.slideUp({ duration: 400, easing: 'easeOutQuint' });
            $(this).hide();
            $(this).prev('span.toggleShippingOptionsShow').show();
        });
    }

    // PrintPage
    $('#productDetail #printPage').show().bind('click', function () {
        //window.print();
    });

    // Show / Hide content on News and Events listing
    $('#newsEventsGallery').find('div.hide').each(function () {
        $(this).hide();
    });
    $('#newsEventsGallery').find('a.readmore').toggle(function () {
        $(this).siblings('.hide').show();
        $(this).html('Hide more');
        return false;
    }, function () {
        $(this).siblings('.hide').hide();
        $(this).html('Read more');
        return false;
    });
    // bind toggle



    /* Image Swticher */
    var imageSwitch = function (imageSwitchPaging, e) {

        var tagMatch = false;
        var clicked = $(e.target);
        var clickedTag = e.target.tagName;
        var clickedIndex = $(e.target).index();

        if (clickedTag.match('LI')) {
            $('li', imageSwitchPaging).removeClass('on');
            clicked.addClass('on');
            tagMatch = true;
        }
        if (tagMatch) {
            return clickedIndex;
        }
    };

    var embedVideo = function (video) {
        var params = {};
        params.menu = "false";
        swfobject.embedSWF(embedDetails.player, embedDetails.id, embedDetails.width, embedDetails.height, embedDetails.version, embedDetails.flash, video, params);
    }

    /* Image Switcher on Product Detail */
    var productDetail = $('#productDetail');
    if (productDetail.size() > 0) {
        var selectedIndex = 0;
        var productDetailImage = $('#productDetailImage').find('img');
        var paging = productDetail.find('.productPaging');

        paging.click(function (e) {
            var clickedIndex = imageSwitch(this, e);
            if (clickedIndex != null) {
                var newImagePath = productDetailArray[clickedIndex][0];
                var newImage = new Image();
                newImage.src = newImagePath;
                productDetail.find('#productDetailImage').after('<div id="overlay"></div>');
                $('#overlay').css('opacity', .7).fadeIn(100);
                if ($(newImage).load()) {
                    $('#overlay').delay(250).fadeOut(100, function () {
                        productDetailImage.attr('src', newImagePath);
                        $(this).remove();
                    });
                }
                selectedIndex = clickedIndex;
            }
        });


        // Video paging.
        var videoPaging = productDetail.find('.videoPaging');
        videoPaging.find('li').click(function () {
            var clickedIndex = $(this).index();
            var flashVars = {};
            flashVars.coverImage = videoArray[clickedIndex][0];
            flashVars.videoHigh = videoArray[clickedIndex][1];
            flashVars.videoPath = videoArray[clickedIndex][2];
            embedVideo(flashVars);
            videoPaging.find('li').removeClass('on');
            $(this).addClass('on');
        });

        // bind video/image switch
        var vidImgSwitch = $('#vidImgSwitch');
        vidImgSwitch.data('showing', 'image'); //image shows by default
        vidImgSwitch.toggle(function () {
            productDetail.find('.video .videoPaging ul li:first').click();
            productDetail.find('.image').fadeOut(100);
            productDetail.find('.video').fadeIn(100);
            $(this).text($(".toggleVideoImgViewImages").text());
        }, function () {
            productDetail.find('.video').fadeOut(100);
            productDetail.find('.image').fadeIn(100);
            $(this).text($(".toggleVideoImgWatchVideos").text());
        });

        // bind magnifier
        productDetail.find('#magnify').click(function () {
            productDetail.find('.image').addClass('zoomed');
            vidImgSwitch.hide();
            productDetailImage.parent('span').addClass('jqzoom');
            productDetail.find('.jqzoom').jqzoom({ largeImage2: productDetailArray[selectedIndex][1] });
        });
        productDetail.find('#closeZoom').click(function () {
            productDetail.find('.jqzoom').jqzoom({ destroy: true });
            productDetailImage.parent('span').removeClass('jqZoom');
            vidImgSwitch.show();
            productDetail.find('.image').removeClass('zoomed');
        });

        // Review Form trigger
        productDetail.find('#reviewFormTrigger').toggle(function () {
            $(this).next('div.reviewForm').slideDown({ duration: 400, easing: 'easeOutQuint' });
        }, function () {
            $(this).next('div.reviewForm').slideUp({ duration: 400, easing: 'easeOutQuint' });
        });
    }

    /* Image Switcher on Product Listing */
    var subCategory = $('#subCategoryListing');
    if (subCategory.size() > 0) {
        var paging = subCategory.find('.imageSwitch');
        paging.click(function (e) {
            var clickedIndex = imageSwitch(this, e);
            var itemIndex = $(this).parent('li').index();
            var newImagePath = productListArray[itemIndex][clickedIndex];
            $(this).prev('.image').find('img').attr('src', newImagePath);
        });
    }

    // Default value declarations
    $('.searchBox .searchInput').defaultvalue('Search');
    $('#extras div.subscribe input.name').defaultvalue('Name*');
    $('#extras div.subscribe input.email').defaultvalue('Email*');
    $('#extras div.subscribe input.postcode').defaultvalue('Postcode*');
    $('#tabsReviews input.nameInput').defaultvalue('Name*');
    $('#tabsReviews input.urlInput').defaultvalue('Link');
    $('#tabsReviews input.titleInput').defaultvalue('Review Title*');
    $('#tabsReviews textarea.reviewInput').defaultvalue('Review');

    // Checkout Tooltip
    $('#checkout div.whatIsCVV').hover(function () {
        $(this).find('div.info').show();
    }, function () {
        $(this).find('div.info').hide();
    });

    // Find a store listing scroll
    var findStore = $('#findStore');
    if (findStore.size() > 0) {
        var topDropdown = $('div.findStoreSelector');
        topDropdown.find('ul').each(function () {
            $(this).css('position', 'static').show();
        });
        topDropdown.find('div.filterList').jScrollPane({ scrollbarWidth: 13, showArrows: true });
        topDropdown.find('div.jScrollPaneContainer').hide();
        topDropdown.find('div.filterSelect').hover(function () {
            $(this).find('div.jScrollPaneContainer').show();
        }, function () {
            $(this).find('div.jScrollPaneContainer').hide();
        });
        findStore.find('div.stockists div.col ul').each(function () {
            $(this).jScrollPane({ scrollbarWidth: 13, showArrows: true });
        });
    }

    // Mini Cart
    var miniCart = $('#miniCart');
    if (miniCart.size() > 0) {
        // 1. overlay
        var overlay = miniCart.find('#miniCartOverlay');
        var docWidth = $(document).width();
        var docHeight = $(document).height();
        var offset = overlay.offset().left;
        overlay.width(docWidth).height(docHeight).css({ 'margin-left': '-' + offset + 'px', 'opacity': 0.26 });

        // 2. fade out
        miniCart.delay(3000).fadeOut();
    }

    // checkouts
    $('#checkout').find('a.nextStep').click(function () {
        //
    });

    // policyPop
    var checkout = $('#checkout');
    if (checkout.size() > 0) {
        $('#checkout a.policyPop').fancybox({
            'width': 300,
            'height': 400,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'type': 'iframe',
            'padding': 20
        });
    }

    // There is now the possibility of Region specific content based on the two letter country code
    // Check to see if we have registered the specific content for the region
    if (typeof countryCode != "undefined") {
        // Country Code has been registered for this page, hide the default content and show the region specific content if it exists
        if ($("#regionSpecific_" + countryCode).length != 0) {
            $("#regionSpecific_Default").hide(function () {
                $("#regionSpecific_" + countryCode).show();
            });
        }
    }

});

function createLinks(items) {
    items.css('cursor', 'pointer');
    items.bind("click", function () {
        var link = $(this).find('a');
        if (link.length > 0) { location.href = link.attr('href'); }
        return false;
    });
}

function changeCountry(coutryCodeArg) {
    countryCallback(coutryCodeArg);
}
function changedCountry() {
    // dummy callback function .... just refresh but do not maintain the scroll position
    scroll(0, 0);
    window.location.reload();
} 

/* Cufon calls
-------------------------------------------------- */
Cufon.replace('#productDetail h1.fn');
Cufon.replace('#categoryIntro h1');
Cufon.replace('#subCategoryIntro h1');
Cufon.replace('#findStore div.storeName h2');
//Cufon.replace('#categoryListing li a');
