var GROSS_HARDCODED_ASSET_PREFIX_URL = "http://cache.reelzchannel.com/assets/content/";

function getFullBaseURL() {
	return 'http://www.reelzchannel.com';
}


var MOVIE_DETAILS_BASE_URL = "/movie/";
var PERSON_DETAILS_BASE_URL = "/person/";
var LOGIN_URL = "/profile/createprofile.aspx?mode=login";

var FRIEND_BASE_URL = "/player.aspx?clipid=";

var REGISTER_URL = "/profile/createprofile.aspx?mode=register";

var MOVIE_FEED_BASE_URL = "/data/moviedetail.aspx?movieid=";

var LARGE_LOADING_IMG_URL = "/assets/global/reelzLoading.gif";
var RATING_HEADER_IMG_URL = "/assets/global/movie-ratings.gif";

var SCROLLER_LEFT_ENABLED_IMG_URL = "/assets/global/embedded-player-arrow-left.gif";
var SCROLLER_LEFT_DISABLED_IMG_URL = "/assets/global/embedded-player-arrow-left-disabled.gif";
var SCROLLER_RIGHT_ENABLED_IMG_URL = "/assets/global/embedded-player-arrow-right.gif";
var SCROLLER_RIGHT_DISABLED_IMG_URL = "/assets/global/embedded-player-arrow-right-disabled.gif";

var NO_POSTER_IMG_URL = "/assets/global/no_movie_image.jpg";


var REELZ_RATING_MODULE_SWF = "/assets/flash/ratingModuleLarge.swf";
var REELZ_MOVIE_PLAYER_SWF = "/assets/flash/syndicatedPlayer.swf";

var LOADING_CONTENT = "<div class=\"hover_loading\">" +
					  "   <image style=\"margin-top:110px\" src=\""+LARGE_LOADING_IMG_URL+"\"/> <br/>" +
					  "</div>";

var ERROR_CONTENT = "<div class=\"hover_error\"><p class=\"error\">Error retrieving that movie.</p></div>";

var KEEP_ALIVE_TIMEOUT_MS = 500;
var DEFAULT_HOVER_CLASSNAME = "hover";

function movieDetailsURL(movieId) {
	return MOVIE_DETAILS_BASE_URL + movieId;
}

function getMovieDataURL(movieId) { 
	return MOVIE_FEED_BASE_URL + movieId; 
}

