function getParameterByName( name, string )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( string );
  if( results == null )
    return "";
  else
    return results[1];
}

$(document).ready(function() {

	var loadJSON = function(callback) {
		
		$.getJSON("/mediaplayer/video-list.js", function(data){
														 
			vidsArr = data.categories;
			callback();
														 
		});
		
	};
	
	var buildSelect = function(value, callback) {
		
		var catsObj = new Object;
		
		$.each(vidsArr, function(i,cat){
										   
			catsObj[cat.friendly] = cat.name;
										 
		});
		
		$('#video_cats').addOption(catsObj, false);
		
		if (value != '') {
			
			$('#video_cats').selectOptions(value, true);
			
		}
		
		callback();
		
	};
	
	var buildList = function(callback) {
		
		$('#video_list').empty();
		
		getVids = $.grep(vidsArr, function(n) {
											   
			return n.friendly == $('#video_cats option:selected').val();
												   
		});
		
		$('#video_cat_desc').html(getVids[0].description);
									   
		$.each(getVids[0].items, function(i,item){
								   
			$('#video_list').append('<li><a href="cat=' + $('#video_cats option:selected').val() + '&amp;vid=' + item.friendly + '">' + item.title + '</a> (' + item.date_long + ')</li>');
		
		});
		
		callback();
		
	};
	
	var loadVid = function (vidItem) {
		
		getItem = $.grep(getVids[0].items, function(n) {
										   
			return n.friendly == vidItem;
										   
		});
		
		if ($.address.path() != '/') {
			
			$.address.title(getItem[0].title + ' | Cato on Campus - Videos');
			
		}
		
		swfobject.removeSWF('player2');
		
		if ( $('#player').size() == 0 ) {
		
			$('#player_container').prepend('<p id="player"><a href="http://www.macromedia.com/go/getflashplayer">Get Flash</a> to see this player.</p>');
			
		}
		
		var embedCode = encodeURIComponent ('<object name="player" id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9.0.115" width="480" height="275"><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.catooncampus.org/mediaplayer/player.swf"> <param name="allowfullscreen" value="true"> <param name="flashvars" value="config=http://www.catooncampus.org/mediaplayer/media_embed.xml?cat=' + $('#video_cats option:selected').val() + '%2526vid=' + getItem[0].friendly + '"> <embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="480" height="275" src="http://www.catooncampus.org/mediaplayer/player.swf" allowfullscreen="true" allowscriptaccess="always" flashvars="config=http://www.catooncampus.org/mediaplayer/media_embed.xml?cat=' + $('#video_cats option:selected').val() + '%2526vid=' + getItem[0].friendly + '"></embed></object>');
		
		var flashvars = {
			streamer:"rtmp://flash.edgecastcdn.net/000873/"+getItem[0].archive,
			file:getItem[0].file,
			duration:getItem[0].playtime,
			start:getItem[0].start,
			respectduration:"true",
			autostart:"false",
			usefullscreen:"true",
			title:getItem[0].title,
			shuffle:"false",
			debug:"console",
			icons:"true",
			provider:"rtmp",
			plugins:"gapro-1,viral-2",
			"viral.matchplayercolors":"true",
			"viral.onpause":"true",
			"viral.oncomplete":"true",
			"viral.allowmenu":"true",
			"viral.functions":"embed,link",
			"viral.embed":embedCode,
			"viral.email_subject":"I like this video from Cato on Campus: " + getItem[0].title,
			"viral.email_footer":"Check out more exciting multimedia from the Cato Institute: http://www.cato.org/multimedia/",
			"viral.link":encodeURIComponent ("http://www.catooncampus.org/videos#/cat=" + $('#video_cats option:selected').val() + "&vid=" + getItem[0].friendly),
			"dock":"true",
			"gapro.accountid":"UA-1677831-12"
		}
		
		var params = {
			allowfullscreen:"true",
			allowscriptaccess:"always",
			allownetworking:"all"
		}
		
		var attributes = {
			id:"player2",
			name:"player2"
		}
		
		swfobject.embedSWF("/mediaplayer/player.swf", "player", "480", "275", "9.0.115", false, flashvars, params, attributes);
		
		$('#video_description').html(getItem[0].description);
		
	};
	
	var buildPage = function(event) {
		
		var selVal;
		var vidVal;
		var vidUrl = event.value.replace('http://www.catooncampus.org/','');
		
		if (vidUrl == '/') {
			
			selVal = '';
			vidVal = '';
			
		} else {
			
			selVal = getParameterByName( 'cat', vidUrl.replace('/', '?') );
			vidVal = getParameterByName( 'vid', vidUrl.replace('/', '?') );
			
		}
		
		loadJSON(function() {
			
			buildSelect(selVal, function() {
								 
				$('#video_cats').change(function() {
									
					$.address.value('cat=' + $('#video_cats option:selected').val());
									
				});
				
				buildList(function() {
					
					$('#video_list li a').address();
					
					if (vidVal == '') {
					
						loadVid (getParameterByName( 'vid', $('#video_list li a').eq(0).attr('href') ));
						
					} else {
						
						loadVid (vidVal);
						
					}
								   
				});
				
			});	
			
		});
		
	};
	
	$.address.change(function(event) {
					 
		buildPage (event);
		
	});

});