var OKB = OKB||{};
var GNM = GNM||{};
var gPg = 0;
var tOut = '';
var inc = 0;
var isArticlePage = (window.location.href.toLowerCase().indexOf('article.aspx')>-1)? true : false;
var isVideosPage = (window.location.href.toLowerCase().indexOf('videos.aspx')>-1)? true : false;
var isCommunityVideosPage = (window.location.href.toLowerCase().indexOf('communityvideos.aspx')>-1)? true : false;

function DoNavigation(urlParam, value)
{
    var newLocation = location.href.replace(new RegExp("([\?|&])("+urlParam+")=[0-9]+(&?)"), "$1$2="+value+"$3");
    if(!(newLocation.match(new RegExp("([\?|&])("+urlParam+")=[0-9]+(&?)")))){
        newLocation = newLocation + "&" + urlParam + "=" + value;
    };
    window.location = newLocation;
} 

function mobileCheck() {
	if (navigator.userAgent.match(/iphone|ipod|lg|samsung|motorola|nokia|iemobile|windows ce|blackberry|android/i)) {
		$('.header').prepend('<div id="BackToMobile"><a href="http://okblitz.com/Mobile.aspx?type=disablebypass">Return to Mobile Site</a></div>');
	}
}

jQuery(function($) {
    // ===== GLOBAL: Auto story rotator =========================
    var options = {
        autoPlayInterval:8000,
        autoPlayInitial:15000
    },
    autoPlayCarousel = function() {
        if ($(".carousel-thumbs li.selected + li:first a").length > 0) {
            $(".carousel-thumbs li.selected + li:first a").click();
            if ($(".carousel-thumbs li.selected").prevAll().length % 4 === 0) {
                //$(".media_thumbs a.next").click();
                $.fn.carousel.animate("next");
            }
            window.carouselTimer = setTimeout(autoPlayCarousel, options.autoPlayInterval);
        } else {
            $(".carousel-thumbs li:first a").click();
            $.fn.carousel.animate("first");
            window.carouselTimer = setTimeout(autoPlayCarousel, options.autoPlayInterval);
        }
    };
    
    $('.rotatorTabs a').click(function(e) {
		var rel = $(e.target).attr('rel');
		if (null != rel) {
			$('.rotatorItems > li').hide();
			$('.rotatorItems > li[rel="' + rel + '"]').show();
			$('.rotatorTabs li').removeClass('current');
			$(e.target).parent().addClass('current');
		}
    });
    
    // ===== GLOBAL: Toggle Input Default Values =========================
    $('input:text').events({
        focus: function() { if (this.value == this.defaultValue) this.value = "" },
        blur: function() { if (this.value == "") this.value = this.defaultValue; }
    });
	// ===== GLOBAL: Trap Enter Key for Search Redirect =========================
	$('#search_form input:text').keydown(function(e){
		if (e.keyCode == 13) {
			eval($('#search_form a').attr('href'));
			e.preventDefault();
		}
	});
	// ===== SEARCH: Trap Enter Key for Search Redirect =========================
	$('#find_team input:text').keydown(function(e){
		if (e.keyCode == 13) {
			eval($('#find_team a:first').attr('href'));
			e.preventDefault();
		}
	});
	
	// ===== SEARCH: Trap Enter Key for Search Redirect =========================
	$('#basic_info input').keydown(function(e){
		if (e.keyCode == 13) {
			eval($('#basic_info a:first').attr('href'));
			e.preventDefault();
		}
	});
	
	// ======= Add Player To Roster Slide-in if user not logged in ====================
	if($("#AddPlayerToRoster").length){
	    $("#AddPlayerToRoster").click(function(e){
			    e.preventDefault();
	            $("#AddPlayerNeedsLogin").slideDown();
	        }
	    );
	}
	
	// ===== TABS: Generic Events =========================
	if($('#tabs').length){
		// Set up tab/container display
		$('#tabs div[id^="tab"]').hide();
		$('#tabs div[id^="tab"]:first').show();
		$('#tabs ul.tabs li:first').addClass('active');
		// Add Click Event
		$('#tabs ul.tabs li a').click(function(){
			$('#tabs ul.tabs li').removeClass('active');
			$(this).parent().addClass('active');
			var currentTab = $(this).attr('href');
			$('"#tabs div[id^="tab"]:visible').hide();
			$(currentTab).show();
			return false;	
		});	
	};
	
	var $HeadlineTabs = jQuery('.tabs').tabs();
	if ( null != $HeadlineTabs )
	{
		$('#tabs-1').show();
		$('#tabs-2').show();
		$('#tabs-3').show();
		var team = ($('#tabs-1 ul li').length > 0);
		var feed = ($('#tabs-3 ul li').length > 0);
		
		if ( feed )	{$HeadlineTabs.tabs('select', 2);}
		else if ( team ){$HeadlineTabs.tabs('select', 0); }
		else {$HeadlineTabs.tabs('select', 1);	}

		if ( !feed ) { $('#feed').hide(); }
		if ( !team ) {	$('#team').hide(); }
	}

	// ===== CAROUSEL: If more than four images =========================
	$('#mediaCarousel').each(function(){
		$('.carousel-thumbs',this).mediaThumbnails();
		$('.carousel-thumbs li a:first',this).click();
		// Begin auto play of carousel items
		if ($("#autoSlideshow").val() !== "false") {
		    window.carouselTimer = setTimeout(autoPlayCarousel, options.autoPlayInitial);
		}
		$(this).carousel();
	});
    
	// ===== DATE/TIME: Format to Relative Time =========================
	if($('.datetimePrettify').length){
		$('.datetimePrettify').each(function(){
			if($(this).text()){
				var date = prettyDate($(this).text());
				$(this).text(date);
			}
		});
	};

    // ===== GLOBAL: Header search button submit need_this form =========================
    $('.generic_button01').click(function(e) {
        if ($(this).parents('form') && $(this).parents('form').attr('method')) {
            e.preventDefault();
            $(this).parents('form').submit();
        }
    });
   
    //  ====== Pagination Events =======================
    $('.page_number ').keyup(function(e) {
        if(e.which==13)
        {
            e.preventDefault();
            $(this).blur(); //Submit the form.
        }
    });
	
    // ===== GLOBAL: Most Popular Links =========================
    $('.popular a').click(function(event) {
        event.preventDefault();
        $('.popular_content').load('/getmostpopular.aspx?time_frame=' + $(this).attr('href'));
        $('.popular a').removeClass('current');
        $(this).addClass('current');
    });
	
    
    /* == GLOBAL: Main Nav == */

    (function($) {

		var
		
		timer,
		
		hideNow = function(speed) {
			clearTimeout(timer);
			$('.header_dropdown:not(:hidden)').stop(true, true).hide(speed);
		},
		
		hideSub = function(e) {
			timer = setTimeout(function() { hideNow('slow'); $('.navbar > ul > li').removeClass('hover'); }, 1000);
		},
		
		holdSub = function(e) {
			clearTimeout(timer);
		},
		
		showSub = function(e) {
			var
			target = $(e.target),
            rel = target.attr('rel');
            if (rel !== "") {
                var
                subnav = $('.header_dropdown.' + rel),
                visibleSub = $('.header_dropdown:visible').length;
                $('.navbar > ul > li').removeClass('hover').find('a[rel="' + rel + '"]').parent().addClass('hover');
                
                clearTimeout(timer);
                if (!!subnav.length && subnav.is(':hidden')) {
                    hideNow(0);
                    if (visibleSub === 0) {
                        subnav.show('fast');
                    } else {
                        subnav.show();
                    }
                }
            }
		},
		
		init = function() {
			$('.navbar li a')
				.bind('mouseover', showSub)
				.bind('mouseout', hideSub);
			$('.header_dropdown')
				.bind('mouseover', holdSub)
				.bind('mouseout', hideSub);
		};
		
		$(document).ready(init);
		
	})(jQuery);

    
    // ========================== Code that generates play icon over lay utilizes the make_play class

    if ($('.make_play').length) {
        $('.make_play').wrap('<div></div>');
        $('.make_play').parent().prepend('<div class="play_over">&nbsp;</div>');
    };

    // ========================= Checks for the default defined max number of pages
    if ($('.mpgs').length) {
        $('.comment_pagination').find('.maxPages').text($('.mpgs').text());
    };

    // ========================= Customer Select Box Code
    // INIT
    //$('.customDropDown').selectbox();
    if ($('#class').length) $('#class').selectbox();
    if ($('#week').length) $('#week').selectbox();
    if ($('#year').length) $('#year').selectbox();
    if ($('#conference').length) $('#conference').selectbox();
    if ($('#division').length) $('#division').selectbox();
    
    
    // RELOAD ON SELECT    
    if ($('#class').length) $('#class_container ul li').events({ click: function() { window.location = '?class=' + $(this).text(); } });
    if ($('#week').length) $('#week_container ul li').events({ click: function() { window.location = '?week=' + $(this).text(); } });
    if ($('#year').length) $('#year_container ul li').events({ click: function() { window.location = '?year=' + $(this).text(); } });

    // ======================== REMOVE A FRIEND
    $("a[href='remove_friend']").click(function(e) { e.preventDefault(); $('.sure_delete:visible').fadeOut(); $(this).parents('tr').find('.sure_delete').fadeIn('normal') });

    // REMOVE A FRIEND CANCEL
    $("a[href='cancel_remove']").click(function(e) { e.preventDefault(); if ($(this).parents('.sure_delete').is(':visible')) $(this).parents('.sure_delete').fadeOut('normal') });

    // COMPLETE REMOVE A FRIEND
    $("a[href='remove_them']").click(function(e) { e.preventDefault(); $.ajax({ type: "GET", url: $("a[href='remove_them']:visible").attr('id'), success: function() { $("a[href='remove_them']:visible").parents('.sure_delete').fadeOut('normal', function() { $(this).parents('tr').fadeOut('slow'); var fCount = document.getElementById('ctl00_ContentPlaceHolder1_lblFriendscount'); fCount.innerHTML = fCount.innerHTML - 1; }) } }); });

    // ======================== INVITE FRIENDS
    $("a[href='invite_friends']").unbind('click');
    $("a[href='invite_friends']").click(function(e) {
        e.preventDefault();
        var $valid = 'f';
        for (i = 1; i <= 5; i++) {
            if ($(this).parents('form').find('input[name=\'friend_email' + i + '\']').attr('value') != '') if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($(this).parents('form').find('input[name=\'friend_email' + i + '\']').attr('value')) == false) { $(this).parents('form').find('input[name=\'friend_email' + i + '\']').addClass('notvalid'); $valid = false; } else { $(this).parents('form').find('input[name=\'friend_email' + i + '\']').removeClass('notvalid'); if ($valid != false) { $valid = true; } }
        }

        if ($valid == true) { $(this).parents('form').submit(); }
        else { $('.novalid:hidden').fadeIn(); }
    });

    //==================Validation of SiteSection selection on community content      
    $(".add_blog_buttons input.generic_button_square, a.uploadAlbumPhoto").click(function(e) {
		
		var hasSelection = false;
		$(".SiteSectionSelectionFS input:checked:first").each(function(){
		    hasSelection=true;
		    return;
		});		
		
		if(!hasSelection)
		{
		    $("#SiteSectionSelectionErrorDiv").slideDown();
		    e.preventDefault();
		}
    });

	//=======================Add Favorite
	$("a[href='add_favorite']").click(function(e) { e.preventDefault(); $.ajax({ type: "GET", url: $(this).attr('id'), success: function() {  } }); var s=$(this).attr('id'); if($(this).text() == 'Add to My OKBlitz'){$(this).text("Remove from My OKBlitz");$(this).attr('id',s+'&flag=0');} else {$(this).text("Add to My OKBlitz");$(this).attr('id',s.replace('&flag=0',''));} });
	
	//=======================Add Flagging
	$("a[href='add_flag']").click(function(e) { e.preventDefault(); $.ajax({ type: "GET", url: $(this).attr('id'), success: function() {  } });  });


    $("a[href='popup_add_photo_link']").click(function(e) {
		e.preventDefault();
		inc++;
		$('.popup_add_photo:visible').fadeOut('fast');
		$('.popup_edit_album:visible').fadeOut('fast');
		$('.popup_delete:visible').fadeOut('fast');
		$('.popup_add_photo').find("input[type='hidden']").attr('value', $(this).parents('.photo_album_sidebar').find('.photo_id').text());
		$('#add_photo_form').attr('target', 'iframer' + inc);
		$('.popup_add_photo').append('<iframe name="iframer' + inc + '" id="iframer' + inc + '" style="display: none;"></iframe>');
		$('.popup_add_photo').fadeIn();
    });

    $('#add_photo_form').submit(function() { $(this).parent().fadeOut(); });

    $("a[href='popup_edit_album_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_edit_album:visible').fadeOut('fast');
        $('.popup_delete:visible').fadeOut('fast');
        $('.popup_add_photo:visible').fadeOut('fast');
        $('.popup_edit_album').find("input[type='hidden']").attr('value', $(this).parents('.photo_album_sidebar').find('.photo_id').text());
        $('.popup_edit_album').find("input[type='text']").attr('value', $(this).parents('.photo_album_sidebar').find('.albumTitle').text());
        $('.popup_edit_album').find("textarea").val($(this).parents('.photo_album_sidebar').find('.albumDescription').text());
        $('#edit_album_form').attr('target', 'iframer');
        $('.popup_edit_album').append('<iframe name="iframer' + inc + '" id="iframer' + inc + '" style="display: none;"></iframe>');
        $('.popup_edit_album').fadeIn();
    });

    $('#edit_album_form').submit(function() { $(this).parent().fadeOut(); });

    $("a[href='popup_delete_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_delete:visible').fadeOut('fast');
        $('.popup_add_photo:visible').fadeOut('fast');
        $('.popup_edit_album:visible').fadeOut('fast');
        $('.popup_delete').find("input[type='hidden']").attr('value', $(this).parents('.photo_album_sidebar').find('.photo_id').text());
        $('#delete_form').attr('target', 'iframer');
        $('.popup_delete').append('<iframe name="iframer' + inc + '" id="iframer' + inc + '" style="display: none;"></iframe>');
        $('.popup_delete').fadeIn();
    });

    $('#delete_form').submit(function() { $(this).parent().fadeOut(); });

    $('.popup_delete a[title=\'cancel\']').unbind('click');
    $('.popup_delete a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_delete:visible').fadeOut('fast'); });

    $('.popup_edit_album a[title=\'cancel\']').unbind('click');
    $('.popup_edit_album a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_edit_album:visible').fadeOut('fast'); });

    $('.popup_add_photo a[title=\'cancel\']').unbind('click');
    $('.popup_add_photo a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_add_photo:visible').fadeOut('fast'); });




    $("a[href='popup_delete_photo_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_delete_photo:visible').fadeOut('fast');
        $('.popup_edit_photo:visible').fadeOut('fast');
        $('.popup_delete_photo').fadeIn();
    });


    $("a[href='popup_delete_video_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_delete_video:visible').fadeOut('fast');
        $('.popup_edit_video:visible').fadeOut('fast');
        $('.popup_delete_video').fadeIn();
    });
    
    $("a[href='popup_edit_photo_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_edit_photo:visible').fadeOut('fast');
        $('.popup_delete_photo:visible').fadeOut('fast');
        $('.popup_edit_photo').find("input[type='text']").attr('value', $(this).parents('.gallery_scroll').find('h2').text());
        $('.popup_edit_photo').find("textarea").attr('value', $(this).parents('.gallery_scroll').find('.description').text());
        $('.popup_edit_photo').fadeIn();
    });
    
	var flag = $("a[href='popup_add_flag_link']").click(function(e) {
		$('.popup_add_flag:visible').fadeOut('fast');  
		$('.popup_add_flag').eq(flag.index(this)).fadeIn();
		e.preventDefault();
	});
    
    $('.popup_add_flag a[title=\'cancel\']').unbind('click');
    $('.popup_add_flag a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_add_flag:visible').fadeOut('fast'); });


    $('.popup_delete_photo a[title=\'cancel\']').unbind('click');
    $('.popup_delete_photo a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_delete_photo:visible').fadeOut('fast'); });

    $('.popup_edit_photo a[title=\'cancel\']').unbind('click');
    $('.popup_edit_photo a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_edit_photo:visible').fadeOut('fast'); });

    $('.popup_delete_video a[title=\'cancel\']').unbind('click');
    $('.popup_delete_video a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_delete_video:visible').fadeOut('fast'); });


    $("a[href='popup_add_community_photo_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_add_photo:visible').fadeOut('fast');
        $('.popup_add_photo').find("input[type='hidden']").attr('value', $(this).parents('.photo_album_sidebar').find('.photo_id').text());
        $('.popup_add_photo').fadeIn();
    });
    
    $("a[href='popup_add_community_video_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_add_video:visible').fadeOut('fast');
        $('.popup_add_video').find("input[type='hidden']").attr('value', $(this).parents('.photo_album_sidebar').find('.photo_id').text());
        $('.popup_add_video').fadeIn();
    });
    
    $('.popup_add_video a[title=\'cancel\']').unbind('click');
    $('.popup_add_video a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_add_video:visible').fadeOut('fast'); });

    $('.popup_add_photo a[title=\'cancel\']').unbind('click');
    $('.popup_add_photo a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_add_photo:visible').fadeOut('fast'); });

    $("a[href='popup_edit_video_link']").click(function(e) {
        e.preventDefault();
        inc++;
        $('.popup_edit_video:visible').fadeOut('fast');
        $('.popup_delete_video:visible').fadeOut('fast');
        $('.popup_edit_video').find("input[type='text']").attr('value', $(this).parents('.gallery_scroll').find('h2').text());
        $('.popup_edit_video').find("textarea").attr('value', $(this).parents('.gallery_scroll').find('.description').text());
        $('.popup_edit_video').fadeIn();
    });
    
    $('.popup_edit_video a[title=\'cancel\']').unbind('click');
    $('.popup_edit_video a[title=\'cancel\']').click(function(e) { e.preventDefault(); $('.popup_edit_video:visible').fadeOut('fast'); });
});
// ///////////////////////////////////////////////////////////////////////////////////////////////////////