var Hover = Class.create();
Hover.prototype = {

	initialize: function(opts) {
		
		this.hoverId = "hover_" + new Date().getTime();

		this.pntrId = this.hoverId + "_arrow";
		this.pntrImgId = this.pntrId + "_img";
		
		this.containerId = this.hoverId + "_container";
		this.contentId = this.hoverId + "_content";
		this.carouselId = this.hoverId + "_carousel";
		
		this.visible = false;
		this.loading = false;
		
		this.currentlyShowingMovieId = null;
		this.currentEventPosition = null;
		this.currentEventElement = null;
		this.yAdjustedAmount = 0;
		this.overTop = false;
		this.overBottom = false;
		
		this.dimensions = null;
		this.options = Object.extend({
			className: DEFAULT_HOVER_CLASSNAME,
			firstElem: this._findDOMFirstElem(), 
			leftOffset: 0,
			topOffset: 0
		}, opts || {});
		
		this.mplayer = null;
		this.hoverData = null;
		
		this._createHover();
		this.element = $(this.hoverId);
		
		this.hideTO = null;
	},

	buildMovieContent: function(hovData) {
		this.hoverData = hovData;
		this.mplayer = new ReelzMediaPlayer( {mediaPlayerContentId: this.hoverData.mediaPlayerId} );
		var hoverHTML = new HoverBuilder(this.hoverData, this.carouselId).buildHover();
		this.updateContent(hoverHTML);

		if ( this.hoverData.hasClips ) { reinitCarousel(this.carouselId); }
	},
	
	updateContent: function(content) {
		$(this.contentId).innerHTML = content;
	},

	showBy: function(evtMousePos, evtElem) {

		var posAndAdjustments = this._findPositionForEvent(evtMousePos, evtElem);

		var xAdjust = posAndAdjustments[0][1];
		var yAdjust = posAndAdjustments[1][1];
		this.yAdjustedAmount = yAdjust;
		var hoverLeftTopBound = [posAndAdjustments[0][0] + xAdjust, posAndAdjustments[1][0] + yAdjust ];
		
		this.setPosition(hoverLeftTopBound);
		
		this.currentEventPosition = evtMousePos;
		this.currentEventElement = evtElem;
		
		this._positionCarrot();

		this.show();
		this._showCarrot();
		
		try { if (is_ie6) { this._hideDropDownHack(); } } catch (ignored){}
	},
	
	isAlreadyShowingMovie:function(movieId, evtElem){
		var alreadyShowing = false;

		if (this.currentlyShowingMovieId == movieId){
			// verify it is the same element and the same id 
			var curPos = Position.page(this.currentEventElement);
			var newPos = Position.page(evtElem);
			if (curPos[0] == newPos[0] && curPos[1] == newPos[1]){
				alreadyShowing = true;
			}
		}
		return alreadyShowing;
	},
	
	show: function() {
		if(this.visible==true) return;
		this.visible = true;
		this.keepAlive();
	},
	
	hide: function() {
		
		this.clearHideTO();
		this._hideCarrot();
		this.element.hide();
		this.visible = false;
		this.loading = false;
		this.currentlyShowingMovieId = null;
		this.currentEventPos = null;
		this.currentEventElem = null;
		
		try { if (is_ie6) this._showDropDownHack(); } catch (ignored){}
		
		return false;
	},
	
	keepAlive: function(){
		this.clearHideTO();
		this.element.show(); 
		return false;
	},
	
	clearHideTO: function(){
		if (this.hideTO != null) {
			clearTimeout(this.hideTO);
			this.hideTO = null;
		}
	},
	
	suggestHide: function(event) {
		if (this.hideTO != null && !this.loading) {
			return false;
		}
		this.hideTO = setTimeout("hideMovieNow()", KEEP_ALIVE_TIMEOUT_MS);
		return false;
	},
	
	setPosition: function(leftTopPos) {
		var h = '315px'
		var w = '367px';

		var left = leftTopPos[0];
		var top = leftTopPos[1];
		
		Position.absolutize(this.element);
		this.element.setStyle({
			left:left+'px', top:top+'px', 
			height: h, width: w,
			zIndex: '150500'
		});
	},	
	
	showClipTitle: function(clipId) {
		var foundClipData = this._getClipData(clipId);
		var str = "<strong>"+foundClipData.title + "</strong>";
		if (foundClipData.description!=null && !foundClipData.description.blank()) {
			str += "<br/>" + foundClipData.description.truncate(50, '...');
		}
		$('clip_playing_info').innerHTML = str;
		$('clip_playing_info').show();
		$('close_media_player').show();
		$('num_avail_clips').hide();
		$('clip_peek_info').hide();
		$('clip_peek_info').hide();
		
		$$('.hover-carousel-component .carousel-list li img').each(function(elem){ elem.setStyle({borderColor: '#999'})});
		$("clip_image_"+clipId).setStyle({borderColor: '#c00'});
	},
	
	peekClipTitle: function(clipId) {
		var foundClipData = this._getClipData(clipId);
		var str = "<strong>"+foundClipData.title + "</strong>";
		if (foundClipData.description!=null && !foundClipData.description.blank()){
			str += "<br/>" + foundClipData.description.truncate(50, '...');
		}
		$('clip_peek_info').innerHTML = str;
		$('clip_peek_info').show();
		$('num_avail_clips').hide();
		$('clip_playing_info').hide();
	},

	hideClipTitle: function() {
		if (this.mplayer.isPlaying()) {
			$('clip_playing_info').show();
			$('close_media_player').show();
			$('num_avail_clips').hide();
		} else {
			$('num_avail_clips').show();
			$('clip_playing_info').hide();
			$('close_media_player').hide();
		}
		
		$('clip_peek_info').hide();
	},
	
	playClip: function(clipId) {
		this.showClipTitle(clipId);
		$(this.hoverData.movieInfoId).hide();
		this.mplayer.hoverData = this.hoverData;
		this.mplayer.playClip(this._getClipData(clipId));
	},
	closePlayer: function() {
		this.mplayer.closePlayer();
		this.hideClipTitle();
		$(this.hoverData.movieInfoId).show();
		$$('.hover-carousel-component .carousel-list li img').each(function(elem){ elem.setStyle({borderColor: '#aaa'})});
		return false;
	},
	
	/* private stuff */
	_getClipData: function(clipId){
		return this.hoverData.clips.find( function(clp){ 
			return (clp.clipId==clipId); 
		} );
	},
	_findDOMFirstElem: function() {
		return $('hover_holder');
	}, 

	_jsToKeepHoverAlive: function() {
		return " onMouseOver=\"hover.keepAlive()\" onMouseOut=\"hover.suggestHide(event)\" ";
	},
	
	_hideDropDownHack: function (){
		/* mostly from and ui.js -- uses intersects() */
		var menus = document.getElementsByTagName("SELECT");
		try {
			for (i = 0; i < menus.length; i++) {
		        if (intersects($(this.containerId), menus[i])) {
					$(menus[i]).hide();
		        }
		    }
		}catch (ignored){}
	},
	_showDropDownHack: function(){
		var menus = document.getElementsByTagName("SELECT");
		for (i = 0; i < menus.length; i++) {
            $(menus[i]).show();
	    }
	},
	_createHover: function() {
		var hoverHTML = "";
		hoverHTML += "<div id=\""+ this.hoverId + "\" style=\"display:none;\" class=\""+ this.options.className +"\" "+ this._jsToKeepHoverAlive() +" >";
		hoverHTML += "    <div class=\""+this.options.className+"_top\"><img src=\"/assets/global/background-top.gif\"/></div>";
		hoverHTML += "    <div id=\""+ this.containerId +"\" class=\""+ this.options.className +"_container\">";
		hoverHTML += "       <div id=\"" + this.contentId + "\" class=\""+ this.options.className +"_content\"> </div>";
		hoverHTML += "    </div>";
		hoverHTML += "    <div class=\""+this.options.className+"_bottom\"><img src=\"/assets/global/background-bottom.gif\"/></div>";
		hoverHTML += "    <div id=\"" + this.pntrId  + "\" style=\"display:none;\" class=\""+this.options.className+"_arrow " + "\"></div>";
		hoverHTML += "</div>";
		new Insertion.After(this.options.firstElem, hoverHTML);
	},
	
	_findPositionForEvent: function(evtMousePos, evtElem) {
		var posAdjustX = this._findXPosition(evtMousePos, evtElem);
		var posAdjustY = this._findYPosition(evtMousePos, evtElem);
		
		// return format
		// [ [xpos, xadjust], [ypos, yadjust]]
		return [posAdjustX, posAdjustY];
	},

	
	_showCarrot: function() {
		var posX = this.currentEventPosition[0];
		
		$(this.pntrId).removeClassName('left_up');
		$(this.pntrId).removeClassName('right_up');
		$(this.pntrId).removeClassName('left_down');
		$(this.pntrId).removeClassName('right_down');

		var onRight = this._isCarrotOnRightSide(posX);
		var upFacing = this._isCarrotFlipped();
		
		if (onRight && upFacing){
			$(this.pntrId).addClassName( 'right_up' );
			
		} else if (onRight && !upFacing){ 
			$(this.pntrId).addClassName( 'right_down' );			
			
		} else if (!onRight && upFacing){ 
			$(this.pntrId).addClassName( 'left_up' );			
			
		} else if (!onRight && !upFacing){ 
			$(this.pntrId).addClassName( 'left_down' );			
		}

		$(this.pntrId).show();

	},
	
	_positionCarrot: function() {
		var halfHeight = this.element.getDimensions().height / 2;

		var top = 0;
		if (this._isCarrotFlipped()){
			if (is_ie6){
				top = 120 - this.yAdjustedAmount;
			} else {
			 	top = 105 - this.yAdjustedAmount;
			}
			if (this.hoverData != null && !this.hoverData.hasClips && top > 150){
				top = 145; // limit the ugly no clips case on bottom of screen
			}
		} else {
			if (is_ie6){
				top = (halfHeight + 10) - this.yAdjustedAmount;
			} else {
				top = halfHeight - this.yAdjustedAmount;
			}
		}
		$(this.pntrId).setStyle({top:  top + "px"});
	},
	
	_hideCarrot: function(){
		$(this.pntrId).hide();
	},

	_isCarrotFlipped: function(){
		return !this.overTop;
	},

	_isCarrotOnRightSide: function(posX){
		var windowSize = this._getWindowInnerSize();
		var carrotOnRight =  (posX > (windowSize[0]/2));
		return carrotOnRight;
	}, 

	_findXPosition: function(evtMousePos, evtElem) {
		var posX = evtMousePos[0];
		if (this._isCarrotOnRightSide(posX)) {
			// over center line --- flip it
			posX -= this.element.getDimensions().width + 70;
		} else {
			posX += 70;
		}
		return [posX, 0];
	},
	
	_findYPosition: function(evtMousePos, evtElem) {

		var evtPos = Position.page(evtElem);
		var halfHeight = this.element.getDimensions().height / 2;
		var posY = Position.cumulativeOffset(evtElem)[1] - halfHeight; 
		
		var adjustment = 0;

		this.overTop = false;
		this.overBottom = false;

		if (halfHeight > evtPos[1]) {
			// goes over top
			var overTop = halfHeight - evtPos[1];
			adjustment += overTop;
			this.overTop = true;
			
		} else if (this._getWindowInnerSize()[1] < (evtPos[1] + halfHeight)) {
			// goes over bottom
			var overBottom = evtPos[1] + halfHeight - this._getWindowInnerSize()[1];
			adjustment -= overBottom;
			this.overBottom = true;
			
		} else {
			// on the page
			adjustment = 0;
		}

		return [posY, adjustment];
	}, 
	
	_getWindowInnerSize: function(){
		var w = 0, h = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
		    w = window.innerWidth;
		    h = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    w = document.documentElement.clientWidth;
		    h = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    w = document.body.clientWidth;
		    h = document.body.clientHeight;
		}
		return [w, h];
	}
}


