var galleryPLImages = [];

FC.vars = {
    selectors: {
        SUBNAV: 'div.lta-subnav',
        HERO: 'div.lta-hero-image',
        HERO_IMG: 'div.lta-hero-image img',
        HERO_LIST: 'ul.lta-hero-list',
        HERO_DESC: 'div.lta-hero-description',
        HERO_TEXT: 'div.lta-hero-text',
        GALLERY: 'div.lta-gallery',
        GALLERY_CAPTION: 'div.lta-gallery div.lta-caption',
        RECORDS: 'div.lta-records',
        HERO_IMG_LINK: 'div.lta-hero-image a',

        HERO_SLIDESHOW: '.lta-hero',

        MEMBERS_HELP_BTN: 'a.lta-helpbutton',

        THUMB_CONTAINER: 'div.lta-thumbnail-container',
        MAIN_IMG: 'a.lta-main-img',
        SAMPLE_MENU: 'div.lta-sample-menu',
        HOSPITALITY: 'div.lta-hospitality, div.lta-tips-advice',
        HOSPITALITY_IMAGE: 'div.lta-hosp-img img',
        SELECTED: '.lta-selected',

        GALLERY_DETAIL: 'div.lta-pg-view-pane',
        GALLERY_DETAIL_MAIN_IMG: 'div.lta-photogallery-detail div.lta-image a',
        GALLERY_DETAIL_THUMB_CONTAINER: 'div.lta-tn-nav div.lta-pg-wrapper',
        GALLERY_DETAIL_CAPTION: 'div.lta-image p',
        GALLERY_DETAIL_MAIN_IMG_NAV: 'div.lta-m-nav',

        LATEST_PHOTO_GALLERY_PANELS: '.gallery-frame .latest-gallery',
        LATEST_PHOTO_GALLERY_PAGES: ".latest-photos-nav .lta-latest-photos-pages",

        LIST_HOVER: '.lta-detailed-listing ul>li',

        TABLE_CONTAINER: 'div.lta-live-feed',
        TABLE_CONTAINER_SM: 'div.lta-live-feed-small',

        MATCH_TABS: "div.lta-match-tabs",

        LIVETICKER: ".live-scroller",
        EXPANDER: "div.lta-expander",

        //Ranking listings
        RANKING_LISTING: ".lta-ranking-listing",
        RANKING_GROUP: ".lta-ranking-listing .ranking-group",

        SITE_SEARCH: ".lta-site-search",

		FLYOUT_NAVIGATION: ".lta-navigation-flyout",

		PLACEHOLDER_TEXT: ".lta-placeholder-text",
		PLACEHOLDER_TEXT_TITLE: ".lta-placeholder-text",
		
		VERTICAL_SCROLLER: "div.lta-vertical-scroll",
		
		MAP_HOLDER : '#lta-map-holder',
		
		BOX_HOVER : 'div.lta-box35',
		BOX_LINK : 'ul.lta-create-goal',
		
		GOAL_EXPANDER : 'ul.lta-goal-categories a.lta-btn-add',
		VERTICAL_NAV_SCROLL : 'div.lta-vertical-nav-scroll',
		GOAL_TOOLTIP : 'table.lta-create-technical td a',
		GOAL_DRAG_DROP : 'ul.lta-existing-goals',
		GOAL_STATUS_RADIOS : 'div.lta-status-radios label',
		
		FANCY_SELECTS : 'span.lta-fancy-select',
		FANCY_SELECT_GROUP: 'span.lta-fancy-select-group',
        FANCY_SELECT_GROUP_ITEM: 'span.lta-fancy-select-group-item',
		REVEAL_ADDITIONAL_INFO : 'p.lta-additional-info span', 
		GOAL_PRINT : 'ul.lta-goal-tools',
		SPONSORS : '.lta-sponsors',
		SPONSORS_GROUP : '.lta-sponsor-group',
        SHOW_MORE_LINK: '.lta-show-more a',
        CONNECTION_SELECT: ".lta-connections-01",
        CONFIRM_AUTO: ".lta-confirm-auto",
        CONFIRM_SWITCH_AUTO: ".lta-switch-to-auto",
        CONFIRM_MAN: ".lta-confirm-man",
		CONFIRM_CLICK : ".lta-confirm-click",
		SIEBEL_ERROR : ".lta-siebel-error"
    },
    paths: {
        GIF: 'images/clear.gif',
        GOALS_AJAX: '/Handlers/GoalSheetsSequence.ashx'
    },
    hero: [],
    strings: {
        SELECTED: 'lta-selected',
        HOVER: 'hover'
    },
    current: 0,
    currentT: 0,
    regEx: {
        STATUS_SELECTED: /lta-status-selected/
    },
    classNames: {
        STATUS_SELECTED: 'lta-status-selected'
    },
    timeouts: {
        SHOW_FLYOUT_NAV: '',
        HIDE_FLYOUT_NAV: ''
    },
    el: 'ul.rating',
    roles: ['Administrator',
		        'Chairman',
		        'Child Protection Officer',
		        'Club Main Contact',
		        'Clubmark Lead',
		        'Coach',
		        'Committee Member',
		        'Competition Organiser',
		        'Head Coach',
		        'Junior Contact',
		        'Match Secretary',
		        'Mini Tennis Contact',
		        'Performance Programme Manager',
		        'Secretary',
		        'Strength And Condition Coach',
		        'Treasurer',
		        'Veterans Contact',
		        'Volunteer Coordinator'],
    rolesLimits: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    rolesRegex: [/Administrator/g,
		        /Chairman/g,
		        /ChildProtectionOfficer/g,
		        /ClubMainContact/g,
		        /ClubmarkLead/g,
		        /Coach/g,
		        /CommitteeMember/g,
		        /CompetitionOrganiser/g,
		        /HeadCoach/g,
		        /JuniorContact/g,
		        /MatchSecretary/g,
		        /MiniTennisContact/g,
		        /PerformanceProgrammeManager/g,
		        /Secretary/g,
		        /StrengthAndConditionCoach/g,
		        /Treasurer/g,
		        /VeteransContact/g,
		        /VolunteerCoordinator/g
    ],
    shortRole: '',
    currentRoles: '',
    newRoles: '',
    rolesObject: {
        memberId: '',
        clubId: '',
        memberRoles: []
    },
    rolesURL: '/Places-To-Play/Roles-Listener/?p2p=', //destination for roles ajax panel data
    countdownMax: '200'
};

//rolesURL: '/Members-Area/Place-To-Play-Administrator/Volunteers-And-Officials/Roles-Listener/?p2p=', //destination for roles ajax panel data

FC.subnav = function(){
	var __subnav = $j(FC.vars.selectors.SUBNAV)[0] , __$li, __hoverLi, __allLis = [], __STR = FC.vars.strings;
	var __$li_a = $j('li a', __subnav);
	
	__$li_a.each(function () {
		var __$li = $j(this).parents('li'), __li;
		
		// if 2 LIs, then 'this' is on the dropdown, else 'this' is the 'A' in the top level LI
		__li = (__$li.length === 2) ? __$li[1] : __$li[0]; 	
		
		// attach a jQ version of the LI to the LI itself
		__allLis[__allLis.length] = __li.$li =__$li = __li.$li || $j(__li);
		
		if (FC.hasIE6) { // if IE6, set the hover class on the parent LI
			__$li.bind('mouseover', function (e) {
				var __j = __allLis.length;
				if (e.target !== __hoverLi) {
					while (__j--){
						__allLis[__j].removeClass(__STR.HOVER);
					}
					__$li.addClass(__STR.HOVER);
					__hoverLi = e.target;
				}
			}).bind('mouseout', function(e){
				__$li.removeClass(__STR.HOVER);
				__hoverLi = null;
			})	


		} else {
			__$li.bind('mouseover', function(){ // removes keyboard focused LI on rollover
					var __j = __allLis.length;
					while (__j--) {
						__allLis[__j].removeClass(__STR.HOVER);
					}
					__hoverLi = this;
			});
		}	
		// create a property on the current anchor that points to the LI's jQ version
		this.par = __li;
	});

	
	// for keyboard control
	if (FC.hasLteIE7) {
		$j(__subnav).bind('focusin', function (e) {
			if (e.target.par) {
					if (e.target.par !== __hoverLi) {
						var __j = __allLis.length;
						while (__j--){
							__allLis[__j].removeClass(__STR.HOVER);
						}
						e.target.par.$li.addClass(__STR.HOVER);
						__hoverLi = e.target.par;
					}
			}
			return false;
		}).bind('focusout', function (e) {
			if (e.target.par === __hoverLi) {
				e.target.par.$li.removeClass(__STR.HOVER);
				__hoverLi = null;
			}
		});
	} else {
		__$li_a.bind('focus', function(){
			if (this.par !== __hoverLi) {
				var __j = __allLis.length;
				while (__j--){
					__allLis[__j].removeClass(__STR.HOVER);
				}
				this.par.$li.addClass(__STR.HOVER);
				__hoverLi = this.par;
			}
		}).bind(' blur', function () {
			if (this.par === __hoverLi) {
				this.par.$li.removeClass(__STR.HOVER);
				__hoverLi = null;
			}
		});
	}	
};

FC.fancyNav = function()
{
	$j("div.lta-fancy-nav li a:first-child").hover
	(
		function()
		{
			$j(this).parent().css({'z-index' : '999'});
			$j(this).find('img').stop().animate
			(
				{
					marginTop: '-10px', 
					marginLeft: '-46px', 
					width: '233px', 
					height: '100px'
				}, 200
			);
		},
		function() 
		{
			$j(this).parent().css({'z-index' : '0'});
			$j(this).find('img').stop().animate
			(
				{
					marginTop: '0', 
					marginLeft: '0',
					width: '140px', 
					height: '60px' 
				}, 150
			);
		}
	);
}

FC.heroPanel = function($list) {
    var __SEL = FC.vars.selectors, __HER = FC.vars.hero, __PTH = FC.vars.paths, __STR = FC.vars.strings;
    var __list = $list[0], __$hero = $j(__SEL.HERO), __hero = __$hero[0];
    var __$lis = $j('li', __list), __$img = $j('img', __hero),
		__$text, __text, __$desc,
		__$pDesc, __$h2Text, __$pText;
    var __css = { left: null };

    $j('.lta-hero-list-item', __$lis[0]).addClass(__STR.SELECTED);
    __$lis.each(function(i) {
        __HER[i] = {
            description: $j('.lta-item-description', this).text(),
            title: $j('.lta-item-title', this).text(),
            subtitle: $j('.lta-item-subtitle', this).text(),
            imgsrc: $j('.lta-hero-list-item img', this)[0].src,
            heroLink: $j('.lta-hero-list-item a', this)[0].href,
            heroTarget: $j('.lta-hero-list-item a', this)[0].target
        };
        $j('.lta-accessibility', this).remove();
    });

    __$img
		.after('<div class="lta-hero-text"><div class="lta-padding"><h2>' + __HER[0].title + '</h2><p>' + __HER[0].subtitle + '</p></div></div>')
		.after('<div class="lta-hero-description" style="display:none"><div class="lta-padding"><p>' + __HER[0].description + '</p></div></div>');

    __$text = $j(__SEL.HERO_TEXT, __hero);
    __text = __$text[0];
    __$desc = $j(__SEL.HERO_DESC, __hero);
    __$pDesc = $j('p', __$desc[0]);
    __$h2Text = $j('h2', __text);
    __$pText = $j('p', __text);

    FC.pngFix(__PTH.GIF, __hero);

    __$lis.bind('mouseenter', function(e) {
        __arr = __HER[__$lis.index(this)];
        __offset = __$text.width();

        $j(__SEL.SELECTED, __list).removeClass(__STR.SELECTED);
        $j('.lta-hero-list-item', this).addClass(__STR.SELECTED);

        if (__$pDesc.text() !== __arr.description) {
            if (!FC.hasLteIE7) {
                __css.left = -__offset;
                __$text.animate(__css, 200);
                __$img.fadeOut(200, function() {
                    $j('a', __hero)[0].href = __arr.heroLink;
                    $j('a', __hero)[0].target = __arr.heroTarget;
                    this.src = __arr.imgsrc;
                    __$img.fadeIn(400, function() {
                        __$pDesc.text(__arr.description);
                        __$h2Text.text(__arr.title);
                        __$pText.text(__arr.subtitle);
                        __css.left = 0
                        __$text.animate(__css, 300);
                    });
                });
            } else {
                __$img.fadeOut(200, function() {
                    __$h2Text.text(__arr.title);
                    __$pText.text(__arr.subtitle);
                    $j(__SEL.HERO_IMG_LINK)[0].href = __arr.heroLink;
                    $j(__SEL.HERO_IMG_LINK)[0].target = __arr.heroTarget;

                    this.src = __arr.imgsrc;
                    __$img.fadeIn(400, function() {
                        __$pDesc.text(__arr.description);
                        FC.pngFix(__PTH.GIF, __hero);
                    });
                });
            }
        }
    });

    if (!FC.hasLteIE7) {
        __$hero
			.bind('mouseenter', function() { __$desc.slideDown(400) })
			.bind('mouseleave', function() { __$desc.slideUp(300) });
    } else {
        __$hero
			.bind('mouseenter', function() { __$desc.show() })
			.bind('mouseleave', function() { __$desc.hide() });
    }
}

FC.recordsScroller = function($rec){
	var __axis = {axis:'x'};
	
	var __$rec = $rec, __rec = $rec[0];
	__$rec.append('<div class="lta-page-nav lta-clear"><ul><li class="lta-prev"><a href="#">Previous Record</a></li><li class="lta-next"><a href="#">Next Record</a></li></ul></div>');
	
	var __$left = $j('li.lta-prev', __rec);
	var __$right = $j('li.lta-next', __rec);
	var __$container = $j('div.lta-records-container', __rec);
	var __$contentBoxes = $j('li.lta-records-set', __rec);
	var __scrollAmount = 1;
	var __current = 0;
	var __max = __$contentBoxes.length;

	//Make sure the scroller is at the start
	__$container.scrollTo( 'li:eq('+0+')', 200, __axis);
	
	if(__max===__$contentBoxes.length){
		__max=__max - __scrollAmount;
	}
	
	// show/hide the prev/next buttons
	__$left.hide();

	//Left scroller button
	__$left.bind("click", function(e){
		if(__current>0){
			__current -= __scrollAmount;
			__$container.scrollTo( 'li.lta-records-set:eq('+__current+')', 500, __axis);
			__$right.show();
				if(__current === 0){
				__$left.hide();
			}
		}
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
	});
	
	//Right scroller button
	__$right.bind("click", function(e){
		if(__current<__max){
			__current += __scrollAmount;
			__$container.scrollTo( 'li.lta-records-set:eq('+__current+')', 500, __axis);
			__$left.show();
			if(__current === __max){
				__$right.hide();
			}
		}
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
	});
	
}

// vertical scroller function */
FC.verticalScroll = function(container){
	var __axis = {axis:'y'}, __$divs = container.find("div.lta-tab-content"), __$ul, __j = __$divs.length;
	
	while (__j--) {
		var __$this = $j(__$divs[__j]), __$contentBoxes, __scrollAmount = 5, __current = 0, height = 0;
		
		__$ul = __$this.find(">ul.lta-listing");
		__$contentBoxes = __$ul.find(">li");
		
		if (__$contentBoxes.length < 5) continue;
		
		for (i=0;i<=4;i++) {
			height += __$contentBoxes.eq(i).height();
		}
		
		__$ul.height(height);
		
		//add controls
		__$ul.before('<a href="#" class="lta-prev">Previous</a>');
		__$ul.after('<a href="#" class="lta-next">More</a>');
		
		var	__$right = $j("a.lta-next", __$divs[__j]), __$left = $j("a.lta-prev", __$divs[__j])
		
		__$ul[0].style.overflow = 'hidden';
		
		var __max = __$contentBoxes.length//*__scrollAmount;
		
		//Make sure the scroller is at the start
		__$this.scrollTo(__$contentBoxes[0], 200, __axis);
		
		if(__max==__$contentBoxes.length){
			__max=__max-1;
		}
		
		// show/hide the prev/next buttons
		__$left.hide();
		
		//Left scroller button
		__$left.bind("click", function(e){
			if(__current>0){
				__current = __current-__scrollAmount;
				__$ul.scrollTo('>li:eq('+__current+')', 500, __axis);
				__$right.show();
					if(__current == 0){
					__$left.hide();
				}
			}
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		});
		
		//Right scroller button
		__$right.bind("click", function(e){
			if(__current<__max){
				__current = __current+__scrollAmount;
				__$ul.scrollTo( '>li:eq('+__current+')', 500, __axis);
				__$left.show();
				if((__max - __current) <= __scrollAmount){
					__$right.hide();
				}
			}
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		});
		
	}
}


