/*------------------------------------------------------------------
From FC.js
------------------------------------------------------------------*/
(function() { var _admcSport = (function() { var initializing = 0, fnTest = /xyz/.test(function() { xyz }) ? /\b_super\b/ : /.*/; var _isIE = 0; var _xhr = window.XMLHttpRequest ? 1 : 0; var _isLteIE6 = 0; var _isIE6 = 0; var _isLteIE7 = 0; var _isIE7 = (_isLteIE7 && window.XMLHttpRequest) ? 1 : 0; _isIE6 = (_isLteIE7 && !window.XMLHttpRequest) ? 1 : _isIE6; _isLteIE6 = (_isLteIE7 && !window.XMLHttpRequest) ? 1 : _isLteIE6; var _detect = navigator.userAgent.toLowerCase(); var _safari_2_x = (_detect.indexOf("safari") >= 0 && _detect.indexOf("412") >= 0) ? 1 : 0; var __appName = navigator.appName.toLowerCase(); var _name = 'FC JavaScript Library.\n\n\u00A9 2009 Fortune Cookie UK'; if (_isLteIE7) { try { document.execCommand('BackgroundImageCache', false, true) } catch (e) { } } return function() { this.hasIE = (function() { return _isIE })(); this.hasLteIE6 = (function() { return _isLteIE6 })(); this.hasIE6 = (function() { return _isIE6 })(); this.hasLteIE7 = (function() { return _isLteIE7 })(); this.hasIE7 = (function() { return _isIE7 })(); this.hasSafari2 = (function() { return _safari_2_x })(); this.admcSport = (function() { return _name })(); this.Class = function() { }; this.Class.subclass = function(prop) { var _super = this.prototype; initializing = 1; var prototype = new this(); initializing = 0; for (var name in prop) { prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn) { return function() { var tmp = this._super; this._super = _super[name]; var ret = fn.apply(this, arguments); this._super = tmp; return ret } })(name, prop[name]) : prop[name] } function Class() { if (!initializing && this.init) this.init.apply(this, arguments) } Class.prototype = prototype; Class.constructor = Class; Class.subclass = arguments.callee; return Class }; this.showChildren = function(el) { var __str = ""; for (var __j in el) { if (el.type || el.hasOwnProperty(__j)) { __str += __j + " = " + el[__j] + ", \n" } } alert(__str) }; this.commonEventObject = function(e) { var __t; if (e.target) { __t = e.target } else if (e.srcElement) { __t = e.srcElement } if (__t.nodeType == 3) { __t = __t.parentNode } return __t }; this.stopReturn = function(e) { if (!e) { e = window.event } (e.stopPropagation) ? e.stopPropagation() : e.cancelBubble = true; (e.preventDefault) ? e.preventDefault() : e.returnValue = false; return false }; this.clearTextNodes = function(n) { var __j = Number(n.length); while (__j--) if (n[__j].nodeType == 3) { n.removeChild(n[__j]) } return n }; this.clearNodes = function(n) { while (n.firstChild) { n.removeChild(n.firstChild) } return n }; this.toDecimalString = function(val) { __val = Number(val); return ((__val * 100) % 100) ? __val.toString() : __val + ".00" }; this.getStyle = function(el, styleProp) { var x = document.getElementById(el), y; if (x.currentStyle) y = x.currentStyle[styleProp]; else if (window.getComputedStyle) y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp); return y }; this.getElementsByClassName = function(cl) { var retnode = [], myclass = /'\\b' + cl + '\\b'/, elem = document.getElementsByTagName('*'); var i = elem.length; while (i--) { if (myclass.test(elem[i].className)) retnode.push(elem[i]) } return (!retnode.length) ? null : retnode }; this.addEvent = function(obj, evt, fn) { if (obj.addEventListener) obj.addEventListener(evt, fn, false); else if (obj.attachEvent) obj.attachEvent('on' + evt, fn); if (obj.getAttribute) { if (obj.getAttribute('href')) { obj.onclick = function() { return false } } else if (obj.getAttribute('href') && !obj.getAttribute('onclick')) { var func = obj.onclick; obj.onclick = function() { func(); return false } } } }; this.removeEvent = function(obj, type, fn) { if (obj.removeEventListener) obj.removeEventListener(type, fn, false); else if (obj.detachEvent) obj.detachEvent('on' + type, fn) }; this.toggle = function(el) { el.style.display = (el.style.display == 'none') ? 'block' : 'none' }; this.setJS = function() { document.body.className = (document.body.className) ? document.body.className + " js" : "js" }; this.setJQ = function() { switch (__appName) { case 'playstation': break; default: document.body.className = (document.body.className) ? document.body.className + " jq" : "jq" } }; this.checkChange = function(str, o) { (o[str]) ? delete o[str] : o[str] = true; for (var __j in o) if (o.hasOwnProperty(__j)) { return true } return false }; this.beforeUnload = function(str) { window.onbeforeunload = (str) ? function(e) { if (e) { e.returnValue = str } return str } : null }; this.resetForm = function(form) { var __input = document.createElement('input'); __input.setAttribute('type', 'reset'); form.appendChild(__input); __input.click(); form.removeChild(form.childNodes[form.childNodes.length]) }; this.pngFix = function(clear, parent) { if (this.hasLteIE6) { } } } })(); window.admcSport = new _admcSport() })();

/*------------------------------------------------------------------
admcSport OBJECT
------------------------------------------------------------------*/

var admcSport;
admcSport.vars =
{
    selectors: {
    MODULETABS: '.module .tabs',
    ACTIVETABS: '.active-tabs',
	FLYOUTTABS: '.flyout-content',
    LIVETICKER: '.ticker .live-scroller .scrolling',
    FILTERNAVIGATION: '.filter-navigation',
    TOGGLER: '.toggler',
    SCROLLER: '.scroller',
    POLLSRADIO: '.poll input[type="radio"]',
    HASDATEFIELD: '.hasdate',
    FILTERNAVIGATION2: '.filter-navigation-2',
    QUICKLINKS: '.quick-links',
    FLYOUT: '.flyout',
    FAVOURITEFOOTBALLSELECT: '#favouriteFootballTeam',
    INNERTABS: '.inner-tabs',
    MATCHCOLLAPSIBLEHOOK: '.match',
    CAROUSELS: '.carousel'


},
    strings: {
        CURRENT: 'current',
        HIDDEN: 'hidden',
        OPEN: 'opened',
        CLOSED: 'closed',
        NEXT: 'next',
        PREVIOUS: 'previous'
    }

};


//*------------------------------------------------------------------//
    admcSport.tabComponents = function() {
        //tab component object
        function tabComponent(el) {
            this.component = $(el);
            this.tabHeaderArray = this.component.find('.tab-header');
            this.tabLinksArray = this.component.find('.tab-navigation a');
            this.tabPanelsArray = this.component.find('.tab-panel');
            return this.init();
        }

        tabComponent.prototype =
		{
		    init: function() {
		        this.prepare();
		        this.attachTabEvent();

		    },
		    prepare: function() {
		    this.tabHeaderArray.addClass(admcSport.vars.strings.HIDDEN);
		        this.clearPanels();
		        $(this.tabLinksArray[0]).addClass(admcSport.vars.strings.CURRENT);
		        $(this.tabPanelsArray[0]).removeClass(admcSport.vars.strings.HIDDEN);
		    },
		    attachTabEvent: function() {
		        var that = this;
		        this.tabLinksArray.each
				(
					function() {
					    $(this).bind
						(
							'click',
							function() {
							    that.clearLinks();
							    that.clearPanels();
							    $(this).addClass(admcSport.vars.strings.CURRENT);
							    var identifier = 'a' + $(this).attr('href');
							    that.component.find(identifier).parent().removeClass(admcSport.vars.strings.HIDDEN);
							    return false;
							}
						)
					}
				)
		    },
		    clearLinks: function() {
		    this.tabLinksArray.removeClass(admcSport.vars.strings.CURRENT);
		    },
		    clearPanels: function() {
		    this.tabPanelsArray.addClass(admcSport.vars.strings.HIDDEN);
		    }
		};

        //init tab component objects

        $(admcSport.vars.selectors.MODULETABS).each
		(
			function() {
			    new tabComponent($(this));
			}
		),
		 $(admcSport.vars.selectors.ACTIVETABS).each
		(
			function() {
			    new tabComponent($(this));
			}
		),
		 $(admcSport.vars.selectors.FLYOUTTABS).each
		(
			function() {
			    new tabComponent($(this));
			}
		)
    },