function loadVideoPlayer(media,image,playPreRoll)
{
	if ( playPreRoll == 'true' )
	{
		loadVideoPlayerEx(media, image, 
							"http://ad.doubleclick.net/pfadx/okblitz.video/index;tile=2;sz=400x300;ord=", 
							"http://ad.doubleclick.net/adi/okblitz.video/index;tile=3;sz=300x250;ord=");
	}
	else
	{
		loadVideoPlayerEx(media, image, "", "");
	}
}
function loadVideoPlayerEx(media,image,videoRreRoll,videoCompanion) {
	var file = ""
	var streamer = "";
	if(media.indexOf("rtmp://") > -1){ 
		streamer = media.substr(0,media.lastIndexOf("/")+1);
		file = media.substr(media.lastIndexOf("/")+1,media.toString().length);
	} else if(media.indexOf("http://") > -1){
		file = media;
	} else {
		file = media;
	};
	var autostart = "true";
	if(isVideosPage && ($.param('cid','',null) == null)){
		autostart = "false";
	} else if(isCommunityVideosPage){
		autostart = "false";	
	}
	var strFlashvars = [
		"&file="+file,
		"&image="+image,
		"&type="+((streamer == "rtmp://isocentric.fc.llnwd.net/isocentric/okblitz/")? "fcsubscribe" : ""),
		"&streamer="+streamer,
		"&skin="+encodeURIComponent("/flash/skin.swf"),
		"&config="+encodeURIComponent("/flash/config.xml"),
		"&autostart="+autostart
	];
	
	var dart = "", companion = "";
	var playPreRoll = false;
	var ord = ""; //Math.random()*10000000000000000;
	if(videoRreRoll.length)
	{
		if ( videoRreRoll.substring(0,4).toLowerCase() == 'http' )
		{
			dart = videoRreRoll + ord + "?";
			playPreRoll = true;
		}
	};
	if(videoCompanion.length)
	{
		if ( videoCompanion.substring(0,4).toLowerCase() == 'http' )
		{
			companion = "&dcinstream.ad.companion="+encodeURIComponent(videoCompanion + ord + "?");
		}
	};

	var strPreRoll = [
		"&plugins=dcinstream",
		"&dcinstream.ad.position=pre",
		"&dcinstream.ad.tag="+encodeURIComponent(dart),
		"&dcinstream.ad.target=videocompanion",
		companion
	];
	
	var aFlashvars = playPreRoll ? strFlashvars.concat(strPreRoll) : strFlashvars;
	
	var flashvars = {};
	var params = {};
	params.allowfullscreen = "true";
	params.allowscriptaccess = "always";
	params.wmode = "transparent";
	params.flashvars = aFlashvars.join('')
	var attributes = {};
	swfobject.embedSWF("/flash/player-licensed.swf", "preview", "576", "324", "9.0.0", false, flashvars, params, attributes);
};
// DART: Call from video pre-roll to display companion ad.
function syncRoadBlock(tgtId, adTag) {
	document.getElementById(tgtId).innerHTML = '<iframe src="' + adTag + '" id="ifr_companion" width=300 height=250 marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}


// ///////////////////////////////////////////////////////////////////////////////////////////////////////

// ===== MEDIA MODULE: Format Thumbnails ==================== 
(function($) {
	// ===== GLOBAL: Parse Querystring =====
	$.param = function(name, href, defaultvalue) {
		var exp = new RegExp('[\\?&]' + name + '=([^&#]*)');
		var param = exp.exec((href) ? href : window.location.href);
		return (param) ? param[1] : defaultvalue;
	};
	$.fn.mediaThumbnails = function(options){
		// extend our default options with those provided
		var $options = $.extend({}, $.fn.mediaThumbnails.defaults, options);

		return this.each(function() {
			var $this = $(this);
			// ~~~~~ cache elements ~~~~~
			var aThumbs = $('li a',this);
			var media = $('#mediaContainer');
			var display = $('.display',media);
			var caption = $('.caption',media);
			//
			for(var x = 0, xl = aThumbs.length; x < xl; ++x){
				// ~~~~~ cache elements ~~~~~
				var thumb = aThumbs[x];
				var img = $('img',thumb);
				var data = {
					'href': $(thumb).attr('href'),
					'type': $(thumb).attr('class'),
					'image': $(img).attr('alt'),
					'title': $(img).attr('title'),
					'caption': $(img).attr('longdesc'),
					'date': $('cite',thumb).text()
				};
				$(thumb).data('info',data);
				// ~~~~~ add captions ~~~~~
				$(thumb).append($('<span class="caption" title="'+data.title+'"><span>'+data.title+'</span></span>'));
				// ~~~~~ if video, add play btn ~~~~~
				if($(thumb).hasClass('video')){
					$(thumb).append($('<span class="video"></span>'));
					$('.video',$(thumb)).css('opacity','0').fadeTo(750,0.5);
				};
				// ~~~~~ scale thumbnail to fit ~~~~~
				$(img).load(function(){
					var scale = scaleRatio($(this).width(),$(this).height(),$options.thumbMaxWidth,$options.thumbMaxHeight, 'scaleToFill');
					$(this).css({'width':scale.width,'height':scale.height}).fadeIn(350);
					return false;
				});
				//
				$(thumb).click(function(){
                    clearTimeout(window.carouselTimer);
					if(!$(this).parent('li.selected').length){
						aThumbs.parent('li.selected').removeClass('selected');
						$(this).parent('li').addClass('selected');
						//
						displayMainImage($(this).data('info'));
					};
					return false;					 
				});
			};
			
			// ===== Format Large Image =====
			function displayMainImage(data){
				// ~~~~~ reset display ~~~~~
				$('.video',media).remove();
				// ~~~~~ add caption ~~~~~
				caption.empty().html( ((data.date == '') ? '' : '<small>'+prettyDate(data.date)) + '</small>' + '<h1>'+data.title+'</h1><p>'+data.caption+'</p>' + ((data.href == '#') ? '' : '<a href="'+data.href+'">FULL STORY</a>'));
				if(isArticlePage)
				{
				    if(data.title.length>0 || data.caption.length>0)
				    {
				        caption.stop().css('bottom', 0);
				    }
				    else
				    {
				        caption.stop().css('bottom', caption.outerHeight()*-1);
				    }
				}
				else
				{
				    caption.stop().css('bottom', caption.outerHeight()*-1);
				}
				// ~~~~~ large image ~~~~~
				display.empty().html('<span><img src="'+data.image+'" border="0" alt="" /></span>');
				$('img', display).load(function(){
					var scale = scaleRatio($(this).width(),$(this).height(),$options.largeMaxWidth,$options.largeMaxHeight, 'scaleToFit');
					$(this).css({'width':scale.width,'height':scale.height}).fadeIn(500,
						function(){
							caption.stop().animate({ 'bottom':'0px' }, 750, 'easeInOutCirc');
						});
					return false;
				});
				// ~~~~~ if video, add play btn ~~~~~
				if(data.type == 'video'){
					$(media).append($('<div class="video"></div>'));
					$('.video',media).css('opacity','.01').fadeTo(500,0.5);
				};
				if(isArticlePage && (data.href.indexOf('.flv') > -1)){
					embedVideoPlayer(data.href, data.image);
				} else {
					// ~~~~~ update based on HREF ~~~~~
					$(media).unbind("click").click(function(){								
						if(data.href.indexOf('rtmp://isocentric.fc.llnwd.net/isocentric/okblitz/') > -1){
							var articleID = data.href.substr(data.href.lastIndexOf('#')+1).split('=')[1];
							var streamID = data.href.substring(data.href.lastIndexOf('/')+1,data.href.lastIndexOf('#'));
							$('<a href="PopVideoPlayer.aspx?ID='+articleID+'&stream='+streamID+'" class="hide"></a>').popupWindow({
								windowName:'LiveVideoWindow',
								width:606,
								height:520, 
								centerBrowser:1
							}).click();
						} else if(data.href.indexOf('.flv') > -1){
							$(media).unbind("click");
							embedVideoPlayer(data.href, data.image);
						} else {
							if(isArticlePage){
								$(media).unbind('click')
							} else {
								document.location.href = data.href;
							};
						};
						return false;
					});
				};
				if(!isArticlePage || (data.href.indexOf('.flv') > -1)){
					$(media).css('cursor','pointer');
				} else {
					$(media).css('cursor','default');
				};
			};
			
			// ===== Embed Video Player =====
			function embedVideoPlayer(video,image){
				var media, streamer, dart = "", companion = "";
				var type = "video";
				// ~~~~~ reset display ~~~~~
				caption.stop().css('bottom',caption.outerHeight()*-1);
				display.empty().html('<span><span id="videoPlayer"></span></span>');
				$('div.video',media).remove();
				// ~~~~~ parse video path ~~~~~
				if(video.indexOf('rtmp:') > -1) {
					streamer = video.substr(0,video.lastIndexOf("/")+1);
					var file = video.substr(video.lastIndexOf("/")+1,video.toString().length);
					if(streamer == "rtmp://isocentric.fc.llnwd.net/isocentric/okblitz/"){
						type = "fcsubscribe";
					} else if(file.toLowerCase().indexOf('.flv') > -1){
						type = "";
					};
				} else {
					file = video;	
				};
				
				var strFlashvars = [
					"&controlbar=over",
					"&screencolor=2d2d2d",
					"&autostart=true",
					"&skin="+encodeURIComponent("flash/skin.swf"),
					"&file="+encodeURIComponent(file),
					"&image="+encodeURIComponent(image),
					"&streamer="+encodeURIComponent(streamer),
					"&type="+type
				];
				
				var ord = ""; //Math.random()*10000000000000000;
				
				if($('#PrerollVideo').length)
				{
					if ( $('#PrerollVideo').text().substring(0,4).toLowerCase() == 'http' )
					{
						dart = $('#PrerollVideo').text() + ord + "?";
					}
				};
				if($('#PrerollCompanion').length)
				{
					if ( $('#PrerollCompanion').text().substring(0,4).toLowerCase() == 'http' )
					{
						companion = "&dcinstream.ad.companion="+encodeURIComponent($('#PrerollCompanion').text() + ord + "?");
						//alert ( companion );
						//alert ( $('#PrerollCompanion').text() + ord + "?" );
					}
				};

				var strPreRoll = [
					"&plugins=dcinstream",
					"&dcinstream.ad.position=pre",
					"&dcinstream.ad.tag="+encodeURIComponent(dart),
					"&dcinstream.ad.target=videocompanion",
					companion
				];
				var aFlashvars = strFlashvars.concat(strPreRoll)
				
				// load the video player
				if (swfobject.hasFlashPlayerVersion("9.0.0")) {
					var att = { data:"flash/player-licensed.swf", width:"576", height:"324", menu:"false", id:"oeVideoPlayer", name:"oeVideoPlayer" };
					var par = { wmode:"transparent", swliveconnect:"true", allowScriptAccess:"always", bgcolor:"#000000", flashvars: aFlashvars.join('') };
					var id = "videoPlayer";
					var so = swfobject.createSWF(att, par, id);
				} else {
					$('videoPlayer').set('html', '<h2>Please <a href="http://www.adobe.com/products/flashplayer/" target="blank">upgrade your Flash Player</a><br /> to experience this site to its fullest.</h2>');
				};
			};
			$(window).load(function(){
				if(isArticlePage) $(media).click();
			});
		});
	};
	// default option
	$.fn.mediaThumbnails.defaults = {
		thumbMaxWidth: 115,
		thumbMaxHeight: 65,
		largeMaxWidth:576,
		largeMaxHeight:324
	};
})(jQuery);

// ===== MEDIA MODULE: Carousel Navigation ==================== 
(function($) {
	$.fn.carousel = function(options){
	
		// extend our default options with those provided
		var
		$options = $.extend({}, $.fn.carousel.defaults, options),
		animate = function (dir){
			var p = 0;
			switch (dir) {
			    case "next":
				    $options.current = ($options.current >= $options.total) ? $options.total : $options.current+1;
				    break;
                case "prev":
				    $options.current = ($options.current <= 0) ? 0 : $options.current-1;
				    break;
                case "first":
                    $options.current = 0;
			};
			
			// Check and update arrow states
		    if ($options.current <= 0) {
		        $(".media_thumbs a.previous").addClass('disabled');
		    } else {
		        $(".media_thumbs a.previous").removeClass('disabled');
		    }
		    if ($options.current >= $options.total) {
		        $(".media_thumbs a.next").addClass('disabled');
		    } else {
		        $(".media_thumbs a.next").removeClass('disabled');
		    }
			
			p = ($options.current*$options.visibleWidth*-1);
			$($options.container).stop().animate({ left: p }, {queue:false, duration:500});
		};
        
        $.fn.carousel.animate = animate;
        
		this.each(function() {
			var $this = $(this);
			var itemsVisible = 4;
			$options.container = $('.media_thumbs ul',$this);
			$options.thumbs = $('a',$options.container);
			if($options.thumbs.length < 2){
				$this.css('display','none');
			} else if($options.thumbs.length <= itemsVisible){ // == no carousel ==
				$('a.previous,a.next', $this).css({'opacity':'0.35','cursor':'default'}).click(function(e){e.preventDefault()});
				$this.css('display','block');
			} else { // == enable carousel ==
				// parameters
				$this.css('display','block');
				var itemSize = $($options.thumbs[0]).outerWidth();
				var itemsTotal = $options.thumbs.length+1;
				$options.visibleWidth = $('div.carousel-thumbs', $this).outerWidth()+5;
				$options.container.css('width',((itemsTotal*itemSize)+itemSize)+'px');
				var pageSize = Math.floor($options.visibleWidth / itemSize);
				var pageTotal = ((itemsTotal-1)%pageSize==0)?itemsTotal:(pageSize-(itemsTotal%pageSize)+itemsTotal);
				$options.total = Math.floor(pageTotal / pageSize)-1;

				// controls
				$this.find("a.previous").addClass('disabled');
				$this.find("a.next").click(function(){
					clearTimeout(window.carouselTimer);
					animate("next");
					return false;
				});
				$this.find("a.previous").click(function(){
				    clearTimeout(window.carouselTimer);
					animate("prev");
					return false;
				});
			};
		});
		
	};

	// default option
	$.fn.carousel.defaults = {
		container: null,
		thumbs: null,
		visibleWidth:0,
		current: 0,
		total: 0
	};
})(jQuery);


// ///////////////////////////////////////////////////////////////////////////////////////////////////////
// ===== HELPER: Bind Events =========================
jQuery.fn.events = function(o) {
    for (var i in o) {
        this.bind(i, o[i]);
    };
    return this;
};

// ===== HELPER: Find Flash Movie =====
function getFlashMovie(movieName) {
	var isIE = ((navigator.appName.indexOf("Microsoft") != -1) && (parseFloat(navigator.appVersion.split("MSIE")[1])<7));
	return (isIE) ? window[movieName] : document[movieName];
};

// ===== HELPER: Scale Image Proportionally =====
function scaleRatio(imgW,imgH,maxW,maxH,mode){
	var width,height;
	var dx = (maxW / imgW);
	var dy = (maxH / imgH);
	if(mode == 'scaleToFill'){
		ratio  = dx > dy ? dx : dy;
	} else {
		ratio  = dx < dy ? dx : dy;	
	};
	// keep aspect ratio
	width  = Math.floor(imgW * ratio);
	height = Math.floor(imgH * ratio);
	return {width:width,height:height}
}

// ===== HELPER: Relative Date Format =====
/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 )//|| day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
		Math.floor( day_diff / 31 ) + " months ago";
};

