/* ----------------------------------------------------------
	title		  : Stoops Framework
	created		  : 11/17/09
	last updated  : 2/5/10
---------------------------------------------------------- */
/* BG Position plugin */
(function($) {
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name === 'background-position'){
				name = 'backgroundPosition';
			}
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
	
	var oldAnim = $.fn.animate;
	$.fn.animate = function(prop){
		if('background-position' in prop){
			prop.backgroundPosition = prop['background-position'];
			delete prop['background-position'];
		}
		if('backgroundPosition' in prop){
			prop.backgroundPosition = '('+ prop.backgroundPosition;
		}
		return oldAnim.apply(this, arguments);
	};
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			var start = $.curCSS(fx.elem,'backgroundPosition');
			
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		//return;
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);
//end plugin






jQuery.noConflict();     
jQuery(document).ready(function($){

var adminView = $('#adminbar #toolbar').length;








//nav 
$('#nav li').hover(function(){
	
	$('.glass', this).animate({
      	"marginTop": "0"
    	}, { duration: "normal" });
    	
    $('a', this).animate({
      	backgroundPosition: "0 30px"
    	}, { duration: "normal" });	
	
	$('.n-desc', this).slideToggle('normal');
	
	
	
	},function(){
	
	$('.n-desc', this).slideToggle('fast');
	
	$('a', this).animate({
      	backgroundPosition: "0 53px"
    	}, { duration: "fast" });
	
	$('.glass', this).animate({
      	"marginTop": "53px"
    	}, { duration: "fast" });
	
	
}).click(function(){
	var theURL = $('a', this).attr('href');
	
	window.location.assign(theURL);
	return false;
	});



//Sub Features
var sfActiveLevel = 0;
var highestLevel = 0;

function setupWishbone () {
	
	$('.cta', '#homePage #content-main').each(function(){
			$('.element', this).each(function(i){
				$(this).addClass('sf-level-'+i);
				
				if (i > highestLevel) { highestLevel = i; }
							
				});
	});
	
	$('#homePage #content-main .cta .element').not('.sf-level-0').hide();
	
}


function runWishbone (domElement) {
	var controlID = $(domElement).attr('id');
	var sfActiveClass = '.sf-level-' + sfActiveLevel;
		
		//fade out all
		$('#homePage #content-main .cta .element').fadeOut('fast');
		
		switch (controlID) {
		case 'sf-previous':
		
		if (sfActiveLevel == 0) {
			
			sfActiveClass = '.sf-level-' + highestLevel;
			$(sfActiveClass, '#homePage #content-main .cta').fadeIn('fast');
			sfActiveLevel = highestLevel;
			
			} else {
				
			
			sfActiveLevel--;	
			sfActiveClass = '.sf-level-' + sfActiveLevel;
			$(sfActiveClass, '#homePage #content-main .cta').fadeIn('fast');	
			
			}
		break;
		
		case 'sf-next':
		
		if (sfActiveLevel == highestLevel) {
			
			sfActiveClass = '.sf-level-' + 0;
			$(sfActiveClass, '#homePage #content-main .cta').fadeIn('fast');
			sfActiveLevel = 0;
			
			} else {
				
			
			sfActiveLevel++;	
			sfActiveClass = '.sf-level-' + sfActiveLevel;
			$(sfActiveClass, '#homePage #content-main .cta').fadeIn('fast');	
			
			}
		break;
		}
	
}


if ( adminView ) {
	$('#homePage #content-main').css({
		'height': 'auto',
		'overflow':'visible'
		});
	
	$('.cta').css({
		'height': 'auto'
		});
	} else {
		
		setupWishbone();
		
		$('#homePage #content-main').hover(function(){
			$('#sub-feature-controls').fadeIn('fast');
			},function(){
			$('#sub-feature-controls').fadeOut('fast');
			});
		
		$('#sf-previous').click(function(){
			sSwoosh.play();
			runWishbone(this);
			return false;
			});
			
		$('#sf-next').click(function(){
			sSwoosh.play();
			runWishbone(this);
			return false;
			});	
			
	}





//Sound
if ( $('#homePage').length ) {
if (adminView) {} else {

	var songPaused = false;
	
	$('body').prepend('<div id="sound-controls"><a id="sc-play-pause" href="#"></a></div>');
	
	$('#sc-play-pause').click(function(){
		if (songPaused) {
			
			soundManager.resumeAll();
			$(this).css('background','url(/Websites/bobstoops/templates/stoopsTheme/css/img/sound-pause.png) no-repeat 0 0');
			songPaused = false;
			
			} else {
			
			soundManager.pauseAll();
			$(this).css('background','url(/Websites/bobstoops/templates/stoopsTheme/css/img/sound-play.png) no-repeat 0 0');
			songPaused = true;
			
			}
		});
	
	
	$('#feature-main, #ipod').click(function(){
		pauseMusic();
		});

	
	if ( $('.player-ipod').length ) {
	$(".player-ipod").popup({
		    width: 269,
		    height: 226,
		    titlebar: false,
		    status: true,
		    resizable: false,
		    toolbar: false,
		    scrollbars: false,
		    menubar: false
		});
}
} //end if admin	
} //end if homepage





//Lightbox stuff
if ( $('#homePage').length ) {
	
	if (adminView) {
	
	$("#lightbox-feature").show().prepend('<h1>This section below is for the lightbox that pops up the first time a user visits</h1><p>If you do not have anything to showcase in the lightbox delete all elements from this section and it will not run allowing the homepage to load as normal. The max width and height of this section should be 890px wide by 500px high. Note: the lightbox will only run once per browser session, this is to keep it from becoming a roadblock for users coming back to the homepage that have already seen it. If you need to preview the lightbox just close your browser and re-open it, that will reset the session.</p>');
	
	} else {
	
	
		if ( $('#lightbox-feature .element').length <= 0) { 
		//nothing
		} else {	
		
		var ssCount = sessionStorage.length;
		
		if (ssCount > 0) {
			var alreadySeen = sessionStorage.getItem("alreadySeenValue");
			} else {
			var alreadySeen = 'N';
			}
	
		if (alreadySeen == 'N' ) {
			//show lightbox
			$("#lightbox-feature").colorbox({width:'910px',height:'530px', opacity:0.7, inline:true, href:"#lightbox-feature",
			onClosed:function(){ 
			sessionStorage.setItem("alreadySeenValue", "Y");
			$("#lightbox-feature").hide();
			}}).click();
			$("#lightbox-feature").show();
			}
		
	}//if empty

}//if admin
}//if home




// News feed
//feed://www.soonersports.com/sports/m-footbl/headline-rss.xml
//http://pipes.yahoo.com/pipes/pipe.run?_id=6ea1ef8914015676ece79d71ea0faf3e&_render=json
//http://pipes.yahoo.com/pipes/pipe.run?_id=86a4c1403f7e6ab4a0845d6275fc21c8&_render=json

var loadingImg = '/Websites/bobstoops/templates/stoopsTheme/css/img/loading.gif';


$('#feature-sub-content').append('<img src="'+ loadingImg +'" alt="loading..." class="ajax-loading" />');

$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=6ea1ef8914015676ece79d71ea0faf3e&_render=json&_callback=?",
        function(j){
          
		$('#feature-sub-content').html('<ul id="news-feed"></ul>');
          
          $.each(j.value.items, function(i,item){
            	$('#news-feed').append('<li><h1 class="postTitle"><a href="'+ item.guid + '">'+ item.title +'</a></h1></li>');
          		});
        });
        
   
   
   
var newsFeedCont = $('#sooner-sports-news-full').parent().contents();
$('#sooner-sports-news-full').parents('.element').replaceWith(newsFeedCont);
    
$('#sooner-sports-news-full').append('<img src="'+ loadingImg +'" alt="loading..." class="ajax-loading" />');

$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=86a4c1403f7e6ab4a0845d6275fc21c8&_render=json&_callback=?",
        function(j){         
          
		$('#sooner-sports-news-full').html('<div class="element"><div class="blogsElement"><div class="blogList"><ul></ul></div></div></div>');
          
          $.each(j.value.items, function(i,item){
            	$('ul', '#sooner-sports-news-full').append('<li class="post'+ (i+1) +'"><h2 class="postTitle"><a href="'+ item.guid + '">'+ item.title +'</a></h2><div class="postBody"><p>'+ item.description +'</p></div><div class="postInfo"><span class="postDate">' + item.pubDate + '</span></div></li>');
          		
          		if (!(item.enclosure == undefined)) {
          		var currentPost = '.post'+ (i+1);
          		$('.postBody', currentPost).prepend('<span class="img-container imgspacing-upperleft"><img src="' + item.enclosure.url + '" /></span>');
          		}
          		
          		});
        });    
        
      

