// JavaScript Document

// function to fade rollover image on hover - wrapped as a jQuery plugin

// wrap as a jQuery plugin and pass jQuery in to our anoymous function
(function($) {
    $.fn.fadehover = function(options) {
        return this.each(function(i) {
            // cache the copy of jQuery(this) - the start image
            var $$ = $(this);

            if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {

                // get the target from the first image and replace the suffix
                var target = $$.attr('src').replace('.gif', '-highlight.gif'); //.replace('.png', '-highlight.png');
                //var target = $$.attr('src').replace('-highlight.gif', '.gif').replace('-highlight.png', '.png');

                // nice long chain: wrap img element in span
                $$.wrap('<span style="position: relative;"></span>')
                // change selector to parent - i.e. newly created span
                        .parent()
                // prepend a new image inside the span
                        .prepend('<img>')
                // change the selector to the newly created image
                        .find(':first-child')
                // set the image to the target
                        .attr('src', target);
                // set initial image opacity to 0
                //.css('opacity', 0);

                // the CSS styling of the start image needs to be handled for
                // different browsers - start with mozilla & IE 8.0
                if ($.browser.mozilla) { // - not used because site set to IE7 compatability mode || ($.browser.msie && $.browser.version > 7.5)) {
                    $$.css({
                        'position': 'absolute',
                        'left': 0,
                        'background': '',
                        'top': this.offsetTop
                    });
                } else if ($.browser.opera && $.browser.version < 9.5) {
                    // opera < 9.5 has a render bug so we can't apply the 'top' : 0 
                    // separately because Opera strips the style set originally somehow...                    
                    $$.css({
                        'position': 'absolute',
                        'left': 0,
                        'background': '',
                        'top': "0"
                    });
                } else { // Safari, IE < 8
                    $$.css({
                        'position': 'absolute',
                        'left': 0,
                        'background': ''
                    });
                }

                // similar effect as single image technique, except using .animate 
                // which will handle the fading up from the right opacity for us
                $$.hover(function() {
                    $$.stop().animate({
                        opacity: 0
                    }, 350);
                }, function() {
                    $$.stop().animate({
                        opacity: 1
                    }, 350);
                });
            }
        });
    };

})(jQuery);

// note that this uses the .bind('load') on the window object, rather than $(document).ready() 
// because .ready() fires before the images have loaded, but we need to fire *after* because
// our code relies on the dimensions of the images already in place.
$(window).bind('load', function() {
    $('img.fade').fadehover();
});

// function to zoom images on hover - wrapped as a jQuery plugin
// assigned on a page by page basis as needed

// wrap as a jQuery plugin and pass jQuery in to our anoymous function
(function($) {
    $.fn.zoomhover = function(options) {
        return this.each(function(i) {

            // set up start & zoom dimensions and find & replace strings
            var startH = 219;
            var startW = 155;
            var zoomH = 290;
            var zoomW = 205;
            var findStr = '-s.';
            var replaceStr = '-m.';

            // check if the image is an option image and if so
            // adjust start & zoom dimensions and find & replace strings
            if (options) {
                startH = 184
                startW = 130
                zoomH = 219;
                zoomW = 155;
                findStr = '-xs.';
                replaceStr = '-s.';
            }

            // find and cache a copy of the start image
            var $1 = $(this).find(':first-child');

            // get the target from the first image and replace the suffix
            var target = $1.attr('src').replace(findStr, replaceStr);

            // change selector to parent - i.e. the current .item a - 
            // and prepend a new image inside it
            $1.parent().prepend('<img>');

            // cache a copy the selector to the newly created image
            var $2 = $1.parent().find(':first-child');

            // set the image to the target
            $2.attr('src', target);

            // the CSS styling of the start image needs to be handled
            // differently for different browsers
            if ($.browser.opera && $.browser.version < 9.5) {
                // opera < 9.5 has a render bug so we can't apply the 'top' : 0 
                // separately because Opera strips the style set originally somehow...                    
                $2.css({
                    'position': 'absolute',
                    'left': 0,
                    'background': '',
                    'top': "0",
                    height: startH,
                    width: startW
                });
            } else { // all other browsers
                $2.css({
                    'position': 'absolute',
                    'left': 0,
                    'background': '',
                    height: startH,
                    width: startW
                });
            }

            // similar effect as single image technique, except using .animate 
            // which will handle the fading up from the right opacity for us
            $(this).hover(function() {
                $1.hide();
                $2.stop().animate({
                    height: zoomH,
                    width: zoomW
                }, 350);
            }, function() {
                $2.stop().animate({
                    height: startH,
                    width: startW
                }, 350, null, function() { $1.show(); });
            });
        });
    };

})(jQuery);

