#					-*- shell-script -*-
##
## children.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##

m4_defun([URBI_CHILDREN_PREPARE],
[

# run TITLE COMMAND...
# --------------------
# Run the COMMAND... (which may use its stdin) and output detailed
# logs about the execution.
#
# Leave un $run_prefix.{cmd, out, sta, err, val} the command, standard
# output, exit status, standard error, and instrumentation output.
run_counter=0
run_prefix=
run ()
{
  local title=$[1]
  run_prefix=$run_counter-$(echo $[1] |
			     sed -e 's/[[^a-zA-Z0-9][^a-zA-Z0-9]]*/-/g;s/-$//')
  run_counter=$(($run_counter + 1))
  shift

  echo "$[@]"> $run_prefix.cmd

  # Beware of set -e.
  local sta
  if "$[@]" >$run_prefix.out 2>$run_prefix.err; then
    sta=0
  else
    sta=$?
    title="$title FAIL ($sta)"
  fi
  echo $sta >$run_prefix.sta

  rst_subsection "$me: $title"
  rst_run_report "$title" "$run_prefix"

  return $sta
}

## ------------------------------------------------- ##
## PID sets -- Lower layer for children management.  ##
## ------------------------------------------------- ##

# pids_alive PIDS
# ---------------
# Return whether some of the PIDs point to alive processes,
# i.e., return 1 iff there are no children alive.
pids_alive ()
{
  local pid
  for pid
  do
    # Using "ps PID" to test whether a processus is alive is,
    # unfortunately, non portable.  OS X Tiger always return 0, and
    # outputs the ps-banner and the line of the processus (if there is
    # none, it outputs just the banner).  On Cygwin, "ps PID" outputs
    # everything, and "ps -p PID" outputs the banner, and the process
    # line if alive.  In both cases it exits with success.
    #
    # We once used grep to check the result:
    #
    # ps -p $pid | grep ["^[	]*$pid[^0-9]"]
    #
    # Unfortunately sometimes there are flags displayed before the
    # process number.  Since we never saw a "ps -p PID" that does not
    # display the title line, we expect two lines.
    case $(ps -p $pid | wc -l | sed -e '[s/^[	 ]*//]') in
      1) # process is dead.
	 ;;
      2) # Process is live.
	 return 0;;
      *) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
    esac
  done
  return 1
}

# pids_kill PIDS
# --------------
# Kill all the PIDS.  This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
pids_kill ()
{
  local pid
  for pid
  do
    if pids_alive $pid; then
      local name
      name=$(cat $pid.name)
      echo "Killing $name (kill -ALRM $pid)"
      kill -ALRM $pid 2>&1 || true
    fi
  done
}

# pids_wait TIMEOUT PIDS
# ----------------------
pids_wait ()
{
  local timeout=$[1]
  shift

  if $INSTRUMENT; then
    timeout=$(($timeout * 5))
  fi

  while pids_alive "$[@]"; do
    if test $timeout -le 0; then
      pids_kill "$[@]"
      break
    fi
    sleep 1
    timeout=$(($timeout - 1))
  done
}

## ---------- ##
## Children.  ##
## ---------- ##

# rst_run_report $TITLE $FILE-PREFIX
# ----------------------------------
# Report the input and output for $FILE-PREFIX.
rst_run_report ()
{
  local title=$[1]
  case $title in
    ?*) title="$title ";;
  esac

  rst_pre "${title}Command"   $[2].cmd
  rst_pre "${title}Pid"       $[2].pid
  rst_pre "${title}Status"    $[2].sta
  rst_pre "${title}Input"     $[2].in
  rst_pre "${title}Output"    $[2].out
  rst_pre "${title}Error"     $[2].err
  rst_pre "${title}Valgrind"  $[2].val
}

# children_alive [CHILDREN]
# -------------------------
# Return whether there are still some children running,
# i.e., return 1 iff there are no children alive.
children_alive ()
{
  local pid
  local pids
  pids=$(children_pid "$[@]")
  for pid in $pids
  do
    # Using "ps PID" to test whether a processus is alive is,
    # unfortunately, non portable.  OS X Tiger always return 0, and
    # outputs the ps-banner and the line of the processus (if there is
    # none, it outputs just the banner).  On Cygwin, "ps PID" outputs
    # everything, and "ps -p PID" outputs the banner, and the process
    # line if alive.  In both cases it exits with success.
    #
    # We once used grep to check the result:
    #
    # ps -p $pid | grep ["^[	]*$pid[^0-9]"]
    #
    # Unfortunately sometimes there are flags displayed before the
    # process number.  Since we never saw a "ps -p PID" that does not
    # display the title line, we expect two lines.
    case $(ps -p $pid | wc -l | sed -e '[s/^[	 ]*//]') in
      1) # process is dead.
	 ;;
      2) # Process is live.
	 return 0;;
      *) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
    esac
  done
  return 1
}

# children_clean [CHILDREN]
# --------------------------
# Remove the children files.
children_clean ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    rm -f $i.{cmd,pid,sta,in,out,err,val}
  done
}

# children_pid [CHILDREN]
# -----------------------
# Return the PIDs of the CHILDREN (whether alive or not).
children_pid ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    test -f $i.pid ||
      error SOFTWARE "children_pid: cannot find $i.pid."
    cat $i.pid
  done
}

# children_register NAME
# ----------------------
# It is very important that we do not leave some random exit status
# from some previous runs.  Standard output etc. are not a problem:
# they *are* created during the run, while *.sta is created *only* if
# it does not already exists (this is because you can call "wait" only
# once per processus, so to enable calling children_harvest multiple
# times, we create *.sta only if it does not exist).
#
# Creates NAME.pid which contains the PID, and PID.name which contains
# the name.
children_register ()
{
  test $[#] -eq 1
  rm -f $[1].sta
  children="$children $[1]"
  echo $! >$[1].pid
  echo $[1] >$!.name
}

# children_report [CHILDREN]
# --------------------------
# Produce an RST report for the CHILDREN.
children_report ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    rst_run_report "$i" "$i"
  done
}

# children_kill [CHILDREN]
# ------------------------
# Kill all the children.  This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
children_kill ()
{
  local pids
  pids=$(children_pid "$[@]")
  pids_kill "$pids"
}

# children_harvest [CHILDREN]
# ---------------------------
# Report the exit status of the children.  Can be run several times.
# You might want to call it once in the regular control flow to fetch
# some exit status, but also in a trap, if you were interrupted.  So
# it is meant to be callable multiple times, which might be a danger
# wrt *.sta (cf., children_register).
children_harvest ()
{
  # Harvest exit status.
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    # Don't wait for children we already waited for.
    if ! test -e $i.sta; then
      local pid
      pid=$(children_pid $i)
      # Beware of set -e.
      local sta
      if wait $pid 2>&1; then
	sta=$?
      else
	sta=$?
      fi
      echo "$sta$(ex_to_string $sta)" >$i.sta
    fi
  done
}

# children_status [CHILDREN]
# --------------------------
# Return the exit status of CHILD.  Must be run after harvesting.
# If several CHILD are given, return the highest exit status.
children_status ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local res=0
  local i
  for i
  do
    # We need to have waited for these children.
    test -f $i.sta ||
      error SOFTWARE "children_status: cannot find $i.sta." \
		     "Was children_harvest called?"         \
		     "Maybe children_cleanup was already called..."
    local sta=$(sed -n '1{s/^\([[0-9][0-9]]*\).*/\1/;p;q;}' <$i.sta)
    if test $res -lt $sta; then
      res=$sta
    fi
  done
  echo $res
}

# children_wait TIMEOUT [CHILDREN]
# --------------------------------
# Wait for the registered children, and passed TIMEOUT, kill the remaining
# ones.  TIMEOUT is increased by 5 if instrumenting.
children_wait ()
{
  local timeout=$[1]
  shift
  local pids
  pids=$(children_pid "$[@]")
  pids_wait $timeout $pids
}

])

#					-*- shell-script -*-
##
## children.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##

m4_defun([URBI_CHILDREN_PREPARE],
[

# run TITLE COMMAND...
# --------------------
# Run the COMMAND... (which may use its stdin) and output detailed
# logs about the execution.
#
# Leave un $run_prefix.{cmd, out, sta, err, val} the command, standard
# output, exit status, standard error, and instrumentation output.
run_counter=0
run_prefix=
run ()
{
  local title=$[1]
  run_prefix=$run_counter-$(echo $[1] |
			     sed -e 's/[[^a-zA-Z0-9][^a-zA-Z0-9]]*/-/g;s/-$//')
  run_counter=$(($run_counter + 1))
  shift

  echo "$[@]"> $run_prefix.cmd

  # Beware of set -e.
  local sta
  if "$[@]" >$run_prefix.out 2>$run_prefix.err; then
    sta=0
  else
    sta=$?
    title="$title FAIL ($sta)"
  fi
  echo $sta >$run_prefix.sta

  rst_subsection "$me: $title"
  rst_run_report "$title" "$run_prefix"

  return $sta
}

## ------------------------------------------------- ##
## PID sets -- Lower layer for children management.  ##
## ------------------------------------------------- ##

# pids_alive PIDS
# ---------------
# Return whether some of the PIDs point to alive processes,
# i.e., return 1 iff there are no children alive.
pids_alive ()
{
  local pid
  for pid
  do
    # Using "ps PID" to test whether a processus is alive is,
    # unfortunately, non portable.  OS X Tiger always return 0, and
    # outputs the ps-banner and the line of the processus (if there is
    # none, it outputs just the banner).  On Cygwin, "ps PID" outputs
    # everything, and "ps -p PID" outputs the banner, and the process
    # line if alive.  In both cases it exits with success.
    #
    # We once used grep to check the result:
    #
    # ps -p $pid | grep ["^[	]*$pid[^0-9]"]
    #
    # Unfortunately sometimes there are flags displayed before the
    # process number.  Since we never saw a "ps -p PID" that does not
    # display the title line, we expect two lines.
    case $(ps -p $pid | wc -l | sed -e '[s/^[	 ]*//]') in
      1) # process is dead.
	 ;;
      2) # Process is live.
	 return 0;;
      *) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
    esac
  done
  return 1
}

