var trackCache = {};

function mediaPlayer(options)
{
	// set the config
	options = options || {};
	options = $.extend({
		container: '#player',
		enablePlayer: false,
		maxItemsDisplayed: 7,
		openLinksInWindow: 'current'
	}, options);

	
	var self	= this;
	var items	= false;
	var ls;

	var c		= $(options.container);
	var miState = 'hide';
	var callbacks = {};
	var currentVolume = 50;
	var pl, playlist;

	// radio player instance
	this.player = {};

	// constructor
	(function()
	{
		// add more-info click functionality
		$('<span />')
			.addClass('more-info')
			.click(function() {
				self.toggleMoreInfo()
			})
			.appendTo($('.current', c));

		// click on artist details, links to artist page
		$('.artist-name, .track-name, a:contains(img)', c).click(function() {
			var href = $(this).parent().find('a').attr('href');
			if($(this).parent().is('.current-text')) {
				href = $('.current a:first', c).attr('href');
			}
			if(options.openLinksInWindow == 'current') {
				window.location.href = href;
			} else if(options.openLinksInWindow == 'parent') {
				window.opener.location.href = href
			}
			
			return false;
		});
		
		if(options.openLinksInWindow == 'parent') {
			$('.more-info-pane a').click(function() {
				var href = $(this).attr('href');
				window.opener.location.href = href;
			});
		}
		
		recycleString($('.previous .artist-name, ', c), 28);
		recycleString($('.track-name', c), 28);

		// initialise media player & controls
		
		if(options.enablePlayer) {
			_initMediaPlayer();
		}

		$('.buy-now a', c).click(function() {
			if($(this).attr('disabled') == 'disabled' || $(this).hasClass('disabled')) return false;
		});

		// handle image errors
		_initImageErrorHandler();
		
		_initLikeTracking();
		// trackCache/like functionality
		

		pl = new PlaylistService();
		pl.registerCallback('updatePlaylist', function(plist) {
			self.setPlaylist(plist);
		});
		
	})();

	function _initImageErrorHandler()
	{
		$('img', c).error(function() {
			
			// reset alt tag
			var defaultImg = '/Layout/Skins/Default/images/default-album.jpg', $img = $(this);
			
			$img.attr('alt', '');
			
			if($img.attr('src').indexOf(defaultImg) == -1) {
				$img.attr('src', defaultImg);
			}
	
		});
	}
		
	function _initLikeTracking()
	{
	    $('.like a', c).click(function (ev) {
	        // stop .net from sending ajax request
	        ev.preventDefault();

	        if ($(this).is('[disabled]')) {
	            return false;
	        }

	        // let's get the track id!
	        var $parent = $(this).parents('div[data-track-id]');
	        if ($parent.length == 0 && $(this).parents('.more-info-pane').length == 1) {
	            $parent = $('.current-text');
	        }
	        var trackId = parseInt($parent.attr('data-track-id'));
	        if (trackId > 0) {
	            _incrementTrack(trackId);
	        }

	        return false;
	    });
	}

	/**
	 * Increment the like count for the supplied track id
	 */
	function _incrementTrack(trackId)
	{
		$.ajax({
			url: '/Handlers/LikeHelperHandler.ashx',
			data: 'trackId='+trackId+'&increment=true',
			dataType: 'text',
			success: function() {
				var newLike = playlist.getByTrackId(trackId).likeCount + 1;
				//trackCache[trackId].likeCount++;
				if($('div[data-track-id='+trackId+'] .like a').length > 0) {
					$('div[data-track-id='+trackId+'] .like a').text('Like ('+newLike+')').attr('disabled', 'disabled');
				} else {
					$('.more-info-pane .like a').text('Like ('+newLike+')').attr('disabled', 'disabled');
				}
			},
			error: function() {
			}
		});
	}
	
	/**
	 * Initialise the media player
	 */
	function _initMediaPlayer()
	{
		self.player = new Player({
			container: options.container,
			eh: function(evnt) {
				if(evnt == 'play') {
					$('.controls .play-pause', c).removeClass('paused');
				}
			}
		});

		$('.controls .play-pause', c).addClass('paused').click(function(event) {
			event.preventDefault();
			$(this).toggleClass('paused');
			self.player.togglePlay();
			return false;
		});
		$('<div id="slider-val">'+currentVolume+'</div>')
			.css({
				position: 'absolute',
				bottom: 16,
				zIndex: 800,
				color: '#FFF',
				padding: 4,
				width: 20,
				textAlign: 'center',
				fontSize: 10
			})
			.hide()
			.appendTo($('.controls', c));

		var sliderOffset = 49;

		$('.controls .volume', c).slider({
			value: currentVolume,
			min: 0,
			max: 100,
			start: function(e, ui) {
				$('#slider-val')
					.text(ui.value)
					.css({
						left: (ui.value + sliderOffset)+'px'
					})
					.fadeIn(100);
			},
			stop: function(e, ui) {
				$('#slider-val')
					.fadeOut(100);
			},
			slide: function(e, ui) {
				self.player.setVolume(ui.value);
				$('#slider-val')
					.text(ui.value)
					.css({
						left: (ui.value + sliderOffset)+'px'
					});
			}
		});
	}
	
	this.setPlaylist = function(plist)
	{
		playlist = plist;
		_execCallback('playlistupdate', [plist]);
		_redraw();
	}
	
	this.getPlaylist = function() 
	{
		return playlist;
	}
	
	function _execCallback(callbackName, args)
	{
		if(callbacks[callbackName]) {
			for(var i = 0; i < callbacks[callbackName].length; i++) {
				callbacks[callbackName][i].apply(this, args);
			}
		}
	}

	this.registerCallback = function(event, callback)
	{
		if(!callbacks[event]) {
			callbacks[event] = [];
		}

		callbacks[event].push(callback);
	}

	/**
	 * Toggle the more information panel
	 */
	this.toggleMoreInfo = function()
	{
		if(miState == 'hide') {
			self.showMoreInfo();
		} else {
			self.hideMoreInfo();
		}
	}

	/**
	 * Show the more information panel for the currently playing item,
	 * only if it's not already shown
	 */
	this.showMoreInfo = function()
	{
		if(miState == 'show') return;
		miState = 'show';
		$('.more-info-pane', c).fadeIn(200);
		$('.current .more-info', c).css({
			backgroundPosition: '0 -36px'
		});
	}

	/**
	 * Hide the more information panel for the currently playing item,
	 * only if it's not already shown
	 */
	this.hideMoreInfo = function()
	{
		if(miState == 'hide') return;
		miState = 'hide';
		$('.more-info-pane', c).fadeOut(200);
		$('.current .more-info', c).css({
			backgroundPosition: '0 0'
		});
	}

	/**
	 * Retrieve the item that is currently playing
	 *
	 * @return object
	 */
	this.getCurrentItem = function()
	{
		return playlist.getCurrent();
	}

	this.redraw = function()
	{
		_redraw();
	}


	// PRIVATE FUNCTIONS
	/**
	 * Retrieve the primary containers dimentions
	 */
	function containerDimentions()
	{
		return {
			height: c.height(),
			width: c.width()
		};
	}

	/**
	 * redraw all the current items
	 */
	function _redraw()
	{
		// @todo refactor for playlist
		var pl = self.getPlaylist(), prev = pl.getPrevious(), next = pl.getNext();
		
		setTimeout(function() {
			_updateItem($('.previous>div, .current, .next>div', c).filter(':eq(0)'), prev[0]);
			setTimeout(function() {
				_updateItem($('.previous>div, .current, .next>div', c).filter(':eq(1)'), prev[1]);
			}, 120);
			setTimeout(function() {
				_updateItem($('.previous>div, .current, .next>div', c).filter(':eq(2)'), prev[2]);
			}, 180);
			
			_updateItem($('.current-text', c), pl.getCurrent());

			_updateItem($('.previous>div, .current, .next>div', c).filter(':eq(4)'), next[0]);
			setTimeout(function() {
				_updateItem($('.previous>div, .current, .next>div', c).filter(':eq(5)'), next[1]);
			}, 120);
			setTimeout(function() {
				_updateItem($('.previous>div, .current, .next>div', c).filter(':eq(6)'), next[2]);
			}, 180);

		}, 1000);
	}

	function _buildArtistUrl(artistName)
	{
		var artistUrl = '/artists/';
		if(artistName != '' && artistName.length > 0) {
			artistUrl += _urlNormalise(artistName) + '/';
		}
		return artistUrl;
	}

	function _updateItem($itmRef, data)
    {
		// no dom reference (.net)
        if($itmRef.length == 0) {
            return;
        }

		if(data && data != undefined && data.artist != '') {
			var 
				artistUrl = _buildArtistUrl(data.artist),
				artistUrlAbs = 'http://'+location.host+artistUrl;
			$itmRef.attr('data-track-id', data.trackId);
			
			var imgUrl = data.image;
			
			var title = data.artist + ' - ' + data.name;
			
			$itmRef
				.attr('data-artist', data.artist)
				.attr('data-track', data.name)
				.find('img')
					.attr('alt', '')
					.attr('src', imgUrl)
					.attr('title', title)
				.end()
				.find('.artist-name')
					.text(data.artist)
				.end()
				.find('.track-name')
					.text(data.name)
				.end()
				.find('.description')
					.text('')
				.end()
				.find('a:first')
					.attr('href', artistUrl)
				.end()
				.find('.like a')
					.removeAttr('disabled')
				.end()
				.find('.like a')
					.text('Like ('+data.likeCount+')')
				.end();
			
			recycleString($itmRef.find('.artist-name'), 26);
			recycleString($itmRef.find('.track-name'), 26);
			
			if(data.status == 'playing') {
			
				var curr = $('.current', c);
			
				curr
					.find('img')
						.attr('alt', '')
						.attr('title', title)
						.attr('src', imgUrl)	
					.end()
					.find('.artist-name')
						.text(data.artist)
					.end()
					.find('.track-name')
						.text(data.name)
					.end()
					.find('.share a')
						.attr('href', artistUrlAbs)
						.attr('title', data.artist + ' on Radar Music')
					.end()
					.find('a:first')
						.attr('href', artistUrl)
					.end()
					.find('.like a')
						.removeAttr('disabled')
                    .end()
                    .find('.like a')
                        .text('Like (' + data.likeCount.toString() + ')')
					.end();

				$('#mini-play .current .like a').text('Like (' + data.likeCount.toString() + ') people');
				if(data.buyurl1 != '') {
					curr.find('.buy-now a').attr('href', data.buyurl1).removeClass('disabled');
				} else {
					curr.find('.buy-now a').attr('href', '#').addClass('disabled');
				}
			} else {
				// buy
				if(data.buyurl1 != '') {
					$itmRef.find('.buy-now a').attr('href', data.buyurl1).removeClass('disabled').end();
				} else {
					$itmRef.find('.buy-now a').attr('href', '#').addClass('disabled').end();
				}
				$itmRef.find('.share a').attr('href', artistUrlAbs).attr('title', data.artist + ' on Radar Music');
			}
			
			$itmRef.find('.share a').removeClass('disabled').removeAttr('disabled');
			$itmRef.find('.like a').removeClass('disabled').removeAttr('disabled');
			$itmRef.find('.buy a').removeClass('disabled').removeAttr('disabled');
		} else {
		
			$itmRef
				.attr('data-artist', data.artist)
				.attr('data-track', data.name)
				.find('img')
					.attr('alt', '')
					.attr('src', '/Layout/Skins/Default/images/default-album.jpg')
					.attr('title', '')
				.end()
				.find('.artist-name')
					.text('')
				.end()
				.find('.track-name')
					.text('')
				.end()
				.find('.description')
					.text('')
				.end()
				.find('a:first')
					.attr('href', '')
				.end()
				.find('.like a')
					.removeAttr('disabled')
				.end()
				.find('.like a')
					.text('Like (' + data.likeCount + ')')
				.end();
		
			$itmRef.find('.share a').addClass('disabled').attr('disabled', 'disabled');
			$itmRef.find('.like a').addClass('disabled').attr('disabled', 'disabled');
			$itmRef.find('.buy a').addClass('disabled').attr('disabled', 'disabled');
		}
	
	}
	
	function _urlNormalise(string)
	{
		string = string.toLowerCase().replace(/([\.\+\?\&]+)/, '');
		string = string.replaceAll('&', '_and_');
		string = string.replaceAll(' ', '-').replaceAll('--', '-');
		return string;
	}

	/**
	 * reduce elements contents until the maxheight has been obtained.
	 */
	function recycleString($element, maxHeight, append)
	{
		append = append || '&hellip;';
		var origHtml = $element.html(), max = 200, i = 0;
		$element.html('<span id="ellip" style="display: inline">'+origHtml+'</span>');
		var ellip = $('#ellip');
		if(ellip.height() > maxHeight) {
			$element.attr('title', ellip.text());
			while(ellip.height() > maxHeight && i < max) {
				i++;
				origHtml = origHtml.substr(0, origHtml.length - 1);
				ellip.html(origHtml+append);
			}
			$element.html(ellip.text());
		} else {
			$element.html(origHtml);
		}
	}
}