// Show the comments when requested
function showOkBlitzTab( tabBase, index )
{
	var $videoTabs = jQuery(tabBase).tabs();
	if ( null != $videoTabs )
	{
		$videoTabs.tabs('select', index);
	}
};

// Highschools page
GNM.HighSchool = (function() {
	var
	options = {
		itemsPerPage:64,
		rowsPerPage:16,
		rowCount:0, // Internally used counters
		currentPage:0,
		numPages:0
	},
	popular = [],
	all = [],
	readListLinks = function(id) {
		var retVal = [];
		$("#" + id + " a").each(function() {
			retVal.push({"title":$(this).text(), "href":$(this).attr("href")});
		});
		return retVal;
	},
	buildTable = function(id, source) {
		var
		out = '<table id="' + id + '" class="schoolList"><tr class="odd first">',
		odd = true,
		first = false,
		rowCount = 0;
		
		for (var i = 0, max = source.length; i < max; i++) {
			first = (i % 4 === 0);
			if (first && i > 0) {
				odd = !odd;
				out += '</tr><tr class="' + (odd ? "odd" : "even") + '">';
				rowCount++;
			}
			out += '<td' + (first ? ' class="first"' : '') + '><a href="' + source[i].href + '">' + source[i].title + '</a></td>';
		}
		out += '</tr></table>';
		options.rowCount = rowCount + 1;
		
		$("#" + id).replaceWith(out);
		$("#" + id).find("tr:gt(" + (options.rowsPerPage - 1) + ")").hide();

	},
	pageClick = function (e) {
		switch ($(e.target).attr("rel")) {
			case "prev":
				if (options.currentPage > 0) {
					options.currentPage--;;
				} else {
					return;
				}
				break;
			case "next":
				if (options.currentPage < options.numPages - 1) {
					options.currentPage++;
				} else {
					return;
				}
				break;
		}
		
		$("#allSchools tr").hide();
		$("#allSchools tr:gt(" + (options.currentPage * options.rowsPerPage) + ")").show();
		$("#allSchools tr:gt(" + ((options.currentPage + 1) * options.rowsPerPage) + ")").hide();
		$("#schoolPagination strong").html(options.currentPage + 1);
		
		$("#schoolPagination .disabled").removeClass("disabled");
		if (options.currentPage === 0) { $("#schoolPagination a[rel='prev']").addClass("disabled") };
		if (options.currentPage >= options.numPages - 1) { $("#schoolPagination a[rel='next']").addClass("disabled") };
		
	},
	letterClick = function (e) {
		if ($(e.target).hasClass("disabled")) { return; }
		var
		letter = $(e.target).text(),
		out = [];
		if (letter == "All") {
			out = all;
		} else {
			for (var i = 0, max = all.length; i < max; i++) {
				if (all[i].title.substr(0, 1) == letter) {
					out.push(all[i]);
				}
			}
		}
		buildTable("allSchools", out);
		buildPagination();
	},
	searchEvent = function (e) {
		var
		exp = new RegExp($(e.target).val(), "gi"),
		out = [];
		for (var i = 0, max = all.length; i < max; i++) {
			if (exp.test(all[i].title)) {
				out.push(all[i]);
			}
		}
		buildTable("allSchools", out);
		buildPagination();
	},
	buildPagination = function () {
		options.numPages = Math.ceil(options.rowCount / options.rowsPerPage);
		options.currentPage = 0;
		$("#schoolPagination").remove();
		var out = '<div id="schoolPagination"><a href="javascript:void(0);" class="pageNav disabled" rel="prev">Previous</a><strong>' + (options.currentPage + 1) + '</strong> of ' + options.numPages + '</strong><a href="javascript:void(0);" class="pageNav" rel="next">Next</a></div>';
		$("#allSchools").after(out);
		$(".pageNav").click(pageClick);
	},
	buildSearch = function() {
		var
		out = '<div id="searchTools"><ul id="schoolLetters"><li><a href="javascript:void(0);" rel="all">All</a></li><li>-</li>',
		c = "";
		for (var i = 65; i < 91; i++) {
			if ($("#allSchools a:contains(" + String.fromCharCode(i) + ")").length == 0) {
				c = "disabled";
			} else {
				c = "";
			}
			out += '<li><a href="javascript:void(0);" class="' + c + '">' + String.fromCharCode(i) + '</a></li>';
		}
		out += '</ul><div id="schoolSearch"><input type="text" /></div></div>';
		$("#allSchools").before(out);
		$("#schoolLetters a").click(letterClick);
		$("#schoolSearch input").keyup(searchEvent);
		$("#schoolSearch input").focus(function(e) { $("#schoolSearch input").addClass("focus"); });
		$("#schoolSearch input").blur(function(e) { $("#schoolSearch input").removeClass("focus"); });
	},
	init = function() {
		var s = (new Date()).getTime();
		popular = readListLinks("mostPopularSchools");
		all = readListLinks("allSchools");
		buildTable("mostPopularSchools", popular);
		buildTable("allSchools", all);
		buildPagination();
		buildSearch();
		//alert((new Date()).getTime() - s);
	};
	
	return { init:init };

})();