# pids_kill PIDS
# --------------
# Kill all the PIDS.  This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
pids_kill ()
{
  local pid
  for pid
  do
    if pids_alive $pid; then
      local name
      name=$(cat $pid.name)
      echo "Killing $name (kill -ALRM $pid)"
      kill -ALRM $pid 2>&1 || true
    fi
  done
}

# pids_wait TIMEOUT PIDS
# ----------------------
pids_wait ()
{
  local timeout=$[1]
  shift

  if $INSTRUMENT; then
    timeout=$(($timeout * 5))
  fi

  while pids_alive "$[@]"; do
    if test $timeout -le 0; then
      pids_kill "$[@]"
      break
    fi
    sleep 1
    timeout=$(($timeout - 1))
  done
}

## ---------- ##
## Children.  ##
## ---------- ##

# rst_run_report $TITLE $FILE-PREFIX
# ----------------------------------
# Report the input and output for $FILE-PREFIX.
rst_run_report ()
{
  local title=$[1]
  case $title in
    ?*) title="$title ";;
  esac

  rst_pre "${title}Command"   $[2].cmd
  rst_pre "${title}Pid"       $[2].pid
  rst_pre "${title}Status"    $[2].sta
  rst_pre "${title}Input"     $[2].in
  rst_pre "${title}Output"    $[2].out
  rst_pre "${title}Error"     $[2].err
  rst_pre "${title}Valgrind"  $[2].val
}

# children_alive [CHILDREN]
# -------------------------
# Return whether there are still some children running,
# i.e., return 1 iff there are no children alive.
children_alive ()
{
  local pid
  local pids
  pids=$(children_pid "$[@]")
  for pid in $pids
  do
    # Using "ps PID" to test whether a processus is alive is,
    # unfortunately, non portable.  OS X Tiger always return 0, and
    # outputs the ps-banner and the line of the processus (if there is
    # none, it outputs just the banner).  On Cygwin, "ps PID" outputs
    # everything, and "ps -p PID" outputs the banner, and the process
    # line if alive.  In both cases it exits with success.
    #
    # We once used grep to check the result:
    #
    # ps -p $pid | grep ["^[	]*$pid[^0-9]"]
    #
    # Unfortunately sometimes there are flags displayed before the
    # process number.  Since we never saw a "ps -p PID" that does not
    # display the title line, we expect two lines.
    case $(ps -p $pid | wc -l | sed -e '[s/^[	 ]*//]') in
      1) # process is dead.
	 ;;
      2) # Process is live.
	 return 0;;
      *) error SOFTWARE "unexpected ps output:" "$(ps -p $pid)" ;;
    esac
  done
  return 1
}

# children_clean [CHILDREN]
# --------------------------
# Remove the children files.
children_clean ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    rm -f $i.{cmd,pid,sta,in,out,err,val}
  done
}

# children_pid [CHILDREN]
# -----------------------
# Return the PIDs of the CHILDREN (whether alive or not).
children_pid ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    test -f $i.pid ||
      error SOFTWARE "children_pid: cannot find $i.pid."
    cat $i.pid
  done
}

# children_register NAME
# ----------------------
# It is very important that we do not leave some random exit status
# from some previous runs.  Standard output etc. are not a problem:
# they *are* created during the run, while *.sta is created *only* if
# it does not already exists (this is because you can call "wait" only
# once per processus, so to enable calling children_harvest multiple
# times, we create *.sta only if it does not exist).
#
# Creates NAME.pid which contains the PID, and PID.name which contains
# the name.
children_register ()
{
  test $[#] -eq 1
  rm -f $[1].sta
  children="$children $[1]"
  echo $! >$[1].pid
  echo $[1] >$!.name
}

# children_report [CHILDREN]
# --------------------------
# Produce an RST report for the CHILDREN.
children_report ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    rst_run_report "$i" "$i"
  done
}

# children_kill [CHILDREN]
# ------------------------
# Kill all the children.  This function can be called twice: once
# before cleaning the components, and once when exiting, so it's
# robust to children no longer in the process table.
children_kill ()
{
  local pids
  pids=$(children_pid "$[@]")
  pids_kill $pids
}

# children_harvest [CHILDREN]
# ---------------------------
# Report the exit status of the children.  Can be run several times.
# You might want to call it once in the regular control flow to fetch
# some exit status, but also in a trap, if you were interrupted.  So
# it is meant to be callable multiple times, which might be a danger
# wrt *.sta (cf., children_register).
children_harvest ()
{
  # Harvest exit status.
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local i
  for i
  do
    # Don't wait for children we already waited for.
    if ! test -e $i.sta; then
      local pid
      pid=$(children_pid $i)
      # Beware of set -e.
      local sta
      if wait $pid 2>&1; then
	sta=$?
      else
	sta=$?
      fi
      echo "$sta$(ex_to_string $sta)" >$i.sta
    fi
  done
}

# children_status [CHILDREN]
# --------------------------
# Return the exit status of CHILD.  Must be run after harvesting.
# If several CHILD are given, return the highest exit status.
children_status ()
{
  test $[#] -ne 0 ||
    { set x $children; shift; }

  local res=0
  local i
  for i
  do
    # We need to have waited for these children.
    test -f $i.sta ||
      error SOFTWARE "children_status: cannot find $i.sta." \
		     "Was children_harvest called?"         \
		     "Maybe children_cleanup was already called..."
    local sta=$(sed -n '1{s/^\([[0-9][0-9]]*\).*/\1/;p;q;}' <$i.sta)
    if test $res -lt $sta; then
      res=$sta
    fi
  done
  echo $res
}

# children_wait TIMEOUT [CHILDREN]
# --------------------------------
# Wait for the registered children, and passed TIMEOUT, kill the remaining
# ones.  TIMEOUT is increased by 5 if instrumenting.
children_wait ()
{
  local timeout=$[1]
  shift
  local pids
  pids=$(children_pid "$[@]")
  pids_wait $timeout $pids
}

])

Fix shell quotation.

Fix shell quotation.

	* build-aux/children.as (children_kill): We do want to split the
	$pids.


/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * 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.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 *   Marc Alcaraz <ekameleon@gmail.com>.
 */

package com.google.analytics.core
{
    import com.google.analytics.debug.DebugConfiguration;
    import com.google.analytics.debug.VisualDebugMode;
    import com.google.analytics.v4.Configuration;

    import flash.display.DisplayObject;
    import flash.display.Stage;
    import flash.events.MouseEvent;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    import flash.utils.getTimer;

    /**
     * The Idle Timer class.
     */
    public class IdleTimer
    {
        private var _loop:Timer;
        private var _session:Timer;
        private var _debug:DebugConfiguration;
        private var _stage:Stage;
        private var _buffer:Buffer;

        private var _lastMove:int;
        private var _inactivity:Number;

        /**
        * Create an instance of the IdleTimer
        *
        * note:
        * the timer will loop every <delay> seconds
        * on each loop
        * we compare the <last mouse move time> to the <current time>
        * and if the result is equal or bigger than the
        * <inativity> seconds we start a sessionTimer
        * -> if the mouse move again we reset the sessionTimer
        * -> if the mouse does not move till we reach the end of the sessionTimeout
        *    we reset the session
        *
        * @param delay number of seconds to check for idle
        * @param inactivity number of seconds to check for inactivity
        * @param sessionTimeout number of seconds to end the session
        */
        public function IdleTimer( config:Configuration, debug:DebugConfiguration,
                                   display:DisplayObject, buffer:Buffer )
        {
            var delay:Number          = config.idleLoop;
            var inactivity:Number     = config.idleTimeout;
            var sessionTimeout:Number = config.sessionTimeout;

            _loop       = new Timer( delay * 1000 ); //milliseconds
            _session    = new Timer( sessionTimeout * 1000, 1 ); //milliseconds

            _debug      = debug;
            _stage      = display.stage;
            _buffer     = buffer;
            _lastMove   = getTimer();
            _inactivity = inactivity * 1000; //milliseconds

            _loop.addEventListener( TimerEvent.TIMER, checkForIdle );
            _session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
            _stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseMove );

            _debug.info( "delay: " + delay + "sec , inactivity: " + inactivity + "sec, sessionTimeout: " + sessionTimeout, VisualDebugMode.geek );

            _loop.start();
        }

        private function onMouseMove( event:MouseEvent ):void
        {
            _lastMove = getTimer();

            if( _session.running )
            {
                _debug.info( "session timer reset", VisualDebugMode.geek );
                _session.reset();
            }
        }

        public function checkForIdle( event:TimerEvent ):void
        {
            var current:int = getTimer();

            if( (current - _lastMove) >= _inactivity )
            {
                if( !_session.running )
                {
                    _debug.info( "session timer start", VisualDebugMode.geek );
                    _session.start();
                }
            }

        }

        public function endSession( event:TimerEvent ):void
        {
            _session.removeEventListener( TimerEvent.TIMER_COMPLETE, endSession );
            _debug.info( "session timer end session", VisualDebugMode.geek );
            _session.reset();
            _buffer.resetCurrentSession();
            _debug.info( _buffer.utmb.toString(), VisualDebugMode.geek );
            _debug.info( _buffer.utmc.toString(), VisualDebugMode.geek );

            _session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
        }

    }
}