/**
 * LightStreamer class
 * 
 * Establishes a connection to lightstreamer
 */
function LightStreamer(options)
{
	options = options || {};
	options = $.extend({
		domain: 'radarmusic.com.au',
		updateCallback: false,
		appName: 'AustereoApp',
		lsDomain: 'http://streamer.radarmusic.com.au/Austereo/ls',
		group: ['Radar'],
		schema: ["NowPlaying","UpComing","LastPlayed"],
		adapter: 'AUSTEREO_ADAPTER_1',
		pushHost: 'streamer.radarmusic.com.au',
		debug: {
			alerts: false
		}
	}, options);

	// private variables
	var lsPage;

	var _lastUpdate;
	
	// public methods

	/**
	 * Establish the connection to lightstreamer
	 */
	this.connect = function()
	{
		_establishLs();
	}

	// private methods

	/**
	 * Establish a new connection to the light streamer server
	 */
	function _establishLs()
	{
		lsPage = new PushPage();

		lsPage.context.setDomain(options.domain);

		lsPage.context.setDebugAlertsOnClientError(options.debug.alerts);
		lsPage.context.setRemoteAlertsOnClientError(options.debug.alerts);

		// handle engine events
		lsPage.onEngineCreation = _onLsEngineCreation;


		// create a new engine
		lsPage.bind();
		lsPage.createEngine(options.appName, options.lsDomain, "SHARE_SESSION", true);

		// establash a new table request to listen to

		var tbl = _lsBuildNVTable(options.group, options.schema, options.adapter, _onLsItemUpdate)
		// handle table events
		lsPage.addTable(tbl, "1");
	}

	/**
	 * Build a ls table
	 * 
	 * @param string group
	 * @param string schema
	 * @param string adapter
	 * @param function callback
	 */
	function _lsBuildNVTable(group, schema, adapter, callback)
	{
		var tbl = new NonVisualTable(group, schema, "MERGE");

		tbl.setSnapshotRequired(true);
		tbl.setCommandLogic(true);
		tbl.setDataAdapter(adapter);

		tbl.onItemUpdate = callback;
		tbl.onStart = function() {
			window.focus();
		}

		return tbl;
	}

	/**
	 * LS Event Handler
	 * When
	 */
	function _onLsEngineCreation(lsEngine)
	{
		lsEngine.context.setDebugAlertsOnClientError(false);
		lsEngine.context.setRemoteAlertsOnClientError(false);

		lsEngine.connection.setLSHost(options.pushHost);
		lsEngine.connection.setLSPort(80);
		lsEngine.connection.setAdapterName("AUSTEREO");

		lsEngine.changeStatus("STREAMING");
	}

	function _onLsItemUpdate(item, itemUpdate)
	{
		// invalid update
		if(itemUpdate == null) return;

		_lastUpdate = itemUpdate;
		_pushUpdate();
	}
	
	this.getLastUpdate = function()
	{
		return _lastUpdate;
	}
	
	this.pushUpdate = function()
	{
		_pushUpdate();
	}
	
	function _pushUpdate()
	{
		if(typeof options.updateCallback == 'function') {
			options.updateCallback(_lastUpdate);
		}
	}
}