GNM.dontMissScroller = (function() {

	var
	opt = {
		itemsPerPage:3,
		pages:null,
		currentPage:null,
		itemWidth:null
	},
	buttonStates = function() {
		if (0 == opt.currentPage) {
			$('.dontMissScroller a[rel="back"]').css('opacity', 0.2).addClass('disabled');
		} else {
			$('.dontMissScroller a[rel="back"]').css('opacity', 1).removeClass('disabled');
		}
		
		if (opt.currentPage >= opt.pages - 1) {
			$('.dontMissScroller a[rel="next"]').css('opacity', 0.2).addClass('disabled');
		} else {
			$('.dontMissScroller a[rel="next"]').css('opacity', 1).removeClass('disabled');
		}
	},
	buttonEvent = function(e) {
		
		switch ($(e.target).attr('rel')) {
			case 'back':
				if (opt.currentPage > 0) {
					gotoPage(--opt.currentPage);
				}
				break;
			case 'next':
				if (opt.currentPage < opt.pages - 1) {
					gotoPage(++opt.currentPage);
				}
			default:
				break;
		}
		
		buttonStates();
		
	},
	gotoPage = function(page) {
	
		var
		x = page * opt.itemWidth * -opt.itemsPerPage;
		if ((page + 1) * opt.itemsPerPage > $('.dontMissScroller li').length) {
			x = ($('.dontMissScroller li').length - opt.itemsPerPage) * -opt.itemWidth;
		}
		$('.dontMissScroller .container ul').stop().animate({left:x + 'px'});
	
	},
	init = function() {
		
		var
		$items = $('.dontMissScroller ul li'),
		count = $items.length;
		if (count > 2) {
			opt.itemWidth = $items.outerWidth() + 10;
			opt.pages = Math.ceil(count / opt.itemsPerPage);
			opt.currentPage = 0;
			$('.dontMissScroller ul').width(opt.itemWidth * count);
			$('.dontMissScroller a.control').bind('click', buttonEvent);
		}
		buttonStates();
		
	};
	
	$(document).ready(init);

})();

