// JS Player code
var Player = {
	
	start: function() {
		
		// Load data asynchronously
		$.getJSON( "config_json_production.txt", // Fetch JSON formatted data (could be generated on server-side by PHP or any server-side script)
			{},
			function( data ) {
				carousel_total = data.total; // Total number of carousel items
				carousel_channels = data.items; // The array of carousel item objects
				Player.initCarousel( carousel_total, carousel_channels ); // Initialize carousel
				Player.initVideoStream(carousel_channels[0][0]);
			}
		);
		
		Player.initScroller(); // Initialize news scroller
	},
	
	// This function accepts number of arguments needed for the different video streams
	initVideoStream: function( channel ) {
		Player.getStream( channel );
		$('#header h2').text( "Currently playing: " + channel.currently );
		$('#footer-right a').attr({ 'href': channel.sponsorUrl, 'title': channel.sponsor });
		$('#footer-right a').text( channel.sponsor );
	},
	
	// Here we are fetching different video stream via streamFile argument
	getStream: function( args ) {
		
		// Here we can define default flashvars, we could also extend with additional arguments if needed.
		// In case additional arguments are needed, don't forget to generate the arguments on the server-side as well.
		var default_flashvars = {
			file: "mp4:museum.sdp",
			type: "rtmp",
			bufferLength: "15",
			start: "0",
			streamer: "rtmp://83.170.115.98/live",
			duration: "3000",
			controlBar: "bottom",
			stretching: "exactfit",
			displayclick: "link",
			link: "http://www.visitshetland.com",
			logo: "",
			image: "",
			autostart: "true"		
		};
		
		var flashvars = args.flashVars;
		var flashvars = flashvars || default_flashvars;
		
		for(var i in default_flashvars) {
			if(typeof flashvars[i] == "undefined") { flashvars[i] = default_flashvars[i] };
		}
		
		var flashvars_string =	"&file=" + flashvars.file;
		flashvars_string += ( flashvars.type.length > 0 ) ? "&type=" + flashvars.type : "";
		flashvars_string += ( flashvars.bufferLength.length > 0 ) ? "&bufferlength=" + flashvars.bufferLength : "";
		flashvars_string += ( flashvars.start.length > 0 ) ? "&start=" + flashvars.start : "";
		flashvars_string += ( flashvars.streamer.length > 0 ) ? "&streamer=" + flashvars.streamer : "";
		flashvars_string += ( flashvars.controlBar.length > 0 ) ? "&controlbar=" + flashvars.controlBar : "";
		flashvars_string += ( flashvars.stretching.length > 0 ) ? "&stretching=" + flashvars.stretching : "";
		flashvars_string += ( flashvars.displayclick.length > 0 ) ? "&displayclick=" + flashvars.displayclick : "";
		flashvars_string += ( flashvars.link.length > 0 ) ? "&link=" + flashvars.link : "";
		flashvars_string += ( flashvars.logo.length > 0 ) ? "&logo=" + flashvars.logo : "";
		flashvars_string += ( flashvars.image.length > 0 ) ? "&image=" + flashvars.image : "";
		flashvars_string += ( flashvars.autostart.length > 0 ) ? "&autostart=" + flashvars.autostart : "";
		
		var allowScriptAccess = args.allowScriptAccess || "always";
		var allowFullScreen =  args.allowFullScreen || "true";
		var wMode = args.wMode || "opaque";
		
		var so = new SWFObject('player.swf','ply','640','380','9');
		so.addParam('allowscriptaccess', allowScriptAccess);
		so.addParam('allowfullscreen', allowFullScreen);
		so.addParam('wmode', wMode);
		so.addParam('flashvars', flashvars_string );
		so.write('player_container');
	},
	
	// Initialize carousel function, accepts total number of carousel items and actual items (array of carousel item objects)
	initCarousel: function( total, channels ) {
		
		$('#cam_carousel').jcarousel({
			itemLoadCallback: function( carousel, state ) {
				
				// Check if the requested items already exist
				if (carousel.has(carousel.first, carousel.last)) { return; }
				
				carousel.size(parseInt(total));
				$.each(channels, function(i, channel) {
					carousel.add( carousel.first+i, Player.cam_carousel_getItemHTML( channel ));
				});

			}
		});
	},
	
	// Item html creation helper.
	cam_carousel_getItemHTML: function( channel ) {
		var container = $("<span></span>").attr('class', 'channel');
		
		var main_stream = $("<a></a>").attr({
			'class': 'description',
			'href': '#',
			'title': channel[0].streamDescription
		}).text(channel[0].streamName).click( function(event) { event.preventDefault; stopVideoPlayer(); Player.initVideoStream(channel[0]) }); //RL added stopVideoPlayer
		
		var image = $("<img></img>").attr({
			'src': channel[0].image,
			'alt': channel[0].streamDescription
		});
				
		// Are there more than 1 streams per channel?
		if(channel.length > 1) {  // Yes, create additional links
			var links = $("<span></span>").attr('class','stream_links');
			container.append(image).append(main_stream);
			
			$.each(channel, function(i, stream) {
				if( i > 0 ) { // Don't create link for the first stream
					var stream_link = $("<a></a>").attr({
						'href': '#',
						'title': stream.streamDescription
					}).text(i.toString()).click( function(event) { event.preventDefault; stopVideoPlayer(); Player.initVideoStream(stream) });
					
					links.append(stream_link);
					if(i+1 < channel.length) { stream_link.after(" "); }
				}
			});
			
			container.append(links);
			
		} else { // No, create only the channel title
			container.append(image).append(main_stream);
		}
		
		return container;
		
	},
	
	// Create news scroller items and initialize scroller
	initScroller: function() {
		var news_item_elem = null;
		
		$.ajax({
                url: "rss_json.php",
                dataType : 'json',
                data : {},
                success : function(feed, textStatus) {
								$.each( feed[0].items, function( i, news_item ) {
									// create paragraph or link element based on whether the feed contains link or is just a text
									news_item_elem = ( news_item.permalink != "undefined" && news_item.permalink != "" && news_item.permalink != feed[0].permalink ) ? $("<a></a>").attr({ 'href': news_item.permalink, 'title': news_item.description, 'target': '_blank' }).text(news_item.title) : $("<p></p>").text(news_item.title);
									$('#scroller').append( news_item_elem );
								});
							$('#scroller').cycle({
								fx: 'scrollDown', 
								speed:    500, 
								timeout:  4000,
								pause: 1
							});
				
                },
                error : function(request, textStatus, err) {
									var news_item_elem = $("<p></p>").text("Feed is unavailable at the moment...");
									$('#scroller').append( news_item_elem );			
								
							$('#scroller').cycle({
								fx: 'scrollDown', 
								speed:    500, 
								timeout:  4000,
								pause: 1
							});
                }
            });
	}
	
}

function stopVideoPlayer() {
	if( mediaPlayer != null ) { mediaPlayer.sendEvent("STOP"); }; // Check if mediaPlayer is instantiated and send the STOP event to it
}

var mediaPlayer = null;
var headerData;
var metaData;

function playerReady(obj) {
	mediaPlayer = document.getElementById(obj['id']);
	mediaPlayer.addModelListener('META','getMetadata');
}

function getMetadata(obj) {
	if(obj.type == 'metadata') {
		metaData = obj;
	}
	if(obj.type == 'headerdata') {
		headerData = obj;
	}
	if((obj.type == 'metadata' || obj.type == 'headerdata') && metaData.StreamTitle != null) {
		$('#header h2').text( "Currently playing: " + metaData.StreamTitle );
	}
}

$(document).ready( Player.start );
$(window).unload( stopVideoPlayer );