// scroller function for sample menu/hospitality component */
FC.panelScroller = function(container){
	var __axis = {axis:'x'};
	
	container.each(function(){
		var __scrollAmount = 1, __current = 0, __hasPNG;
		
		var __$this = $j(this), __$container = $j("div.lta-cf-pane", this),__$contentBoxes = $j("div.lta-cf-item", this), 
			__$right = $j("a.lta-next", this), __$left = $j("a.lta-prev", this), __$link = $j("div.lta-cf-item a", this);
		
		var __container = __$container[0];
		__container.style.overflow = 'hidden';
		__$contentBoxes.css("float","left");
		
		$j("ul.lta-img-nav", this).show();
	
		var __max = __$contentBoxes.length*__scrollAmount;
		
		//Make sure the scroller is at the start
		__$container.scrollTo('div.lta-cf-item:eq('+0+')', 200, __axis);
		
		if(__max==__$contentBoxes.length){
			__max=__max-1;
		}
		
		// show/hide the prev/next buttons
		__$left.hide();
		
		// handle links inside the boxes
		// explicity exclude those coverflows that don't have transparencies
		//__hasPNG =(this.className.indexOf('lta-winners-scroll') > 0 || this.className.indexOf('lta-sample-menu') > 0) ? true : false;
	

		//Link
		__$link.bind("focus", function(){
			// need to detect which image the link being focussed is on, and then scroll to that lta-cf-item
			
			__$container.scrollTo($j(this).parents('div.lta-cf-item'), 500, __axis);
			
			var __current = $j('div.lta-cf-item').index($j(this).parents('div.lta-cf-item')); 
			
			//var listItem = document.getElementById('bar');
			//$j('li').index(listItem))
			
			

		});	
		
		//Left scroller button
		__$left.bind("click", function(e){
			if(__current>0){
				__current = __current-__scrollAmount;
				__$container.scrollTo('div.lta-cf-item:eq('+__current+')', 500, __axis);
				__$right.show();
					if(__current == 0){
					__$left.hide();
				}
			}
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		});
		
		//Right scroller button
		__$right.bind("click", function(e){
			if(__current<__max){
				__current = __current+__scrollAmount;
				__$container.scrollTo( 'div.lta-cf-item:eq('+__current+')', 500, __axis);
				__$left.show();
				if(__current == __max){
					__$right.hide();
				}
			}
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		});

	});// end 'each' statement
}


// scroller function for images on About Us page */
FC.galleryScroller = function($container){
	var __scrollAmount = 8, __current = 0, __axis = {axis:'y'};
	var __scrolls = (FC.hasLteIE7) ? (function(){var __$tmp=$j("div.lta-scroll-control");return [__$tmp[0], __$tmp[1]]})():document.body.querySelector("div.lta-scroll-control");
	
	var __$container = $container, __$down, __$up;
	__$down = $j("a.lta-next-img", __scrolls[1]);
	__$up = $j("a.lta-prev-img", __scrolls[0]);
	
	__$container.css('overflow-y','hidden');
	__$down[0].style.display = __$up[0].style.display = "block";

	var __$contentBoxes = $j("li", __$container[0]);
	var __length = __$contentBoxes.length;
	var __max = __scrollAmount * Math.ceil(__length/__scrollAmount);
	
	//if the number of boxes is the same as the scroll amount - then hide the 'next' arrow - it's not needed
	if(__length <= __scrollAmount){
		__$down.hide();
	}

	//Make sure the scroller is at the start
	__$container.scrollTo( 'li:eq(0)', 200, __axis);
	
		// show/hide the prev/next buttons
	__$up.hide();

	__$up.bind("click", function(e){//Left scroller button
		if(__current>0){
			__current = __current-__scrollAmount;
			__$container.scrollTo( 'li:eq('+__current+')', 500, __axis);	
			__$down.show();
				if(__current === 0){
				__$up.hide();
			}
		}
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
	});

	__$down.bind("click", function(e){ //Right scroller button
		if(__current<__max){
			__current = __current+__scrollAmount;
			__$container.scrollTo( 'li:eq('+__current+')', 500, __axis);
			__$up.show();
				if((__current + __scrollAmount) >= __max){
				__$down.hide();
			}
		}
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
	});
	
};

// scroller function for images on Photogallery- details page */
FC.galleryDetailScroller = function($container) {

    var __scrollAmount = 6, __scrollIndex = 0, __axis = { axis: 'x' };
    //var __controls = (FC.hasLteIE7) ? (function() { var __$tmp = $j("div.lta-tn-nav"); return __$tmp[0] })() : document.body.querySelector("div.lta-tn-nav");
    var __controls = $j("div.lta-tn-nav")[0];

    var __$container = $container, __$down, __$up, __$mDown, __$mUp;
    var __$mainImage = $j('img', FC.vars.selectors.GALLERY_DETAIL_MAIN_IMG);
    var __STR = FC.vars.strings;

    var __$caption = $j(FC.vars.selectors.GALLERY_DETAIL_CAPTION);

    __$down = $j("div.lta-next-image a", __controls);
    __$up = $j("div.lta-prev-image a", __controls);

    //main image controls
    __$mDown = $j("div.lta-m-nav.lta-next-image a");
    __$mUp = $j("div.lta-m-nav.lta-prev-image a");

    __$container.css('overflow-y', 'hidden');

    __$down[0].style.display = __$up[0].style.display = __$mDown[0].style.display = "block";

    var __$contentBoxes = $j("li", __$container[0]);
    var __length = (__$contentBoxes.length - 1);
    var __max = __scrollAmount * Math.ceil(__length / __scrollAmount);
    var __lastScroll = Math.floor(__length / __scrollAmount) * __scrollAmount;


    //if the number of boxes is the same as the scroll amount - then hide the 'next' arrow - it's not needed
    if ((__length + 1) <= __scrollAmount) {
        __$down.hide();
    }

    //Make sure the scroller is at the start
    __$container.scrollTo('li:eq(0)', 200, __axis);

    // show/hide the prev buttons
    __$up.hide();
    __$mUp.hide();

    __$up.bind("click", function(e) {//Left scroller button
        if (FC.vars.currentT > 0) {
            __scrollIndex = __scrollIndex - __scrollAmount;
            FC.vars.currentT = __scrollIndex + __scrollAmount - 1;
            __$container.scrollTo('li:eq(' + __scrollIndex + ')', 500, __axis);
            __$down.show();

            if ((FC.vars.currentT === 0) || (__scrollIndex == 0)) {
                __$up.hide();
            }

            if (FC.vars.currentT < __length) {
                //__$mDown.show();
            }
        }
        //instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);
    });
    __$down.bind("click", function(e) { //Right scroller button
        if (FC.vars.currentT < __max) {
            __scrollIndex = __scrollIndex + __scrollAmount;
            FC.vars.currentT = __scrollIndex;
            __$container.scrollTo('li:eq(' + __scrollIndex + ')', 500, __axis);
            __$up.show();
            //__$mUp.show();

            if ((FC.vars.currentT + __scrollAmount) >= __max) {
                __$down.hide();
            }

            //calculate if main image previous button needs to show
            if (FC.vars.currentT == __length) {
                __$mDown.hide();
            }
        }

        //instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);
    });

    __$mUp.bind("click", function(e) {//Main image Left  button
        if (FC.vars.current > 0) {
            __previousItem = FC.vars.current;
            __previousItem--;
            __$previousEl = __$container.find('li:eq(' + __previousItem + ') a')
            __caption = $j("img", __$previousEl).attr('alt');
            __imgPath = __$previousEl.attr('href');


            __$mainImage.fadeOut(250, function() {
                __$mainImage
					.attr('src', __imgPath)
					.fadeIn(250, function() {
					    $j(__$caption).text(__caption);
					});
            });


            //if FC.vars.current is a multiple of 6, then scroll

            //Work out which set of 6 to scroll to
            var __reset = FC.vars.current - 1;
            __reset = Math.floor(__reset / __scrollAmount)
            __reset = __reset * __scrollAmount;
            __scrollIndex = __reset;
            __$container.scrollTo('li:eq(' + __reset + ')', 500, __axis);
            __$mDown.show();

            if (__reset < __lastScroll) {
                __$down.show();
            }

            //if the previousItem is zero, hide the main image previous button
            if (__previousItem == 0) {
                __$mUp.hide();
            }

            //if the first set of 6 thumbs is displayed, hide the previous button
            if (FC.vars.current <= __scrollAmount) {
                __$up.hide();
            }

        }

        // remove selected class
        $j('li', $container).each(function() {
            if (this.className.indexOf(__STR.SELECTED) != -1) {
                this.className = '';
            }
        });
        // add new selected class
        __$previousEl[0].parentNode.className = __STR.SELECTED;

        FC.vars.current--;

        //instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);

    });


    __$mDown.bind("click", function(e) { //Main image right scroller button

        if (FC.vars.current < __length) {
            __nextItem = FC.vars.current;
            __nextItem++;
            __$nextEl = __$container.find('li:eq(' + __nextItem + ') a');
            __caption = $j("img", __$nextEl).attr('alt');
            __imgPath = __$nextEl.attr('href');

            __$mainImage.fadeOut(250, function() {
                __$mainImage
					.attr('src', __imgPath)
					.fadeIn(250, function() {
					    $j(__$caption).text(__caption);
					});
            });

            //calculate if scrolling is required
            //if __nextItem is a multiple of 6, then scroll
            if ((__nextItem % __scrollAmount == 0) && (FC.vars.current != 0)) {
                __scrollIndex = __scrollIndex + __scrollAmount;
                __$container.scrollTo('li:eq(' + __scrollIndex + ')', 500, __axis);
                FC.vars.currentT = __scrollIndex;
                __$up.show();


                //calculate if scroll section is displayed. if so, hide the next button
                if ((__nextItem + __scrollAmount) >= __max) {
                    __$down.hide();
                }
            }
            else if (FC.vars.current < __scrollIndex) {
                __scrollIndex = __scrollIndex - __scrollAmount;

                FC.vars.currentT = __scrollIndex + __scrollAmount - 1;
                __$container.scrollTo('li:eq(' + __scrollIndex + ')', 500, __axis);
                __$down.show();
            }

            //calculate if last item is displayed. if so, hide the next buttons
            if (__nextItem >= __length) {
                __$mDown.hide();
            }

            //calculate if main image previous button needs to show
            if (__nextItem != 0) {
                __$mUp.show();
            }
            FC.vars.scrollInitialised = true;

        }

        // remove selected class
        $j('li', $container).each(function() {
            if (this.className.indexOf(__STR.SELECTED) != -1) {
                this.className = '';
            }
        });
        // add new selected class
        __$nextEl[0].parentNode.className = __STR.SELECTED;

        FC.vars.current++;

        //instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);
    });
}

// Show image function for images on Photo Gallery page
FC.showGalleryDetailImage = function($main) {
	
    var counter = 0, __image = [], __SEL = FC.vars.selectors, __PTH = FC.vars.paths, __STR = FC.vars.strings, __caption;
    var __$container = $j(__SEL.GALLERY_DETAIL_THUMB_CONTAINER);
    var __$mainImage = $j('img', $main[0]), __$anchors = $j("a", __$container[0]), __$caption = $j(__SEL.GALLERY_DETAIL_CAPTION);
    var __$mDown = $j("div.lta-m-nav.lta-next-image a");
    var __$mUp = $j("div.lta-m-nav.lta-prev-image a");

    __$anchors
		.each(function(i) { // preload images
		    __image[i] = new Image();
		    __image[i].src = this.href;
		});

    __$container
		.unbind()
		.bind("click", function(e) {
		    var __tag = e.target.tagName, __$a;

		    if (__tag == "A") {
		        __$a = $j(e.target);

		    } else if (__tag == "IMG") {
		        __$a = $j(e.target.parentNode.parentNode);
		    } else if(__tag == "SPAN"){
				__$a = $j(e.target.parentNode);	
			}
			
			else {
		        return
		    }

		    var __imgPath = __$a.attr('href');

		    if (__imgPath != '#') {
		        //set the caption from the alt text
		        __caption = $j("img", __$a[0]).attr('alt');

		        // cease all current animations
		        __$caption.stop(true, true);
		        __$mainImage.stop(true, true);

		        __$mainImage.fadeOut(250, function() {
		            __$mainImage
						.attr('src', __imgPath)
						.fadeIn(250, function() {
						    $j(__$caption).text(__caption);
						    FC.pngFix(__PTH.GIF, $j(__SEL.GALLERY)[0]);
						});
		        });

		        // remove selected class
		        $j('li', this).each(function() {
		            if (this.className.indexOf(__STR.SELECTED) != -1) {
		                this.className = '';
		            }
		        });
		        // add new selected class
		        __$a[0].parentNode.className = __STR.SELECTED;
		        var __par = __$a.parent();
		        var index = $j('li', __$container).index(__par);
				
				
				
		        FC.vars.current = index;
				
		        if (FC.vars.current != 0) {
		            __$mUp.show();
		        }
		        else {
		            __$mUp.hide();
		        }
			
				//If it's the last image, hide the main image right button
				if(FC.vars.current == __$anchors.length-1){
					__$mDown.hide();
				}
			    else {
		            __$mDown.show();
		        }			
		    }
		    //instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		});

}

// Show image function for images on About Us page
FC.showImage = function($main){
	var counter = 0, __image = [], __SEL = FC.vars.selectors, __PTH = FC.vars.paths, __STR = FC.vars.strings, __caption;
	var __$container = $j(__SEL.THUMB_CONTAINER);
	var __$mainImage = $j('img', $main[0]), __$anchors = $j("a", __$container[0]), __$caption = $j(__SEL.GALLERY_CAPTION);
	
	__$anchors
		.each(function(i) { // preload images
			__image[i] = new Image();
			__image[i].src = this.href; 
		});
		
	__$container	
		.unbind()
		.bind("click",function(e){
			var __tag = e.target.tagName, __$a;
			
			if (__tag == "A") {
				__$a = $j(e.target);
				
			} else if (__tag == "IMG"){
				__$a = $j(e.target.parentNode);
			} else {
				return
			}
			
			var __imgPath = __$a.attr('href');
			
			if(__imgPath != '#'){
				//set the caption from the alt text
				__caption = $j("img", __$a[0]).attr('alt');
				
				// cease all current animations
				__$caption.stop(true, true);
				__$mainImage.stop(true, true);
				
				__$caption.slideUp(200, function(){
					__$mainImage.fadeOut(250,function(){
						__$mainImage
							.attr('src',__imgPath)
							.fadeIn(250, function(){
								$j('p', __$caption[0]).text(__caption);
								__$caption.slideDown(400);
								FC.pngFix(__PTH.GIF, $j(__SEL.GALLERY)[0]);
							});
					});
				});		
				
				// remove selected class
				$j('li', this).each(function(){
					if(this.className.indexOf(__STR.SELECTED) != -1){
						this.className = '';
					}
				});
				// add new selected class
				__$a[0].parentNode.className = __STR.SELECTED;
			}
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		});			

	FC.pngFix(__PTH.GIF, $j(__SEL.GALLERY)[0]);			
}


FC.hospSlideshow = function($img) {
	var __i = 1, __images = [], __imageCount = 0, __src = $img[0].src;
	var __srcSplit = __src.substring(0, __src.length-5);
	
	//try to preload up to 10 images and count how many exist
	for(__j = 1; __j < 10; __j++){
		__images[__j] = new Image();
		__images[__j].onload = function(){
			__imageCount++;
		}
		__images[__j].src = __srcSplit + __j + ".jpg";
	}
	
	//fade between images
	setInterval(function () {
		$img.fadeOut(400,function(){
			__i++;
			if(__i > __imageCount) {
				__i = 1;
			}
			this.onload = function(){
				$img.fadeIn(400);
			}
			this.src = __srcSplit + __i + ".jpg";
		})
	},6000)
}


FC.setupToggle = function($par){
	var __STR = FC.vars.strings, __par = $par[0];
	
	var __$togSing = $j('a.lta-singles', __par),
		__$togDoub = $j('a.lta-doubles', __par),
		__$divSing = $j('div.lta-singles', __par),
		__$divDoub = $j('div.lta-doubles', __par);
	
	__$divDoub.hide();
	
	__$togDoub.bind("click",function(e){	
		__$togSing.removeClass(__STR.SELECTED);
		__$togDoub.addClass(__STR.SELECTED);
		__$divSing.hide();
		__$divDoub.show();
		
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
	});
	__$togSing.bind("click",function(e){	
		__$togDoub.removeClass(__STR.SELECTED);
		__$togSing.addClass(__STR.SELECTED);
		__$divDoub.hide();
		__$divSing.show();	
		
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
	});
	
	FC.panelScroller(__$divSing);
	FC.panelScroller(__$divDoub);
}


var sponsorcounter = 1;
var intervalID;

FC.sponsorSlideshow = function(m) {
	var __sponsorImage = ".lta-sponsors-widget .lta-s" + sponsorcounter;
	$j(__sponsorImage).fadeOut(350,function(){
		sponsorcounter++;
		if(sponsorcounter==(m + 1)){sponsorcounter=1;}
		__sponsorImage = ".lta-sponsors-widget .lta-s" + sponsorcounter;
		$j(__sponsorImage).fadeIn(350);
	});
				
}

// count element c = class, e = element type
FC.countElement = function(c, e){
	var __elementNum = $j(c + " > " + e).size();
	return __elementNum;
}

// f = function name to pause
FC.pauseBtn = function(){
	
	//Switch the "Open" and "Close" state per click
	$j(".lta-pausePlay a").toggle(function(e){
		$j(this).addClass("lta-play");
		clearInterval(intervalID);		
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
		
		}, function () {
			$j(this).removeClass("lta-play");
			FC.initSlideshow(sponsorcounter);
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
	});

}

// sc = sponsor counter
FC.initSlideshow = function(sc) {
    var maxSponsors = FC.countElement('.lta-sponsors-widget', 'a');
    //console.log(maxSponsors);
    //hide all
    for (i = 1; i < (maxSponsors + 1); i++) {
        var sponsorImage = ".lta-sponsors-widget .lta-s" + i;
        $j(sponsorImage).hide();
    }
    // use the sponsorcounter to figure out what we're up to, and go show it
    var sponsorImage = ".lta-sponsors-widget .lta-s" + sc;
    $j(sponsorImage).show();

    intervalID = setInterval("FC.sponsorSlideshow(" + maxSponsors + ")", 4000);
    return false;
},

FC.countCharacters = function() {
    var _$textarea = $j(".lta-limitchar");

    $j(".lta-char-count").html("You have&nbsp;" + "<strong>500</strong>" + "&nbsp;characters remaining");
    var _$counter = $j(".lta-char-count strong"), _max = Number(500), _loadLength;
    var _textarea = _$textarea[0];

    _loadLength = (_textarea.value.length) ? _max - _textarea.value.length : _max;
    if (_loadLength == 0) {
        _$counter.addClass(FC.vars.strings.LIMIT_REACHED);
    }
    _$counter.text(_loadLength);

    var _textCalc = function(e) {
        var __length = _textarea.value.length;

        if (e.keyCode != 46 && e.keyCode != 8) {
            if (__length >= _max) { // if too long...trim it!
                _$counter.addClass(FC.vars.strings.LIMIT_REACHED);
                _textarea.value = _textarea.value.substring(0, _max);
                _$counter.text(_max - __length);
                return false
            } else {
                _$counter.removeClass(FC.vars.strings.LIMIT_REACHED);
                _$counter.text(_max - __length);
            }
        } else {
            _$counter.removeClass(FC.vars.strings.LIMIT_REACHED);
            _$counter.text(_max - __length);
        }
    };

    _$textarea
           .bind('keydown', _textCalc)
           .bind('keyup', _textCalc)
           .bind('change', _textCalc);
},

FC.helpButton = function() {
    $j("a.lta-helpbutton").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        extraClass: "lta-tooltip",
        showBody: " - ",
        top: -40,
        left: 30
    });
    $j("a.lta-helpbutton").bind('click', function(e) {
        //instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);
    });
}

