<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx"
			   minWidth="500" minHeight="350" creationComplete="init()">

	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.core.FlexGlobals;
			import mx.events.FlexEvent;
			import spark.skins.spark.PanelSkin;

			private var streamer:String;
			private var file:String;
			private var camera:Camera;
			private var microphone:Microphone;
			private var connection:NetConnection;
			private var stream:NetStream;
			private var h264Settings:H264VideoStreamSettings;

			private function publishButtonListener(event:MouseEvent):void {
				if(publishButton.label == 'Publish') {
					publishButton.label = 'Stop';
					connection = new NetConnection();
					connection.connect(streamer);
					connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHander);
				} else {
					publishButton.label = 'Publish';
					stream.close();
					connection.close();
					stream = null;
					connection = null;
				}
			}

			private function netStatusHander(event:NetStatusEvent):void {
				switch(event.info.code) {
					case 'NetConnection.Connect.Success':
						stream = new NetStream(connection);
						stream.attachCamera(camera);
						stream.attachAudio(microphone);
						h264Settings = new H264VideoStreamSettings();
						h264Settings.setProfileLevel(H264Profile.BASELINE, H264Level.LEVEL_3_1);
						stream.videoStreamSettings = h264Settings;
						stream.publish(file, 'live');
						break;
				}
			}

			private function init():void {
				streamer = FlexGlobals.topLevelApplication.parameters.streamer;
				if(streamer == null) {
					Alert.show('Missing flashvars: streamer');
					return;
				}

				file = FlexGlobals.topLevelApplication.parameters.file;
				if(file == null) {
					Alert.show('Missing flashvars: file');
					return;
				}

				publishButton.addEventListener(MouseEvent.CLICK, publishButtonListener);

				camera = Camera.getCamera();
				camera.setMode(640, 480, 30);
				camera.setQuality(131072, 70);

				//videoDisplay.attachCamera(camera);
				var localCam:Video = new Video(640,480);
				localCam.attachCamera(camera);
				videoDisplay.addChild(localCam);

				microphone = Microphone.getMicrophone();
				microphone.setSilenceLevel(0);
				microphone.codec = "Speex";
				microphone.encodeQuality = 6;
			}
		]]>
	</fx:Script>
	<s:BorderContainer x="0" y="0" width="100%" height="100%">
		<s:VideoDisplay width="100%" height="100%" id="videoDisplay"></s:VideoDisplay>
		<s:Button label="Publish" id="publishButton" horizontalCenter="0" bottom="10"></s:Button>
	</s:BorderContainer>
</s:Application>
