var delve_channelID = "";
var delve_startMediaID = "";
var delve_mediaStartPosition = 0;
var delve_videoPlayList = [];
var delve_videoPlayListStartTimes = []
var delve_currentMediaIndex = 0;
var delve_currentMaxIndex = 0;
var delve_playFullList = true;//true on homepage	
var delve_adZone = "";

function delvePlayerCallback(playerId, eventName, data) {		
	var id = "delve_player_used";
	if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
	  DelvePlayer.registerPlayer(id);
	}
    
    switch (eventName) {
      case 'onPlayerLoad':
	  	//called after player is registered
        doOnPlayerLoad();
        break;
	  case 'onPlayStateChanged':
		if (data.isPlaying === true && delve_mediaStartPosition > 0) {
			DelvePlayer.doSeekToSecond(delve_mediaStartPosition / 1000);
			delve_mediaStartPosition = 0;
		}
		break;
	  case 'onMediaComplete':
	  	//called when media is done playing
	  	doOnMediaComplete(data);
		break;	
	  case 'onChannelComplete':
	    //because we don't use the order in the channel we may reach the "last" video and the channel may be complete before our thumbnail bar has played out
	  	doOnChannelComplete(data);
		break;    
    }
}

function doOnChannelComplete(e){
	var thisChannelID = e.id;
	var thisChannelArray = e.mediaList;
	var thisMediaID = thisChannelArray[thisChannelArray.length-1].id;
	var thisMediaIndex =jQuery.inArray(thisMediaID, delve_videoPlayList);
	var maxMediaIndex = delve_videoPlayList.length - 1;
	var nextMediaIndex = 0;
	if (thisMediaIndex != maxMediaIndex){
		nextMediaIndex = thisMediaIndex + 1;
	}
	if (nextMediaIndex > 0){
		playVideoAndSetChannel(nextMediaIndex);
	}	
}
function doOnPlayerLoad() {
	//Here is where we set the ad call <NOTE> the url must be encoded 
	//PRE-ROLL new ad server //does not work asking Randy
	//DelvePlayer.doSetAd('preroll', 'Dart', 'url=http%3A%2F%2Fox-d.targetmediaads.com%2Fv%2F1.0%2Fav%3Fauid%3D32301%0A');
	//POST-ROLL old ad server
	//DelvePlayer.doSetAd('postroll', 'Dart', 'url=http%3A%2F%2Fd.targetmediaads.com%2Ffc.php%3Fscript%3DbannerTypeHtml%3AvastInlineBannerTypeHtml%3AvastInlineHtml%26zones%3Dpre-roll0-0%253D39%26nz%3D1%26source%3D%26r%3DR0.24958777986466885%26block%3D1%26format%3Dvast%26charset%3DUTF-8');
	if (delve_adZone !== false) {
		var ad_url_string = 'url=http%3A%2F%2Fox-d.targetmediaads.com%2Fv%2F1.0%2Fav%3Fauid%3D' + delve_adZone;
		DelvePlayer.doSetAd('preroll','Dart',ad_url_string);
	}
	
	// Carousel related stuff only
	if (window.location.href.indexOf('videos.aspx') === -1) {
		var startMediaID = window.location.hash.length > 0 ? window.location.hash.replace('#', '') : 0;
		
		// If a media ID was passed, separate the id and the start position
		var startTime = 0;
		if (startMediaID !== 0) {
			var t = startMediaID.split('_');
			startMediaID = t[0];
			if (t.length > 1) {
				startTime = t[1];
			}
		} else {
			startTime = delve_videoPlayListStartTimes[startMediaID];
			startMediaID = delve_videoPlayList[startMediaID];
		}
		playVideoAndSetChannel(startMediaID, startTime);
	}
	//DelvePlayer.doLoadChannelAndSetMedia(delve_channelID, '1479089e8f1a41bb97f3c03b68a00864', true, 0);
}
  

function doOnMediaComplete(e){
	var thisMediaID = e.id;
	var thisMediaIndex =jQuery.inArray(thisMediaID, delve_videoPlayList);
	var maxMediaIndex = delve_videoPlayList.length - 1;
	var nextMediaIndex = 0;
	if (thisMediaIndex != maxMediaIndex){
		nextMediaIndex = thisMediaIndex + 1;
	}
	if (nextMediaIndex > 0){
		playVideo(nextMediaIndex);
	}
}