FC.Tabs = function() {
    $j(".lta-tabs").each(function(intIndex) {

        //add check for alltc
        var __alltc = $j(".lta-tab-content", this);
        var __tabs = $j(".lta-toggle-alt li a", this);
        
        if(__tabs.length == 0)
        {
            $j(".lta-tab-content-" + (intIndex + 1)).css({ "display": "block" });
        }
        else
        {
            $j(__tabs).each(function(intIndex) {   
                var __parTabs = $j(this).parents('.lta-tabs');
                var selectedIndex = __parTabs.attr("rel");                   
                if (intIndex == selectedIndex) {
                    $j(".lta-tab-content-" + (intIndex + 1), __parTabs).css({ "display": "block" });
                    $j(this).addClass("lta-selected");
                }
                $j(this).bind("click", function() {
                    var __parTabs = $j(this).parents('.lta-tabs');
                    __alltc.css({ "display": "none" });
                    $j(__tabs).removeClass("lta-selected");
                    $j(".lta-tab-content-" + (intIndex + 1), __parTabs).css({ "display": "block" });
                    $j(this).addClass("lta-selected");
                    return false;
                })
            });
        }
    })
}

FC.PhotoGalleryScroll = function() {
    var __header = $j(".gallery-frame").siblings(".lta-header");
	var __navcontainer = $j(".lta-title-nav");
	var __photonav = ("<p>&nbsp;</p><div class='latest-photos-nav'><div class='lta-latest-photos-pages'><span class='lta-current'>1</span> of <span class='lta-total'></span></div></div>");
    var __pagecount = 0;

	
    __navcontainer.append(__photonav);
	if($j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).length == 1){
		$j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).css({'display': 'none'});
	}
	
    $j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS + ":first").css({ "display": "block" });

    $j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).each(function() {
        __pagecount = __pagecount + 1;
        $j(this).addClass("lta-latest-gallery-" + __pagecount);
    });

	$j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES + ' .lta-total').text(__pagecount);
	
	if($j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).length > 1){
	    AppendBack();
	    AppendNext();
	}
	
    function AppendBack() {
        if (parseInt($j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES + ' .lta-current').text()) == 1) {
            $j(".nav-back").remove();
            $j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).before("<span class='nav-back'><span>Back - disabled</span></span>");
        }
        else {
            $j(".nav-back").remove();
            $j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).before("<a class='nav-back'><span>Back</span></a>");
			
            $j("a.nav-back").bind("click", function(e) {
				$j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).css({ "display":  "none"});
				
                var currentEq = parseInt($j(this).siblings(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).find('.lta-current').text()) - 1;
				var previousEq = currentEq - 1;
				
				$j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).eq(previousEq).css({ "display":"block" });
				$j(this).siblings(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).find('.lta-current').text(previousEq + 1);
				
				AppendBack();
				AppendNext();

                //instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
            });
        }
    }
    
    function AppendNext() {
        if (parseInt($j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES + ' .lta-current').text()) == parseInt($j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES + ' .lta-total').text())) {
            $j(".nav-next").remove();
            $j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).after("<span class='nav-next'><span>Next - disabled</span></span>");
           
        }
        else {
            $j(".nav-next").remove();
            $j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).after("<a class='nav-next'><span>Next</span></a>");

            $j("a.nav-next").bind("click", function(e) {
				$j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).css({ "display":  "none"});
				
                var currentEq = parseInt($j(this).siblings(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).find('.lta-current').text()) - 1;
				var nextEq = currentEq + 1;
				
				$j(FC.vars.selectors.LATEST_PHOTO_GALLERY_PANELS).eq(nextEq).css({ "display":"block" });
				$j(this).siblings(FC.vars.selectors.LATEST_PHOTO_GALLERY_PAGES).find('.lta-current').text(nextEq + 1);
				
				AppendBack();
				AppendNext();
				
				//instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
            });
        }
    }
}

FC.search = function(el){
	searchModule = function(el){
		this.form = $j(el);
		this.basicSearch = this.form.find('.lta-search-basic');
		this.advancedSearch = this.form.find('.lta-search-advanced');
		
		ToggleSearchOptions(this.form.find('.lta-radio-location').children(1).is(':checked'));
		
		this.toggleBtn = this.form.find('.lta-btn-toggle');
		
		this.buttonStatus = function(){
			if (this.advancedSearch.css('display') == 'none') {
				this.toggleBtn.html('More options');
				this.toggleBtn.removeClass('less').addClass('more');
			}
			else {
				this.toggleBtn.html('Less options');
				this.toggleBtn.removeClass('more').addClass('less');
			}
		}
		
		var that = this;
		
		this.toggleBtn.bind('click', function(e){
			that.advancedSearch.slideToggle(function(){
				that.buttonStatus();
			});
			
			//instead of return false - click bubbles up to body element and that handles the event
			$j.data(e.target, 'return', false);
		})
	}
	
	$j('div.lta-search').each(function(){
		new searchModule(this);
		
	})
}

FC.listHover = function() {
    var __$lists = $j(FC.vars.selectors.LIST_HOVER);

    if (__$lists.length == 0) {
        return;
    }

    __$lists.bind('mouseenter', function() {
        //console.log('listhover over');
        $j(this).addClass('hovering');
    });

    __$lists.bind('mouseleave', function() {
        $j(this).removeClass('hovering');
    });

    __$lists.bind('click keypress', function() {
        __a = $j('a', this)[0];
        window.open(__a.href, __a.target ? __a.target : '_self');
        return false;
    });

    __$lists.find('a').bind('click keypress', function() {
        window.open(this.href, this.target ? this.target : '_self');
        return false;
    });
}

function loadXMLString(txt) 
{
    if (window.DOMParser){
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(txt, "text/xml");
    }
    else{ // Internet Explorer
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = "false";
      xmlDoc.loadXML(txt); 
    }
    return xmlDoc;
}

//scores and draws XML feed
FC.liveFeed = function(x, tbl){
	//tbl = FC.vars.selectors.TABLE_CONTAINER_SM;
	var __doublesMatch = false;
	var __lta_fin = false;
	var __i = 0;
	var __tableID = "";
	var __lta_fin_all = 0;
	var __lta_fin = 0;
	var __matchID = []; //**************************************** new variable 
	
	function openFeed(first){
	
	$j.getJSON(liveScoresXmlFeedUrl + "?callback=?",
          function(data){
            if(data.results[0]){
                var xml = loadXMLString(data.results[0]);
                // for each court, run the functions
				// if it's the first run through, set up all the tables etc.  Otherwise, just update the scores.
				if(first==1){
					// **************************** RESET FOR SUBSEQUENT RUNS ************
					__i = 0; 
					// clear the DIV out
					$j(FC.vars.selectors.TABLE_CONTAINER).empty();
					// *******************************************************************
					
					//handleData($j(this));
					$j("court", xml).each(function() {
						// Test for Match ID here
						if($j(this).find('match_id').text() != ""){
							__tableID = getTableID(__i);
							createTable(); // create a table for the data to into
							init($j(this));//initialise the players
							updateScores($j(this));//get the scores	
							
							//****************** ADDED ********************
							// store the initial match ids - we'll test against this in iterations
							__matchID[__i] = $j(this).find('match_id').text();
							//**************************************	

							// test if the match is finished
							__lta_fin = $j(this).find('finished').text();
							// if finished is true for this match, then announce winner 
							if(__lta_fin == "1"){
								announceWinner($j(this));
								__lta_fin_all++;
							}
						__i++;	// ********************** MOVED inside the frunction
						}
					})
					// if all matches aren't finished, start the timer
					if (__lta_fin_all != __i){
						var times = 0;
						$j(document).everyTime(15000, function(i) {
						  openFeed(0);
						}, times);						
					}
				}else{
					__i = 0
					$j("court", xml).each(function() {
						//****************** FUNCTION REWRITTEN ********************						   
						var m1 = $j(this).find('match_id').text();
						// Test for Match ID here							
						if(m1 != ""){
							__tableID = getTableID(__i);
							var hasMatch = 0;
							var x = 0;
							// check and see if the match id exists - if it doesn't, it's a new item
							for(x=0;x <__matchID.length;x++){
								if (__matchID[x] == m1){
									hasMatch++;
								}
							}
							// if it's a new item, stop the time and reopen the feed to refresh all the tables								
							if (hasMatch == 0){
								$j(document).stopTime();
								openFeed(1);
							}
							//**************************************************
							// test if the match is finished
							__lta_fin = $j(this).find('finished').text();
							if(__lta_fin == "1"){
								announceWinner($j(this));
							}else{
								updateScores($j(this));
							}						
							__i++;	// ********************** MOVED inside the frunction						
						}

					})
				}
            }
          }
        );
        
        return false;
    }
	
	function getTableID(i){
		// figure out what's calling the function and set the table id accordingly - this is because different formats go into the different types of tables
		var tabID;
		if(tbl == FC.vars.selectors.TABLE_CONTAINER_SM){
			tabID = "#smlVer" + __i;
			smllVer = true;
		}else{
			tabID = "#regVer" + __i;
		}
		return tabID;
	}
	
	function createTable(){
			if(__tableID.indexOf("smlVer") != -1){
				$j(FC.vars.selectors.TABLE_CONTAINER_SM).append('<table border="0" cellspacing="0" cellpadding="0" class="main-scores resize" width="233" id="smlVer' + __i + '"><tr><td class="left head" colspan="7"><span class="lta-court"></span>&nbsp;-&nbsp;Time on court: <span class="lta-matchTime"></span></td></tr><tr><td class="bg-scores-tl left" width="131"><strong class="lta-name-1_1"></strong>&nbsp;<span class="lta-nat-1_1"></span>&nbsp;<strong class="lta-name-1_2"></strong>&nbsp;<span class="lta-nat-1_2"></span></td><td class="bg-scores-tm small-score lta-set-score lta-set-1_1 lta-inactive" width="12"></td><td class="bg-scores-tm small-score lta-set-score lta-set-2_1 lta-inactive" width="12"></td><td class="bg-scores-tm small-score lta-set-score lta-set-3_1 lta-inactive" width="12"></td><td class="bg-scores-tm small-score lta-set-score lta-set-4_1 lta-inactive" width="12"></td><td class="bg-scores-tm small-score lta-set-score lta-set-5_1 lta-inactive" width="12"></td><td class="bg-scores-tr-blue small-score bg-scores-grey lta-set-score lta_points_1" width="12"></td></tr><tr><td class="bg-scores-bl left"><strong class="lta-name-2_1"></strong>&nbsp;<span class="lta-nat-2_1"></span>&nbsp;<strong class="lta-name-2_2"></strong>&nbsp;<span class="lta-nat-2_2"></span></td><td class="bg-scores-bm small-score lta-set-score lta-set-1_2 lta-inactive"></td><td class="bg-scores-bm small-score lta-set-score lta-set-2_2 lta-inactive"></td><td class="bg-scores-bm small-score lta-set-score lta-set-3_2 lta-inactive"></td><td class="bg-scores-bm small-score lta-set-score lta-set-4_2 lta-inactive"></td><td class="bg-scores-bm small-score lta-set-score lta-set-5_2 lta-inactive"></td><td class="bg-scores-br small-score bg-scores-grey lta-set-score lta_points_2"></td></tr></table>');

			}else{
				$j(FC.vars.selectors.TABLE_CONTAINER).append('<table border="0" cellspacing="0" cellpadding="0" class="main-scores" id="regVer' + __i + '"><tr class="lta-heading"><td colspan="2" width="320" class="left roman results head"><span class="lta-court"></span>&nbsp;-&nbsp;Time on court: <span class="lta-matchTime"></span></td><td class="roman lta-set-1 lta-inactive" width="17">&nbsp;</td><td class="roman lta-set-2 lta-inactive" width="17">&nbsp;</td><td class="roman lta-set-3 lta-inactive" width="17">&nbsp;</td><td class="roman lta-set-4 lta-inactive" width="17">&nbsp;</td><td class="roman lta-set-5 lta-inactive" width="17">&nbsp;</td><td class="roman" width="32">Points</td><td width="81">&nbsp;</td></tr><tr><td class="bg-scores-tl lta-serving lta-serving-1_1" width="32"></td><td class="bg-scores-tm left" width="278"><strong class="lta-name-1_1"></strong>&nbsp;<span class="lta-nat-1_1"></span>&nbsp;<strong class="lta-name-1_2"></strong>&nbsp;<span class="lta-nat-1_2"></span></td><td class="bg-scores-tm lta-set-score lta-set-1_1 lta-inactive"></td><td class="bg-scores-tm lta-set-score lta-set-2_1 lta-inactive"></td><td class="bg-scores-tm lta-set-score lta-set-3_1 lta-inactive"></td><td class="bg-scores-tm lta-set-score lta-set-4_1 lta-inactive"></td><td class="bg-scores-tm lta-set-score lta-set-5_1 lta-inactive"></td><td class="bg-scores-tm bg-scores-grey lta-set-score lta_points_1"></td><td rowspan="2" class="bg-scores-br" valign="top"><div class="bg-scores-tr"><div class="lta-col">&nbsp;</div></div></td></tr><tr><td class="bg-scores-bl lta-serving lta-serving-2_1"></td><td class="bg-scores-bm left"><strong class="lta-name-2_1"></strong>&nbsp;<span class="lta-nat-2_1"></span>&nbsp;<strong class="lta-name-2_2"></strong>&nbsp;<span class="lta-nat-2_2"></span></td><td class="bg-scores-bm lta-set-score lta-set-1_2 lta-inactive"></td><td class="bg-scores-bm lta-set-score lta-set-2_2 lta-inactive"></td><td class="bg-scores-bm lta-set-score lta-set-3_2 lta-inactive"></td><td class="bg-scores-bm lta-set-score lta-set-4_2 lta-inactive"></td><td class="bg-scores-bm lta-set-score lta-set-5_2 lta-inactive"></td><td class="bg-scores-bm bg-scores-grey lta-set-score lta_points_2"></td></tr></table>');
			}
	}
	
	function init(r){
		//initial set up
		// COURT
		$j(__tableID + ' span.lta-court').append($j(r).find("court_name").text());
			
		// check to see if doubles match names are in
		var fn1_2 = $j(r).find('firstname1_2').text();
		var fn2_2 = $j(r).find('firstname2_2').text();
		// check if it has a child node, and if it does, then use it
		if ((fn1_2 != "") && (fn2_2 != "")){__doublesMatch = true;} else {__doublesMatch = false;} //********************************************
		
		// Check to see if the small version exists on the page
		// not sure if the small and big versions will ever be on the same page, but coded just in case they are
		if($j(FC.vars.selectors.TABLE_CONTAINER_SM).length){var smllVer = true}
		
		//Seeding
		var seed1 = $j(r).find("seed1").text();	
		var isSeed1 = (seed1 != "");
		
		// TEAM ONE PLAYER ONE
		if(smllVer){
			// display the shorter name if it's in the smaller side module
			var ln1_1sv = changeCase($j(r).find("name1_1").text()).substring(0, 3);
			if(isSeed1) ln1_1sv = ln1_1sv.toUpperCase();
			$j(__tableID + " strong.lta-name-1_1").append(ln1_1sv);

		}else{
		    var ln1_1fv0 = $j(r).find("firstname1_1").text().charAt(0);
		    var ln1_1fv1 = changeCase($j(r).find("name1_1").text());
			if(isSeed1) ln1_1fv1 = ln1_1fv1.toUpperCase();
			$j(__tableID + " strong.lta-name-1_1").append(ln1_1fv0 + " " + ln1_1fv1);
		}
	 
	 	//nationality
		var nat1_1 = $j(r).find("nat1_1").text(); 	
		$j(__tableID + " span.lta-nat-1_1").append(nat1_1);
	
	    //seeding
		if(isSeed1 && !__doublesMatch){
	        $j(__tableID + " span.lta-nat-1_1").append(" (" + seed1 + ")");
		}
	 
		// TEAM ONE PLAYER TWO 
		if(__doublesMatch){
		    if(smllVer){
			    // display the shorter name if it's in the smaller side module
			    var ln1_2sv = changeCase($j(r).find("name1_2").text()).substring(0, 3);
			    if(isSeed1) ln1_2sv = ln1_2sv.toUpperCase();
			    $j(__tableID + " strong.lta-name-1_2").append("/ " + ln1_2sv);
		    }else{
		        var ln1_2fv0 = $j(r).find("firstname1_2").text().charAt(0);
		        var ln1_2fv1 = changeCase($j(r).find("name1_2").text());
			    if(isSeed1) ln1_2fv1 = ln1_2fv1.toUpperCase();
			    $j(__tableID + " strong.lta-name-1_2").append("/ " + ln1_2fv0 + " " + ln1_2fv1);
		    }
			
			//nationality				
			var nat1_2 = $j(r).find("nat1_2").text(); // add seeding info here
			$j(__tableID + " span.lta-nat-1_2").append(nat1_2);
			
			if(isSeed1){
			    $j(__tableID + " span.lta-nat-1_2").append(" (" + seed1 + ")");
			}
		}
		
		//Seeding
		var seed2 = $j(r).find("seed2").text();	
		var isSeed2 = (seed2 != "");
		
		// TEAM TWO PLAYER ONE
		if(smllVer){
			// display the shorter name if it's in the smaller side module
			var ln2_1sv = changeCase($j(r).find("name2_1").text()).substring(0, 3);
			if(isSeed2) ln2_1sv = ln2_1sv.toUpperCase();
			$j(__tableID + " strong.lta-name-2_1").append(ln2_1sv);
		}else{
		    var ln2_1fv0 = $j(r).find("firstname2_1").text().charAt(0);
		    var ln2_1fv1 = changeCase($j(r).find("name2_1").text());
			if(isSeed2) ln2_1fv1 = ln2_1fv1.toUpperCase();
			$j(__tableID + " strong.lta-name-2_1").append(ln2_1fv0 + " " + ln2_1fv1);
		}
	 
	 	//nationality
		var nat2_1 = $j(r).find("nat2_1").text(); 	
		$j(__tableID + " span.lta-nat-2_1").append(nat2_1);
	
	    //seeding
		if(isSeed2 && !__doublesMatch){
	        $j(__tableID + " span.lta-nat-2_1").append(" (" + seed2 + ")");
		}

		//TEAM TWO PLAYER TWO
		if(__doublesMatch){
		    if(smllVer){
			    // display the shorter name if it's in the smaller side module
			    var ln2_2sv = changeCase($j(r).find("name2_2").text()).substring(0, 3);
			    if(isSeed2) ln2_2sv = ln2_2sv.toUpperCase();
			    $j(__tableID + " strong.lta-name-2_2").append("/ " + ln2_2sv);
		    }else{
		        var ln2_2fv0 = $j(r).find("firstname2_2").text().charAt(0);
		        var ln2_2fv1 = changeCase($j(r).find("name2_2").text());
			    if(isSeed2) ln2_2fv1 = ln2_2fv1.toUpperCase();
			    $j(__tableID + " strong.lta-name-2_2").append("/ " + ln2_2fv0 + " " + ln2_2fv1);
		    }
			
			//nationality				
			var nat2_2 = $j(r).find("nat2_2").text(); // add seeding info here
			$j(__tableID + " span.lta-nat-2_2").append(nat2_2);
			
			if(isSeed2){
			    $j(__tableID + " span.lta-nat-2_2").append(" (" + seed2 + ")");
			}
		}
	}
	
	function updateScores(r){
	    var smllVer = (tbl == FC.vars.selectors.TABLE_CONTAINER_SM);
	    
		// MATCH TIME
		//.lta-matchTime
		var matchTime = $j(r).find("time").text();
		$j(__tableID + ' span.lta-matchTime').text('').html(matchTime);
		
		// POINTS
		var pts1 = $j(r).find("pts1").text();
		$j(__tableID + ' td.lta_points_1').text('').html(pts1);	
		var pts2 = $j(r).find("pts2").text();
		$j(__tableID + ' td.lta_points_2').text('').html(pts2);
		
				
		// FIGURE WHICH SET IS CURRENT
		var s1_1 = $j(r).find('set1_1').text();
		var s1_2 = $j(r).find('set1_2').text();
		var s2_1 = $j(r).find('set2_1').text();
		var s2_2 = $j(r).find('set2_2').text();
		var s3_1 = $j(r).find('set3_1').text();
		var s3_2 = $j(r).find('set3_2').text();
		var s4_1 = $j(r).find('set4_1').text();
		var s4_2 = $j(r).find('set4_2').text();
		var s5_1 = $j(r).find('set5_1').text();
		var s5_2 = $j(r).find('set5_2').text();
		var currentSet = 0;
		
		if(s1_1 != "" || s1_2 != ""){
			// set 1 is current
			currentSet = 1
			//set column header
			if(!smllVer)$j(__tableID + ' td.lta-set-1').text('').html('1').attr('width','17').removeClass('lta-inactive');
			//set values
			s1_1!=""?$j(__tableID + ' td.lta-set-1_1').text('').html(s1_1).removeClass('lta-inactive'):'';
			s1_2!=""?$j(__tableID + ' td.lta-set-1_2').text('').html(s1_2).removeClass('lta-inactive'):'';
		}
		if(s2_1 != "" || s2_2 != ""){
			// set 2 is current
			currentSet = 2;
			if(!smllVer)$j(__tableID + ' td.lta-set-2').text('').html('2').attr('width','17').removeClass('lta-inactive');
			s2_1!=""?$j(__tableID + ' td.lta-set-2_1').text('').html(s2_1).removeClass('lta-inactive'):'';
			s2_2!=""?$j(__tableID + ' td.lta-set-2_2').text('').html(s2_2).removeClass('lta-inactive'):'';
		} 
		if(s3_1 != "" || s3_2 != ""){
			// set 3 is current
			currentSet = 3;
			if(!smllVer)$j(__tableID + ' td.lta-set-3').text('').html('3').attr('width','17').removeClass('lta-inactive');
			s3_1!=""?$j(__tableID + ' td.lta-set-3_1').text('').html(s3_1).removeClass('lta-inactive'):'';
			s3_2!=""?$j(__tableID + ' td.lta-set-3_2').text('').html(s3_2).removeClass('lta-inactive'):'';
		}
		if(s4_1 != "" || s4_2 != ""){
			// set 4 is current
			currentSet = 4;
			if(!smllVer)$j(__tableID + ' td.lta-set-4').text('').html('4').attr('width','17').removeClass('lta-inactive');
			s4_1!=""?$j(__tableID + ' td.lta-set-4_1').text('').html(s4_1).removeClass('lta-inactive'):'';
			s4_2!=""?$j(__tableID + ' td.lta-set-4_2').text('').html(s4_2).removeClass('lta-inactive'):'';
		} 		
		if(s5_1 != "" || s5_2 != ""){
			// set 5 is current
			currentSet = 5;
			if(!smllVer)$j(__tableID + ' td.lta-set-5').text('').html('5').attr('width','17').removeClass('lta-inactive');
			s5_1!=""?$j(__tableID + ' td.lta-set-5_1').text('').html(s5_1).removeClass('lta-inactive'):'';
			s5_2!=""?$j(__tableID + ' td.lta-set-5_2').text('').html(s5_2).removeClass('lta-inactive'):'';
		}
		
		//run through all .lta-set-score and remove class lta-currentSet
		$j(__tableID + ' td.lta-set-score').each(function(index) {
			$j(this).removeClass('lta-currentSet');
		});
		
		// mark up the current set
		switch (currentSet) {
			case 5:
				$j(__tableID + ' td.lta-set-5_1').addClass('lta-currentSet');
				$j(__tableID + ' td.lta-set-5_2').addClass('lta-currentSet');
				break;
			case 4:
				$j(__tableID + ' td.lta-set-4_1').addClass('lta-currentSet');
				$j(__tableID + ' td.lta-set-4_2').addClass('lta-currentSet');
				break;
			case 3:
				$j(__tableID + ' td.lta-set-3_1').addClass('lta-currentSet');
				$j(__tableID + ' td.lta-set-3_2').addClass('lta-currentSet');
				break;
			case 2:
				$j(__tableID + ' td.lta-set-2_1').addClass('lta-currentSet');
				$j(__tableID + ' td.lta-set-2_2').addClass('lta-currentSet');
				break;
			case 1:
				$j(__tableID + ' td.lta-set-1_1').addClass('lta-currentSet');
				$j(__tableID + ' td.lta-set-1_2').addClass('lta-currentSet');
				break;
		}		
		
		// server
		//lta-serving-1_1
		//<div class="serving">Serving</div>
		
		//run through all and clear the text
		$j(__tableID + ' td.lta-serving').each(function(index) {
			$j(this).html('');
		});
		
		//var lta-server-num = 1;
		var __currServer = $j(r).find('serv').text();
		
		switch(__currServer){
			case '1':
				$j(__tableID + ' td.lta-serving-1_1').html('<div class="serving">Serving</div>');
				break;
			case '2':
				$j(__tableID + ' td.lta-serving-2_1').html('<div class="serving">Serving</div>');
				break;
			case '3': 
				$j(__tableID + ' td.lta-serving-1_1').html('<div class="serving">Serving</div>');
				break;
			case '4':
				$j(__tableID + ' td.lta-serving-2_1').html('<div class="serving">Serving</div>');
				break;
		}
	}
	function announceWinner(r){
			// clear the server
			$j(__tableID + ' td.lta-serving').each(function(index) {
				$j(this).html('');
			});	
			
			// show the winner
			var __winner = $j(r).find('winner').text();
			switch(__winner){
				case '1':
					$j(__tableID + ' td.lta-serving-1_1').html('<div class="win">WIN</div>');
					break;
				case '2':
					$j(__tableID + ' td.lta-serving-2_1').html('<div class="win">WIN</div>');
					break;	
			}
				//stop the timer
			//$j(document).stopTime();
	}
	
	function handleData(r){
		

	}
	
	openFeed(1);
}


