var audio_path = 'http://emicmg.edgeboss.net/download/emicmg/divisional/14/audio/mp3/full/100/';
var audio_ext = '.mp3';
var audio_player = null;
var video_player = null;
var currentAudioState = 'NONE';
var currentVideoState = 'NONE';
var flash_compatible = false;

function playerReady(obj) {
    audio_player = document.getElementById('audio_player');
    video_player = document.getElementById('video_player');
    addListeners();
};

function addListeners() {
    if (audio_player && video_player) { 
    	audio_player.addModelListener('STATE', 'audioStateMonitor');
    	video_player.addModelListener('STATE', 'videoStateMonitor');
    } else {
    	setTimeout("addListeners();", 100);
    }
};

function audioStateMonitor(obj) {
	currentAudioState = obj.newstate;
	// Stop video player if it is playing
	if (currentVideoState == "PLAYING") {
		video_player.sendEvent('STOP');
	}
};

function videoStateMonitor(obj) {
	currentVideoState = obj.newstate;
	// Stop audio player if it is playing
	if (currentAudioState == "PLAYING") {
		audio_player.sendEvent('STOP');
		$("div#song_box .list a").removeClass("active");
		$("a.play").removeClass("active");
	}
};

// jQuery functions to control audio player
$(document).ready(function() {    
    // Detect if Flash is available
    // If not we'll fallback to HTML5 javascript controls
    if ((navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.indexOf("Mac") == -1 &&
                                                              navigator.appVersion.indexOf("3.1") == -1) ||
                                             (navigator.plugins && navigator.plugins["Shockwave Flash"]) ||
                                                                navigator.plugins["Shockwave Flash 2.0"]) {
        flash_compatible = true;
    }
    
    $("a.play").bind('click', function(){
        var that = $(this);
        var ref = that.attr('ref');
        var source = audio_path + ref + audio_ext;
        var is_active = that.hasClass("active");
        $("a.play").removeClass("active");
        if (flash_compatible) {
            if (is_active) {
                audio_player.sendEvent('STOP');
            } else {
                that.addClass("active");
                audio_player.sendEvent('LOAD', source);
                audio_player.sendEvent('PLAY');
            }
        } else {
            var audioPlayer = document.getElementById('aplay');
            if (is_active) {
                audioPlayer.pause();
            } else {
                that.addClass("active");
                audioPlayer.setAttribute('src', source);
                audioPlayer.load();
	            audioPlayer.play();
            }
        }
        return false;
    });
});
