var strSWF = "/flash/ReferrerRedirect.ashx";
var _idFlashPlayer = "FlashPlayer";
var strVars = "ctrl="+_idFlashPlayer+"&rootURL=" + encodeURIComponent ("http://" + location.host);
var _fAddHistory = true;
var _fSafari = ((navigator.userAgent.toLowerCase().indexOf("safari") >= 0) && (navigator.platform.toLowerCase().indexOf("mac") >=0));
var _currentChannel = 0;
var _idCommentType = 2;
var channelName = document.getElementById("channelName");
var channelId = document.getElementById("channelId");
    
var _idMedia;
var _strMediaList;

var _idMediaInitial;
var _strMediaListInitial;

var _delegateVideoChanged = new Delegate ();
var _delegateQueryWaitForPostroll = new Delegate ();

var _ruleItem;

// loads and starts the player on the page
// idMedia: the initial media to show
// strMediaList: the context
// fAutoPlayDisabled: allows overriding autoplay
function StartPlayer (idMedia, strMediaList, fAutoPlayDisabled)
{
	// register a callback for when the user's logged-in status changes
	_delegateLoginStatusChanged.Register (
		function (fLoggedIn)
		{
			// reload the comments panel because the user's own comments are hilighted
//			var eltComments = document.getElementById("liComments");
//			var node = GetContentNode (eltComments);
//			if (node)
//				node.load("/browse/Comments.aspx?ct=2&id=" + _idMedia, true); 
		}
	);

	// look in the url fragment for overridden media ID/list
	var strQuery = GetQueryFromAfterPound (window.location.href);
	var qs = ParseQueryString (strQuery);

	if (qs)
	{
		idMedia = qs ["id"] || idMedia; // replace the media ID
		strMediaList = qs ["ml"] || strMediaList;   // replace the media list
	}
	
	// remember the media/list that we started with, so we can handle history correctly
	_idMediaInitial = idMedia;
	_strMediaListInitial = _strMediaList = strMediaList;
	
	// we're going to start playing, but we don't want this event to be added to the history
	_fAddHistory = false;
	
	// initialize the history
	window.dhtmlHistory.initialize();
	var fPlayMedia = !window.dhtmlHistory.fireOnNewListener;
	window.dhtmlHistory.addListener(OnHistoryChange);

	// start playing the video
	//if (fPlayMedia) PlayMedia (idMedia, strMediaList);
	if (fPlayMedia) setTimeout (function () { PlayMedia (idMedia, strMediaList); }, 1); 
	
    if (menuOpen && !stopVideo)
	    PauseVideo();

}

// handles callbacks from the history component fired when the user clicks the next/back browser buttons
function OnHistoryChange (hash)
{
	// get the media/list we started with
	var idMedia = _idMediaInitial;
	var strMediaList = _strMediaListInitial;
	
	// parse the history entry
	var qs = ParseQueryString (hash);
	if (qs)
	{
		// if the history entry contains media/list info, then overrride
		idMedia = qs ["id"] || idMedia;
		strMediaList = qs ["ml"] || strMediaList;
	}

	// prevent recursive history events
	_fAddHistory = false;

	// start playing the video
	setTimeout (function () { PlayMedia (idMedia, strMediaList); }, 1);
}

var _videoPending;  // remembers the last video we played while the player was in fullscreen mode
var _fFullscreen = false;   // is the player currently in fullscreen mode?

// called by the player when it starts playing a new video
function onVideoChanged (video)
{
	// quit if nothing's changed
	if (!video || _idMedia == video.id)
		return;
	
	// remember the video we're now playing
	_idMedia = video.id;	// global
	
	// if we didn't set a media ID when loading the player, remember this now for the history
	if (!_idMediaInitial)
		_idMediaInitial = _idMedia;

	// add this video play to the history, if necessary
	if (_fAddHistory)
	{
		var state = "";
		if (_idMedia)
			state += "id=" + _idMedia;
		if (_strMediaList)
		{
			if (state)
				state += "&";
			state += "ml=" + encodeURIComponent(_strMediaList);
		}
		try
		{
			window.dhtmlHistory.add (state);
		}
		catch(err)
		{
			//alert(err);
		}
	}
    
	// subsequent plays should go in the history
	_fAddHistory = true;

	// browser crash workaround:
	// if the player's in fullscreen mode, then we rembmer the video info and bail.
	if (_fFullscreen)
	{
		_videoPending = video;
		return;
	}
	
	// make sure we don't render this video info twice
	_videoPending = null;
	
	// render the video info
	RenderVideoInfo (video);
	
	// tell anyone else that's interested that the video's changed
	_delegateVideoChanged.Invoke (video.id, _strMediaList);

	// google tracking call:
	if (pageTracker)
	{
		try
		{
			var currentChannelName = document.getElementById("channelName").innerHTML;
			if (!currentChannelName)
				currentChannelName = 'No_Channel_Info';
			if (video.id && video.title)
				vidPart = video.id + '/' + video.title;
			else
				vidPart = 'No_Video_Info';
			pageTracker._trackPageview(('/Stream/' + currentChannelName + '/' + vidPart).replace(/ /g,'_'));
		}
		catch (e)
		{
			pageTracker._trackPageview('/Stream/No_Channel_Info/No_Video_Info/Exception');
		}
	}
}