function changeCase(addrline) {
	var tmpStr = addrline.toLowerCase();
	
	tmpStr = tmpStr.replace (/(\d+)([a-z]{3,})/gi, "$1 $2"); // add space after numbers when 3+ alphachars follow
	tmpStr = tmpStr.replace (/\,/g, " "); // delete commas - replace by space (essential!)
	tmpStr = tmpStr.replace (/(\d+)([.{2,}$])/gi, " $1$2"); // add 4 spaces before numbers not at end of string
	tmpStr = tmpStr.replace (/(\S*)\"(\D+)\"(\S*)/g, '$1 "$2" $3'); // put spaces around "string" (force uppercase)
	tmpStr = tmpStr.replace (/o\'/gi, "O' "); // change o' to O'+space (O' Reilly) (force uppercase)
	tmpStr = tmpStr.replace (/(\s|\.)(mc)([a-z])/g, "$1mc $3"); // add space after Mc (force uppercase)
	tmpStr = tmpStr.replace (/(\D)\./g, "$1. "); // add space after literal . (B. M. Smith > uppercase)
	tmpStr = tmpStr.replace (/\-([a-z])/g, " - $1"); // add spaces around hyphens (force uppercase)
	tmpStr = tmpStr.replace (/(^\s+)/, ""); // remove spaces at start of string
	tmpStr = tmpStr.replace (/\s{4,}/g, " "); // remove excessive spaces > 4
	
	if ((/fpo\b/.test(tmpStr)) || (/fpo\d/.test(tmpStr))) {
		tmpStr = tmpStr.toUpperCase();
		tmpStr = tmpStr.replace (/([A-Z])(\s{2,})/g, "$1 "); // remove spaces >1 between A-Z and A-Z/0-9 (not converse)
	}
			
	var SplitStuff = tmpStr.split(" ");
	var ArrLen = SplitStuff.length;
	
	for (var k=0; k<ArrLen; k++) {
		var word = SplitStuff[k];
		if (/\d/.test(word)) {word = word.toUpperCase()}
		var wordLen = word.length;
		var posn = word.search(/[a-zA-Z]/);
		var firstChars = word.substring(0, posn+1).toUpperCase();
		var postString = word.substring(posn+1,wordLen);
		word = firstChars + postString;
		word = word.replace ( /C\/O\b/g, "C\/o" );
		word = word.replace ( /Po\b/g, "PO" );
		word = word.replace (/\'a/, "'A"); // De'Ath and D'Arcy!
		
		SplitStuff[k] = word;
	}
	
	var newline = SplitStuff.join(" ");
	newline = newline.replace (/\.\s/g, "."); // re-format names B. M. Smith > B.M.Smith
	newline = newline.replace (/Mc\s/,"Mc"); // reformat McXxxx
	newline = newline.replace (" - ","-"); // reformat McXxxx
	addrline = newline;
	return addrline;
}

FC.LiveTicker = function() {

    try {
        var ticker_holder = $j(FC.vars.selectors.LIVETICKER).get(0);
        var ticker_pos = ticker_holder.parentNode.offsetWidth;

        var ticker_data = $j(ticker_holder).html();
        $j(ticker_holder).html('<marquee scrollamount="1" scrolldelay="40"  behavior="scroll" direction="left" width="400">' + ticker_data + '</marquee>');

        $j(ticker_holder).hover
        (
            function() { $j('marquee', this).get(0).stop(); },
            function() { $j('marquee', this).get(0).start(); }
        );
                 
        //finds the width of each item and creates and overall width for the UL
        var __li = $j(FC.vars.selectors.LIVETICKER).find("li");
        var __width = 0;
        for(i=0;i<__li.length;i++){
                        __width = __width+$j(__li[i]).width();
                        __width = __width+30;
        }
        var __ul = $j(FC.vars.selectors.LIVETICKER).find("ul");
        __ul.css({"width":__width+"px"});

    }
    catch (o) { }
}

FC.matchTabs = function() {
                
    var __matchContent = $j("div.lta-match-content");
    var __tabs = $j(FC.vars.selectors.MATCH_TABS).find("div.lta-toggle-alt ul li");
    var __containers = $j(FC.vars.selectors.MATCH_TABS).find("div.order-container");
    
    __matchContent.hide();

    for(var i = 0; i < __containers.length; i++)
        $j(__containers[i]).addClass("lta-match-content-" + (i + 1));
       
    $j(".lta-match-content-1").show();

    __tabs.bind("click",function(e){
                                                                                         
        var __index =__tabs.index(this);

        __tabs.find("a").removeClass("lta-selected");
        $j(__tabs[__index]).find("a").addClass("lta-selected");
        __index = __index+1;
        __matchContent.hide();
        $j(".lta-match-content-"+__index).show();
        
        //instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);                                                                                                               
    });               
}


FC.rowHighlight = function() {
    var __$rows = $j('.ranking tr'),
        __a;

    if (__$rows.length == 0) {
        return;
    }

    __$rows.bind('mouseenter', function() {
        __a = $j('a', this)[0];
        __a && $j(this).addClass('current');
    });

    __$rows.bind('mouseleave', function() {
        __a = $j('a', this)[0];
        __a && $j(this).removeClass('current');
    });

    __$rows.bind('click keypress', function() {
        __a = $j('a', this)[0];
        __a && window.open(__a.href, __a.target ? __a.target : '_self');
        return false;
    });

    __$rows.find('a').bind('click keypress', function() {
        window.open(this.href, this.target ? this.target : '_self');
        return false;
    });
}

FC.flyoutNavigation = function($els) {

    $els.each(function() {
        var _TIME = FC.vars.timeouts,
            _$this = $j(this),
            _$li = _$this.parent(),
            _$a = _$this.prev(),
            _$links = _$this.find('a');

        _$li.addClass('has-flyout');

        _$a.bind('focus', function() {
            _$a.addClass('hovered');
            $els.hide();
            _$this.show();
        });
        _$a.bind('blur', function() {
            _$a.removeClass('hovered');
        });

        _$links.bind('focus', function() {
            _$a.addClass('hovered');
        });

        _$links.bind('blur', function() {
            _$a.removeClass('hovered');
        });

        _$li.bind('mouseenter', function() {
            _showFlyout = function() { _$this.show(); }
            _$a.addClass('hovered');
            _TIME.SHOW_FLYOUT_NAV = setTimeout("_showFlyout()", 400);
        });
        _$li.bind('mouseleave', function() {
            _$a.removeClass('hovered');
            clearTimeout(_TIME.SHOW_FLYOUT_NAV);
            _$this.hide();
        });
    });

    $j('.lta-anon a, .lta-member a, li.lta-nav a').bind('focus', function() {
        $els.hide();
    })

    function Flyout(flyout) {
        this.root = flyout.parentNode;
        this.rootLink = $j(this.root).find('>a');
        this.flyout = $j(flyout);
    }


    $j('.lta-navigation-flyout').each(function() {
        new Flyout(this);
    });
};


FC.placeholderText = function() {
    function PlaceholderText(root) {
        this.defaultText = root.value;
        this.root = root;
        this.$root = $j(root);

        this.$root.addClass('contains-default-text');

        var placeholderText = this;
        this.root.onfocus = function() {
            placeholderText.remove();
        }
        this.root.onblur = function() {
            placeholderText.replace();
        }
    }
    PlaceholderText.prototype.remove = function() {
        if (this.root.value == this.defaultText) {
            this.root.value = '';
            this.$root.removeClass('contains-default-text');
        }
    }

    PlaceholderText.prototype.replace = function() {
        if (this.root.value == '') {
            this.root.value = this.defaultText;
            this.$root.addClass('contains-default-text');
        }
    }

    $j(FC.vars.selectors.PLACEHOLDER_TEXT).each(function() {
        new PlaceholderText(this);
    });
}

FC.placeholderTitleText = function() {
    var $placeholder = $j('.lta-placeholder-text');

    $placeholder.each(function() {
        $j(this).val($j(this).attr('title'));
    });

    $placeholder.focus(function() {
        if ($j(this).val() == $j(this).attr('title')) {
            $j(this).val('');
        }
    }).blur(function() {
        if ($j(this).val() == "") {
            $j(this).val($j(this).attr('title'));
        }
    });
}


//RANKING LISTING
FC.rankingListing = function(listing) {

    var __listing = $j(listing);
    var __groups = $j(FC.vars.selectors.RANKING_GROUP);

    __groups.hide();
    if (__groups.length) { __groups[0].style.display = "block"};

    //Create drop down and insert before first group 
    if(__groups.length > 1)
    {
        var __switcher = "<select name='player-switcher' id='player-switcher'>"
        for (i = 0; i < __groups.length; i++) {
            var __h = __groups[i].getElementsByTagName("h3");
            //tidy up text into same as ID
            var __value = $j(__h[0]).parent().attr("id")
            __switcher += "<option value=" + __value + ">" + __h[0].innerHTML + "</option>";
        }
        __switcher += "</select>";
        if (__groups.length) { $j(__groups[0]).before(__switcher); }

        var __select = $j("#player-switcher");
        __select.bind("change", function() {
            __groups.hide();
            $j("#" + $j(this).val()).show();
    });
    }
}

//RANKING LISTING LEGACY
FC.rankingListingLegacy = function(listing) {

    var __listing = $j(listing);
    var __groups = $j(FC.vars.selectors.RANKING_GROUP);

    __groups.hide();
    __groups[0].style.display = "block";

    var __select = $j(".player-switcher");
    __select.bind("change", function() {
        __groups.hide();
        $j("#" + $j(this).val()).show();
    });
}


// 12.0 HERO, 12.1 HERO WITH PANEL
FC.heroSlideshow = function() {
var $heros = $j('.lta-hero');
    
    function HeroSlideshow(root) {
        var that = this;

        this.root = root;
        this.$root = $j(root);
        this.heroHeight = this.$root.innerHeight();

        this.items = [];
        $heros.find('.lta-hero-item').each(function(index) {
            var item = new HeroSlideshowItem(that, this, index)
            that.items.push(item);
            index > 0 && item.hide();
        });

        this.currentItem = this.items[0];
        this.currentItem.show();

        this.$corners = this.$root.find('.lta-hero-corners');
        this.setMouseoverAnimation();

        if (this.items.length > 1) {
            this.SLIDEINTERVAL = 5000;

            this.PLAY_TEXT = 'Play'
            this.PAUSE_TEXT = 'Pause'
            this.NEXT_TEXT = 'Next'
            this.PREVIOUS_TEXT = 'Previous'

            this.playing = false;
            this.isGoingToPlay = false;

            this.setCornersLink();
            this.addCountControls();
            this.play();
        }
    }

    HeroSlideshow.prototype.addCountControls = function() {
        // Add controls container
        this.$countControls = $j('<div class="lta-hero-slideshow-count-controls"><h3>Slideshow Controls</h3><ul></ul></div>');
        this.$controlsList = this.$countControls.find('ul');

        this.$countCurrent = this.$countControls.find('.lta-current');

        this.$root.append(this.$countControls);

        // Add controls
        this.previousControl = new HeroSlideshowNextPreviousControl(this, 'previous');
        this.playPauseControl = new HeroSlideshowPlayPauseControl(this);
        this.nextControl = new HeroSlideshowNextPreviousControl(this, 'next');

        this.$controlsList.append(this.previousControl.$html);
        this.$controlsList.append(this.playPauseControl.$html);
        this.$controlsList.append(this.nextControl.$html);
    }

    HeroSlideshow.prototype.setCornersLink = function() {
        var $cornersLink = this.$corners.find('a');

        if ($cornersLink.length == 0) {
            this.$corners.append('<a href="#"></a>');
            var $cornersLink = this.$corners.find('a');
        }

        $cornersLink.attr('href', this.currentItem.url);
        $cornersLink.attr('target', this.currentItem.target);
        $cornersLink.text(this.currentItem.linkText);
    }

    HeroSlideshow.prototype.setMouseoverAnimation = function() {
        for (var i in this.items) {
            if (!this.items[i].$panel.length || this.items[i].$panel.length > 0) {
                return;
            }
        }

        var that = this;
        this.$corners.mouseover(function() {
            var item = that.currentItem;
            if (item.$paragraph.text() != '') {
                item.$text.animate({ 'top': item.textOpenPosition + 'px' });
            }
        });
        this.$corners.mouseout(function() {
            var item = that.currentItem;
            item.$text.animate({ 'top': item.textClosedPosition + 'px' });
        });
    }

    HeroSlideshow.prototype.next = function() {
        if (this.currentItem.itemIndex == this.items.length - 1) {
            this.switchTo(this.items[0]);
        }
        else {
            this.switchTo(this.items[this.currentItem.itemIndex + 1]);
        }
    }

    HeroSlideshow.prototype.previous = function() {
        if (this.currentItem.itemIndex == 0) {
            this.switchTo(this.items[this.items.length - 1]);
        }
        else {
            this.switchTo(this.items[this.currentItem.itemIndex - 1]);
        }
    }

    HeroSlideshow.prototype.switchTo = function(item) {
        var that = this;
        var item = item;

        // Make the current item invisible
        this.currentItem.hide();

        // Update the current item
        that.currentItem = item;
        that.setCornersLink();

        // Make the current item visible
        that.currentItem.show();

        // Update pagination
        that.$countCurrent.text(that.currentItem.itemIndex + 1);
    }

    HeroSlideshow.prototype.play = function() {
        var that = this;
        var next = function() { that.next(); }

        this.playing = window.setInterval(next, this.SLIDEINTERVAL);
    }

    HeroSlideshow.prototype.pause = function() {
        window.clearInterval(this.playing);
        this.playing = false;
    }


    function HeroSlideshowItem(slideshow, root, index) {
        this.slideshow = slideshow;
        this.$root = $j(root);
        this.$text = this.$root.find('.lta-hero-item-text');
        this.$paragraph = this.$root.find('.lta-hero-item-text p');
        this.itemIndex = index;

        this.$panel = this.$root.find('.lta-hero-item-panel');
        if (this.$panel.length > 0) {
            this.$button = this.$panel.find('a.lta-btn');

            this.linkText = this.$button.find('span').text();
            this.url = this.$button.attr('href');
            this.target = this.$button.attr('target');
        }
        else {
            this.linkText = this.$root.find('h3').text();
            this.url = this.$root.find('h3 a').attr('href');
            this.target = this.$root.find('h3 a').attr('target');
        }

        this.configureMouseoverAnimation();
    }

    HeroSlideshowItem.prototype.hide = function(callback) {
        var that = this;
        this.$root.fadeOut(function() {
            that.$root.css({ 'z-index': '0' });
            that.$root.find('img').css({ 'visibility': 'hidden' });
            if (callback) {
                callback();
            }
        });
    }

    HeroSlideshowItem.prototype.show = function() {
        this.$root.css({ 'z-index': '5' });
        this.$root.find('img').css({ 'visibility': 'visible' });
        this.$root.fadeIn();
    }

    HeroSlideshowItem.prototype.configureMouseoverAnimation = function() {
        // Figure out the full height of <div class="hero-item-text">, and subtract that from the height of the hero to get the �??open�? vertical position
        var heroHeight = this.slideshow.heroHeight;
        var textHeight = this.$text.innerHeight();
        this.textOpenPosition = heroHeight - textHeight;

        // Figure out the height of the paragraph in <div class="hero-item-text">, subtract that from its full height, subtract the result from the height of the hero, then add 4 to get the �??closed�? vertical position. (Adding 4 is a bit of an arbitrary tweak to get the paragraph to fully disappear.)
        var paragraphHeight = this.$text.find('p').innerHeight();
        this.textClosedPosition = heroHeight - (textHeight - paragraphHeight) + 4;

        // Set the vertical position of <div class="hero-item-text"> to the �??closed�? vertical position
        this.$text.css('top', this.textClosedPosition + 'px');
    }


    function HeroSlideshowPlayPauseControl(slideshow) {
        this.slideshow = slideshow;
        this.$link = $j('<a href="#pause" class="pause">' + this.slideshow.PAUSE_TEXT + '</a>');
        this.$html = $j('<li></li>').append(this.$link);

        var that = this;
        this.$link.bind('click', function(e) {
            that.playPause();
            //instead of return false - click bubbles up to body element and that handles the event
            $j.data(e.target, 'return', false);
        });
    }

    HeroSlideshowPlayPauseControl.prototype.playPause = function() {
        if (this.$link.hasClass('pause')) {
            this.slideshow.pause();
            this.$link.removeClass('pause');
            this.$link.addClass('play');
            this.$link.attr('href', '#play');
            this.$link.text(this.slideshow.PLAY_TEXT);
        }
        else {
            this.slideshow.play();
            this.$link.removeClass('play');
            this.$link.addClass('pause');
            this.$link.attr('href', '#pause');
            this.$link.text(this.slideshow.PAUSE_TEXT);
        }
    }


    function HeroSlideshowNextPreviousControl(slideshow, nextPrevious) {
        this.slideshow = slideshow;
        this.nextPrevious = nextPrevious;

        this.$link = $j('<a href="#' + this.nextPrevious + '" class="' + this.nextPrevious + '">' + this.slideshow[this.nextPrevious + '_TEXT'] + '</a>');
        this.$html = $j('<li></li>').append(this.$link);

        var that = this;
        this.$link.bind('click', function(e) {
            var wasPlaying = false;

            if (that.slideshow.playing) {
                var wasPlaying = true;
                that.slideshow.pause();
            }

            that.slideshow[that.nextPrevious]();

            if (wasPlaying) {
                that.slideshow.play();
            }
            //instead of return false - click bubbles up to body element and that handles the event
            $j.data(e.target, 'return', false);
        });
    }

    $heros.each(function() {
        new HeroSlideshow(this);
        // $heros.find('.lta-hero-item').fadeOut('slow');
    });
}

// 18.0 SEARCH
FC.siteSearch = function() {
    function SiteSearch() {
        this.PLACEHOLDER_TEXTS = {
            'Competition': 'Competition name or code',
            'Player': 'Enter a Players name',
            'Court': 'Enter a Postcode',
            'Coach': 'Enter a Postcode',
            'Website': 'What are you looking for?'
        }

        this.ADVANCED_SEARCH_URLS = {};

        this.$html = $j(FC.vars.selectors.SITE_SEARCH);

        this.$select = this.$html.find('select.lta-search-extent');
        this.select = this.$select.get(0);
        this.$options = this.$select.find('option');
        this.$text = this.$html.find('.lta-search-text');
        this.$advancedSearchLinks = this.$html.find('.lta-advanced-search-links');
        this.$moreOptionsInner = this.$html.find('.lta-more-options-inner');
        this.$moreOptionsLink = null;

        this.replaceSelect();
        this.setAdvancedSearchUrls();
        this.updateMoreOptionsLink();
        this.updatePlaceholderText();

        var that = this;

        $j('body').bind('click', function(e) {
            var __isReturn = $j.data(e.target, 'return'),
				__ul = that.$searchUL[0],
				rOpen = /\blta-open\b/;

            __ul.className = __ul.className.replace(rOpen, "")
            that.$selectedSearchText.css('display', 'inline');

            if (__isReturn === false) {
                return false;
            }
        })

    }

    SiteSearch.prototype.replaceSelect = function() {
        that = this;

        this.$select.after('<ul id="search-extent" class="lta-search-extent"></ul>');

        this.$searchUL = this.$html.find('ul.lta-search-extent');


        this.$searchUL.before('<a href="#" class="lta-selected-search"><span class="lta-selected-search-span"><span>' + this.$options.get(0).text + '</span></span><span class="lta-accessibility"> click this to change the search context</span></a>');

        that.$selectedSearch = this.$html.find('a.lta-selected-search span.lta-selected-search-span');
        that.$selectedSearchText = this.$html.find('a.lta-selected-search span.lta-selected-search-span span');
        that.$selectedSearchHeight = that.$selectedSearch.height();

        var onClickHandler = function(e) {
            var __ul = that.$searchUL[0],
				rOpen = /\blta-open\b/;

            if (!rOpen.test(__ul.className)) __ul.className += " lta-open";
            else __ul.className = __ul.className.replace(rOpen, "");

            //that.$selectedSearch.text('');
            that.$selectedSearchText.css('display', 'none');
            that.$selectedSearch.height(that.$selectedSearchHeight);
            return false;

        };

        that.$selectedSearch.parent().bind('click', onClickHandler);

        for (i = 0, j = this.$options.length, arr = []; i < j; i++) {
            arr[i] = '<li><a href="#">' + this.$options.get(i).text + '</a></li>';
        }

        this.$searchUL.append(arr.join(""));

        //set the width of the selected search item to the width of the UL minus 20px (the UL has 20px padding);
        that.$selectedSearch.width(this.$searchUL.width())

        $allA = this.$searchUL.find('a');

        $allA.bind('click', function(e) {
            var __ul = that.$searchUL[0],
				rOpen = /\blta-open\b/;

            that.$select[0].selectedIndex = $allA.index(this);
            that.$selectedSearchText[0].innerHTML = $j(this).text();
            that.$selectedSearchText.css('display', 'inline');
            __ul.className = __ul.className.replace(rOpen, "")

            that.updatePlaceholderText();
            that.updateMoreOptionsLink();

            //instead of return false - click bubbles up to body element and that handles the event
            $j.data(e.target, 'return', false);
        });


    }

    SiteSearch.prototype.setAdvancedSearchUrls = function() {
        var that = this;

        this.$advancedSearchLinks.find('a').each(function(i) {
            var optionText = that.$options.eq(i).text();
            that.ADVANCED_SEARCH_URLS[optionText] = this.href;
        });
    }

    SiteSearch.prototype.updateMoreOptionsLink = function() {

        $j('.lta-more-options-inner a').remove();

        if (this.select.value == 'Competition') {
            this.$moreOptionsLink = $j('<a href="' + this.ADVANCED_SEARCH_URLS[this.select.value] + '" title="Advanced ' + this.select.value + ' Search">More options</a>');
            this.$moreOptionsInner.append(this.$moreOptionsLink);
        }


    }

    SiteSearch.prototype.updatePlaceholderText = function() {
        this.$text.attr({ 'value': this.PLACEHOLDER_TEXTS[$j(this.select.options[this.select.selectedIndex]).text()] });

        FC.placeholderText();
    }


    new SiteSearch();
}

FC.mapToggle = function(__par){
	var __onClickKeypressHandler = function(e){
		var $$this = $j(this);
		switch (e.keyCode) {
			case 13: // enter key
			case 32: // space bar
			case undefined: //mouse click
			case 0: //mouse click in IE
				if ($$this.hasClass('lta-showhide-hide')) {
					$j('a', $$this).html('Show map');
					this.className = this.className.replace(/lta-showhide-hide/g, "lta-showhide-show");
					__par.slideUp();
				} else {
					$j('a', $$this).html('Hide map');
					this.className = this.className.replace(/lta-showhide-show/g, "lta-showhide-hide");
					__par.slideDown();
				}
				//instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
			default:
				return;
		}
	}
	
	if($j(__par).hasClass("lta-pre")){
		$j(__par).prev().append('<div class="lta-padding floatright"><span class="lta-showhide-button lta-showhide-hide"><a href="#">Hide map</a></span></div>');
	} else {
		$j(__par).after('<div class="lta-padding-sides floatright"><span class="lta-showhide-button lta-showhide-hide"><a href="#">Hide map</a></span></div>');
	} //this if should be removed once we decide if the controls go before or after the map
	
	$j('.lta-showhide-button').bind('click keydown', __onClickKeypressHandler);
}

FC.boxHover = function(__el){
	__$el = $j(__el);
	
	__$el.bind('mouseover', function() {
		$j(this).removeClass('lta-box35').addClass('lta-box36');
	});
	
	__$el.bind('mouseout', function() {
		$j(this).removeClass('lta-box36').addClass('lta-box35');
	});

}

FC.goalExpander = function(__el){
	// This is a modification of the lta-expander component
	// This version looks for an anchor with class "lta-btn-add" and binds a click event to it.

	__$buttons= $j(__el);
	
	__$buttons.bind('click', function(e) {
		var __$this= $j(this);
		var __$buttonContent= __$this.find('span');
		
		var __$expandContent= $j(this).parent().next(), __$existingGoalIntro = __$expandContent.next('div.lta-goal-intro');
		
		__$expandContent.toggleClass('lta-expander-open');
		
		
		if(__$expandContent.hasClass('lta-expander-open')) {
			__$existingGoalIntro.css('position', 'static');
			__$expandContent.slideDown('fast', function() {
				__$existingGoalIntro.css('position', 'relative');
			});
			
			if(!FC.hasIE) {
				__$this.animate({'opacity': 0}, 'fast', function() {
					__$this.addClass('lta-btn-hide');
					__$buttonContent.text('Hide goals');
					__$this.animate({'opacity': 1}, 'fast');
				});
			}
			else {
				__$this.hide();
				__$this.addClass('lta-btn-hide');
				__$buttonContent.text('Hide goals');
				__$this.show();
			}
			
		}
		else {
			__$existingGoalIntro.css('position', 'static');
			__$expandContent.slideUp('fast', function() {
				__$existingGoalIntro.css('position', 'relative');
			});
			
			if(!FC.hasIE) {
				__$this.fadeOut('fast', function() {
					__$this.removeClass('lta-btn-hide');
					__$buttonContent.text('Add new goal');
					__$this.fadeIn('slow');
				});
			}
			else {
				__$this.hide();
				__$this.removeClass('lta-btn-hide');
				__$buttonContent.text('Add new goal');
				__$this.show();
			}
		}
		
		//instead of return false - click bubbles up to body element and that handles the event
		$j.data(e.target, 'return', false);
		
		//return false;
	});
};

FC.expander = function($expander){
	//each expander item is made up of 2 elements
	//			-the lta-expander-header which is clicked to expand/contract content
	//			-the lta-expander-content 
	
	$headings= $expander.find('div.lta-expander-header h3');
	$headings.wrapInner('<a href="#"></a>');
	$headings.find('a').bind('click', function() {
		var $header= $j(this).parents('div.lta-expander-header');
		
		$header.toggleClass('lta-expander-open');
		
		if($header.hasClass('lta-expander-open')) { 
			$header.next('.lta-expander-content').slideDown('fast');
		}
		else {
			$header.next('.lta-expander-content').slideUp('fast');
		}
		
		return false;
	});
};

FC.vertNavScroll = function(){
	var __SEL = FC.vars.selectors;
	var __axis = {axis:'x'};

	$j(__SEL.VERTICAL_NAV_SCROLL).each(function(){

		var __$this = $j(this);	
		var __scrollAmount=1, __$contentBoxes = $j(".lta-nav-item", __$this);
		
		var __$container = $j("div.lta-nav-container", __$this);
		
		//add controls
		__$container.before('<div class="lta-head lta-clear"><div class="lta-prev"><a href="#">Previous goal sheets</a></div><h2></h2><div class="lta-next"><a href="#">Next goal sheets</a></div></div>');
		
		var __$right = $j("div.lta-next", __$this), __$left = $j("div.lta-prev", __$this), __$heading= $j('h2', 'div.lta-head');
		var __$achievedPeriods= $j('li.lta-achieved a', __$this);
		
		//var __max = __$contentBoxes.length*__scrollAmount;
		var __max = __$contentBoxes.length-1;
		if(typeof(navScrollPos) == "undefined") navScrollPos = 0;
		
		//Find the first h2, get its text, and set the heading to that.  Make sure the scroller is at the start
		__$heading.text(__$container.find('h2:eq('+navScrollPos+')').text());
		__$container.scrollTo('ul:eq('+navScrollPos+')', 200, __axis);
		
		if (navScrollPos == 0) {
			__$left.addClass('lta-prev-disabled');
			__$left.empty();
			__$left.append('<span>Previous goal sheets</span>');
		} else if (navScrollPos == __max){
			__$right.addClass('lta-next-disabled');
			__$right.empty();
			__$right.append('<span>Next goal sheets</span>');
		}
	
		//Left scroller button
		__$left.bind("click", function(e){
			if(__$left.hasClass('lta-prev-disabled')) {
				//instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
			}
			else {
				if(navScrollPos>0){
					navScrollPos = navScrollPos-__scrollAmount;
					__$achievedPeriods.css('position','static');
					__$achievedPeriods.find('span').css('display','none');
					
					if(!FC.hasIE) {
						__$heading.fadeOut('fast', function() {
							__$container.scrollTo('.lta-nav-item:eq('+navScrollPos+')', 500, {
							axis:'x',
							onAfter:function(){ 
								__$heading.text($j('.lta-nav-item:eq('+navScrollPos+')').find('h2').text());
								__$heading.fadeIn();
								$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved a').css('position','relative');
								$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved span').css('display','block');
								//__$achievedPeriods.css('position','relative');
								} 
							});
						});
					}
					else {
						__$heading.hide(1, function() {
							__$container.scrollTo('.lta-nav-item:eq('+navScrollPos+')', 500, {
							axis:'x',
							onAfter:function(){ 
								__$heading.text($j('.lta-nav-item:eq('+navScrollPos+')').find('h2').text());
								__$heading.show();
								$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved a').css('position','relative');
								$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved span').css('display','block');
								//__$achievedPeriods.css('position','relative');
								} 
							});
						});
					}
					
					//__$right.show();
					__$right.removeClass('lta-next-disabled');
					__$right.empty();
					__$right.append('<a href="#">Next goal sheets</a>');
						
					if(navScrollPos == 0){
						//__$left.hide();
						__$left.addClass('lta-prev-disabled');
						__$left.empty();
						__$left.append('<span>Previous goal sheets</span>');
					}
				}
				//instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
			}
		});
	
		//Right scroller button
		__$right.bind("click", function(e){
			if(__$right.hasClass('lta-next-disabled')) {
				//instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
			}
			
			else {
				if(navScrollPos<__max){
					navScrollPos = navScrollPos+__scrollAmount;
					
					__$achievedPeriods.css('position','static');
					__$achievedPeriods.find('span').css('display','none');
					
					if(!FC.hasIE) {
						__$heading.fadeOut('fast', function() {
							__$container.scrollTo('.lta-nav-item:eq('+navScrollPos+')', 500, {
								axis:'x',
								onAfter:function(){ 
									__$heading.text($j('.lta-nav-item:eq('+navScrollPos+')').find('h2').text());
									__$heading.fadeIn();
									//__$achievedPeriods.css('position','relative');
									$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved a').css('position','relative');
									$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved span').css('display','block');
								} 
							});
							
						});
					}
					else {
						__$heading.hide(1, function() {
							__$container.scrollTo('.lta-nav-item:eq('+navScrollPos+')', 500, {
								axis:'x',
								onAfter:function(){ 
									__$heading.text($j('.lta-nav-item:eq('+navScrollPos+')').find('h2').text());
									__$heading.show();
									//__$achievedPeriods.css('position','relative');
									$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved a').css('position','relative');
									$j('div.lta-nav-item:eq('+navScrollPos+')').find('li.lta-achieved span').css('display','block');
								} 
							});
							
						});
					}
					//__$left.show();
					__$left.removeClass('lta-prev-disabled');
					__$left.empty();
					__$left.append('<a href="#">Previous page</a>');
					
					if((__max - navScrollPos) <= __scrollAmount){
						__$right.addClass('lta-next-disabled');
						__$right.empty();
						__$right.append('<span>Next goal sheets</span>');
					}
				}
				//instead of return false - click bubbles up to body element and that handles the event
				$j.data(e.target, 'return', false);
			}
		});
	});// end 'each' statement
}

FC.goalTooltip= function(__el) {
	var __$el= $j(__el);
	
	__$el.each(function() {
		var __$that= $j(this);
		var __$anchorText= __$that.text();
		
		__$that.empty();
		__$that.append('<span class="lta-tooltip-container"><span class="lta-tooltip"><span class="lta-tooltip-bottom"><span class="lta-tooltip-padding"><p>'+ __$anchorText +'</p></span></span></span></span>');
		
		__$that.bind('mouseenter', function() {
			$j('span.lta-tooltip').hide();
			if(FC.hasIE) {
				$j(this).find('span.lta-tooltip').show();
			}
			else {
				$j(this).find('span.lta-tooltip').fadeIn('fast').css('display','block');
			}
		
		});
		__$that.bind('mouseleave', function() {
			if(FC.hasIE) {
				$j(this).find('span.lta-tooltip').fadeOut('fast');
			}
			else {
				$j(this).find('span.lta-tooltip').hide();
			}
		
		});
		
	});
}


FC.goalDragDrop = function(__$els) {
	var __$innerBox = __$els.find('li div.lta-box-inner'),
		i= __$els.length,
		__result = [];
	
	__$els.prev().append('<div class="lta-btn-container lta-clear"><a href="#" class="lta-btn lta-btn-alt"><span class="lta-btn">Save this order</span></a></div>')
	
	
	
	$j('.lta-btn-container a').bind('click', function(e){
		var __$this = $j(this),
		    __$goals = __$this.parents('li').find('.lta-sortable-goal'),
		    __goalArray = [],
		    __goalString,
		    __goalSheetId;
		
		__$goals.each(function(){
		    __goalArray.push(this.id)
		})
		
		__goalSheetId = $j('#hdnGoalSheetId').val()
		
		__goalString = __goalArray.join('|');
		//console.log(__goalString);
		//console.log($j('#hdnGoalSheetId').val());
		
		$j.ajax({
		    type: "POST",
		  	url: FC.vars.paths.GOALS_AJAX,
		  	data: {"goals":__goalString, "goalSheetId": __goalSheetId },
		  	success: function(){
		  	    var _i= __$els.length;
		  	
                __$this.parents('li').find('div.lta-btn-container').removeClass('lta-show');
                
                while(_i--){
		            __result[_i]= $j(__$els[_i]).sortable('toArray');
	            }
			}
		})
		
		//instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);
	})
	
	$j('.lta-goal-intro a.lta-btn').bind('click', function(e) {
		var __$nextList= $j(this).parents('div.lta-goal-intro').next();
		var __serialized= __$nextList.sortable('serialize');
		
		//instead of return false - click bubbles up to body element and that handles the event
        $j.data(e.target, 'return', false);
		
	});
	
	
	
	 __$els.sortable({
		revert: true,
		update: function(){
			var __currentList = __$els.index(this), __currentResult= $j(__$els[__currentList]).sortable('toArray'), __l= __currentResult.length, __hasChanged = false;
			while(__l--) {
				if(__currentResult[__l] != __result[__currentList][__l]) {
					__hasChanged = true;
				}
			}
			
			if(__hasChanged) {
				__$els.eq(__currentList).prev().find('div.lta-btn-container').addClass('lta-show')
			}
			else {
				__$els.eq(__currentList).prev().find('div.lta-btn-container').removeClass('lta-show')
			}
		},
		start: function() {
			$j(this).find('div.lta-box-inner').css('cursor', 'move');
			
			//user is dragging, so unbind the click function that takes you through to that goals page
			__$innerBox.unbind('click');
		},
		stop: function(event, ui) {
			if(FC.hasIE) {
        $j(ui.item).addClass('lta-zoom');
      }
      		
			$j(this).find('div.lta-box-inner').css('cursor', 'default');
			
			//re-bind the function that takes you through to that goals page
			 __$innerBox.bind('click', function() {
				clickHandler(this);
			});
		}
	});
	 
	var clickHandler = function(el) { 
		window.location= $j(el).find('h3 a').attr('href');
	}
	
	
	//clicking anywhere inside the lta-box-inner div needs to take you through that goals page.
    __$innerBox.bind('click', function() {
		clickHandler(this);
	});

	 __$innerBox.bind('mouseover',function() {
		this.style.cursor='pointer';
	});
	 
	  __$innerBox.bind('mouseout',function() {
		this.style.cursor='default';
	});

	while(i--){
		 __result[i]= $j(__$els[i]).sortable('toArray');
	}
	
	$j(__$els).disableSelection();
	
}

$j('.lta-default-cursor').click(function(e) {
    e.preventDefault();
})

FC.revealAdditionalInfo = function(__el){
	var __$el = $j(__el);
	var __$elContent = __$el.text();
	
	__$el.after('<a href="#">Show all</a>');
	__$el.addClass('lta-accessibility');
	
	$j('p.lta-additional-info a').bind('click', function() {
		var __$text= $j(this).prev('span');
		
		if(__$text.hasClass('lta-accessibility')) {
			__$text.removeClass('lta-accessibility');
			$j(this).text('Hide additional text');
		}
		else {
			__$text.addClass('lta-accessibility');
			$j(this).text('Show all text');
		}
		return false;
	});
	
	
}

FC.goalStatusRadios = function(__$els){
	var __length = __$els.length;
	
	__$els.bind('click keypress', function(){
		var __i = __length;
		while(__i--){
			if (FC.vars.regEx.STATUS_SELECTED.test(__$els[__i].className)) __$els[__i].className = __$els[__i].className.replace(FC.vars.classNames.STATUS_SELECTED, "");
		}
		if (!FC.vars.regEx.STATUS_SELECTED.test(this.className)) this.className += FC.vars.classNames.STATUS_SELECTED;
	});
	
	__$els.each(function(index){
		_checked = $j(this).find('input').attr('checked');
		if(_checked) this.className += FC.vars.classNames.STATUS_SELECTED;
	});
	
}

FC.goalPrinting = function(__el) {
	var __$el= $j(__el);
	
	__$el.append('<li class="lta-print"><a href="#">Print goals</a></li>');
	
	__$el.find('.lta-print a').bind('click', function() {
		window.print();
	});
}

FC.fancySelects = function(__$els) {
    var __$body = $j('body'),
		__i = __$els.length,
		__a = document.createElement('A'),
		__spanOut = document.createElement('SPAN'),
		__spanIn = document.createElement('SPAN'),

	__onClickHandler = function(e) {
	    var __$sels = $j('.lta-fancy-select'),
			__$values = $j('.lta-fancy-select-value'),
			__$uls = $j('.lta-fancy-select-ul'),
			__ulsLength = __$uls.length,
			__target = $j(e.target),
			__par = __target.parents('.lta-fancy-select'),
			__$ul = $j('.lta-fancy-select-ul', __par),
			__$select = $j('select', __par),
			__$value = $j('.lta-fancy-select-value', __par),
			rOpen = /\blta-open\b/;

	    while (__ulsLength--) {
	        __$uls[__ulsLength].className = __$uls[__ulsLength].className.replace(rOpen, "");
	    }
	    __$values.css('visibility', 'visible');
	    __$sels.css('z-index', '10');

	    switch (e.target.className) {
	        case 'lta-fancy-select-value':
	            var _ulWidth = 0;
	            if (!rOpen.test(__$ul[0].className)) {
	                __$ul[0].className += " lta-open";
	                __par.css('z-index', '100');

	                $j('li', __$ul[0]).each(function() {
	                    if (this.offsetWidth > _ulWidth) _ulWidth = this.offsetWidth;
	                })
	                __$ul[0].style.width = _ulWidth;
	            }
	            else {
	                __$ul[0].className = __$ul[0].className.replace(rOpen, "");
	            }
	            __$value.css('visibility', 'hidden');
	            break;
	        case 'lta-fancy-select-option':
	            __$select[0].selectedIndex = $j('li', __$ul).index(__target.parent()[0]);
	            __$value[0].innerHTML = e.target.firstChild.nodeValue;
	            __$value.css('visibility', 'visible');
	            __$ul[0].className = __$ul[0].className.replace(rOpen, "")
	            if ($j(this).hasClass('lta-select-month')) {
	                var __days, __daysSelect = $j('.lta-select-day').find('select')[0], __daysValue = $j('.lta-select-day').find('.lta-fancy-select-value')[0], __$daysLis = $j('span.lta-select-day li'), __$daysLength = __$daysLis.length, __date = new Date(), __year = __date.getFullYear(), __leapYear = false;

	                //leap year is true if the year is divisible by 4 but not 100.  If it's divisible by 4 & 100, then it must also be divisible by 400
	                if (__year % 4 == 0) {

	                    if (__year % 100 == 0) {

	                        if (__year % 400 == 0) {
	                            __leapYear = true;
	                        }

	                    }

	                    else if (__year % 100 > 1) {
	                        __leapYear = true;
	                    }
	                }

	                switch (__$value[0].innerHTML) {
	                    case 'February':
	                        if (__leapYear) {
	                            __days = 29
	                        }
	                        else {
	                            __days = 28
	                        }
	                        break;

	                    case 'April':
	                        __days = 30
	                        break;

	                    case 'June':
	                        __days = 30
	                        break;

	                    case 'September':
	                        __days = 30
	                        break;

	                    case 'November':
	                        __days = 30
	                        break;

	                    default:
	                        __days = 31
	                        break;
	                }

	                switch (__days) {
	                    case 28:
	                        if (__$daysLength > __days) {
	                            __$daysLis.filter(':nth-child(1n+' + (__days + 1) + ')').remove();
	                        }
	                        if (__daysSelect.selectedIndex > 27) {
	                            __daysSelect.selectedIndex = 27;
	                            __daysValue.innerHTML = 28;
	                        }
	                        break;

	                    case 29:
	                        if (__$daysLength > __days) {
	                            __$daysLis.filter(':nth-child(1n+' + (__days + 1) + ')').remove();
	                        }
	                        if (__daysSelect.selectedIndex > 28) {
	                            __daysSelect.selectedIndex = 28;
	                            __daysValue.innerHTML = 29;
	                        }
	                        break;

	                    case 30:
	                        if (__$daysLength > __days) {
	                            __$daysLis.filter(':nth-child(1n+' + (__days + 1) + ')').remove();
	                        }
	                        else if (__$daysLength == 28) {
	                            __$daysLis.parent().append('<li><a class="lta-fancy-select-option">29</a></li><li><a class="lta-fancy-select-option">30</a></li>')
	                        }
	                        else if (__$daysLength == 29) {
	                            __$daysLis.parent().append('<li><a class="lta-fancy-select-option">30</a></li>');
	                        }
	                        if (__daysSelect.selectedIndex > 29) {
	                            __daysSelect.selectedIndex = 29;
	                            __daysValue.innerHTML = 30;
	                        }
	                        break;

	                    case 31:
	                        if (__$daysLength == 28) {
	                            __$daysLis.parent().append('<li><a class="lta-fancy-select-option">29</a></li><li><a class="lta-fancy-select-option">30</a></li><li><a class="lta-fancy-select-option">31</a></li>')
	                        }
	                        else if (__$daysLength == 29) {
	                            __$daysLis.parent().append('<li><a class="lta-fancy-select-option">30</a></li><li><a class="lta-fancy-select-option">31</a></li>');
	                        }
	                        else if (__$daysLength == 30) {
	                            __$daysLis.parent().append('<li><a class="lta-fancy-select-option">31</a></li>');
	                        }
	                        break;

	                    default:
	                        break;

	                }


	            }

	        default:
	    }

	    __$select.change();

	    //instead of return false - click bubbles up to body element and that handles the event
	    $j.data(e.target, 'return', false);
	},

	__bodyClickHandler = function(e) {
	    var __$ul = $j('.lta-fancy-select-ul'),
			__ulLength = __$ul.length,
			__$value = $j('.lta-fancy-select-value'),
			rOpen = /\blta-open\b/;

	    switch (e.target.className) {
	        case 'lta-fancy-select-value':
	            break;
	        case 'lta-fancy-select-option':
	            break
	        default:
	            while (__ulLength--) {
	                __$ul[__ulLength].className = __$ul[__ulLength].className.replace(rOpen, "");
	            }
	            __$value.css({
	                'display': 'block',
	                'visibility': 'visible'
	            });
	    }
	};

    __spanOut.className = 'lta-fancy-select-inner';
    __a.href = '#';
    __spanIn.className = 'lta-fancy-select-value';

    __a.appendChild(__spanIn);
    __spanOut.appendChild(__a);

    while (__i--) {
        var __docFrag = document.createDocumentFragment(), __$select = $j(__$els[__i]).find('select'), __$options = $j(__$els[__i]).find('option'), __length = __$options.length, __ul = document.createElement('UL');

        __ul.className = 'lta-fancy-select-ul';

        for (__j = 0; __j < __length; __j++) {
            var __a = document.createElement('A'), __li = document.createElement('LI');

            __a.className = 'lta-fancy-select-option'
            __a.appendChild(document.createTextNode(__$options[__j].firstChild.nodeValue))
            __li.appendChild(__a);
            __ul.appendChild(__li);
        }

        __spanOut.firstChild.firstChild.innerHTML = __$options[__$select[0].selectedIndex].firstChild.nodeValue;

        __docFrag.appendChild(__spanOut.cloneNode(true));
        __docFrag.appendChild(__ul);

        __$els[__i].appendChild(__docFrag);

    }

    __$els.bind('click', __onClickHandler);
    __$body.bind('click', __bodyClickHandler);

}

FC.fancySelectGroup = function(__$els) {
    var __SEL = FC.vars.selectors,
		__$items = $j(__SEL.FANCY_SELECT_GROUP_ITEM),
		__select = __$els.find('select'),
		__index = __select[0].selectedIndex,
		__updateGroup = function(_index) {
		    __$items.hide();
		    $j(__$items[_index]).show();
		}

    __select.bind('change', function() {
        var _index = this.selectedIndex;
        __updateGroup(_index);
    })

    __updateGroup(__index);

}

/* Clubs functions - copied from functions-clubs.js */

FC.showHideHelp = function(){
	//$j('.js-helptext').hide();
	
	$j('.js-helptext .inner .padding').append('<p class="floatright"><a href="#" class="hidehelp">Hide help</a></p>');
	
	$j('.help a').bind('click', function(){
		var boxToOpen = "#" + $j(this).attr('class');
		$j(boxToOpen).slideDown(250);
		return false;
	});
	$j('.helplink a').bind('click', function(){
		var boxToOpen = "#" + $j(this).attr('class');
		$j(boxToOpen).slideDown(250);
		return false;
	});
	$j('.hidehelp').bind('click', function(){
		$j(this).parents('.js-helptext').slideUp(250);
		return false;
	});
	
	
}

FC.ratingMouseOver = function(){
	$j(FC.vars.el).find("label").each(function(){
		$j(this).bind("mouseover", function(){
			if($j(this).hasClass('open')){
				$j(this).find('img').attr({
					src: "/images/clubs/star-over.gif"
				})
			};
			$j(this).parent().prevAll().each(function(){
				if ($j(this).find("label").hasClass('open')) {
					$j(this).find('img').attr({
						src: "/images/clubs/star-over.gif"
					});
				}
			});
		});				
	});
}

FC.ratingFocus = function(){
	$j(FC.vars.el).find("input").each(function(){
		$j(this).bind("focus", function(){
			if($j(this).siblings("label").hasClass('open')){
				$j(this).siblings("label").find('img').attr({
					src: "/images/clubs/star-over.gif"
				})
			};
			$j(this).parent().prevAll().each(function(){
				if ($j(this).find("label").hasClass('open')) {
					$j(this).find('img').attr({
						src: "/images/clubs/star-over.gif"
					});
				}
			});
		});				
	});
},

FC.ratingMouseOut = function(){
	$j(FC.vars.el).find("label").each(function(){
		$j(this).bind("mouseout", function(){
			if($j(this).hasClass('open')){
				$j(this).find('img').attr({
					src: "/images/clubs/star-off.gif"
				})
			};
			$j(this).parent().prevAll().each(function(){
				if ($j(this).find("label").hasClass('open')) {
					$j(this).find('img').attr({
						src: "/images/clubs/star-off.gif"
					});
				}
			});
		});
	});
}

FC.ratingBlur = function(){
	$j(FC.vars.el).find("input").each(function(){
		$j(this).bind("blur", function(){
			if($j(this).siblings("label").hasClass('open')){
				$j(this).siblings("label").find('img').attr({
					src: "/images/clubs/star-off.gif"
				})
			};
			$j(this).parent().prevAll().each(function(){
				if ($j(this).find("label").hasClass('open')) {
					$j(this).find('img').attr({
						src: "/images/clubs/star-off.gif"
					});
				}
			});
		});
	});
},
		

FC.addRating = function(){
	
	// .club ul.rating li input{position:absolute;left:-9999px;top:-9999px;}
	$j(FC.vars.el).find('input').css('position', 'absolute').css('left', '-9999em');
	// <img src="/images/clubs/star-off.gif" width="16" height="15" alt="1 star" />
	$j(FC.vars.el).find("label").each(function(intIndex){
		$j(this).empty().append($j('<img src="/images/clubs/star-off.gif" width="16" height="15" alt="' + (intIndex + 1) + ' star" />'))
	})
	
	FC.ratingMouseOver();
	FC.ratingFocus();
	FC.ratingMouseOut();
	FC.ratingBlur();
	
	$j(FC.vars.el).find("label").bind("click", function(){
		$j(this).removeClass('open');
		
		$j(this).parent().prevAll().find("label").removeClass('open');
		$j(this).parent().prevAll().find('img').attr({
			src: "/images/clubs/star-on.gif"
		})
		
		$j(this).parent().nextAll().find("label").addClass('open');
		$j(this).parent().nextAll().find('img').attr({
			src: "/images/clubs/star-off.gif"
		})
		
		$j(this).find('img').attr({
			src: "/images/clubs/star-on.gif"
		})
		
		$j(this).next().attr("checked", true);
		
		return false;
	})
	
	$j(FC.vars.el).find("input").bind("change", function(){
		$j(this).siblings("label").removeClass('open');
		
		$j(this).parent().prevAll().find("label").removeClass('open');
		$j(this).parent().prevAll().find('img').attr({
			src: "/images/clubs/star-on.gif"
		})
		
		$j(this).parent().nextAll().find("label").addClass('open');
		$j(this).parent().nextAll().find('img').attr({
			src: "/images/clubs/star-off.gif"
		})
		
		$j(this).siblings("label").find('img').attr({
			src: "/images/clubs/star-on.gif"
		})
		
		return false;
	})
	
}

FC.initMembersList = function(){
	FC.membersList();
}

FC.createMembersList = function() {
    var _$allRoles = $j('.roles').find('span'),
        _allRoles = "";

    for (var i = 0; i < _$allRoles.length; i++) {
        if(_$allRoles[i].firstChild){
            _allRoles += _$allRoles[i].firstChild.nodeValue + ', ';
        }
    }

    _allRoles = _allRoles.replace(/ /g, '');

    for (var i = 0; i < FC.vars.roles.length; i++) {
        var _tempRoles = _allRoles;
        FC.vars.shortRole = FC.vars.roles[i].replace(/ /g, '');
        var currentRoles = $j('.roleslist').parent().siblings('.roles').find('span').text().replace(/ /g, '');

        var checker = "", disable = "";

        var _rolesLimit = FC.vars.rolesLimits[i];

        if (_rolesLimit > 0) {

            _roleCount = _tempRoles.match(FC.vars.rolesRegex[i]) ? _tempRoles.match(FC.vars.rolesRegex[i]).length : 0;

            if (_roleCount >= _rolesLimit && currentRoles.indexOf(FC.vars.shortRole) == -1) {
                disable = 'disabled="disabled"';
            };
        }

        if (currentRoles.indexOf(FC.vars.shortRole) != -1) {
            checker = 'checked="checked"';
        }

        ($j('<div></div>').addClass('field').addClass('clear')
			.append($j('<input type="checkbox" ' + checker + ' ' + disable + '></input>').attr('name', FC.vars.shortRole).attr('id', FC.vars.shortRole))
			.append($j('<label></label>').attr('for', FC.vars.shortRole).text(FC.vars.roles[i]))
		)
		.insertBefore($j('.roleslist .lta-btn-save'));
    }
}

FC.updateMembersList = function() {
    FC.vars.currentRoles = $j('.roleslist').parent().siblings('.roles').find('span').text().replace(/ /g, '').toLowerCase();
    $j('.roleslist input').each(function() {
        if (FC.vars.currentRoles.indexOf($j(this).attr('id')) > -1) {
            $j(this).attr('checked', 'checked');
        }
    })
}

FC.newRoles = function() {
    FC.vars.newRoles = ''
    $j('.roleslist input:checked').each(function() {
        FC.vars.newRoles = FC.vars.newRoles + $j(this).siblings('label').text() + ', '
    });
    if (FC.vars.newRoles == '') {
        FC.vars.newRoles = ' '
    } else {
        FC.vars.newRoles = FC.vars.newRoles.substring(0, FC.vars.newRoles.length - 2)
    }

    $j('.roleslist').parent().siblings('.roles').find('span').text(FC.vars.newRoles);
}

FC.membersList = function() {
    $j('.memberslist').find('.update > a').bind('click', function() {
        $j(this).parents('tr').addClass('selected');
        ($j('<div></div>').addClass('roleslist').css('display', 'none')
			.append($j('<div></div>').addClass('roles-top'))
			.append($j('<div></div>').addClass('roles-content')
				.append($j('<div></div>').addClass('padding')
					.append($j('<fieldset></fieldset>')
						.append($j(this).parent().siblings('roles').find('span'))
						.append($j('<a class="lta-btn lta-btn-alt-3 lta-btn-save" href="#"><span>Save</span></a>').bind('click', function() {
						    this.style.cursor = 'wait';
						    FC.submitMembersList();
						    return false;
						}))
						.append($j('<a class="lta-btn lta-btn-alt-3" href="#"><span>Cancel</span></a>').bind('click', function() {
						    FC.resetMembersList();
						    return false;
						}))
					)
				)
			)
			.append($j('<div></div>').addClass('roles-bottom'))
		)
		.appendTo($j(this).parent());
        $j('.memberslist').find('.update > a').removeAttr('href').unbind('click');
        $j('.memberslist').find('.update > a > img').attr('src', '/images/clubs/btn-update-disabled.gif');
        FC.createMembersList();
        FC.updateMembersList();
        $j(this).siblings('.roleslist').slideDown(250);
        $j(this).remove();
        return false;
    })
}

FC.resetMembersList = function(){
	$j('.roleslist').slideUp(250, function(){
		($j('<a></a>').attr('href', '#')
			.append($j('<img></img>').attr('height', '20').attr('width', '63').attr('alt', 'Update').attr('src', '/images/clubs/btn-update.gif'))
		).prependTo($j(this).parent());
		$j(this).remove();
		$j('.memberslist').find('tr').removeClass('selected');
		$j('.memberslist').find('.update > a').attr('href', '#');
		$j('.memberslist').find('.update > a > img').attr('src', '/images/clubs/btn-update.gif');
		FC.membersList();
	});
}

FC.submitMembersList = function(){
	document.body.style.cursor = 'wait';
	FC.vars.rolesObject.memberId = $j('.roleslist').siblings()[0].value;
	FC.vars.rolesObject.clubId = $j('.roleslist').siblings()[1].value;
	FC.vars.rolesObject.memberRoles = []
	$j('.roleslist input:checked').each(function(){
		FC.vars.rolesObject.memberRoles.push($j(this).attr('id'));
	})
	//submit data here
	$j.post(FC.vars.rolesURL + FC.vars.rolesObject.clubId, { memberId: FC.vars.rolesObject.memberId, memberRole: FC.vars.rolesObject.memberRoles, clubId: FC.vars.rolesObject.clubId  }, function(){
		FC.newRoles();
		FC.resetMembersList();
		document.body.style.cursor = 'auto';
	});
}

FC.imageViewer = function(){
	$j('.imageviewer > li > a').bind('click', function(){
    	__url = $j(this).attr('href');
		__img = new Image();
		$j('.imageviewer > li.main > span').empty().addClass('loading');
    	$j(__img).load(function () {
        $j(this).css('display', 'none');
        $j(this).hide();
        $j('.imageviewer > li.main > span').removeClass('loading').append(this);
        $j(this).fadeIn(500);
        }).error(function () {
            $j('.imageviewer > li.main > span').text('The image could not be loaded')
        }).attr('src', __url);
		return false;
    });

}

FC.confirm = function(){
	$j("a.confirm").bind('click', function() {
		link = $j(this).attr('href');
		text = $j(this).text().toLowerCase();
		FC.confirmAction(text, link, function(r) {
			if(r){
				window.location.href = link
			} else {
				//do nothing
			};
		});
		return false;
	});
}

FC.confirmAction = function(text, link, callback){
	
	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$j("body", "html").css({
				height: "100%",
				width: "100%"
			});
			$j("html").css("overflow", "hidden");
			if ($j('.hideSelect').length == 0 ) {//iframe to hide select elements in ie6
				$j("body").append("<iframe class='hideSelect'></iframe><div class='overlay'></div><div class='popup'><div class='popup-top'><div class='popup-middle'><h3>Are you sure?</h3><p class='popup-text'></p></div></div><div class='popup-bottom clear'></div></div>");
			}
		}
		else {//all others
			if (document.getElementById("TB_overlay") === null) {
				$j("body").append("<div class='overlay'></div><div class='popup'><div class='popup-top'><div class='popup-middle'><h3>Are you sure?</h3><p class='popup-text'></p></div></div><div class='popup-bottom clear'></div></div>");
			}
		}
		
		if (FC.detectMacXFF()) {
			$j(".overlay").addClass("overlayMacFFBGHack");//use png overlay so hide flash
		}
		else {
			$j(".overlay").addClass("overlayBG");//use background and opacity
		}
		
		$j(".popup-text").text('This will permanently remove the relationship between this BTM and your club.');
		
		$j(".popup-bottom").append('<a href="#" class="popup-no floatleft"><img height="28" width="121" alt="No, don\'t do this" src="/images/clubs/btn-no-dont-do-this.gif"/></a><a href="#" class="popup-yes floatright"><img height="28" width="98" alt="Yes, I\'m sure" src="/images/clubs/btn-yes-im-sure.gif"/></a>');
		
		$j(".popup-yes").click( function() {
			if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
				$j(".hideSelect").remove();
				$j("body","html").css({height: "auto", width: "auto"});
				$j("html").css("overflow","");
			}
			$j(".popup").remove();
			$j(".overlay").remove();
			callback(true);
			return false;
		});
		$j(".popup-no").click( function() {
			if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
				$j(".hideSelect").remove();
				$j("body","html").css({height: "auto", width: "auto"});
				$j("html").css("overflow","");
			}
			$j(".popup").remove();
			$j(".overlay").remove();
			callback(false);
			return false;
		});
		$j(".popup-yes").focus();

	} 
	catch (e) {
		
	}
	
}