//*------------------------------------------------------------------//
    admcSport.filterNavigationComponents = function() {
        function filterNavigationComponent(el) {
            this.component = $(el);
            this.filterListing = this.component.find('ul.filter-listing');
            this.collapseLevels = this.filterListing.attr('id').split('-');
            this.currentLink = this.filterListing.find('a.current');

            this.constructLinks();

            this.collapsables = $(this.constructCssSelectorString()).prev('a.identifier');
            this.collapsables.next().hide();

            this.openCurrentLink();

            var that = this;
            this.collapsables.each
			(
				function() {

				    $(this).bind
					(
						'click',
						function() {
						    //Find sibling li elements
				    $(this).parent().siblings().find('a.icon').removeClass(admcSport.vars.strings.OPEN).addClass(admcSport.vars.strings.CLOSED);


						    if ($(this).next().css('display') == "block") {
						        $(this).removeClass(admcSport.vars.strings.OPEN).addClass(admcSport.vars.strings.CLOSED);
						    }
						    else {
						        $(this).removeClass(admcSport.vars.strings.CLOSED).addClass(admcSport.vars.strings.OPEN);
						    }
						    //Slide up children and siblings
						    $(this).parent().children().find('a.identifier').removeClass(admcSport.vars.strings.OPEN).addClass(admcSport.vars.strings.CLOSED);
						    $(this).parent().siblings().find('a.identifier').removeClass(admcSport.vars.strings.OPEN).addClass(admcSport.vars.strings.CLOSED);
						    $(this).parent().children().find('ul').slideUp();
						    $(this).parent().siblings().find('ul').slideUp();
						    $(this).next().slideToggle();
						    return false;
						}
					)
				}
			)

        }

        filterNavigationComponent.prototype =
		{
		    constructLinks: function() {
		        this.spanIdentifiers = this.component.find('span.identifier');
		        this.spanIdentifiers.each
				(
					function() {
					    $('<a class="identifier identifier-span" href="#">' + $(this).html() + '</a>').insertBefore($(this));
					    $(this).remove();
					}
				)
		    },
		    openCurrentLink: function() {
		    this.currentLink.parents('ul').prev().addClass(admcSport.vars.strings.OPEN);
		        this.currentLink.parents('ul').show();
		    },
		    constructCssSelectorString: function() {
		        var string = "";
		        for (i = 0; i < this.collapseLevels.length; i++) {
		            string += "." + this.collapseLevels[i] + ","
		        }
		        return string;
		    }
		}


        $(admcSport.vars.selectors.FILTERNAVIGATION).each
		(
			function() {
			    new filterNavigationComponent($(this));
			}
		)
    },


//*------------------------------------------------------------------//
    admcSport.togglerComponents = function() {
        function toggleComponent(el) {
            this.component = $(el);
            this.togglerHead = this.component.find('.head h2').wrapInner('<a class="icon closed" href="#"></a>');
            this.togglerBody = this.component.find('.body');
            this.currentLinks = this.component.find('a.current');
            var that = this;
            if (this.currentLinks.length == 0) {
                this.togglerBody.hide();
            }



            this.togglerHead.bind
			(
				'click',
				function() {
            $(this).find('a').toggleClass(admcSport.vars.strings.OPEN);
				    that.togglerBody.slideToggle();
				    return false;
				}
			)
        };

        $(admcSport.vars.selectors.TOGGLER).each
		(
			function() {
			    new toggleComponent($(this));
			}
		)
    },


