// ===== Scroll Smoothly to Anchor Tags =================================================================
window.addEvent('domready', function(){ 
	if(!window.opera) new SmoothScroll({duration: 1500, transition: Fx.Transitions.Quart.easeInOut}); 
})

// ===== Global Rollovers ===============================================================================
function addRollovers(){
	var rollover = $$('img.rollover');
	rollover.each(function(element){
		element.onmouseover = function() { element.src = element.src.replace("_inactive","_active"); };
		element.onmouseout = function() { element.src = element.src.replace("_active","_inactive"); };
	});
};

function addSubmitRollovers(){
	var rollover = $$('input.rollover');
	rollover.each(function(element){
		element.onmouseover = function() { element.src = element.src.replace("_inactive","_active"); };
		element.onmouseout = function() { element.src = element.src.replace("_active","_inactive"); };
	});
};


window.addEvent('domready',function(){
    addRollovers();
});

// ===== Menu Dropdown Functions ====================================================================
var dropdown = function(id) {
	if($(id)){
		var links = $(id).getChildren();
		links.each(function(li){
			if(li.getTag() == "li"){
				var bkgd = $('mainNavLogo'+li.getAttribute('id').replace(/\D/g,'')).getElement('img');		
				var fade = new Fx.Style(bkgd, 'opacity', {duration:400, transition: Fx.Transitions.sineOut, wait: false}).set(0);
				li.addEvents({
					'mouseenter':function(){ 
						this.addClass('sfhover');
						//fade.start([1,fade])
						fade.start(1);
					},
					'mouseleave':function(){
						this.removeClass('sfhover');
						//fade.start([0, fade])
						fade.start(0);
					}
				});
			}
		});
		
	}
};
window.addEvent('domready',function(){
	dropdown('mainNav');
});


// ===== Main Content Flash Module ====================================================================
var mySlide;
var nOpen = nClose = "";
window.addEvent('domready',function(){
	var activeTab = activeItem = "";
	if($('tabs')) {
	active = $('tabs').getElements('li');
	active.each(function(li){ 
		if(li.hasClass('active')){
			activeTab = li.getText();
			activeItem = li.className.replace('active','').trim();
		}
	});
	}
	if($('tabs')){
		var so = new SWFObject('flash/tabsModule.swf', 'oeTabsModule', '470', '59', '8');
		so.addParam("allowScriptAccess","always");
		so.addParam('wmode','transparent');
		so.addVariable("activeTab",activeTab);
		so.addVariable("activeItem",activeItem);
		so.addVariable("isIE",((window.ie)?true:false));
		so.addVariable("isIndex",$E('body').hasClass('index'));
		so.write("tabs");
	}
	if($('tabsContent')){
		var so = new SWFObject('flash/mainModule.swf', 'oeMainModule', '980', '382', '8');
		so.addVariable("activeTab",activeTab);
		so.addVariable("activeItem",activeItem);
		so.addVariable("isIE",((window.ie)?true:false));
//		if($E('.index')){
//			so.addParam('allowFullScreen', 'true');
//			so.addVariable('fullscreen','true');
//			so.write("tabsContent");
//		} else {
			so.addParam('wmode','transparent');
			so.write("tabsContent");
//		}
	}
	nOpen = 441;
	nClose = 60;
	mySlide = new Fx.Style('tabsContainer', 'height',{duration: 750, transition: Fx.Transitions.Quart.easeInOut});
	if($('btnExpand')){
		$('tabsContent').innerHTML = "";
		mySlide.addEvent('onComplete',function(){
			if($('tabsContainer').getStyle('height').toInt() > 100){
				$('tabsContainer').addClass("bkg");
				$('btnExpand').innerHTML = "collapse";
				so.write("tabsContent");
			} else {
				$('btnExpand').innerHTML = "expand";
				$('tabsContainer').removeClass("bkg");
			}
			$('btnExpand').toggleClass('expand');
			$('btnExpand').toggleClass('collapse');
		});
		$('btnExpand').addEvent('click', function(e){
			new Event(e).stop();
			if($('tabsContainer').getStyle('height').toInt() > 100){
				$('tabsContent').innerHTML = "";
				$('tabsContainer').addClass("bkg");
				mySlide.start(nOpen,nClose);
			} else {
				$('tabsContainer').addClass("bkg");
				mySlide.start(nClose,nOpen);	
			}
		});
	}
	if($('tabsContainer') && $('tabsContainer').hasClass('display')) mySlide.start(nClose,nOpen);
	if($('tabsContainer') && $('tabsContainer').hasClass('fullDisplay')) mySlide.set(nOpen);
});

