/** SuperSprint Singleton **/
var SuperSprint = {

    /** Homepage Hero Banners **/
    Hero: {

        Data: {

            TransitionDelay: 6000,
            FadeSpeed: 1000,
            CurrentBanner: 0,
            //TotalBanners: 5,
            ContainerID: null,
            ControlID: null,
            ButtonsID: null,
            _Timer: null
        },

        Init: function(containerID, controlID, buttonsID) {

            this.Data.ContainerID = containerID;
            this.Data.ControlID = controlID;
            this.Data.ButtonsID = buttonsID;

            this.Controls.Init();
            this.ChangeLinks();
            $(controlID + ' ul li:eq(0) a').addClass('active');

            //hide all but first
            var items = $(containerID + ' ul li');
            items.css({ 'position': 'absolute', 'z-index': SuperSprint.Hero.Data.TotalBanners });
            for (i = 1, l = items.length; i < l; i++) {
                var zi = $(containerID + ' ul li:eq(' + i + ')').css('z-index') - i;
                $(containerID + ' ul li:eq(' + i + ')').css({ 'display': 'none', 'z-index': zi });
            }

            this.ResetInterval();

        },

        Play: function(oldBanner) {
            if (typeof oldBanner !== 'undefined') {
                $(this.Data.ContainerID + ' ul li:eq(' + oldBanner + ')').fadeOut(this.Data.FadeSpeed);
            } else {
                $(this.Data.ContainerID + ' ul li:eq(' + this.Data.CurrentBanner + ')').fadeOut(this.Data.FadeSpeed);
            }

            if (this.Data.CurrentBanner < this.Data.TotalBanners - 1) {
                this.Data.CurrentBanner += 1;
            } else {
                this.Data.CurrentBanner = 0;
            }

            this.Controls.Change();
            this.ChangeLinks();
            $(this.Data.ContainerID + ' ul li:eq(' + this.Data.CurrentBanner + ')').fadeIn(this.Data.FadeSpeed);

            this.ResetInterval();

        },

        _SetInterval: function() {
            SuperSprint.Hero.Data._Timer = setInterval('SuperSprint.Hero.Play()', SuperSprint.Hero.Data.TransitionDelay);
        },

        _ClearInterval: function(interval) {
            clearInterval(SuperSprint.Hero.Data._Timer);
            SuperSprint.Hero.Data.Timer = null;
        },

        ResetInterval: function() {
            if (this.Data._Timer != null) {
                this._ClearInterval();
                this._SetInterval();
            } else {
                this._SetInterval();
            }
        },

        ChangeLinks: function() {
            if (typeof this.hl !== 'undefined') {

                if (this.Data.CurrentBanner) {
                    if (this.hl[this.Data.CurrentBanner].enter != '') {
                        $('#hp-hero-links .enter-btn').animate({ width: '120px' });
                        $('#hp-hero-links .enter-btn').attr('href', this.hl[this.Data.CurrentBanner].enter);
                    } else {
                        $('#hp-hero-links .enter-btn').animate({ width: 0 });
                    }

                    if (this.hl[this.Data.CurrentBanner].gal != '') {
                        $('#hp-hero-links .gallery-btn').animate({ width: '120px' });
                        $('#hp-hero-links .gallery-btn').attr('href', this.hl[this.Data.CurrentBanner].gal)
                    } else {
                        $('#hp-hero-links .gallery-btn').animate({ width: 0 });
                    }
                }
            }
        },

        Controls: {

            Init: function() {
                $(SuperSprint.Hero.Data.ControlID + ' ul li').click(function(e) {
                    e.preventDefault();
                    var list = this.parentNode.getElementsByTagName('li');
                    var prevBanner = SuperSprint.Hero.Data.CurrentBanner;

                    for (i = 0; i < list.length; i++) {
                        if (list[i] == this) {
                            SuperSprint.Hero.Data.CurrentBanner = (i - 1);
                        }
                    }

                    SuperSprint.Hero.Play(prevBanner);

                });

            },

            Change: function(indexNumber) {
                var index = indexNumber || SuperSprint.Hero.Data.CurrentBanner;
                $(SuperSprint.Hero.Data.ControlID + ' ul li a').removeClass('active');
                $(SuperSprint.Hero.Data.ControlID + ' ul li:eq(' + index + ') a').addClass('active');
            }

        }

    },

    /** homepage module swapper **/
    Module: {
        GetLength: function(id) {
            return $(id + ' ul.hp-module-container > li').length;
        },

        HideAllButFirst: function(containerID) {
            var items = $(containerID + ' ul.hp-module-container > li');
            for (i = 1, l = items.length; i < l; i++) {
                $(containerID + ' ul.hp-module-container > li:eq(' + i + ')').css({ 'display': 'none' });
            }
        },

        InitControls: function(containerID) {

        }
    },


    ModuleInit: function(id) {
        this.prototype = SuperSprint.Module;
        this.prototype.constructor = SuperSprint.ModuleInit;

        //inherit
        for (i in this.prototype) {
            this[i] = this.prototype[i];
        }

        var current = 0,
			length = this.GetLength(id);

        this.HideAllButFirst(id);

        var Back = $(id + ' .module-controls .back');
        var Next = $(id + ' .module-controls .next');
        Back.click(function(e) {
            e.preventDefault();
            if (current == 0) {
                current = (length - 1);
            } else {
                current -= 1;
            }

            $(id + ' ul.hp-module-container > li').css('display', 'none');
            $(id + ' ul.hp-module-container > li:eq(' + current + ')').css('display', 'block');

        });

        Next.click(function(e) {
            e.preventDefault();
            if (current == (length - 1)) {
                current = 0;
            } else {
                current += 1;
            }

            $(id + ' ul.hp-module-container > li').css('display', 'none');
            $(id + ' ul.hp-module-container > li:eq(' + current + ')').css('display', 'block');

        });
    },

    /** form **/
    Form: {
        StandardiseFieldsets: function() {
            var highest = 0;
            for (i = 0; i < $('.online-entry fieldset').length; i++) {
                if ($('.online-entry fieldset:eq(' + i + ')').height() > highest) {
                    highest = $('.online-entry fieldset:eq(' + i + ')').height();
                }
            }

            $('.online-entry fieldset').height(highest);
        }
    },

    /** images **/
    Image: {
        Preload: function(imageSrc) {

            var i = new Image();
            i.src = imageSrc;

        }
    }


};