//*------------------------------------------------------------------//
    admcSport.photoCarousel = function() {

        var $photoCarousels = $('.carousel');

        if ($photoCarousels.length == 0) {
            return;
        }

        function PhotoCarousel(root) {
            this.$root = $(root);

            var itemContainerRoot = this.$root.find('.carousel-items').get(0);
            this.itemContainer = new PhotoCarouselItemsContainer(itemContainerRoot, this);

            this.items = [];

            var photoCarousel = this;

            this.itemContainer.$root.find('.item').each(
				function() {
				    var item = new PhotoCarouselItem(this, photoCarousel);
				    photoCarousel.items.push(item);
				}
			);

            this.itemWidth = this.items[0].width;

            this.currentItemIndex = 0;

            this.switchToControls = [];
            this.$switchToControls = null;
            this.nextPreviousControls = {};
            this.$nextPreviousControls = null;
            this.$metadata = this.$root.find('.metadata');
            if (!this.isGrid6_2()) {
                this.$metadata.hide();
            }
			this.$footer = this.$root.find("div.carousel-footer");

            //Sportal additions
            this.$counter = null;

            // On the video gallery, the “border” is an inner shadow image positioned over the photo. As this catches click events and thus prevents the images themselves from being clickable, we turn it into a link, and keep its href synchronised with that of the current item.
            
			this.$borderLink = $('<a href="#">&nbsp;</a>');
            this.$root.find('.border').append(this.$borderLink);

            this.$playIcon = null;
            if (this.$root.find('.play-icon').length) {
                this.$playIcon = this.$root.find('.play-icon');
                this.$playIcon.hide();
            }
            //End Sportal additions

            this.addControls();

            //Sportal additions
            if (!this.isGrid6_2()) {
                this.addCounter();
            }
            //End Sportal additions


            this.isAnimating = false;

            if (!this.isGrid6_2()) {
                this.$root.mouseenter(function() {
                    photoCarousel.showControlsAndMetadata();
                });

                this.$root.mouseleave(function() {
                    photoCarousel.hideControlsAndMetadata();
                });
            }

            this.switchTo(this.currentItemIndex);
        }

        PhotoCarousel.prototype.switchTo = function(newItemIndex) {
            if (this.isAnimating) {
                return false;
            }
            else {
                this.isAnimating = true;

                var photoCarousel = this;

                //Sportal Additions
                photoCarousel.$borderLink.attr('href', '');
				photoCarousel.$borderLink.text('');
                //End Sportal Additions

                var animationProperties = {};
                if ($('html').attr('dir') == 'rtl') {
                    animationProperties['right'] = -this.itemWidth * newItemIndex;
                }
                else {
                    animationProperties['marginLeft'] = -this.itemWidth * newItemIndex;
                }


                this.itemContainer.$root.animate(
					animationProperties,
					'normal',
					'swing',
					function() {
					    photoCarousel.currentItemIndex = newItemIndex;
					    photoCarousel.updateSwitchToControls();
					    photoCarousel.updateNextPreviousControls();

						var currentItem = photoCarousel.items[photoCarousel.currentItemIndex];


					    //Sportal Additions - update counter; update borderLink url and text
					    photoCarousel.updateCounter();
						
				        photoCarousel.$borderLink.attr('href', currentItem.href);
						photoCarousel.$borderLink.text(currentItem.text);
					    //End

					    photoCarousel.isAnimating = false;
					}
				);
            }
        }

        PhotoCarousel.prototype.next = function() {
            this.switchTo(this.currentItemIndex + 1);
        }

        PhotoCarousel.prototype.previous = function() {
            this.switchTo(this.currentItemIndex - 1);
        }

        PhotoCarousel.prototype.addControls = function() {
            if (this.$root.hasClass('.multimedia-photos') && this.$root.parents('.grid-4').count == 0) {
                var $switchToControls = $('<ul class="switch-to"></ul>');

                for (var i = 0; i < this.items.length; i++) {
                    var control = new PhotoCarouselSwitchToControl(i, this);
                    this.switchToControls.push(control);
                    $switchToControls.append($('<li>').append(control.$html));
                }

                this.$root.append($switchToControls);
                this.$switchToControls = $switchToControls;
            }
            else {
                this.switchToControls = null;
                this.$switchToControls = null;
            }

            var $nextPreviousControls = $('<ul class="next-previous"></ul>');
            this.nextPreviousControls[admcSport.vars.strings.NEXT] = new PhotoCarouselNextPreviousControl(admcSport.vars.strings.NEXT, this);
            this.nextPreviousControls['previous'] = new PhotoCarouselNextPreviousControl('previous', this);

            $nextPreviousControls.append($('<li class="next"></li>').append(this.nextPreviousControls[admcSport.vars.strings.NEXT].$html));
            $nextPreviousControls.append($('<li class="previous"></li>').append(this.nextPreviousControls[admcSport.vars.strings.PREVIOUS].$html));

            this.$root.append($nextPreviousControls);
            this.$nextPreviousControls = $nextPreviousControls;
            this.nextPreviousControls[admcSport.vars.strings.NEXT].$html.parent().hide();
            this.nextPreviousControls[admcSport.vars.strings.PREVIOUS].$html.parent().hide();

            if (this.isGrid6_2()) {
                var scrollerControl = new PhotoCarouselScrollerControl(this);
                this.$root.append(scrollerControl.$html);
            }
        }

        PhotoCarousel.prototype.updateSwitchToControls = function() {
            if (this.switchToControls) {
                for (var i = 0; i < this.switchToControls.length; i++) {
                    if (this.switchToControls[i].isSelected) {
                        this.switchToControls[i].deselect();
                    }
                }
                this.switchToControls[this.currentItemIndex].select();
            }
        }

        PhotoCarousel.prototype.updateNextPreviousControls = function() {
        var previousControl = this.nextPreviousControls[admcSport.vars.strings.PREVIOUS];
        var nextControl = this.nextPreviousControls[admcSport.vars.strings.NEXT];

            if (this.currentItemIndex == 0) {
                if (previousControl.isActive) {
                    previousControl.makeInactive();
                }
            }
            else {
                if (!previousControl.isActive) {
                    previousControl.makeActive();
                }
            }

            if (this.currentItemIndex == this.items.length - 1) {
                if (nextControl.isActive) {
                    nextControl.makeInactive();
                }
            }
            else {
                if (!nextControl.isActive) {
                    nextControl.makeActive();
                }
            }
        }

        PhotoCarousel.prototype.showControlsAndMetadata = function() {
            if (this.switchToControls) {
                this.$switchToControls.fadeIn();
            }
            //Sportal Additions
            if (this.$counter) {
                this.$counter.fadeIn();
            }
            if (this.$playIcon) {
                this.$playIcon.show(); /* IE can’t deal with fading alpha PNGs */
            }
            //End Sportal Additions
            this.nextPreviousControls[admcSport.vars.strings.NEXT].$html.parent().fadeIn();
            this.nextPreviousControls[admcSport.vars.strings.PREVIOUS].$html.parent().fadeIn();

            this.$metadata.fadeIn();
        }

        PhotoCarousel.prototype.hideControlsAndMetadata = function() {
            if (this.switchToControls) {
                this.$switchToControls.fadeOut();
            }
            //Sportal Additions
            if (this.$counter) {
                this.$counter.fadeOut();
            }
            if (this.$playIcon) {
                this.$playIcon.hide(); /* IE can’t deal with fading alpha PNGs */
            }
            //End Sportal Additions
            this.nextPreviousControls[admcSport.vars.strings.NEXT].$html.parent().fadeOut();
            this.nextPreviousControls[admcSport.vars.strings.PREVIOUS].$html.parent().fadeOut();

            this.$metadata.fadeOut();
        }


        function PhotoCarouselItemsContainer(root, photoCarousel) {
            this.$root = $(root);
            this.photoCarousel = photoCarousel;
        }


        function PhotoCarouselItem(root, photoCarousel) {
            this.$root = $(root);
            this.width = this.$root.width();
            this.src = this.$root.find('img').attr('src');

            //Sportal additions
            this.href = this.$root.find('.content a').attr('href');
			this.text = this.$root.find('.content a img').attr('alt');
            //End Sportal additions
        }


        function PhotoCarouselSwitchToControl(itemIndex, photoCarousel) {
            this.photoCarousel = photoCarousel;
            this.isSelected = false;

            this.$html = $('<a href="#"><span>Go to photo ' + itemIndex + '</span></a>');

            var control = this;
            this.$html.click(
				function() {
				    control.photoCarousel.switchTo(itemIndex);
				    return false;
				}
			);
        }

        PhotoCarouselSwitchToControl.prototype.select = function() {
            this.$html.addClass('selected');
            this.isSelected = true;
        }

        PhotoCarouselSwitchToControl.prototype.deselect = function() {
            this.$html.removeClass('selected');
            this.isSelected = false;
        }


        function PhotoCarouselScrollerControl(photoCarousel) {
            this.$html = $('<div class="module scroller clear"><div class="head hidden"><h2>Select a photo</h2></div><div class="body clear"><div class="scroller-window"><ul class="scroller-items"></ul></div></div></div>');

            // For each photo in the carousel
            for (var i in photoCarousel.items) {
                var photo = photoCarousel.items[i];
                var itemOptions = {};

                itemOptions['imagePath'] = photo.src;
                itemOptions['index'] = i;

                var scrollerItem = new PhotoCarouselScrollerItem(photoCarousel, itemOptions);
                this.$html.find('.scroller-items').append(scrollerItem.$html);
            }
        }


        function PhotoCarouselScrollerItem(photoCarousel, options) {
            this.photoCarousel = photoCarousel;
            this.index = options['index'];

            if (this.index == 0) {
                var firstChild = ' class="first-child"';
            }
            else {
                var firstChild = '';
            }

            this.$html = $('<li' + firstChild + '><div class="image"><a href="#' + this.index + '" title="Switch to photo ' + this.index + '"><img alt="" src="' + options['imagePath'] + '" width="130" height="72" /></a></div></li>');

            var scrollerItem = this;
            this.$html.find('a').click(function() {
                scrollerItem.select();
                return false;
            });
        }

        PhotoCarouselScrollerItem.prototype.select = function() {
            this.photoCarousel.switchTo(this.index);
        }


        function PhotoCarouselNextPreviousControl(text, photoCarousel) {
            this.photoCarousel = photoCarousel;
            this.text = text;
            this.isActive = true;

            this.$html = $('<a href="#' + text + '" class="active"><span>' + text + ' photo</span></a>');

            var control = this;
            this.clickNext = function() {
                control.photoCarousel.next();
                return false;
            }
            this.clickPrevious = function() {
                control.photoCarousel.previous();
                return false;
            }

            this.bindEvents();
        }

        PhotoCarouselNextPreviousControl.prototype.bindEvents = function() {
        if (this.text == admcSport.vars.strings.NEXT) {
                this.$html.click(this.clickNext);
            }
            if (this.text == admcSport.vars.strings.PREVIOUS) {
                this.$html.click(this.clickPrevious);
            }
        }

        PhotoCarouselNextPreviousControl.prototype.makeInactive = function() {
            if (this.isActive) {
                this.hrefattr = this.$html.removeAttr('href');
                this.$html.addClass('inactive');
                this.$html.unbind('click');
                this.isActive = false;
            }
        }

        PhotoCarouselNextPreviousControl.prototype.makeActive = function() {
            if (!this.isActive) {
                this.$html.attr('href', '#' + this.text);
                this.$html.removeClass('inactive');
                this.bindEvents();
                this.isActive = true;
            }
        }


        //Sportal Additions
        PhotoCarousel.prototype.addCounter = function() {

            var __counter = $("<ul class='counter'></ul>");
            this.$counter = __counter;

            this.$footer.append(__counter);

            for (i = 0; i < this.items.length; i++) {
                if (i == 0) {
                    var __li = $("<li><a href='#' class='on'>Photo " + i + "</a></li>");
                }
                else {
                    var __li = $("<li><a href='#'>Photo " + i + "</a></li>");
                }

                __counter.append(__li);
            }

            var __counters = this.$footer.find("ul.counter li");

            // Fix width of counter list, to cure a layout issue in IE 7 and 6
            __counter.css('width', (__counters.width() * __counters.length) + 'px');

            var carousel = this;
            __counters.bind("click", function() {
	
                var __index = __counters.index(this);
                carousel.switchTo(__index);
                return false;

            });
            this.$counter.hide();
        }

        PhotoCarousel.prototype.updateCounter = function() {

            var __counters = this.$root.find("ul.counter li a");
            if (__counters.length) {
                __counters.removeClass("on");

                for (i = 0; i <= this.currentItemIndex; i++) {
                    __counters[i].className = "on";
                }
            }


        }

        PhotoCarousel.prototype.isGrid3 = function() {
            if (this.$root.parent().hasClass('grid-3')) {
                return true;
            }
            else {
                return false;
            }
        }

        PhotoCarousel.prototype.isGrid6_2 = function() {
            if (this.$root.parents('.grid-6-2').length > 0 && this.$root.parents('.grid-4, .grid-3').length == 0) {
                return true
            }
            else {
                return false;
            }
        }

        $photoCarousels.each(function() {
            new PhotoCarousel(this);
        });


    },