function openTabsContent(){
	if($$('#top .subpage')){
		if($('tabsContainer').getStyle('height').toInt() < 100){
			mySlide.start(nClose,nOpen);
		}
	}
}

// ===== Inline Content Flash Module ====================================================================
window.addEvent('domready',function(){
	if($('inlineModule') && $E('#inlineModule span')){
		var so = new SWFObject('flash/inlineModule.swf', 'oeInlineModule', '340', '364', '8');
			so.addVariable("dataFile",$E('#inlineModule span').innerHTML);
			so.addParam('wmode','transparent');
			so.write("inlineModule");
	}
});

// ===== Tabs Content Expandable Area ===================================================================
window.addEvent('domready', function(){
	var nOpen = (window.ie6)? 444 : 441;
	var nClose = 60;
	var mySlide = new Fx.Style('tabsContainer', 'height',{duration: 750, transition: Fx.Transitions.Quart.easeInOut});
	if($('btnExpand')){
		mySlide.addEvent('onComplete',function(){
			if($('tabsContainer').getStyle('height').toInt() > 100){
				$('btnExpand').innerHTML = "collapse";
			} else {
				$('btnExpand').innerHTML = "expand";
			}
			$('btnExpand').toggleClass('expand');
			$('btnExpand').toggleClass('collapse');
		});
		$('btnExpand').addEvent('click', function(e){
			new Event(e).stop();
			if($('tabsContainer').getStyle('height').toInt() > 100){
				mySlide.start(nOpen,nClose);
			} else {
				mySlide.start(nClose,nOpen);	
			}
		});
	}
	if($('tabsContainer') && $('tabsContainer').hasClass('display')) mySlide.start(nClose,nOpen);
	if($('tabsContainer') && $('tabsContainer').hasClass('fullDisplay')) mySlide.set(nOpen);
});

// ===== Accordion Module ===============================================================================
window.addEvent('domready',function(){
	var accordion = new Accordion('div.toggle', 'div.element', {
		show:-1,
		opacity:true,
		duration:400,
		transition:Fx.Transitions.Expo.easeInOut,
		onActive: function(toggler, element){
			toggler.setStyle('color', '#639');
			var label = toggler.getElement('b');
			var arrow = label.getStyle('background-image');
			label.setStyle('background-image',arrow.replace('_inactive','_active'));
		},
		onBackground: function(toggler, element){
			toggler.setStyle('color', '#333');
			var label = toggler.getElement('b');
			var arrow = label.getStyle('background-image');
			label.setStyle('background-image',arrow.replace('_active','_inactive'));
		}, onComplete: function(){
			if(window.ie6 || window.ie7){
				var leftCol = $('leftColumn').getCoordinates().height;
				var rightCol = $E('#container .contentArea').getCoordinates().height;
				var height = (rightCol < leftCol)? leftCol : rightCol;
				$E('#container .contentArea').setStyle('height',height);
			}
		}
	}, $('accordion'));
	// ===== Find Item To Display =====
	if($('accordion')){
		$('accordion').getElements('.toggle').each(function(toggle,i){
			if(toggle.hasClass('display')){
				accordion.display(i);
			}
		});
	}
});

