var mavenVideo = function(){
/*
INPUTS
-- theContainer
   id of the HTML element to be populated
-- theUrl
   url of the feed
-- type
   CSS class that will determine the orientation
   of the HTML to be returned...mavenDefault for 
   left-to-right in the left column, mavenAlt for
   top-to-bottom in the right column)
-- destUrl
   the destination url (the page the Maven player resides on) value=# if you want to stay on the same page
-- startIndex,
   the start index ("if the start index is at 3,
   start at the 4th item in the feed")
-- feedDataType
   data type of the feed (optional)...currently the only two options are RSS and JSON...if no data type is specified, the script assumes JSON.
*/
	var pmd = {};
	return	{
 		init: function( theContainer, theUrl, type, destUrl, startIndex, feedDataType, playlist, playerMetadata ) {
 		   if (playerMetadata) mavenVideo.readPlayerMetadata(playerMetadata);
 		   mavenVideo.renderVideos(
 		                           theContainer, theUrl, type,
 		                           destUrl, startIndex, feedDataType, playlist
 		                           );
 		},
 		
 		readPlayerMetadata : function (playerMetadata){
 			pmd.container=(playerMetadata.container)?playerMetadata.container:null;
 		  pmd.height=(playerMetadata.height)?playerMetadata.height:null;
 		  pmd.width=(playerMetadata.width)?playerMetadata.width:null;
 		  pmd.bgColor=(playerMetadata.bgColor)?playerMetadata.bgColor:null;
 		  pmd.playerId=(playerMetadata.playerId)?playerMetadata.playerId:null;
 		  pmd.linkTarget=(playerMetadata.linkTarget)?playerMetadata.linkTarget:null;
 		},
 		renderVideos: function( theContainer, theUrl, type, destUrl, startIndex, feedDataType, playlist ) {
 		   //var theEvent = this;
 		   //alert(theEvent);
 		   try {
 		      var requester = new XMLHttpRequest();
 		   } catch( error ) {
 		      try {
 		         var requester = new ActiveXObject( "Microsoft.XMLHTTP" );
 		      } catch( error ) {
 		         var requester = null;
 		      }
 		   }
 		
 		   if ( requester != null ) {
 		      /*theEvent._timer = setTimeout(
 		         function(){
 		            requester.abort();
 		            mavenVideo.writeError("The server is unable to process the request at this time.");
 		         },
 		      10000); */
 		      requester.open( "GET", theUrl, true );
 		      requester.onreadystatechange = function() {
 		        /* clearTimeout(theEvent._timer); */
 		        if ( requester.readyState == 4 ) {
 		          if ( requester.status == 200 || requester.status == 304 ) {
 		             //choose rendering based on datatype
 		             //default to JSON if no datatype provided
 		             switch( feedDataType ) {
 		                 case 'RSS':
 		                    mavenVideo.writeFromRss(
 		                                            requester.responseXML, theContainer, type,
 		                                            destUrl, startIndex, playlist
 		                                            );
 		                 break;
 		                 case 'JSON':
 		                    mavenVideo.writeFromJson(
 		                                             requester.responseText, theContainer, type,
 		                                             destUrl, startIndex, playlist
 		                                             );                     
 		                 break;
 		                 default:
 		                    mavenVideo.writeFromJson(
 		                                             requester.responseText, theContainer, type,
 		                                             destUrl, startIndex, playlist
 		                                             );
 		                 break;
 		             }
 		          } else {
 		            mavenVideo.writeError( 'The server was unable to be contacted.' );
 		          }
 		        }
 		      };
 		      requester.send( null );
 		   }
 		},
 		
 		writeFromRss: function( responseXml, theContainer, type, destUrl, startIndex, playlist ) {
 		
 		   //tidy container
 		   var videoBag = document.getElementById( theContainer );
 		   while ( videoBag.hasChildNodes() ) {
 		      videoBag.removeChild( videoBag.lastChild );
 		   }
 		
 		   //set up counter and startIndex
 		   var data = responseXml.getElementsByTagName( 'item' );
 		   if ( startIndex > data.length ) {
 		      startIndex = 0;
 		   }
 		
 		
 		   //write out the data
 		   for (var i = startIndex; i < data.length; i++ ) {

					if (i > startIndex+4) break;
 		
 		      // get the XML data
 		      var clipTitle = data[i].getElementsByTagName('title')[0].firstChild.nodeValue;
 		      var clipLength = (data[i].getElementsByTagName('duration')[0]) ? data[i].getElementsByTagName('duration')[0].firstChild.nodeValue : "";
 		      if (data[i].getElementsByTagName('videoId')[0]){
 		      	var clipID = data[i].getElementsByTagName('videoId')[0].firstChild.nodeValue;
 		    	} else {
 		    		//parse link property
 		    		var clipID = data[i].getElementsByTagName('link')[0].firstChild.nodeValue.split('maven_referralObject=')[1].replace(/<\/link>/g,"");
 		    	}
 		
 		      if ( document.getElementsByTagNameNS ) {
 		         var clipImgPre = data[i].getElementsByTagNameNS('*','thumbnail');
 		         var clipImg = clipImgPre[0].getAttribute('url');
 		         var clipDescPre = data[i].getElementsByTagNameNS('*','description');
 		         var clipDesc = clipDescPre[0].firstChild.nodeValue;
 		      } else {
 		         clipImg = data[i].getElementsByTagName('media:thumbnail')[0].getAttribute('url');
 		         clipDesc = data[i].getElementsByTagName('media:description')[0].firstChild.nodeValue;
 		      }
 		
 		      //write out the data
 		      mavenVideo.writeUpdate( videoBag, type, destUrl, clipTitle, clipImg, clipDesc, clipLength, clipID, playlist );
 		   }
 		
 		},
 		
 		writeFromJson: function( responseText, theContainer, type, destUrl, startIndex, playlist ) {
 		
 		   var data = eval( '(' + responseText + ')' );
 		
 		   //get the data and ensure only 5 results get returned
 		   var dataExtracted = new Array();
 		   var dataItems = data.items;
 		
 		   for ( i = 0; i < dataItems.length; i++ ) {
 		      dataExtracted.push( dataItems[i] );
 		   }
 		
 		   if ( startIndex > dataExtracted.length ) {
 		      startIndex = 0;
 		   }
 		
 		   var firstFive = dataExtracted.splice( startIndex, 5 );
 		
 		   //tidy container
 		   var videoBag = document.getElementById( theContainer );
 		   while ( videoBag.hasChildNodes() ) {
 		      videoBag.removeChild( videoBag.lastChild );
 		   }
 		
 		   //write out the data
 		   for ( i = 0; i < firstFive.length; i++ ) {
 		      //get the JSON data
 		      var clipTitle = firstFive[i].title;
 		      var clipImg = firstFive[i].thumbnailURL;
 		      var clipDesc = firstFive[i].description;
 		      var clipLength = firstFive[i].length;
 		      var clipID = firstFive[i].contentID;
 		
 		      //write out the data
 		      mavenVideo.writeUpdate( videoBag, type, destUrl, clipTitle, clipImg, clipDesc, clipLength, clipID, playlist );
 		   }
 		
 		},
 		
 		writeUpdate: function( videoBag, type, destUrl, clipTitle, clipImg, clipDesc, clipLength, clipID, playlist ) {
			var ondemandUrl = destUrl+ '?playlistId=' + playlist + '\u0026videoId='+ clipID;
			var onclickCall = 'mavenVideo.loadVideoPlayer(\''+pmd.playerId+'\',\'\',\''+clipID+'\',\''+pmd.width+'\',\''+pmd.height+'\',\''+pmd.bgColor+'\',\''+pmd.container+'\');return false;';
			if (pmd.container == null) onclickCall = "";
			var linkTarget = (pmd.linkTarget)? pmd.linkTarget:"_self";
			var truncDesc = mavenVideo.truncate( clipDesc, 100, '...' );
			var clipDuration = mavenVideo.formatMs(clipLength);
			var summary = '';
			if (type == "mavenAlt"){
				summary = 
					'<div class="summary">'+
						'<h3><a href="'+ondemandUrl+'" target="'+ linkTarget +'" onclick="'+ onclickCall +'">'+ clipTitle +'</a></h3>'+
						'<p>'+truncDesc+'</p>'+
						'<p class="cta clearfix">'+
							'<a href="'+ondemandUrl+'" target="'+ linkTarget +'" onclick="'+onclickCall+'">Watch</a>'+
							'<span class="mavenDuration">'+clipDuration+'</span>'+
						'</p>'+
					'</div>';
			}else {
				summary = 
					'<div class="summary">'+
						'<p class="cta clearfix">'+
							'<a href="'+ondemandUrl+'" target="'+ linkTarget +'" onclick="'+onclickCall+'">Watch</a>'+
							'<span class="mavenDuration">'+clipDuration+'</span>'+
						'</p>'+
						'<h3><a href="'+ondemandUrl+'" target="'+ linkTarget +'" onclick="'+ onclickCall +'">'+ clipTitle +'</a></h3>'+
						'<p>'+truncDesc+'</p>'+
					'</div>';
			}
			var videoItem = 
				'<div class="mavenLink">'+
					'<div class="mavenIco">'+
					'<a href="'+ ondemandUrl +'" title="'+ clipTitle +'" target="'+ linkTarget +'" onclick="'+onclickCall+'"></a>'+
						'<img width="90" height="68" src="'+ clipImg +'" alt="'+ clipTitle +'"/>'+
					'</div>'+
					summary +
				'</div>';
			videoBag.innerHTML+=videoItem;
 		},
 		
 		writeError: function( errorMsg ) {
 		   //alert( errorMsg );
 		},
 		
 		/*
 		Input parameters:
 		String text, Number length, String ellipsis
 		Returns: String text
 		*/
 		truncate: function( text, length, ellipsis ) {
 		   // Set length and ellipsis to defaults if not defined
 		   if ( typeof length == 'undefined' ) {
 		      var length = 100;
 		   }
 		   if ( typeof ellipsis == 'undefined' ) {
 		      var ellipsis = '...';
 		   }
 		   // Return if the text is already lower than the cutoff
 		   if ( text.length < length ) {
 		      return text;
 		   }
 		   /* Otherwise, check if the last character is a space.
 		   If not, keep counting down from the last character
 		   until we find a character that is a space */
 		   for ( var i = length - 1; text.charAt(i) != ' '; i-- ) {
 		      length--;
 		   }
 		   /* The for() loop ends when it finds a space, and the length var
 		   has been updated so it doesn't cut in the middle of a word. */
 		   return text.substr( 0, length ) + ellipsis;
 		},
 		
 		formatMs: function( msValue ) {
 		   var finalVal = '';
 		   //format number of seconds into MM:SS format
 		   initVar = msValue; // The initial data, in milliseconds
 		   milliVar = Math.floor( initVar / 1000 );
 		   minVar = Math.floor( milliVar / 60 ); // The minutes
 		   secVar = milliVar % 60; // The balance of seconds
 		   secVar += "";//convert to string
 		   if (secVar.length == 1) secVar = "0" + secVar;
 		   finalVal = minVar + ":" + secVar + ' min';
 		   return finalVal;
 		},
 		
		loadVideoPlayer : function (playerId, playlistId, videoId, width, height, bgColor, container){
			/*
				playerId: tells the swf which player version to render in the container (string)
				playlistId: tells the swf which playlist to associate with a player (string)
				videoId: tells the swf which video to load from the playlist (string)
				height: embedded player height in pixels (string)
				width: embedded player width in pixels (string)
				bgColor: embedded player background color in hex (string)
				container: html parent element id of the embedded player (string)
				*************NOTE: make sure the maven include script for the player version desired is in the head***************
			*/
			if (!bgColor) bgColor="#ffffff";
			if (!height) height="248";
			if (!width) width="360";
			var so = new SWFObject (streamPath, 'video', width, height, '9', bgColor); 
			so.addParam('allowScriptAccess', 'always');
			so.addParam('allowFullScreen', 'true');
			so.addParam('scale', 'noscale'); 
			so.addParam('salign', 'TL');
			so.addVariable("playerId", playerId);
			so.addVariable("referralParentPlaylistId", "null" );
			so.useExpressInstall('swfobject/expressinstall.swf');
		
			//check for legacy query parameters
			var pId = (getQueryParamValue("maven_referralPlaylistId"))?getQueryParamValue("maven_referralPlaylistId"):playlistId;
			var vId = (getQueryParamValue("maven_referralObject"))?getQueryParamValue("maven_referralObject"):videoId;
			//overwrite legacy query parameters if new query parameters exist
			pId = (getQueryParamValue("playlistId"))?getQueryParamValue("playlistId"):pId;
			vId = (getQueryParamValue("videoId"))?getQueryParamValue("videoId"):vId;

			pId ? so.addVariable("referralPlaylistId",pId) : so.addVariable("referralPlaylistId","null");
			if (vId) so.addVariable("referralObject", vId);
			
			so.write(container); //render the video player
		}
  };
}();