// function to preload images and crossfade once loaded, creating
// a slideshow that does not require preloading of whole page and
// therefore does not impact on other 'load' events - the order
// is load image, fade image, load next image, fade next image
// etc. once all images are loaded the slideshow loops but no
// longer loads images as they are already cached by the browser
function preLoadCrossFadeImages(selector, images, speed, delay, status) {

    if (typeof speed == 'undefined')
        speed = 750;

    if (typeof delay == 'undefined') {
        if (selector == '.leftslideshow') {
            delay = 2000;
        }
        else {
            delay = 750;
        }
    }

    if (typeof status == 'undefined') {
        // create a new instance of the status helper object to manage 
        // the status of this particular slideshow instance
        status = new preLoadCrossFadeImagesStatus;
    }

    // check if the image at current index 'c' is loaded
    if (!status.loaded[status.c]) {

        ////alert('load status for '+status.c+' is '+ status.loaded[status.c]);

        // check if we've even tried to load yet
        if (status.loaded[status.c] == undefined) {
            // if not, create a new image
            var img = new Image(310, 438);

            //alert('images[' + status.c + ']');
            //alert('images['+status.c+'][0] = ' + images[status.c][0]);
            // set the src url of the image
            img.src = images[status.c][0];

            // bind a function to the 'load' event of the image so it notifies
            // the loaded[] array when it is available
            jQuery(img).bind('load', function() { status.loaded[status.c] = true; });

            // set the status to false so we know loading has started
            status.loaded[status.c] = false;
            ////alert('setting load status for ' + status.c + ' to ' + status.loaded[status.c]);
        }
        else {
            // increment the loading counter to indicate roughly the time taken
            // for loading the image (the image loads in the background)
            status.l++;
        }

        // check we haven't been trying to load the same image too long - in this case 5 seconds
        if (status.l > 20) {
            // if we have then skip forward to the next image
            // increment the loop counter
            status.c++;
            // check we haven't gone past the end of the array
            if (status.c > (images.length - 1)) {
                // if we have then reset the loop counter
                status.c = 0;
                // increment a total loop counter and break out of slideshow if number of loops reaches 100
                status.t++;
                if (status.t > 99) {
                    return;
                }
            }
            // reset the current loading counter value
            status.l = 0;
            // start the next loop iteration
            // set images = null; speed = null; etc. after function call to avoid memory leaks
            setTimeout(function() { preLoadCrossFadeImages(selector, images, speed, delay, status); selector = null; images = null; speed = null; delay = null; }, 250);
        }
        else {
            // set a timeout loading interval to allow the image to load in the background
            // set images = null; speed = null; etc. after function call to avoid memory leaks
            setTimeout(function() { preLoadCrossFadeImages(selector, images, speed, delay, status); selector = null; images = null; speed = null; delay = null; }, 250);
        }
    }
    else {

        // if the image has loaded, cache the slideshow container
        var $0 = jQuery(selector);

        // set up the link and title text for the next image
        $0.attr('href', images[status.c][1]);
        $0.attr('title', images[status.c][2]);

        // get the current background image url - ie the currently visible 
        // image which is the previous image in the slideshow
        var target = $0.css('backgroundImage').replace(/^url|[\(\)]/g, '');
        
        // set the container background to the current 'c' (ie next) image
        $0.css('background', 'url(' + images[status.c][0] + ') top left no-repeat');

        // append a new image into the slideshow container, fade out and then remove to reveal background
        // chain together so everything happens at once otherwise you get left with empty <img> elements in IE
        var $1 = $0.append('<img src="' + target + '">').find(':first-child').fadeOut(speed, function() { $1.remove(); }); ;
        
        /*
        alert('src=' + target);

        // set its 'src' attribute to the current background
        $1.attr('src', target);

        // fade out and remove the previous image to reveal the background
        $1.fadeOut(speed, function() { $1.remove(); });
        */

        // increment the loop counter
        status.c++;

        // set up the timeout delay by multiplying the current loading counter
        // value by the loading interval
        var d = delay - (status.l * 250);

        // if the delay is negative (ie the image has taken more than x 
        // milliseconds to load) set delay to zero
        if (d < 0)
            d = 0;

        // reset the current loading counter value
        status.l = 0;

        // if the current loop counter exceeds the size of the url array, reset to zero
        if (status.c > images.length - 1) {
            status.c = 0;
            // increment a total loop counter and break out of slideshow if number of loops reaches 100
            status.t++;
            if (status.t > 99) {
                return;
            }
        }

        // start the next loop iteration
        // set images = null; speed = null; etc. after function call to avoid memory leaks
        setTimeout(function() { preLoadCrossFadeImages(selector, images, speed, delay, status); selector = null; images = null; speed = null; delay = null; }, d);

    }

}

// helper object to maintain status of a particular instance
// of a slideshow thus avoiding use of global variables
function preLoadCrossFadeImagesStatus() {
    this.loaded = [true];
    this.c = 1;
    this.l = 0;
    this.t = 0;
}



// function to scroll newsticker on homepage - calls itself at the end
// so scroll repeats, calculates speed from current position so can be 
// called on hover without speeding up over time
function scroll() {
    var target = $('.newsticker div').width();
    if (parseInt($('.newsticker div').css('left')) == (0 - target)) {
        $('.newsticker div').css('left', '720px');
    }
    $('.newsticker div').animate({ left: 0 - target }, (target + parseInt($('.newsticker div').css('left'))) * 10, 'linear', scroll);
}

function closeSubscribeForm() {
    $('.subscribeform').stop().hide('medium')
}

$(document).ready(function() {
    $('.subscribelink').bind('click', function() {
        $('.subscribeform').css('top', $(this).offset().top - 300);
        $('.subscribeform').css('left', $(this).offset().left - 119);
        $('.subscribeform').stop().show('medium');
    });
}); 