//*** The Sooners Fade ***

if ( $('.cycle-slider').length ) {
	
	$('.cycle-slider').before('<p id="sliderNext"><a href="#">Next</a></p><p id="sliderPrev"><a href="#">Prev</a></p>');

	$('.cycle-slider').cycle({ 
	    fx: 'fade',
		speed: 400,
		timeout: 3000,
		pause: 1, 
		next: '#sliderNext', 
		prev: '#sliderPrev'		
	});
}



//*** countdown & schedule ***

if ( $('#homePage').length ) {



//MM/dd/yyyy hh:mm:ss tt
var rightNow = new Date();
var lastGame = '';
var games = '';
var itemsTmp = new Array();
var itemsSorted = [];
var datesSorted = [];
var theSchedule = '';

function compareDates(a, b) {
	var dateA = new Date(a);
	var dateB = new Date(b);
	return dateA - dateB;
}


//get schedule
$.ajax({
	type: "GET",
	url: "/Websites/bobstoops/templates/stoopsTheme/schedule.xml",
	dataType: "xml",
	success: function(xml) {
		
		
		games = $(xml).find('game');			
		
		
		$.each(games, function(i) {
		itemsTmp[i] = $(this).attr("time");
		});


		//console.log(itemsTmp);
		
		itemsTmp.sort(compareDates);

		
		//console.log(itemsTmp);
		
		$.each(itemsTmp, function(i) {
		itemsSorted[i] = $( "game[time=" + itemsTmp[i] + "]", xml).get(0);
		});
		
		//console.log(itemsSorted);
		
		$("game", xml).remove();
		$.each(itemsSorted, function() {
		$("schedule", xml).append(this);
		});


		theSchedule = xml;
		
		checkSchedule();
		
		
	} //end success
}); //end ajax


function checkSchedule() {
	var dayNow = '';
	var dayLastGame = '';
	
	//create datesSorted array
	$.each(itemsSorted, function(i) {
		datesSorted[i] = new Date($(this).attr("time"));
		});
	
	
	lastGame = datesSorted[datesSorted.length-1];
	
	
	dayNow = new Date(rightNow.toLocaleDateString());
	dayLastGame = new Date(lastGame.toLocaleDateString());
	
	//console.log(dayNow);
	//console.log(dayLastGame);
	
	if (dayNow > dayLastGame) {
		//console.log('we are past! no games!');
		$('#countdown').hide();
		
	} else {
		
		$('#feature').prepend('<a href="#" id="schedule-link">Schedule</a>');
		
		$('#countdown').append('<ul id="c-schedule"></ul> <div id="versus"><span id="vs-home">Sooners</span><span id="vs-guest"></span></div><div id="clock"><div id="ticktock"></div></div><a href="#" id="c-close">Close</a>');
		
		$('#c-close').click(function(){
			$('#countdown').slideUp('fast');
			$('#schedule-link').show();
			return false;
			});
		
		$('#schedule-link').click(function(){
			$(this).hide();
			$('#countdown').slideDown('fast');
			return false;
			});
		
		buildClock(dayNow);
		
		$('#countdown').slideDown('normal');
		}
}



function buildClock(dayNow) {
	var dayTmp = '';
	var i = '';
	var indexMatch = '';
	var gameTime = '';
	
	//game today? find a matching date
	for (i in datesSorted) {
		
		dayTmp = datesSorted[i].toLocaleDateString();
		
		if (dayNow.toLocaleDateString() == dayTmp) {
			indexMatch = i;
			break;
			}
		}
	
	
	
	//no
	if (indexMatch.replace(/\s/g,'') == '') {
		//reset
		i = '';
		dayTmp = '';
		
		//find next game
		for (i in datesSorted) {

		dayTmp = datesSorted[i];
		
		if (rightNow < dayTmp) {
			indexMatch = i;
			break;
			}
		}
		
		//console.log('next game - indexMatch:' + indexMatch);
		
		gameTime = datesSorted[indexMatch];
		startTheClock(gameTime);
		buildSchedule(indexMatch);		
		
		
	} else {
	//yes		
	
		//past time?
		if ( rightNow.toLocaleTimeString() > datesSorted[indexMatch].toLocaleTimeString() ) {
		//yes - show what time the game is today
		
		var a_p = "";
		var d = datesSorted[indexMatch];
		var curr_hour = d.getHours();
		if (curr_hour < 12) { a_p = "AM"; } else { a_p = "PM"; }
		if (curr_hour == 0) { curr_hour = 12; }
		if (curr_hour > 12) { curr_hour = curr_hour - 12; }
		var curr_min = d.getMinutes();		
		curr_min = curr_min + "";
		if (curr_min.length == 1) { curr_min = "0" + curr_min; }
			
		$('#clock').css('background-image','none').html('<h1 id="game-today">Game today at <span id="game-time"> '+ curr_hour + " : " + curr_min + " " + a_p +'</span></h1>');
		
		} else {
		// no  - start countdown
		gameTime = datesSorted[indexMatch];
		startTheClock(gameTime);
		}
	
	buildSchedule(indexMatch);
	
	}
}


function buildSchedule(indexMatch) {
	var rivalNickname = '';
	var gamesAfterSelected = '';
	var gamesBeforeSelected = '';
	var startPrintingIndex = '';
	var i ='';
	var tmpRivalID = '';
	var numOfRotations = 3;
	
	rivalNickname = $(itemsSorted[indexMatch]).attr('nickname');	
	$('#vs-guest').text(rivalNickname);

	gamesAfterSelected = itemsSorted.length - ((indexMatch*1) + 1);
	//console.log(gamesAfterSelected);
	
	if (gamesAfterSelected >= 3) {
		
		startPrintingIndex = indexMatch;
			
	} else {
		
		if (itemsSorted.length < 3) {
			startPrintingIndex = 0;
			numOfRotations = itemsSorted.length - 1;		
		} else {
			gamesBeforeSelected = 3 - gamesAfterSelected;
			startPrintingIndex = indexMatch - gamesBeforeSelected;
		}
	}
	
	
	for (i=0;i<=numOfRotations;i++) {		
		tmpRivalID = $(itemsSorted[startPrintingIndex]).attr('id');
		
		$('#c-schedule').append('<li id="' + tmpRivalID + '"><span class="c-date">' + datesSorted[startPrintingIndex].format('m/d/yy') + '</span></li>');
		
		startPrintingIndex++;
		}
}



function startTheClock (gameTime) {
	$('#clock #ticktock').countdown({
	until: gameTime, 
	compact: true, 
	onExpiry: itsGameTime, 
    layout: '<div class="c-time{d10} day10"></div><div class="c-time{d1} day1"></div>' + 
        '<div class="c-sep"></div>' + 
        '<div class="c-time{h10} hour10"></div><div class="c-time{h1} hour1"></div>' + 
        '<div class="c-sep"></div>' + 
        '<div class="c-time{m10} min10"></div><div class="c-time{m1} min1"></div>' + 
        '<div class="c-sep"></div>' + 
        '<div class="c-time{s10} sec10"></div><div class="c-time{s1} sec1"></div>'});
}

function itsGameTime() {
	$('#clock').css('background-image','none').contents().remove();
	$('#clock').append('<h1 id="game-msg">It\'s Game Time!</h1>')
}


} // end if home