//*------------------------------------------------------------------//
    admcSport.scroller = function() {
        var $scrollers = $(admcSport.vars.selectors.SCROLLER);

        if ($scrollers.length == 0) {
            return;
        }

        function Scroller(root) {
            this.$root = $(root);

            var itemContainerRoot = this.$root.find('.scroller-items').get(0);
            this.itemContainer = new ScrollerItemsContainer(itemContainerRoot, this);

            this.items = [];

            var scroller = this;

            this.itemContainer.$root.find('> li').each(
				function() {
				    var item = new ScrollerItem(this, scroller);
				    scroller.items.push(item);
				}
			);

            this.itemWidth = this.items[1].width;

            this.currentItemIndex = 0;

            this.nextPreviousControls = {};
            this.addControls();
            this.isAnimating = false;

            this.switchTo(this.currentItemIndex);
        }

        Scroller.prototype.switchTo = function(newItemIndex) {
            if (this.isAnimating) {
                return false;
            }
            else {
                this.isAnimating = true;

                var scroller = this;

                var animationProperties = {};
                if ($('html').attr('dir') == 'rtl') {
                    animationProperties['right'] = -this.itemWidth * newItemIndex;
                }
                else {
                    animationProperties['marginLeft'] = -this.itemWidth * newItemIndex;
                }

                this.itemContainer.$root.animate(
					animationProperties,
					'normal',
					'swing',
					function() {
					    scroller.currentItemIndex = newItemIndex;
					    scroller.updateNextPreviousControls();

					    scroller.isAnimating = false;
					}
				);
            }
        }

        Scroller.prototype.next = function() {

            if (this.currentItemIndex + 4 > this.items.length - 4) {
                this.switchTo(this.items.length - 4);
            }
            else {
                this.switchTo(this.currentItemIndex + 4);
            }
        }

        Scroller.prototype.previous = function() {
            if (this.currentItemIndex - 4 < 0) {
                this.switchTo(0);
            }
            else {
                this.switchTo(this.currentItemIndex - 4);
            }
        }

        Scroller.prototype.addControls = function() {
            var $nextPreviousControls = $('<ul class="scroller-controls"></ul>');
            this.nextPreviousControls[admcSport.vars.strings.NEXT] = new ScrollerNextPreviousControl(admcSport.vars.strings.NEXT, this);
            this.nextPreviousControls[admcSport.vars.strings.PREVIOUS] = new ScrollerNextPreviousControl(admcSport.vars.strings.PREVIOUS, this);

            $nextPreviousControls.append($('<li class="next"></li>').append(this.nextPreviousControls[admcSport.vars.strings.NEXT].$html));
            $nextPreviousControls.append($('<li class="previous"></li>').append(this.nextPreviousControls[admcSport.vars.strings.PREVIOUS].$html));

            this.$root.append($nextPreviousControls);
        }

        Scroller.prototype.updateNextPreviousControls = function() {
        var previousControl = this.nextPreviousControls[admcSport.vars.strings.PREVIOUS];
        var nextControl = this.nextPreviousControls[admcSport.vars.strings.NEXT];

            if (this.currentItemIndex == 0) {
                if (previousControl.isActive) {
                    previousControl.makeInactive();
                }
            }
            else {
                if (!previousControl.isActive) {
                    previousControl.makeActive();
                }
            }

            if (this.currentItemIndex == this.items.length - 4) {
                if (nextControl.isActive) {
                    nextControl.makeInactive();
                }
            }
            else {
                if (!nextControl.isActive) {
                    nextControl.makeActive();
                }
            }
        }


        function ScrollerItemsContainer(root, scroller) {
            this.$root = $(root);
            this.scroller = scroller;
        }


        function ScrollerItem(root, scroller) {
            this.$root = $(root);

            this.scroller = scroller;

            this.width = this.$root.width() + parseInt(this.$root.css('margin-left')) + parseInt(this.$root.css('margin-right'));

            this.$caption = this.$root.find('.caption');

            var scrollerItem = this;
            this.$root.bind('mouseenter', function() { scrollerItem.showCaption(); });
            this.$root.bind('mouseleave', function() { scrollerItem.hideCaption(); });
        }

        ScrollerItem.prototype.showCaption = function() {
            this.$caption.animate(
				{ 'top': 0 }
			);
        }

        ScrollerItem.prototype.hideCaption = function() {
            this.$caption.animate(
				{ 'top': 130 }
			);
        }


        function ScrollerNextPreviousControl(text, scroller) {
            this.scroller = scroller;
            this.text = text;
            this.isActive = true;

            this.$html = $('<a href="#' + text + '" class="active"><span>' + text + ' item</span></a>');

            var control = this;

            this.clickNext = function() {
                control.scroller.next();
                return false;
            }
            this.clickPrevious = function() {
                control.scroller.previous();
                return false;
            }

            this.bindEvents();
        }

        ScrollerNextPreviousControl.prototype.bindEvents = function() {
        if (this.text == admcSport.vars.strings.NEXT) {
                this.$html.click(this.clickNext);
            }
            if (this.text == admcSport.vars.strings.PREVIOUS) {
                this.$html.click(this.clickPrevious);
            }
        }

        ScrollerNextPreviousControl.prototype.makeInactive = function() {
            if (this.isActive) {
                this.hrefattr = this.$html.removeAttr('href');
                this.$html.addClass('inactive');
                this.$html.unbind('click');
                this.isActive = false;
            }
        }

        ScrollerNextPreviousControl.prototype.makeActive = function() {
            if (!this.isActive) {
                this.$html.attr('href', '#' + this.text);
                this.$html.removeClass('inactive');
                this.bindEvents();
                this.isActive = true;
            }
        }

        $scrollers.each(function() {
            new Scroller(this);
        });
    },


