/**
 * @author rrobinson
 */

/**
 * This function implements jsTrace ...
 * @param {string} msg
 */
function trace( msg ){
	if( typeof( jsTrace ) != 'undefined' ){
		jsTrace.send( msg );
	}
}

var jsHDVideo = (function() {
    // -------------------------------------------------------
    // --------------- PRIVATE PROPERTIES --------------------
    // -- while these properties are not available after the
    // -- the function returns they are still available to 
    // -- each of the methods in the object returned because
    // -- lexical scoping in javascript
    // -------------------------------------------------------

    // ------------------- CONSTANTS -----------------------------
    var CONST_PLAYERDIV = "playerDiv";
    var CONST_IFRAME_ID = "hdfndngoIframe";
    var CONST_HDPLAYER_PAGENAME = "";

    if ((typeof(isNewPlayer) != 'undefined') && (isNewPlayer))
        CONST_HDPLAYER_PAGENAME = "VideoPlayer.aspx";
    else
        CONST_HDPLAYER_PAGENAME = "HDFandangoPlayer.aspx";
    // -----------------------------------------------------------

    var _isPlayerLoaded = false;
    var _isMediaComplete = true;
    var _clipData = null;
    var Count = 0;
    var videoTimer = null;
    var countTimerInterval = 0;

    /**
    * This function will invoke the function passed as the method parameter as a member of the
    * object passed as the scope parameter and pass the parameter arg to the invoked function.
    *
    * @param {Object} scope
    * @param {function} method
    * @param {*} arg
    */
    var delegate = function(scope, method, arg) {
        return function() {
            return method.call(scope, arg);
        };
    };

    /**
    * This function simply dumps a javascript object as a string
    *
    * @param {string} header
    * @param {Object} obj
    * @param {number} level
    */
    var dumpObj = function(obj, depth) {
        var indent = '';
        var level = 0;
        if (depth) {
            level = depth;
            for (var i = 0; i < level; i++) {
                indent += "\t";
            }
        }

        var text = "{";
        for (var prop in obj) {
            text += "\n" + indent + prop + ":";
            if (typeof obj[prop] == 'object') {
                text += dumpObj(obj[prop], level + 1);
            }
            else {
                text += obj[prop] + ",";
            }
        }
        text += indent + "}\n";

        return text;
    };

    // -------------------------------------------------------
    // The following statement simply returns an object containing
    // the methods for jsHDVideo.
    // -------------------------------------------------------
    return {
        /**
        * several functions in hdtrailers.js use this field to extract & construct a response object from the
        * 'rel' attribute of an anchor tag on the HD Galleries page.
        *
        * 
        * old: hdVideoFields : ["playurl", "gotoMovie", "guid", "movieCategory", "movieTitle", "movieID"],		 
        **/
        hdVideoFields: ["gotoMovie", "guid", "movieCategory", "movieTitle", "movieID"],

        initialize: function() {
            //_isPlayerLoaded = false;
            _isMediaComplete = true;
            _clipData = null;
            Count = 0;
            videoTimer = null;
            countTimerInterval = 0;

            trace("tracing is on");
            tpController.register(delegate(this, this.playerLoaded));
        },

        /**
        * This method returns the value of _isPlayerLoaded ...
        */
        isPlayerLoaded: function() {
            return _isPlayerLoaded;
        },

        /**
        * This method stops the videoTimer
        */
        stopVideoTimer: function() {
            if (videoTimer) {
                clearInterval(videoTimer);
                videoTimer = null;
            }
        },

        play: function(obj) {
            trace("called play(): dumping:");
            trace(dumpObj(obj));

            this.startPlayer(obj);

            // By the time this point is reached the 'obj' object has been augmented with a title from
            // thePlatform for trailer about to be played. The following call will cause an _hbPageView()
            // call to track the playing of this trailer.
            //this.wssPageView(obj);
        },

        endPlayback: function() {
            trace("endPlayback() called");

            if (!_isMediaComplete) {
                tpController.stop();
                tpController.dispatchEvent("OnMediaEnd", _clipData, tpController.ID, "javascript");
            }

            //_isPlayerLoaded = false;

            // remove the iframe
            var playerDiv = document.getElementById(CONST_PLAYERDIV); // get the iframe parent
            var iframe = document.getElementById(CONST_IFRAME_ID);
            if (playerDiv) {
                if (iframe) {
                    // remove the current iframe
                    playerDiv.removeChild(iframe);
                    iframe = null;
                }
            }

        },

        /**
        * Every quarter second this method is called to check if the _isPlayerLoaded variable is true.
        * If it is true then it stops the video timer and calls tpController.setReleaseURL() to send
        * the currently selected player url to the flvPlayer.
        * 
        * @param {Object} hdURL
        */
        sendReleaseURL: function(hdURL) {
            trace("isPlayerLoaded = " + this.isPlayerLoaded());
            if (this.isPlayerLoaded()) {
                this.stopVideoTimer();
                tpController.setReleaseURL(hdURL);
            }
            else if (countTimerInterval >= 30) {
                this.stopVideoTimer();
                trace("HD player not ready! Closing player window.");
                return;
            }
            countTimerInterval++;
        },

        /**
        * This method is provided as a callback function to registered with tpController.registerFunction().
        * If called it will set the variable _isPlayerLoaded to true;
        */
        playerLoaded: function() {
            _isPlayerLoaded = true;
            this.configureListeners();
            trace("The player has been loaded!");
        },

        /**
        * This method establishes event listeners for several events dispatched by thePlatform's controls
        */
        configureListeners: function() {
            trace("Called jsHDVideo.configureListeners");
            tpController.addEventListener("OnPlayerLoaded", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnClipInfoLoaded", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnJavascriptLoaded", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMute", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnSetReleaseUrl", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnSetVolume", "DVIDEO.jsEventHandler");
            tpController.addEventListener("OnShowFullScreen", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnReleaseStart", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnReleaseEnd", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaLoadStart", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaLoading", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaStart", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaPlaying", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaEnd", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaComplete", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaBuffer", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaPlay", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaPause", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaUnpause", "jsHDVideo.jsEventHandler");
            tpController.addEventListener("OnMediaSeek", "jsHDVideo.jsEventHandler");
            // tpController.addEventListener("", "jsHDVideo.jsEventHandler");
            trace("tpController Event Listeners configured!");
        },

        removeListeners: function() {
            trace("Called jsHDVideo.removeListeners");
            tpController.removeEventListener("OnPlayerLoaded", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnClipInfoLoaded", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnJavascriptLoaded", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMute", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnSetReleaseUrl", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnSetVolume", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnShowFullScreen", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnReleaseStart", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnReleaseEnd", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaLoadStart", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaLoading", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaStart", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaPlaying", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaEnd", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaComplete", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaBuffer", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaPlay", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaPause", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaUnpause", "jsHDVideo.jsEventHandler");
            tpController.removeEventListener("OnMediaSeek", "jsHDVideo.jsEventHandler");
            // tpController.removeEventListener("", "jsHDVideo.jsEventHandler");
            trace("tpController Event Listeners removed!");
        },

        /**
        * This method is the event listener for events dispatched from thePlatform's controls
        * 
        * @param {Object} evt	thePlatform's javascript Event object
        */
        jsEventHandler: function(evt) {	// parameter is Event from utils.js (from thePlatform's PDK)
            //trace("jsEventHandler() handling event.type = " + e.type);
            switch (evt.type) {
                case "OnPlayerLoaded":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    if (!_isPlayerLoaded) _isPlayerLoaded = true;
                    break;
                case "OnClipInfoLoaded":
                    break;
                case "OnJavascriptLoaded":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    break;
                case "OnMute":
                    // WSS Reporting:
                    _hbLink("VIDHD_Player_MDC", "VIDHD_Player_MDC_Volume");
                    break;
                case "OnSetReleaseUrl":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    break;
                case "OnSetVolume":
                    // WSS Reporting:
                    _hbLink("VIDHD_Player_MDC", "VIDHD_Player_MDC_Volume");
                    break;
                case "OnShowFullScreen":
                    // WSS Reporting: (Expand)
                    _hbLink("VIDHD_Player_MDC", "VIDHD_Player_MDC_Expand");
                    break;
                case "OnReleaseStart":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    _clipData = null;
                    break;
                case "OnReleaseEnd":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    break;
                case "OnMediaLoadStart":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    break;
                case "OnMediaLoading":
                    break;
                case "OnMediaStart":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    _isMediaComplete = false;
                    _clipData = evt.data;
                    //trace("_clipData : " + dumpObj(_clipData));
                    break;
                case "OnMediaPlaying":
                    //trace("jsEventHandler() handling event.type = " + evt.type);
                    break;
                case "OnMediaEnd":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    break;
                case "OnMediaComplete":
                    _isMediaComplete = true;
                    break;
                case "OnMediaBuffer":
                    break;
                case "OnMediaPlay":
                    trace("jsEventHandler() handling event.type = " + evt.type);
                    //_hbLink("lid=VIDHD_Player_MDC", "");
                    break;
                case "OnMediaPause":
                    // WSS Reporting:
                    _hbLink("VIDHD_Player_MDC", "VIDHD_Player_MDC_Pause");
                    break;
                case "OnMediaUnpause":
                    // WSS Reporting:
                    _hbLink("VIDHD_Player_MDC", "VIDHD_Player_MDC_Play");
                    break;
                case "OnMediaSeek":
                    // WSS Reporting:
                    _hbLink("VIDHD_Player_MDC", "VIDHD_Player_MDC_Scrub");
                    break;
            }
        }, // closing jsEventHandler

        /**
        * This method starts the player for the IE browsers. It first extracts the protocol and domain from the
        * from the current page location and build a new url referencing the page to be installed in the iframe and
        * provides a parameter indicating the releaseUrl of the movie requested. Finally, it builds the iframe.
        **/
        startPlayer: function(obj) {
            var protocol = window.location.protocol + "//";
            var host = window.location.host;
            var pagename = CONST_HDPLAYER_PAGENAME;

            if ((host.toLowerCase()).indexOf(".com") == -1) {
                host += "/";
            }

            var virtDir = ("" + window.location).indexOf('/mdc2.0/') >= 0 ? "/mdc2.0/" : "/";
            var playerUrl = protocol + host + virtDir + pagename + "?src=" + obj["guid"] + "&movie=" + obj["movieTitle"] + "&video=" + obj["videoTitle"];    // Dev-workstation version

            trace("startPlayer(): playerUrl = " + playerUrl);

            this.createIframe(CONST_PLAYERDIV, CONST_IFRAME_ID, playerUrl);

        },

        /**
        * This method will contruct the iframe for IE browsers
        **/
        createIframe: function(divId, frameId, src) {
            var playerDiv = document.getElementById(divId);

            var iframe = document.getElementById(frameId);

            if (iframe) {
                // remove the current iframe
                playerDiv.removeChild(iframe);
                iframe = null;
            }

            // create a new iframe
            iframe = document.createElement("iframe");
            iframe.setAttribute("id", frameId);
            iframe.setAttribute("frameBorder", "0");
            iframe.style.border = "0px";
            iframe.setAttribute("marginheight", "0");
            iframe.setAttribute("marginwidth", "0");
            iframe.setAttribute("height", "450");
            iframe.setAttribute("width", "800");
            iframe.setAttribute("scrolling", "no");
            iframe.setAttribute("src", src);
            iframe.style.visibility = "visible";

            playerDiv.appendChild(iframe);
        }

        /* *********** */
} // end of object returned by this function

    })();

/**
 * When the open event is called, this function will be used to 'open'
 * the overlay, container and data portions of the modal dialog.
 *
 * onOpen callbacks need to handle 'opening' the overlay, container
 * and data.
 */
function modalOpen (dialog) {		
	dialog.overlay.fadeIn(200, function () {
		$("#simplemodal-overlay").css("height",$(document).height()); //fix for IE 'no' height issue				
		var topAdjust = $("#simplemodal-container").css("top");		
		/* firefox fix */
		topAdjust = ($(window).height()-$("#simplemodal-container").height())/2;
		
		if (($(window).height() < 600) || (topAdjust == "0px")) {
			topAdjust = "24px";	
		}				
		dialog.container.hide().css("top",topAdjust).fadeIn(200, function () {
			dialog.data.hide().fadeTo(500,1,function() { $(this).show();
  			});
		});
	});
	
	// add click event for WSS reporting on clicking close box
	$("a.modalCloseImg").click(function(){_hbLink("VIDHD_Player_Close_MDC", "VIDHD_Player_MDC_Close_X");});
}
/**
 * After the dialog is shown, this callback will bind some effects
 * to the data when the 'button' button is clicked.
 *
 * This callback is completely user based; SimpleModal does not have
 * a matching function.
 */
function modalShow (dialog) {
	dialog.data.find('input.animate').one('click', function () {
		dialog.data.slideUp('slow', function () {
			dialog.data.slideDown('slow');
		});
	});
}
/**
 * When the close event is called, this function will be used to 'close'
 * the overlay, container and data portions of the modal dialog.
 *
 * The SimpleModal close function will still perform some actions that
 * don't need to be handled here.
 *
 * onClose callbacks need to handle 'closing' the overlay, container
 * data and iframe.
 */
function modalClose (dialog) {
	dialog.data.hide('fast', function () {
		dialog.container.hide('fast', function () {
			dialog.overlay.fadeOut('fast', function () {
				$.modal.close();
			});
		});
	});				
	
	jsHDVideo.endPlayback();
} 

/**
 * Temporarily disable ads
 */ 
function hideAds() {
	$("#HeaderContainer .AdUnit iframe, #container .AdUnit iframe").css("visibility","hidden");
}

function revealAds() {
	embeds = document.getElementsByTagName('iframe');
	for(i = 0; i < embeds.length; i++) {
	    embeds[i].style.visibility = 'visible';
	}
}

/**
 * used to populate the sharethis attributes with the title and url
 */
function objToShareThisAttr(theSexyObject) {	
	// insert the share this span
	$("#modalPlayer .sharethisContainer").html("<span st_url=\"" + theSexyObject.trailerPage + "\" st_title=\"" + theSexyObject.videoTitle + "\" class=\"st_sharethis_custom\">ShareThis</span>");
	
	// Rebind the ShareThis action to the button
	stButtons.locateElements();
}

/**
 * When the user clicks on a movie in the browse section this function will be invoked.
 * It will extract all relevant info it need from the html tags that makeup the movie 
 * info on the page; it will update the dialog then it will play the movie.
 */
function hdsetup(thisEl) {
	var obj = parseRelString($(thisEl).attr("rel"));
	objToShareThisAttr(obj,thisEl);
	// get the movie title
	var title = $(thisEl).children("span").children("span").children("input").val();
	
	// need to add the title (from thePlatform) to the obj object just in case there is no movieTitle (the Fandango movie title)
	obj["title"] = title;
	
	// add info to the popup dialog
	$("#playerContent h2").text(obj["videoTitle"]);
	setMovieDetailsLink(obj);
	
	// start playing the movie
	jsHDVideo.play(obj);
}

/**		SECTION I    ********************************************************************
 * NOTE: Because the info on the HTML page is layed out slightly differently for each of
 * layout areas displaying HD movie trailer images, titles and links several functions are
 * needed to extract the info that must be passed to the popup dialog.
 *
 * Each of the functions in this section are variations on the hdsetup() function to achieve
 * the same result for the popup dialog 
 */
function hdSetFeaturedImageLink(thisEl)
{
	var obj = parseRelString($(thisEl).attr("rel"));
	objToShareThisAttr(obj,thisEl);
	// extract the title:
	var title = $(thisEl).attr("title");
	
	// the title in the image alt attribute has a suffix " HD Trailer" which should be removed
	title = title.replace(" HD Trailer", "");
	
	// need to add the title (from thePlatform) to the obj object just in case there is no movieTitle (the Fandango movie title)
	obj["title"] = title;
	
	trace("title = " + title);
	$("#playerContent h2").text(obj["videoTitle"]);
	setMovieDetailsLink(obj);
	
	jsHDVideo.play(obj);
}

function hdSetFeaturedTitleLink(thisEl)
{
	var obj = parseRelString($(thisEl).attr("rel"));
	objToShareThisAttr(obj,thisEl);
	// extract the title:
	var title = $(thisEl).text();
	
	// need to add the title (from thePlatform) to the obj object just in case there is no movieTitle (the Fandango movie title)
	obj["title"] = title;
	
	trace("title = " + title);
	$("#playerContent h2").text(obj["videoTitle"]);
	setMovieDetailsLink(obj);
	
	jsHDVideo.play(obj);
}

function hdSetFeaturedPlayable(thisEl) 
{
	var obj = parseRelString($(thisEl).attr("rel"));
	objToShareThisAttr(obj,thisEl);
	// extract the title:
	var title = $(thisEl).attr("title");
	
	// need to add the title (from thePlatform) to the obj object just in case there is no movieTitle (the Fandango movie title)
	obj["title"] = title;
	
	trace("title = " + title);
	$("#playerContent h2").text(obj["videoTitle"]);
	setMovieDetailsLink(obj);
	
	jsHDVideo.play(obj);
}

/**
* Check a value for the url in an anchor tag, and if it's empty then hide the DOM element 
* Optional: the name of a previous sibling to hide (such as an arrow graphic)
*
*/
function setOrRemoveLink(uri, domId, prevSibToRemove) {
    if (uri.length > 0) {
        if (prevSibToRemove) {
            $(domId).prev(prevSibToRemove).show();
        }
        $(domId).attr("href", uri).show();
    } else {
        if (prevSibToRemove) {
            $(domId).prev(prevSibToRemove).hide();
        }
        $(domId).hide();
    }
}
/**
 * This function updates the fields on the popup with data from the array of values ("obj") passed in 
 * from the rel tag.
 *
 */
function setMovieDetailsLink(obj) {
    // Update all the fields on the page
    if (obj["mpaaRating"].length > 0) {
        $("#modalPlayer #playerContent .movieInfo span").html(obj["mpaaRating"]).show();
    } else {
        $("#modalPlayer #playerContent .movieInfo span").hide();
    }

    var titleToSet = obj["videoTitle"];
    $("#playerLogo").html(titleToSet);

    $("#modalPlayer #playerContent .movieInfo a").html(obj["movieTitle"]);
    $("#modalPlayer #playerContent .movieInfo a").attr("href", obj["gotoMovie"]);

    setOrRemoveLink(obj["movieReviewsUrl"], "#modalPlayer #playerContent #goToFullMovieDetails", ".arrowGreen");
    setOrRemoveLink(obj["movieTimesUrl"], "#modalPlayer #playerContent #goToGetMovieTimes", ".arrowGreen");
    setOrRemoveLink(obj["movieTrailersUrl"], "#modalPlayer #playerContent a.buttons.viewAllTrailers");
    
    return;
}

/**
 * The function extracts values from a string where the values in the string are delimited by '^'
 * It returns an object containing name/value pairs where the names have been predefined by an array
 * called fields (internal to the function) 
 **/
function parseRelString(str) {
	var result = {};
	
	var arry = str.split("^");
	var fields = ["gotoMovie",
	                "guid",
	                "movieCategory",
	                "movieTitle",
	                "movieID",
	                "videoTitle",
	                "description",
	                "thumbnailURL",
	                "trailerPage",
	                "mpaaRating",
	                "movieReviewsUrl",
	                "movieTimesUrl",
	                "movieTrailersUrl"];

	if (fields.length <= arry.length)
	{	
		for (var i = 0; i < fields.length; i++)
		{
			result[fields[i]] = arry[i];
		}
	}
	else
	{
		result[fields[0]] = arry[0];
		result[fields[1]] = "#";
	}
	
	return result;
}
/********************************************************************
 **		END OF SECTION I    
 ********************************************************************/

/**
 * name: removeSortClass
 * description: This function removes the style class value 'ascending' or 'descending'
 * from the class attribute for the element with the given id.
 *
 * param: id	dom element id
 **/
function removeSortClass(id)
{
	if ($(id).hasClass("ascending"))
	{
		$(id).removeClass("ascending");
	}
	else if ($(id).hasClass("descending"))
	{
		$(id).removeClass("descending");
	}	
}

function flipSortClass(id, defaultClass)
{
	if ($(id).hasClass("ascending"))
	{
		$(id).removeClass("ascending");
		$(id).addClass("descending");
	}
	else if ($(id).hasClass("descending"))
	{
		$(id).removeClass("descending");
		$(id).addClass("ascending");
	}
	else
	{
		$(id).addClass(defaultClass);
	}
}


$(document).ready(function() {
	/* modify click behavior of the 2 sort fields */
	$("#HDTrailersContent_SortTitle").click(function(){
		/* remove ascending/descending class */
		removeSortClass("#HDTrailersContent_SortDate");
		flipSortClass("#HDTrailersContent_SortTitle", "ascending");
	});
	
	$("#HDTrailersContent_SortDate").click(function(){
		/* remove ascending/descending class */
		removeSortClass("#HDTrailersContent_SortTitle");
		flipSortClass("#HDTrailersContent_SortDate", "descending");
	});
	
	/* add class playable to items that can trigger the player */    		
	$(".playable").live("click", function(e) {
		if (e.button == 0) {		
			e.preventDefault(); // keep anchor effect from happening
					
			$('#modalPlayer').modal({	
				zIndex: 900000,
				opacity: 75,
				onOpen: modalOpen,
				onClose: modalClose, 
				persist: true,
				overlayClose: true			
			});		
			hdsetup(this);
		} else {
			return false;
		}		
	});
	
	$("#hdFeaturedImageLink").click(function(e) {
		e.preventDefault(); // keep anchor effect from happening
		
		$('#modalPlayer').modal({
			opacity: (70),
			onOpen: modalOpen,
			onClose: modalClose, 
			persist: false,	
			overlayClose: true		
		});
		hdSetFeaturedImageLink(this);
	});
	
	$("#hdFeaturedTitleLink").click(function(e) {
		e.preventDefault(); // keep anchor effect from happening
		
		$('#modalPlayer').modal({
			opacity: (70),
			onOpen: modalOpen,
			onClose: modalClose, 
			persist: false,
			overlayClose: true			
		});
		hdSetFeaturedTitleLink(this);
	});
	
	$("a.featured_playable").live("click", function(e){
		if (e.button == 0) {
			e.preventDefault(); // keep anchor effect from happening
			
			$('#modalPlayer').modal({
				opacity: (70),
				onOpen: modalOpen,
				onClose: modalClose, 
				persist: false,
				overlayClose: true			
			});
			hdSetFeaturedPlayable(this);
		} else {
			return false;
		}
	});
	
	$(document).keydown(function(e){
		if( e.which == 27 )
			$.modal.close();
	});
	
	$("#other_featured a.image").hover(function() {
		$(this).siblings(".covermask").show();
	}, function() {
		$("#other_featured .covermask").hover(function() {
			$(this).show();
		}, function() {
			$(this).hide();
		});
		$(this).siblings(".covermask").hide();
	});
	
	$("a.simplemodal-close").live("click",function() {
		$.modal.close();
	});
});