FC.detectMacXFF = function() {
	var userAgent = navigator.userAgent.toLowerCase();
	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
		return true;
	}
	
}

FC.courtsTooltip = function(){
	
	$j('.courts img').each(function(){
		var altAtt = $j(this).attr('alt');
		$j(this).tooltip({
			track: true, 
    		delay: 0, 
    		showURL: false,
			bodyHandler: function() { 
		        return altAtt; 
		    },
			extraClass: "tool-tip",
			top: -55, 
    		left: -150                                      
		})
	})
}

//FC.countdown = function() {
//    var limit = $j('textarea.countdown').attr('limit');
//    var currentLength = $j('textarea.countdown').val().length;
//    $j('textarea.countdown').parents('.field').find('.counttext').append($j('<span>&nbsp;- you have <span class="countvalue">' + (limit - currentLength) + '</span> characters left</span>'));
//    $j('textarea.countdown').bind('keydown keypress keyup', function() {
//        if ($j(this).val().length > limit) {
//            $j(this).val($j(this).val().substring(0, limit));
//        } else {
//            $j('.countvalue').text(limit - $j(this).val().length);
//        }
//    })
//}

FC.countdown = function() {
    var limit = $j('textarea.countdown').attr('limit'),
        limit1 = $j('textarea.countdown1').attr('limit'),
        limit2 = $j('textarea.countdown2').attr('limit'),
        limit3 = $j('textarea.countdown3').attr('limit');

    var currentLength = $j('textarea.countdown').val().length,
        currentLength1 = $j('textarea.countdown1').val().length,
        currentLength2 = $j('textarea.countdown2').val().length,
        currentLength3 = $j('textarea.countdown3').val().length;

    $j('textarea.countdown').parents('.field').find('.counttext').append($j('<span>&nbsp;- you have <span class="countvalue">' + (limit - currentLength) + '</span> characters left</span>'));
    $j('textarea.countdown').bind('keydown keypress keyup', function() {
        if ($j(this).val().length > limit) {
            $j(this).val($j(this).val().substring(0, limit));
        } else {
            $j('.countvalue').text(limit - $j(this).val().length);
        }
    })

    $j('textarea.countdown1').parents('.field').find('.counttext1').append($j('<span>&nbsp;- you have <span class="countvalue1">' + (limit1- currentLength1) + '</span> characters left</span>'));
    $j('textarea.countdown1').bind('keydown keypress keyup', function() {
        if ($j(this).val().length > limit1) {
            $j(this).val($j(this).val().substring(0, limit1));
        } else {
            $j('.countvalue1').text(limit1 - $j(this).val().length);
        }
    })

    $j('textarea.countdown2').parents('.field').find('.counttext2').append($j('<span>&nbsp;- you have <span class="countvalue2">' + (limit2 - currentLength2) + '</span> characters left</span>'));
    $j('textarea.countdown2').bind('keydown keypress keyup', function() {
        if ($j(this).val().length > limit2) {
            $j(this).val($j(this).val().substring(0, limit2));
        } else {
            $j('.countvalue2').text(limit2 - $j(this).val().length);
        }
    })

    $j('textarea.countdown3').parents('.field').find('.counttext3').append($j('<span>&nbsp;- you have <span class="countvalue3">' + (limit3 - currentLength3) + '</span> characters left</span>'));
    $j('textarea.countdown3').bind('keydown keypress keyup', function() {
        if ($j(this).val().length > limit3) {
            $j(this).val($j(this).val().substring(0, limit3));
        } else {
            $j('.countvalue3').text(limit3 - $j(this).val().length);
        }
    })
}