//*------------------------------------------------------------------//
    admcSport.favouriteFootballTeam = function() {
        if ($('#favouriteSports_football').length == 0 || $('#favouriteFootballTeam').length == 0) {
            return;
        }

        // Localize
        if (admcSport.pageIsArabic()) {
            var LEAGUE_LABEL = 'دوري قرة القدم المفضل:';
            var TEAM_LABEL = 'فريق كرة القدم المفضل:';

            var LEAGUE_PLACEHOLDER = 'اختر دوري';
            var TEAM_PLACEHOLDER = 'اختار الفريق';
        }
        else {
            var LEAGUE_LABEL = 'Favourite football league:';
            var TEAM_LABEL = 'Favourite football team';

            var LEAGUE_PLACEHOLDER = 'Select league';
            var TEAM_PLACEHOLDER = 'Select team';
        }

        // Find the existing Favourite football team <select> element
        var $select_team_by_league = $('#favouriteFootballTeam');

        // Make a <select> for leagues. This selection doesn’t need to be sent to the server.
        var $select_league = $('<select id="favouriteFootballLeague"></select>');
        $select_league.append($('<option value="leagueID_none">' + LEAGUE_PLACEHOLDER + '</option>'));

        // Make an object to keep the team <select>s for each league
        var select_teams = {};
        select_teams['leagueID_none'] = $('<select id="favouriteFootballTeam" name="favouriteFootballTeam"><option value="">' + TEAM_PLACEHOLDER + '</option></select>');

        // For each league <optgroup>
        $select_team_by_league.find('optgroup').each(function() {
            var league_id = this.id;

            // Add an <option> to the leagues <select>
            var $option = $('<option value="' + league_id + '">' + this.label + '</option>');
            $select_league.append($option);

            // Create a <select> containing all the teams from the league <optgroup>
            var $select_team = $('<select id="favouriteFootballTeam" name="favouriteFootballTeam"></select>');
            $select_team.append($(this).find('option'));

            // Pop that <select> into the object we’re using to keep track of them.
            select_teams[league_id] = $select_team;
        });

        // Select the first item in the league and team <select>s
        $select_league.get(0).selectedIndex = 0;
        for (var key in select_teams) {
            select_teams[key].get(0).selectedIndex = 0;
        }

        // Create a <div class="field"></div> for the league <select>
        var $select_league_container = $('<div class="field clear"><div class="label"><label for="favouriteFootballLeague">' + LEAGUE_LABEL + '</label></div><div class="input"></div></div>');
        $select_league_container.find('.input').append($select_league);

        // Create a <div class="field"></div> for the team <select>, and populate it with the team <select> for the currently selected league
        var $select_team_container = $('<div class="field clear"><div class="label"><label for="favouriteFootballTeam">' + TEAM_LABEL + '</label></div><div class="input"></div></div>');
        var $select_team_container_input = $select_team_container.find('.input');

        var selectedLeagueId = $select_league.get(0).options[$select_league.get(0).selectedIndex].value;

        $select_team_container_input.append(select_teams[selectedLeagueId]);


        $select_league.change(function() {
            // Replace the current team <select> with the team <select> for the currently selected league
            $select_team_container_input.find('select').replaceWith(select_teams[this.options[this.selectedIndex].value]);
        });

        // Replace the existing Favourite football team field with our new ones
        var $existing_field = $select_team_by_league.parents('.field');

        $existing_field.after($select_league_container);
        $select_league_container.after($select_team_container);

        $existing_field.remove();

        // Make the visibility of our new ones dependent on the state of the football checkbox

        var checkboxShowHide = function() {
            if ($('#favouriteSports_football').get(0).checked) {
                $select_league_container.show();
                $select_team_container.show();
            }
            else {
                $select_league_container.hide();
                $select_team_container.hide();
            }
        }

        checkboxShowHide();
        $('#favouriteSports_football').click(checkboxShowHide);
    },


