//dojo.require("dojo.io.*");

	var opMap = new Array();
	opMap[0] = 'play_tracks';
	opMap[1] = 'play_album';
	opMap[2] = 'play_tracks';
	opMap[3] = 'play_tracks';
	opMap[4] = 'play_tracks';
	
    var PlayerObjectReference = null;
	var strPlaylistID = null;
	
	function PopupBlocker(){
		var blnReturnValue = false;
		checkForPlayer();
		if( PlayerObjectReference == null ){
			if( document.getElementById( 'PopupBlockedNoticeFloat' ) != null ){
				if( document.getElementById( 'disc_sort' ) != null )
					document.getElementById( 'disc_sort' ).style.display = 'none';
				if( document.getElementById( 'type' ) != null )
					document.getElementById( 'type' ).style.display = 'none';
				try{
					var intAvailableWidth = innerWidth;
				}
				catch(e){
					var intAvailableWidth = document.body.clientWidth;
				}
				document.getElementById( 'PopupBlockedNoticeFloat' ).style.display = 'block';
			}
			else{
				var strPopupBlockerLAyers = '<div class="PopupBlockerWarning">';
				strPopupBlockerLAyers += '<div class="PopupBlockerText">We\'ve detected that you have a pop-up blocker active.</div>';
				//strPopupBlockerLAyers += '<div class="PopupBlockerButton"><a href="javascript:OpenPopupPlayer()"><img src="/images/buttons/popup_blocker/btn_launch_free_player.gif" width="181" height="22" alt="" /></a></div>';
				//strPopupBlockerLAyers += '<div class="PopupBlockerCancelLink"><a href="javascript:void(null)" onclick="CancelPopup()">Cancel Player</a></div>';
				//strPopupBlockerLAyers += '<div class="PopupBlockerLink"><a href="javascript:void(null)" onclick="OpenPopupWindow( \'/info/info_popup_blocker.html\', \'PopupBlocker\', 365, 670, \'center\', \'center\' )">Click here</a> to learn how to add Napster to your  pop-up blocker\'s approved Web site list</div>';
				strPopupBlockerLAyers += '</div>';
				document.getElementById( 'PopupBlockedNotice' ).style.display = 'block';
				document.getElementById( 'PopupBlockedNotice' ).innerHTML = strPopupBlockerLAyers;
				objPlayerTimer = setTimeout( CloseWarning, 60000 );
			}
			blnReturnValue = true;
		}
		return blnReturnValue;
	}
	
	function PreparePlaylist( intPlaylistID ){
		var search_url = "/playlistPlayXML/" + intPlaylistID;
		strPlaylistID = intPlaylistID;
		var Playlist = new Ajax.Request(
			search_url, {
				method: 'get',
				paramters: '',
				onComplete: CreatePlaylistTracks
			}
		);
	}
	
	function CreatePlaylistTracks(){
		if( arguments[0] != null )
			objPlaylistXML = arguments[0].responseXML.documentElement;
		var objAjaxSubData = objPlaylistXML.getElementsByTagName( 'playlist' );
		strPlaylistIDs = objAjaxSubData[0].getAttribute( 'track_ids' );
		_Play( strPlaylistIDs, 2 );
	}
	
	function PlayPlaylist( intPlaylistID ){
		var objPlugin = document.getElementById( 'objNapsterPlugin' );
		try{
			$SCEG( 'Click', 's_eVar3="Play_Playlist_' + intPlaylistID + '_"' );
		}
		catch(e){}
		if( !$B.isNapCompatible || ( objPlugin == null || objPlugin.object == null ) || $C( 'SL' ) == 'LFM' ){
			_Play( intPlaylistID, 2 );
		}
		else if(!$C( 'CLID' )) {
			_Play( intPlaylistID, 2 );
		}
		else{
			PreparePlaylist( intPlaylistID )
		}
	}

	function _Play( strIds, intType, blnAutomix, queue ){
		var checkFlash = confirmFlashVersion();
		if(!checkFlash) { // don't have the right version of flash, so stop
			return;
		}
		/* if(typeof $SCData == 'undefined') {
			return;
		} */
		strIds = strIds.replace(/\s+/g, '');
		if(typeof(queue) == "undefined") { var queue = 0; }
		
		//make track plays queue - switch up for easter egg
		//if(!$SCData('PP') || $SCData('PP') == 0) { if ((intType == 0) && (queue == 0)) { queue = 2; } }
		
		var numItems = strIds.split( ',' ).length;
		if (blnAutomix == 1) {
			displayUMessage("Automix added to Now Playing",2,"play");
		} else {
			switch(intType) {
				case 0:	var umessage = (numItems > 1) ? numItems + " tracks" : "Track";
						umessage += " added to Now Playing";
						displayUMessage(umessage,2,"play"); break;
				case 1: displayUMessage("Album added to Now Playing",2,"play"); break;
				case 2: displayUMessage("Playlist added to Now Playing",2,"play"); break;
				case 3: displayUMessage("Playlist added to Now Playing",2,"play"); break;
				case 4: displayUMessage("Artist added to Now Playing",2,"play"); break;
				case 5: displayUMessage("Radio station added to Now Playing",2,"play"); break;
				case 6: displayUMessage("Playlist added to Now Playing",2,"play"); break;
				case 7: displayUMessage("Work added to Now Playing",2,"play"); break;
			}
		}
		
		var typeMap = new Array();
		typeMap[0] = 'track';
		typeMap[1] = 'album';
		typeMap[2] = 'playlist';
		typeMap[3] = 'user_playlist';
		typeMap[4] = 'artist';
		typeMap[5] = 'radio';
		typeMap[6] = 'user_playlist'; // external napsterlinks (other user's playlists)
		typeMap[7] = 'work'; // classical works
		
		/* first check to see if they're from the US */
		/* if( $C('COUNTRYCODE') == 'US' ) { */
		/* they're from the US, so... */
		/* check for login first */
		/* if(!$C('CLID')) {
			var playURL = "http://home.gb.napster.com/new_player/validate_play.html?play_id=" + strIds + "&type=" + typeMap[intType];
			var retURL = escape( playURL );
			if( $SCData( 'uac' ) != null && $SCData( 'uac' ) == 'nl' )
				$SCData( 'rs', 3 );
			else
				$SCData( 'rs', 1 );
			var intCompliance = Math.random();
			$SCData( 'ls', 1 );
			$SCEG( 'Sign-In/Registration', '' );
			if( !PopupBlocker() ){
				//check for player
				if(PlayerObjectReference == null || (PlayerObjectReference.closed || !PlayerObjectReference.closed)) {
					checkForPlayer();
				}
				// are we sending them to login or reg
				var playerAction = (!($SCData('r')) || ($SCData('r') == '0')) ? 'registration' : 'login'; 
				PlayerObjectReference.window.location.href = "https://home.napster.com/nweb/" + playerAction + "/new_player/?return_url=" + retURL; 
			}
			return;
			}
		} 
		*/
		
		var blnOpCodeSucess = false;
		
		/* for 4.0 web service, we always use the web player
		if( $C( 'CLID' ) ){
			if( $C( 'SL' ) != 'LFM' && FWSupportedCountries[$C('COUNTRYCODE')] ){
				blnOpCodeSucess = $OC( "op=" + opMap[intType] + "%26ids%3d" + strIds, $C( 'CLID' ), null );
				if( blnOpCodeSucess )
					$C( 'PLAYDATA', '', true, null );
			}
		}
		*/
		
		/* intType is either 0 for track or 1 for album */
		if( !blnOpCodeSucess ) { /* this will be false if they're from an unsupported country */
			if( !PopupBlocker() ){
				if( strPlaylistID != null )
					var playerURL = "http://home.gb.napster.com/player/?play_id=" + strPlaylistID + "&type=" + typeMap[intType];
				else
					var playerURL = "http://home.gb.napster.com/player/?play_id=" + strIds + "&type=" + typeMap[intType];
				
				if ( blnAutomix ) {
					playerURL += "&automix=1";
				}
				//old code converting user playlists to tracks and sending playlistname
				/*else {
					if(intType == 3) {
						var cname = collection.store.getPlaylistName(strIds);
						strIds = collection.store.getPlaylistData(strIds)[0].tracks;
						
						intType = 0;
						playerURL = "http://home.gb.napster.com/player/?play_id=" + strIds + "&type=" + typeMap[intType] + "&pln=" + cname;
					}
				}*/
				
				//check for player
				if(PlayerObjectReference == null || (PlayerObjectReference.closed || !PlayerObjectReference.closed)) {
					checkForPlayer();
				}
// alert(playerURL);
				/*
				if( $C('COUNTRYCODE') == 'US' && !$C( 'CLID' ) ){ // we only have to login for US
					//see if they're eligible for free play
					if ($SCData( 'FPF' ) == 0 ) {
						//alert("fpf");
						PlayerObjectReference.window.location.href = playerURL;
						return;
					}
					else {
						//alert("! fpf"); 
						var playURL = "http://home.gb.napster.com/player/validate_play.html?play_id=" + strIds + "&type=" + typeMap[intType];
						var retURL = escape( playURL );
						if( $SCData( 'uac' ) != null && $SCData( 'uac' ) == 'nl' )
							$SCData( 'rs', 3 );
						else
							$SCData( 'rs', 1 );
						var intCompliance = Math.random();
						$SCData( 'ls', 1 );
						// $SCEG( 'Sign-In/Registration', '' );
						var playerAction = (!($SCData('r')) || ($SCData('r') == '0')) ? 'registration' : 'login'; 
						PlayerObjectReference.window.location.href = "https://home.napster.com/nweb/" + playerAction + "/player/?return_url=" + retURL;
					}
				}
				else if( PlayerObjectReference.window.location.href.indexOf( "player" ) < 0 ) {
				*/
				//alert("queue: " + queue);
				if( PlayerObjectReference.window.location.href.indexOf( "player" ) < 0 ) {
					PlayerObjectReference.window.location.href = playerURL;
				}
				else if (queue == 1) {
					//PlayerObjectReference.focus();
					PlayerObjectReference.appendData( strIds,typeMap[intType], blnAutomix );
				}
				else if (queue == 2) {
					PlayerObjectReference.focus();
					PlayerObjectReference.addNewData( strIds,typeMap[intType], blnAutomix );
				}
				else {
					if($SCData('PP')) {
						switch($SCData('PP')) {
							case "1":	PlayerObjectReference.focus();
										//alert($SCData('PP'));
										PlayerObjectReference.insertNewData( strIds,typeMap[intType], blnAutomix );
										break;
							case "2":	PlayerObjectReference.focus();
										//alert($SCData('PP'));
										PlayerObjectReference.appendData( strIds,typeMap[intType], blnAutomix );
										break;
							case "3":	PlayerObjectReference.focus();
										//alert($SCData('PP'));
										PlayerObjectReference.loadNewData( strIds,typeMap[intType], blnAutomix );
										break;
							default: 	PlayerObjectReference.focus();
										//PlayerObjectReference.loadNewData( strIds,typeMap[intType], blnAutomix );
										//PlayerObjectReference.addNewData( strIds,typeMap[intType], blnAutomix );
										PlayerObjectReference.insertNewData( strIds,typeMap[intType], blnAutomix, 1 );
										break;
						}
					} else {
						//alert("?" + $SCData('PP'));
						PlayerObjectReference.focus();
						//PlayerObjectReference.loadNewData( strIds,typeMap[intType], blnAutomix );
						//PlayerObjectReference.addNewData( strIds,typeMap[intType], blnAutomix );
						PlayerObjectReference.insertNewData( strIds,typeMap[intType], blnAutomix, 1 );
					}
				}
			}
		}
    }

    function checkForPlayer(){
		//PlayerObjectReference = window.open( "","PlayerWin","width=355,height=365,menubar=yes,location=no,resizable=yes,scrollbars=yes,status=no" );
		//PlayerObjectReference = window.open( "","PlayerWin","width=355,height=365,menubar=yes,location=no,resizable=yes,scrollbars=yes,status=no" )
		PlayerObjectReference = window.open( "","PlayerWin","width=355,height=365,menubar=no,location=no,resizable=no,scrollbars=no,status=no" );
		self.name = "napsterMain";
		//alert(self.name);
    }

    function PlayClip( strIds ) {
        var playerURL = "http://home.gb.napster.com/player/?play_id=" + strIds + "&type=clip";
        //check for player
        if(PlayerObjectReference == null || (PlayerObjectReference.closed || !PlayerObjectReference.closed)) {
            checkForPlayer();
        }
        if (PlayerObjectReference.window.location.href.indexOf("player") < 0) {
            PlayerObjectReference.window.location.href = playerURL;
        }
        else {
            PlayerObjectReference.focus();
            PlayerObjectReference.loadNewData(strIds,typeMap[intType]);
        }
    }

