function fixExternalLinks() {
	$$('#courant a').each(function(e) {
		if((e.rel != 'radio') && (!e.href.startsWith('mailto:')) && (!e.href.startsWith('#'))) {
			e.target = '_blank';
		}
	});
}

function sendEvent(typ, prm) {
	thisMovie("mpl").sendEvent(typ, prm);
}

function getUpdate(typ, pr1, pr2, pid) {
	if(typ == "item") { 
		currentItem = pr1;
		setTimeout("getItemData(currentItem)", 100);
	}

	if((typ == "state") && (pr1 != undefined)) {
		currentState = pr1;

		if(!startedFlag) {
			startedFlag = true;

			if(startTrackNo != undefined) {
				sendEvent('playitem', startTrackNo);
			}
		}
	}
}

function getItemData(idx) {
	new Ajax.Request(radio[idx], {
    method: 'get',

    onSuccess: function(transport) {
      var response = transport.responseText || "no response text";
      $('courant-ajax').update(response + '<div class="clear"></div>');
     	fixExternalLinks();
    },

    onFailure: function() {
    	$('courant-ajax').update('?I/O Error: ' + radio[idx]);
	  }
  });
}

function initRadio() {
	currentTrackNo = 0;
	
	if($$('#artwork object')[0] == undefined) {
		$$('a.self-radio', 'a[rel="play"]', 'area[rel="play"]').each(function(link) {
			Event.observe(link, 'click', function(event) {
				var link = event.element();
				var isTrackSel = false;
				if(link.href == undefined) link = link.up('a');
				var query = link.href.toQueryParams();
				var pisteId = query['piste'];
	
				if(pisteId) {
					startTrackNo = prog[pisteId];
					isTrackSel = true;
				}
	
				link.blur();
	
				if((isTrackSel) || (isSelf != true)) {
					if(isSelf != true) {
						$('nav-top').scrollTo();
						Effect.BlindDown('radio', { duration: 0.2, queue: 'end' });
	
					} else {
						if(isTrackSel) {
							if(startedFlag) sendEvent('playitem', startTrackNo);
						}
					}
	
					isSelf = true;
				}
	
				event.stop();
			});
		});
	}
}

function thisMovie(movieName) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

var startTrackNo;
var startedFlag;
var isSelf;