/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * 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.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 *   Marc Alcaraz <ekameleon@gmail.com>.
 */

package com.google.analytics.core
{
    import com.google.analytics.debug.DebugConfiguration;
    import com.google.analytics.debug.VisualDebugMode;
    import com.google.analytics.v4.Configuration;

    import flash.display.DisplayObject;
    import flash.display.Stage;
    import flash.events.MouseEvent;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    import flash.utils.getTimer;

    /**
     * The Idle Timer class.
     */
    public class IdleTimer
    {
        private var _loop:Timer;
        private var _session:Timer;
        private var _debug:DebugConfiguration;
        private var _stage:Stage;
        private var _buffer:Buffer;

        private var _lastMove:int;
        private var _inactivity:Number;

        /* note:
           the timer will loop every <delay> seconds
           on each loop
           we compare the <last mouse move time> to the <current time>
           and if the result is equal or bigger than the
           <inativity> seconds we start a sessionTimer
           -> if the mouse move again we reset the sessionTimer
           -> if the mouse does not move till we reach the end of the sessionTimeout
              we reset the session
        */
        /**
        * Create an instance of the IdleTimer
        *
        * @param delay number of seconds to check for idle
        * @param inactivity number of seconds to check for inactivity
        * @param sessionTimeout number of seconds to end the session
        */
        public function IdleTimer( config:Configuration, debug:DebugConfiguration,
                                   display:DisplayObject, buffer:Buffer )
        {
            var delay:Number          = config.idleLoop;
            var inactivity:Number     = config.idleTimeout;
            var sessionTimeout:Number = config.sessionTimeout;

            _loop       = new Timer( delay * 1000 ); //milliseconds
            _session    = new Timer( sessionTimeout * 1000, 1 ); //milliseconds

            _debug      = debug;
            _stage      = display.stage;
            _buffer     = buffer;
            _lastMove   = getTimer();
            _inactivity = inactivity * 1000; //milliseconds

            _loop.addEventListener( TimerEvent.TIMER, checkForIdle );
            _session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
            _stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseMove );

            _debug.info( "delay: " + delay + "sec , inactivity: " + inactivity + "sec, sessionTimeout: " + sessionTimeout, VisualDebugMode.geek );

            _loop.start();
        }

        private function onMouseMove( event:MouseEvent ):void
        {
            _lastMove = getTimer();

            if( _session.running )
            {
                _debug.info( "session timer reset", VisualDebugMode.geek );
                _session.reset();
            }
        }

        public function checkForIdle( event:TimerEvent ):void
        {
            var current:int = getTimer();

            if( (current - _lastMove) >= _inactivity )
            {
                if( !_session.running )
                {
                    _debug.info( "session timer start", VisualDebugMode.geek );
                    _session.start();
                }
            }

        }

        public function endSession( event:TimerEvent ):void
        {
            _session.removeEventListener( TimerEvent.TIMER_COMPLETE, endSession );
            _debug.info( "session timer end session", VisualDebugMode.geek );
            _session.reset();
            _buffer.resetCurrentSession();
            _debug.info( _buffer.utmb.toString(), VisualDebugMode.geek );
            _debug.info( _buffer.utmc.toString(), VisualDebugMode.geek );

            _session.addEventListener( TimerEvent.TIMER_COMPLETE, endSession );
        }

    }
}

fix comment for asdoc

fix comment for asdoc


package org.jivesoftware.xiff.data{
	/*
	 * Copyright (C) 2003-2007
	 * Nick Velloff <nick.velloff@gmail.com>
	 * Derrick Grigg <dgrigg@rogers.com>
	 * Sean Voisen <sean@voisen.org>
	 * Sean Treadway <seant@oncotype.dk>
	 *
	 * This library is free software; you can redistribute it and/or
	 * modify it under the terms of the GNU Lesser General Public
	 * License as published by the Free Software Foundation; either
	 * version 2.1 of the License, or (at your option) any later version.
	 *
	 * This library is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	 * Lesser General Public License for more details.
	 *
	 * You should have received a copy of the GNU Lesser General Public
	 * License along with this library; if not, write to the Free Software
	 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
	 *
	 */

	import org.jivesoftware.xiff.data.ISerializable;
	import org.jivesoftware.xiff.data.XMPPStanza;
	import flash.xml.XMLNode;

	/**
	 * This class provides encapsulation for manipulation of presence data for sending and receiving.
	 *
	 * @author Sean Voisen
	 * @since 2.0.0
	 * @availability Flash Player 7
	 * @param recipient The recipient of the presence, usually in the form of a JID.
	 * @param sender The sender of the presence, usually in the form of a JID.
	 * @param presenceType The type of presence as a string. There are predefined static variables for this.
	 * @param showVal What to show for this presence (away, online, etc.) There are predefined static variables for this.
	 * @param statusVal The status; usually used for the "away message."
	 * @param priorityVal The priority of this presence; usually on a scale of 1-5.
	 * @toc-path Data
	 * @toc-sort 1
	 */
	public class Presence extends XMPPStanza implements ISerializable
	{
		// Static variables for specific type strings
		public static var AVAILABLE_TYPE:String = "available";
		public static var UNAVAILABLE_TYPE:String = "unavailable";
		public static var PROBE_TYPE:String = "probe";
		public static var SUBSCRIBE_TYPE:String = "subscribe";
		public static var UNSUBSCRIBE_TYPE:String = "unsubscribe";
		public static var SUBSCRIBED_TYPE:String = "subscribed";
		public static var UNSUBSCRIBED_TYPE:String = "unsubscribed";
		public static var ERROR_TYPE:String = "error";

		// Static variables for show values
		public static var SHOW_AWAY:String = "away";
		public static var SHOW_CHAT:String = "chat";
		public static var SHOW_DND:String = "dnd";
		public static var SHOW_NORMAL:String = "normal";
		public static var SHOW_XA:String = "xa";
		public static var SHOW_OFFLINE:String = "offline";

		// Private node references for property lookups
		private var myShowNode:XMLNode;
		private var myStatusNode:XMLNode;
		private var myPriorityNode:XMLNode;

		public function Presence( recipient:String=null, sender:String=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0 )
		{
			super( recipient, sender, presenceType, null, "presence" );

			show = showVal;
			status = statusVal;
			priority = priorityVal;
		}

		/**
		 * Serializes the Presence into XML form for sending to a server.
		 *
		 * @return An indication as to whether serialization was successful
		 * @availability Flash Player 7
		 */
		override public function serialize( parentNode:XMLNode ):Boolean
		{
			return super.serialize( parentNode );
		}

		/**
		 * Deserializes an XML object and populates the Presence instance with its data.
		 *
		 * @param xmlNode The XML to deserialize
		 * @return An indication as to whether deserialization was sucessful
		 * @availability Flash Player 7
		 */
		override public function deserialize( xmlNode:XMLNode ):Boolean
		{
			var isDeserialized:Boolean = super.deserialize( xmlNode );

			if (isDeserialized) {
				var children:Array = xmlNode.childNodes;
				for( var i:String in children )
				{
					switch( children[i].nodeName )
					{
						case "show":
							myShowNode = children[i];
							break;

						case "status":
							myStatusNode = children[i];
							break;

						case "priority":
							myPriorityNode = children[i];
							break;
					}
				}
			}
			return isDeserialized;
		}

		/**
		 * The show value; away, online, etc. There are predefined static variables in the Presence
		 * class for this:
		 *

		 *
Presence.SHOW_AWAY

		 *
Presence.SHOW_CHAT

		 *
Presence.SHOW_DND

		 *
Presence.SHOW_NORMAL

		 *
Presence.SHOW_XA

		 *

		 *
		 * @availability Flash Player 7
		 */
		public function get show():String
		{
			if (myShowNode == null) return null;

			if (!exists(myShowNode.firstChild)){
				return Presence.SHOW_NORMAL;
			}
			return myShowNode.firstChild.nodeValue;
		}

		public function set show( showVal:String ):void
		{

			myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
		}

		/**
		 * The status; usually used for "away messages."
		 *
		 * @availability Flash Player 7
		 */
		public function get status():String  {
			if (myStatusNode == null || myStatusNode.firstChild == null) return null;
			return myStatusNode.firstChild.nodeValue;
		}

		public function set status( statusVal:String ):void
		{
			myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
		}

		/**
		 * The priority of the presence, usually on a scale of 1-5.
		 *
		 * @availability Flash Player 7
		 */
		public function get priority():Number
		{
			if (myPriorityNode == null) return NaN;
			var p:Number = Number(myPriorityNode.firstChild.nodeValue);
			if( isNaN( p ) ) {
				return NaN;
			}
			else {
				return p;
			}
		}

		public function set priority( priorityVal:Number ):void
		{
			myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
		}
	}
}