var playJSloaded = 1;

    function sendMusic( strIds, type, strMediaName, strArtistName ) {
		var strMediaAndArtist = strMediaName + ( ( strArtistName != null )? ' by ' + strArtistName : '' );
		var strEmailMessage = 'mailto:?subject=Free Music From Napster&body=Listen to this great music from Napster! Click below to hear ' + strMediaAndArtist + ', and go to Napster.com to listen to 2 million more free tracks.%0A%0A';
		strEmailMessage += "http://home.gb.napster.com/player/" + type + "/" + strIds;
		self.location.href = strEmailMessage;
    }
	
	function AddEvent( objElement, strEvent, funcAction ){
		try{
			objElement.attachEvent( 'on' + strEvent, function(){ eval( funcAction ) } );
		}
		catch(e){
			try{
				objElement.addEventListener( strEvent, function(){ eval( funcAction ) } , false );
			}
			catch(e){}
		}
	}
	
	function CloseMessage( strMessageLayerName ){
		document.getElementById( strMessageLayerName ).style.display = "none";
		return true;
	}
	
	var objPlayerTimer = null;

    function playNLink( plid,plt ){
		$SCData( 'uac', 'nl' );
		//objPlayInterval = setInterval( function(){
		//	if( playJSloaded ){
		//		clearInterval( objPlayInterval );
                Play( plid, plt );
		//	}
		//}, 25 );
    }
	
	function CloseWarning(){
		if( objPlayerTimer != null )
			clearTimeout( objPlayerTimer );
		if( document.getElementById( 'FlashMovie' ) != null ){
			document.getElementById( 'FlashMovie' ).style.display = 'block';
			document.getElementById( 'PopupBlockedNotice' ).style.display = 'none';
		}
		if( document.getElementById( 'PopupBlockedNoticeFloat' ) != null ){
			if( document.getElementById( 'disc_sort' ) != null )
				document.getElementById( 'disc_sort' ).style.display = 'inline';
			if( document.getElementById( 'type' ) != null )
				document.getElementById( 'type' ).style.display = 'inline';
			document.getElementById( 'PopupBlockedNoticeFloat' ).style.display = 'none';
		}
		return true;
	}
	
	function OpenPopupPlayer(){
		CloseWarning();
        //check if we have play data in the query else fallback to PLAYDATA cookie
        var plid = query.plid;
        var plt = query.plt;
        if( ( plid == null || plid == '' ) || ( plt == null || plt == '' ) ){
			if( $C( 'PLAYDATA' ) != null && $C( 'PLAYDATA' ) != '' ){
                var strLocation = unescape( $C( 'PLAYDATA' ) );
                queryPD = new Arguments( strLocation );
                plid = queryPD.plid;
                plt = queryPD.plt;
            }
            else {
                //TODO: handle case where we have no valid play data
            }
        }
		_Play( plid, plt );
	}
	
	function Play( strIds, intType, blnAutomix ){
		var multipleItems = 0;
		strIds = new String( strIds );
		intType = parseInt( intType );
		var numItems = strIds.split( ',' ).length;
		// SC tracking
		// this can be hard coded for now - can only track plays from a button (no right click)
		// and can't drag to player (different window)


		var scPlayVarsStr = 's.eVar1="Play"; s.eVar2="Button";s.eVar3=s.pageName;'; 
		if( numItems > 1 && intType == 0 ){
			scPlayVarsStr += 's.eVar5="MultipleTracks";';
		}
		else if( blnAutomix ) {
			var AutoMixSC = new Array();
			AutoMixSC[0] = "Track"; //based on track
			AutoMixSC[1] = "Album"; // based on album
			AutoMixSC[2] = "Playlist"; // based on Napster-programmed playlist
			AutoMixSC[4] = "Artist"; // based on artist
			AutoMixSCTag= AutoMixSC[intType];
			scPlayVarsStr += 's.eVar5="' + AutoMixSCTag + '";';
		}
		else{
			if( intType == 0 ) {
				scPlayVarsStr += 's.eVar5="Track";';
			}
			else if( intType == 1 ) {
				scPlayVarsStr += 's.eVar5="Album";';
			}
			else if( intType == 2 ) {
				scPlayVarsStr += 's.eVar5="Playlist";';
			}
			else if( intType == 5 ) {
				scPlayVarsStr += 's.eVar5="Radio";';
			}
		}
		$SCEG( 'ContentAction',scPlayVarsStr);

		/*
		switch(intType) {
			case 0:	var umessage = "The " + numItems + " selected track";
					(numItems > 1)?umessage += "s have":umessage += " has";
					umessage += " been added to Now Playing.";
					displayUMessage(umessage,2,"play"); break;
			case 1: displayUMessage("The selected album is loading in Now Playing.",2,"play"); break;
			case 2: displayUMessage("The selected playlist is loading in Now Playing.",2,"play"); break;
			case 3: displayUMessage("The selected playlist is loading in Now Playing.",2,"play"); break;
			case 4: displayUMessage("The selected radio station is loading in Now Playing.",2,"play"); break;
			case 5: displayUMessage("The selected radio station is loading in Now Playing.",2,"play"); break;
			case 6: displayUMessage("The selected playlist is loading in Now Playing.",2,"play"); break;
			case 7: displayUMessage("The selected work is loading in Now Playing.",2,"play"); break;
		}
		*/
		_Play( strIds, intType, blnAutomix, 0 );
	}
	
	function Queue( strIds, intType, blnAutomix ){
		//alert("Queue run");
		strIds = new String( strIds );
		intType = parseInt( intType );
		if( strIds.split( ',' ).length > 1 && intType == 0 ){
			// $SCEG( 'Click', 's_eVar3="Queue_All_' + $FILEPATH() + '"' );
		}
		else{
			if( intType == 0 ) {
				// $SCEG( 'Click', 's_eVar3="Queue_Track_' + strIds + '_' + $FILEPATH() + '"' );
			} else {
				if( intType == 1 ) {
					// $SCEG( 'Click', 's_eVar3="Queue_Album_' + strIds + '_' + $FILEPATH() + '"' );
				}
			}
		}
		_Play( strIds, intType, blnAutomix, 1 );
		//PlayerObjectReference.testscream("from link");
	}
	
	function ClickFromFlash( strURL ){
		// $SCEG( 'Click', 's_eVar3="Flash_URL_' + strURL + '"' );
		document.location.href = strURL;
	}
	
	function PlayFromHome( plid, plt ){
        var strQ = '?plid=' + plid + '&plt=' + plt + '&playfromhome=true';
        $C( 'PLAYDATA', strQ );
		if( plt < 2 )
			playNLink( plid, plt );
		else
			PlayPlaylist( plid );
	}
	
	function getAllListReturnTracks() {
		var haveItems = false;
		if(document.getElementById("listReturn")) {
			var tracks = document.getElementById("listReturn").getElementsByTagName("tr");
			var itemArray = new Array();
			var itemType = "";
			if(tracks.length) {
				for(var i=0; i<tracks.length; i++) {
					var type = tracks[i].getAttribute("type");
					if(tracks[i].id) {
						haveItems = true;
						switch(tracks[i].id.substring(0, 1)) {
							case "t":	// universalMessage += "Track ID#" + inputs[i].value.substring(1);
										itemArray.push(tracks[i].id.substring(1));
										itemType = 0;
										// this.deleteItem(inputs[i].value.substring(1), 0);
										break;
						}
					}
				}
				if(haveItems) {
					return itemArray;
				} else {
					return 0;
				}
			}
		} else {
			return 0;
		}
	}
		
	function playAllListReturnTracks() {
		var playItemArray = getAllListReturnTracks();
		if(playItemArray) {
			// added to alleviate bug 3275
			if(playItemArray.length > 125) {
				playItemArray.length = 125;
			}
			Play(playItemArray, 0);
		}
	}
		
	function addAllListReturnTracks() {
		var addItemArray = getAllListReturnTracks();
		if(addItemArray) {
			AddToLibrary(addItemArray.join(","), 0);
		}
	}
	
	function CancelPopup(){
		$C( 'PLAYDATA', '', true, null );
		CloseWarning();
	}

     if ( $C( 'PLAYDATA' ) != null && $C( 'PLAYDATA' ) != '' ) {
		if( $C( 'PLAYDATA' ).indexOf( 'elnk' ) == -1 && ( $C( 'ENUID' ) == null || $C( 'ENUID' ) == '' ) ){
			$C( 'PLAYDATA', '', true, null );
		}
	 	else{
        	var strLocation = unescape( $C( 'PLAYDATA' ) );
	        query = new Arguments( strLocation );
		}
    }
    //initiate play if you find attrs on the query string (return URL from login)
    if( query.plid && query.plt ){
		AddEvent( window, 'load', "playNLink( '" + query.plid + "', " + query.plt + " )" );
    }
	
	if( ( $C( 'PLAYDATA' ) != null && $C( 'PLAYDATA' ) != '' ) && ( query.mix_pl != null && query.mix_pl != '' ) )
		PreparePlaylist( query.mix_pl.replace( 'MIX_', '' ) );



	function PlayTopTracks(aid) {
		var topTracksIDs = {
				url: "http://home.gb.napster.com/cgi-bin/webPlayArtistTopTracks.cgi?artist_id=" + aid + "&COUNTRYCODE=" + $C('COUNTRYCODE') + "&EXPLICIT=" + $C('EXPLICIT'),
				//mimetype: "text/plain", 
				//load: function(type, jsonData, evt) {
				load: function(jsonData, ioArgs) {
					eval(jsonData);
					return jsonData;
				}
			};
		dojo.xhrGet(topTracksIDs);
	}

	function confirmFlashVersion() {
		var noFlashMsg = '';
		var showMsg = 0;
		var minVersion = 8;
		if(flashinstalled < 2) {
			noFlashMsg = 'We\'re sorry, Napster requires that you install the Adobe Flash Player to use the Napster Web service. To get the latest free version of the Flash plug-in, please <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW" target="_blank">click here.</a>';
			showMsg = 1;
		}
		else {
			if(flashversion < minVersion) {
				noFlashMsg = 'We\'re sorry, Napster requires a newer version of Adobe Flash Player than you currently have installed. To get the latest free version of the Flash plug-in, please <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW" target="_blank">click here.</a>'; 
				showMsg = 1;
			}
		}
		if(showMsg > 0) {
			if(document.getElementById('PopupBlockedNotice')) {
				document.getElementById( 'PopupBlockedNotice' ).style.display = 'block';
				document.getElementById( 'PopupBlockedNotice' ).getElementsByTagName("h2")[0].innerHTML = noFlashMsg;
				return false;
			}
		}
		return true;
	}
