//
// note: relies on Thickbox being in place and MUST be called after thickbox 

// should we manually trigger cycle by carousel?
//

var token     = '4c5c0f1c156391199ccaf8993ea13aa4';
var auto_play = 'false';
var show_play = 'true';
var player    = 'http://cdn-akm.vmixcore.com/core-flash/UnifiedVideoPlayer/UnifiedVideoPlayer.swf';
var path      = 'http://media.kansascity.com/';
var appendage = '<img src="'+path+'images/media-player/next.png" class="media-next prev-next" alt="&raquo;" />';
var ap        = false;		
var loaded    = false;

$(document).ready(function() {
 	$('#media-player #thumbs').append('<ul id="thumbslist"></ul>');
 	
 	// Create cycle and thumbnails, but do not start cycle -- use timeout:0 for manual control
	$('#media-full').show();
	$('#media-full').cycle({ 
	    fx:    'fade', 
	    speed:  600, 
    	 timeout: 0, 
    	 cleartype:  1,
    	 pager:  '#thumbslist',
    	 pagerAnchorBuilder: function(idx, slide) { // callback fn that creates a thumbnail to use as pager anchor 
           var src = $('img',slide); 
           if ($(src).attr('class')) { // it found id because we loaded an image from workbench
           		src = $(src).attr('class').replace('thumb-', '');
           		return '<li id="photo-thumb-'+idx+'" style="background-image: url('+src+')"></li>'
           } else {
           		return '<li id="vid-thumb-'+((idx/2)+1)+'"></li>';
           }
       }
 	});
 	
 	// get videos from vmix and fill in lists
	createMediaPlayer();	
	
	//set the initial selected li
 	$('#media-player #thumbs li').eq(0).addClass('selected');
	$("#ourvid").append(appendage); 

	// and add "show gallery" image on remaining non-video list items
	$('#media-full li p a').append('<img src="'+path+'images/media-player/show-gal.png" class="showgal" alt="show gallery" />');
 	
 	
 	// ACTIONS
 	// When clicking a thumb, reset "selected", and temporarily pause slides
	$('#media-player #thumbs li').click( function() {
    	$('#media-player #thumbs li').removeClass('selected');
    	$(this).addClass('selected');
		pause_slides();
		t = setTimeout('resume_slides()', 6000);
    });
	
	// show/hide AP content
	$('#apbug').click(function (e) {
		e.preventDefault();
		if (ap == false) {
			$('#ourvid').hide();
			$('#apvid').show();
			ap = true;
			$('#apbugger').html('Hide');
		} else {
			$('#ourvid').show();
			$('#apvid').hide();
			ap = false;
			$('#apbugger').html('Show');
		}
	});
});


// HELPERS:
// create a thickbox and populate it with the appropriate info
$('.tb_trigger').live('click', function() {
	hed = $(this).parent().find('h4').html();
	desc = $(this).parent().find('p.vid_caption').html();
	id = $(this).attr('id').replace('vmix','');
	vid = buildObject(id, id, true, false);
	tb = vid + 
	'<div class="right media-sharebox">'+
	'Link: <input type="text" value="http://videos.kansascity.com/vmix_hosted_apps/p/media?id='+ 
	$(this).attr('rel') + '" onClick="this.select()" readonly="readonly">' +

	'Share: <textarea onClick="this.select()" readonly="readonly">' +
	 vid.replace(/^\s*|\s*$/g,'') + 
	'<p style="margin:0"><a href="http://www.kansascity.com">Kansas City Star Video</a></p>'+
	'</textarea></div>'+
	'<h4>'+ hed + '</h4>'+
	'<p>' + desc + '</p>';
	
	$('#vidhold').html(tb);
	tb_show(hed, "#TB_inline?height=470&width=630&inlineId=vidhold");
	pause_slides();
});


//pause and resume slideshows
function pause_slides() {
	$('#media-player #thumbs').addClass('paused');
}

function resume_slides() {
	$('#media-player #thumbs').removeClass('paused');
}


//Override the default thickbox tb_remove to add in our resume functionality 
function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	
	resume_slides();
   return false;
}


// Get vids from Vmix and fill in thumbnail list
function createMediaPlayer() {
	$.getJSON('/cgi-bin/php/vmixer.php?api=media&action=getMediaList&params='+escape('limit=5&genre_ids=00004698&alltime=1'), function(r) {
	//$.getJSON('/static/vmix/vmixer_front.html', function(r) {
	   // we're going to build the thumbs first		
		//console.log(r)
		for (i in r){
			if (r[i].title) {
		   	inti = parseInt(i)+1;
			   $('li#vid-thumb-'+inti).attr('title',r[i].title).attr('rel', r[i].token).css('backgroundImage','url(http://image.vmixcore.com/imgman.jpg?width=100&height=80&url='+r[i].thumbnail[0].url+')');
			   //console.log('built thumb')
		  }
		}

		for (i in r){
			if (r[i].title) {
	   	inti = parseInt(i)+1;
		   	vidstring='<p class="tb_trigger" id="vmix'+r[i].token+'" rel="'+ r[i].id+'">'+
							 '<img src="http://image.vmixcore.com/imgman.jpg?height=300&url='+r[i].thumbnail[0].url+'" alt="">'+
							 '<img src="'+path+'images/media-player/show-vid.png" class="showgal" alt="show video" /></p>'+
						 	 '<h4>'+r[i].title.replace('Raw Video: ','')+'</h4>'+
						 	 '<p class="hide vid_caption">'+r[i].description+'</p>';
				$('#media-full li#vid-'+inti).html(vidstring);
			}
		}
		 	// begin thumbs carousel, and use it to control media-full cycle above
	 	$("#media-player #thumbs").show();
	 	$('#media-player #thumbs').jCarouselLite({
	     	auto: 6000,
	     	speed: 500,
			visible: 3,
			btnNext: "#media-player .media-next",
			btnPrev: "#media-player .media-prev",
			start: -1,
			beforeStart: function(a) {
				var index = $("#media-player #thumbs li").index($(a).eq(1));
	     		//$('#debug').html("Before animation starts:" + index);
				$('#media-player #thumbs li.selected').removeClass('selected');
				mod_index = (index-2);
				if (mod_index > 9){
					mod_index = mod_index-10
				}
				$('#media-full').cycle(mod_index);
	     	},
	 		afterEnd: function(a) {
	     		$(a).next().slice(0,1).addClass('selected');
	 		}
	 	}); 	 		
	});
};



// build a flash object with the appropriate video
function buildObject(id, token, auto_play, show_play) {
 	flashvar = 'show_control_bar=true&ad_service=vmix&ad_target=genre=Local&token='+
 	    token+'&auto_play='+auto_play+'&show_play_icon='+show_play;
	newObject = '<object type="application/x-shockwave-flash" data="'+ player +'" width="608" height="380" id="vmix'+id+'">'+
		    		'<param name="movie" value="'+player+'" />'+
		    		'<param name="allowfullscreen" value="true" />'+
	     			'<param name="allowscriptaccess" value="always" />'+
	     			'<param name="swliveconnect" value="true" />'+
	     			'<param name="wmode" value="transparent" />'+
	     			'<param id="flashvars" name="flashVars" value="'+flashvar+'"/>'+
	     			'<param name="flashVersion" value="8" />'+
	     			//'<h2>You do not appear to have <a href="http://www.adobe.com/go/getflashplayer">Flash</a> installed.</h2>' +
	     			'</object>';
	  
	return newObject
};