package org.jivesoftware.xiff.data{
	/*
	 * Copyright (C) 2003-2007
	 * Nick Velloff <nick.velloff@gmail.com>
	 * Derrick Grigg <dgrigg@rogers.com>
	 * Sean Voisen <sean@voisen.org>
	 * Sean Treadway <seant@oncotype.dk>
	 *
	 * This library is free software; you can redistribute it and/or
	 * modify it under the terms of the GNU Lesser General Public
	 * License as published by the Free Software Foundation; either
	 * version 2.1 of the License, or (at your option) any later version.
	 *
	 * This library is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	 * Lesser General Public License for more details.
	 *
	 * You should have received a copy of the GNU Lesser General Public
	 * License along with this library; if not, write to the Free Software
	 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
	 *
	 */

	import org.jivesoftware.xiff.data.ISerializable;
	import org.jivesoftware.xiff.data.XMPPStanza;
	import flash.xml.XMLNode;

	/**
	 * This class provides encapsulation for manipulation of presence data for sending and receiving.
	 *
	 * @author Sean Voisen
	 * @since 2.0.0
	 * @availability Flash Player 7
	 * @param recipient The recipient of the presence, usually in the form of a JID.
	 * @param sender The sender of the presence, usually in the form of a JID.
	 * @param presenceType The type of presence as a string. There are predefined static variables for this.
	 * @param showVal What to show for this presence (away, online, etc.) There are predefined static variables for this.
	 * @param statusVal The status; usually used for the "away message."
	 * @param priorityVal The priority of this presence; usually on a scale of 1-5.
	 * @toc-path Data
	 * @toc-sort 1
	 */
	public class Presence extends XMPPStanza implements ISerializable
	{
		// Static constants for specific type strings
		public static const AVAILABLE_TYPE:String = "available";
		public static const UNAVAILABLE_TYPE:String = "unavailable";
		public static const PROBE_TYPE:String = "probe";
		public static const SUBSCRIBE_TYPE:String = "subscribe";
		public static const UNSUBSCRIBE_TYPE:String = "unsubscribe";
		public static const SUBSCRIBED_TYPE:String = "subscribed";
		public static const UNSUBSCRIBED_TYPE:String = "unsubscribed";
		public static const ERROR_TYPE:String = "error";

		// Static constants for show values
		public static const SHOW_AWAY:String = "away";
		public static const SHOW_CHAT:String = "chat";
		public static const SHOW_DND:String = "dnd";
		public static const SHOW_NORMAL:String = "normal";
		public static const SHOW_XA:String = "xa";
		public static const SHOW_OFFLINE:String = "offline";

		// Private node references for property lookups
		private var myShowNode:XMLNode;
		private var myStatusNode:XMLNode;
		private var myPriorityNode:XMLNode;

		public function Presence( recipient:String=null, sender:String=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0 )
		{
			super( recipient, sender, presenceType, null, "presence" );

			show = showVal;
			status = statusVal;
			priority = priorityVal;
		}

		/**
		 * Serializes the Presence into XML form for sending to a server.
		 *
		 * @return An indication as to whether serialization was successful
		 * @availability Flash Player 7
		 */
		override public function serialize( parentNode:XMLNode ):Boolean
		{
			return super.serialize( parentNode );
		}

		/**
		 * Deserializes an XML object and populates the Presence instance with its data.
		 *
		 * @param xmlNode The XML to deserialize
		 * @return An indication as to whether deserialization was sucessful
		 * @availability Flash Player 7
		 */
		override public function deserialize( xmlNode:XMLNode ):Boolean
		{
			var isDeserialized:Boolean = super.deserialize( xmlNode );

			if (isDeserialized) {
				var children:Array = xmlNode.childNodes;
				for( var i:String in children )
				{
					switch( children[i].nodeName )
					{
						case "show":
							myShowNode = children[i];
							break;

						case "status":
							myStatusNode = children[i];
							break;

						case "priority":
							myPriorityNode = children[i];
							break;
					}
				}
			}
			return isDeserialized;
		}

		/**
		 * The show value; away, online, etc. There are predefined static variables in the Presence
		 * class for this:
		 *

		 *
Presence.SHOW_AWAY

		 *
Presence.SHOW_CHAT

		 *
Presence.SHOW_DND

		 *
Presence.SHOW_NORMAL

		 *
Presence.SHOW_XA

		 *

		 *
		 * @availability Flash Player 7
		 */
		public function get show():String
		{
			if (myShowNode == null) return null;

			if (!exists(myShowNode.firstChild)){
				return Presence.SHOW_NORMAL;
			}
			return myShowNode.firstChild.nodeValue;
		}

		public function set show( showVal:String ):void
		{

			myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
		}

		/**
		 * The status; usually used for "away messages."
		 *
		 * @availability Flash Player 7
		 */
		public function get status():String  {
			if (myStatusNode == null || myStatusNode.firstChild == null) return null;
			return myStatusNode.firstChild.nodeValue;
		}

		public function set status( statusVal:String ):void
		{
			myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
		}

		/**
		 * The priority of the presence, usually on a scale of 1-5.
		 *
		 * @availability Flash Player 7
		 */
		public function get priority():Number
		{
			if (myPriorityNode == null) return NaN;
			var p:Number = Number(myPriorityNode.firstChild.nodeValue);
			if( isNaN( p ) ) {
				return NaN;
			}
			else {
				return p;
			}
		}

		public function set priority( priorityVal:Number ):void
		{
			myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
		}
	}
}

Make the constants const so it doesn't warn when I use them in data binding expressions