$(document).ready(function() {

    if ($('#hp-hero-banner')) { /** check if exists as it will only be on homepage **/
        SuperSprint.Hero.Init('#hp-hero-banner', '#hp-hero-controls', '#hp-hero-links');
    }

    //initial set up of modules if javascript is enabled
    $('.hp-module').css({ 'height': '199px', 'overflow': 'hidden' });
    $('.hp-module-inner').css({ 'height': '179px', 'overflow': 'hidden' });
    $('.module-controls').css('visibility', 'visible');

    if ($('#recent-events')) {
        new SuperSprint.ModuleInit('#recent-events');
    }
    if ($('#upcoming')) {
        new SuperSprint.ModuleInit('#upcoming');
    }
    if ($('#latest-news')) {
        new SuperSprint.ModuleInit('#latest-news');
    }

    //ie6 hover fix
    $('#main-navigation ul li').hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });

    //Set all fieldsets on page to same height
    //SuperSprint.Form.StandardiseFieldsets();

    //preload subnav bg
    SuperSprint.Image.Preload('/i/bg-nav-subnav.png');
    SuperSprint.Image.Preload('/i/bg-nav-subnav-ie6.gif');

    // hide any empty headings
    $("h1, h2, h3, h4, h5, h6, strong, em").each(function() {
        var text = $(this).html().trim();
        if (text == "" || text == "&nbsp;" || text == "&nbsp;&nbsp;" || text == "&nbsp;&nbsp;&nbsp;") {
            $(this).remove();
        }
    });

    // faq stuff
    $("dl.faq-list dt").click(function() {
        if (!$(this).is(":animated")) {
            $(this).next().slideToggle(150);
            $(this).toggleClass('open');
        }
        return false;
    })
	.each(function() {
	    var $this = $(this);
	    $this.html("<a href=#view-answer>" + $this.html() + "</a>");
	})
	.next()
	.hide()
	.parent()
	.addClass('collapsible-faq-list');

    // add indents with JS
    $("dl.faq-list dd span").attr("style", "padding: 0 10px 10px 35px;");
    // replace any h1's in our lists with h2's
    $("dl dd h1").each(function() {
        // get the inner contents
        $(this).replaceWith("<h2>" + $(this).html() + "</h2>");
    });

    /* open the CVV window */
    $(".online-entry #ccv-whats-this").click(function() {
        window.open('/i/cvv.gif', 'cvvwindow', 'menubar=0,resizable=0,width=180,height=113,status=0,scrollbars=0,toolbar=0,location=0');
        return false;
    }).attr("href", "#");

    // make the gallery go now
    try {
        $('ul.image-gallery-list').addClass('gallery_demo'); // adds new class name to maintain degradability
        $('ul.gallery_demo').galleria({
            history: true, // activates the history object for bookmarking, back-button etc.
            clickNext: true, // helper for making the image clickable
            insert: '#main_image', // the containing selector for our main image
            onImage: function(image, caption, thumb) { // let's add some image effects for demonstration purposes

                // fade in the image & caption
                if (!($.browser.mozilla && navigator.appVersion.indexOf("Win") != -1)) { // FF/Win fades large images terribly slow
                    image.css('display', 'none').fadeIn(1000);
                }
                caption.css('display', 'none').fadeIn(1000);

                // fetch the thumbnail container
                var _li = thumb.parents('li');

                // fade out inactive thumbnail
                _li.siblings().children('img.selected').fadeTo(500, 0.3);

                // fade in active thumbnail
                thumb.fadeTo('fast', 1).addClass('selected');

                // add a title for the clickable image
                image.attr('title', 'Next image >>');
            },
            onThumb: function(thumb) { // thumbnail effects goes here

                // fetch the thumbnail container
                var _li = thumb.parents('li');

                // if thumbnail is active, fade all the way.
                var _fadeTo = _li.is('.active') ? '1' : '0.3';

                // fade in the thumbnail when finnished loading
                thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn(1500);

                // hover effects
                thumb.hover(
				    function() { thumb.fadeTo('fast', 1); },
				    function() { _li.not('.active').children('img').fadeTo('fast', 0.3); } // don't fade out if the parent is active
			    )
            }
        });
    }
    catch (Exception) {
    }