function playVideo(videoIndex) {
	var thisMediaID = delve_videoPlayList[videoIndex];
	var thisMediaStartPosition = delve_videoPlayListStartTimes[videoIndex];
	if (thisMediaStartPosition.length == 0){
		thisMediaStartPosition = 0;
	}
	delve_mediaStartPosition = thisMediaStartPosition;
	if (delve_adZone !== false) {
		var ad_url_string = 'url=http%3A%2F%2Fox-d.targetmediaads.com%2Fv%2F1.0%2Fav%3Fauid%3D' + delve_adZone;
		DelvePlayer.doSetAd('preroll','Dart',ad_url_string);
	}
	setCopyLink(thisMediaID, thisMediaStartPosition);
	
	DelvePlayer.doLoadMedia(thisMediaID, true);
	// DelvePlayer.doSetMedia(thisMediaID, true, thisMediaStartPosition);
}

function setCopyLink(mediaId, startTime) {
	if (typeof(mediaId) !== 'undefined') {
		starttime = typeof(startTime) !== 'undefined' ? startTime : 0;
		jQuery('#shareVid').val('http://www.useducationtv.com/default.aspx?sid=' + player.schoolId + '#' + mediaId + '_' + startTime);
	}
}

function pauseVideo(){
	DelvePlayer.doPause();	
}

function playVideoByMediaID(mediaID){
	DelvePlayer.doLoadMedia(mediaID, true);
}

function playVideoAndSetChannel(mediaId, startTime) {
	if (mediaId != undefined && mediaId != 0) {
		delve_mediaStartPosition = startTime;
		DelvePlayer.doLoadChannelAndSetMedia(delve_channelID, mediaId, true, startTime);
		setCopyLink(mediaId, startTime);
	} else {
		DelvePlayer.doPause();
	}
}
function playVideoAndSetChannelAndStartPosition(mediaID, startPosition){
	delve_mediaStartPosition = startPosition;
	// If the libraries haven't loaded yet, keep coming back until they do
	if (typeof(DelvePlayer) !== 'undefined') {
		DelvePlayer.doLoadChannelAndSetMedia(delve_channelID, mediaID, true, startPosition);
		setCopyLink(mediaID, startPosition);
	} else {
		setTimeout(function() { playVideoAndSetChannelAndStartPosition(mediaID, startPosition); }, 250);
	}
}
/* ==============================================================================*/
/* --------- end: NEW CODE FOR LIMELIGHT PLAYER --------------------------------------*/
jQuery.noConflict();