function PlaylistService()
{
	var ls, self = this, _callbacks = {}, _playlist, ts, _tsSent = [];
	
	var _current, _previous, _next;
	
	(function() {
		$.log('pl: init');
		ts = new TrackService;
		ts.registerCallback('details', _handle_tsDetails);
		if(_isLsAvailable()) {
			ls = new LightStreamer({
				updateCallback: _handle_lsUpdate
			});
			ls.connect();
		}
	})();
	
	// public methods
	this.setPlaylist = function(playlist)
	{
		_playlist = playlist;
		_runCallback('updatePlaylist', [playlist]);
	}
	
	this.resend = function() 
	{
		_runCallback('updatePlaylist', [_playlist]);
		return true;
	}
	
	this.registerCallback = function(type, callback)
	{
		_registerCallback(type, callback);
	}
	
	this.updateCarts = function()
	{
		_updateCarts();
	}
	
	// private methods
	function _handle_tsDetails(cartId, details)
	{
		$.log('pl: track update');
		_returnSentCart(cartId); 
		// find the item we're trying to update
		// @todo refactor this dodgy code
		if(_current.cart == cartId) {
			_current = $.extend({
				likeCount: details.likeCount,
				trackId: details.trackId,
				image: details.url
			}, _current);
		} else {
			// search others
			found = false
			for(var i = 0; i < _next.length; i++) {
				if(_next[i].cart == cartId) {
					found = true;
					_next[i] = $.extend({
						likeCount: details.likeCount,
						trackId: details.trackId,
						image: details.url
					}, _next[i]);
				}
			}
			if(!found) {
				for(var i = 0; i < _previous.length; i++) {
					if(_previous[i].cart == cartId) {
						found = true;
						_previous[i] = $.extend({
							likeCount: details.likeCount,
							trackId: details.trackId,
							image: details.url
						}, _previous[i]);
					}
				}
			}
		}
		
		// check if the playlist is ready
		if(_areAllCartsReturned()) {
			$.log('pl: create playlist');
			self.setPlaylist(new Playlist(_previous, _current, _next));
		}
	}
	
	function _areAllCartsReturned()
	{
		return _tsSent.length === 0;
	}
	
	function _returnSentCart(cartId)
	{
		var newTsSent = [], i;
		for(i = 0; i < _tsSent.length; i++) {
			if(_tsSent[i] != cartId) {
				newTsSent.push(_tsSent[i]);
			}
		}
		_tsSent = newTsSent;
	}
	
	/**
	 * handle the lightstreamer update call
	 */
	function _handle_lsUpdate(itemUpdate)
	{
		$.log('pl: ls update');
		_current	= $.parseJSON(itemUpdate.getNewValue("NowPlaying")).list[0];
		_next		= $.parseJSON(itemUpdate.getNewValue("UpComing")).list.slice(0, 3);
		_previous	= $.parseJSON(itemUpdate.getNewValue("LastPlayed")).list.slice(0, 3);

		var i;
		$.log('pl: ls update tracks');
		$.log('current', _current);
		$.log('next', _next);
		$.log('previous',_previous);
		
		// update all items with the trackservicedata
		_updateCarts();

	}
	
	function _updateCarts()
	{
		_sendTsRequest(_current);
		for(i = 0; i < _next.length; i++) {
			_sendTsRequest(_next[i]);
		}
		for(i = 0; i < _previous.length; i++) {
			_sendTsRequest(_previous[i]);
		}
	}
	
	/**
	 * Send a request to the track service. Any requests are stored to 
	 * know when the sevice returns the results
	 */
	function _sendTsRequest(item)
	{
		if(ts.getDetailsByCart(item)) {
			_tsSent.push(item.cart);
		}
	}
	
	/**
	 * Check if lightstreamer is available in the current environment
	 */
	function _isLsAvailable()
	{
        return window.location.host.indexOf('radarmusic.com.au') >= 0 && typeof PushPage == 'function';
	}
	
	function _registerCallback(type, callback)
	{
		if(!_callbacks[type]) {
			_callbacks[type] = [];
		}
		_callbacks[type].push(callback);
	}
	
	function _runCallback(type, args)
	{
		if(_callbacks[type]) {
			var i, len = _callbacks[type].length;
			for(i = 0; i < len; i++) {
				_callbacks[type][i].apply(this, args);
			}
		}
	}
}

