// Globals
var streams = [];
var videoCount = 16; // must be square of 2 for 
var loadedCount = 0;
var embeds = [];
var aspectRatio;

// Grab the URL query variables
// http://stackoverflow.com/questions/439463/how-to-get-get-and-post-variables-with-jquery
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

// Change the video count if we passed one in
if($_GET['count']) {
	videoCount = $_GET['count'];
}


// On Document Ready
$(document).ready(function() {
	//console.log('Document Ready');
	//console.log('jQuery Version ' + $().jquery);
	// Load Some Feeds
	
	jQuery.getJSON('http://api.justin.tv/api/stream/list.json?category=social&jsonp=?', function(json) {
		
		//console.log('Feeds Received:');		
		
		for (var i in json) {
			////console.log(i);
			
			// Make sure it meets our requirements.
			if((json[i].stream_type == 'live') && 
				 (json[i].channel.subcategory == 'lifecasting') &&
				 (json[i].channel.mature == false) &&
				 (json[i].channel.embed_enabled == true) &&
				 (loadedCount < videoCount)) {
			
				 	// Go ahead and add it
				 	//console.log(json[i].channel.login);
				 	
				 	// Create a div to hold the video
				 	$('#wrapper').append('<div class="video" id="' + json[i].channel.login + '"></div>');
				 	
				 	// Place the player inside the div
				 	var thisPlayer = jtv_api.new_player(json[i].channel.login, {'channel': json[i].channel.login,
				 																									'consumer_key':'PcoohlDmGOhTWhGvDpjew',
				 																									'auto_play':true, 
				 																									'custom':true,
				 																									'watermark_position':'bottom_right'});

					// Add the stream to the list so we can controll it later				 																									
				 	streams.push(thisPlayer);
				 	
				 	// Decrement the limit
				 	loadedCount++;
				 	

				 	
			}
		}
		
		embeds = $('.video embed');
		embeds.height(265); // set them to 4:3 aspect ratio to avoid bars, 353 x 265
		
		// start listening for resize events, then run the resize routine once so everything starts correctly
		$(window).bind('resize', function () {
			resizeProcedures();
		});
		resizeProcedures();			
					

		
		
	});

});



// RESIZING
var resizeProcedures = function() {
	//console.log('resizing');
	
	// First fit the big rect, with the same aspect ratio as one of the videos	
	// TK better maximization of space... find rows, cols, then size to closest that will fit?
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	var wrapper = $('#wrapper');
	var aspectRatio = 4 / 3;


	if((windowWidth / windowHeight) > aspectRatio) {
		// Landscape, set relative to height
		wrapper.width(windowHeight * aspectRatio);
		wrapper.height(windowHeight);
	}
	else {
		// Portrait, set relative to width
		wrapper.width(windowWidth);
		wrapper.height(windowWidth / aspectRatio);
	}

/*
	embeds.width(wrapper.width() / videoCount);
	embeds.height(wrapper.height() / videoCount);	
*/
	
	
	// total area
	var totalArea = wrapper.width() * wrapper.height();
	var eachArea = totalArea / videoCount;
	
	// find multiplier to fill area
	var multiplier = Math.sqrt((eachArea / 12));
	
	embeds.width(4 * multiplier);
	embeds.height(3 * multiplier);

}



// Thanks to http://www.vaughn.tv/
// Gives us a flash object we can call external interface functions on
// Full list here: http://apiwiki.justin.tv/mediawiki/index.php/Live_Video_SWF_Documentation
function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}