package
{
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.events.Event;
    import flash.utils.setTimeout;

    import FacilitatorSocket;
    import events.FacilitatorSocketEvent;

    import ProxyPair;
    import RTMFPProxyPair;
    import SQSProxyPair;
    import TCPProxyPair;

    import rtmfp.CirrusSocket;
    import rtmfp.events.CirrusSocketEvent;

    public class swfcat extends Sprite
    {
        /* Adobe's Cirrus server for RTMFP connections.
           The Cirrus key is defined at compile time by
           reading from the CIRRUS_KEY environment var. */
        private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net";
        private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;

        private const DEFAULT_FACILITATOR_ADDR:Object = {
            host: "tor-facilitator.bamsoftware.com",
            port: 9002
        };

        /* Default Tor client to use in case of RTMFP connection */
        private const DEFAULT_TOR_CLIENT_ADDR:Object = {
            host: "127.0.0.1",
            port: 9002
        };

        // Milliseconds.
        private const FACILITATOR_POLL_INTERVAL:int = 10000;

        // Socket to Cirrus server
        private var s_c:CirrusSocket;
        // Socket to facilitator.
        private var s_f:FacilitatorSocket;
        // Handle local-remote traffic
        private var p_p:ProxyPair;

        private var client_id:String;
        private var proxy_pair_factory:Function;

        private var proxy_pairs:Array;

        private var debug_mode:Boolean;
        private var proxy_mode:Boolean;

        /* TextField for debug output. */
        private var output_text:TextField;

        /* Badge for display */
        private var badge:Badge;

        private var fac_addr:Object;
        private var relay_addr:Object;

        public function swfcat()
        {
            proxy_mode = false;
            debug_mode = false;

            // Absolute positioning.
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;

            // Wait until the query string parameters are loaded.
            this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
        }

        public function puts(s:String):void
        {
            if (output_text != null) {
                output_text.appendText(s + "\n");
                output_text.scrollV = output_text.maxScrollV;
            }
        }

        private function loaderinfo_complete(e:Event):void
        {
            var fac_spec:String;
            var relay_spec:String;

            debug_mode = (this.loaderInfo.parameters["debug"] != null)
            proxy_mode = (this.loaderInfo.parameters["proxy"] != null);
            if (proxy_mode && !debug_mode) {
                badge = new Badge();
                addChild(badge);
            } else {
                output_text = new TextField();
                output_text.width = stage.stageWidth;
                output_text.height = stage.stageHeight;
                output_text.background = true;
                output_text.backgroundColor = 0x001f0f;
                output_text.textColor = 0x44cc44;
                addChild(output_text);
            }

            puts("Starting: parameters loaded.");

            /* TODO: use this to have multiple proxies going at once */
            proxy_pairs = new Array();

            fac_spec = this.loaderInfo.parameters["facilitator"];
            if (fac_spec) {
                puts("Facilitator spec: \"" + fac_spec + "\"");
                fac_addr = parse_addr_spec(fac_spec);
                if (!fac_addr) {
                    puts("Error: Facilitator spec must be in the form \"host:port\".");
                    return;
                }
            } else {
                fac_addr = DEFAULT_FACILITATOR_ADDR;
            }

            main();
        }

        /* The main logic begins here, after start-up issues are taken care of. */
        private function main():void
        {
            if (proxy_mode) {
                establish_facilitator_connection();
            } else {
                establish_cirrus_connection();
            }
        }

        private function establish_cirrus_connection():void
        {
            s_c = new CirrusSocket();
            s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void {
                puts("Cirrus: connected with id " + s_c.id + ".");
                if (proxy_mode) {
                    start_proxy_pair();
                    s_c.send_hello(client_id);
                } else {
                    establish_facilitator_connection();
                }
            });
            s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void {
                puts("Error: failed to connect to Cirrus.");
            });
            s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void {
                puts("Cirrus: closed connection.");
            });
            s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void {
                puts("Cirrus: received hello from peer " + e.peer);

                /* don't bother if we already have a proxy going */
                if (p_p != null && p_p.connected) {
                    return;
                }

                /* if we're in proxy mode, we should have already set
                   up a proxy pair */
                if (!proxy_mode) {
                    relay_addr = DEFAULT_TOR_CLIENT_ADDR;
                    proxy_pair_factory = rtmfp_proxy_pair_factory;
                    start_proxy_pair();
                    s_c.send_hello(e.peer);
                } else if (!debug_mode && badge != null) {
                    badge.proxy_begin();
                }

                p_p.client = {peer: e.peer, stream: e.stream};
            });

            s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY);
        }

        private function establish_facilitator_connection():void
        {
            s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port);
            s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void {
                puts("Facilitator: connect failed.");
                setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
            });

            if (proxy_mode) {
                s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void {
                    var client_addr:Object = parse_addr_spec(e.client);
                    relay_addr = parse_addr_spec(e.relay);
                    if (client_addr == null) {
                        puts("Facilitator: got registration " + e.client);
                        proxy_pair_factory = rtmfp_proxy_pair_factory;
                        if (s_c == null || !s_c.connected) {
                            client_id = e.client;
                            establish_cirrus_connection();
                        } else {
                            start_proxy_pair();
                            s_c.send_hello(e.client);
                        }
                    } else {
                        proxy_pair_factory = tcp_proxy_pair_factory;
                        start_proxy_pair();
                        p_p.client = client_addr;
                    }
                });
                s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void {
                    puts("Facilitator: no registrations available.");
                    setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
                });
                puts("Facilitator: getting registration.");
                s_f.get_registration();
            } else {
                s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void {
                    puts("Facilitator: registration failed.");
                    setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
                });
                puts("Facilitator: posting registration.");
                s_f.post_registration(s_c.id);
            }
        }

        private function start_proxy_pair():void
        {
            p_p = proxy_pair_factory();
            p_p.addEventListener(Event.CONNECT, function (e:Event):void {
                puts("ProxyPair: connected!");
            });
            p_p.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("ProxyPair: connection closed.");
                p_p = null;
                if (proxy_mode && !debug_mode && badge != null) {
                    badge.proxy_end();
                }
                establish_facilitator_connection();
            });
            p_p.relay = relay_addr;
        }

        private function rtmfp_proxy_pair_factory():ProxyPair
        {
            return new RTMFPProxyPair(this, s_c, s_c.local_stream_name);
        }

        // currently is the same as TCPProxyPair
        // could be interesting to see how this works
        // can't imagine it will work terribly well...
        private function sqs_proxy_pair_factory():ProxyPair
        {
            return new SQSProxyPair(this);
        }

        private function tcp_proxy_pair_factory():ProxyPair
        {
            return new TCPProxyPair(this);
        }

        /* Parse an address in the form "host:port". Returns an Object with
           keys "host" (String) and "port" (int). Returns null on error. */
        private function parse_addr_spec(spec:String):Object
        {
            var parts:Array;
            var addr:Object;

            parts = spec.split(":", 2);
            if (parts.length != 2 || !parseInt(parts[1]))
                return null;
            addr = {}
            addr.host = parts[0];
            addr.port = parseInt(parts[1]);

            return addr;
        }
    }
}

import flash.text.TextFormat;
import flash.text.TextField;

class Badge extends flash.display.Sprite
{
    /* Number of proxy pairs currently connected. */
    private var num_proxy_pairs:int = 0;
    /* Number of proxy pairs ever connected. */
    private var total_proxy_pairs:int = 0;

    [Embed(source="badge.png")]
    private var BadgeImage:Class;
    private var tot_client_count_tf:TextField;
    private var tot_client_count_fmt:TextFormat;
    private var cur_client_count_tf:TextField;
    private var cur_client_count_fmt:TextFormat;

    public function Badge()
    {
        /* Setup client counter for badge. */
        tot_client_count_fmt = new TextFormat();
        tot_client_count_fmt.color = 0xFFFFFF;
        tot_client_count_fmt.align = "center";
        tot_client_count_fmt.font = "courier-new";
        tot_client_count_fmt.bold = true;
        tot_client_count_fmt.size = 10;
        tot_client_count_tf = new TextField();
        tot_client_count_tf.width = 20;
        tot_client_count_tf.height = 17;
        tot_client_count_tf.background = false;
        tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
        tot_client_count_tf.x=47;
        tot_client_count_tf.y=0;

        cur_client_count_fmt = new TextFormat();
        cur_client_count_fmt.color = 0xFFFFFF;
        cur_client_count_fmt.align = "center";
        cur_client_count_fmt.font = "courier-new";
        cur_client_count_fmt.bold = true;
        cur_client_count_fmt.size = 10;
        cur_client_count_tf = new TextField();
        cur_client_count_tf.width = 20;
        cur_client_count_tf.height = 17;
        cur_client_count_tf.background = false;
        cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
        cur_client_count_tf.x=47;
        cur_client_count_tf.y=6;

        addChild(new BadgeImage());
        addChild(tot_client_count_tf);
        addChild(cur_client_count_tf);

        /* Update the client counter on badge. */
        update_client_count();
    }

    public function proxy_begin():void
    {
        num_proxy_pairs++;
        total_proxy_pairs++;
        update_client_count();
    }

    public function proxy_end():void
    {
        num_proxy_pairs--;
        update_client_count();
    }

    private function update_client_count():void
    {
        /* Update total client count. */
        if (String(total_proxy_pairs).length == 1)
            tot_client_count_tf.text = "0" + String(total_proxy_pairs);
        else
            tot_client_count_tf.text = String(total_proxy_pairs);

        /* Update current client count. */
        cur_client_count_tf.text = "";
        for(var i:Number = 0; i < num_proxy_pairs; i++)
            cur_client_count_tf.appendText(".");
    }
}

