YAHOO.namespace('music.video');
YAHOO.music.video.Evp = ( function () {

    /* private constants */
    INTL_FOP_PARAMS = {
        "us" : { eid: "1301797" , skinCode : "4195329"   , langStr : "us" },
        "uk" : { eid: "1301655" , skinCode : "529531929" , langStr : "uk", bw: "300"},
        "ca" : { eid: "1307409" , skinCode : "642778130" , langStr : "ca" },
        "fr" : { eid: "1307665" , skinCode : "536871958" , langStr : "fr" },
        "de" : { eid: "1307668" , skinCode : "535823379" , langStr : "de"},
        "e1" : { eid: "1307666" , skinCode : "559940628" , langStr : "esa" },
        "au" : { eid: "1307669" , skinCode : "638583825" , langStr : "au" },
        "nz" : { eid: "5300947" , skinCode : "638583832" , langStr : "nz" },  
        "es" : { eid: "1307660" , skinCode : "534774805" , langStr : "es" }, 
        "it" : { eid: "1307667" , skinCode : "533726231" , langStr : "it" },
        "mx" : { eid: "8257040" , skinCode : "640680960" , langStr : "e1" }, 
        "br" : { eid: "8257049" , skinCode : "644875264" , langStr : "pt" }
    };
    var FOP_URL = 'http://d.yimg.com/m/up/music_e/embedflv/swf/fop.swf';
    /* for beta testing only
    if(Boolean(/\.stage/.exec(document.location))) {
    	YAHOO.Env = "beta";
    }
    if(YAHOO.Env=="beta") {
    	FOP_URL = 'http://cosmosweb01.bcst.sp1.yahoo.com/ver/268.0/embedflv/swf/fop.swf';
	}
	try {
		console.log('FOP_URL:'+FOP_URL);
	} catch(e) {}
	*/
    /* configure parameters */
    var fopContainerId = "";
    var vidLineupContainerId = "";
    var orgVideoId = "";
    var videoId = "";
    var totalVideos = "";
    var navType = "";
    var videosPerPage = "";
    var stationId = "";
    var startVideoId = "";
    var gatewayAdStationId = "";
    var wsCallUrlBase = "";
    var ratingWidgetPref;
    var intl =  "";
    var userID = "";
    var vidList = ""; // list of video ids to be passed into fop (optional)
    var navTextLine = "";
    var mode = "";
    var playerWidth = '576';
    var playerHeight = '356';
    var spaceID = ""; // constant spaceID can be used in minimal mode
    var prevSpaceID = "";
    var adsRefreshedSinceLastVideo = 0;
    var playlistType = "preprogrammed"; // CML logging, ondemand is for watching your own playlist, everything else is preprogrammed
    var attributionImageElm = document.getElementById("embeddedVideoAttributionImage_iframe");
    var hideShareButton = false;


    /* private variables */
    var videoLineUp = [];
    var curVideoIndex = -1;
    var curSpaceId = "";
    var okToReplaceAds = true;
    var curPageIndex = 1;
    var autoScrollMode = true;
    var startVideoIndex;
    var so; // swf object reference
    var eIDValue = "1301797"; // default value for US locale
    var hackYloc = "";  // HACK - stores Y location of 'Add To Playlist' button right after the page load
    var lrecTimer = null;
    var pager = {}; // object to store external paging data handlers
    var videoMetaDataLoadedEvt = new YAHOO.util.CustomEvent('onVideoMetaData');
    var isMusicReferer = 0;
    var adClipInfo = []; // stores spaceid-clipid pairs
    
    /* private functions */

    function loadConfig(config) {
        if ("fopContainerId" in config) {
            fopContainerId = config.fopContainerId;
        }
        if ("vidLineupContainerId" in config) {
            vidLineupContainerId = config.vidLineupContainerId;
        }
        if ("orgVideoId" in config) {
            orgVideoId = config.orgVideoId;
        }
        if ("videoId" in config) {
            videoId = config.videoId;
        }
        if ("navType" in config) {
            navType = config.navType;
        }
        if ("videosPerPage" in config) {
            videosPerPage = config.videosPerPage;
        }
        if ("stationId" in config) {
            stationId = config.stationId;
        }
        if ("startVideoId" in config) {
            startVideoId = config.startVideoId;
        }
        if ("gatewayAdStationId" in config) {
            gatewayAdStationId = config.gatewayAdStationId;
        }
        if ("intl" in config) {
            intl = config.intl;
        }
        if ("wsCallUrlBase" in config) {
            wsCallUrlBase  = config.wsCallUrlBase;
        }
        if ("ratingWidgetPref" in config) {
            ratingWidgetPref  = config.ratingWidgetPref;
        }
        if ("userID" in config) {
            userID  = config.userID;
        }
        if ("vidList" in config) {
            vidList  = config.vidList;
        }
        if ("totalVideos" in config) {
            totalVideos  = config.totalVideos;
        }
        if ("navTextLine" in config) {
            navTextLine  = config.navTextLine;
        }
        if ("mode" in config) {
            mode = config.mode;
        }
        if ("playerHeight" in config) {
            playerHeight = config.playerHeight;
        }
        if ("playerWidth" in config) {
            playerWidth = config.playerWidth;
        }
        if ("spaceID" in config) {
            spaceID  = config.spaceID;
        }
        if ("playlistType" in config) {
            playlistType  = config.playlistType;
        }
        if ("isMusicReferer" in config) {
            isMusicReferer = config.isMusicReferer;
        }
        if ("hideShareButton" in config) {
            hideShareButton = config.hideShareButton;
        }
    }
    
    function getExternalEmbedCode(vid) {
        var shareEnable = 1;
        if (intl != "us") {
            shareEnable = 0;
        }
        var eIDValue = INTL_FOP_PARAMS[intl].eid;
        var langValue = INTL_FOP_PARAMS[intl].langStr; 
        var skinCode = INTL_FOP_PARAMS[intl].skinCode; 

        //sv=0&amp; used for beta testing
        return  '<object width="400" height="255" id="uvp_fop" allowFullScreen="true">'+
                '<param name="movie" value="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf"/>'+
                '<param name="flashVars" value="id=v'+vid+'&amp;eID='+eIDValue+'&amp;lang='+langValue+'&amp;enableFullScreen=0&amp;shareEnable='+shareEnable+'"/>'+
                '<param name="wmode" value="transparent"/>'+
                '<embed height="255" width="400" id="uvp_fop" allowFullScreen="true"'+ 
                ' src="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf" type="application/x-shockwave-flash"'+
                ' flashvars="id=v'+vid+'&amp;eID='+eIDValue+'&amp;lang='+langValue+'&amp;ympsc='+skinCode+'&amp;enableFullScreen=1&amp;shareEnable='+shareEnable+'" />'+
                '</object>';
    }

    function loadFOP() {
        // get intl fop parameters
        var eIDValue = INTL_FOP_PARAMS[intl].eid;
        var skinCode = INTL_FOP_PARAMS[intl].skinCode;
        var language = INTL_FOP_PARAMS[intl].langStr;

        var checkForStartIndex = false;
        if (startVideoId !== '') {
           checkForStartIndex = true;
        }
        
        var VidArray = videoLineUp;
        if (vidList !== "") {
            // list of video Ids is passed in separated by 'comma'
            VidArray = vidList.split(','); 
        }

        // create the video lineup string to be passed into fop
        var initPlayerLineup = "";
        var lineupLen = VidArray.length;
        for (i=0; i < lineupLen; i++) {
            initPlayerLineup += 'v'+VidArray[i];
            if (checkForStartIndex) {
                if (VidArray[i] == startVideoId) {
                    startVideoIndex = i;
                }
            }
            if (i != lineupLen - 1) {
                initPlayerLineup += ',';
            }
        }
     
        so = new SWFObject(FOP_URL,'fopObj', playerWidth, playerHeight, '8', '#2C2C2C');
        so.addVariable('id',initPlayerLineup);
        so.addVariable('eID',eIDValue);
        so.addVariable('prepanelEnable', '0');
        so.addVariable('infopanelEnable', '1');
        if (startVideoId === '') {
            so.addVariable('autoStart', '1');
        } else {
            so.addVariable('autoStart', '0');
        }
        so.addVariable('eh', 'YAHOO.music.video.Evp.fopCallBackHandler');
        if (intl == 'us') {
            if (hideShareButton !== true) { 
                so.addVariable('shareEnable','1');
            }
        }
        so.addVariable('lang', language);
        so.addVariable('ympsc', skinCode);
        so.addVariable('enableFullScreen','1');
        if (gatewayAdStationId !== '') {
            so.addVariable('chid',gatewayAdStationId);
        } else if ( stationId ) {
            so.addVariable('chid','category:'+stationId);
        }
        
        if ("bw" in INTL_FOP_PARAMS[intl]) {
            so.addVariable("bw",INTL_FOP_PARAMS[intl].bw);
        }

        if ( ! isMusicReferer ) {
            so.addVariable("fs", "1");
        }
        
        // For scripting access
        so.addParam("allowScriptAccess", "always");
        so.addParam("wmode","transparent");
        so.addParam("allowFullScreen","true");
        so.addVariable("playlistType",playlistType);
        so.write(fopContainerId);
    }

    function buildVideosLineupArray()
	{
        var videoElems = YAHOO.util.Dom.getElementsByClassName('ymusic-img-link', 'a', vidLineupContainerId);

        for (var i=0; i < videoElems.length; i++)
		{
            videoLineUp.push(videoElems[i].getAttribute('mid')); 
        }
        if(videoElems.length < 1)
		{
            videoLineUp.push(videoId);
        }
    }
    
    function handleNewVideoLoading(pItem) {
        var playerVideoIndex = document.fopObj.getCurrentIndex();
        if (curVideoIndex == 0 || curVideoIndex != playerVideoIndex) {
            var indexFromVideoLineup = playerVideoIndex - ((curPageIndex -1) * videosPerPage);
            if (indexFromVideoLineup >= 0  && indexFromVideoLineup < videosPerPage) {
                // item playing is part of the video lineup section
				try {
				// console.log('calling playingVideoFromLineup from handlenewvideoloading');
				// console.log('curVideoIndex: '+curVideoIndex);
				// console.log('playerVideoIndex: '+playerVideoIndex);
				} catch(e) {}
                playingVideoFromLineup(playerVideoIndex);
            } else {
                selectVideoLineupElement(-1);
                curVideoIndex = -1;
                var curVid = pItem.clipid.replace('v','');
                fetchVideoMetadata(curVid);
                if (autoScrollMode) {
                    autoScrollVideoLineup(indexFromVideoLineup);
                }
            }
        }
        if(mode.toString() !== 'minimal') {
        	//removed all ad management from here, LREC and HB switch on metadata refresh
        } else {
            // handle minimal mode
            refreshLRECForMinimalMode( curSpaceId );
        }
    }
    
    function refreshLRECForMinimalMode ( spaceId ) {
        kickDarla ( "LRECRotation", spaceId );
        document.getElementById("YMusicRegion_TN1_R2C2_R1_iframe").style.display = "block";
        var iframeElm;
        if ( ( iframeElm = document.getElementById("YMusicRegion_TN1_R2C2_R1_iframe") ) ) {
            iframeElm.style.display = "block";
            iframeElm.parentNode.style.marginLeft='0px';
            window.setTimeout(function() {
                var docElm;
                if (YAHOO.env.ua.ie) {
                    // why does this not work - docElm = iframeElm.contentWindow.document;
                    docElm = window.frames["YMusicRegion_TN1_R2C2_R1_iframe"].document;
                } else {
                    docElm = iframeElm.contentDocument;
                }
                if ( docElm ) {
                    docElm.body.style.background="transparent";
                    docElm.body.style.color="#ffffff";
                }
            }, 1000);
        }
    }
    
    
    function fopEventsHandler ( pType, pItem ) {
        var playerVideoIndex;
        switch (pType) {
        case "init": // thrown when the player has been initialized and the flash external API is ready to be accessed
            selectVideoLineupElement(0);
            curVideoIndex = 0;
            if (startVideoId !== '') {
                document.fopObj.playIndex(startVideoIndex);
                if (autoScrollMode) {
                    autoScrollVideoLineup(startVideoIndex);
                }
                // playingVideoFromLineup(startVideoIndex);
		        selectVideoLineupElement(startVideoIndex);
				curVideoIndex = startVideoIndex; // Saves it
            }
        	try{
        		//console.log("init, setting okToReplace true");
        	} catch(e) {}
            curSpaceId = spaceID;
	        try {
	        	//console.log("initialization of player event caught and called rotateLREC");
	        } catch(e) {}
	        attributionImageElm = document.getElementById("embeddedVideoAttributionImage_iframe");
	        if ( attributionImageElm ) {
	            attributionImageElm.src = "/php/blankframe.html";
	        }
            break;
        case "itemBegin": // thrown when a video starts playing for the first time
        	try{
        		//console.log("itemBegin:"+pItem.type);
        	} catch(e) {}
        	prevSpaceID = curSpaceId;
            if(pItem.spaceId) {
            	curSpaceId = pItem.spaceId;
        	}
            try {
                //console.log("before logic: adsRefreshedSinceLastVideo: "+adsRefreshedSinceLastVideo);
                //console.log("prevSpaceID: "+prevSpaceID +"curSpaceId: "+curSpaceId);
            } catch(e) {}
            if(pItem.type === "S_AD") {
                if(prevSpaceID != curSpaceId) {
                    fetchRotatingAds();
                    adsRefreshedSinceLastVideo = 1;
                }
            } else if(pItem.type === "S_STREAM") {
                if(adsRefreshedSinceLastVideo==1 && prevSpaceID == curSpaceId) {
                    adsRefreshedSinceLastVideo = 0;
                    //console.log('not rotating for this stream');
                } else {
                    //console.log('YES, rotating for this stream');
                    adsRefreshedSinceLastVideo = 0;
                    fetchRotatingAds();
                }
            }
            try {
                //console.log("after logic: adsRefreshedSinceLastVideo: "+adsRefreshedSinceLastVideo);
            } catch(e) {}
        	
				try {
					// console.log("what is it "+document.fopObj.getCurrentIndex());
				} catch(e) {}
            if(pItem.type === "S_STREAM") {
				if(document.fopObj.getCurrentIndex()==0) {
					rotateLREC();
	            }
	        	try{
	        		//console.log("itemBegin, stream, setting okToReplace true");
	        	} catch(e) {}
            }
        	handleNewVideoLoading( pItem );
            break;
        case "itemEnd" : // thrown when a video has played for its total duration
        	try{
        		//console.log("itemEnd:"+pItem.type);
        	} catch(e) {}
            break;
        case "done" : //thrown when all videos have played
            playerVideoIndex = document.fopObj.getCurrentIndex();
            if (playerVideoIndex >= (totalVideos-1)) {
                // reached the end of the playlist
                document.fopObj.playIndex(0);
            }
            break;
        case "seeking" : //thrown when the vidSeek() request has been initiated
        case "onSeekComplete" : //thrown when the vidSeek() request has completed and playback has started
        case "streamPlay" : // thrown anytime a video begins to play
        case "streamPause" : // thrown when vidPause() is requested and completed
        case "streamStop" : // thrown when playback has stopped for whatever reason (not the same as itemEnd)
            break;
        case "streamError" : // thrown when an error occurs with the stream
    	    //temporary fix to avoid stall, player will add own recovery logic, then this should be removed
    	    if(pItem.type === "S_STREAM") {
    			document.fopObj.playIndex(document.fopObj.getCurrentIndex());
    	    }
    	    break;
        case "userClick" : // thrown when a user click on clicks on playback compoents w/i the post panel
            var nextClick = false;
            var prevClick = false;
            if (pItem.clickPosition.indexOf('Next') > 0) {
                nextClick = true;
            } 
            if (pItem.clickPosition.indexOf('Prev') > 0) {
                prevClick = true;
            } 
            if (nextClick || prevClick) {
                playerVideoIndex = document.fopObj.getCurrentIndex();
                var skipToIndex;
                if (nextClick) {
                    skipToIndex = (playerVideoIndex + 1) % totalVideos; 
                    if (skipToIndex === 0) {
                        document.fopObj.playIndex(0);
                        indexFromVideoLineup = (curPageIndex -1) * videosPerPage;
                    } else {
                        indexFromVideoLineup = skipToIndex - ((curPageIndex -1) * videosPerPage);
                    }
                } else if (prevClick) {
                    skipToIndex =  playerVideoIndex - 1;
                    if (skipToIndex >= 0) {
                        indexFromVideoLineup = prevIndex - ((skipToIndex -1) * videosPerPage);
                    }
                }
                if (autoScrollMode && indexFromVideoLineup) {
                    autoScrollVideoLineup(indexFromVideoLineup);
                }
                if (skipToIndex >= 0) {
                    playingVideoFromLineup(skipToIndex);
                }

            }
            break;
        default :
            break;
        }
    }


    function selectVideoLineupElement (newSelectIndex)
	{
        var vidLineupContainer = document.getElementById(vidLineupContainerId);
        if (vidLineupContainer)
		{
            var liElms =  vidLineupContainer.getElementsByTagName("li"); 
            if (newSelectIndex >= 0)
			{
                if(curVideoIndex >= 0)
				{
                    YAHOO.util.Dom.removeClass(liElms[curVideoIndex],'active');
                }
                YAHOO.util.Dom.addClass(liElms[newSelectIndex],'active');
            }
			else
			{
                // de-select existing item
                if(curVideoIndex >= 0)
				{
                    YAHOO.util.Dom.removeClass(liElms[curVideoIndex],'active');
                }
            }
        }
    }
    
    
    /* mvoes the location of 'AddToPlaylist' popup dialog for single video page */
    function shiftPopupLocation (offset) {
        var addToPlaylistElm = YAHOO.util.Dom.getElementsByClassName('ymusic_popup_container','div')[0];
        if(addToPlaylistElm && document.getElementById('mpPulldown_menu') !== null) {
    		var pulldownMenuElm = document.getElementById('mpPulldown_menu');
    		var containerYPos = Number(addToPlaylistElm.style.top.replace('px',''));
    		var pulldownYPos = Number(pulldownMenuElm.style.top.replace('px',''));

    		// change the y location of the container as well as the pulldown menu inside it
    		addToPlaylistElm.style.top = (containerYPos + offset) +'px';
    		pulldownMenuElm.style.top = ( pulldownYPos + offset) + 'px';
    	}
    }
    
    function fetchVideoMetadata(curVideoId)
	{
		try {
			// console.log('fetching video metadata');
		} catch(e){}
    	var intlPrefix = "";
    	if(intl != "us")
		{
    		intlPrefix = intl + ".";
        }
        //determine environment for artist page link creation
        var yahooServer = "prod";
        if(Boolean(/new\.music\.stage/.exec(document.location))) {
	        var yahooServer = "stage";
        } else if(Boolean(/new\.music\.test/.exec(document.location))) {
	        var yahooServer = "test";
        }
        
		// update videoId which is used by addToPlaylistModule
        videoId = curVideoId; 
        
		YAHOO.music.video.addToMyPlaylists.updateCurrentVideoId(videoId);
        
		// create URL for ajax call --
        var url = '/services/musicvideos/ymusic_proxy.php';
        // create wsapi url to pass into the proxy
        var wsUrl;

        if (userID === "")
		{
            wsUrl = wsCallUrlBase + videoId + ";response=artists,categories,releases;output=json";
        }
		else
		{
            wsUrl = wsCallUrlBase + videoId + ";response=artists,categories,releases;output=json;ratings="+userID;
        }
        
        var postData = 'url=' + encodeURIComponent(wsUrl);

        var callBack =
		{
            success : function(retObj) {
                try {
                    var artistName, artistId, artistLink;
                    var videoMetaDataObj = eval("(" + retObj.responseText + ")");
                       
                    var ratingElm;   
                    if (mode == "minimal") {
                        // insert new rating value
                        ratingElm = document.getElementById('YMusic_SingleVideoRatingWidget');
        		        if (ratingWidgetPref == 'advanced') {
                		    if (ratingElm) {
                                ratingElm.setAttribute('rating',videoMetaDataObj.Videos.Video.rating);
                                ratingElm.setAttribute("mid",videoMetaDataObj.Videos.Video.id);
                            }
                            attachRatingEvent();

                		} else {
                		    if (ratingElm) {
                                ratingElm.setAttribute("mid",videoMetaDataObj.Videos.Video.id);
                                changeRating("YMusic_SingleVideoRatingWidget", videoMetaDataObj.Videos.Video.rating);   
                            }

                		}
        		        // insert the external embed codes
                        document.getElementById('YMusic_singleEmbedTextInput').value = getExternalEmbedCode(videoId);
        		        return;
                    } 
                    
                    // store Yposition of the pop-up container (its abosolutely positioned)
                    var orgY = YAHOO.util.Dom.getY('btnAddToPlaylist'); 
                    
                    // insert video Title
                    var videoTitle = videoMetaDataObj.Videos.Video.title;
                    document.getElementById('YMusic_singleVideoTitle').innerHTML = videoTitle;
                    
                    // insert the artist info line
                    if(videoMetaDataObj.Videos.Video.Artist[0]) {
                    	artistName = videoMetaDataObj.Videos.Video.Artist[0].name;
                    	artistId = videoMetaDataObj.Videos.Video.Artist[0].id;
	                    artistLink = "/"+YAHOO.music.util.Normalizer.normalizeForURL(artistName)+"/";
		                if(intlPrefix!="") {
		                	if(yahooServer=="prod") {
			                	artistLink = "http://"+intlPrefix+"music.yahoo.com/ar-"+videoMetaDataObj.Videos.Video.Artist[0].id+"---"+artistName.replace(/\s/g,'-');
			                } else {
			                	artistLink = "http://music."+yahooServer+"."+intlPrefix+"music.yahoo.com/ar-"+videoMetaDataObj.Videos.Video.Artist[0].id+"---"+artistName.replace(/\s/g,'-');
			                }
		                }
	                } else {
                   		artistName = videoMetaDataObj.Videos.Video.Artist.name;
                   		artistId = videoMetaDataObj.Videos.Video.Artist.id;
	                    artistLink = "/"+YAHOO.music.util.Normalizer.normalizeForURL(artistName)+"/";
		                if(intlPrefix!="") {
		                	if(yahooServer=="prod") {
			                	artistLink = "http://"+intlPrefix+"music.yahoo.com/ar-"+videoMetaDataObj.Videos.Video.Artist.id+"---"+artistName.replace(/\s/g,'-');
			                } else {
			                	artistLink = "http://music."+yahooServer+"."+intlPrefix+"music.yahoo.com/ar-"+videoMetaDataObj.Videos.Video.Artist.id+"---"+artistName.replace(/\s/g,'-');
			                }
		                }
	                }

                    var artistNode =  document.getElementById('YMusic_singleVideoArtistName');
                    artistNode.innerHTML = artistName;
                    artistNode.href = artistLink;
                    artistNode.title = artistLink;
                    
                    // insert album info
                    var albumName = '';
                    var albumLink = '';
                    if ("Album" in videoMetaDataObj.Videos.Video &&
                        typeof videoMetaDataObj.Videos.Video.Album == 'object') {
                        var albumItem = null;
                        if ("length" in videoMetaDataObj.Videos.Video.Album) { 
                            var albumArrayItem = videoMetaDataObj.Videos.Video.Album;
                            for ( var i=0; i < albumArrayItem.length; i++) {
                                if ( typeof albumArrayItem[i] == 'object' && "Release" in albumArrayItem[i]) {
                                    albumItem = albumArrayItem[i];
                                    break;
                                }
                            }
                        } else {
                            // single album item
                            albumItem = videoMetaDataObj.Videos.Video.Album;
                        }
                        if (albumItem) {
                            albumName = albumItem.Release.title;
                            albumLink =  "/"+YAHOO.music.util.Normalizer.normalizeForURL(artistName)+"/albums/"+YAHOO.music.util.Normalizer.normalizeForURL(albumName)+"--"+albumItem.Release.id;
                        }
                    }
                    if (document.getElementById('YMusic_videoAlbumInfo')) {
                        if (albumName) {
                            document.getElementById('YMusic_videoAlbumInfo').style.display = "block";
                            var albumNode =  document.getElementById('YMusic_singleVideoAlbumName');
                            albumNode.innerHTML = albumName;
                            albumNode.title = albumLink;
                            albumNode.href = albumLink;
                        } else {
                            // hide album info line
                            document.getElementById('YMusic_videoAlbumInfo').style.display = "none";
                        }
                    }
                    

                    // enable/disable go-to single video page link
                    var videoPageLink = "/videos/"+ encodeURIComponent(artistName.replace(/\s/g,'')) + "/" + encodeURIComponent(videoTitle.replace(/\s/g,'-').replace('#','')) + "--"+ videoId;
                    var videoPageLinkElm = document.getElementById('YMusic_singleVideoPageLink');
                    videoPageLinkElm.href = videoPageLink;
                    if (videoId !== orgVideoId) {
                        videoPageLinkElm.parentNode.style.display = "block";
                    } else {
                        videoPageLinkElm.parentNode.style.display = "none";
                    }
                    
                    // insert the external embed codes
                    document.getElementById('YMusic_singleEmbedTextInput').value = getExternalEmbedCode(videoId);

                    // insert label and copyright year
                    if ("label" in videoMetaDataObj.Videos.Video && videoMetaDataObj.Videos.Video.label.length > 1) {
                        document.getElementById('YMusic_singleVideoLabelItem').style.display ='block';
                        document.getElementById('YMusic_singleVideoLabel').innerHTML = ' '+videoMetaDataObj.Videos.Video.label;
                    } else {
                        document.getElementById('YMusic_singleVideoLabelItem').style.display ='none';
                    }
                    if ("copyrightYear" in videoMetaDataObj.Videos.Video && videoMetaDataObj.Videos.Video.copyrightYear.length > 1) {
                   	    document.getElementById('YMusic_singleVideoYear').innerHTML = videoMetaDataObj.Videos.Video.copyrightYear;
                    } else {
                   	    document.getElementById('YMusic_singleVideoYear').innerHTML = "";
                    }

                    // insert the categories
                    var categories = [];
                    if("Category" in videoMetaDataObj.Videos.Video) {
    					var categoryObj = videoMetaDataObj.Videos.Video.Category;
                        if ("length" in videoMetaDataObj.Videos.Video.Category) {
                            for (i=0; i < categoryObj.length; i++ ) {
                                categories.push('<a class="ymusic_category" href="/videos/'+categoryObj[i].id+'">'+categoryObj[i].name+'</a>');
                            }
                        } else {
                            categories.push('<a class="ymusic_category" href="/videos/'+categoryObj.id+'">'+categoryObj.name+'</a>');
                        }
    				}
                    if (categories.length > 0) {
                        document.getElementById('YMusic_singleVideoCategoriesItem').style.display = "inline";
                        document.getElementById('YMusic_singleVideoCategories').innerHTML = categories.join(", ");
                    } else {
                        document.getElementById('YMusic_singleVideoCategoriesItem').style.display = "none";
                    }

                    // insert new rating value
                    ratingElm = document.getElementById('YMusic_SingleVideoRatingWidget');
    		        if (ratingWidgetPref == 'advanced') {
    		            if (ratingElm) {
    		                ratingElm.setAttribute('rating',videoMetaDataObj.Videos.Video.rating);
                            ratingElm.setAttribute("mid",videoMetaDataObj.Videos.Video.id);
		                }
		                attachRatingEvent();
  
    		        } else {
    		            if (ratingElm) {
                            ratingElm.setAttribute("mid",videoMetaDataObj.Videos.Video.id);
                            changeRating("YMusic_SingleVideoRatingWidget", videoMetaDataObj.Videos.Video.rating);   
                        }
    		            
    		        }
    		        
    		        // fire event
    		        videoMetaDataLoadedEvt.fire({ vid:videoMetaDataObj.Videos.Video.id, aid: artistId, aname: artistName });
    		        
    		        
                    // re-position the pop-up container if necessary    
                    var newY = YAHOO.util.Dom.getY('btnAddToPlaylist');
                    if (newY != orgY) {
                        shiftPopupLocation(newY-orgY);
                    }

                } catch (ex) {
                    //alert("Error fetching video metadata - "+ex.message);
                }
            },
            failure : function(retObj)
			{
                //alert("Error fetching video metadata");
            }
        };
        YAHOO.util.Connect.asyncRequest('POST',url,callBack,postData);
        if (document.getElementById("YMusicRegion_TN1_R2C2_R1_iframe")) {
            document.getElementById("YMusicRegion_TN1_R2C2_R1_iframe").style.display = "block";
        }
    }
    
	function fetchRotatingAds() {
        //zero out attribution image because if nothing is returned in new call it will stick around
        attributionImageElm = document.getElementById("embeddedVideoAttributionImage_iframe");
	    if ( attributionImageElm ) {
	        attributionImageElm.style.display = "none";
            attributionImageElm.src = "/php/blankframe.html";
	    }
        if ( intl === "de" ) {
            kickDarla ("videoRotationDE", curSpaceId);
        } else {
            kickDarla ("videoRotation", curSpaceId);
        }
        attributionImageElm = document.getElementById("embeddedVideoAttributionImage_iframe");
        if ( attributionImageElm ) {
            attributionImageElm.style.display = "block";
        }
    	try{
    		//console.log("replaced ads, setting okToReplace false");
    	} catch(e) {}
	}
	
    function thumbnailFromVideoLineupClicked (e, obj)
	{
        YAHOO.util.Event.stopEvent(e);

        var mediaID = Number(this.getAttribute('mid'));
        var aNode;                                      

        if (mediaID === '')
		{
            if (document.all)
			{
                // for IE
                aNode = this.parentNode.parentNode.childNodes[0].childNodes[0];
            } 
			else
			{
                aNode = this.parentNode.parentNode.childNodes[1].childNodes[1];
            }
			mediaID = Number(aNode.getAttribute('mid'));
		}
		else
		{
            aNode = this;
        }

        var findIndex = -1 ;
        
        // find index of the video playing from the DOM, in order to take care of duplicate video ids (especially in case of playlist page)
        var allLi = document.getElementById(vidLineupContainerId).getElementsByTagName('li');
        var liElm = aNode.parentNode.parentNode;
		
        for (var i = 0, ilen = allLi.length; i < ilen; i++)
		{
            if (allLi[i] == liElm)
			{
                findIndex = i;
                break;
            }
        }

        if (findIndex >= 0)
		{
            document.fopObj.playIndex(findIndex);
            playingVideoFromLineup(findIndex);
        }
    }
    
    function playingVideoFromLineup (index)
	{
		try {
			//console.log('playing video from lineup');
		} catch(e){}
        selectVideoLineupElement(index);
        fetchVideoMetadata(videoLineUp[index]);
		curVideoIndex = index; // Saves it
    }

    // incorporate this into global later
    function changeRating (elemId, rVal) {
        if (userID) {
            var rCss = (rVal == -1) ? "" :  " m" + Math.round(rVal/10);
            var elem = document.getElementById(elemId);
            $.kids(elem)[1].className = "myRating" + rCss;
        }
    }
    
    function autoScrollVideoLineup (indexFromVideoLineup) 
    {
        if (indexFromVideoLineup < 0 ) {
            var goPrevPages = Math.abs(indexFromVideoLineup) / videosPerPage;
            for (var i=0; i < goPrevPages; i++) {
                // autoscroll to previous page
                fetchPrevData();
            }
        } else if (indexFromVideoLineup >= videosPerPage) {
            if (mode !== 'minimal') {
                postLoadImgGroup.fetch();
            }
            var goNextPages = Math.floor(indexFromVideoLineup / videosPerPage);
            for (i=0; i < goNextPages; i++) {
                // autoscroll to next page
                fetchNextData();
            }
        }
    }
    
    function updateScrollButtons ()
	{
        var scrollUpContainerElm = document.getElementById('scrollUpContainer');
        var scrollDownContainerElm = document.getElementById('scrollDownContainer');

		var prevPrefix = "btn-prev3";
		var nextPrefix = "btn-next3";
		if (YAHOO.util.Dom.hasClass(scrollUpContainerElm, 'ymusic-link-prev') || YAHOO.util.Dom.hasClass(scrollUpContainerElm, 'ymusic-link-prev-disabled') || YAHOO.util.Dom.hasClass(scrollUpContainerElm, 'ymusic-link-next') || YAHOO.util.Dom.hasClass(scrollUpContainerElm, 'ymusic-link-next-disabled'))
		{
			prevPrefix = "link-prev"; 
			nextPrefix = "link-next";
		}
        
        if (!scrollUpContainerElm || !scrollDownContainerElm)
		{
            return;
        }

		// Disable both buttons as default state
		YAHOO.util.Dom.addClass(scrollUpContainerElm, 'ymusic-' + prevPrefix + '-disabled');
		YAHOO.util.Dom.removeClass(scrollUpContainerElm, 'ymusic-' + prevPrefix);
        YAHOO.util.Dom.addClass(scrollDownContainerElm, 'ymusic-' + nextPrefix + '-disabled');
        YAHOO.util.Dom.removeClass(scrollDownContainerElm, 'ymusic-' + nextPrefix);

        if (totalVideos > videosPerPage)
		{
            // multi page view 
            if (curPageIndex == 1)
			{
                // enable next button
                YAHOO.util.Dom.addClass(scrollDownContainerElm, 'ymusic-' + nextPrefix);
                YAHOO.util.Dom.removeClass(scrollDownContainerElm, 'ymusic-' + nextPrefix + '-disabled');
            }
			else if (curPageIndex == Math.ceil((totalVideos / videosPerPage)))
			{
                // enable prev button 
                YAHOO.util.Dom.addClass(scrollUpContainerElm, 'ymusic-' + prevPrefix);
                YAHOO.util.Dom.removeClass(scrollUpContainerElm, 'ymusic-' + prevPrefix + '-disabled');
            }
			else
			{
				// Enable both buttons
				YAHOO.util.Dom.addClass(scrollUpContainerElm, 'ymusic-' + prevPrefix);
				YAHOO.util.Dom.removeClass(scrollUpContainerElm, 'ymusic-' + prevPrefix + '-disabled');
		        YAHOO.util.Dom.addClass(scrollDownContainerElm, 'ymusic-' + nextPrefix);
		        YAHOO.util.Dom.removeClass(scrollDownContainerElm, 'ymusic-' + nextPrefix + '-disabled');
            }
        }
    }
    
    function nextBtnClicked (e)
	{
		if (e != null)
		{
			YAHOO.util.Event.stopEvent(e);
		}
        if (YAHOO.util.Dom.hasClass(this, 'ymusic-btn-next3-disabled') || YAHOO.util.Dom.hasClass(this, 'ymusic-link-next-disabled'))
		{
            return;
        }

        YAHOO.util.Dom.setStyle(document.getElementById(vidLineupContainerId).getElementsByTagName('ul')[0], 'visibility', 'hidden');
        YAHOO.util.Dom.setStyle('loadingMsgContainer', 'display', 'block');

        // once user clicks the scroll buttons, auto scroll mode is OFF
        if (autoScrollMode)
		{
            autoScrollMode = false;
        }
        window.setTimeout("YAHOO.music.video.Evp.fetchNextData()", 250);
    }

    function prevBtnClicked (e)
	{
		if (e != null)
		{
			YAHOO.util.Event.stopEvent(e);
		}
        if (YAHOO.util.Dom.hasClass(this, 'ymusic-btn-prev3-disabled') || YAHOO.util.Dom.hasClass(this, 'ymusic-link-prev-disabled'))
		{
            return;
        }

        YAHOO.util.Dom.setStyle(document.getElementById(vidLineupContainerId).getElementsByTagName('ul')[0], 'visibility', 'hidden');
        YAHOO.util.Dom.setStyle('loadingMsgContainer', 'display', 'block');

        // once user clicks the scroll buttons, auto scroll mode is OFF
        if (autoScrollMode)
		{
            autoScrollMode = false;
        }
        window.setTimeout("YAHOO.music.video.Evp.fetchPrevData()", 250);
    }
    
    function fetchNextData()
	{
        var playerVideoIndex;
        
        // check if any external paging handlers are registered to be called
        if (pager.next) {
            pager.next.apply(pager.scopeObj);
            curPageIndex += 1;
            playerVideoIndex = document.fopObj.getCurrentIndex();
            selectVideoLineupElement(playerVideoIndex);
            curVideoIndex = playerVideoIndex;
            return;
        }
        
        var oldIndex = (curPageIndex - 1)* videosPerPage;
        var newIndex = (curPageIndex)* videosPerPage;
        var videoLineupNodes = document.getElementById(vidLineupContainerId).getElementsByTagName('li');

        var i = oldIndex;
        var j = newIndex;
        var pageNumVideos = videosPerPage;
        if (((curPageIndex + 1) * videosPerPage) > totalVideos) {
            // last incomplete page (containing less than videosPerPage videos)
            pageNumVideos = totalVideos - (curPageIndex  * videosPerPage);
        }
        for(var k=0; k < videosPerPage; k++)
		{
            videoLineupNodes[i].style.display = "none";
            if (k < pageNumVideos) {
                videoLineupNodes[j].style.display = "block";
            }
            i++; j++; 
        }
        
		YAHOO.util.Dom.setStyle(document.getElementById(vidLineupContainerId).getElementsByTagName('ul')[0], 'visibility', 'visible');
        YAHOO.util.Dom.setStyle('loadingMsgContainer', 'display', 'none');

        curPageIndex += 1;
        playerVideoIndex = document.fopObj.getCurrentIndex();
        selectVideoLineupElement(playerVideoIndex);
        curVideoIndex = playerVideoIndex;
        updateScrollButtons();
        if (navTextLine) {
            updateNavText();
        }

    }

    function fetchPrevData () {
        var playerVideoIndex;
        
        // check if any external paging handlers are registered to be called
        if (pager.prev) {
            pager.prev.apply(pager.scopeObj);
            curPageIndex -= 1;
            playerVideoIndex = document.fopObj.getCurrentIndex();
            selectVideoLineupElement(playerVideoIndex);
            curVideoIndex = playerVideoIndex;
            return;
        }
        
        var oldIndex = (curPageIndex-1)* videosPerPage;
        var newIndex = (curPageIndex-2)* videosPerPage;
        var videoLineupNodes = document.getElementById(vidLineupContainerId).getElementsByTagName('li');

        var i = oldIndex;
        var j = newIndex;
        var curPageNumVideos = videosPerPage;
        if ((curPageIndex * videosPerPage) > totalVideos) {
            // current page is the last incomplete page
            curPageNumVideos = totalVideos - ((curPageIndex -1) * videosPerPage);
        }  
        for(var k=0; k < videosPerPage ;k++) {
            if (k < curPageNumVideos) {
                videoLineupNodes[i].style.display = "none";
            }
            videoLineupNodes[j].style.display = "block";
            i++; j++; 
        }
        
		YAHOO.util.Dom.setStyle(document.getElementById(vidLineupContainerId).getElementsByTagName('ul')[0], 'visibility', 'visible');
        YAHOO.util.Dom.setStyle('loadingMsgContainer', 'display', 'none');

        curPageIndex -= 1;
        playerVideoIndex = document.fopObj.getCurrentIndex();
        selectVideoLineupElement(playerVideoIndex);
        curVideoIndex = playerVideoIndex;
        updateScrollButtons();
        if (navTextLine) {
            updateNavText();
        }
    }
    
    function updateNavText() {
        var x = (curPageIndex - 1) * videosPerPage + 1;
        var y = x + Number(videosPerPage) - 1;
        if (y > totalVideos) {
            y = totalVideos;
        }
        
        var txtNavLine = navTextLine.replace('%x%', x);
        txtNavLine = txtNavLine.replace("%y%", y);
        txtNavLine = txtNavLine.replace("%z%", totalVideos);
        
        var navElm = document.getElementById('navIndexLine');
        if (navElm) {
            navElm.innerHTML= txtNavLine;
        }
    }
    
    function myPlaylistsFetched(type, args) {
        var newY = YAHOO.util.Dom.getY('btnAddToPlaylist');
        if (hackYloc !== newY) {
            shiftPopupLocation(newY - hackYloc);
        }
    }

    function rotateLREC() {
        // clear the old timer and set up a new one
        if (lrecTimer) {
            window.clearInterval(lrecTimer);
        }
        try {
        	//console.log("rotating LREC");
        } catch(e) {}
        lrecTimer = window.setInterval(function() {
            kickDarla ("LRECRotation", curSpaceId);
        },30000);
    }


    /* public interface */
    return {
        init : function(config) {
            loadConfig(config);
            buildVideosLineupArray();
            loadFOP();
            
            if (mode != "minimal") {
                var isMultiPage = false;
                if (totalVideos !== "" && videosPerPage !== "") {
                    isMultiPage = true;
                } else {
                    // single page
                    videosPerPage = totalVideos;
                }

                /*
                 * START HACK -- this fetchVideoMetadata is a redundant call to fetch video metadata 
                 * because we are not asking for categories and releases in the first call
                 */
                YAHOO.music.video.addToMyPlaylists.evtGetPlaylistsDone.subscribe(myPlaylistsFetched);
                hackYloc = YAHOO.util.Dom.getY('btnAddToPlaylist');
            	curVideoIndex = 0;
            	// let's not fetch video metadata here, do it on video start because metadata fetch needs spaceid... fetchVideoMetadata(videoLineUp[0]);
            	/** END HACK  **/
           
                document.getElementById('YMusic_singleEmbedTextInput').value = getExternalEmbedCode(videoId);
                YAHOO.music.util.Ellipsis.ellipsizeElementsByClassName('ymusic_ellipsisbox','a',vidLineupContainerId, true);
                YAHOO.music.util.Event.addDelegateListener('ymusic_playembedvideo', vidLineupContainerId, 'click', thumbnailFromVideoLineupClicked);
            
                if (isMultiPage)
				{
                    YAHOO.util.Event.on('scrollUpContainer','click', prevBtnClicked);
                    YAHOO.util.Event.on('scrollDownContainer','click', nextBtnClicked);
                    updateScrollButtons();
                }
            } else {
                // minimal (livesets) mode
                fetchVideoMetadata(videoLineUp[0]); // for the ratings value
                YAHOO.music.util.Event.addDelegateListener('ymusic_playembedvideo', vidLineupContainerId, 'click', thumbnailFromVideoLineupClicked);
                document.getElementById('YMusic_singleEmbedTextInput').value = getExternalEmbedCode(videoId);
            }

        },
        fopCallBackHandler : fopEventsHandler,
        fetchNextData : fetchNextData,
        fetchPrevData : fetchPrevData,
        // external (optional) paging handler
        setPagingHandler : function ( pagingFunctions ) {
            if ( pagingFunctions.next && pagingFunctions.prev ) {
                pager = pagingFunctions;
            }
        },
        videoMetaDataLoadedEvt : videoMetaDataLoadedEvt
    };


})();