var HoverContentData = Class.create();
HoverContentData.prototype = {
	initialize: function(movie_id, requested_movieid, title, poster_url, year, genre, rating, directors, actors, synopsis, next_showing, 
		has_more_showings, has_reviews, num_comments, is_authenticated, my_rating, avg_user_rating, reelz_rating, clips, objecturl, embedcode) {
		this.realId = movie_id;
		this.movieId = movie_id.sub('m','');
		this.realRequestedMovieId = requested_movieid;
		this.requestedMovieId = requested_movieid.sub('m','');
		this.title = title;
		this.imgName = poster_url;
		this.year = year;
		this.genre = genre;
		this.rating =  rating;
		this.directors = directors;
		this.actors = actors;
		this.synopsis = synopsis;
		this.nextShowing = next_showing;
		this.hasMoreShowings = has_more_showings;
		this.hasReviews = has_reviews;
		this.numComments = num_comments;
		this.isAuthenticated = is_authenticated;
		this.myRating = my_rating;
		this.avgUserRating = avg_user_rating;
		this.reelzRating = reelz_rating;
		this.clips = clips; //array of ClipData
		this.hasClips = (clips != null && clips.size()>0);
		this.objecturl = objecturl;
		this.embedcode = embedcode
		
		var baseId = new Date().getTime();
		this.movieInfoId = baseId + "_movie_info";
		this.clipsInfoId = baseId + "_clips_info";
		this.mediaPlayerId = baseId + "_media_player";
		this.carouselId  = baseId + "_carousel";
	}
}

