// Initialisation lib audio
var selected_preset = "";
var flashPlayer;
stats_commit_period = 300;
presets = null;
audio_player = null;
loaded_presets = 0;
sel_preset = 0;
sel_title = '';
var calculBodyLoad = 0;
var calculFlashLoad = 0;
var plugStatus = "initiate";
var plugUrl = null;
var plugAttribute = null;
var ieCheck = 0;
var currentPlayingSite;
// State of player
play_state = "play";
hasAssets = false;
var safariCheck = navigator.userAgent.indexOf('Safari');
// Initialisation Of Presets
var presetTable = $H({});
var cover_urls = [];
var tooltips = [];
var default_cover = 'player/images/radio5.jpg';
var assetPlayTable = $H({});
var ctimer;

var ProductAsset = Class.create();
ProductAsset.prototype = {
	initialize: function(codec, urls, description, product_id) {
		this.codec = codec;
		this.urls = urls;
		this.description = description;
    this.product_id = product_id;
	},

	getCodec: function() {
		return this.codec;
	},

	getUrls: function() {
		return this.urls;
	},

	getDescription: function() {
		return this.description;
	},
	
	getProductId: function() {
        return this.product_id;
	}
};

function my_test_handler(event_type, attribute, url) {
	//alert(event_type + ' :: ' + attribute + ' :: ' + url);
}

function on_audiolib_event(event_type, attribute, url) {

		if (event_type == 'missingPlugin' || event_type == 'notSupportedProduct') {
			 plugStatus =  event_type;
			 plugAttribute = attribute;
			 plugUrl = url;
			 try {
			 	get_flash().UpdateStatusLine('Missing::' + attribute + '::' + plugUrl);
			 } catch (err) {}
		} else if (plugStatus != 'missingPlugin'){
			 	try {
					get_flash().UpdateStatusLine(attribute);
				} catch (err) {}
		} else {
			plugStatus = "initiate";
			plugAttribute = null;
			plugUrl = null;
		}
}

// When clicking on a preset
function OnPresetSelection(n) {
		setAssetJSNI(presetTable[n].getCover(), presetTable[n].getID());
}

function getAssetFromProduct(productId) { }

function setInformationPlay(idNumber, url, codec, title, bitrate, cover, infoDisplay, site) {
	test_UpdateProductInfo(title, "", bitrate, cover);

	currentPlayingSite = site;
	if (currentPlayingSite == "noneWeb") {
		webo = false;
	} else {
		webo = true;
	}
	
	if (url.length > 0) {
		
		/* Tag Meta 
			metadata_clear(); 
			buya = false; 
			is_book = false;
			infor = true;
			is_slide_next = false;
			is_slide_previous = false;
		if (hasMeta) { // If radio with metas
			is_slide_next = true;
			suscribeMeta(idNumber);
			get_flash().OpenSlider(true);
			buya = true; 
			is_book = true;
		} else if (list_id_pod != null){ // If podcast
			currentPlaylist = null;
			descript = (infoDisplay != null) ? infoDisplay : "";
			get_flash().UpdatePanelInfo(title, descript, "");
		} else { // If radios with no meta
			currentPlaylist = null;
			get_flash().OpenSlider(false);
			get_flash().UpdatePanelInfo("Cette radio n'a pas d'informations contextuelles",
			 	"", "", "./img/img_fr/blankPixel.gif"); 
		}
		/* ----End---- */
		
		
		audio_player.setNewAsset(new ProductAsset(codec, url, infoDisplay, idNumber));
		plugStatus = "initiate";
		plugAttribute = null;
		plugUrl = null;
		audio_player.attemptToPlay();	
		if (ctimer != null)  clearTimeout(ctimer);
		if (plugStatus == 'missingPlugin' || plugStatus == 'notSupportedProduct') {
			checkPluginStatusJSNI();
			setStatus(false);
		}
	} else {
		audio_player.setNewAsset(null);
		setStatus(false);
	}
	setProductCapabilities();
}

/* TAG REMOVE */

// Play a radio and set the information of the player
function playRadios(isComposite, idProduct) {
	if (isComposite) {
		skip = true;
		paus = true;
		audio_player.setCompositeProduct(idProduct, 0, 1);
		
	} else {
		skip = false;
		paus = false;
		audio_player.setAtomicProduct(idProduct[0]);
	}
	setProductCapabilities();
	setStatus(true);
}

/* ----End----*/