/*
    // auto wire up of all default buttons
    var $buttons = $("input.default");

    for (var i = 0; i < $buttons.length; i++) {
        var button = $buttons[i];
        var $parent = $(button).parent();
        var $previousParent = $(button);

        // find the highest ancestor which still contains only 1 default button
        while ($parent && $parent.find("input.default").length == 1) {
            $previousParent = $parent;
            $parent = $parent.parent();
        }

        // find all input elements within this ancestor and set this button as the default
        $("input[@type=text], input[@type=password]").defaultbutton($(button));
    }
*/
});

(function($) {
    var defaultOptions = {
        disable: true,
        check: true
    };

    $.fn.checkAll = function(master, options) {
        var $master = $(master);
        var $dependents = this;
        options = $.extend(defaultOptions, options);

        $master.click(function() {
            var $this = $(this);
            if ($this.is(":selected") || $this.is(":checked")) {
                checkAll($dependents, options);
            }
            else {
                uncheckAll($dependents, options);
            }
        });

        // initialise correctly
        if ($master.is(":selected") || $master.is(":checked")) {
            checkAll($dependents, options);
        }

        // don't break the chain
        return this;
    };

    function checkAll($dependents, options) {
        for (var i = 0; i < $dependents.length; i++) {
            var $input = $($dependents[i]);
            if (options.disable) {
                $input.attr("disabled", "disabled");
            }
            if (options.check) {
                // HACK - don't want to select our sprint race
                if ($input.attr('type') == 'radio' && $input.attr('value') == '38'/*38 is live*/) {
                    $input.hide();
                    $input.after("<input type='checkbox' disabled='disabled'>");
                }
                else if ($input.attr('type') == 'radio') {
                    $input.hide();
                    $input.after("<input type='checkbox' checked='true' disabled='disabled'>");
                }
            }
        }

        // disable categories as well if they're not series categories
        if (options.disable) {
            $cats = $(".form-item span[rel=no-series-category] input");
            $cats.attr("disabled", "disabled");
            $cats.removeAttr("checked");
            $cats.parents('span').addClass('disabled');
        }

        $dependents.parents('fieldset').addClass('disabled');
    }

    function uncheckAll($dependents, options) {
        for (var i = 0; i < $dependents.length; i++) {
            var $input = $($dependents[i]);
            if (options.disable) {
                $input.attr("disabled", "");
            }
            if (options.check) {
                if ($input.attr('type') == 'radio') {
                    $input.show();
                    $input.next().remove();
                }
            }
        }

        // disable categories as well if they're not series categories
        if (options.disable) {
            $cats = $(".form-item span[rel=no-series-category] input");
            $cats.removeAttr("disabled");
            $cats.parents('span').removeClass('disabled');
        }

        $dependents.parents('fieldset').removeClass('disabled');
    }

})(jQuery);