// ===== Countdown To Event ===============================================================================
window.addEvent('domready',function(){
	if($('countdown')){
		var Event = {
			Total : 3,
			Count : 1,
			TimeZone : "ET",
			Date1 : {
				StartDate	: new Date("10/24/2008 15:30"),
				EndDate		: new Date("10/24/2008 17:20"),
				OnNowMsg 	: "Watch it live on ESPN2!",
				OnFinish	: ""
			},
			Date2 : { 
				StartDate	: new Date("10/25/2008 12:00"),
				EndDate		: new Date("10/25/2008 18:00"),
				OnNowMsg 	: "Watch now on ESPN!",
				OnFinish	: ""
			},
			Date3 : { 
				StartDate	: new Date("11/06/2009 13:30"),
				EndDate		: new Date("11/06/2009 18:00"),
				OnNowMsg 	: "Watch it live on ESPN!",
				OnFinish	: ""
			}
		}
		var Clock = new CountdownClock($$('#countdown div.clock'),Event);
	}
});
var CountdownClock = new Class({
    initialize: function(el,options){
        this.options = options;
		this.today = new Date();
		this.date = this.options["Date"+this.options.Count].StartDate;
		this.type = "onClock";
		this.el = el;
		this.text = "";
		this.step = 1;
		this.periodical;
		this.nZone = -6;
		/*
		switch(this.options.TimeZone.toUpperCase()){
			case "ET": this.nZone = -5; break;
			case "CT": this.nZone = -6; break;
			case "MT": this.nZone = -7; break;
			case "PT": this.nZone = -8; break;
		}
		*/
		this.countdown();
		this.display();
	},
	display: function(){
		switch(this.step++){
			case 1:
				this.date = this.options["Date"+this.options.Count].StartDate;
				this.type = "onClock";
				this.text = "";
				break;
			case 2:
				this.date = this.options["Date"+this.options.Count].EndDate;
				this.type = "onNow";
				this.text = this.options["Date"+this.options.Count].OnNowMsg;
				break;
			case 3:
				this.type = "onFinish"
				this.text = this.options["Date"+this.options.Count].OnFinish;
				if(this.options.Count < this.options.Total){
					this.options.Count++;
					this.step = 1;
					this.display();
				}
				break;
		}
		this.periodical = this.countdown.periodical(1000,this);
	},
	countdown: function(){
		this.today = new Date();
		// ===== Reset Timezone ============================
		//var utc = this.today.getTime() + (this.today.getTimezoneOffset() * (60*1000));
		var utc = this.today.getTime() + (300 * (60*1000));
		var now = new Date(utc+((60*60*1000)*this.offset()));
		// ===== Format Date ===============================           
		//Find the difference, and convert that into seconds.                  
		var nTime = Math.round((this.date.getTime() - now.getTime()) / 1000);
		if(nTime > -1) { // still counting
			if(this.type == "onClock"){
				var days = this.addZeros(Math.floor(nTime / (60 * 60 * 24)));
				nTime %= (60 * 60 * 24);
				var hours = this.addZeros(Math.floor(nTime / (60 * 60)));
				nTime %= (60 * 60);
				var minutes = this.addZeros(Math.floor(nTime / 60));
				nTime %= 60;
				var seconds = this.addZeros(nTime);
				this.el.setHTML(days+'<em>days</em> '+hours+'<em>hrs</em> '+minutes+'<em>mins</em>');
			} else if(this.type == "onNow"){
				this.el.setHTML(this.text);
			};
		} else {
			$clear(this.periodical);
			if(this.type != "onFinish"){
				this.display();
			} else {
				if(this.text != ""){
					this.el.setHTML('<em>'+this.text+'<em>');
				}
			}
		}
	},
	offset: function(){
		var thisYear = this.today.getFullYear();
		var MarchDate = 14 - (Math.floor (1 + thisYear * 5 / 4) % 7);
		var NovemberDate = 7 - (Math.floor (1 + thisYear * 5 / 4) % 7);
		var startDate = new Date(thisYear,2,MarchDate);
		var endDate = new Date(thisYear,10,NovemberDate);
		return (this.today.getTime() > startDate.getTime() && this.today.getTime() < endDate.getTime())? this.nZone+1 : this.nZone;
	},
	addZeros: function(digits){
		return (Number(digits) < 10) ? "0"+digits : digits;
	}
});