//Gameday
$('#gameday-timeline li').not('li#holder').click(function(){
	
	var selectedTimeHTML = $(this).html();
	
	$('#gameday-timeline li').removeClass('activeTime').filter(this).addClass('activeTime');
	
	$('#gameday-timeline li#holder').fadeOut('fast',function(){
		
		$(this).html(selectedTimeHTML).fadeIn('normal');
		
		});
	
	});

$('#gameday-timeline').append('<li id="holder"></li>');
$('#gameday-timeline li:first').click();




if ( $('#homePage').length ) {
var video_id = 9051185;

var videoTxt = $('#moogaloop').text();

if (videoTxt.replace(/\s/g,'') == '') {} else {
	video_id = videoTxt;
	}

		var moogaloop = false;
		
	
		
// Run the javascript when the page is ready
		var swf_id = 'moogaloop';
		
	 	var flashvars = {
	        clip_id: video_id,
	        show_portrait: 0,
	        show_byline: 0,
	        show_title: 0,
	        fullscreen: 1,
	        server: 'vimeo.com',
	        autoplay: 0,
	        color: '90002c',
			js_api: 1, // required in order to use the Javascript API
			js_onLoad: 'vimeo_player_loaded', // moogaloop will call this JS function when it's done loading (optional)
			js_swf_id: 'moogaloop' // this will be passed into all event methods so you can keep track of multiple moogaloops (optional)
	    };
		var params = {
			allowscriptaccess: 'always',
			allowfullscreen: 'true'
		};
		var attributes = {};
			
		swfobject.embedSWF("http://vimeo.com/moogaloop.swf", swf_id, "640", "360", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	
} //end if homepage





//parallax
if ( $('#homePage').length ) {
	
	var winH = $(window).height(); 
	var winW = $(window).width();
	
	$('#parallax-viewport').css({
		'width': winW,
		'height': winH
		}).jparallax({ 
		mouseport: $('html'),
		frameDuration: 40
		},{ytravel: .3, xtravel: .3}, {ytravel: .5, xtravel: .7},{ytravel: .5, xtravel: .8},{ytravel: .5, xtravel: .9});


$(window).resize(function(){
	winH = $(window).height(); 
	winW = $(window).width();
	$('#parallax-viewport').css({'width': winW,'height': winH});
});

}//end if home page



});//end doc ready

function pauseMusic() {
		soundManager.pauseAll();
		jQuery('#sc-play-pause').css('background','url(/Websites/bobstoops/templates/stoopsTheme/css/img/sound-play.png) no-repeat 0 0');
		songPaused = true;
		}


function vimeo_player_loaded(swf_id) {
			moogaloop = document.getElementById(swf_id);
			moogaloop.api_addEventListener('onPlay', 'vimeo_on_play');
			moogaloop.api_addEventListener('onFinish', 'vimeo_on_finish');
}
		
function vimeo_on_finish(swf_id) {
					
}

function vimeo_on_play(swf_id) {
	pauseMusic();
}

/*
 * BG Position Plugin
 * @author Alexander Farkas
 * v. 1.21
 http://plugins.jquery.com/project/backgroundPosition-Effect 
*/