/*
	Javascript for communication  between site and player
*/

var playerWindow = null;
var playerApp = null;
var flashMovie = null;
var timerId = null;
var players = new Array();
var playCount = 0;
var dragging = false;
var openAttempts = 0;
var currentPlayer;

// Max attemts to communicate with pop-up player (+error txt if reached)
var maxOpenAttempts = 30
var openErrorTxt = 'Beklager! Der er problemer med kommunikationen med pop-up playeren, pr\u00F8v at lukke pop-upen og klik p\u00E5 play linket igen. Kontant support@bandbase.dk hvis du fortsat oplever denne fejl. \n \nSorry! Error communication with pop-up player, try closing the pop-up and click play again. Contact support@bandbase.com if you continue having problems.';

function HideStickyAd() {
    jQuery('#StickyAd').hide();
}

// Open (or fokus on) pop-up player
function openPlayerPopup() {
	if( !playerWindow || playerWindow.closed) {
		playerWindow = window.open(('/PlayerV2/default.aspx'), 'Player','statusbar=0,width=835,height=562,top=100,left=100,resizable=no,scrollbars=no,menubar=no,status=0');	
	} else if(playerWindow.focus) {
		playerWindow.focus();
	}
}

// Check if pop-up is open and connected
function isPlayerOpen() {
	return isPlayerOpenFunction();
}

function isPlayerOpenFunction() {
	clearTimeout(timerId);
	if(flashMovie != null && playerApp.isMovieReady() ) {
		return true;
	} else {
		return false;
	}
}

// Check if pop-up is playing
function isPlayerPlaying() {
	var result = false;
	if(isPlayerOpenFunction()) {
		var result = flashMovie.isPlayerPlaying();
		return result;
	}
	return result;
}

function getInlinePlayer(id) {
	var playerId = "playerIdP_" + id;
	var flashMovie = getSwfObj(playerId);
	return flashMovie;
}

