var p = null;
var popup = null;
var isPopup = false;
var pending = null;
var popupOpts = "menubar=no,status=no,scrollbars=no,menubar=no,location=yes,width=380,height=404";

// adapt options
if(navigator.userAgent.search("Chrome/5") != -1 && navigator.userAgent.search("Mac") != -1){
	// 51px de plus en h
	popupOpts = "menubar=no,status=no,scrollbars=no,menubar=no,location=yes,width=380,height=455";
}

function onPopupNotif(notif) {
	//log("onPopupNotif() type:" + notif.type + " data:" + notif.data);
	switch (notif.type) {
	case "ready":
		p = notif.data;
		log("onPopupNotif pending:"+pending);
		if (pending)
			p.setCurrentState(pending);
		pending = null;
		break;
	case "close":
		isPopup = false;
		popup = null;
		p = getPlayer();
		controlPlayer("enable");
		if (notif.data) p.setCurrentState(notif.data);
		break;
	case "show-formats":
		loadUrl(ratesAndFormatsUrl);
		break;
	}
}

function onPlayerNotif(notif) {
	log("onPlayerNotif() type=" + notif.type);

	switch (notif.type) {
	case "detach":
		
		try {			
			log("Start detaching player " + p);
			pending = p.getCurrentState();
			controlPlayer("disable");
			controlPlayer("stop");
			log("Open player popup (current popup= " + popup + ")");
			  
			if (!popup || popup.closed) { 
					popup = window.open(websiteUrl + "html/popup.html", "popupplayer", popupOpts);
			}
			else {
				popup.focus();
			}
			if (popup && !popup.closed) {
				isPopup = true;
			} else {
				isPopup = false;
			}
		} catch(e) {
			txt="There was an error on this page.\n\n";
		    txt+="Error description: " + e.description + "\n\n";
		    txt+="Error: " + e + "\n\n";
		    txt+="Click OK to continue.\n\n";
		    alert(txt);
		}
		break;

	case "ready":
		p = getPlayer();
		RSR.player.ready = true;
		RSR.player.autoPlay();
		break;

	case "show-formats":
		loadUrl(ratesAndFormatsUrl);
		break;
	case "show-selection":
	//	log("TODO show selection");
		break;
	case "add-selection":
	//	log("TODO add selection: " + notif.data.url);
		break;
	}
	
	
}

// Ex: ratesAndFormats
function loadUrl(url) {
	// function in addOnsManager.js
	openURL(url, "_self");
}

function controlPlayer(action) {
//	log("controlPlayer() action=" + action + " isPopup=" + isPopup);
	p.doAction(action);
}

function log(str) {
	jQuery("#debug").append(str + "<br>");
}

function getCurrentState() {
	return p.getCurrentState();
}

function getPlayer() {
	return document.getElementById("rsrplayer");
}

function play(url, duration, title) {
	if (!duration) duration = 0;
	if (!title) title = null;	
	try {
		p.doAction("play", {url:url, duration:duration, title:title});
	} catch(e) {
		txt="There was an error on this page.\n\n";
	    txt+="Error description: " + e.description + "\n\n";
	    txt+="Error: " + e + "\n\n";
	    txt+="Click OK to continue.\n\n";
	    alert(txt);
	}
}
