<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2006 Renaun Erickson (http://renaun.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ignore
-->
<!--

The application implemented demonstrates the basics of creating a Video Conference appliction using Flex and FMS.

The Logger class used in the classes here can be found at: http://renaun.com/blog/flex-components/comp-logger/

To see the application run go to http://renaun.com/flex2/fms/VideoConferenceWDDJ/FlexVideoMain.html
To see the application's source code go to http://renaun.com/flex2/fms/VideoConferenceWDDJ/srcview/

-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns="*"
    initialize="haveCamera = ( Camera.getCamera() != null )"
    layout="vertical" viewSourceURL="srcview/index.html">
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            
            [Bindable]
            private var haveCamera:Boolean;
            
            [Bindable]
            public var nc:NetConnection;
            
            public var users_so:SharedObject;
            [Bindable]
            public var dpUsers:ArrayCollection;
            
            /**
             *  This function creates the FMS connection and sets the Status event handler
             */
            public function createConnection():void
            {
                Logger.debug( "MAIN:createConnection" );
                // Check the user name length
                if( txtName.text.length > 0 ) {
                    // Create Connection and setup Events
                    nc = new NetConnection();
                    nc.objectEncoding = ObjectEncoding.AMF0;
                    nc.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
                    // A simple Identifier for the asc side
                    var identifier:String = txtName.text;
                    while( identifier.search( " " ) > 0 )
                        identifier = identifier.replace( " ", "_" );
                    nc.connect( "rtmp:/flex_videoconference/", txtName.text, identifier );
                } else {
                    Alert.show( "Please provide a name for the video chat connection!" );
                }
            }        
            
            /**
             *    Waits for any status from the connection to FMS
             */
            public function netStatusHandler( event:NetStatusEvent ):void
            {
                Logger.debug( "MAIN:connectionSuccess:Success" );                
                switch( event.info.code ) {
                    case "NetConnection.Connect.Success":
                        // Connection succeeded now create components
                        connectComponents();
                        // Change to Video view
                        vsMain.selectedChild = pnlVideo;
                    break;
                    case "NetConnection.Connect.Rejected":
                        Alert.show( "The number of users has been limited for this demo, please try again in a few minutes.", "Restricted Usage" );
                    break;                    
                }

            }

            /**
             *    Method called to create the components
             */
            public function connectComponents():void
            {
                Logger.debug( "MAIN:connectComponents" );
                // Simple User shared object and event handling
                SharedObject.defaultObjectEncoding  = flash.net.ObjectEncoding.AMF0;
                users_so = SharedObject.getRemote("users_so", nc.uri, false);
                users_so.addEventListener( SyncEvent.SYNC, usersSyncHandler );
                users_so.connect( nc );
            }

            /**
             *    Listens for any change to the users shared object
             */
            public function usersSyncHandler( event:SyncEvent ):void
            {
                Logger.debug( "MAIN:usersSyncHandler" + event.target.data );
                var results:Object = event.target.data;
                var usersArray:Array = new Array();
                for( var a:String in results ) {
                    var obj:Object = new Object();
                    obj.name = results[ a ];
                    obj.identifier = a;
                    usersArray.push( obj );
                }
                dpUsers = new ArrayCollection( usersArray );
            }

            /**
             *    Closes connections and handles the logout
             */
            public function logout():void
            {
                Logger.debug( "MAIN:connectComponents" );
                users_so.close();
                nc.close();
                dpUsers = null;
                users_so = null;
                nc = null;
                vsMain.selectedChild = pnlLogin;
            }            
            
        ]]>
    </mx:Script>

    <mx:ViewStack 
        id="vsMain"
        width="100%" height="100%">
        <!-- Login Panel -->
        <mx:Panel 
            id="pnlLogin"
            title="Flex and FMS Video Conference Demo">
            <mx:Form>
                <mx:FormItem label="Name:">
                    <mx:TextInput 
                        id="txtName"
                        enabled="{ haveCamera }" />
                </mx:FormItem>
                <mx:Button 
                    label="Submit"
                    click="createConnection()"
                    enabled="{ haveCamera }" />
                <mx:Label text="{ ( haveCamera ) ? '':'Now camera is found!' }" />
            </mx:Form>
        </mx:Panel>
        <!-- Video Panel -->
        <mx:Panel 
            id="pnlVideo"
            width="100%" height="100%"
            title="Welcome { txtName.text }!"
            layout="vertical">

            <mx:Tile 
                height="100%" width="100%">
                <mx:Repeater 
                    id="rpUsers"
                    dataProvider="{ dpUsers }">
                    <VideoPod 
                        nc="{ nc }"
                        isSender="{ rpUsers.currentItem.name == txtName.text }"
                        userItem="{ rpUsers.currentItem }" />
                </mx:Repeater>
            </mx:Tile>
            <mx:Label
                width="100%"
                text="Video Quality is set really low to not use up all my bandwidth!"
                color="0xFF0000" />
            <mx:ControlBar>
                <mx:Button 
                    label="Logout"
                    click="logout()"/>                
            </mx:ControlBar>
        </mx:Panel>
        
    </mx:ViewStack>

</mx:Application>