// ===== Sliding Carousel ===============================================================================
var carousels = [];
window.addEvent('domready',function(){
	$$('.carousel').each(function(el,i){
		var container = el.getElement('div.carouselContent');
		var items = el.getElements('.carouselItem');
		var controls = el.getElement('.controls');
		carousels[i] = new SlideCarousel(container,{
			items:items,
			frameSize:el.getStyle('width').toInt(),
			itemSize:items[0].getStyle('width').toInt(),
			display:controls.getElement('.galleryCount'),
			prev:controls.getElement('.btnPrev'),
			next:controls.getElement('.btnNext')
		});
	});
});
var SlideCarousel = new Class({
	initialize: function(container, options) {
		this.setOptions(options);
		this.active = false;
		this.activeImage = 1;
		this.container = container;
		this.aItems = $A(this.options.items);
		this.nDisplay = this.options.display;
		this.itemSize = this.options.itemSize;
		this.itemsTotalWidth = this.aItems.length*this.itemSize;
		this.container.setStyle('width',this.itemsTotalWidth+'px');
		this.itemsTotal = this.aItems.length;
		this.pageSize = Math.floor(this.options.frameSize / this.options.itemSize);
		this.pageTotal = (this.itemsTotal%this.pageSize==0)?this.itemsTotal:(this.pageSize-(this.itemsTotal%this.pageSize)+this.itemsTotal);
		this.totalPages = Math.floor(this.pageTotal / this.pageSize);
		this.nDisplay.setHTML(this.activeImage +" of "+ this.totalPages);
		if(this.totalPages > 1){
			this.prevLink = this.options.prev;
			this.nextLink = this.options.next;
			this.prevLink.addClass('btnDisabled');
			this.nextLink.addClass('btnEnabled');
			this.prevLink.addEvent("click", function(event) {new Event(event).stop(); this.previous()}.bind(this));
			this.nextLink.addEvent("click", function(event) {new Event(event).stop(); this.next()}.bind(this));
		} else { 
			this.options.prev.remove();
			this.options.next.remove();
			this.options.display.remove();
		}
		
		this.xPos = this.container.getStyle('left').toInt();
		this.position = new Fx.Style(this.container, 'left', {
			duration: 750,
			transition:Fx.Transitions.quartInOut,
			onStart: function(){
				// disable both buttons
				this.prevLink.removeClass("btnEnabled");
				this.nextLink.removeClass("btnEnabled");
				this.prevLink.addClass("btnDisabled");
				this.nextLink.addClass("btnDisabled");
				this.active = true;
			}.bind(this),
			onComplete: function(){
				if(this.activeImage > 1){
					this.prevLink.removeClass("btnDisabled");
					this.prevLink.addClass("btnEnabled");
				}
				if(this.activeImage < this.totalPages){
					this.nextLink.removeClass("btnDisabled");
					this.nextLink.addClass("btnEnabled");
				}
				this.active = false;
			}.bind(this)
		});
	},
	previous: function() {
		if(this.active) return;
		return this.changeImage(this.activeImage-1);
	},
	next: function() {
		if(this.active) return;
		return this.changeImage(this.activeImage+1);
	},
	changeImage: function(imageNum) {
		if((imageNum <= 0) || (imageNum > this.totalPages)) return false;
		this.xPos = this.container.getStyle('left').toInt();
		var dir = (imageNum > this.activeImage)? -1 : 1;
		this.position.custom(this.xPos,this.xPos+((this.itemSize*this.pageSize)*dir));
		this.activeImage = imageNum;
		this.nDisplay.setHTML(this.activeImage +" of "+ this.totalPages);
	}
});
SlideCarousel.implement(new Options);

// ===== Rotating Fan Pick Quotes w/ Fader ========================================================================
window.addEvent('domready',function(){
	if(!$('fanPicksQuote')) return;
	var fadeEffect = new Fx.Style('fanPicksQuote', 'opacity',{
		duration:750,
		transition: Fx.Transitions.linear,
		onComplete: function(){
			if($('fanPicksQuote').getStyle('opacity') == 0){
				 loop = ((loop+1) % quotes.length);
				$('fanPicksQuote').setHTML(quotes[loop]).forceEllipsis();
				fadeEffect.start(0, 1);
			} else {
				fadeEffect.start.pass([1,0], fadeEffect).delay(8000);
			}
		}
	});

	var loop = 0;
	var quotes = [];
	var stopFade = false;
	var items = $('fanPicks').getElements('span');
	items.each(function(quote){
		quotes.push(quote.innerHTML);
		quote.remove();
	});
	$('fanPicksQuote').addEvent('click',function(e){
		new Event(e).stop();
		document.location.href = $('fanPicksBtn').getAttribute('href');
	}).setStyle('cursor','pointer');
	// ===== Start Fader =====
	$('fanPicksQuote').setHTML(quotes[loop]).forceEllipsis();
	fadeEffect.set(0).start(0, 1);
});
Element.extend({
	forceEllipsis: function(){
		var ellipsis = false;
		var height = this.getStyle('height').toInt();
		var scrollSize = this.getSize().scrollSize.y;
		while(scrollSize > height){
			this.setHTML(this.innerHTML.trim().substr(0,this.innerHTML.trim().lastIndexOf(" ")));
			scrollSize = this.getSize().scrollSize.y;
			ellipsis = true;
		}
		if(ellipsis) this.setHTML(this.innerHTML.trim().substr(0,this.innerHTML.trim().lastIndexOf(" ")) + "&hellip;");
	}
});
String.prototype.clean = function() {
    return this.replace(/^\s*|\s*$/g, "");
};
// ===== Fan Pick Quote Popup Form Submission ====================================================
window.addEvent('domready',function(){
	if($('fanPicks')){
			var picksSlide = new Fx.Slide('submitFanPicks', {
			mode: 'vertical',
			duration: 500,
			transition:Fx.Transitions.quartInOut
		}).hide();
		$('slidein').addEvent('click', function(e){
			e = new Event(e);
			picksSlide.slideIn();
			e.stop();
		});
		$('slideout').addEvent('click', function(e){
			e = new Event(e);
			picksSlide.slideOut();
			e.stop();
		});
	}
	/*if($('picksForm')){
		//console.log("Done");
		$('picksSubmit').addEvent('submit', function(e) {
			new Event(e).stop();
			var log = $('picksFormContainer').empty().addClass('ajaxLoading');
			new Ajax ({
				update: log,
				onComplete: function() {
					log.removeClass('ajaxLoading');
				}
			}).send();
		});
	}*/
});