/* TAG UPDATE 

// Play a radio and set the information of the player
function playRadios(isComposite, idProduct) {
	currentPodIndex = 0;
	if (isComposite) {
		list_id_pod = idProduct;
		is_skip_previous = false; 
		is_skip_next  = list_id_pod.length > 1 ? true : false;
		paus = true;
		audio_player.setCompositeProduct(idProduct, 0, 1);
	} else {
		list_id_pod = null;
		is_skip_next = false;
		is_skip_previous = false;
		paus = false;
		audio_player.setAtomicProduct(idProduct[0]);
	}
	is_playable = true;
	setProductCapabilities();
	setStatus(true);
}

/* --End-- */


// Create a new preset
function createPreset(numPreset, ID, title, cover) {
  	presetTable[numPreset] = new infoPreset(ID, title, cover);
	cover_urls[numPreset] = cover;
	tooltips[numPreset] = title;
}

function showPreset() {
	 get_flash().InitPresets(default_cover, cover_urls, tooltips);
}

// Apply all the preset to the player
function pushPresetToFlash() {
	
	/* TAG REMOVE */	

	showPreset();
	get_flash().ChangePlayState("pause");
	get_flash().ChangeVolumeState(5);
	
	skip = false;
	infor = false;
	setProductCapabilities();
	
	audio_player = new AudiolibController(get_flash(), getLanguageJSNI());
	audio_player.getAudioLib(on_audiolib_event);
	
	/* -- End -- */
	
	/* TAG UPDATE 
 
	if (audio_player == null) {
		get_flash().ChangePlayState("pause");
		get_flash().ChangeVolumeState(5);
	}
	audio_player = new AudiolibController(get_flash(), getLanguage());
	audio_player.getAudioLib(on_audiolib_event);

	showPreset();
	setProductCapabilities();
	
	/* ---End--- */
	
	if (plugStatus == 'missingPlugin') {
    	try {
          get_flash().UpdateStatusLine('Missing::' + plugAttribute + '::' + plugUrl);
        } catch (err) { }
	}

}

// Switch the play or stop, setting a state
function setStatus(toPlay) {
	if (toPlay) {
		play_state = "stop";
		if (paus) {
			get_flash().ChangePlayState("pause");
		} else {	
			get_flash().ChangePlayState("stop");
		}
	} else {
		
			if (paus == true) {
				audio_player.pause();
			} else {
				audio_player.stop();
			}

		play_state = "play";
		get_flash().ChangePlayState("play");
	}
}

// When clicking on a player button
function OnButtonPressed(button_name) {
	
	if (button_name == "perso") {
		checkAuthentJSNI()
	}
	
	/* TAG REMOVE */
	
	if (button_name == "back") {
		audio_player.previous();
	}
	if (button_name == "next") {
		audio_player.next();
	}
	
	/* ---End--- */
	
	/* TAG UPDATE 
	
	if (button_name == "back") {
		if (currentPodIndex > 0 && list_id_pod != null) {
			currentPodIndex --;
			is_skip_next = true;
			is_skip_previous = (currentPodIndex == 0) ? false : true;
			setProductCapabilities();
			audio_player.previous();
		}
	}
	if (button_name == "next") {
		if (currentPodIndex < list_id_pod.length -1 && list_id_pod != null) {
			currentPodIndex ++;
			is_skip_previous = true;
			is_skip_next = (currentPodIndex == list_id_pod.length -1) ? false : true;
			setProductCapabilities();
			audio_player.next();
		}
	}
	
	/* ---End--- */
	
	if (button_name == "play_pause_stop") {
		playOrStop();
	}
	if (button_name== "home_page") {
		if (currentPlayingSite != "noneWeb") {
			open(currentPlayingSite, '_blank');
		}
	}
	
	/* Tag Meta 

	if (button_name == "set_favorite") {
		checkWassupJSNI();
		setBookmarkJSNI(titleRadio, artist, track, album , currentId);
	}
	
	if (button_name == "see_next") {
		if (currentPlayIndex < currentPlaylist.length -1 && currentPlaylist != null) {
			currentPlayIndex ++;
			setMetaPlayer(currentPlaylist[currentPlayIndex]);
			is_slide_previous = true;
			is_slide_next = (currentPlayIndex == currentPlaylist.length -1) ? false : true;
			setProductCapabilities();
		}
	}
	if (button_name == "see_previous") {
		if (currentPlayIndex > 0 && currentPlaylist != null) {
			currentPlayIndex --;
			setMetaPlayer(currentPlaylist[currentPlayIndex]);
			is_slide_next = true;
			is_slide_previous = (currentPlayIndex == 0) ? false : true;
			setProductCapabilities();
		}
	}
	/* ----End---- */
	
}

// Switch the play or stop, without having to know what is the state
function playOrStop() {
	if (play_state == "play") {
		setStatus(true);
		audio_player.play();
	} else {
		if (ctimer != null)  clearTimeout(ctimer);
		setStatus(false);
	}	
}