var ClipData = Class.create();
ClipData.prototype = {
	initialize: function(clipId, title, length, description, priOwnId, priOwnName, priOwnURL, priOwnType, mediaURL, 
		repFrame, repFrameThumb, preroll, adtag, clipType, tracking, objectUrl, embedcode) {
			
		this.clipId = clipId;
		this.title = title;
		this.length = length;
		this.description = description;
		this.priOwnId = priOwnId;
		this.priOwnName = priOwnName;
		this.priOwnURL = priOwnURL;
		this.priOwnType = priOwnType;
		this.mediaURL = mediaURL;
		this.repFrame = repFrame;
		this.repFrameThumb = repFrameThumb;
		this.preroll = preroll;
		this.adtag = adtag;
		this.clipType = clipType;
		this.tracking = tracking;
		this.objectUrl = objectUrl;
		this.embedcode = embedcode
	}
}

function getData(nodes) //Use this method when getting data in a CDATA area of an xml file
{
	for(var i = 0; i < nodes.length; i++)
		if(nodes[i].data.length > 0)
			return nodes[i].data;
}

function readAtt(elem, name){
	var att = "";
	try { att = elem.getAttribute(name) || ""; } catch (e) { att=""; }
	return att;
}

var HoverContentXMLTransformer = Class.create();
HoverContentXMLTransformer.prototype = {
	initialize: function(xml) {
		
		var movies = xml.getElementsByTagName("movie");
		var adtags = xml.getElementsByTagName("adTag");

		var movie = movies[0];
		var adtagElem = adtags[0];
		var adtag =  readAtt(adtagElem, 'tag');
		
		var movieId = readAtt(movie, 'id'); 
		var reqMovieId = readAtt(movie, 'reqmovieid'); 
		
		var title = readAtt(movie, 'title'); 

		var posterURL = readAtt(movie, 'image'); 
		if (posterURL == null || posterURL.blank() || posterURL == GROSS_HARDCODED_ASSET_PREFIX_URL) {
			posterURL = NO_POSTER_IMG_URL;
		}
		
		var year = readAtt(movie, 'releaseyear'); 
		var genre = readAtt(movie, 'genre'); 
		var rating = readAtt(movie, 'mparating'); 
		var synopsis = readAtt(movie, 'shortdesc'); 
		
		var reelzRating = readAtt(movie, 'reelzrating'); 
		var userRating = readAtt(movie, 'userrating'); 
		var myRating = readAtt(movie, 'myrating'); 
		
		var nextShowing = readAtt(movie, 'nextshowing'); 
		var nextShowingURL = readAtt(movie, 'nextshowingurl'); 
		
		var hasMoreShowings = readAtt(movie, 'mshowing');

		var commentCount = readAtt(movie, 'comcount');
		
		var actorsXML = movie.getElementsByTagName("actorlist");
		var actors = this.parsePeopleHash(actorsXML);

		var directorsXML = movie.getElementsByTagName("directorlist");
		var directors = this.parsePeopleHash(directorsXML);

		var clipsXML = movie.getElementsByTagName("cliplist");

		var clips = this.parseClips(clipsXML, adtag);
		
		var isAuthenticated = isLoggedIn(); 

		var hasReviews = readAtt(movie, 'hasreviews');
		if (hasReviews==null || hasReviews.blank() || hasReviews=="0" ){
			hasReviews = false;
		} else if (hasReviews == "1"){
			hasReviews = true;
		}
		
		var objectUrl = readAtt(movie,'objecturl');
		
		var tempembed = xml.getElementsByTagName("embedcode");
		var embedcode = getData(tempembed[0].childNodes);

		this.hoverData = new HoverContentData(movieId, reqMovieId, title, posterURL, year, genre, rating,
			directors, actors, synopsis, nextShowing, hasMoreShowings, hasReviews, commentCount,
			isAuthenticated, myRating, userRating, reelzRating, clips, objectUrl, embedcode);
	},
	
	parsePeopleHash: function(peopleXMLList){
		var peeps = $H({});
		
		try {
			var people = peopleXMLList[0].getElementsByTagName("person");
		    for( var i = 0; i < people.length; i++ ) {
				var person = people.item( i );
				var personId = readAtt(person, 'id').sub('p','');
				var personToken = readAtt(person, 'first_name') + ' ' + readAtt(person, 'last_name');
				personToken = personToken.replace(/[^/\w]{1,}/g, '-').toLowerCase();
				if(personToken.substring(0, 1) == '-') {
					personToken = personToken.substring(1, personToken.length);
				}
				personId = personId.sub('d','') + "/" + personToken;
				peeps[personId] = readAtt(person, 'first_name') + "&nbsp;" + readAtt(person, 'last_name');
			}
		} catch(ignored){}
		return peeps;
	},
	
	parseClips: function(clipsXMLList, adtag){
		var clipDatas = [];
		//return clipDatas;
		try {
			var clips = clipsXMLList[0].getElementsByTagName("clip");
		    for( var i = 0; i < clips.length; i++ ) {
				var clip = clips.item( i );

				var clipType = readAtt(clip, 'cliptype');
				clipType = (clipType==null || clipType.blank()) ? "0" : clipType;
				switch(clipType){
					case "0": clipType = "unknown"; break;
					case "1": clipType = "studio"; break;
					case "2": clipType = "reelz"; break;
					case "3": clipType = "user generated"; break;
				}
				
				var tracking = '1';
				
				var priOwnType = readAtt(clip, 'primaryownertype');
				priOwnType = (priOwnType==null || priOwnType.blank() || priOwnType=="0") ? "unknown" : priOwnType;
				
				clipDatas.push(
					new ClipData(
						readAtt(clip, 'id'),
						readAtt(clip, 'title'),
						readAtt(clip, 'length'),
						readAtt(clip, 'description'),
						readAtt(clip, 'primaryownerid'),
						readAtt(clip, 'primaryownername'),
						readAtt(clip, 'primaryownerurl'),
						priOwnType,
						readAtt(clip, 'url'),
						readAtt(clip, 'repFrame'),
						readAtt(clip, 'repFrameThumb'),
						readAtt(clip, 'preroll'), 
						adtag,
						clipType,
						tracking,
						readAtt(clip, 'objecturl')));
			}
		} catch(ignored){}
		return clipDatas;
	}
	
}