window.addEvent('domready',function(){
	if(!$('picksForm')) return;
	$('picksSubmit').addEvent('click', function(e) {
		new Event(e).stop();
		details = "<blockquote>Thank you for your submission. ONLY handcapping analysis from fans for this race will be considered for random display on this site. We reserve the right to edit submissions for content.<\/blockquote>";
		$('picksForm').send({
			onComplete: function() {
				$("picksForm").setHTML(details);
				//$('picksForm').empty();
			}
		});
	});
});


// ===== Toggle Tab Items ========================================================================
window.addEvent('domready',function(){
	if(!$('inlineTabs')) return;
	var tabBtns = $('inlineTabs').getElements('.tab');
	var tabItem = $('inlineTabs').getElements('.content');
	var activeTab = tabBtns[0];
	tabBtns.each(function(tab){
		tab.addEvent('click',function(e){
			new Event(e).stop();
			tabItem.each(function(item){ item.addClass('hide') });
			tabBtns.each(function(tab){
				var img = tab.getElement('img');
				img.src = img.src.replace('_active','_inactive');
			});
			var num = tab.className.replace(/\D/g,'');
			var img = tab.getElement('img');
			img.src = img.src.replace('_inactive','_active');
			tabItem[num-1].removeClass('hide');
		});
	});
});

// ===== Show Tab Item Photos on Rollover ========================================================
window.addEvent('domready',function(){
	if(!$('inlineTabs')) return;
	var content = $('inlineTabs').getElements('.content');
	content.each(function(tab){
		var photo = tab.getElements('.photo img')[0];
		var mainPhoto = photo.src;
		var links = tab.getElements('a');
		links.each(function(link){
			if(link.className.length){
				link.addEvent('mouseenter',function(e){
					photo.src = link.className;									
				});
				link.addEvent('mouseleave',function(e){
					photo.src = mainPhoto;	
				});
			}
		});
	});
});



/*Churchill*/
// ===== Popup details @ index ====================================================================
var homeSlide = [];
window.addEvent('domready',function(){
	if($('scheduleDetail')){
			homeSlide = new Fx.Slide('scheduleDetail', {
			mode: 'vertical',
			duration: 500,
			transition:Fx.Transitions.quartInOut
		}).hide();
		$('slideout').addEvent('click', function(e){
			e = new Event(e);
			homeSlide.slideOut();
			e.stop();
		});
	}
	if($('scheduleContainer')){
		var schedule = $("scheduleContainer").getElements("a.slideIn");
		schedule.each(function(element){
			element.addEvent('click', function(e){
				new Event(e).stop();
				homeSlide.slideIn();
				var xmlUrl = "/xmlfeed.aspx?action=scheduledetail&id=" + element.id.replace('detail','');
				new Ajax(xmlUrl, {
					method: 'get',
					onComplete: function(text, xml) { 
						var details = xml.getElementsByTagName("Details")[0];
						$("scheduleDetail").getElement(".date").setHTML(details.getAttribute("Date"));
						$("scheduleDetail").getElement(".heading").setHTML(details.getAttribute("Heading"));
						$("scheduleDetail").getElement(".division").setHTML(details.getAttribute("Division"));
						$("scheduleDetail").getElement(".grade").setHTML(details.getAttribute("Grade"));
						$("scheduleDetail").getElement(".purse").setHTML(details.getAttribute("Purse"));
						$("scheduleDetail").getElement(".distance").setHTML(details.getAttribute("Distance"));
						$("scheduleDetail").getElement(".age").setHTML(details.getAttribute("Age"));
						$("scheduleDetail").getElement(".track").setHTML(details.getAttribute("Track"));
						$("scheduleDetail").getElement(".weather").setHTML(details.getAttribute("Weather"));
						$("scheduleDetail").getElement(".tv").setHTML(details.getAttribute("TV"));
					}
				}).request();
			});
		})
	}
});

