/**
 * @fileOverview This file contains all Media Portal code
 * @author <a href='http://wiki.element115.net/index.php/User:Schopra'>schopra</a> 
 */

/**
 * collection of Media Portal specific methods and data
 * 
 * @namespace
 * @requires media.js, with {@link mediaDirectory} and {@link mediaObject}<br />prototype.js<br />effects.js (scriptaculous)
 * @author schopra
 */
var media_portal = {
	/**
	 * collection of methods to manage player
	 * 
	 * @namespace
	 * @property {String} videoPortalID
	 * @property {String} metaDataID
	 * @property {String} featuredVideoID
	 * @property {String} width
	 * @property {String} height
	 */
	player: {
		videoPortalID: "video_portal",
		metaDataID: "meta_data",
		featuredVideoID: "featured_video",
		width: "460",
		height: "259",  // should be 237? (probably not)
		/**
		 * checks to see if a mediaObject exists for #/[assetid].  uses setFeaturedVideo if found
		 * @function
		 */
		changeVideo: function(){
			var pathArray = SWFAddress.getPathNames();
			if(typeof mediaDirectory["child_"+pathArray[0]]!=="undefined"){
				this.setFeaturedVideo(mediaDirectory["child_"+pathArray[0]]);
			}else{
				eHA.log.create("mediaObject doesn't exist yet, attempting to addById",3);
				if(mediaDirectory.addById(pathArray[0])){
					this.setFeaturedVideo(mediaDirectory["child_"+pathArray[0]]);
				}
			}
		},
		/**
		 * Creates this.featuredVideo as a pointer to mediaObject for the current featured_video on page.<br />
		 * Initiates playing of video.
		 * 
		 * @function
		 * @param {mediaObject} obj To be used with a mediaObject to identify
		 * the featured video on the page
		 */
		setFeaturedVideo: function(obj){
			var newVideo = obj;
			
			if(typeof newVideo.properties!=="undefined"){
				
				// force this media to NOT use panels
				newVideo.properties.usePanels = false;
				
				var autostart = "false";
				if(typeof this.featuredVideo !== "undefined" && typeof this.featuredVideo.properties!=="undefined" && typeof this.featuredVideo.properties.id !== "undefined" && $(this.featuredVideo.properties.id) && $(this.featuredVideo.properties.id).up("div.thumbnail")){
					$(this.featuredVideo.properties.id).up("div.thumbnail").removeClassName("sel");
				}
				
				if(typeof this.featuredVideo !== "undefined" && typeof this.featuredVideo.properties!=="undefined" && typeof this.featuredVideo.properties.id !== "undefined"){
					this.featuredVideo.remove();
					$(this.videoPortalID).update("<div id='"+this.featuredVideoID+"'></div>");
					autostart = "true";
				}
				
				this.featuredVideo = newVideo;
				this.featuredVideo.properties.embed_id = this.featuredVideoID;
				this.featuredVideo.properties.portal = true;
				this.featuredVideo.onbeforeinsert = function(){
					this.featuredVideo.properties.height = this.height;
					this.featuredVideo.properties.width = this.width;
				}.bind(this);
				
				mediaDirectory.state.autostart.value = autostart;
				
				if(typeof this.featuredVideo.properties!=="undefined" && typeof this.featuredVideo.properties.id!=="undefined" && $(this.featuredVideo.properties.id) && $(this.featuredVideo.properties.id).up("div.thumbnail"))
				 $(this.featuredVideo.properties.id).up("div.thumbnail").addClassName("sel");
				this.featuredVideo.initiate();
				this.displayMetaData();
			}else{
				eHA.log.create("failed to play featured video (id: "+this.featuredVideo.properties.assetid+")", 1);
			}
		},
		/**
		 * displays meta data for this.featuredVideo in a DIV after #video_portal
		 * @function
		 */
		displayMetaData: function(){
			if($(this.metaDataID)){
				try{
					var thisLabel = "Video";
					var thumbPath = this.defaultVideoThumbPath;
					if(this.featuredVideo.properties.type==="sound"){
						thisLabel = "Audio";
						thumbPath = this.defaultAudioThumbPath;
					}
					if(this.featuredVideo.properties.type==="youtube"){
						thumbPath = this.defaultYouTubeThumbPath;
					}
					
					if(typeof this.featuredVideo.properties.path_tn!=="undefined")
						thumbPath = this.featuredVideo.properties.path_tn;
					var thumb = new Element("img",{"src":thumbPath,"alt":this.featuredVideo.properties.title});
					var videoTitle = new Element("h5").update(this.featuredVideo.properties.title);
					if(typeof this.pageTitle==="undefined"){
						this.pageTitle = SWFAddress.getTitle();
					}
					SWFAddress.setTitle(this.featuredVideo.properties.title.unescapeHTML()+" - "+this.pageTitle);
					var videoDescription = new Element("p",{className:"description"}).update(this.featuredVideo.properties.description);
					var thisUrl = new Element("p",{className:"url"}).update("<span class='label'>URL:</span><span class='value'>"+SWFAddress.getBaseURL()+"#"+SWFAddress.getValue()+"</span>");
					
					var infoDiv = new Element("div",{className:"info"});
					infoDiv.insert({'bottom':thumb}).insert({'bottom':videoTitle}).insert({'bottom':videoDescription}).insert({'bottom':thisUrl});
					
						var viewsH5 = new Element("h5").update("Plays");
						this.stats.views = $(new Element("span",{className:"value"}));
						this.stats.views.update("0");
					var viewsDiv = new Element("div",{className:"views"}).insert({'bottom':viewsH5}).insert({'bottom':this.stats.views});
					
					var ratingsUL = new Element("ul").update("<li class='star-1'><a href=''>1</a></li><li class='star-2'><a href=''>2</a></li><li class='star-3'><a href=''>3</a></li><li class='star-4'><a href=''>4</a></li><li class='star-5'><a href=''>5</a></li>");
						this.stats.ratings.wrapper = new Element("div",{className:"rating-0"}).update(ratingsUL);
					var rateDiv = new Element("div",{className:"ratings"}).update("<h5>Rate this "+thisLabel+"</h5>").insert({'bottom':this.stats.ratings.wrapper});
						this.share = new Element("a",{'id':'share_link','href':''}).update("Share");
					
					var shareDiv = new Element("div",{className:"share"}).update("<h5>Share this "+thisLabel+"</h5>").insert({'bottom':this.share});
					
					var interactiveDiv = new Element("div",{className:"interactive"});
					interactiveDiv.insert({'bottom':viewsDiv}).insert({'bottom':rateDiv}).insert({'bottom':shareDiv});
					if(typeof addthis!=="undefined" && typeof addthis.button!=="undefined"){
						addthis.button(this.share,{},{url:SWFAddress.getBaseURL()+"#"+SWFAddress.getValue(),title:this.featuredVideo.properties.title});
					}
					
					// this line clears out old metadata
					$(this.metaDataID).update(infoDiv).insert({'bottom':interactiveDiv});
					
					this.stats.access({action:"update",data:"views"});
					this.stats.access({action:"load",data:"ratings"});
					
					// need to check ratings cookie before events are assigned
					var oldRating;
					if(oldRating = Cookie.getData("portal-rating-"+media_portal.player.featuredVideo.properties.assetid)){
						this.stats.ratings.disable(oldRating);
					}else{
						this.stats.ratings.events();
					}
				}catch(err){
					eHA.log.create("video id: "+media_portal.player.featuredVideo.properties.assetid+". meta data error: "+err.name+" "+err.message,1);
				}
			}
		},
		/**
		 * holds data and more namespaces for accessing and managing information related to the stats site entry and cs element
		 * @namespace
		 */
		stats: {
			/**
			 * holds data and functions for managing ratings
			 * @namespace
			 */
			ratings: {
				/**
				 * adds events to ratings links (stars)
				 * @function
				 */
				events: function(){
					this.wrapper.select("a").each(function(element,iteration){
						element.observe("click",function(event){
							event.stop();
							var thisRating = event.element().innerHTML;
							media_portal.player.stats.access({action:"update",data:"ratings",rating:thisRating});
							Cookie.setData("portal-rating-"+media_portal.player.featuredVideo.properties.assetid,thisRating);
							media_portal.player.stats.ratings.disable(thisRating,function(){
								media_portal.player.stats.ratings.highlight();
							});
						});
						element.observe("mouseover",function(event){
							var thisRating = event.element().innerHTML;
							event.element().up("ul").addClassName("hover-"+thisRating);
						});
						element.observe("mouseout",function(event){
							var thisRating = event.element().innerHTML;
							event.element().up("ul").removeClassName("hover-"+thisRating);
						});
					});
				},
				/**
				 * highlight ratings (invoked after selection).  this adds a "highlight" class to the ratings wrapper then removes it after 1 second
				 * @function
				 */
				highlight: function(){
					eHA.log.create("highlighting ratings",3);
					this.wrapper.addClassName("highlight");
					setTimeout("media_portal.player.stats.ratings.wrapper.removeClassName(\"highlight\")",1000);
				},
				/**
				 * disable interactive functionality of ratings links.  called onload if user has already rated. called after user rates if rating for the first time
				 * @function
				 * @param {String} rating rating to assign to <p> tag w/ rating message
				 * @param {function} callback Exists to be used for highlight function
				 */
				disable: function(rating,callback){
					this.wrapper.select("a").each(function(element,iteration){
						element.stopObserving("click").stopObserving("mouseover").stopObserving("mouseout");
						element.observe("click",function(event){
							event.stop();
						});
					});
					this.wrapper.down("ul").insert({'after':"<p>"+"Your rating: "+rating+"</p>"}).className = "disable";
					if(typeof callback!=="undefined")
						callback();
				},
				/**
				 * updates the ratings wrapper w/ a class equivalent to the given rating
				 * @function
				 * @param {String} stringValue the given rating
				 */
				update: function(stringValue){
					eHA.log.create("updating ratings to "+stringValue,3);
					this.averageRating = stringValue;
					try{
						if(stringValue.toString().indexOf(".")!=-1){
							// if decimal is between .2 and .8 (exclusive), class is given "-half" post-fix
							var hasHalf = (parseInt(stringValue.toString().split(".")[1])>2 && parseInt(stringValue.toString().split(".")[1])<8);
							if(hasHalf){
								stringValue = stringValue.toString().split(".")[0]+"-half";
							}else{
								stringValue = Math.round(stringValue);
							}
						}
					}catch(err){
						eHA.log.create("ratings.update error "+err.message,3);
					}
					eHA.log.create("updating ratings className to "+stringValue,3);
					this.wrapper.className = "rating-"+stringValue;
				}
			},
			/**
			 * useful for directly accessing the stats site entry
			 * @function
			 * @param {object} options An object literal referencing "action" and "data" parameters
			 * @example
			 * 
			 *		this.stats.access({action:"update",data:"views"});
			 *		this.stats.access({action:"load",data:"ratings"});
			 */
			access: function(options){
				try{
					var parameters = {
							  cid: media_portal.player.featuredVideo.properties.assetid,
							  c: media_portal.player.featuredVideo.properties.assettype,
							  childpagename: media_portal.player.stats.childpagename,
							  pagename: media_portal.player.stats.pagename,
							  site: eHA.Site
							};
						Object.extend(parameters,options);
						new Ajax.Request(media_portal.player.stats.URL,
						  {
						    method:'get',
						    parameters: parameters,
						    onCreate: function(){
								eHA.log.create("AJAX request player.stats.access ("+Object.toJSON(parameters)+") created", 3);
						    },
						    onSuccess: function(transport){
						    	eHA.log.create("AJAX request player.stats.access ("+Object.toJSON(parameters)+") succeeded", 3);
						    },
						    onComplete: function(transport){
						    	eHA.log.create("AJAX request player.stats.access ("+Object.toJSON(parameters)+") completed", 3);
						    	
						    	var statsData = transport.responseText.evalJSON(true);
						    	
					    		eHA.log.create("player.stats.access returned data ("+parameters.data+"): "+Object.toJSON(statsData), 3);
					    		media_portal.player.stats[parameters.data].update(statsData[parameters.data]);
							},
						    onFailure: function(){
								eHA.log.create("AJAX request player.stats.access ("+Object.toJSON(parameters)+") failed", 1);
							}
						  });
				}catch(err){
					eHA.log.create("AJAX request player.stats.access ERROR ("+err.message+") failed", 1);
				}
			}
		},
		/**
		 * sets the first video (loaded in page) as this.featuredVideo
		 * @function
		 */
		start: function(){
			 
			 this.stats.URL = "/cs/Satellite";
			 this.stats.pagename = eHA.Site+"_default_Wrapper";
			 this.stats.childpagename = eHA.Site+"/Utilities/stats";
			 this.defaultAudioThumbPath = eHA.resourcepath+"images/Audio_Thumbnail.jpg";
			 this.defaultVideoThumbPath = eHA.resourcepath+"images/Video_Thumbnail.jpg";
			 this.defaultYouTubeThumbPath = eHA.resourcepath+"images/YouTube_Thumbnail.jpg";
			 
			 this.media_type = "Video";
			 
			 if($("video_media_type")){
				 this.media_type = $F("video_media_type");
				 if(this.media_type==="Audio")
					 this.height = "0";
			 }
			 
			 // EXTERNAL_CHANGE is used for back button
			 SWFAddress.addEventListener(SWFAddressEvent.EXTERNAL_CHANGE, function(event){
					eHA.log.create("SWFAddress event: "+Object.toJSON(event), 3);
					//alert("SWFAddress event: "+Object.toJSON(event));
					this.changeVideo();
				 }.bind(this));

			 SWFAddress.addEventListener(SWFAddressEvent.INTERNAL_CHANGE, function(event){
					eHA.log.create("SWFAddress event: "+Object.toJSON(event), 3);
					//alert("SWFAddress event: "+Object.toJSON(event));
					this.changeVideo();
				 }.bind(this));
				

			 if(typeof SWFAddress.getPathNames()!=="undefined" && typeof SWFAddress.getPathNames()[0]!=="undefined"){
				 // explicitly listen for INIT event (this is not necessary if the hash is empty onload)
				 SWFAddress.addEventListener(SWFAddressEvent.INIT, function(event){
						eHA.log.create("SWFAddress event: "+Object.toJSON(event), 3);
						//alert("SWFAddress event: "+Object.toJSON(event));
						this.changeVideo();
					 }.bind(this));
			 }else{
				// the INTERNAL_CHANGE event picks up this initial setValue
				if($$("#"+this.featuredVideoID+" a.mediaObject")[0]){
					var firstVideoObject = mediaDirectory.findByEl($$("#"+this.featuredVideoID+" a.mediaObject")[0]);
					var hashPath = "/"+firstVideoObject.properties.assetid;
					SWFAddress.setValue(hashPath);
				}
			 }
			 
		}
	},
	/**
	 * collection of methods related to videoGroups
	 * @namespace
	 * @property {double} motionDuration duration time for scriptaculous's motion effects 
	 * @property {String} videoGroupHeight is overwritten by height of container (contains "px")
	 * @property {String} videoGroupsContainerID id of container
	 */
	videoGroups: {
		videosPerPage: 5,
		motionDuration: 0.6,
		videoGroupHeight: "480px",
		videoGroupsContainerID: "content_navigation",
		/**
		 * uses selector to create groupObjects.  forces container to position: relative, assigns height explicitly.<br />
	     * when objects are done being created, they are assigned position: absolute in preparation for motion
		 * @function
		 */
		start: function(){
			if($(this.videoGroupsContainerID)){
				var containerHeight = $(this.videoGroupsContainerID).getHeight();
				this.videoGroupHeight = containerHeight+"px";
				$(this.videoGroupsContainerID).setStyle({
					position: "relative",
					height: containerHeight+"px"
				});
			}
			if($(this.videoGroupsContainerID).select(".group")[0]){
				var rank = 0;
				$(this.videoGroupsContainerID).select(".group").each(function(element){
					this.createGroupObject(element,rank);
					rank++;
				}.bind(this));
				var groupKeys = this.getGroupKeys();
				var maxHeight = 0;
				var previousButtonPosition = "0px";
				var totalGroups = groupKeys.length;
				for(var i=0; i<totalGroups; i++){
					
					this["child_"+i].body.setStyle({
						position: "absolute",
						overflow: "hidden"
					});
					this["child_"+i].topValue.top = previousButtonPosition;
					previousButtonPosition = (parseInt(this["child_"+i].buttonHeight,10) + parseInt(previousButtonPosition,10)).toString()+"px";
					this.assignThumbnailEvents(this["child_"+i].body);
					if(parseInt(maxHeight,10)<parseInt(this["child_"+i].bodyHeight,10)){
						maxHeight = parseInt(this["child_"+i].bodyHeight,10);
					}
				}
				maxHeight = parseInt(maxHeight,10) + (2*parseInt(this["child_0"].buttonHeight,10));
				this.videoGroupHeight = maxHeight.toString()+"px";
				var containerHeight = (parseInt(maxHeight,10) + ((totalGroups+1) * parseInt(this["child_0"].buttonHeight,10))).toString()+"px";
				$(this.videoGroupsContainerID).setStyle({
					height: containerHeight
				});
				for(var i=0; i<totalGroups; i++){
					var topOffset=0;
					if(i>0){
						topOffset = this["child_"+(i-1)].topValue.top;
					}
					this["child_"+i].topValue.bottom = (parseInt(topOffset,10)+parseInt(maxHeight,10)).toString()+"px";
				}
				/**
				 * below line will activate first group
				 * this.activateGroup(this["child_0"]);
				 */
				/**
				 * below line will activate the latest_videos group
				 */
				this.activateGroup(this[this["childRankPointer_latest_videos"]]);
			}
			if(typeof $("video_topic_selector")!== "undefined"){
				$("video_topic_selector").observe("change",function(){
					this.changeChannel($("video_topic_selector")[$("video_topic_selector").selectedIndex].value);
				}.bind(this));
			}
			this.assignVideoSearchEvents();
		},
		/**
		 * @function
		 * @returns {Array} returnArray String Array of all group keys of media_portal.videoGroups
		 */
		getGroupKeys: function(){
			var returnArray = []; 
			for(var i=0;i<Object.keys(this).length;i++){
				if(Object.keys(this)[i].indexOf("child_")!=-1){
					returnArray.push(Object.keys(this)[i]);
				}
			}
			return returnArray;
		},
		/**
		 * creates groupObjects as children of media_portal.videoGroups.
		 * 
		 * @function
		 * @param {Element} el the HTML element to derive groupObject properties from
		 * @param {int} rank the integer ordinal rank assigned to this group (based on location / order in DOM)
		 */
		createGroupObject: function(el,rank){
			$(el).setStyle({top:$(el).positionedOffset().top+"px"});
			this["child_"+rank] = {
					id: el.id,
					body: $(el),
					bodyHeight: $(el).getHeight()+"px",
					button: $(el).down("h3"),
					buttonHeight: (parseInt($(el).down("h3").getStyle('margin-bottom'),10)+parseInt($(el).down("h3").getHeight(),10)).toString()+"px",
					open: false,
					position: 'top',
					rank: rank,
					topValue: {
						current: this.topOffset(el),
						top: this.topOffset(el),
						bottom: (parseInt(this.topOffset(el),10)+parseInt(this.videoGroupHeight,10)).toString()+"px"
						}
			};
			this["childRankPointer_"+el.id] = "child_"+rank;
			this["child_"+rank].button.setAttribute('tabindex','0');
			this["child_"+rank].button.observe('keydown',function(event){if(event.keyCode==Event.KEY_RETURN){this.activateGroup(this["child_"+rank])}}.bind(this));
			this["child_"+rank].button.observe("click",function(){this.activateGroup(this["child_"+rank])}.bind(this));
			this["child_"+rank].button.observe("mouseover",function(){this["child_"+rank].button.addClassName("hover")}.bind(this));
			this["child_"+rank].button.observe("mouseout",function(){this["child_"+rank].button.removeClassName("hover")}.bind(this));
		},
		/**
		 * Uses Prototype's getStyle('top') method to provide the int value
		 * @param {Element} el the HTML element for which to find topOffset
		 * @returns {int} the value of topOffset
		 */
		topOffset: function(el){
			return $(el).getStyle('top');
		},
		/**
		 * activates a groupObject
		 * @param {Object} obj the groupObject which is to be activated
		 */
		activateGroup: function(obj){
			 try{
					var parallel_morphs = new Array();
					obj.open = true;
					obj.position = 'top';
					obj.body.addClassName("open");
					parallel_morphs.push(eval("new Effect.Morph('"+obj.id+"',{style:'top:"+obj.topValue.top+";height:"+this.videoGroupHeight+";'},{sync:true})"));
					
					var groupKeys = this.getGroupKeys();
					eHA.log.create("groupKeys: "+groupKeys.inspect(),3);
					for(var i=0;i<=groupKeys.length;i++){
						if(typeof this[groupKeys[i]]!=="undefined"){
							if(this[groupKeys[i]].rank<obj.rank){
								// group appears above selected
								this[groupKeys[i]].position = 'top';
								this[groupKeys[i]].open = false;
								this[groupKeys[i]].body.removeClassName("open");
								parallel_morphs.push(eval("new Effect.Morph('"+this[groupKeys[i]].id+"',{style:'top:"+this[groupKeys[i]].topValue.top+";height:"+this[groupKeys[i]].buttonHeight+";'},{sync:true})"));
							}else{
								if(this[groupKeys[i]].rank>obj.rank){
									// group appears below selected
									this[groupKeys[i]].position = 'bottom';
									this[groupKeys[i]].open = false;
									this[groupKeys[i]].body.removeClassName("open");
									parallel_morphs.push(eval("new Effect.Morph('"+this[groupKeys[i]].id+"',{style:'top:"+this[groupKeys[i]].topValue.bottom+";height:"+this[groupKeys[i]].buttonHeight+";'},{sync:true})"));
								}
							}
						}
					}
					new Effect.Parallel( parallel_morphs, { duration: this.motionDuration });
			 }catch(err){
				 eHA.log.create("ERROR "+err.message,1);
			 }
		},
		/**
		 * assigns thumbnail onclick events to a groupObject's thumbnails
		 * @param {Object} obj
		 */
		assignThumbnailEvents: function(el){
			 if(typeof $(el).select("div.thumbnail a")[0]!=="undefined"){
					$(el).select("div.thumbnail a").each(function(element){
						element.stopObserving("click");
						element.observe("click",function(event){
							event.stop();
							var hashPath = "/"+mediaDirectory.findByEl(element).properties.assetid;
							SWFAddress.setValue(hashPath);
							//media_portal.player.setFeaturedVideo(mediaDirectory.findByEl(element));
						});
					});
				 }
		},
		/**
		 * changes video channels using AJAX
		 * @function
		 * @param {String} channelValue from the select / dropdown
		 * @param {int} start video in channel on which to start (for pagination)
		 */
		changeChannel: function(channelValue,start){
			eHA.log.create("beginning changeChannel", 3);
			if(typeof channelValue!=="undefined" && (typeof channelValue!=="string" || channelValue!=="null")){
				if(typeof start==="undefined")
					start = 1;
				var thisCid = channelValue;
				var thisSubtype = "Vodcast";
				var thisC = "eHA_Module_C";
				if(typeof channelValue==="object" || (typeof channelValue==="string" && channelValue.indexOf("&")!=-1)){
					var channelObject = channelValue;
					if(typeof channelValue==="string" && channelValue.indexOf("&")!=-1){
						channelObject = channelValue.toQueryParams();
					}
					eHA.log.create("evaluating channelObject: "+Object.toJSON(channelObject), 3);
					thisCid = channelObject.cid;
					thisSubtype = channelObject.subtype;
					thisC = channelObject.c;
				}
				var URL = "/cs/Satellite";
				var pagename = eHA.Site+"/"+thisC+"/"+eHA.Site+"/"+thisSubtype+"/channel";
				var preloader = new Element("img",{"src":eHA.resourcepath+"images/wide-preloader.gif","alt":"please wait",className:"preloader"});
				var parameters = {
					  start: start,
					  pagename: pagename,
					  site: eHA.Site,
					  c: thisC,
					  cid: thisCid,
					  videosPerPage: this.videosPerPage
					};
				new Ajax.Request(URL,
				  {
				    method:'get',
				    parameters: parameters,
				    onCreate: function(){
						if($("topic_videos").select("div.thumbnail")[0])
							$("topic_videos").select("div.thumbnail").invoke("remove");
						if($("topic_videos").select("div.page_links")[0])
							$("topic_videos").select("div.page_links").invoke("remove");
						if($("topic_videos").select("div.rss")[0])
							$("topic_videos").select("div.rss").invoke("remove");
						eHA.log.create(parameters.cid+": AJAX request for Video Channel created", 3);
						$("topic_videos").insert({'bottom':preloader});
				    },
				    onSuccess: function(transport){
				    	eHA.log.create(parameters.cid+": AJAX request for Video Channel succeeded", 3);
				    },
				    onComplete: function(transport){
					    eHA.log.create(parameters.cid+": AJAX request for Video Channel completed", 3);
					    if($("topic_videos").select("img.preloader")[0])
					    	$("topic_videos").select("img.preloader")[0].remove();
					    
					    $("topic_videos").insert({'bottom':transport.responseText});
					    
					    mediaDirectory.assignMediaEvents("#topic_videos a.mediaObject");
					    media_portal.videoGroups.assignThumbnailEvents($("topic_videos"));
					    media_portal.videoGroups.assignPaginationEvents($("topic_videos"));
					},
				    onFailure: function(){
						eHA.log.create(parameters.cid+": AJAX request for Video Channel resulted in failure", 1);
					}
				  });
			}

		},
		/**
		 * assigns pagination events to both search results and channels
		 * @function
		 * @param {Element} el
		 * @param {String} searchkey optional
		 */
		assignPaginationEvents: function(el,searchkey){
			if(typeof $(el)!=="undefined"){
				if(typeof $(el).select("div.page_links ul li a")[0]!=="undefined"){
					if(typeof searchkey !== "undefined"){
						eHA.log.create(searchkey+" (video search): assigning pagination events", 3);
						$(el).select("div.page_links ul li a").each(function(element){
							element.observe("click",function(event){
								var media_type = $F("video_media_type");
								media_portal.videoGroups.startVideoSearch(searchkey, eHA.elementToObjectLiteral(element).startValue,media_type);
								event.stop();
							});
						});
					}else{
						var channelObject = eHA.elementToObjectLiteral($(el).select("div.page_links")[0]);
						eHA.log.create(Object.toJSON(channelObject)+": assigning pagination events", 3);
						$(el).select("div.page_links ul li a").each(function(element){
							element.observe("click",function(event){
								event.stop();
								media_portal.videoGroups.changeChannel(channelObject, eHA.elementToObjectLiteral(element).startValue);
							});
						});
					}
				}else{
					eHA.log.create("can't find page_links", 2);
				}
			}
		},
		/**
		 * assigns video search events to form beneath video player
		 * @function
		 */
		assignVideoSearchEvents: function(){
			if($("video_search_form") && $("video_searchkey") && $("video_old_searchkey") && $("video_media_type")){
				$("video_search_form").observe("submit",function(event){
					event.stop();
					var searchkey = $F("video_searchkey");
					var media_type = $F("video_media_type");
					$("video_old_searchkey").value = searchkey;
					var start = 1;
					this.startVideoSearch(searchkey,start,media_type);
				}.bind(this));
			}
		},
		/**
		 * sets search_videos group's buttonHeight to that of child_0.  Makes this group visible and uses "activateGroup" to make it active
		 * @function
		 * @param {String} searchkey
		 * @param {int} start
		 * @param {String} media_type either "Audio", "Video", or "All"
		 */
		startVideoSearch: function(searchkey,start,media_type){
			if($("search_videos")){
				this[this["childRankPointer_search_videos"]].buttonHeight = this["child_0"].buttonHeight;
				$("search_videos").show();
				this.activateGroup(this[this["childRankPointer_search_videos"]]);

				if(typeof start==="undefined")
					start = 1;
				// http://umdev.element115.net/cs/Satellite?childpagename=um/Video/video_search&pagename=default_um_Wrapper
				var URL = "/cs/Satellite";
				var pagename = eHA.Site+"_default_Wrapper";
				var childpagename = eHA.Site+"/Video/video_search";
				var preloader = new Element("img",{"src":eHA.resourcepath+"images/wide-preloader.gif","alt":"please wait",className:"preloader"});
				
				var packedargs = {
					  start: start,
					  searchkey: searchkey,
					  videos_to_display: this.videosPerPage,
					  media_type: media_type
					};
				var parameters = {
					  childpagename: childpagename,
					  pagename: pagename,
					  site: eHA.Site,
					  packedargs: Object.toQueryString(packedargs)
					};
				
				new Ajax.Request(URL,
				  {
				    method:'get',
				    parameters: parameters,
				    onCreate: function(){
						if($("search_videos").select("div.thumbnail")[0])
							$("search_videos").select("div.thumbnail").invoke("remove");
						if($("search_videos").select("div.page_links")[0])
							$("search_videos").select("div.page_links").invoke("remove");
						if($("search_videos").select("h4.search_info")[0])
							$("search_videos").select("h4.search_info").invoke("remove");
						if($("search_videos").select("span.no_result")[0])
							$("search_videos").select("span.no_result").invoke("remove");
						
						eHA.log.create("AJAX request for video search ("+packedargs.searchkey+") created", 3);
						$("search_videos").insert({'bottom':preloader});
				    },
				    onSuccess: function(transport){
				    	eHA.log.create("AJAX request for video search ("+packedargs.searchkey+") succeeded", 3);
				    },
				    onComplete: function(transport){
					    eHA.log.create("AJAX request for video search ("+packedargs.searchkey+") completed", 3);
					    try{
					    	if($("search_videos").select("img.preloader")[0]){
					    		$("search_videos").select("img.preloader")[0].remove();
					    	}
					    	$("search_videos").insert({'bottom':transport.responseText});
					    	
					    	mediaDirectory.assignMediaEvents("#search_videos a.mediaObject");
					    	media_portal.videoGroups.assignThumbnailEvents($("search_videos"));
					    	media_portal.videoGroups.assignPaginationEvents($("search_videos"),packedargs.searchkey);
					    }catch(err){
					    	eHA.log.create(err.toString(),1);
					    }
					},
				    onFailure: function(){
						eHA.log.create("AJAX request for video search ("+packedargs.searchkey+") resulted in failure", 3);
					}
				  });
			}
		}

	},
	/**
	 * to be executed when the page is loaded, to setup the media_portal
	 * @function
	 */
	onload: function(){
		document.stopObserving("media:loaded");
		this.player.start();
		this.videoGroups.start();
	}
};

if($("video_portal")){
	document.observe("media:loaded", function(event){
		media_portal.onload();
	});
}