var HoverBuilder = Class.create();
HoverBuilder.prototype = {
	initialize: function(data, carouselId) {
		this.hoverData = data;
		this.carouselId = carouselId;
	},
	
	buildHover: function(){
		return this.hoverData.hasClips ? this.buildHoverWithClips() : this.buildHoverSimple();
	},
	
	buildHoverSimple: function(){
		html = "<div class=\"movie_content\" id=\""+ this.hoverData.movieInfoId +"\">";
		html += "    <div class=\"movie_info\">";
		html += "        <div class=\"poster\"><img src=\"" + this.hoverData.imgName + "\" width=\"96\" height=\"144\" title=\""+ this.hoverData.title +"\"/></div>";
		html +=	"        <div class=\"info\">";
		html += "            <h3>"+this.buildMovieTitleLink(this.hoverData)+"</h3>";
		html += "            <p>("+ this.hoverData.year+") "+ this.hoverData.genre+" <strong>"+this.hoverData.rating+"</strong></p>";
		
		var dirArr = [];
		this.hoverData.directors.each(function(pair) {
			dirArr.push("<a href=\""+ PERSON_DETAILS_BASE_URL + pair.key + "\">" + pair.value.strip() + "</a>");
		});
		html += "            <p><strong>Directed by:</strong> " + dirArr.join(", ") + "</p>";
		
		var actArr = [];
		var actCount = 0;
		this.hoverData.actors.each(function(pair) {
			if (actCount++ > 1){ return; }
			actArr.push("<a href=\""+ PERSON_DETAILS_BASE_URL + pair.key + "\">" + pair.value.strip() + "</a>");
		});
		html += "		    <p><strong>Starring:</strong> "+ actArr.join(", ") +"</p>";

		html += "	    	<p><strong>Overview:</strong> " + this.hoverData.synopsis.truncate(75, ' [...]'); +"</p>";
		html += "        </div>";
		html += "    </div>";

		html += "    <div class=\"hover_rater\">";
		html += "        <img src=\""+RATING_HEADER_IMG_URL+"\" width=\"190\" height=\"11\" /><br/>";
		
		html += this.buildRatingModuleSwfEmbed(this.hoverData.isAuthenticated, "mv_"+this.hoverData.movieId+"_hoverRaterLarge", this.hoverData.reelzRating, this.hoverData.avgUserRating, this.hoverData.movieId, this.hoverData.myRating);
		html += "    </div>";

		html += "    <div class=\"next_showing\">";
		html += "        <p style=\"margin-top:5px\"><strong>Next Showing:</strong> "+ this.hoverData.nextShowing +" &nbsp;";
		if (this.hoverData.hasMoreShowings) { html += "|&nbsp; <a href=\""+ this.hoverData.objecturl +"\">More</a>"; }
		html += "        </p>";

		if (this.hoverData.hasReviews){
			html += "       <p><strong>Critic Reviews:</strong> ";
			html += "           <a href=\""+this.hoverData.objecturl+"?tab=review\">Read our review</a>";
			html += "       </p>";
		}
		
		html += "        <p><strong>User Comments:</strong> ";
		if (this.hoverData.numComments > 0){
			html += "<a href=\"" +this.hoverData.objecturl +"\">"+this.hoverData.numComments+" comment"+ (this.hoverData.numComments > 1 ? "s": "") +"</a> &nbsp;|&nbsp; ";
			if (this.hoverData.isAuthenticated) {
				html += "<a href=\""+this.hoverData.objecturl+"\">Add yours</a>";
			} else {
				html += this.buildLoginOrRegisterLinks() + " to add yours.";
			}
		} else {
			if (this.hoverData.isAuthenticated) {
				html += "<a href=\""+this.hoverData.objecturl+"\">Be the first to comment on this movie.</a>";
			} else {
				html += this.buildLoginOrRegisterLinks() + " to review or comment on this movie.";
			}
		}
		
		html += "        </p>";
		html += "    </div>";
		html += "</div>";
		
		return html;		
	},
	
	buildLoginOrRegisterLinks: function() {
		return "<a href=\""+LOGIN_URL+"\">Login</a> or <a href=\""+REGISTER_URL+"\">register</a>";
	},
	
	buildHoverWithClips: function() {

		html = this.buildHoverSimple();

		html += "<div class=\"media_player\" id=\""+this.hoverData.mediaPlayerId+"\" style=\"display:none;\"></div>";
		html += "<div class=\"clips\" id=\""+this.hoverData.clipsInfoId+"\">";
		html += "    <div style=\"display:none;\" class=\"close_media_player\" id=\"close_media_player\" onclick=\"javascript:hover.closePlayer(); return false;\"><a href=\"#\">Close Player</a></div>";

		html += "    <p id=\"num_avail_clips\" class=\"clip_info\"><strong>"+ this.hoverData.clips.size() +" Clip"+ (this.hoverData.clips.size() == 1 ? "": "s") + " Available. Click to Play.</strong></p>";
		html += "    <p id=\"clip_peek_info\" class=\"clip_info\" style=\"display:none;\"></p>";
		html += "    <p id=\"clip_playing_info\" class=\"clip_info\" style=\"display:none;\"></p>";
		html += "    <div class=\"thumbnails\">" +  this.buildClipsThumbs(this.carouselId, this.hoverData.clips) + "</div>";
		html += "</div>";
		return html;
	},

	buildClipsThumbs: function(carouselId, clips) {
		html =  "<table width=\"100%\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
		html += "<tr>";
		html += "<td style=\"padding:0 5px; width:9px; text-align:center\" ><div id=\"prev-arrow-container\"><img id=\"prev-arrow\" class=\"left-button-image\" src=\"\"/></div></td>";
		html += "<td><div class=\"hover-carousel-component\" id=\""+carouselId+"\">";
		html += "    <div class=\"carousel-clip-region\">";
		html += "        <ul class=\"carousel-list\">";
		clips.each(function(clip){
			html += "            <li><a href=\"#\" onclick=\"javascript:hover.playClip("+clip.clipId+"); return false;\"";
			html += "                              onmouseover=\"javascript:hover.peekClipTitle("+clip.clipId+");\" ";
			html += "                               onmouseout=\"javascript:hover.hideClipTitle();\" >";
			html += "                <img id=\"clip_image_"+clip.clipId+"\" src=\"" + clip.repFrameThumb + "\" width=\"68\" height=\"38\" /></a></li>";
		});
		html += "        </ul>";
		html += "    </div>";
		html += "</div>";
		html += "</td>"
		html += "<td style=\"padding:0 5px; width:9px;text-align:center\"><div id=\"next-arrow-container\" ><img id=\"next-arrow\" class=\"right-button-image\" src=\"\"/></div></td>";
		html += "</tr>";
		html += "</table>";
		return html;
	},
	
	buildRatingModuleSwfEmbed: function(loggedin, ratingDivId, reelzrating, avguserrating, movieid, myrating) {
		var so = new SWFObject(REELZ_RATING_MODULE_SWF, ratingDivId, "190", "41", "8", "#f5f8e5");
	    	so.addParam("wmode", "transparent");
		    so.addVariable("loggedin", loggedin);
		    //so.addVariable("embedcode",this.hoverData.embedcode);
		    so.addVariable("reelzrating", Math.round(reelzrating));
		    so.addVariable("avguserrating", Math.round(avguserrating));
		    so.addVariable("movieid", Math.round(movieid));
		    so.addVariable("myrating", myrating);
		return so.getSWFHTML();
	},
	
	buildMovieTitleLink: function(movie) {
		return "<a href=\"" + movie.objecturl +"\" title=\""+movie.title+"\">"+ movie.title +"</a>";
	}
}