/**
 * Playlist data
 */
function Playlist(previous, current, next)
{
	var _previous = previous, _current = current, _next = next;
	
	this.getCurrent = function() 
	{
		return _current;
	}
	
	this.getPrevious = function() 
	{
		return _previous;
	}
	
	this.getNext = function() 
	{
		return _next;
	}
	
	/**
	 * Search the cart item based on its id
	 */
	this.getCart = function(cartId)
	{
		var list = _getList(), i, len = list.length;
		for(i = 0; i < len; i++) {
			if(list[i].cart == cartId) {
				return list[i];
			}
		}
		return false;
	}

	this.getByTrackId = function (trackId) {
	    var list = _getList(), i, len = list.length;
	    for (i = 0; i < len - 1; i++) {
	        if (list[i].trackId == trackId) {
	            return list[i];
	        }
	        else {
	            
	        }
	    }
	    return false;
	}
	
	/**
	 * Get entire list, regardless of state
	 */
	this.getList = function()
	{
		return _getList();
	}
	
	function _getList() {
	    var list = _previous;
	    list.push(_current);
//	    list = $.merge(list, _current);
		list = $.merge(list, _next);
		return list;
	}
}

/**
 * Request additional track details from the web service
 */
function TrackService(options)
{
	options = options || {};
	options = $.extend({
		defaultImageUrl: '/Layout/Skins/Default/images/default-album.jpg'
	}, options);
	var _cache = {}, _callbacks = {};
	
	(function() {
		$.log('ts: init');
	})();
	
	
	this.getDetailsByCart = function(cart)
	{
		return _getDetailsByCart(cart);
	}
	
	/**
	 * register a callback. this allows multiple calls to be made (async)
	 */
	this.registerCallback = function(type, callback)
	{
		_registerCallback(type, callback);
	}
	
	// private methods
	function _getDetailsByCart(item)
	{
		var cartId = item.cart;
		$.log('ts: get cart '+cartId);
		if(cartId == undefined || cartId == '') {
			$.log('ts: cart fail');
			//_runCallback('details', [cartId]);
			return false;
		}
		if(!_cache[cartId]) {
			_getDataFromDotNet(item, function(data) {
				_cache[cartId] = data;
				_runCallback('details', [cartId, _cache[cartId]]);
			});
		} else {
			// emulate ajax response time
			setTimeout(function() {
				_runCallback('details', [cartId, _cache[cartId]]);
			}, 30);
		}
		return true;
	}
	
	function _getDataFromDotNet(item, success)
	{
		$.ajax({
			url: '/handlers/playlisthelperhandler.ashx',
			data: 'cart='+item.cart+'&name='+item.title,
			dataType: 'xml',
			success: function(xmlData) {
				var trackId, url, count, description = '';
				// check the response
				if($('tracks>track', xmlData).length == 0) {
					trackId = 0;
					url = options.defaultImageUrl;
					count = 0;
				} else {
					trackId	= parseInt($('tracks>track:first>trackid', xmlData).text()),
					url		= $('tracks>track:first>albumcoverurl', xmlData).text(),
					count	= parseInt($('tracks>track:first>count', xmlData).text());
				}
			
				// callback
				success.apply(this, [{
					trackId: trackId,
					url: url,
					likeCount: count,
					description: description
				}]);
			}
		});
	}
	
	function _registerCallback(type, callback)
	{
		if(!_callbacks[type]) {
			_callbacks[type] = [];
		}
		_callbacks[type].push(callback);
	}
	
	function _runCallback(type, args)
	{
		if(_callbacks[type]) {
			var i, len = _callbacks[type].length;
			for(i = 0; i < len; i++) {
				_callbacks[type][i].apply(this, args);
			}
		}
	}
}