// updates the dynamic parts of the page that we're
function RenderVideoInfo (video)
{
	// update the "Now Playing" display in the medialist accordions on the right
	if ($jq('#currentMediaID').html()!= null && $jq('#currentMediaID').html() != video.id && $jq('#currentMediaID').html()!='') {
	    SelectMedia(video.id);
	    LoadNowPlaying(video.id);
	    LoadComments(video.id);
	    $jq('#currentMediaID').html(video.id);
	}
	
//	var admLink = document.getElementById("ctl00_linkHeaderAdmin");
//	if (admLink) {
//	    admLink.href = admLink.href.substring(0,admLink.href.indexOf("/admin/")+7) + "EditMedia.aspx?id=" + video.id;
//	}

	// update various media-specific panels

	// embed panel
	//var eltPanelEmbed = document.getElementById("panelEmbed");
	//eltPanelEmbed.setURL("/play/panels/embed.aspx?id=" + _idMedia + "&ml=" + encodeURIComponent(_strMediaList));


       	// ratings widget
	    /*var eltRatingInput = document.getElementById("RatingInput");
	    var eltRatingWrapper = document.getElementById("RatingWrapper");
	    var eltRatingText = document.getElementById("RatingText");
    	
	    if (video.ratingsExempt)
	    {
		    if (eltRatingInput)
			    eltRatingInput.style.display = "none";
		    if (eltRatingText)
			    eltRatingText.style.display = "none";
	    }
	    else if (eltRatingInput && eltRatingWrapper && eltRatingText)
	    {
		    eltRatingInput.style.display = "block";
		    eltRatingWrapper.className = "star_0";
		    eltRatingText.style.display = "block";
		    if (video.ratingsCount >= 3)
		    {
			    InnerText (eltRatingText, AddCommas(video.ratingsCount) + " Ratings");
			    eltRatingWrapper.className = "star_" + video.rating;
		    }
		    else
			    InnerText (eltRatingText, "Rate this Video:");
	    }
	*/
	    // HD graphic
	    SetClass (document.body, "fHasHD", video.fHasHD);
    
	var fCompanionWasVisible = _fCompanionVisible;
	var fChannelChanging = video.channelID != _currentChannel;
	
	// hide the previous companion ad, if any
	HideCompanionAd ();

	// update the page title

//	if (document.title)
//		document.title = video.title + " - Crackle";

	/*var eltVideoDateShared = document.getElementById('VideoDateShared');
	var strShortDate = _month[video.dateShared.getMonth()] + " " + video.dateShared.getDate() + "," + video.dateShared.getFullYear();
	eltVideoDateShared.innerHTML = strShortDate;
	*/

	//update stats	
	var eltSFlashPlayerContainer = document.getElementById('FlashPlayerContainer');
	if (eltSFlashPlayerContainer)
			eltSFlashPlayerContainer.className = "FlashPlayerContainer";
		
	var eltVideoPlaylistCount = document.getElementById('VideoPlaylistCount');
	if (eltVideoPlaylistCount)
		eltVideoPlaylistCount.innerHTML = video.playlistCount;

	var eltVideoPointCount = document.getElementById('VideoPointCount');
	if (eltVideoPointCount)
		eltVideoPointCount.innerHTML = video.leaderboardPoints;	
		
		var eltVideoViewCount = document.getElementById('VideoViewCount');
	if (eltVideoViewCount)
		eltVideoViewCount.innerHTML = video.viewCount;
	
	
	var eltBrowsePanel = document.getElementById('CrackleBrowsePanel');
	if (eltBrowsePanel && eltBrowsePanel.VideoChange)
		eltBrowsePanel.VideoChange(video);
	
	
	// remove any waiting for postroll messages
	var eltAccordionLinks = document.getElementById("accordionLinks");
	RemoveClass(eltAccordionLinks, "ppr");
}

