/**
 * A video bar embedable. Loosely based on code provided by BrightCove
 * @author: Joe Hohertz
 * @version: 1.1
 * @modified: 2009-09-22 [Craig Nagy]
 */
function video_bar_generator(token, defaultsort, basetags) {

	this.token = token || null;
	this.defaultsort = (defaultsort != null) ? defaultsort : 'PLAYS_TRAILING_WEEK';
	this.basetags = basetags || null;

	/**
	 * Total number of videos to display
	 */
	this.num = 4;
	
	/**
	 * Number of videos to display per row
	 */
	this.per_row = 4;
	
	/**
	 * Number of videos to retrieve on each request.
	 * Depending on video status and scheduling, not 
	 * all videos will be displayed; so multiple requests
	 * are made until the number of videos (num) has been filled.
	 * To reduce the number of requests, make this number slightly
	 * larger than the number of videos (num).
	 */
	this.buffer = 10;	
	
	/**
	 * Ref: http://docs.brightcove.com/en/media/#PublicVideoFieldsEnum
	 * If empty, default fields are retrieved. Note that the is_live
	 * function depends on STARTDATE, ENDDATE, and ITEMSTATE
	 */
	this.video_fields = "ID,NAME,SHORTDESCRIPTION,LONGDESCRIPTION,CREATIONDATE,PUBLISHEDDATE,LASTMODIFIEDDATE,STARTDATE,ENDDATE,LINKURL,LINKTEXT,TAGS,VIDEOSTILLURL,THUMBNAILURL,REFERENCEID,LENGTH,ECONOMICS,ITEMSTATE,PLAYSTOTAL,PLAYSTRAILINGWEEK,VERSION,CUEPOINTS,SUBMISSIONINFO,CUSTOMFIELDS,RELEASEDATE,FLVURL,RENDITIONS,GEOFILTERED,GEORESTRICTED,GEOFILTEREXCLUDE,EXCLUDELISTEDCOUNTRIES,GEOFILTEREDCOUNTRIES,ALLOWEDCOUNTRIES,ACCOUNTID,FLVFULLLENGTH,VIDEOFULLLENGTH";
	
	// Resource strings
	this.title = "OTHER CLIPS";
	this.playersite = "http://video.citytv.com";
	this.morelink = "http://video.citytv.com";
	this.moretext = "View More Videos";

	/**
	 * Performs the async request to the BC API and displays
	 * the video information in the destdiv.
	 *
	 * Ref: http://docs.brightcove.com/en/media/
	 */
	this.embed = function(destdiv, tags, title, sort, playersite, itemplayersite, viewMoreText) {

	    var self = this; // reference to the video_bar_generator context
	    var calltags = tags || "";
	    var callsort = sort || this.defaultsort;
	    var calltitle = title || this.title;
	    var callmorelink = playersite || this.morelink;
	    var callmoretext = viewMoreText || this.moretext;
	    var callplayersite = playersite || this.playersite;
	    var callitemplayersite = itemplayersite || this.playersite;
	    var page_number = 0;
	    var max_requests = 50; // prevents infinite recusion
	    var display_count = 0;
	    var localscope = {};

	    if (this.basetags) {
	        calltags += (',' + this.basetags);
	    }

	    // Build and inject initial markup for video list
	    var html = [
			'<div id="Video-Suggestions"><h3 class="title">', calltitle, '</h3>',
			'<a class="moreVideoLink" href="', callmorelink, '">', callmoretext, '</a>',
			'<div class="clr"></div><div class="Video-Clip-List"></div><div class="clr"></div></div>'];
	    $container = $(html.join('')).appendTo(destdiv);
	    // To prevent multiple calls from overlapping
	    localscope[destdiv] = $container.find('div.Video-Clip-List');

	    // Make the initial call
	    $.getJSON(query_url(), display_videos);

	    /**
	    * Callback function for displaying videos
	    */
	    function display_videos(data) {
	        if (data.items && data.items.length > 0) {
	            // loop through our video data to generate each video item's markup
	            $.each(data.items, function(i, item) {
	                if (is_live(item) && display_count < self.num) {
	                    append_video(item);
	                    display_count++;
	                }
	            });

	            // make another request if we haven't filled
	            // the number of videos required
	            if (display_count < self.num && ++page_number < max_requests) {
	                $.getJSON(query_url(), display_videos);
	            }

	        } else {
	            // If no more videos, output nothing
	            //localscope[destdiv].append('<p style="padding:1em;text-align:center;">Sorry, videos clips are temporarily unavailable.</p>');
	        }
	    };

	    /**
	    * Appends a video to the videos list
	    */
	    function append_video(item) {
	        // build HTML for each clip.
	        var h = [
			'<div class="Video-Clip"><div class="Video-Clip-Top"></div>',
	        // link it to the video site
				'<a href="', callitemplayersite, '/video/detail/', item.id, '.000000/',
				item.name.replace(/[^a-zA-Z0-9-_]{1,}/ig, '-'), '/" style="margin: 0pt;">',
	        // thumbnail
				'<img class="Video-Image-Thumbs" src="', item.thumbnailURL, '" alt="video"></a><br>',
	        // title
				'<p><a href="', callitemplayersite, '/video/detail/', item.id,
				'.000000/', item.name.replace(/[^a-zA-Z0-9-_]{1,}/ig, '-'), '/">',
				ellipsis(item.name, 40), '</a></p>',
	        // description
				'<p>', ellipsis(item.shortDescription, 140), '</p>',
			'</div>'];

	        // first video in each row
	        if (display_count % self.per_row == 0) {
	            h[0] = '<div class="firstClip">' + h[0]; h[h.length] = '</div>';
	            // last video in each row
	        } else if (display_count % self.per_row == self.per_row - 1) {
	            h[0] = '<div class="lastClip">' + h[0];
	            h[h.length] = '</div><div class="clr"></div>';
	        }

	        // tack this entry onto the video list
	        localscope[destdiv].append(h.join(''));
	    };

	    /**
	    * Generates the URL to query the BC video api
	    * @see judos (judos.js)
	    */
	    function query_url() {
	        // Generate our query
	        var query = '';
	        if (calltags) {
	            query = judos.getURL("find_videos_by_tags", {
	                "token": self.token,
	                "and_tags": escape(calltags),
	                "sort_by": callsort,
	                "page_number": page_number,
	                "page_size": self.buffer,
	                "video_fields": self.video_fields
	            });
	        } else {
	            query = judos.getURL("find_all_videos", {
	                "token": self.token,
	                "sort_by": callsort,
	                "page_number": page_number,
	                "page_size": self.buffer,
	                "video_fields": self.video_fields
	            });
	        }
	        return query;
	    };

	};       // this.embed
	
	/**
	 * Helper to determine if a video is live based
	 * on it's state and scheduled dates. If neither
	 * dates are set, the video is assumed to be live.
	 */
	function is_live(video)
	{
		if(video.itemState && video.itemState != "ACTIVE")
			return false;
			
		var now = new Date();
		var displayStart = new Date();
		var displayEnd = new Date();
		if(video.startDate) displayStart.setTime(video.startDate);
		if(video.endDate) displayEnd.setTime(video.endDate);
		
		if(video.startDate && video.endDate)
			return now >= displayStart && now <= displayEnd;
		else if(video.startDate)
			return now >= displayStart;
		else if(video.endDate)
			return now <= displayEnd;
		else
			return true;
	};
	
	/**
	 * Restricts the length of a string to a given
	 * number of characters.
	 */
	function ellipsis (text, size) {
		var newtext = text;
		if (newtext.length > size) {
			newtext = newtext.substring(0, size);
			newtext = newtext.replace(/\w+$/, '');
			newtext = newtext + "..."
		}
		return newtext;
	};
};