package
{
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.events.Event;
    import flash.utils.setTimeout;

    import FacilitatorSocket;
    import events.FacilitatorSocketEvent;

    import ProxyPair;
    import RTMFPProxyPair;
    import SQSProxyPair;
    import TCPProxyPair;

    import rtmfp.CirrusSocket;
    import rtmfp.events.CirrusSocketEvent;

    public class swfcat extends Sprite
    {
        /* Adobe's Cirrus server for RTMFP connections.
           The Cirrus key is defined at compile time by
           reading from the CIRRUS_KEY environment var. */
        private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net";
        private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;

        private const DEFAULT_FACILITATOR_ADDR:Object = {
            host: "tor-facilitator.bamsoftware.com",
            port: 9002
        };

        /* Default Tor client to use in case of RTMFP connection */
        private const DEFAULT_TOR_CLIENT_ADDR:Object = {
            host: "127.0.0.1",
            port: 9002
        };

        // Milliseconds.
        private const FACILITATOR_POLL_INTERVAL:int = 10000;

        // Socket to Cirrus server
        private var s_c:CirrusSocket;
        // Socket to facilitator.
        private var s_f:FacilitatorSocket;
        // Handle local-remote traffic
        private var p_p:ProxyPair;

        private var client_id:String;
        private var proxy_pair_factory:Function;

        private var proxy_pairs:Array;

        private var debug_mode:Boolean;
        private var proxy_mode:Boolean;

        /* TextField for debug output. */
        private var output_text:TextField;

        /* Badge for display */
        private var badge:Badge;

        private var fac_addr:Object;
        private var relay_addr:Object;

        public function swfcat()
        {
            proxy_mode = false;
            debug_mode = false;

            // Absolute positioning.
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;

            // Wait until the query string parameters are loaded.
            this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
        }

        public function puts(s:String):void
        {
            if (output_text != null) {
                output_text.appendText(s + "\n");
                output_text.scrollV = output_text.maxScrollV;
            }
        }

        private function loaderinfo_complete(e:Event):void
        {
            var fac_spec:String;
            var relay_spec:String;

            debug_mode = (this.loaderInfo.parameters["debug"] != null)
            proxy_mode = (this.loaderInfo.parameters["proxy"] != null);
            if (proxy_mode && !debug_mode) {
                badge = new Badge();
                addChild(badge);
            } else {
                output_text = new TextField();
                output_text.width = stage.stageWidth;
                output_text.height = stage.stageHeight;
                output_text.background = true;
                output_text.backgroundColor = 0x001f0f;
                output_text.textColor = 0x44cc44;
                addChild(output_text);
            }

            puts("Starting: parameters loaded.");

            /* TODO: use this to have multiple proxies going at once */
            proxy_pairs = new Array();

            fac_spec = this.loaderInfo.parameters["facilitator"];
            if (fac_spec) {
                puts("Facilitator spec: \"" + fac_spec + "\"");
                fac_addr = parse_addr_spec(fac_spec);
                if (!fac_addr) {
                    puts("Error: Facilitator spec must be in the form \"host:port\".");
                    return;
                }
            } else {
                fac_addr = DEFAULT_FACILITATOR_ADDR;
            }

            main();
        }

        /* The main logic begins here, after start-up issues are taken care of. */
        private function main():void
        {
            if (proxy_mode) {
                establish_facilitator_connection();
            } else {
                establish_cirrus_connection();
            }
        }

        private function establish_cirrus_connection():void
        {
            s_c = new CirrusSocket();
            s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void {
                puts("Cirrus: connected with id " + s_c.id + ".");
                if (proxy_mode) {
                    start_proxy_pair();
                    s_c.send_hello(client_id);
                } else {
                    establish_facilitator_connection();
                }
            });
            s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void {
                puts("Error: failed to connect to Cirrus.");
            });
            s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void {
                puts("Cirrus: closed connection.");
            });
            s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void {
                puts("Cirrus: received hello from peer " + e.peer);

                /* don't bother if we already have a proxy going */
                if (p_p != null && p_p.connected) {
                    return;
                }

                /* if we're in proxy mode, we should have already set
                   up a proxy pair */
                if (!proxy_mode) {
                    relay_addr = DEFAULT_TOR_CLIENT_ADDR;
                    proxy_pair_factory = rtmfp_proxy_pair_factory;
                    start_proxy_pair();
                    s_c.send_hello(e.peer);
                } else if (!debug_mode && badge != null) {
                    badge.proxy_begin();
                }

                p_p.client = {peer: e.peer, stream: e.stream};
            });

            s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY);
        }

        private function establish_facilitator_connection():void
        {
            s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port);
            s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void {
                puts("Facilitator: connect failed.");
                setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
            });

            if (proxy_mode) {
                s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void {
                    var client_addr:Object = parse_addr_spec(e.client);
                    relay_addr = parse_addr_spec(e.relay);
                    if (client_addr == null) {
                        puts("Facilitator: got registration " + e.client);
                        proxy_pair_factory = rtmfp_proxy_pair_factory;
                        if (s_c == null || !s_c.connected) {
                            client_id = e.client;
                            establish_cirrus_connection();
                        } else {
                            start_proxy_pair();
                            s_c.send_hello(e.client);
                        }
                    } else {
                        proxy_pair_factory = tcp_proxy_pair_factory;
                        start_proxy_pair();
                        p_p.client = client_addr;
                    }
                });
                s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void {
                    puts("Facilitator: no registrations available.");
                    setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
                });
                puts("Facilitator: getting registration.");
                s_f.get_registration();
            } else {
                s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void {
                    puts("Facilitator: registration failed.");
                    setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL);
                });
                puts("Facilitator: posting registration.");
                s_f.post_registration(s_c.id);
            }
        }

        private function start_proxy_pair():void
        {
            p_p = proxy_pair_factory();
            p_p.addEventListener(Event.CONNECT, function (e:Event):void {
                puts("ProxyPair: connected!");
            });
            p_p.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("ProxyPair: connection closed.");
                p_p = null;
                if (proxy_mode && !debug_mode && badge != null) {
                    badge.proxy_end();
                }
                establish_facilitator_connection();
            });
            p_p.relay = relay_addr;
        }

        private function rtmfp_proxy_pair_factory():ProxyPair
        {
            return new RTMFPProxyPair(this, s_c, s_c.local_stream_name);
        }

        // currently is the same as TCPProxyPair
        // could be interesting to see how this works
        // can't imagine it will work terribly well...
        private function sqs_proxy_pair_factory():ProxyPair
        {
            return new SQSProxyPair(this);
        }

        private function tcp_proxy_pair_factory():ProxyPair
        {
            return new TCPProxyPair(this);
        }

        /* Parse an address in the form "host:port". Returns an Object with
           keys "host" (String) and "port" (int). Returns null on error. */
        private static function parse_addr_spec(spec:String):Object
        {
            var parts:Array;
            var addr:Object;

            parts = spec.split(":", 2);
            if (parts.length != 2 || !parseInt(parts[1]))
                return null;
            addr = {}
            addr.host = parts[0];
            addr.port = parseInt(parts[1]);

            return addr;
        }
    }
}

import flash.text.TextFormat;
import flash.text.TextField;

class Badge extends flash.display.Sprite
{
    /* Number of proxy pairs currently connected. */
    private var num_proxy_pairs:int = 0;
    /* Number of proxy pairs ever connected. */
    private var total_proxy_pairs:int = 0;

    [Embed(source="badge.png")]
    private var BadgeImage:Class;
    private var tot_client_count_tf:TextField;
    private var tot_client_count_fmt:TextFormat;
    private var cur_client_count_tf:TextField;
    private var cur_client_count_fmt:TextFormat;

    public function Badge()
    {
        /* Setup client counter for badge. */
        tot_client_count_fmt = new TextFormat();
        tot_client_count_fmt.color = 0xFFFFFF;
        tot_client_count_fmt.align = "center";
        tot_client_count_fmt.font = "courier-new";
        tot_client_count_fmt.bold = true;
        tot_client_count_fmt.size = 10;
        tot_client_count_tf = new TextField();
        tot_client_count_tf.width = 20;
        tot_client_count_tf.height = 17;
        tot_client_count_tf.background = false;
        tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
        tot_client_count_tf.x=47;
        tot_client_count_tf.y=0;

        cur_client_count_fmt = new TextFormat();
        cur_client_count_fmt.color = 0xFFFFFF;
        cur_client_count_fmt.align = "center";
        cur_client_count_fmt.font = "courier-new";
        cur_client_count_fmt.bold = true;
        cur_client_count_fmt.size = 10;
        cur_client_count_tf = new TextField();
        cur_client_count_tf.width = 20;
        cur_client_count_tf.height = 17;
        cur_client_count_tf.background = false;
        cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
        cur_client_count_tf.x=47;
        cur_client_count_tf.y=6;

        addChild(new BadgeImage());
        addChild(tot_client_count_tf);
        addChild(cur_client_count_tf);

        /* Update the client counter on badge. */
        update_client_count();
    }

    public function proxy_begin():void
    {
        num_proxy_pairs++;
        total_proxy_pairs++;
        update_client_count();
    }

    public function proxy_end():void
    {
        num_proxy_pairs--;
        update_client_count();
    }

    private function update_client_count():void
    {
        /* Update total client count. */
        if (String(total_proxy_pairs).length == 1)
            tot_client_count_tf.text = "0" + String(total_proxy_pairs);
        else
            tot_client_count_tf.text = String(total_proxy_pairs);

        /* Update current client count. */
        cur_client_count_tf.text = "";
        for(var i:Number = 0; i < num_proxy_pairs; i++)
            cur_client_count_tf.appendText(".");
    }
}

Make parse_addr_spec static.

Make parse_addr_spec static.

Uniformity with master.


package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.net.Socket;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.events.SecurityErrorEvent;
    import flash.utils.ByteArray;

    public class swfcat extends Sprite
    {
        private const TOR_ADDRESS:String = "173.255.221.44";
        private const TOR_PORT:int = 9001;

        private var output_text:TextField;

        // Socket to Tor relay.
        private var s_t:Socket;
	// Socket to Facilitator.
	private var s_f:Socket;
        // Socket to client.
        private var s_c:Socket;

        private var fac_address:String;
        private var fac_port:int;

	private var client_address:String;
	private var client_port:int;

        private function puts(s:String):void
        {
            output_text.appendText(s + "\n");
            output_text.scrollV = output_text.maxScrollV;
        }

        public function swfcat()
        {
            output_text = new TextField();
            output_text.width = 400;
            output_text.height = 300;
            output_text.background = true;
            output_text.backgroundColor = 0x001f0f;
            output_text.textColor = 0x44CC44;
            addChild(output_text);

            puts("Starting.");
            // Wait until the query string parameters are loaded.
            this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
        }

        private function loaderinfo_complete(e:Event):void
        {
            var fac_spec:String, parts:Array;

            puts("Parameters loaded.");
            fac_spec = this.loaderInfo.parameters["facilitator"];
            if (!fac_spec) {
                puts("Error: no \"facilitator\" specification provided.");
                return;
            }
            puts("Facilitator spec: \"" + fac_spec + "\"");
            parts = fac_spec.split(":", 2);
            if (parts.length != 2 || !parseInt(parts[1])) {
                puts("Error: Facilitator spec must be in the form \"host:port\".");
                return;
            }
            fac_address = parts[0];
            fac_port = parseInt(parts[1]);

            go(TOR_ADDRESS, TOR_PORT);
        }

        /* We connect first to the Tor relay; once that happens we connect to
           the facilitator to get a client address; once we have the address
	   of a waiting client then we connect to the client and BAM! we're in business. */
        private function go(tor_address:String, tor_port:int):void
        {
            s_t = new Socket();

            s_t.addEventListener(Event.CONNECT, tor_connected);
            s_t.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("Tor: closed.");
                if (s_c.connected)
                    s_c.close();
            });
            s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
                puts("Tor: I/O error: " + e.text + ".");
                if (s_c.connected)
                    s_c.close();
            });
            s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
                puts("Tor: security error: " + e.text + ".");
                if (s_c.connected)
                    s_c.close();
            });

            puts("Tor: connecting to " + tor_address + ":" + tor_port + ".");
            s_t.connect(tor_address, tor_port);
        }

        private function tor_connected(e:Event):void
        {
	    /* Got a connection to tor, now let's get served a client from the facilitator */
            s_f = new Socket();

            puts("Tor: connected.");
            s_f.addEventListener(Event.CONNECT, fac_connected);
            s_f.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("Facilitator: closed connection.");
            });
            s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
                puts("Facilitator: I/O error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });
            s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
                puts("Facilitator: security error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });

            puts("Facilitator: connecting to " + fac_address + ":" + fac_port + ".");
            s_f.connect(fac_address, fac_port);

            /*s_c = new Socket();

            puts("Tor: connected.");
            s_c.addEventListener(Event.CONNECT, client_connected);
            s_c.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("Client: closed.");
                if (s_t.connected)
                    s_t.close();
            });
            s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
                puts("Client: I/O error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });
            s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
                puts("Client: security error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });

            puts("Client: connecting to " + client_address + ":" + client_port + ".");
            s_c.connect(client_address, client_port);*/
        }

	private function fac_connected(e:Event):void
        {
            puts("Facilitator: connected.");

            s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
                var client_spec:String = new String();
		client_spec = s_f.readMultiByte(0, "utf-8");
                puts("Facilitator: got \"" + client_spec + "\"");
                //s_c.writeBytes(bytes);
		/* Need to parse the bytes to get the new client. Fill out client_address and client_port */
            });

	    s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
        }

        private function client_connected(e:Event):void
        {
            puts("Client: connected.");

            s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
                var bytes:ByteArray = new ByteArray();
                s_t.readBytes(bytes, 0, e.bytesLoaded);
                puts("Tor: read " + bytes.length + ".");
                s_c.writeBytes(bytes);
            });
            s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
                var bytes:ByteArray = new ByteArray();
                s_c.readBytes(bytes, 0, e.bytesLoaded);
                puts("Client: read " + bytes.length + ".");
                s_t.writeBytes(bytes);
            });
        }
    }
}