// called by the player when the player's list changes
function onListChanged (list)
{
	_strMediaList = list.search.key;
}

// called by the player when it switches fullscreen mode
function onFullscreenChanged (fFullscreen)
{
	// disable the ad refreshes while in fullscreen
	if (_adRight)
		_adRight.AllowRefresh (!fFullscreen);
	if (_adFooter)
		_adFooter.AllowRefresh (!fFullscreen);
	
	if (fFullscreen != _fFullscreen)
	{
		_fFullscreen = fFullscreen;
		
		// if we're switching out of fullscreen mode and there was a pending video,
		// then render the video's info on the page
		if (!fFullscreen && _videoPending)
		{
			var video = _videoPending;
			_videoPending = null;
			RenderVideoInfo (video);
		}
	}
	
	// google tracking of fullscreen switches
	if (pageTracker)
	{
		if (fFullscreen)
			pageTracker._trackPageview ("/Actions/Full_Screen_On");
		else
			pageTracker._trackPageview ("/Actions/Full_Screen_Off");
	}
}

function isFlashPlayerPlugin() {
    var MM_contentVersion = 9;
                    var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
                    if ( plugin ) {
		                    var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	                        for (var i = 0; i < words.length; ++i)
	                        {
		                    if (isNaN(parseInt(words[i])))
		                    continue;
		                    var MM_PluginVersion = words[i]; 
	                        }
	                    var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
                    }
                    else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)) {
                        try {
                            MM_FlashCanPlay = (typeof(new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+MM_contentVersion)) == "object");
                        } catch (e) {
                            MM_FlashCanPlay = false;
                        }
                    }
     return MM_FlashCanPlay;
}

// play a given video in a given context
function PlayMedia (idMedia, strMediaList, fAutoPlayDisabled)
{
    $jq('#currentMediaID').html(idMedia);
    //SelectMedia(idMedia);
    //LoadNowPlaying(idMedia);
	// this removes those pesky dotted outlines on link labels
	ClearFocus ();
	window.scrollTo(0,0);

	// sanitize the inputs:

	idMedia = parseInt (idMedia);
	
	// don't do anything if nothing's changed
	if (idMedia == _idMedia && strMediaList == _strMediaList)
		return false;

	if (!strMediaList)
	{
		if (!idMedia)
			return false;	// nothing to do
		strMediaList = "";
	}

	// check to see if we've already created the flash player
	var eltPlayer = document.getElementById (_idFlashPlayer);
    
	if (eltPlayer)
	{
		// if we have a media ID, then play that, otherwise just play the list from the start
		if (idMedia)
			eltPlayer.PlayMedia && eltPlayer.PlayMedia (idMedia, strMediaList);
		else
			eltPlayer.PlayMediaList && eltPlayer.PlayMediaList (strMediaList);
		
		//EnsureVisible(eltPlayer);	// scroll the page so the player is visible
		return false;
	}
	// use SWFObject to create the player
	var so = new SWFObject("/flash/ReferrerRedirect.ashx", _idFlashPlayer, "555", "310", "9.0.115", "#000000", "high", window.location);
	if (!_version.IsMac)
		so.useExpressInstall('/flash/expressinstall.swf');

	so.addParam ("wmode", "window");
	so.addParam ("allowFullScreen", "true");
	so.addParam ("allowScriptAccess", "always");

	// pass in various flashvars to the player:

	if (!isNaN (idMedia) && idMedia > 0)
		so.addVariable("id", idMedia);
	
	if (strMediaList)
		so.addVariable("ml", encodeURIComponent (strMediaList));
	
	if (fAutoPlayDisabled)
		so.addVariable("ap", 0);
	
	// tel the player which host has the media:
	if (_strRemoteMediaServer)
		so.addVariable("rms", encodeURIComponent (_strRemoteMediaServer));
	
	// QueryReferrer is broken on Safari/Windows, force the external site
	if (_version.IsSafari && !_version.IsMac)
		so.addVariable ("site", 16);
	
	so.addVariable("rootURL", encodeURIComponent ("http://" + location.host));
	so.addVariable("ctrl", _idFlashPlayer);	// tell the player the name of its control
	so.addVariable("internal", 1);
	
	if (so.write("FlashPlayerContainer")&&isFlashPlayerPlugin())
	{
		// notify the player of any login status changes on the page
		_delegateLoginStatusChanged.Register (
			function (fLoggedIn)
			{
				var eltPlayer = document.getElementById (_idFlashPlayer);
				if (eltPlayer && eltPlayer.changeLoginStatus)
					eltPlayer.changeLoginStatus (fLoggedIn);
			}
		);
	}
	else
	{
		// FAIL: show the no-flash error
		var elt = document.getElementById ("FlashPlayerContainer");
		elt.innerHTML = "<a href='http://www.adobe.com/go/getflashplayer'><img src='/images/GetFlash9.jpg' alt='Click here to install Adobe&acute;s Flash Player'/></a>";
		AddClass(elt, "noflash");
	}
	
	shareOnFacebook();
	return false;
}