var ReelzMediaPlayer = Class.create();
ReelzMediaPlayer.prototype = {
	initialize: function(opts){
		this.options = Object.extend({
			mediaPlayerContentId: "reelz_hover_media_player_content",
			width: "354",
			height: "228",
			backgroundColor: "#333333",
			divId: "reelz_hover_media_player",
			notsure: "8", /* what is this? */
			wmode: "transparent",
			quality: "high"
		}, opts || {});
		this.playing = false;
	},
	
	playClip: function(clipData) {
		var wasPlaying = this.playing;
		this.playing = true;
		$(this.options.mediaPlayerContentId).innerHTML = this.renderSWF(clipData);
		if (!wasPlaying) {
			$(this.options.mediaPlayerContentId).show();
		}
		return false;
	},
	closePlayer: function() {
		if (!this.playing){ return; }
		this.playing = false;
		$(this.options.mediaPlayerContentId).hide();
		$(this.options.mediaPlayerContentId).innerHTML = "";
		
		return false;
	},

	renderSWF: function(clipData) {
		var so = new SWFObject(REELZ_MOVIE_PLAYER_SWF, this.options.divId, this.options.width, this.options.height, this.options.notsure, this.options.backgroundColor);
	     	so.addParam("wmode", escape(this.options.wmode));
	 		so.addParam("quality", escape(this.options.quality));
			so.addParam("allowScriptAccess", "always");
			
		    so.addVariable("clipid", escape(clipData.clipId));
		    so.addVariable("clipurl", escape(clipData.mediaURL));
			so.addVariable("title", escape(clipData.title));
			so.addVariable("description", escape(clipData.description));
			so.addVariable("embedcode",escape(this.hoverData.embedcode));
			
			//so.addVariable("embedcode",escape(clipData.embedcode));
			//so.addVariable("embedcode",this.hoverData.embedcode);
			
			
			so.addVariable("actionPrefix", "/flash_analytics/website_hover/");
			so.addVariable("videourl", escape(""));
			so.addVariable("adtag", escape(clipData.adtag));
			so.addVariable("repframe", escape(clipData.repFrame));
			so.addVariable("useremail",  escape(getProfileEmail()));
			so.addVariable("friendurl", escape(getFullBaseURL() + clipData.objectUrl));
			so.addVariable("relatedname", escape(""));
			so.addVariable("relatedurl", escape(""));
			so.addVariable("preroll", escape(clipData.preroll));
			so.addVariable("autoplay", "true");
			
			so.addVariable("tracking",  escape(clipData.tracking));
			so.addVariable("primaryownername", escape(clipData.priOwnName));
			so.addVariable("primaryownertype", escape(clipData.priOwnType));
			so.addVariable("cliptype", escape(clipData.clipType));
			
		 return so.getSWFHTML();
	}, 
	isPlaying: function(){
		return this.playing;
	}
}