package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.net.Socket;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.events.SecurityErrorEvent;
    import flash.utils.ByteArray;

    public class swfcat extends Sprite
    {
        private const TOR_ADDRESS:String = "173.255.221.44";
        private const TOR_PORT:int = 9001;

        private var output_text:TextField;

        // Socket to Tor relay.
        private var s_t:Socket;
	// Socket to Facilitator.
	private var s_f:Socket;
        // Socket to client.
        private var s_c:Socket;

        private var fac_address:String;
        private var fac_port:int;

	private var client_address:String;
	private var client_port:int;

        private function puts(s:String):void
        {
            output_text.appendText(s + "\n");
            output_text.scrollV = output_text.maxScrollV;
        }

        public function swfcat()
        {
            output_text = new TextField();
            output_text.width = 400;
            output_text.height = 300;
            output_text.background = true;
            output_text.backgroundColor = 0x001f0f;
            output_text.textColor = 0x44CC44;
            addChild(output_text);

            puts("Starting.");
            // Wait until the query string parameters are loaded.
            this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
        }

        private function loaderinfo_complete(e:Event):void
        {
            var fac_spec:String, parts:Array;

            puts("Parameters loaded.");
            fac_spec = this.loaderInfo.parameters["facilitator"];
            if (!fac_spec) {
                puts("Error: no \"facilitator\" specification provided.");
                return;
            }
            puts("Facilitator spec: \"" + fac_spec + "\"");
            parts = fac_spec.split(":", 2);
            if (parts.length != 2 || !parseInt(parts[1])) {
                puts("Error: Facilitator spec must be in the form \"host:port\".");
                return;
            }
            fac_address = parts[0];
            fac_port = parseInt(parts[1]);

            go(TOR_ADDRESS, TOR_PORT);
        }

        /* We connect first to the Tor relay; once that happens we connect to
           the facilitator to get a client address; once we have the address
	   of a waiting client then we connect to the client and BAM! we're in business. */
        private function go(tor_address:String, tor_port:int):void
        {
            s_t = new Socket();

            s_t.addEventListener(Event.CONNECT, tor_connected);
            s_t.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("Tor: closed.");
                if (s_c.connected)
                    s_c.close();
            });
            s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
                puts("Tor: I/O error: " + e.text + ".");
                if (s_c.connected)
                    s_c.close();
            });
            s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
                puts("Tor: security error: " + e.text + ".");
                if (s_c.connected)
                    s_c.close();
            });

            puts("Tor: connecting to " + tor_address + ":" + tor_port + ".");
            s_t.connect(tor_address, tor_port);
        }

        private function tor_connected(e:Event):void
        {
	    /* Got a connection to tor, now let's get served a client from the facilitator */
            s_f = new Socket();

            puts("Tor: connected.");
            s_f.addEventListener(Event.CONNECT, fac_connected);
            s_f.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("Facilitator: closed connection.");
            });
            s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
                puts("Facilitator: I/O error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });
            s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
                puts("Facilitator: security error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });

            puts("Facilitator: connecting to " + fac_address + ":" + fac_port + ".");
            s_f.connect(fac_address, fac_port);

            /*s_c = new Socket();

            puts("Tor: connected.");
            s_c.addEventListener(Event.CONNECT, client_connected);
            s_c.addEventListener(Event.CLOSE, function (e:Event):void {
                puts("Client: closed.");
                if (s_t.connected)
                    s_t.close();
            });
            s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
                puts("Client: I/O error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });
            s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
                puts("Client: security error: " + e.text + ".");
                if (s_t.connected)
                    s_t.close();
            });

            puts("Client: connecting to " + client_address + ":" + client_port + ".");
            s_c.connect(client_address, client_port);*/
        }

	private function fac_connected(e:Event):void
        {
            puts("Facilitator: connected.");

            s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
                var client_spec:String = new String();
		client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
                puts("Facilitator: got \"" + client_spec + "\"");
                //s_c.writeBytes(bytes);
		/* Need to parse the bytes to get the new client. Fill out client_address and client_port */
            });

	    s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
        }

        private function client_connected(e:Event):void
        {
            puts("Client: connected.");

            s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
                var bytes:ByteArray = new ByteArray();
                s_t.readBytes(bytes, 0, e.bytesLoaded);
                puts("Tor: read " + bytes.length + ".");
                s_c.writeBytes(bytes);
            });
            s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
                var bytes:ByteArray = new ByteArray();
                s_c.readBytes(bytes, 0, e.bytesLoaded);
                puts("Client: read " + bytes.length + ".");
                s_t.writeBytes(bytes);
            });
        }
    }
}

Use e.bytesLoaded, not 0, to read the client address.

An argument of 0 works for Jonathan but for be it returns a 0-length
string.


import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;

class idiomesAnimation extends Movieclip
        {

  private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");

			function idiomesAnimation():Void
		{

			this.onEnterFrame = this.enterSlide;

		}

	private function enterSlide():Void
                {

			arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
			arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
			arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
			arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);

			return this;

		}

	public function IdiomesColour():Void
		{

			this.onRelease = this arrayColour;

			target = this.arrayLang_arr[i];
			target._tint = 0x8DC60D;

			return this;

		}

	private function arrayColour():Void
		{

			for ( var:i ; arrayLang_arr[i] <4; i++)
			{
				this.colorTo("#628D22", 0.3, "easeOutCirc");
				_parent.colorTo('#4b4b4b', 1, 'linear', .2);

			}

		}

	}

import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;

class idiomesAnimation extends Movieclip
        {

  private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");

			function idiomesAnimation():Void
		{

			this.onEnterFrame = this.enterSlide;

		}

	private function enterSlide()
                {

			arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
			arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
			arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
			arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);

			return this;

		}

	public function IdiomesColour()
		{

			this.onRelease = this arrayColour;

			target = this.arrayLang_arr[i];
			target._tint = 0x8DC60D;

			return this;

		}

	private function arrayColour()
		{

			for ( var:i ; arrayLang_arr[i] <4; i++)
			{
				this.colorTo("#628D22", 0.3, "easeOutCirc");
				_parent.colorTo('#4b4b4b', 1, 'linear', .2);

			}

		}

	}

Update idiomesAnimation.as

