var $j = jQuery.noConflict();

var id = false;
/*
var haveqt;
if (navigator.plugins) {
	for (i=0; i < navigator.plugins.length; i++ ) {
		if (navigator.plugins[i].name.indexOf("QuickTime") >= 0){ 
			haveqt = true; 
			break;
		}
	}
}
if ((navigator.appVersion.indexOf("Mac") > 0) && (navigator.appName.substring(0,9) == "Microsoft") && (parseInt(navigator.appVersion) < 5) ){ 
	haveqt = true;
}
*/

$j(document).ready(function () {
	$j('.preview').each(function(){
		$j(this).click(preview);	
	});
});


function preview(){
	if(typeof(pageTracker) != 'undefined')	pageTracker._trackPageview('/preview/'+ id);
	id = $j(this).attr('id'); // set the global
	
	$j('#play_' + id).hide(); // Hide the "play" button
	$j('#play_' + id).after('<img src="/images/loading.gif" id="loading_'+ id + '" onclick="qt_stop(\'' + id + '\');" title="Click to stop" class="pointer" />'); // Show a 'stop' button

	
	var terms = $j(this).attr('title').replace('Listen to ', '');
	
	$j.getJSON('http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term='+terms.replace(' ', '+')+'&media=music&country=GB&callback=?', function(data){
		//console.log(data);
		if(data.results[0]) embed(data.results[0].previewUrl);
		else{
			//alert('not available');
			$j('#loading_' + id).hide(); // Hide the "loading" spinner
			$j('#play_' + id).after('<img src="/images/cross.png" alt="" />'); // Show a cross

		}
	});
	
}

function show_play(track_id){
	$j('#stop_'+track_id).remove();
	$j('#play_'+track_id).show();
}

function embed(uri){
	html = QT_GenerateOBJECTText_XHTML(uri, 0, 0, '', 'emb#NAME' , 'player_' + id , 'obj#id' , 'player_' + id, 'autoplay', true, 'enablejavascript', true);	//console.log(html);
	$j('#play_' + id).after('<span id="playerwrapper_'+ id +'">' + html + '</span>');
	$j('#loading_' + id).hide(); // Hide the "loading" spinner
	$j('#play_' + id).after('<img src="/images/stop.png" id="stop_'+id+'" onclick="qt_stop(\'' + id + '\');" title="Click to stop" class="pointer" />'); // Show a 'stop' button
	// Set it to play button again after 30 secs
	var t = setTimeout('qt_stop("'+id+'")', 31000);
}

function qt_stop(track_id){
	
	//alert( track_id );
	//console.log($j("object#player_"+track_id));

	if($j("embed[name='player_"+track_id+"']")[0]) $j("embed[name='player_"+track_id+"']")[0].Stop(); 
	
	$j('param[value=player_'+track_id+']').parent().remove();
	$j('#playerwrapper_'+track_id).remove(); // Remove the div holding the embed
	$j('#stop_'+track_id).remove(); 		// Remove the "stop" option
	$j('#play_'+track_id).show(); 			// Show the "play" option again
}