(function() {
	
	var
	defaultSportId = 6,
	config = {
		iframed:(String(window.location).indexOf("ticker") != -1),
		loader:"/images/ticker_load.gif",
		defaultSporId:6,
		startSportId:null
	},
	
	formatDate = function(s) { // Expects ISO Date/Time
		s = s.replace("T", " ").split(" ");
		var d = s[0].split("-");
		var t = s[1].split(":");
		return new Date(d[0],d[1] - 1,d[2],t[0],t[1],t[2]);
	},
	
	formatTime = function(d) {
		var h = d.getHours();
		var m = d.getMinutes();
		var s = "AM";
		if (("" + m).length == 1) { m = "0" + m; }
		if (h >= 12) { h -= 12; s = "PM"; }
		if (h === 0) { h = 12; }
		return h + ":" + m + " " + s;
	},
	
	events = function(e) {
		
		$("#overlay").hide();
		$(".selected").removeClass("selected");
		
		var
		divisionEvent = function(e) {
			dropDowns.loadDivision($(e.target).attr("rel"));
			$("#sports").hide(); $("#divisions").hide();
		},
		
		dropdownEvent = function(e) {
			var r = $(e.target).attr("rel"), l = $("#" + r);
			if (l.css("display") == "none") {
				$("#sports").hide(); $("#divisions").hide();
				var p = $(e.target).position();
				var h = $(e.target).outerHeight();
				$("#dropdowns [rel='" + r + "']").addClass("selected"); $("#dropdowns ." + r).addClass("selected");
				l.css({left:p.left,top:p.top + h}).show();
				$("#overlay").show();
			} else {
				l.hide();
			}		
		},
		
		controlEvent = function() {
			if (slider.info.count < slider.info.display) { return; }
			var r = $(e.target).attr("rel");
			if (r != "prev" && r != "next") { return; }
			switch (r) {
				case "prev":
					if (slider.info.current > 0) { slider.info.current -= slider.info.display; }
					break;
				case "next":
					if (slider.info.current < slider.info.count - slider.info.display) { slider.info.current += slider.info.display; }
					break;
			}
			if (slider.info.current <= 0) { $("a[rel='prev']").addClass("disabled"); slider.info.current = 0; } else { $("a[rel='prev']").removeClass("disabled"); }
			if (slider.info.current + slider.info.display > slider.info.count- 1) { $("a[rel='next']").addClass("disabled"); slider.info.current = slider.info.count - slider.info.display; } else { $("a[rel='next']").removeClass("disabled"); }
			$("#tickerWrap ul").stop().animate({left:(slider.info.current * slider.info.width * -1) + "px"});	
		};
		
		if ($(e.target).parent().hasClass("link")) {
			window.top.location.href = ($(e.target).parent().attr("rel"));
		}
		
		switch ($(e.target).attr("class")) {
			case "division":
				divisionEvent(e);
				break;
			case "sport":
				dropDowns.loadSport($(e.target).attr("rel"));
				$("#sports").hide(); $("#divisions").hide();
				break;
			case "dropdown sport":
			case "dropdown division":
				dropdownEvent(e);
				break;
			case "link":
			case "score link":
				window.top.location.href = ($(e.target).parent().attr("rel"));
				break;
			case "control":
				controlEvent(e);
				break;
			default:
				$(".selected").removeClass("selected");
				$("#divisions").hide();
				$("#sports").hide();
		}
		
	},
	
	dropDowns = {
		divisions:[], sports:[],
		links:{"College Football":"/CollegeScoreboard.aspx?id=2125","College Baseball":"/CollegeScoreboard.aspx?id=2191","College Basketball":"/CollegeScoreboard.aspx?id=2192","National Basketball Association":"/CollegeScoreboard.aspx?id=3456","Womens College Basketball":"/CollegeScoreboard.aspx?id=2385","Womens College Softball":"/CollegeScoreboard.aspx?id=2385",	"High School Football":"/scoreboard.aspx?id=1719","High School Basketball":"/scoreboard.aspx?id=2123","Womens High School Basketball":"/scoreboard.aspx?id=2124"},
		init:function() {
			dropDowns.initSports();
		},
		initSports:function() {
			var url = config.iframed ? "/proxy/?url=http%3A%2F%2Fwww.okblitz.com%2Fscheduleprocessor.aspx%3Ftype%3Dsport" : "/scheduleprocessor.aspx?type=sport";
			$.ajax({
				url:url,
				dataType:"xml",
				success:function(data) {
					var out = "";
					$(data).find("Sport").each(function() {
						var id = parseInt($(this).attr("SportTypeId"), 10);
						switch (id) {
							case 1:
							case 3:
							case 4:
							case 5:
							case 6:
							case 7:
							case 8:
								var title = $(this).attr("Title"), abbr = $(this).attr("Abbrev");
								if (config.startSportId == id) { config.startSportId = title; }
								dropDowns.sports[id] = {"abbr":abbr, "title":title};
								out += '<li><a href="javascript:void(0);" class="sport" rel="' + id + '">' + $(this).attr("Title") + '</a></li>';
						}
					});
					$("#sports").html(out);
					dropDowns.initDivisions();
				}
			});		
		},
		initDivisions:function() {
			var url = config.iframed ? "/proxy/?url=http%3A%2F%2Fwww.okblitz.com%2Fscheduleprocessor.aspx%3Ftype%3Ddivision" : "/scheduleprocessor.aspx?type=division";
			$.ajax({
				url:url,
				dataType:"xml",
				success:function(data) {
					var ls = "", ld = 0;
					$(data).find("DivisionType").each(function() {
						var type = $(this).attr("SportType"), id = $(this).attr("DivisionTypeId");
						dropDowns.divisions.push({type:type, id:id, name:$(this).attr("Description")});
						if ($(this).attr("SportType") == config.startSportId && !ls && !ld) {
							ls = type;
							ld = id;
						}
					});
					if (ls && ld) {
						for (var i in dropDowns.sports) {
							if (dropDowns.sports[i].title == ls) {
								ls = i;
								break;
							}
						}
						dropDowns.loadSport(ls, ld);
					}
				}
			});
		},
		loadSport:function(s, div) {
			var out = "", f = div||null;
			s = dropDowns.sports[s].title;
			$("#full").attr("href", "http://www.okblitz.com" + dropDowns.links[s]);
			$("#dropdowns > a.sport").html(s);
			for (var i = 0; i < dropDowns.divisions.length; i++) {
				var t = dropDowns.divisions[i];
				if (t.type == s) {
					if (!f) { f = t.id; }
					out += '<li><a href="javascript:void(0);" class="division" rel="' + t.id + '">' + t.name + '</a></li>';
				}
			}
			$("#divisions").html(out);
			dropDowns.loadDivision(f);
		},
		loadDivision:function(d) {
			for (var i in dropDowns.divisions) {
				if (dropDowns.divisions[i].id == d) {
					var href = $("#full").attr("href");
					var full = href.match(/id=([\d]+)/);
					if (typeof(full) == 'object') {
						$('#full').attr('href', 'http://www.okblitz.com/scoreboard.aspx?id=' + full[1] + '&div=' + d);
					}
					$("#dropdowns > a.division").html(dropDowns.divisions[i].name);
					break;
				}
			}
			load(d);
		}
	},
	
	slider = {
		info:{count:0,width:0,current:0,display:6},
		init:function() {
			slider.update();
		},
		update:function() {
			slider.info.current = 0;
			slider.info.width = $("#tickerWrap ul li:first").outerWidth();
			slider.info.count = $("#ticker li").length;
			$("#tickerWrap > a").removeClass("disabled");
			$("#tickerWrap a[rel='prev']").addClass("disabled");
			if (slider.info.count <= slider.info.display) {
				$("#tickerWrap a[rel='next']").addClass("disabled");
			}
			$("#tickerWrap ul").width(slider.info.width * slider.info.count);
		}
	},

	getSportAlias = function(id) {
		var retVal = null;
		switch (parseInt(id)) {
			case 1:
				retVal = 'CFB';
				break;
			case 2:
				retVal = 'CBB';
				break;
			case 3:
				retVal = 'CBK';
				break;
			case 4:
				retVal = 'NBA';
				break;
			case 5:
				retVal = 'WCBK';
				break;
			case 6:
				retVal = 'HFB';
				break;
			case 7:
				retVal = 'HBK';
				break;
			case 8:
				retVal = 'WHBK';
				break;
			case 9:
				retVal = 'WNBA';
				break;
		}
		return retVal;
	},
	
	displayLink = function(teamBaseId) {
		retVal = false;
		teamBaseId = parseInt(teamBaseId);
		if (teamBaseId == 14 || teamBaseId == 24 || teamBaseId == 3) {
			retVal = true;
		}
		return retVal;
	},
	
	getGameStatus = function(statusType, time) {
		retVal = '';
		switch (statusType) {
			case 'In-Progress':
				retVal = 'Playing';
				break;
			case 'Final':
				retVal = 'Final';
				break;
			case 'Pre-Game':
				retVal = time;
				break;
			case 'Postponed':
				retVal = 'Post.';
				break;
			case 'Cancelled':
				retVal = 'Canc.';
				break;
			case 'Weather':
				retVal = 'Delay';
				break;
		}
		return retVal;
	},
	
	load = function(id) {
		$("#ticker").html('<img src="' + config.loader + '" alt="Loading">');
		var url = config.iframed ? "/proxy/?url=http%3A%2F%2Fwww.okblitz.com%2Fscheduleprocessor.aspx%3Ftype%3Dtickerschedules%26id%3D" + id : "/scheduleprocessor.aspx?type=tickerschedules&id=" + id;
		$.ajax({
			url:url,
			dataType:"xml",
			success:function(data) {
				var out = "<ul>";
				$(data).find("Schedule").each(function() {
					var d = formatDate($(this).attr("DateLocal").replace("T", " ")), today = new Date(), date = "";
					if (d.getDay() == today.getDay() && d.getMonth() == today.getMonth() && today.getFullYear() == d.getFullYear()) {
						date = "Today";
					} else {
						date = (d.getMonth() + 1) + "/" + d.getDate();
					}
					var cell = "", link = false;
					var score = $(this).find("Score").attr("Value")||false;
					var status = $(this).attr('ScheduleStatusType');
					var time;
					if ($(this).attr("ToBeAnnounced") == "true") {
						time = "TBA";
					} else {
						time = formatTime(d);
					}
					cell += "<h2>" + date + "</h2>";
					$(this).find("Entry").each(function() {
						score = $(this).find("Score").attr("Value")||false;
						var s = score ? '<span class="' + $(this).find("Score").attr("ScoreResultType") + '">' + score + '</span>' : '';
						time = getGameStatus(status, time);
						var $team = $(this).find('Team');
						var alias = $team.attr('Alias');
						
						// URL format
						// SportType/CleanName-Alias
						if ($(this).find('UsageTeams').length === 0 && ($team.attr('SportTypeId') == '6' || displayLink($team.attr('TeamBaseId')))) {
							var name = $team.attr('Name');
							var sport = getSportAlias($team.attr('SportTypeId'));
							name = name.replace(/,\\\<\>:|\?\'&^%$!\*\(\)#/, '').replace(' ', '').replace(' ', '');
							link = 'http://www.okblitz.com/' + sport + '/' + name + '-' + alias;
							cell += '<p><a href="' + link + '">' + s + alias + '</a></p>';
						} else {
							cell += '<p>' + s + alias + '</p>';
						}

					});
					cell += "<h3>" + time + "</h3>";
					var c = score ? "score " : "";
					out += "<li" + (c ? ' class="' + c + '"' : '') + ">" + cell + "</li>";
				});
				out += "</ul>";
				if (out == "<ul></ul>") { out = "<p>No scores or schedule available at this time</p>"; }
				$("#ticker").html(out);
				slider.update();
			},
			error:function(a,b,c) {
				$("#ticker").html("<p>No scores or schedule available at this time</p>");
				slider.update();
			}
		});
	},
	
	init = function() {
		config.startSportId = $("#SportTypeId").val()||defaultSportId;
		dropDowns.init();
		slider.init();
		$("#okbTicker").click(events);
	};
	
	$(document).ready(init);
	
})();