$(document).ready(function() {
    $("#series-race-selection input[type=radio]").checkAll("#series-race-selection input[type=checkbox]");
});



(function($) {
    var defaultOptions = {
        css: {
            border: "1px dotted #ccc",
            padding: "10px"
        },
        overlayCSS: {
            backgroundColor: "#FFF"
        },
        message: null
    };

    $.fn.dependsOn = function(master, options) {
        var $master = $(master);
        if ($master.length > 0) {
            var $dependents = this;
            options = $.extend($.extend({}, defaultOptions), options);

            $master.click(function() {
                var $this = $(this);
                if ($this.is(":selected") || $this.is(":checked")) {
                    unblock($dependents);
                }
                else {
                    block($dependents, options);
                }
            });

            // initialise correctly
            if (!$master.is(":selected") && !$master.is(":checked")) {
                block($dependents, options);
            }
        }
        // don't break the chain
        return this;
    };

    function block($dependents, options) {
        $dependents.block(options);
    }

    function unblock($dependents) {
        $dependents.unblock();
    }

})(jQuery);


(function($) {
    $.fn.radioGroupBehaviour = function(options) {
        var $items = this;

        $items.click(function() {
            var $this = $(this);
            if ($this.is(":selected") || $this.is(":checked")) {
                $items.not(this).attr("checked", "");
            }
            else {
                $this.attr("checked", "");
            }
        });

        // ensure only 1 item is selected when we attach
        $items.each(function() {
            if ($(this).is(":selected") || $(this).is(":checked")) {
                $items.not(this).attr("checked", "");
                return false;
            }
        });
        // don't break the chain
        return this;
    };
})(jQuery);

$(document).ready(function() {
    $(".online-entry #credit-card-details").dependsOn("#terms-and-conditions input[type=checkbox]:first", { message: "Please accept the <strong>terms and conditions</strong> to continue" });
    $(".online-entry input.pay, .online-entry div.buttons-form-item a.pay").dependsOn("#terms-and-conditions input[type=checkbox]:first");
    $(".online-entry div.has-team-and-individual-entry input[type=radio]").radioGroupBehaviour();
});