/** 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 i   n 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
			    )
			}
		});


		// HACK
		/**** (AD: 31/05/10) Disable / Enable Drop Down List (t-shirt size) for current registrant entering as a Team ******/
		var cbid_enterIntoTeam = "#EventRegistrationWizard_5_RegistrationWizard_ProfileDetailsControl_chkEnterIntoTeam";
		var ddlid_attribute = "#EventRegistrationWizard_5_RegistrationWizard_ProfileDetailsControl_MerchandiseProducts_ctrl0_ddlAttribute";

		if ($(cbid_enterIntoTeam)) {
			$(cbid_enterIntoTeam).click(function() {
				DisableEnableDropDown(ddlid_attribute, $(cbid_enterIntoTeam).is(':checked'));
			});

			$(cbid_enterIntoTeam).ready(function() {
				DisableEnableDropDown(ddlid_attribute, $(cbid_enterIntoTeam).is(':checked'));
			});
		}

	}
	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' || $input.attr('value') == '64' ||
					$input.attr('value') == '100' || $input.attr('value') == '103' || $input.attr('value') == '104' || 
					$input.attr('value') == '111')) {
                    $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);

// checks all valid races
function validRaceCheckAll(raceId) {
    // enable all categories
    $cats = $(".form-item span[class=disabled] input");
    $cats.removeAttr("disabled");
    $cats.parents('span').removeClass('disabled');

    // disable those not valid for this race
    $cats = $(".form-item span[rel*=valid-race]:not([rel*=valid-race-" + raceId + "]) input");
    $cats.attr("disabled", "disabled");
    $cats.removeAttr("checked");
    $cats.parents('span').addClass('disabled');
}

$(document).ready(function() {
	$("#series-race-selection input[type=radio]").checkAll("#series-race-selection input[type=checkbox]");


	if ($("#race-selection")) {
		validRaceCheckAll($("#race-selection input[type=radio]").eq(0).val());
	}

	$("#race-selection input[type=radio]").click(function() {
		validRaceCheckAll(this.value);
	});
});

(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();
});


/***** Enables or disables drop down list - must provide ID of ddl and true|false to enable|disable ********/
function DisableEnableDropDown(ddl_id, enable) {
    
    if ($(ddl_id)) {
        if (enable == true) {
            if ($(ddl_id).attr("disabled")) {
                $(ddl_id).removeAttr("disabled");
            }
        }
        else {
            $(ddl_id).attr("disabled", "disabled");
        }
    }
}

// JM: Race Results helpers
$(document).ready(function() {

	if ($("table.results-view")) {

		// set the alt rows colour
		setAltRows();

		// Get the amount of results
		var results = $("table.results-view tr").length;

		$("table.results-view tr").each(function(index) {

			// If there are more than 100 results, with the last 6, set to be from the bottom up
			if (results > 0 && (index + 1) > (results - 6)) {
				$("table.results-view tr:eq(" + index + ") .detailed-result").addClass("show-from-bottom");
			}

			$(this).bind('click', function() {
				$(this).find(".detailed-result").fadeIn(200);
			});
		});

		$("table.results-view tr").bind('mouseleave', function() {
			$(this).find(".detailed-result").fadeOut(200);
		});

	}

	$("#results-filter .results-filter-select").change(function() {
		filterResults(this, $(this).attr('value'));
	});

	$("#my-result-jump-link").click(function() {
		$.scrollTo($("#my-result"), 100);
		return false;
	});
	//$(...).scrollTo( $('div li:eq(14)'), 800 );

});

function setAltRows() {

	var realIndex = 0;

	$('table.results-view tr.result-row').each(function (index) {

		// Remove all classes by default
		$(this).removeClass('alt-row');

		if ($(this).css('display') == "none") {
			return;
		}

		if (realIndex > 0 && ((realIndex % 2) == 0)) {
			$(this).addClass('alt-row');
		}

		realIndex++

	});
}

function filterResults(sender, category) {

	if (category == "-1") {

		$("table.results-view tr.result-row").css('display', '');
		
	} else {

		$("table.results-view tr.result-row").each(function(index) {
			if (index > 0) {
				$(this).css('display', 'none');
			}
		});

		$("table.results-view tr.result-row[category=" + category + "]").css('display', '');

	}

	setAltRows();
}