// ===== Toggle Tab Items ========================================================================
window.addEvent('domready',function(){
	if(!$('inlineTabsPull')) return;
	var tabBtns = $('inlineTabsPull').getElements('.tab');
	var tabItem = $('inlineTabsPull').getElements('.content');
	var divisionName = '';
	if ($('divisionname')!=null) divisionName=$('divisionname').value;
	var activeTab = tabBtns[0];
	var activeItem;
	var num;
	var d = new Date();
	var currentMonth = d.getMonth() +1;
		if (currentMonth < 10) { currentMonth = "0" + currentMonth; }
	var currentYear = d.getFullYear();
	// Population of Content by new month
	var loadComplete = function() {
		var newMonth = $(activeItem.id).getElements("a.month");
		newMonth.each(function(element){
			element.addEvent('click', function(e){
				new Event(e).stop();
//				var newMonthUrl = currentYear + element.id + "_" + activeItem.id + ".html";
				var newMonthUrl = "ajax.aspx?type=" + activeItem.id + "&year=" + currentYear + "&month=" + element.id;
				if (divisionName!="") newMonthUrl+='&division=' + divisionName;
				new Ajax(newMonthUrl, {
					method: 'get',
					update: activeItem,
					onComplete: loadComplete
				}).request();
			});
		});
		if(window.ie6 || window.ie7){
			var leftCol = $('leftColumn').getCoordinates().height;
			if ($('type')!=null) {
			    var rightCol = $(activeItem.id).getCoordinates().height + 800;
			} 
			else if ($('stakesTabs')!=null) {
			    var rightCol = $(activeItem.id).getCoordinates().height + 700;
			}
			else {
			    var rightCol = $(activeItem.id).getCoordinates().height + 200;
			}
			var height = (rightCol < leftCol)? leftCol : rightCol;
			$E('#container .contentArea').setStyle('height',height);
		}
	}
	tabBtns.each(function(tab){
		tab.addEvent('click',function(e){
			new Event(e).stop();
			tabItem.each(function(item){ item.addClass('hide') });
			tabBtns.each(function(tab){
				var img = tab.getElement('img');
				img.src = img.src.replace('_active','_inactive');
			});
			num = tab.className.replace(/\D/g,'');
			var img = tab.getElement('img');
			img.src = img.src.replace('_inactive','_active');
			tabItem[num-1].removeClass('hide');
			// Population of Content by tab
			activeItem = tabItem[num-1];
			var urlCall = tabItem[num-1].id;
//			var url = currentYear + currentMonth + "_" + urlCall + ".html";
			var url = "ajax.aspx?type=" + urlCall + "&year=" + currentYear + "&month=" + currentMonth;
			if (divisionName!="") url+='&division=' + divisionName;
			new Ajax(url, {
				method: 'get',
				update: tabItem[num-1],
				onComplete: loadComplete
			}).request();
		});
	});
	// Population of Content initially
	addEvent('domready',function(){
		if($('startTab')){
                var startTab = $('startTab').innerHTML;
                activeItem = tabItem[startTab];
                tabItem[0].addClass('hide');
                function defImg() {
                            var defImg = tabBtns[0].getElement('img');
                            defImg.src = defImg.src.replace('_active','_inactive');
                }
                function startImg() {
                            var startImg = tabBtns[startTab].getElement('img');
                            startImg.src = startImg.src.replace('_inactive','_active');
                }
                defImg();
                startImg();
                tabItem[startTab].removeClass('hide');
            } else {
                        activeItem = tabItem[0];
            }

//		var loadUrl = currentYear + currentMonth + "_" + activeItem.id + ".html";
		var loadUrl = "ajax.aspx?type=" + activeItem.id + "&year=" + currentYear + "&month=" + currentMonth;
		if (divisionName!="") loadUrl+='&division=' + divisionName;
		new Ajax(loadUrl, {
			method: 'get',
			update: activeItem,
			onComplete: loadComplete
		}).request();
	});
});




/*JZ */
function searchBios()
{
    location.href='/statsbios.aspx?query=' + escape(document.getElementById('textfieldName').value) + '#biosearch';
}

function searchBiosKeyDown(e)
{
    if (window.navigator.appName.indexOf("Microsoft")>(-1)){ 
		if (event.keyCode == 13)
		{
			event.returnValue=false;
			event.cancel = true;
			searchBios();
		} 
    } else {
		if (e.keyCode == 13){ 
		        searchBios(); 
                return false; 
        } 
    }
    return true;
}