function setLimitPlay() {
	ctimer = setTimeout(function(){
		if (play_state == "stop") {
			if (!checkAuthentJSNI() || !hasDeviceJSNI()) {
				setStatus(false);	
			}
		}
	},30000); 
}

// Calcul the load, when the body is ready
function loadCalcul() {
	calculBodyLoad = 1;
}

// Launch when the player has been loaded
function OnPlayerReady(n) {
	calculFlashLoad = 1;
}

function checkFlashLoad() {
	return get_flash() != null;
}

// When drop a preset onto the player
function test_ProductDroppedAt(url, tooltip, x, y) {
	var num_preset = get_flash().ProductDroppedAt(url, x, y, tooltip);
	return num_preset;
}

// When drag a product over the player
function test_ProductDraggedAt(url, x, y) {
  	var num_preset = get_flash().ProductDraggedAt(url, x, y, "tooltip");
}

// When the player volume is changing
function OnVolumeChange(n) {
	audio_player.setVolume(n);
}

// Get the current Flash Player
function get_flash() {
  if(navigator.appName.indexOf('Microsoft') != -1)
    return window['my_flash'];
  else
    return document['my_flash'];
}

/* TAG REMOVE */

// Set the visual information to show on the player
var skip = true, paus = true, webo = false, infor = true, persoa = true, buya = true;
function setProductCapabilities() {
	get_flash().SetProductCapabilities(skip, paus, webo, infor, persoa, buya);
}

/* ----End--- */

/* TAG UPDATE 

// Set the visual information to show on the player
	var paus = true;
	var webo = false;
	var infor = false;
	var persoa = true;
	var buya = true;
	var is_book = false;
	var is_eject = false;
	var is_playable = false;
	var is_slide_next = false;
	var is_slide_previous = false;
	var is_skip_next = false;
	var is_skip_previous = false;
	var currentPodIndex = 0;
	var list_id_pod = new Array();
	
function setProductCapabilities() {
	try { 
		get_flash().SetProductCapabilities(
			is_skip_previous, is_skip_next, 
			paus, webo, infor, 
			persoa, buya, is_book, is_eject, 
			is_playable, is_slide_previous, is_slide_next);
	} catch(e) {}
}

/* --End---- */

// Update all infos of the player
function test_UpdateProductInfo(title, status, bitrate, cover) {
  var res = get_flash().UpdateProductInfo(
      title, status, bitrate, cover);
}

function refreshTheFrame() {
	} 
	
	
/*  Tag Meta  

	var currentPlaylist = null;
	var currentPlayIndex = 0;
	var track = "", artist = "", album = "", titleRadio = "", albumCover ="";
	var currentId = 0;
	var refreshTime;


    flashCont = new Object();
    flashCont.onAudioEvent = function(audioStatus) { }
    flashCont.onConfigEvent = function(eventType, name, url) { }
		
	flashCont.onMetadata = function(metadata, playlist) {
		// Check to not refresh to begin, if meta is same 
		if ((currentPlaylist != null && currentPlaylist[0].trackName != metadata.trackName) 
				|| currentPlaylist == null) { 
			currentPlayIndex = 0; 
			setMetaPlayer(metadata);
			currentPlaylist = playlist;
		}
	} 

	function suscribeMeta(idNumber) {
		currentId = idNumber;
		metadata_subscribe(currentId) 
	}
 
	function setMetaPlayer(metadata) {
		track = metadata.trackName ? metadata.trackName // If trackName
				: metadata.animatorName ? metadata.animatorName // If animator 
				: "Aucune information n'est disponible"; // If nothing
		artist = metadata.artistName ? metadata.artistName // If artist 
				: metadata.broadcastName ? metadata.broadcastName  // If broadcast
				: ""; // If nothing
		album = metadata.albumName ? metadata.albumName // If album 
				: metadata.topic ? metadata.topic // If topic
				: ""; // If nothing
		albumCover = metadata.albumCover ?  metadata.albumCover //If album
					: metadata.topicCover ? metadata.topicCover  // If topic
					: metadata.animatorCover ? metadata.animatorCover // If animator
					: "./img/img_fr/blankPixel.gif"; // If nothing
		if (currentPlayIndex == 0) artist = "En cours : " + artist;
			else artist = "Precedemment : " + artist;
		get_flash().UpdatePanelInfo(artist, album, 
				track,"http://195.210.43.250/phoenix/"+albumCover);
	}
  
    function onBodyLoad() {
		 initMetadata(flashCont);
    }

	function spy(msg) {
		$("debug").innerHTML = $("debug").innerHTML + msg + '<br>';
	}

/* ---End--- */