jQuery(function($) {
	//set channel id and adzone for video player
	delve_channelID = window.player.channelId;
	
	/* if($('#delveChannelID').length){
		delve_channelID = $('#delveChannelID').html();
		delve_adZone = $('#delveAdZone').html();
	}; */
	//set thumbnail bar up and set first video to player
	if($('.carousel-thumbs').length){
		
		$('.carousel-thumbs li a:first').each(function(){
			startMediaStartPosition = $(this).attr("rel");
			if (startMediaStartPosition.length == 0){
				startMediaStartPosition = 0;
			}
			//pass the first media id to the player
			//break;
		});
		//add all videos in thumbnail carousel to playlist
		$('.carousel-thumbs li a').each(function(){
			var MediaID = $(this).attr("href").substring(1);
			var MediaStartPosition = $(this).attr("rel");
			if (MediaStartPosition.length == 0){
				MediaStartPosition = 0;
			}
			//append to playlist
			delve_videoPlayList.push(MediaID);
			delve_videoPlayListStartTimes.push(MediaStartPosition);
		});
		
		$(".carousel-thumbs li a").click(function(event){
			event.preventDefault();
			// Check for a media ID on the hash, otherwise use the first thumbnail
			var thisMediaID = $(this).attr("href").substring(1);
			var thisMediaIndex =jQuery.inArray(thisMediaID, delve_videoPlayList);
			//on click set the media id and starttime to player
			delve_adZone = window.player.carouselAdToggle ? window.player.carouselAdZone : false;
			playVideo(thisMediaIndex);
		});

		
	};
	
	//lbrennan 510 bandaid for buttons not clikcing		
	$('#buttons #viewAllVideo').bind('click',function(e){
		window.location = $("#buttons #viewAllVideo").attr("href");
		return false;
	});
	$('#buttons #membersOnlyVideo').bind('click',function(e){
		window.location = $("#buttons #membersOnlyVideo").attr("href");
		return false;
	});
	//open fb and twitter in new window
	if($('#mainContent .facebook a').length){
		$("#mainContent .facebook a").attr("target","_blank");
	};
	
	if($('#mainContent .twitter a').length){
		$("#mainContent .twitter a").attr("target","_blank");
	};
	
	// ===== GLOBAL: Cached Version of $.getScript() =====
	$.getCachedScript = function(url, callback, cache) {
		$.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: cache || true });
	};
	
	// ===== 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 ==========
	var redirectURL = "/Search.aspx?";
	$('#header .search input:text').keydown(function(e){
		if (e.keyCode == 13) {
			var sid_param = gup( 'sid' ); 
			redirectURL = redirectURL + "sid=" + sid_param;
			window.location = redirectURL + "&sp=" + $(this).val();
			return false;
		}
	});
	// ~~~~~ Associate Submit Button to Search field ~~~~~
	$('#header .search input.submit').bind('click',function(e){
		var sid_param = gup( 'sid' ); 
		redirectURL = redirectURL + "sid=" + sid_param;
		window.location = redirectURL  + "&sp=" + $('#header .search input:text').val();
		return false;
	});
	
	
	$('div.newsthumb').each(function(){
		newsimage = $(this).find('img');
		if (newsimage.attr("src") == ''){
			$(this).removeClass('newsthumb');
			$(this).addClass('newsthumbHide');
		}
	});
	// ===== Carousel: If more than four images =====
	$('div.inlineMediaContainer').each(function(){
		$(this).carousel({pagination:true});
	});
	
	
	
	// ===== INDEX: Show/Hide Events ==========
	var indexEvents = $('#eventsCell li.event');
	if(indexEvents.length > 1){
		$('#btnDisplayEvents img').attr('class','down');
		$('#btnDisplayEvents').bind('click',function(e){
			var btn = $('#btnDisplayEvents img');
			var height = (btn.hasClass('down'))? ($('#eventsCell li').length*40) : 80;
							
			$('#eventsCell ul').animate({height:height+'px'},'fast',function(){
				$('#btnDisplayEvents img').attr('class',(height==80)?'down':'up');
			});
			return false;
		})
	};
	
	// ===== GLOBAL: Enable :hover for IE6 ==========
	$('#menu li').hover(function(){
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	// ===== Popup Video Player ==========
	var videoCollection = $('ul.videoResults li');
	if(videoCollection.length){
		videoCollection.popupVideos();
	};

});

// ===== Global Functions =========================
jQuery.fn.events = function(o){
    for (var i in o) {
        this.bind(i, o[i]);
    }
    return this;
};