FC.showMore = function($smLinks) {
    $smLinks.toggle(function() {
        var $this = $(this);
        $this.parent().parent().next('.lta-expandable').show(); //.animate({height: 'toggle'}, 500);
        $this.parent().parent().addClass("lta-expanded-par");
        $this.children('span').attr('class', $this.children('span').text());
        $this.children('span').text('Close');
    }, function() {
        var $this = $(this);
        $this.parent().parent().next('.lta-expandable').hide(); //.animate({height: 'toggle'}, 500);
        $this.parent().parent().removeClass('lta-expanded-par');
        $this.children('span').text($this.children('span').attr('class'));
    });
};

FC.connectSelect = function($selectOne) {
	var s = $j(".lta-connections-01");
	
	//give up if no select 2
	if(s.length === 0) {
		return false;
	}
    
	//bind events
	s.bind("change",changeHandler);
		
	//change handler
	function changeHandler(e) {
		var o = e.target === s[0] ? s[1] : s[0]; //check which select
		o.selectedIndex = 4 -  e.target.selectedIndex ; // set the value 
	}
}



FC.confirmClick = function() {
    var _linkClickHandler = function(e) {
        switch (e.keyCode) {
            case 13: // enter key
            case undefined: //mouse click
            case 0: //mouse click in IE
                if ($j('tr.lta-added').length == 0 
                || $j(this).parents('.lta-ballot-table').length > 0 
                || $j(this).parents('.lta-search-extent-container').length > 0 
                || $j(this).parents('.lta-hero-slideshow-count-controls').length > 0)
                    return;
                
                _link = this.href;

                $j('.lta-confirm').css('display', 'block');
                $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
                $j('.lta-confirm-stay').unbind('click').bind('click', function() {
                    $j('.lta-confirm').css('display', 'none');
                    return false;
                })
                
                $j('.lta-confirm-go').unbind('click').bind('click', function() {
                    $j('.lta-confirm').css('display', 'none');
                    window.location.href = _link;
                    return false;
                })

            default:
                return false;
        }
    }, _inputClickHandler = function(e) {
        switch (e.keyCode) {
            case 13: // enter key
            case undefined: //mouse click
            case 0: //mouse click in IE
                if ($j(this).parents('.lta-ballot-table').length > 0)
                    return;
                    
                var _$target = $j(e.currentTarget);

                $j('.lta-confirm').css('display', 'block');
                $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
                $j('.lta-confirm-stay').unbind('click').bind('click', function() {
                    $j('.lta-confirm').css('display', 'none');
                    return false;
                })
                $j('.lta-confirm-go').unbind('click').bind('click', function() {
                    _$target.unbind('click').trigger('click');
                    return false;
                })
            default:
                return false;
        }
    }, _inputViewClickHandler = function(e) {
        switch (e.keyCode) {
            case 13: // enter key
            case undefined: //mouse click
            case 0: //mouse click in IE
            
                var _$target = $j(e.currentTarget);

                $j('.lta-confirm').css('display', 'block');
                $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
                $j('.lta-confirm-stay').unbind('click').bind('click', function() {
                    $j('.lta-confirm').css('display', 'none');
                    return false;
                })
                $j('.lta-confirm-go').unbind('click').bind('click', function() {
                    _$target.unbind('click').trigger('click');
                    return false;
                })
            default:
                return false;
        }
     }, _inputAutoSwitchClickHandler = function(e) {
        switch (e.keyCode) {
            case 13: // enter key
            case undefined: //mouse click
            case 0: //mouse click in IE
            
                var _$target = $j(e.currentTarget);

                $j('.lta-switch-to-auto').css('display', 'block');
                $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
                $j('.lta-confirm-cancel-auto').unbind('click').bind('click', function() {
                    $j('.lta-switch-to-auto').css('display', 'none');
                    return false;
                })
                $j('.lta-confirm-go-auto').unbind('click').bind('click', function() {
                    _$target.unbind('click').trigger('click');
                    return false;
                })
            default:
                return false;
        }
     }

    //$j('a').bind('click keypress', _linkClickHandler);

    $j('input[type=submit]').each(function() {

        if (!$j(this).hasClass('no-confirm') 
            && $j('input[value^=Notify]').length > 0
            && $j(this).hasClass('lta-view-btn')) {
            $j(this).bind('click keypress', _inputViewClickHandler);
        }
        else if(!$j(this).hasClass('no-confirm')
            && $j(this).hasClass('lta-confirm-switch-to-auto')){
            $j(this).bind('click keypress', _inputAutoSwitchClickHandler);
        }
        else if (!$j(this).hasClass('no-confirm') 
            && !$j(this).hasClass('.lta-view-btn')) {
            $j(this).bind('click keypress', _inputClickHandler);
        }
    });
}