var showMovieTO = null;
var showMovieEventElem = null;
var showMovieEventMousePos = null;
var showMovieId = null;

function showMovie(event, movieId) {
	try 
	{
	    if (showMovieId == movieId){
		    // skip this case -- we are waiting to show
		    hover.clearHideTO();
		    return false;
    		
	    } else if (hover.isAlreadyShowingMovie(movieId, Event.findElement(event, 'a'))) {
		    hover.keepAlive();
		    return false;
	    }
    	
	    if (showMovieTO == null) {
		    hideMovieNow();

		    showMovieId = movieId;
    		
		    showMovieEventMousePos = [Event.pointerX(event), Event.pointerY(event)];
		    showMovieEventElem = Event.findElement(event, 'a');
    		
		    showMovieTO = setTimeout('doShowMovie()', 1000);
		    // timeout event binding is jacked 
		    // doShowMovie();
	    } else {
		    // we are tyring to show a different movie
		    // and one is already scheduled to show -- ignore the first and start showing the second
		    hideMovieNow();
		    showMovie(event, movieId);
	    }
	} catch (e) {
	
	}
	return false;
}

function clearShowTimer() {
	clearTimeout(showMovieTO);
	showMovieTO = null;
	showMovieEventElem = null;
	showMovieEventMousePos = null;
	showMovieId = null;
}

