	var position;
	var width;
	var thumbTimer = null;
	var thumbTimerActive = false;
	var playerIdle = true;
	var mute = true;
	var volume = .7;
	var currentTimecode = 0;
	var startTimeOffset = 0;
	var hasTimeCodes = false;
	
	$(document).ready(function() {
		$('.thumbnaildiv').each(function() {
			$(this).find('img').hover(
					function() {						
						$('.current_thumb').removeClass('current_thumb');
						$(this).addClass('current_thumb');
						thumbTimerActive = true;
						if(document.getElementById('thumbnailPlayer')) {
							thumbTimer = setTimeout('playThumbnail()', 500);
						}						
    				},
    				function() {	    				
    					$('.current_thumb').removeClass('current_thumb');
    					if (thumbTimerActive) {
							thumbTimerActive = false;
							clearTimeout(thumbTimer);
							hasTimeCodes = false;
						}						
    				}
			);
			$('#playerDiv').mouseleave(
					function(){
						$('.thumbnaildiv').css({'background': ''});
						$('.pdivbackrnd').remove();
						var player = document.getElementById('thumbnailPlayer');
						player.pauseMovie();
						playerIdle = true;
						mute = true;
						hasTimeCodes = false;
						
						$('a.player_volume').removeClass('volumeOn');						
						$('.current_thumb').removeClass('current_thumb');						
						$(".player_loading").show();
						
//						$("#mini_player").css({
//							'width':'0',
//							'height':'0',
//    						'overflow':'hidden'});
						$('#playerDiv').css({
							'position':'absolute',
							'top':'-1000px',
							'left':'-1000px'});
					});
		});
	});
	
	function playThumbnail() {
		if (!thumbTimerActive) return;
		
		var charEllipses = String.fromCharCode(8230);
		
		thumbTimerActive = false;
		var data;
		try {
			data = $('.current_thumb').parent().parent().metadata({type: 'attr', name: 'meta'});
		} catch (e) {}
		//alert(data.embedCode);

		var timecodeShowDefault = 6;
		var thumb = $('#'+data.embedCode);
		var playerDiv = $('#playerDiv');
		position = $(thumb).parent().position();

		position = $('.current_thumb').offset();

		if (data.showVol == 1) {
			playerDiv.find('.player_volume').show();
		}
		else {
			playerDiv.find('.player_volume').hide();
    	}
    	
		var path = data.lib.split('%2F');
    	var url = "/index/detail/lib/" + path[0];
    	
    	if (path.length > 1) {
			url = url + "/sublib/" + path[1];
    	}
		
    	url = url  + "/ec/" + data.embedCode;
    	
	    playerDiv.find(".timecodes_container").hide();
    	var timecodes = data.timecodes;
    	if (timecodes) {
    		timecodeShow = (timecodes.length > timecodeShowDefault) ? timecodeShowDefault : timecodes.length;
    		var timecodeSpan = '';
	    	for (var i = 0; i < timecodeShow; i++) {
	    		if (i > 0)
	    			timecodeSpan += '&nbsp;';
	    		timecodeSpan += '<a href="javascript:playAt(' + timecodes[i] + ');">' + (i+1) + '</a>';
	    	}
	    	if (timecodeSpan != '') {
    			hasTimeCodes = true;
    			if (data.keyword.indexOf(' ') == -1) {
    				if (data.keyword.length > 10) {
    					data.keyword = data.keyword.slice(0, 10);
    					data.keyword = data.keyword + charEllipses;
    				}
	    			keywordSpan = "<em>" + data.keyword +"</em> found at:";
		    		playerDiv.find(".timecodes_header")
		    		         .html(keywordSpan);
		    	}
    			playerDiv.find(".timecodes")
	    		         .html(timecodeSpan);
	    		playerDiv.find(".timecodes_container")
    					 .show();
    					 
    			url = url + "/offset/" + timecodes[0];
	    	}
		}
		
	/* Limits Title length to a max of 15 characters to prevent overflow */
		var movTitle = data.title;
		if (movTitle.length > 15) {
			movTitle = movTitle.slice(0, 15);
			movTitle = movTitle + charEllipses;
    	}
					
   		playerDiv.find('.title').html(movTitle);
		playerDiv.find('.title').attr('href', url);
		playerDiv.find('.btn_details').attr('href', url);
		playerDiv.find('.description').html(data.description);
		playerDiv.find('.duration').html(data.duration);
		playerDiv.find('.air_date').html(data.airDate);
		playerDiv.find('.play_count').html(data.playCount);
		
		$('.current_thumb').removeClass('current_thumb');
		
//		$("#mini_player").css({
//			'width':'0',
//			'height':'0',
//    		'overflow':'hidden'});
		playerIdle = true;
		currentTimecode = 0;
		startTimeOffset = data.timeoffset;
		
		try {
			document.getElementById('thumbnailPlayer')
		        .setQueryStringParameters({embedCode: data.embedCode, 
		                                   height: data.height, 
		                                   width: data.width, 
		                                   autoplay: 1, 
		                                   hide: 'all', 
		                                   layout: 'chromeless'});
		} catch (e) {}                                  
		
		$('.player_status').html('Loading...');
		$(".player_loading").show();		                                   
		                                   
		$('#playerDiv').css({
			'position':'absolute',
			'top':Math.round(position.top)+'px',
			'left':Math.round(position.left)+'px'
		});			
    }
    
    function playAt(startingTime) {
    	try {
//    		if (playerIdle) return;
    		currentTimecode = startingTime;
    		var player = document.getElementById('thumbnailPlayer');
    		try {
    			player.skipAd();
    		} catch(e) {}
    		player.setPlayheadTime(startingTime);
    		player.playMovie();
			url = $('#playerDiv').find('.title').attr('href');
			url = url.replace(/\/offset\/(\d*)$/i, '/offset/' + startingTime);
			$('#playerDiv').find('.title').attr('href', url);
			$('#playerDiv').find('.btn_details').attr('href', url);
    	} catch (e) { /*alert(e.message);*/ }
    }
    
    function toggleVolume() {
//    	if (playerIdle) return;
    	if (mute) {
    		// unmute
    		document.getElementById('thumbnailPlayer').setVolume(volume);
    		$('.player_volume').html('Unmuted');
    		mute = false;
    	}
    	else {
			document.getElementById('thumbnailPlayer').setVolume(0);
    		$('.player_volume').html('Muted');
			mute = true;
		}
    }
    
	function thumbnailPlayerEvent(playerId, eventName, eventArgs) {
		var ciecc, ttc, ecc, vc;
		switch (eventName) {
			case 'apiReady':
				if (mute) {
					document.getElementById(playerId).setVolume(0);
				}
				if (startTimeOffset > 0) {
					$('.player_status').html('Buffering..');
					playAt(startTimeOffset);
				}
				break;
			case 'playheadTimeChanged':
				$('.player_status').html(formatTime(eventArgs.playheadTime));
				if (playerIdle) {
					$(".player_loading").hide();
				}
				break;
			case 'seeked':
				$('.player_status').html('Buffering...');
				break;
			case 'stateChanged':
				if (playerIdel)
					playerIdle = false;
				$('.player_status').html(eventArgs.state);
				break;
			case 'adStarted':
				document.getElementById(playerId).skipAd();
				break;
//			case 'startContentDownload':
//				$('.player_status').html('Downloading...');
//				break;
			default:
//				$('.player_status').html(eventName);
		}
    }
	
	/**
	 * Converts an int to a string with padding
	 * @param int Integer to convert
	 * @param int Length of resulting string
	 * @param string Character to use for padding, defaults to 0
	 * @returns string
	 */
	function strPad(i,l,s) {
		var o = i.toString();
		if (!s) { s = '0'; }
		while (o.length < l) {
			o = s + o;
		}
		return o;
	};
	
	/**
	 * Formats a timecode
	 * @param int Time value measured in seconds
	 * @returns string Formatted timecode
	 */
	function formatTime(time) {
		var secs = parseInt(time % 60);
		var mins = parseInt(time / 60) % 60;
		var hours = parseInt(time / 3600);
		try {
			return hours.toString()+':'+strPad(mins,2)+':'+strPad(secs,2);
		} catch (e) {
			return e.message;
		}
    }