// ===== InlineMediaContainer: Thumbnail Carousel ==================== 
(function($) {
	$.fn.carousel = function(options){
		// extend our default options with those provided
		var $options = $.extend({}, $.fn.carousel.defaults, options);
		var $this;
		
		return this.each(function() {
			$this = $(this);
			var itemsVisible = 4;
			$options.container = $('.media_thumbs ul',$this);
			$options.thumbs = $('a',$options.container);
			if($options.thumbs.length === 1){
				$('.media_thumbs',$this).css('display','none');
			} else if($options.thumbs.length <= itemsVisible){ // == no carousel ==
				$('a.previous,a.next', $this).css('display','none');
				$('.media_thumbs',$this).css('display','block');
			} else { // == enable carousel ==
				// ~~~~~ parameters ~~~~~
				$('.media_thumbs',$this).css('display','block');
				var itemSize = $($options.thumbs[0]).outerWidth();
				var itemsTotal = $options.thumbs.length;
				$options.visibleWidth = $('div.carousel-thumbs', $this).outerWidth(true) + 3;
				$options.container.css('width',((itemsTotal*itemSize)+itemSize+itemSize)+'px');
				var pageSize = Math.floor($options.visibleWidth / itemSize);
				var pageTotal = (itemsTotal%pageSize==0)?itemsTotal:(pageSize-(itemsTotal%pageSize)+itemsTotal)-1;
				$options.total = Math.ceil(pageTotal / pageSize);
				
				// ~~~~~ controls ~~~~~
				$this.find("a.next").click(function(){
					animate("next");
					return false;
				});
				$this.find("a.previous").click(function(){		
					animate("prev");
					return false;
				}).css({'opacity':'0.5','cursor':'default'});
				createPagination();
			}
		});
		function animate(dir){
			var p = 0;
			if(!isNaN(dir)){
				$options.current = dir;
			} else if(dir == "next"){
				$options.current = ($options.current >= $options.total) ? $options.total : parseInt($options.current)+1;
			} else {
				$options.current = ($options.current <= 0) ? 0 : parseInt($options.current)-1;
			};	
			p = ($options.current*$options.visibleWidth*-1);
			$($options.container).stop().animate({ left: p }, 500);
			
			$("a.next", $this).css({'opacity':'1','cursor':'pointer'});
			$("a.previous", $this).css({'opacity':'1','cursor':'pointer'});
			if($options.current >= $options.total) $("a.next", $this).css({'opacity':'0.5','cursor':'default'});
			if($options.current <= 0) $("a.previous", $this).css({'opacity':'0.5','cursor':'default'});
			
			// ~~~~~ page icons ~~~~~
			$options.pageIcons.removeClass('active');
			$($options.pageIcons[$options.current]).addClass('active');
		};
		function createPagination(){
			var ul = $('ul.controls', $this);
			
			if($options.thumbs.size() == 4){ 
				ul.remove(); return; 
			} else {
				ul.css('display','block');	
			}
			
			// ===== Add Pagination =====
			if($options.pagination){
				var pages = [];
				for(var x=0,xl=$options.total;x<xl;x++){
					pages.push('<li><a href="#" rel="'+x+'" class="page"><span>'+(x+1)+'</span></a>');
				};
				ul.html(pages.join(''));
				$options.pageIcons = $this.find('ul.controls li a.page');
				$options.pageIcons.each(function(n,page){ $(page).parent('li').css({'left':(n * 18)+'px'}); });
				$options.pageIcons.click(function(e){ e.preventDefault(); animate($(this).attr('rel')); });
			};
			animate(0);
		};
	};

	// default option
	$.fn.carousel.defaults = {
		container: null,
		thumbs: null,
		visibleWidth:0,
		current: 0,
		total: 0,
		pageIcons:null
	};
})(jQuery);


		
(function($){
	$.fn.popupVideos = function(options){
		// extend our default options with those provided
		var $options = $.extend({}, $.fn.popupVideos.defaults, options);
		        
		return this.each(function() {
			var $this = $(this);
			
			// ~~~~~ cache elements ~~~~~
			var $mediaID = $this.find('a').attr('href').substring(1);
			var	$starttime = $this.find('a').attr('rel');
			$('#light').hide();
			
			$this.find('a').bind('click',function(e){
				e.preventDefault();
				
				// ~~~~~ Show Selected Image ~~~~~
				$this.parent('ul').find('li span.selected').removeClass('selected');
				$(this).find('span').addClass('selected');
				// ~~~~~ Show Lightbox ~~~~~
				//need to delay setting the vide because delve player won't register while it's hidden
				$('#light').show();
				setTimeout(function(){
					embedVideoPlayer($mediaID,$starttime);
                }, 1200);
				
				$('#fade').fadeIn();
				
				// ~~~~~ Tout: Click to close ~~~~~
				$('#fade,div.btnClose').click(function(e){
					//STOP THE VIDEO
					pauseVideo();
					//hide player
					$('#light').hide();
					$('#fade').fadeOut();
					return false;						   
				});
			});
			
			// ===== Embed Video Player =====
			function embedVideoPlayer(mediaID,startTime){				
				//NEW CODE FOR LIMELIGHT PLAYER
				//show the video div and set the video id				
				//playVideoAndSetChannelAndStartPosition(mediaID,startTime);
				playVideoByMediaID (mediaID,startTime);
			};
		});
	};
	// default option
	$.fn.popupVideos.defaults = {
		largeMaxWidth:641,
		largeMaxHeight:361,
		autostart:true
	};
})(jQuery);

 // This method acts just like binding a click-event; the
 // difference is that it cancels the default event
 // implicitly such that you don't have to in your method.
 jQuery.fn.voidClick = function( method ){
	 // Bind a click event to each item in the collection.
	 this.click(
		 function(){
			 // Execute given method callback in current
			 // context as defined by jQuery.
			 method.apply( this, arguments );
			  
			 // Cancel default event.
			 return( false );
		 }
	 );
  
	 // Return existing jquery collection for chaining.
	 return( this );
 }
 