function doShowMovie() {
	hover.hide();
	var movieId = showMovieId;
	showMovieTO = null;
	showMovieId = null;
	
	if (hover.isAlreadyShowingMovie(movieId, showMovieEventElem)) {
		hover.keepAlive();
		return false;
	}
	
	if (hover.loading) {
		hover.keepAlive();
		return false;
	}
	
	hover.updateContent(LOADING_CONTENT);
	hover.loading = true;
	hover.showBy(showMovieEventMousePos, showMovieEventElem);
	hover.currentlyShowingMovieId = movieId;

	new Ajax.Request(getMovieDataURL(movieId), {
		method: 'get',
	  	parameters: {}, 
		onSuccess: function(transport, json) {
			var hoverData = new HoverContentXMLTransformer(transport.responseXML).hoverData;
			
			if (hoverData.requestedMovieId != hover.currentlyShowingMovieId) { 
				return; 
			}
			
			hover.loading = false;
			hover.clearHideTO();
			hover.buildMovieContent(hoverData);
			hover.showBy(showMovieEventMousePos, showMovieEventElem);
			hover.keepAlive();
		},
		onFailure: function(transport){
			hover.loading = false;
			hover.clearHideTO();
			hover.updateContent(ERROR_CONTENT);
			hover.currentlyShowingMovieId = null;
		}
	});
}

function hideMovie(event, elem) {
	try{
	hover.suggestHide(event);
	}
	catch(e) {}
	return false;
}

function hideMovieNow() {
	clearShowTimer();
	hover.hide();
	return false;
}

var carousel = null;
function reinitCarousel(id) {      
	carousel = null;
	carousel = new Carousel(id, {buttonStateHandler: buttonStateHandler, animParameters: {duration: 0.5}, numVisible:4});
}

function buttonStateHandler(button, enabled) {
	if (button == "prev-arrow") {
		if (enabled) {
    		$('prev-arrow').src = SCROLLER_LEFT_ENABLED_IMG_URL;
			$('prev-arrow').title = "Scroll for more clips";
		} else {
    		$('prev-arrow').src = SCROLLER_LEFT_DISABLED_IMG_URL;
			$('prev-arrow').title = "";
		}
	} else {
		if(enabled) {
			$('next-arrow').src = SCROLLER_RIGHT_ENABLED_IMG_URL;	
			$('next-arrow').title = "Scroll for more clips";
		} else {
			$('next-arrow').src = SCROLLER_RIGHT_DISABLED_IMG_URL;	
			$('next-arrow').title = "";
		}
	}
}

var hover = null;
Event.observe(window, 'load', initHover);
function initHover(){
	hover = new Hover({className: "hover", firstElem: 'hover_holder'});
}