//*------------------------------------------------------------------//
	admcSport.matchUpdates = function() {
		
		// It seemed simpler in my head.
		//
		// On every page, there are at least three areas that need to be updated with live match updates: the ticker (.live-scroller), and the “Match Updates” area and “Current, recent and upcoming matches” areas in the Match Centre flyout.
		//
		// On other pages (e.g. the Match Centre homepage), more areas of the page have to be updated.
		//
		// The object “matchUpdatesManager” handles this process:
		//
		// - its init() function initialises itself with the following properties:
		//
		//     1. latestUpdate: reads a class from the <body> tag so that it knows when the server created the page – it sends this value to the server the first time it updates itself
		//     2. updateAreas: creates an UpdateArea object for each entry in updateAreaConfig. Update Areas are areas of the page that need updating with events. Their config is explained below. When an update area is created, it parses itself to identify which matches it contains (using the matchid classes in its HTML), and stores properties of the matches (their team names, and the current home and away scores) in matchUpdatesManager's matches object. (Occasionally, functions that update the HTML will refer to this object; see below.)
		//
		// - its updatePage() function, called every minute after the page loads does the following:
		//     1. Makes an AJAX call to the url given in matchUpdatesManager.url, to get the match events that have occured since the last update
		//     2. Creates a MatchEventSet object for the events returned. When created, the MatchEventSet appends the raw HTML of each returned event to the “Match Updates” area in the Match Centre flyout.
		//     3. Iterates through the match events in the set, and does two things with each of them:
		//        a) Passes the event to the “update” function of its match (stored in matchUpdatesManager.matches), so that the match is updated
		//        b) Passes the event to the “update” function of each UpdateArea, so that the HTML can be updated
		//
		// Updating the HTML is controlled by updateAreaConfig. Each key in updateAreaConfig is a selector for an area of the page that contains an HTML representation of one or more matches. Each updateAreaConfig object contains one property “matchEventHandlers”, which is an object containing a handler function for each match event that needs to be reflected in the HTML.
		//
		// Not all update areas require a handler for every match event. For example, the “Current, recent and upcoming matches” section of the flyout only shows the scores of current matches, so it only needs a handler function for the “goal” match event so that it can update the score.
		//
		// Where effectively the same handler is used for lots of match events and/or update areas, it has been broken out into a function stored in matchUpdatesManager, and given a suffix of MatchEventHandler, e.g. _updateScoreMatchEventHandler (used in several areas for updating the score; assumes a certain arrangement of classes in the page’s HTML) and _liveScrollerMatchEventHandler (could be used for several events in the live scroller, although currently only goals are reflected there).
		
		function MatchEvent(html){
			// One of these is created for each match event included in an update from the server
			this.html = html;
			var $html = $(html);
			
			// Required event attributes
			this.matchID = matchUpdatesManager._parseMatchIDClass($html);
			this.timestamp = matchUpdatesManager._parseTimestampClass($html);
			this.eventType = $html.find('td.event-type').attr('class').replace('event-type', '').match(/event-([^ ]*)/)[1];
			
			// OPTIONAL EVENT ATTRIBUTES
			
			// teamID
			var teamIDmatch = $html.attr('class').match(/teamid([^ ]*)/);
			if(teamIDmatch){
				this.teamID = teamIDmatch[1]
			}
			else {
				this.teamID = null;
			}
			
			// isHomeTeamEvent
			if($html.find('.home-team.alert').length > 0){
				this.isHomeTeamEvent = true;
			}
			else{
				this.isHomeTeamEvent = false;
			}
			
			// minute
			var minuteTag = $html.find('span.minute');
			if(minuteTag.length > 0) {
				this.minute = parseInt(minuteTag.text());
			}
			else {
				this.minute = null;
			}
			
			// playerName
			var playerTag = $html.find('span.player');
			if(playerTag.length > 0){
				this.playerName = playerTag.text();
			}
			else {
				this.playerName = null;
			}
		}

		function MatchEventSet(htmlString){
			this.matchEvents = [];
			var timestamps = [];
			
			var that = this;
			//$(htmlString).filter('tr').each(function(){
			$('tr', htmlString).each(function(){
				// Extract the timestamps for each event, so that we can update the latestUpdate property later on
				var matchEvent = new MatchEvent(this);
				
				that.matchEvents.push(matchEvent);
				timestamps.push(matchEvent.timestamp);
			});
		
			timestamps.sort();
			timestamps.reverse();
			this.latestTimestamp = timestamps[0];
		}
		
		function UpdateArea($html, matchEventHandlers) {
			this.$html = $html;
			this.matchEventHandlers = matchEventHandlers;
			
			// Store the matchids and current scores for all matches contained in the update area in the matches object.
			//this.$html.find('*[class^=matchid]').each(function(){
			this.$html.find('*[class*=matchid]').each(function(){
				
				var $this = $(this);
				
				var matchID = matchUpdatesManager._parseMatchIDClass($this);
				
				if(!(matchID in matchUpdatesManager.matches)) {
					matchUpdatesManager.matches[matchID] = {};
				}
				
				var match = matchUpdatesManager.matches[matchID];
				
				var $scores = $this.find('.score');
				if($scores.length > 0){
					if(!('.homeScore' in match)){
						match.homeScore = parseInt($scores.filter('.home-score').text());
					}
					
					if(!('.awayScore' in match)){
						match.awayScore = parseInt($scores.filter(':not(.home-score)').text());
					}
				}
				
				var $homeTeam = $this.find('.home-team');
				if($homeTeam.length > 0){
					if(!('.homeTeam' in match)){
						match.homeTeam = $homeTeam.text();
					}
				}
				
				var $awayTeam = $this.find('.away-team');
				if($awayTeam.length > 0){
					if(!('.awayTeam' in match)){
						match.awayTeam = $awayTeam.text();
					}
				}
				
				match.update = matchUpdatesManager._updateMatchScore;
			});
		}
		UpdateArea.prototype.update = function(matchEvent){
			// If we’ve got a handler for this kind of event
			if(this.matchEventHandlers[matchEvent.eventType]){
				// Call it
				this.matchEventHandlers[matchEvent.eventType](matchEvent, this.$html);
			}
		}
		
		var matchUpdatesManager = {
			url: '/ADMCDelivery/feeds/updates/updates.jsp',
			latestUpdate: null,
			
			updateAreas: [],
			
			matches: {},
			
			updateAreaConfig: {
				// “Current, recent and upcoming matches” areas in the Match Centre flyout
				'.flyout .upcoming-matches' : {
					'matchEventHandlers' : {
						'goal' : function(matchEvent, $html){
							return matchUpdatesManager._updateScoreMatchEventHandler(matchEvent, $html);
						}
					}
				},
				
				// “Match Updates” areas in the Match Centre flyout (and the duplicate of it in the body on the Match Centre homepage)
				'.flyout .match-updates .body table tbody, #content .match-updates .body table tbody' : {
					'matchEventHandlers' : {
						'goal' : function(matchEvent, $html){
							return matchUpdatesManager._matchUpdatesMatchEventHandler(matchEvent, $html);
						},

						'yellowcard' : function(matchEvent, $html){
							return matchUpdatesManager._matchUpdatesMatchEventHandler(matchEvent, $html);
						},

						'redcard' : function(matchEvent, $html){
							return matchUpdatesManager._matchUpdatesMatchEventHandler(matchEvent, $html);
						},

						'halftime' : function(matchEvent, $html){
							return matchUpdatesManager._matchUpdatesMatchEventHandler(matchEvent, $html);
						},

						'fulltime' : function(matchEvent, $html){
							return matchUpdatesManager._matchUpdatesMatchEventHandler(matchEvent, $html);
						}
					}
				},
				
				// Scores ticker (green text on black at the top of the page)
				'.live-scroller marquee' : {
					'matchEventHandlers' : {
						'goal' : function(matchEvent, $html){
							var $item = matchUpdatesManager._liveScrollerMatchEventHandler(matchEvent, $html);
							
							$item.prepend($('<span class="last-event goal">Goal: ' + matchEvent.playerName + ' (' + matchEvent.minute + ')</span>'));
							
							matchUpdatesManager._updateScoreMatchEventHandler(matchEvent, $html);
						}
					}
				},
				
				// “Latest from Match Centre” module
				'.tb-shade-4': {
					'matchEventHandlers' : {
						'goal' : function(matchEvent, $html){
							return matchUpdatesManager._updateScoreMatchEventHandler(matchEvent, $html);
						}
					}
				},
				
				// Match Centre home page: big match info areas in the middle of the page
				'.match-center': {
					'matchEventHandlers' : {
						'goal' : function(matchEvent, $html){
							var $goalsTableBody = $html.find('.matchid' + matchEvent.matchID + ' table.goals tbody');
							//var $matchScore = $html.find('.matchid' + matchEvent.matchID + ' h2.match');
							
							// If this is the first goal since the page was refreshed, remove the “none” row
							if($goalsTableBody.find('td.none').length > 0){
								$goalsTableBody.find('tr').remove();
							}
							
							if(matchEvent.isHomeTeamEvent){
								var $goal = $('<tr><td class="home">' + matchEvent.playerName + ' (' + matchEvent.minute + ')</td><td class="away"></td></tr>');
							}
							else {
								var $goal = $('<tr><td class="home"></td><td class="away">' + matchEvent.playerName + ' (' + matchEvent.minute + ')</td></tr>');
							}
							
							$goalsTableBody.append($goal);
						},

						'yellowcard' : function(matchEvent, $html){
							var $yellowCardsTableBody = $html.find('.matchid' + matchEvent.matchID + ' table.cards tbody.yellow-cards');
							
							// If this is the first yellow card since the page was refreshed, remove the “none” row
							if($yellowCardsTableBody.find('td.none').length > 0){
								$yellowCardsTableBody.find('tr').remove();
							}
							
							if(matchEvent.isHomeTeamEvent){
								var $card = $('<tr class="yellow-card"><td class="home">' + matchEvent.playerName + ' (' + matchEvent.minute + ')</td><td class="away"></td></tr>');
							}
							else
							{
								var $card = $('<tr class="yellow-card"><td class="home"></td><td class="away">' + matchEvent.playerName + ' (' + matchEvent.minute + ')</td></tr>');
							}
							
							$yellowCardsTableBody.append($card);
						},

						'redcard' : function(matchEvent, $html){
							var $redCardsTableBody = $html.find('.matchid' + matchEvent.matchID + ' table.cards tbody.red-cards');
							
							// If this is the first red card since the page was refreshed, remove the “none” row
							if($redCardsTableBody.find('td.none').length > 0){
								$redCardsTableBody.find('tr').remove();
							}
							
							if(matchEvent.isHomeTeamEvent){
								var $card = $('<tr class="red-card"><td class="home">' + matchEvent.playerName + ' (' + matchEvent.minute + ')</td><td class="away"></td></tr>');
							}
							else
							{
								var $card = $('<tr class="red-card"><td class="home"></td><td class="away">' + matchEvent.playerName + ' (' + matchEvent.minute + ')</td></tr>');
							}
							
							$redCardsTableBody.append($card);
						},
						
						'halftime' : function(matchEvent, $html){
							var $halfTimeTableBody = $html.find('.matchid' + matchEvent.matchID + ' table.half-time tbody');
							
							// If half time has just happened, the HTML page should have the “-” cell in there. However, just in case the HTML and the JavaScript are out of sync, we’ll only do stuff if the “-” cell is in the HTML.
							if($halfTimeTableBody.find('td.none')){
								var match = matchUpdatesManager.matches[matchEvent.matchID];
								
								$halfTimeTableBody.find('tr').remove();
								
								var $halfTimeScore = '<tr><td class="home">' + match.homeTeam + '</td><td class="score">' + match.homeScore + ' - ' + match.awayScore + '</td><td class="away">' + match.awayTeam + '</td></tr>';
							
								$halfTimeTableBody.append($halfTimeScore);
							}
						}
					}
				},
				
				// Match Centre: match heading at the top of the page
				'.match-banner': {
					'matchEventHandlers': {
						'goal' : function(matchEvent, $html){
							var $events = matchUpdatesManager._bannerMatchEventHandler(matchEvent, $html);
							
							$events.append('<li class="goal">' + matchEvent.playerName +' (' + matchEvent.minute + ')</li>');
						},
						
						'yellowcard' : function(matchEvent, $html){
							var $events = matchUpdatesManager._bannerMatchEventHandler(matchEvent, $html);
							
							$events.append('<li class="yellow-card">' + matchEvent.playerName +' (' + matchEvent.minute + ')</li>');
						},
						
						'redcard' : function(matchEvent, $html){
							var $events = matchUpdatesManager._bannerMatchEventHandler(matchEvent, $html);
							
							$events.append('<li class="red-card">' + matchEvent.playerName +' (' + matchEvent.minute + ')</li>');
						}
					}
				}
			},

			_parseTimestampClass: function($tag){
				return $tag.attr('class').match(/timestamp([0-9]*)/)[1];
			},
			
			_parseMatchIDClass: function($tag){
				//return $tag.attr('class').match(/matchid([^ ]*)/)[1];
				return $tag.attr('class').match(/.*matchid([^ ]*).*/)[1];
			},
			
			_updateScoreMatchEventHandler: function(matchEvent, $html){
				var $score = $html.find('.matchid' + matchEvent.matchID + ' span.score.teamid' + matchEvent.teamID);
			
				var currentScore = parseInt($score.first().text());
				var newScore = currentScore + 1;
			
				$score.text(newScore);
			},
			
			_bannerMatchEventHandler: function(matchEvent, $html){
				if($html.find('.matchid' + matchEvent.matchID).length == 0){
					return;
				}
				
				if(matchEvent.isHomeTeamEvent){
					var $events = $html.find('table.meta tbody .home');
				}
				else {
					var $events = $html.find('table.meta tbody .away');
				}
			
				if($events.find('ol').length == 0){
					$events.append($('<ol class="unsigned"></ol>'));
				}
				$events = $events.find('ol');
			
				return $events;
			},
			
			_liveScrollerMatchEventHandler: function(matchEvent, $html){
				var $item = $html.find('.matchid' + matchEvent.matchID);
				
				$item.find('.last-event').remove();
				
				return $item;
			},
			
			_matchUpdatesMatchEventHandler: function(matchEvent, $html){
				
				$html.each(function(){
					var $this = $(this);
					var $currentMatches;
					
					if($this.parents('.flyout').length > 0){
						$currentMatches = $this.parents('.tab-panel').find('.upcoming-matches');
					}
					else {
						if($this.parents('#content').length > 0){
							$currentMatches = $this.parents('#content').find('.match-center');
						}
					}
					
					if($currentMatches.find('.matchid' + matchEvent.matchID).length > 0){
						$(matchEvent.html).clone().prependTo($this);// Clone because we sometimes need this to appear in multiple places, e.g. if it’s a featured game and in a league
					}
				});
			},
			
			_updateMatchScore: function(matchEvent){
				if(matchEvent.eventType == 'goal'){
					if(matchEvent.isHomeTeamEvent){
						this.homeScore = this.homeScore + 1;
					}
					else{
						this.awayScore = this.awayScore + 1;
					}
				}
			},
			
			updatePage: function(){
				$.ajax({
					url: this.url,
					
					data: {
						'latestupdate': this.latestUpdate
					},
					
					dataType: 'html',
					
					context: this,
					
					success: function(data) {
						// Create MatchEventSet for the match events we got back from the server
						var matchEventSet = new MatchEventSet(data);
						// Update the latest update time
						if (matchEventSet.latestTimestamp)
							this.latestUpdate = matchEventSet.latestTimestamp;
						
						// For each event...
						for(var i in matchEventSet.matchEvents){
							var matchEvent = matchEventSet.matchEvents[i];
							// ...update the match in question...
							this.matches[matchEvent.matchID].update(matchEvent);
							
							// ...and ask each UpdateArea to update itself with the events in question.
							for(var j in this.updateAreas) {
								var updateArea = this.updateAreas[j];
								
								updateArea.update(matchEvent);
							}
						}
					}
				});
			},
			
			init: function(){
				// Get the timestamp that the server put in the timestamp class on the body tag, to send to the server when we first ask for updates.
				this.latestUpdate = this._parseTimestampClass($('body'));
				// Cycle through updateAreaConfig, and make an UpdateArea object for each part of the page that needs updating with match events. Store the object in UpdateAreas.
				// Note that the UpdateArea object will populate the matches object above
				for(var selector in this.updateAreaConfig) {
					var $html = $(selector);
					var matchEventHandlers = this.updateAreaConfig[selector].matchEventHandlers;
					
					if($html.length > 0){
						this.updateAreas.push(new UpdateArea($html, matchEventHandlers));
					}
				}
			}
		};
		//matchUpdatesManager.init();

		//window.setInterval(function(){matchUpdatesManager.updatePage();}, 1000*30);
	}