FC.siebelError = function() {
    var _$closeLink = $j('.lta-siebel-error-close'),
		_inputClickHandler = function(e) {
		        $j('.lta-siebel-error').css('display', 'none');
		    return false;
		};

    _$closeLink.bind('click', _inputClickHandler);
}


FC.confirmAuto = function() {
    var _$confirmInput = $j('input.lta-ballot-confirm-auto'),
		_$goLink = $j('.lta-confirm-go-auto'),
		_$closeLink = $j('.lta-confirm-close-auto'),
		_$closeLink = $j('.lta-confirm-cancel-auto'),
		_inputClickHandler = function(e) {
		    $j('.lta-confirm-auto').css('display', 'block');
		    $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
		    _$goLink.unbind('click').bind('click', function() {
		        return false;
		    }); ;
		    _$goLink.css({ opacity: 0.4 }).addClass('lta-confirm-dis');
		    _$closeLink.unbind('click').bind('click', function() {
		        $j('.lta-confirm-auto').css('display', 'none');
		        return false;
		    });
		    $j('.lta-confirm-check').unbind('change').bind('change', function() {
		        if (this.checked) {
		            _$goLink.css({ opacity: 1 }).removeClass('lta-confirm-dis')
		            _$goLink.unbind('click').bind('click', function() {
		                _$confirmInput.unbind('click').trigger('click');
		                return false;
		            });
		        } else {
		            _$goLink.unbind('click').bind('click', function() {
		                return false;
		            });
		            _$goLink.css({ opacity: 0.4 }).addClass('lta-confirm-dis-auto')
		        }
		    })
		    return false;
		};

	_$confirmInput.bind('click', _inputClickHandler);

	$j('.lta-confirm-cancel-auto span').click(function() {

	    if ($j('.lta-auto-check').is(':checked'))
	        $j('.lta-auto-check').removeAttr('checked');
	});
}