function clickButton(e, buttonid){ 
      var bt = document.getElementById(buttonid); 
      if (typeof bt == 'object'){ 
			
            if (window.navigator.appName.indexOf("Microsoft")>(-1)){ 
				if (event.keyCode == 13)
				{
					event.returnValue=false;
					event.cancel = true;
					bt.click();
				} 
            } else {
				if (e.keyCode == 13){ 
                        bt.click(); 
                        return false; 
                } 
            }
      }
} 

function printThisPage(){ 
    var pageTitle = "Breeders' Cup"
    var content = '<div style="background-color:#FFFFFF;">'+document.getElementById("printArea").innerHTML+'</div>'; 
    var printPage = '<html><head><title>'+pageTitle+'</title><link type="text/css" rel="stylesheet" href="/css/styles_print.css" /></head><body onLoad="self.print()">'+content+'</body></html>';
    var winFeatures = "toolbar=yes,location=no,directories=no,menubar=no,scrollbars=yes,width=650,height=600,left=100,top=25"; 
    var win = window.open("","",winFeatures); 
    win.document.open(); 
    win.document.write(printPage); 
    win.document.close(); 
    win.focus(); 
}







/**************Churchill****************/
// ===== Genre DropdownList @ Index ===================================================================
Element.extend({
	hide: function(){ return this.setStyle('display', 'none') },
	show: function(){ return this.setStyle('display', 'block') }
});
var DropdownList = new Class({
	initialize: function(options){
        this.options = options;
		this.active = null;
		this.hideTimer = null;
		this.originalList = $(this.options.id).getElement('ul');
		this.genreList = this.originalList.clone().addClass('selectOptions').setStyle('display','block');
		$(this.options.id).adopt(this.genreList);
		this.originalList.remove();
		this.position = $$('#'+this.options.id+' .selectedOption')[0];
		this.listWidth = this.position.getStyle('width').toInt();
		this.padding = 0;
		var list = this.genreList.getElements('li');
		list.each(function(li){
			li.innerHTML = '<span>'+li.innerHTML+'</span>';
			var width = li.getElement('span').getCoordinates().width;
			if(width > this.listWidth){
				this.listWidth = width;
				this.padding = 10;
			}
		}.bind(this));
		this.genreList.setStyles({
			'position':'absolute',
			'z-index':'9999',
			'top':(this.position.getStyle('top').toInt()+this.position.getStyle('height').toInt())+'px',
			'left':this.position.getStyle('left'),
			'width':(this.listWidth+this.padding)+'px',
			'display':'none'
		}).addEvent('mouseenter', function(){ 
			this.showDropdown();
		}.bind(this)).addEvent('mouseleave', function(){ 
			this.hideDropdown();
		}.bind(this));
		this.genreList.getElements('li').each(function(element) {
			element.addEvent('mouseenter', function(){
				this.showDropdown();
				if(!element.hasClass('active')) 
					element.addClass('hover');
					element.removeClass('list');
			}.bind(this));
			element.addEvent('mouseleave', function(){
				if(!element.hasClass('active')){
					element.removeClass('hover');
					element.addClass('list');
				}
			});
			element.addEvent('click', function(){
				if(this.active != null) this.active.removeClass('active');
				this.active = element;
				element.addClass('active');
				this.genreList.hide();
				this.activate(element);
			}.bind(this));
			if(element.hasClass('active')) this.active = element;
		}.bind(this));
		$$('#'+this.options.id+' .selectedOption')[0].addEvent('click', function(e){
			new Event(e).stop();
			(this.genreList.style.display == 'none')? this.showDropdown() : this.hideDropdown();
		}.bind(this)).addEvent('mouseleave', function(e){
			this.hideDropdown();
		}.bind(this));
	},
	
	activate: function(element){
		if($(this.options.id).hasClass('redirect')){
			$E('#'+this.options.id+' .selectedOption span').setHTML(element.innerHTML.removeHTML());
			$E('#'+this.options.id+' .toQueryString').setHTML(element.id);
			var aQueryString = $$('.redirect .toQueryString');
			var total = aQueryString.length;
			if(total){
				var params = "";
				var doc = document.location.toString();
				var url = doc.substr(0,doc.indexOf(document.location.search));
				aQueryString.each(function(element,i){
					var sClass = element.className.toString();
					var paramName = sClass.substring(sClass.indexOf(' ')+1,sClass.indexOf('?'));
					params += paramName +"="+ element.innerHTML.removeHTML() + ((i<total-1)?"&":"");
				});
				var currentDay = 0;
				if($('dateList')){
					var dayImg = $('dateList').getElements('a img');
					dayImg.each(function(img,i){
						if(img.src.indexOf('_on.gif')>-1) currentDay = i;
					});
					document.location.href = url+"?"+params;
				} else { 
					document.location.href = url+"?"+params; //+"&day="+currentDay;
				}
			}
		} else {
			var genre = element.innerHTML.removeHTML().trim();
			$$('#'+this.options.id+' .selectedOption span')[0].setHTML(genre);
			var url = "/scheduleajax.aspx?type=" + genre + "&day=" + Schedule.currentDay;
			location.href = url;
		}      
	},
	
	showDropdown: function(){
		if(this.hideTimer){
			window.clearTimeout(this.hideTimer);
			this.hideTimer = null;
		}
		this.genreList.show();
	},
	hideDropdown: function(){
		this.hideTimer = window.setTimeout(function(){
			this.genreList.hide();										
		}.bind(this),1000);
	}
});