//*------------------------------------------------------------------//

    admcSport.QuickPoll = function() {

        var __pollRadios = $(admcSport.vars.selectors.POLLRADIOS);
        $(".quick-poll").each(function() {


            if (__pollRadios) {

                var __submitbtn = $(this).find("input.button");
                $(__pollRadios).change(function() {
                    $((__pollRadios)).parent("div.input").removeClass("active");
                    $((__pollRadios + ":checked")).parent("div.input").addClass("active");

                });
                $(__submitbtn).bind("click", function() {
                    var __currentpoll = $(this).parents(".quick-poll");
                    var __value = "?val=" + $(__pollRadios + ":checked").val();
                    $(__currentpoll).find(".navigation").hide();
                    $(__currentpoll).find(".poll").hide();
                    if ($("html").attr("dir") === "ltr") {
                        var __url = "opinion-poll-results-ajax.html?";
                    }
                    else {
                        var __url = "opinion-poll-results-ajax-rtl.html?";
                    }
                    $.ajax({ url: __url + __value, cache: false, success: function(html) {
                        $(__currentpoll).find(".bar-graph").remove();
                        $(__currentpoll).find(".bar-graph-nav").remove();
                        $(__currentpoll).children(".body").append(html);

                    }
                    });

                });
                /*$(".quick-poll a.change-vote").live("click", function() {
                var __currentpoll = $(this).parents(".quick-poll");
                $(__currentpoll).find(".bar-graph").remove();
                $(__currentpoll).find(".bar-graph-nav").remove();
                $(__currentpoll).find(".navigation").show();
                $(__currentpoll).find(".poll").show();
                return false;
                });*/
            }
        });






    },
    admcSport.LiveTicker = function() {

        try {
            var ticker_holder = $(admcSport.vars.selectors.LIVETICKER).get(0);
			var ticker = $(ticker_holder).find('marquee').get(0);
            var ticker_pos = ticker_holder.parentNode.offsetWidth;

            $(ticker_holder).hover(
            	function() { ticker.stop(); },
            	function() { ticker.start(); }
        	);
        }
        catch (o) { }
    },
    admcSport.datePicker = function() {

        var __inputfield = admcSport.vars.selectors.HASDATEFIELD;
        if (__inputfield.length > 0) {
            $(".hasdate .input").after("<a href='#' class='date-picker'><img src='/deployedfiles/admc-sport/CommonFiles/images/portal/icons/date.gif' alt='' /></a>")
            if ($('html').attr('dir') == 'rtl') {
                $("#datePicker").datepicker();
            }
            else {
                $.datepicker.setDefaults($.datepicker.regional['']);
                $("#datePicker").datepicker();
            }
            $(".date-picker").bind("click", function() {
                $("#datePicker").focus();
                $("#datePicker").click();
                return false;
            });

        }


    },
    admcSport.quickLinks = function() {

        var __quickLinks = $(".quick-links");

        if (__quickLinks.length > 0) {
            if (admcSport.pageIsArabic()) {
                __quickLinks.append("<select name='competitions'><option value=''>مسابقات</option></select><select name='teams'><option value=''>مسابقات</option></select>");
            }
            else {
                __quickLinks.append("<select name='competitions'><option value=''>Competitions</option></select><select name='teams'><option value=''>Teams</option></select>");
            }
        }

    },

    admcSport.filterNavigation = function() {
        var __nav = $(admcSport.vars.selectors.FILTERNAVIGATION2);
        var __navtrigger = $(".filter-navigation-2 ul li a");
        var __toggletrigger = $(".filter-navigation-2 ul li h2");
        var __innerlist = $(".filter-navigation-2 ul ul");
        __innerlist.hide();
        $(".filter-navigation-2 form").slideUp();
        __toggletrigger.each(function() {
            $(this).wrapInner('<a class="icon closed" href="#"></a>');
            $(this).toggle(function() {
                $(this).siblings("ul").slideDown();
                ($(this).parents("ul")).siblings("form").slideDown();

                $(this).children("a.icon").addClass(admcSport.vars.strings.OPEN);
            },
            function() {
                $(this).siblings("ul").slideUp();
                $(this).children("a.icon").removeClass(admcSport.vars.strings.OPEN);
                ($(this).parents("ul")).siblings("form").slideUp();
            }
        )
        });


        if (__nav.length > 0) {
            $(__navtrigger).toggle(
                function() {
                    $(this).parent("li").addClass("active")

                },
                  function() {
                      $(this).parent("li").removeClass("active")
                  }
                )

        }

    },
    admcSport.innerTabComponent = function() {
        if ($(".inner-tabs").length > 0) {
            $(".inner-tabs").each(function() {

                var __tabcontent = $(this).find(".inner-tab-content")
                var __firsttabid = $(__tabcontent[0]).find("a.named-anchor").attr("id")
                var __counter = 0;
                __tabcontent.hide();

                $(__tabcontent[0]).show();
                $(this).find(".inner-tab-nav ul li span.button").each(function() {

                    var __firstbuttontxt = $(this).text();
                    $(this).parents("li").append("<a class='button' href=" + "'#" + __firsttabid + "'><span class='icon'>" + __firstbuttontxt + "</span></a>");
                    $(this).siblings("a").hide();

                });

                $(this).find(".inner-tab-nav ul li").each(function() {
                    __counter++;

                    $(this).addClass("button-" + __counter);
                    $(this).children("a").bind("click", function() {

                        var __buttontxt = $(this).text();
                        $(this).parents(".inner-tabs").find(".inner-tab-nav ul li").removeClass("active");
                        $(this).parents(".inner-tabs").find(".inner-tab-nav ul li span.button").remove();
                        $(this).parents(".inner-tabs").find(".inner-tab-nav ul li a").show();
                        $(this).parents("li").addClass("active");
                        $(this).parent("li").append("<span class='button'><span class='icon'>" + __buttontxt + "<span class='hidden'> - active</span>" + "</span></span>")
                        $(this).hide();
                        var __currentclass = ($(this).parent("li").attr("class").split("button-", [2])[1]);
                        __tabcontent.hide();
                        var __value = $.trim(__currentclass.split("active", [2])[0]);
                        $(__tabcontent[__value - 1]).show();
                        return false;
                    });
                });
            });
        }

    },

    admcSport.matchCollapsables = function() {
        function matchCollapsable(el) {
            this.match = el;
            this.matchPreview = el.find('.match-preview');
            this.matchDetail = el.find('.match-detail');
            this.matchToggler = $('<a class="replaced match-toggler closed" href="#">Hide / Show</a>');
            this.matchDetail.slideUp();

            this.matchPreview.prepend(this.matchToggler);

            var that = this;
            this.matchToggler.bind
		(
			'click',
			function() {
			    that.matchToggler.toggleClass('closed');
			    that.matchDetail.slideToggle();
			    return false;
			}
		)


        }

        $('.match').each
	(
		function() {
		    new matchCollapsable($(this));
		}
	);

        // Add “Expand all” button, which just calls “click” on every match toggler, and sets its own text correctly
        if (admcSport.pageIsArabic()) {
            var COLLAPSE_TEXT = 'اغلاق';
            var EXPAND_TEXT = 'التفاصيل';
        }
        else {
            var COLLAPSE_TEXT = 'Collapse all';
            var EXPAND_TEXT = 'Expand all';
        }

        var collapseAll = $('<a href="#" class="button button-plus-icon"><span class="button-icon">' + EXPAND_TEXT + '</span></a>');

        collapseAll.bind('click', function() {
            var $this = $(this);

            if ($this.find('.button-icon').text() == EXPAND_TEXT) {
                // Expand all
                $('.match-toggler').each(function() {
                if ($(this).hasClass(admcSport.vars.strings.CLOSED)) {
                        $(this).click();
                    }
                });

                // Set the button to “Collapse all”
                $this.find('.button-icon').text(COLLAPSE_TEXT);

                $this.addClass('button-minus-icon');
                $this.removeClass('button-plus-icon');
            }
            else {
                // Collapse all
                $('.match-toggler').each(function() {
                if (!$(this).hasClass(admcSport.vars.strings.CLOSED)) {
                        $(this).click();
                    }
                });

                // Set the button to “Expand all”
                $this.find('.button-icon').text(EXPAND_TEXT);

                $this.addClass('button-plus-icon');
                $this.removeClass('button-minus-icon');
            }

            return false;
        });

        //$('.match-center').prepend($('<p class="match-toggler-all"></p>').append(collapseAll));
    },
	

    admcSport.pageIsArabic = function() {
        if ($('html').attr('lang') == 'ar') {
            return true;
        }
        else {
            return false;
        }
    }
    //*------------------------------------------------------------------//

    $(function() {
		// PNG fix for Watch Premier League Now images; see http://allinthehead.com/retro/338/supersleight-jquery-plugin
		$('.watch-now-ad .body img[src$=.png], .watch-now-ad-2 .body img[src$=.png]').supersleight({shim: '/deployedfiles/admc-sport/CommonFiles/js/library/supersleight.gif'});// shim image path is relative to the HTML file
		
        var __SEL = admcSport.vars.selectors, __$tmp;
        (function(arg) {
            for (var __i = 0, __j = arg.length, __o; __i < __j; __i++) {
                __o = arg[__i];
                (function() {
                    __$tmp = $(__o.test);
                    return __$tmp.length
                })() ? __o.func(__$tmp) : null;
            }

        })([{ func: admcSport.LiveTicker, test: __SEL.LIVETICKER },		
        { func: admcSport.photoCarousel, test: __SEL.CAROUSELS },
		{ func: admcSport.tabComponents, test: __SEL.MODULETABS },
		{ func: admcSport.tabComponents, test: __SEL.ACTIVETABS },
		{ func: admcSport.filterNavigationComponents, test: __SEL.FILTERNAVIGATION },
		{ func: admcSport.togglerComponents, test: __SEL.TOGGLER },
		{ func: admcSport.scroller, test: __SEL.SCROLLER },
		{ func: admcSport.QuickPoll, test: __SEL.POLLSRADIO },
		{ func: admcSport.datePicker, test: __SEL.HASDATEFIELD },
		{ func: admcSport.filterNavigation, test: __SEL.FILTERNAVIGATION2 },
		{ func: admcSport.quickLinks, test: __SEL.QUICKLINKS },
	//	{ func: admcSport.matchFlyout, test: __SEL.FLYOUT },
		{ func: admcSport.favouriteFootballTeam, test: __SEL.FAVOURITEFOOTBALLSELECT },
		{ func: admcSport.innerTabComponent, test: __SEL.INNERTABS },
		{ func: admcSport.matchCollapsables, test: __SEL.MATCHCOLLAPSIBLEHOOK },
		
		{ func: admcSport.matchUpdates, test: 'body' }
	]);

       

        var output = (function(arr) { return arr[0].g })([{ g: 'stuff'}])

        __$tmp = null;

      
    });
//$("body").addClass("js");
  