FC.confirmSwitchToAuto = function() {
    var _$confirmInput = $j('.lta-confirm-switch-to-auto'),
		_$goLink = $j('.lta-confirm-go-auto'),
		_$closeLink = $j('.lta-confirm-cancel-auto'),
		_inputClickHandler = function(e) {
		    $j('.lta-switch-to-auto').css('display', 'block');
		    $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
		    
		    _$closeLink.unbind('click').bind('click', function() {
		        $j('.lta-switch-to-auto').css('display', 'none');
		        return false;
		    });
		    
		    return false;
		};
    _$confirmInput.bind('click', _inputClickHandler);
}


FC.confirmMan = function() {
    var _$confirmInput = $j('input.lta-ballot-confirm-man'),
		_$goLink = $j('.lta-confirm-go-man'),
		_$closeLink = $j('.lta-confirm-close-man'),
		_$closeLink = $j('.lta-confirm-cancel-man'),
		_inputClickHandler = function(e) {
		    $j('.lta-confirm-man').css('display', 'block');
		    $j('.lta-confirm-overlay').css('height', document.body.clientHeight);
		    _$goLink.unbind('click').bind('click', function() {
		        return false;
		    });
		    _$goLink.css({ opacity: 0.4 }).addClass('lta-confirm-dis');
		    _$closeLink.unbind('click').bind('click', function() {
		        $j('.lta-confirm-man').css('display', 'none');
		        return false;
		    });
		    $j('.lta-confirm-check').unbind('change').bind('change', function() {
		        if (this.checked) {
		            _$goLink.css({ opacity: 1 }).removeClass('lta-confirm-dis')
		            _$goLink.unbind('click').bind('click', function() {
		                _$confirmInput.unbind('click').trigger('click');
		                return false;
		            });
		        } else {
		            _$goLink.unbind('click').bind('click', function() {
		                return false;
		            });
		            _$goLink.css({ opacity: 0.4 }).addClass('lta-confirm-dis-man')
		        }
		    })
		    return false;
		};

    _$confirmInput.bind('click', _inputClickHandler);

    $j('.lta-confirm-cancel-man span').click(function() {
        if ($j('.lta-manual-check').is(':checked'))
            $j('.lta-manual-check').removeAttr('checked');
    });
}

$j(function() {

    var __SEL = FC.vars.selectors, __$tmp;
    (function(arg) {
        for (var __i = 0, __j = arg.length, __o; __i < __j; __i++) {
            __o = arg[__i];
            (function() {
                __$tmp = $j(__o.test);
                return __$tmp.length
            })() ? __o.func(__$tmp, __o.args || null) : null;
        }

    })([{ func: FC.heroPanel, test: __SEL.HERO_LIST },
		{ func: FC.recordsScroller, test: __SEL.RECORDS },
		{ func: FC.galleryScroller, test: __SEL.THUMB_CONTAINER },
		{ func: FC.showImage, test: __SEL.MAIN_IMG },
		{ func: FC.panelScroller, test: __SEL.SAMPLE_MENU },
		{ func: FC.panelScroller, test: __SEL.HOSPITALITY },
		{ func: FC.hospSlideshow, test: __SEL.HOSPITALITY_IMAGE },
		{ func: FC.setupToggle, test: '.lta-prev-winners' },
		{ func: FC.Tabs, test: '.lta-tabs' },
	    { func: FC.countCharacters, test: '.lta-limitchar' },
		{ func: FC.showGalleryDetailImage, test: __SEL.GALLERY_DETAIL_MAIN_IMG },
        { func: FC.helpButton, test: __SEL.MEMBERS_HELP_BTN },
		{ func: FC.galleryDetailScroller, test: __SEL.GALLERY_DETAIL },
		{ func: FC.PhotoGalleryScroll, test: '.gallery-frame .latest-gallery' },
		{ func: FC.liveFeed, test: __SEL.TABLE_CONTAINER, args: __SEL.TABLE_CONTAINER },
		{ func: FC.liveFeed, test: __SEL.TABLE_CONTAINER_SM, args: __SEL.TABLE_CONTAINER_SM },
		{ func: FC.LiveTicker, test: '.live-scroller' },
		{ func: FC.rowHighlight, test: '.ranking' },
		{ func: FC.matchTabs, test: __SEL.MATCH_TABS },
		{ func: FC.listHover, test: __SEL.LIST_HOVER },
		{ func: FC.verticalScroll, test: __SEL.VERTICAL_SCROLLER },
		{ func: FC.rankingListing, test: __SEL.RANKING_LISTING },
		{ func: FC.heroSlideshow, test: __SEL.HERO_SLIDESHOW },
		{ func: FC.siteSearch, test: __SEL.SITE_SEARCH },
		{ func: FC.flyoutNavigation, test: __SEL.FLYOUT_NAVIGATION },
		{ func: FC.placeholderText, test: __SEL.PLACEHOLDER_TEXT },
		{ func: FC.placeholderTitleText, test: __SEL.PLACEHOLDER_TEXT },
		{ func: FC.subnav, test: __SEL.SUBNAV },
		{ func: FC.mapToggle, test: __SEL.MAP_HOLDER },
		{ func: FC.boxHover, test: __SEL.BOX_HOVER },
		{ func: FC.goalExpander, test: __SEL.GOAL_EXPANDER },
		{ func: FC.vertNavScroll, test: __SEL.VERTICAL_NAV_SCROLL },
		{ func: FC.goalTooltip, test: __SEL.GOAL_TOOLTIP },
		{ func: FC.goalDragDrop, test: __SEL.GOAL_DRAG_DROP },
		{ func: FC.goalStatusRadios, test: __SEL.GOAL_STATUS_RADIOS },
		{ func: FC.fancySelects, test: __SEL.FANCY_SELECTS },
		{ func: FC.fancySelectGroup, test: __SEL.FANCY_SELECT_GROUP },
		{ func: FC.expander, test: __SEL.EXPANDER },
		{ func: FC.addRating, test: 'ul.rating' },
		{ func: FC.initMembersList, test: '.memberslist' },
		{ func: FC.showHideHelp, test: '.js-helptext' },
		{ func: FC.imageViewer, test: '.imageviewer' },
		{ func: FC.confirm, test: 'a.confirm' },
		{ func: FC.courtsTooltip, test: '.courts' },
		{ func: FC.countdown, test: 'textarea.countdown' },
		{ func: FC.showMore, test: __SEL.SHOW_MORE_LINK },
		{ func: FC.connectSelect, test: __SEL.CONNECTION_SELECT },
		{ func: FC.confirmAuto, test: __SEL.CONFIRM_AUTO },
		{ func: FC.confirmSwitchToAuto, test: __SEL.CONFIRM_SWITCH_AUTO },
		{ func: FC.confirmMan, test: __SEL.CONFIRM_MAN },
		{ func: FC.confirmClick, test: __SEL.CONFIRM_CLICK},
		{ func: FC.siebelError, test: __SEL.SIEBEL_ERROR}
	]);

    //if(FC.hasIE6) 
    FC.search();
    FC.fancyNav();

    var output = (function(arr) { return arr[0].g })([{ g: 'stuff'}])

    __$tmp = null;

    if ($j('div.lta-sponsors-widget img').length) {
        // initialise the slideshow
        FC.initSlideshow(sponsorcounter);
        // initialise the pause button
        FC.pauseBtn(intervalID);
        return false;
    }

    //for maps
    if ($j('#map_canvas').length) {
        try { initializeMap() }
        catch (e) { }
    }

});

function CreatePlacesToPlaySearchMap()
{
    var bounds = new GLatLngBounds();

    for(var i = 0; i < venues.length; i++)
    { 
        if(venues[i][1] != null && venues[i][2] != null)
        {                                                    
            var coordinates = new GLatLng(venues[i][1], venues[i][2]);
            map.addOverlay(CreateMarker(coordinates, document.getElementById(venues[i][0])));
            bounds.extend(coordinates);
        }
    }
    
    var zoom = map.getBoundsZoomLevel(bounds);
    if(zoom > 14) zoom = 14;
    map.setCenter(bounds.getCenter(), zoom); 
}

function ShowEventsOnMap() 
{
//    var bounds = new GLatLngBounds();

    for(var i = 0; i < venues.length; i++)
    { 
        if(venues[i][1] != null && venues[i][2] != null)        
        {     
            var coordinates = new GLatLng(venues[i][1], venues[i][2]);
            map.addOverlay(CreateMarkerForEvents(coordinates, document.getElementById(venues[i][0])));
            //            bounds.extend(coordinates);
        }
    }
    
//    var zoom = map.getBoundsZoomLevel(bounds);
//    if(zoom > 14) zoom = 14;
      map.setCenter(new GLatLng(centreLat, centreLng), zoomLevel); 
}

function CreateMarker(coordinates, anchor)
{
    var icon = new GIcon();   
    icon.image = $j(anchor).parents('li').find('img').attr('src');
    icon.infoWindowAnchor = new GPoint(10, 15);
    icon.iconAnchor = new GPoint(10, 36);
        
    var marker = new GMarker(coordinates, icon);
    var popupHtml = $j(anchor).parents('div.lta-courts-facilities').html();
    
    GEvent.addListener(marker, 'click', function(){marker.openInfoWindowHtml(popupHtml);});
    anchor.onmouseover = function(){marker.openInfoWindowHtml(popupHtml);};

    return marker;
}

function CreateMarkerForEvents(coordinates, anchor)
{
    var icon = new GIcon();   
    icon.image = '/images/icons/event-map-pin.png';;
    icon.infoWindowAnchor = new GPoint(10, 15);
    icon.iconAnchor = new GPoint(10, 36);
        
    var marker = new GMarker(coordinates, icon);
    //var popupHtml = $j(anchor).parents('div.lta-courts-facilities').html();
    
    var infoDiv = $j(anchor).parents('td.lta-event-info-on-map');

    var infoHtml = infoDiv.html();
    var dateHtml = infoDiv.siblings('.lta-event-date').html();
    var popupHtml = infoHtml + dateHtml;
    
    GEvent.addListener(marker, 'click', function(){marker.openInfoWindowHtml(popupHtml);});
    // anchor.onmouseover = function(){marker.openInfoWindowHtml(popupHtml);};

    return marker;
}

function ToggleSearchOptions(enabled)
{
    $j('.lta-search-checkboxes').find('input').attr("disabled", !enabled);
    $j('.lta-search-advanced-options').find('select').attr("disabled", !enabled);
}
