$(document).ready(initVideos);

function initVideos()
{
	var html = '';
	for( var i=0, len=videos.length; i<len; ++i )
	{
		html += makeVidListEntry(i);
	}
	$('#more_video').html(html);
	
	showVideo( Math.floor( Math.random()*len) );
}

function makeVidListEntry(idx)
{
	var vid = videos[idx];
	var desc = truncateText( vid['description'], 70 );
	var html = '<a href="javascript:showVideo(' + idx + ')"><div class="videos">'
	+ '	<div class="video_thumb"><img src="' + vid['thumbnail'] + '" class="more_v_thumb"/></div>'
	+ '	<div class="thumb_title">' + vid['title'] + '</div>'
		+ '	<div class="thumb_desc">' + desc + '</div>'
		+ '	<div class="view_video">View Video</div>'
		+ '</div></a>';
	return html;
}

function truncateText( str, maxChars )
{
	if( str.length <= maxChars+3 )// +3 for elipsis
		return str;
	var re=new RegExp('(.{1,'+maxChars+'})\\b');
	var matched = str.match(re);
	/*var shortStr = str.substr( 0, maxChars );
	var spaceIdx = shortStr.lastIndexOf( ' ' );
	var retStr = shortStr.substr( 0, spaceIdx ) + '...';*/
	var retStr = (matched == null ) ? '' : matched[1] + '...';
	return retStr;
}

function showVideo(idx)
{
	var vid = videos[idx];
	embedVid(idx);
	$('#video_title').html( vid.title );
	$('#video_text').html( vid.description );
}

function embedVid(idx)
{
	var replaceElem = 'vid_outer';
	var width = '536';
	var height = '320';
	var flashParams = {
		'allowfullscreen':'true',
		'allowscriptaccess':'always'
	};
	
	var vidId = videos[idx]['id'];
	
	var swfUrl = 'http://vimeo.com/moogaloop.swf?clip_id='
			+ vidId
			+ '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;show_title=0&amp;color=&amp;fullscreen=1';
	swfobject.embedSWF(swfUrl, replaceElem, width, height, '9.0.0', null, null, flashParams );
}