window.addEvent('domready',function(){
	var dropdown = $$('.selectDropdown');
	if(dropdown.length){
		dropdown.each(function(element){
			element = new DropdownList({id:element.id});
		});
	}
});
String.prototype.removeHTML = function(){
	return this.replace(/<[^>]*>/g,"")
};
String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/g, "");
};




// ===== popUp Biography Mini  ===================================================================
window.addEvent('domready',function(){
	// Browser Check
	var d, dom, ie, ie4, ie5x, moz, mac, ie5mac, op;
	d = document;
	n = navigator;
	na = n.appVersion;
	nua = n.userAgent;
	mac = ( na.indexOf('Mac') != -1 );
	if ( !d.layers ){
		dom = ( d.getElementById );
		op = ( nua.indexOf('Opera') != -1 );
		saf = ( nua.indexOf('Safari') != -1 );
		moz = ( nua.indexOf('Gecko') != -1 && !saf );
	
		ie5x = ( d.all && dom );
		ie5mac = ( mac && ie5x );
	}
	// Set Div Position
	function findPosition(element) {
		var x,w,y,h,s;
		if (document.getBoxObjectFor) { // mozilla (pc & mac)
			var box = document.getBoxObjectFor(element); 
			x = box.x;
			w = box.width;
			y = box.y;
			h = box.height;
			s = 3; // scrollTop;
			return { x: x, y: (y+s), width: w, height: h }
		} else { // All Other browsers
			if(element.offsetParent) {
				var posWidth = element.offsetWidth;
				var posHeight = (saf)? element.offsetHeight+5 : element.offsetHeight;
				for(var posX = 0, posY = 0; element.offsetParent; element = element.offsetParent) {
					posX += element.offsetLeft;
					posY += element.offsetTop;
				}
				return { x: posX, y: posY, width: posWidth, height: posHeight };
			} else {
				return { x: element.x, y: element.y, width: element.offsetWidth, height: element.offsetHeight };
			}
		}
	}
	var miniBio = $$('.miniBio');
	miniBio.each(function(callBio){
		callBio.addEvent('click', function(e) {
		new Event(e).stop();
		if ($("bioContainer")){
			document.body.removeChild($("bioContainer"));
		}
		// Calling the Ajax and creating the Container
		var bioId = callBio.id;
		var bioHref = callBio.getAttribute('href');
		var loadUrl = "/ajax.aspx?type=minibio&id=" + bioId;
		var divContainer = document.createElement("div");
			divContainer.id = "bioContainer";
			document.body.appendChild(divContainer);
			placeContainer("bioContainer");
			new Ajax(loadUrl, {
				method: 'get',
				update: $("bioContainer").setHTML("Loading..."),
				onComplete: function(text, xml) { 
					setOpacity(divContainer);
					var closeMiniBio = $$('.bioHide');
					closeMiniBio.addEvent('click', function(e) {
						new Event(e).stop();
						document.body.removeChild(divContainer);
					});
				}
			}).request();
		// Placing the Container
		function setOpacity(el){
			el.style.filter="alpha(opacity:95)";
			el.style.KHTMLOpacity="0.95";
			el.style.MozOpacity="0.95";
			el.style.opacity="0.95";
			}
		function placeContainer(e) {
			var oPOS = findPosition(callBio);
			divContainer.style.top = (oPOS.y + oPOS.height) + "px";
			divContainer.style.left = oPOS.x + "px";
			}
		});
	});
});