/**
 * Flash Radio Player
 */
function Player(options)
{
	options = options || {};

	options = $.extend({
		container: 'body',
		stream: {
			name: 'radar',
			rtmp: 'rtmp://66.70.119.243'
		},
		eh: false
	}, options);

	var $c = $(options.container);

	this.playing = false;

	function _init()
	{
		// inject player into the dom
	    if (swfobject.hasFlashPlayerVersion('9.0.0')) {
	        initFlashPlayer();
	    } else {
	        initInstallFlash();
	    }
    }

    function initInstallFlash() 
    {
        $('<div class="no-flash"><a href="http://get.adobe.com/flashplayer/" target="_blank">Install Flash. Aquire Audio</a></div>').appendTo($c);
    }

    /**
     *
     */
    function initFlashPlayer() 
    {
        // register the flash event callback handler
        window.fsCallback = _flashCallback;

        // inject flash
        $('<div id="swfplayer" />')
            .appendTo($c);

        swfobject.embedSWF('/Flash/Radar_Streaming_Player.swf', 'swfplayer', 1, 1, '9.0.0', '', {
            streamName: options.stream.name,
            streamRTMP: options.stream.rtmp
        }, {
            wmode: 'transparent'
        }, {
            id: 'swfswfplayer',
            width: 1,
            height: 1
        });
    }

    /**
    * Handles the callback from the flash object
    */
	function _flashCallback(eventType)
	{
		if(options.eh) {
			options.eh(eventType);
		}
		switch(eventType) {
			case 'play':
				this.playing = true;
				this.setVolume(currentVolume);
				break;
		}
		
	}

	this.setVolume = function(volume)
	{
		try {
			swfobject.getObjectById('swfswfplayer').setVolumePercent(volume);
		} catch(e) {
			
		}
	}

	this.togglePlay = function()
	{
		if(this.playing) {
			this.playing = false;
		}
		swfobject.getObjectById('swfswfplayer').togglePause();
	}

	_init();
}