function PauseVideo()
{
	var eltPlayer = document.getElementById (_idFlashPlayer);
	if (typeof(eltPlayer) != "undefined" && eltPlayer && !stopVideo) {
        hideFlashPlayer();
        eltPlayer.pauseVideo ();
	    stopVideo = true;
	    }
	else hideFlashPlayer();
}
function PlayVideo()
{
	var eltPlayer = document.getElementById (_idFlashPlayer);
    if (typeof(eltPlayer) != "undefined" && eltPlayer && stopVideo) {
        showFlashPlayer();
        eltPlayer.playVideo (); 
	    //eltPlayer.PauseVideo ();
	    stopVideo = false;
	} else showFlashPlayer();
}
// scroll the browser window so an element is visible on the page
function EnsureVisible(elt)
{
	var windowTop = document.body.scrollTop;

	if (windowTop == 0)
	{
		if (window.pageYOffset)
			windowTop = window.pageYOffset;
		else
			windowTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	
   /* var  windowHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) 
	{
		windowHeight = window.innerHeight;
	} 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
	{
		windowHeight = document.documentElement.clientHeight;
	} 
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
	{
		windowHeight = document.body.clientHeight;
	}
   */ 	
	var eltTop = elt.offsetTop;
	var eltHeight = elt.scrollHeight;
	var eltBottom = eltTop + eltHeight;
		
		
	//alert (windowHeight + " " + windowTop + " " + ( eltBottom / 4));
			
	if (windowTop > (eltBottom / 4))
	{
		window.scrollTo(0, eltTop);
	}

}

// is this still used?
function AddParam (elt, name, value)
{
	var eltParam = document.createElement ('param');
	eltParam.setAttribute ('name', name);
	eltParam.setAttribute ('value', value);
	elt.appendChild (eltParam);
}


// update the dynamic channel-specific areas on the page
function RenderChannelInfo (idChannel)
{
	// get the channel info from the loaded collection, bail if not found
	var channel = _channels.GetChannel (idChannel);
	if (!channel)
		return;

	// refresh the ads
	if (_adRight)
		_adRight.SetPage("");
	if (_adFooter)
		_adFooter.SetPage("");

	// get the rules parent for this channel
	// (the first self-or-ancestor that has the 'use rules' checkbox checked)
	var channelRules = channel.GetRulesParent ();
	if (channelRules == null)
		channelRules = channel;

	// update the channel branding images
	var eltFlashPlayerContainer = document.getElementById("FlashPlayerContainer");
	
	// update the subscription link
	var eltChannelSubscribeLink = document.getElementById('SubscribeLink'); 
	if (eltChannelSubscribeLink)
	{
		eltChannelSubscribeLink.onclick = function ()
		{
			SubscribeToList('fc=' + channel.ID + '&fx=', "subscribe to this channel.");
			return false;
		}
	}
	
	// update the RSS link
	var eltRSSLink = document.getElementById ('ChannelRSSLink');       
	if (eltRSSLink)
	{
		eltRSSLink.href = channel.ChannelRSSLink;
	}

	// update the blogs panel
	var eltBlogPanel = document.getElementById('liBlogs');
	if (eltBlogPanel)
	{
		if (channelRules && channelRules.BlogURL)
		{
			eltBlogPanel.style.display = "";
			GetContentNode (eltBlogPanel).setURL("/Play/Panels/Blogs.aspx?id=" + channelRules.ID);
		}
		else
		{
			eltBlogPanel.style.display = "none";
		}
	}

	// update the fans panel
	var eltFansPanel = document.getElementById('liFans');
	if (eltFansPanel)
	{
		GetContentNode (eltFansPanel).setURL("/Play/Panels/ShowFans.ashx?id=" + channel.ID);
	}
	
	// select the channel's category in the slider
	var channelCategory = channel.GetCategory ();
	if (channelCategory)
		SelectCategory (channelCategory.ID);

	// update the movie UI (hide various panels)
	SetClass (document.body, "fIsMovie", channel.IsMovie);
}

// remember if the companion ad is currently visible
var _fCompanionVisible = false;

function HideCompanionAd ()
{	
	if (!_fCompanionVisible)
		return;	// no change
	
	if (_adRight)
		_adRight.AllowRefresh (!_fFullscreen);
	if (_adFooter)
		_adFooter.AllowRefresh (!_fFullscreen);

	SetClassOption(document.body, "companion", null);
	_fCompanionVisible = false;
}


function LoadCompanionAd(strHTML)
{
	//HideCompanionAd();
	
	if (!strHTML)
		return HideCompanionAd ();

	var eltCompanionDiv = document.getElementById ('CompanionDiv');
	if (eltCompanionDiv)
		eltCompanionDiv.innerHTML = strHTML;

	
	if (!_fCompanionVisible)
	{
		var eltAd = document.getElementById ("adRight");
		if (eltAd)
			eltAd.innerHTML = "";
	}

	SetClassOption (document.body, "companion", "Show");
	if (_adRight)
		_adRight.AllowRefresh (false);
	if (_adFooter)
		_adFooter.AllowRefresh (false);
	_fCompanionVisible = true;
}


// navigate to a user's profile page
function ViewUser(idUser)
{
	if (idUser > 0)
		location.href = "/Members/" + idUser;
}

function LoadNowPlaying (idMedia) {
    // now playing content
    $jq.ajax({
        url: '/Play/NowPlaying.aspx?id='+idMedia + '&channelId=' + $jq('#channelId').attr('value'),
        cache: false,
        async: false,
        success: function(msg) {
            $jq('#nowPlaying').html(msg);
        }
    });
}

// set the 'now playing' item in the show accordions
function SelectMedia (idMedia)
{
    //LoadNowPlaying(idMedia);
 	var eltContent = document.getElementById("idFolderContent_main");
	var eltUL = eltContent.getElementsByTagName("UL")[1];
	if (eltUL) var crtpage = SelectMediaLI (eltUL, idMedia, true)
	else {
	    eltUL = eltContent.getElementsByTagName("UL")[0];
	    if (eltUL)
	        var crtpage = SelectMediaLI (eltUL, idMedia, true);
	}
	return crtpage;
	//if (typeof(eltUL.tagName) == "undefined") eltUL = eltUL.nextSibling;

}

function SelectMediaLI (eltUL, id, fScroll)
{
    if (eltUL.parentNode.tagName.toUpperCase() == "LI")
     for (var eltLIParent = eltUL.parentNode.parentNode.firstChild; eltLIParent; eltLIParent = eltLIParent.nextSibling) {            
        if (!eltLIParent.tagName || eltLIParent.tagName.toUpperCase () != "LI")
            continue;
            eltCurrentUL = eltLIParent.getElementsByTagName("UL")[0];
	        for (var eltLI = eltCurrentUL.firstChild; eltLI; eltLI = eltLI.nextSibling)
	        {
		        if (!eltLI.tagName || eltLI.tagName.toUpperCase () != "LI")
			        continue;
        		
		        var attrID = eltLI.getAttribute ("g:id");
		        if (!attrID)
			        continue;
        		
		        var fCurrent = parseInt (attrID) == id;
        		
		        SetClass (eltLI, "selectedItem", fCurrent);
        		
		        if (fScroll && fCurrent) {
		            var strLIid = eltLI.parentNode.parentNode.id;
		            var currentPage = strLIid.substring(strLIid.indexOf('item-')+5, strLIid.length);
		        }
		            
	        }
		        if (!fCurrent)
			        continue;    
    }
     else 
    	    for (var eltLI = eltUL.firstChild; eltLI; eltLI = eltLI.nextSibling)
	            {
		            if (!eltLI.tagName || eltLI.tagName.toUpperCase () != "LI")
			            continue;
            		
		            var attrID = eltLI.getAttribute ("g:id");
		            if (!attrID)
			            continue;
            		
		            var fCurrent = parseInt (attrID) == id;
            		
		            SetClass (eltLI, "selectedItem", fCurrent);
            		
		            if (fScroll && fCurrent)
		                var currentPage=0;
	            }
                    return currentPage;
}

// update comments
function LoadComments (idMedia) {
    var stringURL = window.location.href;
    if(document.getElementById("idComments") != undefined) {
	    var comments = new ddajaxtabs("commentstabs", "idComments");
	    if (stringURL.indexOf("/admin/ChannelLayoutEdit.aspx") > 0) {
	        comments.loadajaxpage("/browse/Comments.aspx?ct=2&id=" + idMedia + "&inAdmin=true");
	    } else {
	        comments.loadajaxpage("/browse/Comments.aspx?ct=2&id=" + idMedia);
	    }
        comments.onajaxpageload = function() {
             document.getElementById("numComments").innerHTML = "("+document.getElementById("numCommentsHidden").innerHTML+")";
        };
    }
}

function LoadCommentsAdmin(idMedia) {
    var comments = new ddajaxtabs("commentstabs", "idComments");
    comments.loadajaxpage("/browse/Comments.aspx?ct=2&id=" + idMedia + "&inAdmin=true");
    comments.onajaxpageload = function() {
        document.getElementById("numComments").innerHTML = "(" + document.getElementById("numCommentsHidden").innerHTML + ")";
    };
}

// when the show panels load, set the 'now playing' item
function onSearchPanelLoad ()
{
	if (_idMedia)
		SelectMedia (_idMedia);
}

// called by the player: determine whether or not the postroll can show
function queryWaitForPostroll ()
{
/*	var eltAccordionLinks = document.getElementById("accordionLinks");	
	if (_accordionLinks.FindOpenPanel())
	{
		// show a warning to the user that they need to close the panel in order to continue
		AddClass(eltAccordionLinks, "ppr");
		return true;
	}
*/	
	// pause if there's an video comment upload in progress
	if (_uploadInProgress)
		return true;
		
	// pause if the user's currently typing a comment
	if (_fTypingComment)
		return true;
		
	//check to see if panel is open
	return _delegateQueryWaitForPostroll.Invoke ();
}


//this function is called by Progress.js which is used by the
//Brettle Progress Bar for ther Video Comment Uploader
function SetUploadStatus( newUploadStatus )
{
	//alert("setuploadStatus called: " + newUploadStatus);
	uploadStatus = newUploadStatus;

	switch ( newUploadStatus )
	{
		case "cancelled":
			_uploadInProgress = false;
			_delegateUploadStatus.Invoke("Upload Cancelled", true, false);
			//these parameters are statusString, isWarning, showProgress, uploadInProgress

			alert( "You cancelled your upload!" );
			break;
		    
		case "rejected":
			_uploadInProgress = false;
			_delegateUploadStatus.Invoke("The file was rejected.", true, false);
			
			alert( "The file was rejected." );
			break;
		    
		case "failed":
			_uploadInProgress = false;
			_delegateUploadStatus.Invoke("Upload Failed", true, false);

			alert( "Your upload failed, please try again!" );
			break;
	}
}

function OpenEmailPanel()
{
	var eltLink = document.getElementById("btnEmail");
	openPlayPanel(eltLink, 'panelEmail');
}

function isIneligible(str)
{
	setCookie("AgeGatingDOB", str, 1, "/", ".crackle.com");
}

function checkIsIneligible()
{
	return getCookie('AgeGatingDOB');
}

function hideFlashPlayer()
{
    var eltFlashPlayer = document.getElementById('FlashPlayerContainer');
    if (eltFlashPlayer != null && typeof(eltFlashPlayer)!= "undefined")
        eltFlashPlayer.style.visibility='hidden';
}

function showFlashPlayer()
{
    var eltFlashPlayer = document.getElementById('FlashPlayerContainer');
    if (eltFlashPlayer != null && typeof(eltFlashPlayer)!= "undefined")
        eltFlashPlayer.style.visibility='visible';
}


function CloseAddPanel() {
    document.getElementById("addtoplaylistcontent").innerHTML= "";
    return false;
}
var ajaxtabsArray = new Array();

function LoadModule (moduleId, url) {
    $jq.ajax({
        url: url,
        cache: false,
        async: false,
        success: function(r, s) {
            $jq(moduleId).html(r);
        }
    });
}

function LoadFolderContent (fldId, fldContentId, defaultTab) {
   $jq('#ajaxtabs_'+fldId).tabs ({
                    cache: false,
                    ajaxOptions: {async: false},
                    selected: (defaultTab) ? defaultTab: 0,
                    show: function(event,ui) {

                        $jq('#ajaxtabs_'+fldId+' li').removeClass('ui-tabs-selected ui-state-active');
                        $jq(ui.tab).parent().addClass('ui-tabs-selected ui-state-active');
                    
                        var strURL = $jq.data(ui.tab, 'load.tabs');
                        if (strURL) {
                            var rgParts = strURL.split('?');
                            var qs = ParseQueryString (rgParts [1]);
                            var playlistId = qs["id"];
                            var mediaCount = parseInt($jq('#mediaCount'+playlistId).html());
                            if (fldContentId == "idFolderContent_main") {
                                if($jq('#playlistRSS'+playlistId)) {
                                    $jq('#titleRSS_'+fldId).html($jq('#playlistRSS'+playlistId).html());
                                }
                                hideDropDown('ajaxtabs_'+fldId);
                                displaySelectedItem(ui.tab, 'ajaxtabs_'+fldId);
                            }

                            if ((fldContentId == "idFolderContent_main")&&$jq('#currentMediaID')) 
                                var currentPage = SelectMedia(parseInt($jq('#currentMediaID').html()));
                            BuildCarouselObject(playlistId, mediaCount, currentPage, qs["mf"], qs["dci"], qs["m"], qs["nor"]);
                                                      
                        }
                    }
                })
            
}

function BuildCarouselObject(playlistID, itemCount, currentItem, mf, dci, m, nor) {
    var playlist = new YAHOO.extension.Carousel("playlist"+playlistID,
        {
            numVisible : (nor > 1)? 1: ((dci == "True")? ((m == "True")?5:3):4),
            animationSpeed: 0.25,
            scrollInc: (nor > 1)? 1: ((dci == "True")? ((m == "True")?5:3):4),
            navMargin: 20,
            prevElement: "prev-arrow"+playlistID,
            nextElement: "next-arrow"+playlistID,
            size: (nor > 1)? Math.ceil(itemCount/(nor*((dci == "True")? ((m == "True")?5:3):4))) : itemCount,
            "prevButtonStateHandler": handlePrevButtonState,
            "nextButtonStateHandler": handleNextButtonState
        }
   )
   if (currentItem) playlist.scrollTo(currentItem);
}

var handlePrevButtonState = function (type, args) {
    var enabling = args[0];
    var leftImage = args[1];
    if(enabling) {
        leftImage.src = "/images/buttons/left-enabled.gif";
    }
    else {
        leftImage.src = "/images/dot.gif";
    }
}

var handleNextButtonState = function (type, args) {
    var enabling = args[0];
    var rightImage = args[1];
    if(enabling) {
        rightImage.src = "/images/buttons/right-enabled.gif";
    }
    else {
        rightImage.src = "/images/dot.gif";
    }
}

function BuildToolTip(elt,itemId, channelId) {
    $jq(elt).bt({
        offsetParent: 'body',
        ajaxPath: '/browse/ToolTip.aspx?id='+itemId+((channelId != '0')?('&channelId='+channelId):''),
        positions: ['right','left'],
        padding: 0,
        width: '318px',
        spikeGirth: 40,
        spikeLength: 20,
        cornerRadius: 10,
        fill: 'rgb(255,255,255)',
        shadow: true,
        shadowBlur: 22,
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        hoverIntentOpts: {interval: 500, timeout: 0},
        cssStyles: {
            fontSize: '1em',
            fontFamily: 'Arial,Helvetica,san-siref'
            
        }
    });

}
function CurrentMedia (strURL) {
    var rgParts = strURL.split('#');
    var qs = ParseQueryString (rgParts [1]);
    if (qs["id"]) {
        return qs["id"];
    } else {
        return null;
    }    
}
function CurrentPlaylist (strURL) {
    var rgParts = strURL.split('#');
    var qs = ParseQueryString (rgParts [1]);
    if (qs["ml"]) {
        rgParts = qs["ml"].split('&');
        var ss=ParseQueryString (rgParts [1]);
        return ss["fpl"];
    } else {
        return null;
    }        
}