function getSwfObj(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

// check if inline player is playing
function isInlinePlayerPlaying(id) {
	var flashMovie = getInlinePlayer(id);
	var isPlaying = false;
	
	if (flashMovie)
		isPlaying = flashMovie.isInlinePlayerPlaying();
}

function startInlinePlayer(id) {
	var flashMovie = getInlinePlayer(id);
	flashMovie.startInlinePlayer();
}

function inlinePlayerEnded(id) {
    // Go to and play next song when flash command it
    startNextInlinePlayer(id);
}

function updateMetadata(time, trackName, trackLink, bandName, bandLink, isFavorite, trackId, currentplayerID) {
    // Update the inlineplayer fields from the actual playing flash
    jQuery('#TimeTotal')[0].innerHTML = time;
    jQuery('#TrackName').text(trackName);
    jQuery('#BandName').text(bandName);
    jQuery('#TrackName').attr({href : "" + trackLink + ""});
    jQuery('#BandName').attr({href : "" + bandLink + ""});
    // Unbind earlier to prevent it from register all previous "hearts"
    jQuery("#inlineHeartIcon").unbind("click");
    // Love track
    jQuery("#inlineHeartIcon").bind("click", function(e){inlineLoveTrack(trackId)});
    // Logic for showing hearted tracks
    if (isFavorite == 1) {
        jQuery("#inlineHeartIcon").attr({
            "className":"GreenIconWhiteBG",
            "class":"GreenIconWhiteBG"
            });
    } else {
        jQuery("#inlineHeartIcon").attr({
            "className":"ButtonIcon",
            "class":"ButtonIcon"
            });
    }
    // Asign current player to Global Player
    currentPlayer = currentplayerID;
    
    //Show sticky controls
    if (jQuery('#StickyPlayerInner').is(":hidden")) {
        jQuery('#StickyPlayerInner').show();
        // Init Volume and position slider for first use
        initSliders();
    };
    
    // Pause popup player if exists
    
    //pause();
    
    // Keypresses -- check keys here : http://www.quirksmode.org/js/keys.html or http://unixpapa.com/js/key.html
    jQuery(document.body).keydown( function (e) {
        
        if (e.which == 39) // Left arrow
            inlinePlayerNext();
        if (e.which == 37) // Right arrow
            inlinePlayerPrevious();
     });

    //Show sticky ad for x sec. on first and every 4th play
    if (playCount == 0) {   
        //Load banner
         document.getElementById('ctl00_ShowAd2_IframeAdSlot').src = '/UserControl/AdSlots/default.aspx?adslot=Bandbase_InlinePlayer_300x250&amp;AdIframeID=ctl00_ShowAd2_IframeAdSlot';

    };
    playCount++;
}

function initSliders() {
    
    // Init Positionslider
    jQuery("#positionslider").slider({
        start:      function(event, ui) {dragging = true;},
        slide:      function(event, ui) {inlineplayerUpdateTimePosition(ui.value);},
        stop:       function(event, ui) {dragging = false;},
        animate:    true
    });
    
    // init Volumeslider            
    jQuery("#volumeslider").slider({
        orientation:    "vertical",
      //range:          "min",
        value:          80,
	    animate:        true,
        slide:          function(event, ui) {inlineSetVolume(ui.value);}
    });
    inlineSetVolume(80);
}

function showStickyAd() {

    //Check if any banner is loaded
    if (jQuery('#ctl00_ShowAd2_IframeAdSlot').attr("src") != "") {
        //Show sticky ad div
        jQuery('#StickyAd').show("fast")
        jQuery('#StickyAd').animate({ height: 283 });    
        
        //Hide again after 20 sec.
        setTimeout(function() {
            jQuery('#StickyAd').animate(
                { height: 0 }
                , "fast"
                , "swing",
                function() {
                    jQuery(this).hide();
                }
                );
        }, 20000);    
    }
}

function inlinePlayerPauseIcon() {  
    //Show Pause Icon, initiated from inline flash player
    jQuery('#PlayIcon').attr({
        'src':'/images/icons/pause.gif',
        'className':'GreenIconWhiteBG',
        'class':"GreenIconWhiteBG"
    });
}

function inlinePlayerPlayIcon() {
    // Show Play Icon, initiated from inline flash player
    jQuery('#PlayIcon').attr({
        'src':'/images/icons/play_old.gif',
        'className':'ButtonIcon',
        'class':"ButtonIcon"
    });
}
function inlinePlayerLoadIcon() {
    // Show Load Icon, initiated from inline flash player
    jQuery('#PlayIcon').attr({
        'src':'/images/icons/load.gif',
        'className':'ButtonIcon',
        'class':"ButtonIcon"
    })
}

function updateTime(time, procentage) {
    // Update the TimeTotal field with the playing time from the current playing flash
    if (time.indexOf('NaN') == -1) {
        jQuery('#Time')[0].innerHTML = time;
        
        if (dragging == false) {
            // Update slide position
            jQuery('#positionslider').slider('option', 'value', procentage);    
        }
    }
}

function inlineSetVolume(val) {
    // Set inlinePlayer Volume
    document.getElementById(currentPlayer).inlineVolume(val);
}

function inlineplayerUpdateTimePosition(val) {
    // Update the time in the current player according to slider (procentage)
    document.getElementById(currentPlayer).inlineUpdateTimePosition(val);
}

function inlineLoveTrack(trackId) {
    // Called from inlineplayer love button
    // Show load icon      
    jQuery("#inlineHeartIcon").attr({
        'src':'/images/icons/load.gif',
        'className':'ButtonIcon',
        'class':"ButtonIcon"
    });
    // Call LoveTrack with parameters
    LoveTrack(trackId);
}

function inlinePlayerStop() {
    // Called from Play button
    document.getElementById(currentPlayer).stopPlaying(); 
}

function PopUpPlayerStopInlinePlayer() {
    // Called from popup
    if (flashMovie.isInlinePlayerPlaying())
        document.getElementById(currentPlayer).fadeOutAndStop(); 
}

function inlinePlayerPause() {
    // Called from Play button
    document.getElementById(currentPlayer).inlineTogglePause(); 
}

function inlinePlayerPrevious() {
    // Called from prevous button
    startPreviousInlinePlayer(currentPlayer);
}

function inlinePlayerNext() {
    // Called from next button or Flash player when reached end of song
    startNextInlinePlayer(currentPlayer);
}

function startPreviousInlinePlayer(id) {
    // find the provided id index in players array
    var index = jQuery(players).index(id);
    // variable to hold player
    var player;
    
    // Start playing if a song is there
    if (index >= 0) {
        // assign next player to an object
        player = document.getElementById(players[index - 1]);
        // make the player play
        player.startInlinePlayer();
    } else {
        // The provided ID don't exists, play first instead
        player = document.getElementById(players[0]);
        player.startInlinePlayer();
    }
}

function startNextInlinePlayer(id) {
    // find the provided id index in players array
    var index = jQuery(players).index(id);
    // variable to hold player
    var player;
    
    // Make sure to don't play in fat footer
    var np = document.getElementById(players[index + 1]).getAttribute("id");
    
    if (index >= 0 && np.indexOf("FatFooter") == -1) {
        // Start playing if a song is there
        if (index < (jQuery(players).length-1)) {
            // assign next player to an object
            player = document.getElementById(players[index + 1]); //jQuery('#' + players[index + 1] +' > *')[0];
        } else {
            // We reach the end of avalable tracks, play first
            player = document.getElementById(players[0]); //jQuery('#' + players[0] +' > *')[0]
        }       
        // make the player play
        player.startInlinePlayer();      
    } else {
        // The provided ID don't exists, play first instead
        player = document.getElementById(players[0]);
        player.startInlinePlayer();
    }
}

// General output
function javaTracer(msg,msg2) {
	//jQuery('#Debug').innerHTML += msg + ":" + msg2 + "<br>";
}

// Starter afspilning i pop-up player
function play() {
	if(isPlayerOpenFunction()) {
		flashMovie.playTrack();
	} else {
		return false;
	}

}

// pauser pop-up playeren (husk at den skal fade ned)
function pause() {
	if(isPlayerOpenFunction()) {
		tmp = flashMovie.pause();
	} else {
		return false;
	}
}

// tager næste item på playlist
function next() {
	if(isPlayerOpenFunction()) {
		flashMovie.next();
	} else {
		return false;
	}
}

// tager forrige item på playlist
function prev() {
	if(isPlayerOpenFunction()) {
		flashMovie.prev();
	} else {
		return false;
	}
}

// loader en playliste ud fra listens ID
function loadPlaylist(playlistId) {
	if (!playlistId) {
		playlistId = document.forms["uidform"].playlistId.value;
		};
		
	if(isPlayerOpenFunction()) {
	    openAttempts = 0;
		flashMovie.loadPlaylist(playlistId);
	} else if (openAttempts >= maxOpenAttempts) {
	    // Count open attemts to stop loop to avoid player opening again when closed
	    openAttempts = 0;
	    alert(openErrorTxt);
	} else {
		openPlayerPopup();
		timerId = setTimeout(function () { loadPlaylist(playlistId); },500);
		openAttempts++
	}
}

// loader en playliste ud fra listens ID
function loadCollection(collectionId) {
	if (!collectionId) {
		collectionId = document.forms["uidform"].collectionId.value;
		};
		
	if(isPlayerOpenFunction()) {
	    openAttempts = 0;
		flashMovie.loadCollection(collectionId);
    } else if (openAttempts >= maxOpenAttempts) {
	    // Count open attemts to stop loop to avoid player opening again when closed
	    openAttempts = 0;
	    alert(openErrorTxt);
	} else {
		openPlayerPopup();
		timerId = setTimeout(function () { loadCollection(collectionId); },500);
		openAttempts++
	}
}


// returnerer true/false om den aktuelle playlist har flere sange efter den aktuelle sang
function playlistHasNext() {
	if(isPlayerOpenFunction()) {
		var result = flashMovie.playlistHasNext();
	} else {
		return false;
	}
}

// returnerer true/false om den aktuelle playlist har sange før den aktuelle sang
function playlistHasPrev() {
	if(isPlayerOpenFunction()) {
		var result = flashMovie.playlistHasPrev();
	} else {
		return false;
	}
}

// tjekker om en sang/video findes på den aktuelle playliste
// Type: ”Track” eller ”Video”
// ID: TrackID eller VideoID
function playlistItemExist(ItemID) {

	if (!ItemID)
		ItemID = document.forms["uidform"].existingId.value;

	if(isPlayerOpenFunction()) {
		var result = flashMovie.playlistItemExist(ItemID);		
		return result;
	} else {
		return false;
		//openPlayerPopup();
		//timerId = setTimeout(function () { playlistItemExist(ItemID); },500);
	}
}

function playQuickTrack(TrackId,VideoId) {

	//console.log('playQuickTrack - TrackId: '+ TrackId +' VideoId: '+ VideoId +' flashMovie: ' + flashMovie);
	
	if (!TrackId)
		TrackId = "0"; //document.forms["uidform"].playTrackId.value;
	if(!VideoId)
		VideoId = "0";
	
	//if(isPlayerOpenFunction() && typeof flashMovie.playQuickTrack == 'function') {
	if(isPlayerOpenFunction()) {
		openAttempts = 0;
		flashMovie.playQuickTrack(TrackId,VideoId);	
	} else if (openAttempts >= maxOpenAttempts) {
	    // Count open attemts to stop loop to avoid player opening again when closed
	    openAttempts = 0;
	    alert(openErrorTxt);
	} else {
		openPlayerPopup();
		timerId = setTimeout(function () { playQuickTrack(TrackId,VideoId); },500);
		openAttempts++
	}
}

// Play a string of tracks
function playListOfTracks(ListOfTracks) {
    
	if(isPlayerOpenFunction()) {
	    openAttempts = 0;
		flashMovie.playListOfTracks(ListOfTracks);
	} else if (openAttempts >= maxOpenAttempts) {
	    // Count open attemts to stop loop to avoid player opening again when closed
	    openAttempts = 0;
	    alert(openErrorTxt);
	} else {
		openPlayerPopup();
		timerId = setTimeout(function () { playListOfTracks(ListOfTracks); },500);
		openAttempts++
	}
}

// Add a string of tracks to the current playlist
function addListOfTrackToCurrentPlaylist(ListOfTracks) {

	if(isPlayerOpenFunction()) {
	    openAttempts = 0;
		flashMovie.addListOfTrackToCurrentPlaylist(ListOfTracks);
	} else if (openAttempts >= maxOpenAttempts) {
	    // Count open attemts to stop loop to avoid player opening again when closed
	    openAttempts = 0;
	    alert(openErrorTxt);
	} else {
		openPlayerPopup();
		timerId = setTimeout(function () { addListOfTrackToCurrentPlaylist(ListOfTracks); },500);
		openAttempts++
	}
}

function addToCurrentPlaylist(TrackId,VideoId) {

    //console.log('addToCurrentPlaylist - TrackId: '+ TrackId +' VideoId: '+ VideoId +' isPlayerOpenFunction(): ' + isPlayerOpenFunction());

	if(!TrackId)
		TrackId = "0";
	if(!VideoId)
		VideoId = "0";
	
	if(isPlayerOpenFunction()) {
		flashMovie.addToCurrentPlaylist(TrackId,VideoId);		
	} else {
		return false;
	}
	
}

function addToPlaylist(PlaylistID,TrackId,VideoId) {

    //console.log('addToPlaylist - PlaylistID: '+ PlaylistID +' TrackId: '+ TrackId +' VideoId: '+ VideoId +' isPlayerOpenFunction(): ' + isPlayerOpenFunction() +' currentPlaylistID(): '+ currentPlaylistID());

	if (!TrackId)
		TrackId = "0";
	if(!VideoId)
		VideoId = "0";
	
	if(isPlayerOpenFunction()) {
		flashMovie.addToPlaylist(PlaylistID,TrackId,VideoId);
		
		//Reload playlist if current
		if (currentPlaylistID() == PlaylistID) {
		    reloadPlaylist();
		}

	} else {
		return false;
	}
}

// returnerer ID’et på den aktuelle playlist (0 hvis quicklist eller collection etc.)
function currentPlaylistID() {
	if(isPlayerOpenFunction()) {
		var result = flashMovie.currentPlaylistID();
		return result;
	} else {
		return false;
	}
}

// Opdaterer den aktuelle playlist 
function reloadPlaylist() {
	if(isPlayerOpenFunction()) {
		flashMovie.reloadPlaylist();
	} else {
		return false;
	}
}

function refreshListOfPlaylists() {
	if(isPlayerOpenFunction()) {
		flashMovie.refreshListOfPlaylists();
	} else {
		return false;
	}
}

// returnerer om det er en sang eller video som afspilles
function currentItemValue(itemAttribute) {
	if (!itemAttribute)
		itemAttribute = document.forms["uidform"].itemAttribute.value;

	if(isPlayerOpenFunction()) {
		var result = flashMovie.currentItem(itemAttribute);
		return result;
	} else {
		return false;
	}
}

// returnerer om den aktuelle sang eller video er fra et band, en user eller en business
function currentAuthorValue(value) {
	if(isPlayerOpenFunction()) {
		var result = flashMovie.currentAuthor(value);
		return result;
	} else {
		return false;
	}
}

function ShareOnFacebook(ItemName, ItemLink) {
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(ItemLink)+'&t='+encodeURIComponent(ItemName),'sharer','toolbar=0,status=0,width=626,height=450');
    return false;
}

function insertPlayers() {

    //Hide sticky controls and ad
//    if (jQuery('#ctl00_StickyPlayer').is(":hidden") == false) {
//        jQuery('#ctl00_StickyPlayer').hide();
//        jQuery('#StickyAd').hide();
//    };

    // Find each play span and insert player
    jQuery("span[class*='bbp_']").each(function(i) {
        var id = this.className.substr(4);
        var sp = this;

        var so = new SWFObject("http://www.bandbase.dk/PlayerV2/InlinePlayer.swf?28", "bbPlayer_" + sp.id, "20", "20", "10", "#ffffff", "high");
        so.addParam("allowScriptAccess", "always");
        so.addParam("allowFullScreen", "true");
        so.addParam("wmode", "transparent");
        so.addVariable("bbPlayerId", "bbPlayer_" + sp.id);
        so.addVariable("bbTrackId", id);
        so.addVariable("bbuid", userID);
        so.write(sp.id);

        //jQuery("#" + this.id).parent().wrap('<div meebo:notsharable="true" />');
        jQuery("#" + this.id).removeAttr("class");

        // Put playerID in global array, we can access later
        players[i] = "bbPlayer_" + sp.id;
    })
}