function gid(name)
{
	return document.getElementById(name);
};



function gup( name )
{
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}

var adCarousel = function(data) {
	
	var
	
	$ = jQuery,
	
	currentSlide = -1,
	slideCount = data.length,
	timer = null,
	timerDelay = 6000,
	slideWidth = 0,
	
	$slides = $('.adCarousel .ads'),
	$dots = $('.adCarousel .navDots'),
	$prev = $('.adCarousel .control[rel="prev"]'),
	$next = $('.adCarousel .control[rel="next"]'),
	
	controlClick = function(e) {
		clearInterval(timer);
		switch ($(e.target).attr('rel')) {
			case 'prev':
				if (currentSlide > 0) {
					gotoPage(parseInt(currentSlide) - 1);
				}
				break;
			case 'next':
				if (currentSlide < slideCount - 1) {
					gotoPage(parseInt(currentSlide) + 1);
				}
				break;
		}
	},
	
	dotClick = function(e) {
		clearInterval(timer);
		gotoPage($(e.target).attr('rel'));
	},
	
	mouseOver = function(e) {

		$('.adCarousel').addClass('hover');
	},
	
	mouseOut = function(e) {
		$('.adCarousel').removeClass('hover');
	}
	
	gotoPage = function(num) {
	
		if (num != currentSlide) {
			// $slides.find('li:eq(' + currentSlide + ')').find('object').hide();
			$dots.find('.selected').removeClass('selected');
			$slides.stop().animate({'left':'-' + (num * slideWidth) + 'px'}, {'queue':false});
			currentSlide = num;
			$dots.find('li:eq(' + num + ')').addClass('selected');
			
			// Hide all flash containers except the current one
			$slides.find('.swfWrapper:visible').fadeOut(function() { $(this).empty(); });
			var $swf = $slides.find('li:eq(' + currentSlide + ') .swfWrapper');
			if ($swf.length) {
				$swf.html('<div id="flash_content_' + num + '"></div>').show();
				swfobject.embedSWF($swf.attr('src'), 'flash_content_' + num, '607', '90', '9.0.0', '', {}, {'wmode':'transparent', 'play':'true'});
			}
			
			$prev.removeClass('disabled');
			$next.removeClass('disabled');
			if (currentSlide === 0) {
				$prev.addClass('disabled');
			}
			if (currentSlide >= slideCount - 1) {
				$next.addClass('disabled');
			}
		}
			
	},
	
	timerCallback = function() {
		var toSlide = currentSlide < slideCount - 1 ? currentSlide + 1 : 0;
		gotoPage(toSlide);
	},
	
	initSlides = function() {
	
		var out = '', dots = '';
		
		for (var i = 0, count = data.length; i < count; i++) {
			switch (data[i].type) {
				case 'flash':
					out += '<li><div class="swfWrapper" src="' + data[i].image + '"></div></li>';
					break;
				case 'iframe':
					out += '<li><iframe src="CarouselAd.aspx?id=' + data[i].id + '" scrolling="no" frameborder="0"></iframe></li>';
					break;
				default:
					out += '<li><a href="' + data[i].link + '" target="_blank"><img src="' + data[i].image + '" /></a></li>';
					break;
			}
			dots += '<li><a href="javascript:void(0);" rel="' + i + '">' + i + '</a></li>';
		}
		
		$slides.html(out);
		$dots.html(dots);
		
		slideWidth = $slides.find('li').outerWidth(true);
		$slides.width(slideWidth * slideCount);
		timer = setInterval(timerCallback, timerDelay);
		$dots.width(18 * slideCount);
		
	},
	
	init = function() {
		initSlides();
		$dots.find('a').click(dotClick);
		$('.adCarousel .control').click(controlClick);
		gotoPage(0);
		$('.adCarousel').mouseover(mouseOver).mouseout(mouseOut);
	};
	
	init();
	
};
