/*
 * Cellblock general-purpose management console, a component of
 * the Gloto Platform.  See www.gloto.com for more information,
 * terms, and licensing.
 *
 * Copyright (C) 2005-2010, Gloto Corp.
 * http://www.cellblock.com/terms.htm
 */

function Caption( resources )
{
	var caption = this;
	this.resources = resources;
	var flashVars = createFlashVars();  

	this.embedPlayer = function( elementId, startIndex, displayModel, pauseOnStart )
	{    
		util.getElement( elementId ).innerHTML = caption.createEmbed( startIndex, displayModel, pauseOnStart );
	};  

	this.embedGallery = function( )
	{
		caption.gallery = new Gallery( caption.resources.aka, caption.resources.container, caption.resources.perPage, caption.resources.paging, caption.resources.click );
		caption.gallery.loadThumbnails();
	};

	this.embedWinner = function( id, width, height, target, clickEvent ){
                function createClick(data){
                  return function(){ if(clickEvent) clickEvent(data); };//caption.launchPopUp(frameId,"comment",true); };
                };

		var target = util.clear( target );
		var src = config.getPublicUrl("gallery") + "/" + id + "-" + width + "x" + height + ".jpg";
		util.createElement({
			type: "img",
			className: "pointer",
			src: src,
			parentNode: target,
                        onclick: createClick( id )
		});
	};
	
	function createFlashVars(){	    
		var obj = {
				"cbId": config.getId(),
				"contextUrl":config.getContextDisplay(true)
		};

		return obj;
	};

	function getFlashVars( additionalParams )
	{
		var buf = "";
		for( key in flashVars )
		{
			if( flashVars[key] )
			{
				buf += (buf.length > 0 ? "&" : "") + key + "=" + flashVars[key];
			}
		}

		if( additionalParams )
		{
			for( key in additionalParams )
			{
				if( additionalParams[key] )
				{
					buf += (buf.length > 0 ? "&" : "") + key + "=" + additionalParams[key];
				}
			}
		}
		return buf;
	}

	this.createEmbed = function( startAt, displayModel, pauseOnStart )
	{
		var moreParams = {};
		if( startAt ){
			moreParams["startIndex"] = startAt;
		}
		if( displayModel ){
			moreParams["displayModel"] = displayModel;
		}

		if( pauseOnStart ){
			moreParams["pauseOnStart"] = pauseOnStart;	
		}

		var embedCode = "<object width='400' height='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0'>";
		embedCode += "<param name='movie' value='" + config.getPublicUrl("flash") + "/cellblockPlayer.swf' />";
		embedCode += "<param name='FlashVars' value='" + getFlashVars( moreParams ) + "'/>";
		embedCode += "<embed FlashVars='" + getFlashVars( moreParams ) + "' ";
		embedCode += "src='" + config.getPublicUrl("flash") + "/cellblockPlayer.swf'" +
		"width='400' height='370' swLiveConnect='true'> </embed>";
		embedCode += "</object>";
		return embedCode;
	};  

	this.launchPopUp = function( frameId, action, navigation )
	{
		if( action == "caption" ){
			window.open("caption.html?realm=" + config.getRealm() + "&cb=" + config.getId() + "&frame=" + frameId, "detail", "height=600,width=450,scrollbars=yes,resizable=no,status=no,toolbar=no" );
		}else if( action == "comment" ){
			window.open("comment.html?realm=" + config.getRealm() + "&cb=" + config.getId() + "&frame=" + frameId, "detail", "height=600,width=450,scrollbars=yes,resizable=no,status=no,toolbar=no" );
		}
	};	  

	function Gallery( aka, domContainer, thumbnailsPerPage, pagingContainer, clickEvent )
	{		
		var gallery = this;
		this.aka = aka;
		this.frameArray = new FrameArray();
		var _uid = 1;
		var page = 0;
		var pageCount = 0;
		var domContainer = util.clear( domContainer );
		var pagingContainer = util.getElement(pagingContainer);
		var thumbnailsPerPage = thumbnailsPerPage || 40;

		var pageWidget = util.getElement( pagingContainer );
		pageWidget.setAttribute( 'id', pagingContainer );  

		// Thumbnails Setup
		var thumbnailWidget = document.createElement( 'div' );
		thumbnailWidget.setAttribute( 'id', 'thumbnailWidget' );
		domContainer.appendChild( thumbnailWidget );

		this.setFirstPage = function(){
			page = 0;
		};

		this.setLastPage = function(){
			page = pageCount - 1;
		};

		this.loadThumbnails = function( newMode, sortBy, refresh, callback )
		{	
			page = 0;
			api.numFrames( gallery.aka, function( data ){
				setCount(data, callback);
			});
		};

		this.getPage = function(){
			return page;
		};

		this.changePage = function( i )
		{
			page = i;
			generatePaging();
		};

		function setCount( data, callback )
		{
			if( util.valid( data ) )
			{

				pageCount = Math.floor( data.count / thumbnailsPerPage );

				// Add a partial page for the last few frames
				if( data.count % thumbnailsPerPage > 0 )
				{
					++pageCount;
				}

				if( page >= pageCount && page > 0 ){ // check for out of bounds
					--page;
				}
			}else{
				util.error( data );
			}

			generatePaging(callback);
		}

		function generatePaging(callback)
		{	
			// Clear Select all state
			var selectAll = util.getElement("selectAll");
			if( selectAll != null ){
				selectAll.setAttribute("state", null);
			}

			util.createPaging( pageWidget, page, pageCount, "Page: ", null, gallery.changePage );
			api.frameInfo( gallery.aka, calculateIndex(), thumbnailsPerPage, function( data ){
				display(data);
				if( callback )
					callback();
			});
		}

		function calculateIndex()
		{
			return ( page  ) * thumbnailsPerPage;
		}

		function createUID( type )
		{
			_uid++;
			return type + "_" + _uid;
		}

		function display( data )
		{	
			gallery.frameArray.clear();

			var i;

			if(data.frames == undefined)
			{
				return;
			}

			util.clear(thumbnailWidget);
			for( i = 0; i < data.frames.length; i++ )
			{
				var frame = data.frames[i];
				var id = createUID( "thumbnail" );
				var type = ("video/x-flv" == frame.mime) ? "video" : "image";
				var foo = new Frame({
					id: frame.id,
					mime: frame.mime,
					thumbnail: frame.thumbnail,
					medium: frame.medium,
					full: frame.full,
					caption: frame.caption,
					sourceAddress: frame.sourceAddress,
					embedCode: frame.embedCode,
					spanId: id
				});

				var index = gallery.frameArray.addFrame(foo);

				var frameObj = gallery.frameArray.getFrame(index);    

				var span = util.createElement({
					type: "span",
					id: id,
					className: "thumbnail",
					parentNode: thumbnailWidget
				});

				var div = util.createElement({
					type: "div",
					id: "thumbnail",
					parentNode: span
				});

				var table = util.createElement({
					type: "table",
					width: "100%",
					height: "100%",
					cellpadding: "0",
					cellspacing: "0",
					parentNode: div
				});

				var tbody = util.createElement({
					type: "tbody",
					parentNode: table
				});

				var tr = util.createElement({
					type: "tr",
					parentNode: tbody
				});

				var td = util.createElement({
					type: "td",
					align: "center",
					valign: "middle",
					parentNode: tr
				});

				function createClick( frame, index ){
					return function(){ if( clickEvent != null ){ clickEvent(frame.id) } };
				};

				var a = util.createElement({
					type: "a",
					href: util.noClick(),
					onclick: createClick( frame, index ),
					parentNode: td
				});

				var img = util.createElement({
					type: "img",
					id: "thumbnail",
					src: frame.thumbnail,
					parentNode: a
				});
			} // for
		} // display
	} // gallery
}