Update idiomesAnimation.as


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
    import org.mangui.hls.constant.HLSSeekMode;
    import org.mangui.hls.constant.HLSMaxLevelCappingMode;

    public final class HLSSettings extends Object {
        /**
         * Limit levels usable in auto-quality by the stage dimensions (width and height).
         *      true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
         *             Max level will be set depending on the maxLevelCappingMode option.
         *      false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
         *
         * Note: this setting is ignored in manual mode so all the levels could be selected manually.
         *
         * Default is false
         */
        public static var capLevelToStage : Boolean = false;
        /**
         * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
         *      HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
         *      HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
         *
         * Default is HLSMaxLevelCappingMode.DOWNSCALE
         */
        public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
        // // // // // // /////////////////////////////////
        //
        // org.mangui.hls.stream.HLSNetStream
        //
        // // // // // // /////////////////////////////////
        /**
         * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
         *
         * Default is -1 = auto
         */
        public static var minBufferLength : Number = -1;
        /**
         * Defines maximum buffer length in seconds.
         * (0 means infinite buffering)
         *
         * Default is 120.
         */
        public static var maxBufferLength : Number = 120;
        /**
         * Defines maximum back buffer length in seconds.
         * (0 means infinite back buffering)
         *
         * Default is 30.
         */
        public static var maxBackBufferLength : Number = 30;
        /**
         * Defines low buffer length in seconds.
         * When crossing down this threshold, HLS will switch to buffering state.
         *
         * Default is 3.
         */
        public static var lowBufferLength : Number = 3;
        /**
         * Defines seek mode to one form available in HLSSeekMode class:
         *      HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
         *      HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
         *
         * Default is HLSSeekMode.KEYFRAME_SEEK.
         */
        public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
        /** max nb of retries for Key Loading in case I/O errors are met,
         *      0, means no retry, error will be triggered automatically
         *     -1 means infinite retry
         */
        public static var keyLoadMaxRetry : int = -1;
        /** keyLoadMaxRetryTimeout

         * Maximum key retry timeout (in milliseconds) in case I/O errors are met.
         * Every fail on key request, player will exponentially increase the timeout to try again.
         * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
         *
         * Default is 64000.
         */
        public static var keyLoadMaxRetryTimeout : Number = 64000;
        /** max nb of retries for Fragment Loading in case I/O errors are met,
         *      0, means no retry, error will be triggered automatically
         *     -1 means infinite retry
         */
        public static var fragmentLoadMaxRetry : int = 4000;
        /** fragmentLoadMaxRetryTimeout

         * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
         * Every fail on fragment request, player will exponentially increase the timeout to try again.
         * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
         *
         * Default is 4000.
         */
        public static var fragmentLoadMaxRetryTimeout : Number = 64000;
        /** fragmentLoadSkipAfterMaxRetry

         * control behaviour in case fragment load still fails after max retry timeout
         * if set to true, fragment will be skipped and next one will be loaded.
         * If set to false, an I/O Error will be raised.
         *
         * Default is true.
         */
        public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
        /**
         * If set to true, live playlist will be flushed from URL cache before reloading
         * (this is to workaround some cache issues with some combination of Flash Player / IE version)
         *
         * Default is false
         */
        public static var flushLiveURLCache : Boolean = false;
        /** max nb of retries for Manifest Loading in case I/O errors are met,
         *      0, means no retry, error will be triggered automatically
         *     -1 means infinite retry
         */
        public static var manifestLoadMaxRetry : int = -1;
        /** manifestLoadMaxRetryTimeout

         * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
         * Every fail on fragment request, player will exponentially increase the timeout to try again.
         * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
         *
         * Default is 64000.
         */
        public static var manifestLoadMaxRetryTimeout : Number = 64000;
        /**
         * If greater than 0, specifies the preferred bitrate.
         * If -1, and startFromLevel is not specified, automatic start level selection will be used.
         * This parameter, if set, will take priority over startFromLevel.
         */
        public static var startFromBitrate : Number = -1;
        /** start level :
         *  from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
         * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
         * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
         */
        public static var startFromLevel : Number = -1;
        /** seek level :
         *  from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
         * -1 : automatic start level selection, keep previous level matching previous download bandwidth
         */
        public static var seekFromLevel : Number = -1;
        /** use hardware video decoder :
         *  it will set NetStream.useHardwareDecoder
         *  refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
         */
        public static var useHardwareVideoDecoder : Boolean = false;
        /**
         * Defines whether INFO level log messages will will appear in the console
         * Default is true.
         */
        public static var logInfo : Boolean = true;
        /**
         * Defines whether DEBUG level log messages will will appear in the console
         * Default is false.
         */
        public static var logDebug : Boolean = false;
        /**
         * Defines whether DEBUG2 level log messages will will appear in the console
         * Default is false.
         */
        public static var logDebug2 : Boolean = false;
        /**
         * Defines whether WARN level log messages will will appear in the console
         * Default is true.
         */
        public static var logWarn : Boolean = true;
        /**
         * Defines whether ERROR level log messages will will appear in the console
         * Default is true.
         */
        public static var logError : Boolean = true;
    }
}

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
    import org.mangui.hls.constant.HLSSeekMode;
    import org.mangui.hls.constant.HLSMaxLevelCappingMode;

    public final class HLSSettings extends Object {
        /**
         * Limit levels usable in auto-quality by the stage dimensions (width and height).
         *      true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
         *             Max level will be set depending on the maxLevelCappingMode option.
         *      false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
         *
         * Note: this setting is ignored in manual mode so all the levels could be selected manually.
         *
         * Default is false
         */
        public static var capLevelToStage : Boolean = false;
        /**
         * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
         *      HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
         *      HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
         *
         * Default is HLSMaxLevelCappingMode.DOWNSCALE
         */
        public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
        // // // // // // /////////////////////////////////
        //
        // org.mangui.hls.stream.HLSNetStream
        //
        // // // // // // /////////////////////////////////
        /**
         * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
         *
         * Default is -1 = auto
         */
        public static var minBufferLength : Number = -1;
        /**
         * Defines maximum buffer length in seconds.
         * (0 means infinite buffering)
         *
         * Default is 120.
         */
        public static var maxBufferLength : Number = 120;
        /**
         * Defines maximum back buffer length in seconds.
         * (0 means infinite back buffering)
         *
         * Default is 30.
         */
        public static var maxBackBufferLength : Number = 30;
        /**
         * Defines low buffer length in seconds.
         * When crossing down this threshold, HLS will switch to buffering state.
         *
         * Default is 3.
         */
        public static var lowBufferLength : Number = 3;
        /**
         * Defines seek mode to one form available in HLSSeekMode class:
         *      HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
         *      HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
         *
         * Default is HLSSeekMode.KEYFRAME_SEEK.
         */
        public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
        /** max nb of retries for Key Loading in case I/O errors are met,
         *      0, means no retry, error will be triggered automatically
         *     -1 means infinite retry
         */
        public static var keyLoadMaxRetry : int = -1;
        /** keyLoadMaxRetryTimeout

         * Maximum key retry timeout (in milliseconds) in case I/O errors are met.
         * Every fail on key request, player will exponentially increase the timeout to try again.
         * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
         *
         * Default is 64000.
         */
        public static var keyLoadMaxRetryTimeout : Number = 64000;
        /** max nb of retries for Fragment Loading in case I/O errors are met,
         *      0, means no retry, error will be triggered automatically
         *     -1 means infinite retry
         */
        public static var fragmentLoadMaxRetry : int = 4000;
        /** fragmentLoadMaxRetryTimeout

         * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
         * Every fail on fragment request, player will exponentially increase the timeout to try again.
         * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
         *
         * Default is 4000.
         */
        public static var fragmentLoadMaxRetryTimeout : Number = 64000;
        /** fragmentLoadSkipAfterMaxRetry

         * control behaviour in case fragment load still fails after max retry timeout
         * if set to true, fragment will be skipped and next one will be loaded.
         * If set to false, an I/O Error will be raised.
         *
         * Default is true.
         */
        public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
        /**
         * If set to true, live playlist will be flushed from URL cache before reloading
         * (this is to workaround some cache issues with some combination of Flash Player / IE version)
         *
         * Default is false
         */
        public static var flushLiveURLCache : Boolean = false;
        /** max nb of retries for Manifest Loading in case I/O errors are met,
         *      0, means no retry, error will be triggered automatically
         *     -1 means infinite retry
         */
        public static var manifestLoadMaxRetry : int = -1;
        /** manifestLoadMaxRetryTimeout

         * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
         * Every fail on fragment request, player will exponentially increase the timeout to try again.
         * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
         *
         * Default is 64000.
         */
        public static var manifestLoadMaxRetryTimeout : Number = 64000;
        /**
         * If greater than 0, specifies the preferred bitrate.
         * If -1, and startFromLevel is not specified, automatic start level selection will be used.
         * This parameter, if set, will take priority over startFromLevel.
         */
        public static var startFromBitrate : Number = -1;
        /** start level :
         *  from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
         * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
         * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
         */
        public static var startFromLevel : Number = -1;
        /** seek level :
         *  from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
         * -1 : automatic start level selection, keep previous level matching previous download bandwidth
         */
        public static var seekFromLevel : Number = -1;
        /** use hardware video decoder :
         *  it will set NetStream.useHardwareDecoder
         *  refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
         */
        public static var useHardwareVideoDecoder : Boolean = false;
        /**
         * Defines whether INFO level log messages will will appear in the console
         * Default is true.
         */
        public static var logInfo : Boolean = true;
        /**
         * Defines whether DEBUG level log messages will will appear in the console
         * Default is false.
         */
        public static var logDebug : Boolean = false;
        /**
         * Defines whether DEBUG2 level log messages will will appear in the console
         * Default is false.
         */
        public static var logDebug2 : Boolean = false;
        /**
         * Defines whether WARN level log messages will will appear in the console
         * Default is true.
         */
        public static var logWarn : Boolean = true;
        /**
         * Defines whether ERROR level log messages will will appear in the console
         * Default is true.
         */
        public static var logError : Boolean = true;
    }
}

fix typo

fix typo