As Functions

Embed Size (px)

Citation preview

  • 8/3/2019 As Functions

    1/47

    1

    Action Script Functions

    Compiler Aditya Kappagantula

    Date 21-1-12

    Type Actionscript Functions

    Version Actionscript 3

    Note: Refer the index page [2] for function descriptions.

    Note: Please add any other functions that you find useful. Also please add the function name in

    index page.

    Note: Search for the function name to navigate to the function.

  • 8/3/2019 As Functions

    2/47

    2

    INDEX NAME

    1 Basic Array Shuffler

    2

    2dArray from text file

    3 7 out of 49 lottery

    4 count (a1+a2+---an)*(b1+b2+---bm)

    5 Add values in arrays

    6 Array Unique

    7 Array flip

    8 Array.addItemAt(item, index)

    9 Array.removeItemAt(index)

    10 Array.bSearch (key, options) - search a sorted associative array using bisection algorithm

    11 Array.contains()

    12 Array.Contains_Mod()

    13 Array.distinctShuffle()

    14 Array.fromFile()15 Array.inArray()

    16 Array.moveElement(index,num)

    17 Array.moveItem

    18 Array.next(); Array.previous()

    19 Array.prototype.arrayToVar

    20 Array.qsort

    21 Array.unique()

    22 arrayMul

    23 Average from nested arrays

    24 Bubble sort

    25 Compare Arrays

    26 Copies an array rather than just creating a reference to an array

    27 copyArray

    28 Find and remove

    29 Find nearest value

    30 Find the index of a string in array

    31 For-in loop

    32 Get max and min values in an array

    33 Join two arrays element by element

    34 Array shuffler

    35 random number generation

    36 recording keystrokes into an array

    37 Remove repeated

    items38 Xml to array [recursive]

    39 Popup manager

    40 Transition Class

    41 Count Down timer

    42 Birthdate to Age

    43 Date

    44 Date extension class

    45 Digital clock

  • 8/3/2019 As Functions

    3/47

    3

    46 set number to 2decimal places

    47 Round to nearest

    48 format number with commas

    49 Format numbers with commas efficiently

    50 Random alpha numeric password generator

    51 roman to Arabic

    52 Drag and drop class53 Trace Object Class

    54 Bad word filter

    55 Word counting

    56 is Prime

    57 Tooltip class

    58 Array Collection filter function

    59 Center of Stage

    60 Array Collection to XML

    61 Unique Array Collection Values

    62 Convert XML TO ArrayCollection

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    7576

    77

    78

    79

    80

    81

    82

    83

    84

    85

    86

    8788

    89

    90

    91

    92

    93

    94

    95

  • 8/3/2019 As Functions

    4/47

    4

    96

    97

    Basic Array Shuffler

    function sortRand () {if (random(2) == 0) {

    return -1;

    }if (random(2) == 0) {return 1;

    }}

    array.sort(sortRand);

    2D Array from text file

    *this works for the MySecondaryArray having only exactly 3 fields.i'm sure it could be done so that it adjusts automaticallybut i didnt need it to so i didnt bother.

    the text file goes like this :myTextFileVar=this;;that::the next;;\n\nthis2;;that2::the next2;;\n\nthis3;;3that::3the next& where each "\n"is a carrige return in the text file meaning there is1 line between listed items to make it easier to use,and "&" is the absolute last character to indicate theend of the variable. if lost use trace actions to figure out what does what. enjoy.*/

    _root.myConstuctor = new LoadVars();_root.myConstuctor.load("MytextFile.txt");_root.myConstuctor.onLoad = function(true) {

    if (true) {_root.myParsingVar1 = _root.myConstuctor.myTextFileVar;_root.myParsingArray = _root.myParsingVar1.split("\n\n");_root.myMainArray = new Array();for (j=0; j

  • 8/3/2019 As Functions

    5/47

    5

    pickfrom.splice(rand, 1);}trace("Rest: "+pickfrom+"\nShow Winner: "+winlist);

    /* I used it for loading 7 randomly picked movies(holding nothing but pictures) out of 17 total and no repetition!Each time the user clicks back to the site he gets to

    see different pix on my slider bar....*/

    a count

    //count (a1+a2+---an)*(b1+b2+---bm)//author: tigerchinak=0Number.prototype.mu=function(a,b){

    for(i=0;i

  • 8/3/2019 As Functions

    6/47

    6

    Array.prototype.unique = function(){

    for (i=0; i

  • 8/3/2019 As Functions

    7/47

    7

    trace( neto.addItemAt( 30 , 2 ) );

    Array.removeItemAt(index)

    // This is a modification of Joo Neto's code to// do the opposite of his function 'addItemAt'.// This function removes an item from the array// at the location specified. Be careful as the// index for this function starts from 1 not 0// i.e. if removeItemAt(1) is called the first// element is removed, not the second.

    Array.prototype.removeItemAt = function(index){if(index

  • 8/3/2019 As Functions

    8/47

    8

    // Copyright: no rights reserved, no liability covered, no warranty of use given orimplied, no indemnity offered, support optional.

    Array.prototype.bSearch = function (key, options) {this.sortDESCENDING = (options & Array.DESCENDING) ? true : false;this.sortNUMERIC = (options & Array.NUMERIC) ? true : false;this.sortCASEINSENSITIVE = (options & Array.CASEINSENSITIVE) ? true : false;this.padRole = String.fromCharCode(31); // Use this character to

    delimit fields in search key and array test row.

    var iL = 0, iU = this.length-1, iM = 0; // Initialize search boundry.var iterations = 0; // The bisection search algorithm

    iterates about log2(Array.length) times when searching a sorted array.

    while (iU-iL > 1) {iM = (iU+iL) >> 1; // Bisect array's search boundary

    until search key is found in the array row under test, or search fails boundaryconditions.

    iterations++;this.getRow2Test(key, iM); // Private function, defined below,

    to populate this.sKey and this.tKey.if ( (this.sKey >= this.tKey) != this.sortDESCENDING)iL=iM;elseiU=iM;

    }if ( iterations > Math.round(Math.LOG2E*Math.log(this.length)) ) {

    trace( "Warning: search took too long! \n Details: " + iterations + "iterations of outer search loop were used, \n compared to theoretical maximum oflog2(array size): " + Math.round(Math.LOG2E*Math.log(this.length)) );

    trace( " Perhaps this array has not been sorted correctly, or differentoptions should be pased to this function." );

    }this.getRow2Test(key, (this.sortDESCENDING ? iU: iL)) // Return with Array

    index position when search found.if ( this.sKey == this.tKey )return (this.sortDESCENDING ? iU: iL);this.getRow2Test(key, 0)if (this.sKey == this.tKey)return 0;this.getRow2Test(key, this.length-1)if (this.sKey == this.tKey)return this.length-1;return -1; // Return -1, when search key not found.

    };// bSearch private function builds formatted search key (this.sKey) and test row(this.tKey)Array.prototype.getRow2Test = function (key, row) {

    this.sKey=""; // Search key.this.tKey=""; // Test row.for (var role in key) {

    var iPadRole = Math.max( String(key[role]).length,String(this[row][role]).length ) + 1;

    if ( typeof key[role] == "number" && this.sortNUMERIC) {// NUMERIC sorted number elements must pad to the rightfor (var p = String(key[role]).length; p

  • 8/3/2019 As Functions

    9/47

    9

    this.sKey = this.sKey.toUpperCase();this.tKey = this.tKey.toUpperCase();

    }};

    // example...var playList = new Array();playList.push( {slide: 2, clip: "_level0.instance3", cue: 4000} );playList.push( {slide: 3, clip: "_level0.instance1", cue: 5000} );

    playList.push( {slide: 1, clip: "_level0.instance1", cue: 1000} );playList.push( {slide: 10, clip: "_level0.instance2", cue: 2000} );playList.sortOn( ["clip", "slide"], Array.DESCENDING | Array.NUMERIC |Array.CASEINSENSITIVE)var index = playList.bSearch( {clip: "_level0.instance1", slide: 1}, Array.DESCENDING |Array.NUMERIC | Array.CASEINSENSITIVE )if (index)trace("clip found, with cue time: " + playList[index].cue); // clip found, with cuetime: 1000elsetrace("Oops, clip not found");

    Array.contains()

    /*--------------------------------------------------------------------Array.Contains(value)

    A function to find if value is contained inside the array anywhere...

    Author:David B. ([email protected])Date:July 13, 2003Version:0.1aLicense:As is! You assume all responsibility for this code.Use as you see fit. Use at your own risk!

    Inputs:[value] = the value to find inside the array.

    Returns:[int] = the number of occurrence of that [value] inside the array.

    Example:var a;var cnt;a = new Array(1,2,3,3,3,4);cnt = a.Contains(3);trace(cnt);------------------------------------------------------------------------*/ Array.prototype.Contains = function(value){

    var found = 0;var i = 0;

    for(i=0; i

  • 8/3/2019 As Functions

    10/47

    10

    Array.prototype.Contains = function (value) {loc = new Array ();var found = 0;var i = 0;for (i = 0; i < this.length; i++) {

    if (this[i] == value or (this[i].indexOf (value) -1)) {loc.push (this[i]);

    found++;}}return found + ' [' + value + '\'s] found' + ' => ' + loc.toString

    ();delete loc;

    };choice = new Array ();choice[0] = new Array ('ffo', 'mAry', 'envelope', 'mary', 'choA', 'a','Abraoa');choice[1] = new Array (5, 43, 24, 33, 5563, 3346, 34, 3, 345, 3, 243);choice[2] = new Array (354, 3, 678, 112, 74564, 1, 423, 26, 4678, 1245678,44);trace (choice[1].Contains ('5'));trace (choice[0].Contains ('a'));

    trace (choice[0].Contains ('A'));trace (choice[0].Contains ('oA'));

    Array.distinctShuffle()

    //Simple array randomiser...

    Array.prototype.distinctShuffle = function() {this.sort(function(a,b) { i = Math.round((Math.random() * 100) -

    50); return i;});return this;

    };

    var n = new Array(1,2,3,4,5,6,7,8,9,10);

    trace(n);n.distinctShuffle();trace(n);n.distinctShuffle();trace(n);n.distinctShuffle();trace(n);stop();

    Array.distinctShuffle()

    /*I needed a script that would randomise an array and return a completely unique array.Each element had to have a new position.

    I came across a script entitled "Randomize an array with no similarities to previouslayout"at: http://www.actionscript.org/actionscripts_library/Array_Object/but after testing it found that an error occurs when unshift() is used.The resulting array is only completely unique in cases where unshift() isn't applied.

    Here is my solution, tested and working in Flash 5 and above:

  • 8/3/2019 As Functions

    11/47

    11

    */

    /*-------------------------------------------------------------------*/

    Array.prototype.distinctShuffle = function() {result = [];for (posArray=[], i=0; i=0; last--){

    selected = this[last];

    rand = random(posArray.length-1);lastPos = posArray.getPos(last);if (lastPos == null){

    result[posArray[rand]] = selected;posArray.splice(rand, 1);

    }else{posArray.splice(lastPos, 1);result[posArray[rand]] = selected;posArray.splice(rand, 1);posArray.push(last);

    }}return result;

    };

    Array.prototype.getPos = function(item){for(i=0; i

  • 8/3/2019 As Functions

    12/47

    12

    Array.inArray()

    Array.prototype.inArray = function (value)// Creates a new method for the array object.// Returns true if the passed value is found in the// array -- by matching for identity, not similarity.// Returns false if the item is not found.{

    var i;for (i=0; i < this.length; i++) {

    // Matches identical (===), not just similar (==).if (this[i] === value) {

    returntrue;}

    }returnfalse;

    };

    Array.moveElement(index,num)

    //Array.moveElement(index,num)// index - element in array to move// num - move Array elements up(postive num, towards index 0) or down(negative

    num, towards end of array)Array.prototype.moveElement = function(index,num){

    var num=int(num);if(num>0){ //move upward num times

    var i=index;while(i>index-num){

    if(i==0) break;var e = this[i];//this.slice(i,i+1);this.splice(i,1);this.splice(i-1,0,e/*.slice()*/;i--;

    }}else if(num

  • 8/3/2019 As Functions

    13/47

    13

    myArray.moveItem("C");function display(c) {

    trace(c.toString());}

    Array.next(); Array.previous()

    Array.prototype.next=function (currentValue){var setKey;

    for (at inthis) {if (currentValue == this[at]){

    returnthis[setKey];}setKey=at;

    }}

    Array.prototype.prev=function (currentValue){var setKey;var i=0;for (at inthis) {

    if (setKey==i){returnthis[at];

    }if (currentValue == this[at]){

    setKey=(i+1);

    }i++;

    }}ASSetPropFlags(Array.prototype,["next","prev"],1);

    /* example

    flashzone=new Array();flashzone[1]="1-1-1";flashzone[3]="3-3-3";flashzone['kk']="kkvalue";flashzone[7]="7-7-7";flashzone[25]="25-25-25";flashzone['zz']="zzValue";flashzone[11]="11-11-11";

    flashzone[13]="13-13-13";

    trace("nextValue=> " add flashzone.next("kkvalue"))trace("================")trace("prevValue=> " add flashzone.prev("11-11-11"))

    */

    Array.prototype.arrayToVar

    // Arrayelemnts to VariablesArray.prototype.arrayToVar = function(varname) {

    if (varname == undefined) varname = "variable";for (var i = 0; i < personen.length; i++) {

    _root[varname+"_"+i] = personen[i];}

    };ASSetPropFlags(Array.prototype,"arrayToVar",1,true);

    personen = ["Matthias","Caroline","Martin","Ralf"];personen.arrayToVar("person");

    // Tryfor (i in _root) {

    // trace(i + "=" + _root[i]);ausgabe_txt.text += i+"="+_root[i]+"\n";

  • 8/3/2019 As Functions

    14/47

    14

    }

    Array.qsort

    Array.prototype.qsort = function( obj ){vartype = [];

    if ( ( typeof obj == "object" ) && ( obj.length == undefined ) ) type.push( obj);

    elsetype = obj;

    this.qs( 0 , this.length - 1 , type[ 0 ].prop );if ( type[ 0 ].order == -1 ) this.reverse();

    if ( type.length > 1 ){for ( var i = 1 ; i < type.length ; i++ ){

    var ret = [];var aux = [];while ( this.length > 0 ){

    aux.push( this.shift() );if ( this[ 0 ][ type[ i - 1 ].prop ] != aux[ 0 ][ type[

    i - 1 ].prop ] ){ret.push( aux );

    aux = [];}}

    for ( var j = 0 ; j < ret.length ; j++ ){var a = ret[ j ]if ( a.length > 1 ) a.qs( 0 , a.length - 1 , type[ i

    ].prop );if ( type[ i ].order == -1 ) a.reverse();for ( var k = 0 ; k < a.length ; k++ ){

    this.push( a[ k ] );}

    }}

    }}

    Array.prototype.qs = function( left , right , prop ){var nInt = function( value ){return( int( value ) == value ? value : int( value ) + 1 );

    }var i = left;var j = right;var x = this[ nInt( ( i + j ) / 2 ) ];do {

    if ( prop == undefined ){while ( ( this[ i ] < x ) && ( i < right ) ) i++;while ( ( this[ j ] > x ) && ( j > left ) ) j--;

    } else {while ( ( this[ i ][ prop ] < x[ prop ] ) && ( i < right ) )

    i++;while ( ( this[ j ][ prop ] > x[ prop ] ) && ( j > left ) ) j--

    ;}

    if ( i

  • 8/3/2019 As Functions

    15/47

    15

    var num = [ 10 , 16 , 33 , 1 , 15 , 21 ];var str = [ "Joao" , "Jonas" , "Navy" , "Joao" , "Joao" , "Neto" ];var obj = [ { nome : "Joao" , idade : 10 , local : "ap" },{ nome : "Jonas" , idade : 16 , local : "rj" },{ nome : "Navy" , idade : 33 , local : "sc" },{ nome : "Joao" , idade : 1 , local : "cp" },{ nome : "Joao" , idade : 15 , local : "bp" },{ nome : "Neto" , idade : 21 , local : "rs" } ];

    num.qsort();str.qsort();obj.qsort( [ { prop : "nome" , order : 1 } , { prop : "idade" , order : -1 } ] );

    trace( num );trace( str );

    for ( var i = 0 ; i < obj.length ; i++ ){var p = "";for ( var j in obj[ i ] )p += j + ": " + obj[ i ][ j ] + " , ";trace( p );

    }

    Array.randomize()

    Array.prototype.randomize = function () {returnthis.sort(function(a,b) {return (Math.floor(Math.random()*2) == 0) ? 1 :

    -1;});};

    myArray = [1,2,3,4,5,6,7,8,9,10];trace(myArray.randomize());

    Array.unique()

    Array.prototype.unique = function() {for (i=0; i

  • 8/3/2019 As Functions

    16/47

    16

    answer2 = arrayMul ([10, 10], [5, -5, 10]);// Note answer2.length = 3

    Average from nested arrays

    //function by missing-link//first we create our functionArray.prototype.getNestedAverages = function(){

    //create a new array to hold the averagesaverages = newArray();//now for the loop statementsfor (var i = 0; i

  • 8/3/2019 As Functions

    17/47

    17

    This script compares arrays and counts the number of items which are in both arrays but in the wrong

    place, and in both arrays in the same (right) place. I can forsee problems if the arrays sometimes haveduplicate numbers like array1=[6,2,2,7] but other than that this should work: array1=[5,3,6,1];array2=[1,5,4,6];for (var j = 0; j

  • 8/3/2019 As Functions

    18/47

    18

    b = b.findAndRemove("paperone");trace(b) // Array after

    //-------------------------------------------------------

    Find nearest value

    /*

    nearest();Author: Tony Kenny [email protected] January 2002

    Use this function as you like.All I ask is that you leave this message in any distribution.This function take two arguments.The first being an array containing a list of values.The second a value to check.nearest() will return the *array index* of the nearest value.*/function nearest(arr, checkval) {

    if (arr.length

  • 8/3/2019 As Functions

    19/47

    19

    //output: 1

    For-in loop

    for in loop can be used to access the elements of an array.an importantthing is that it read /retrieves the data from right to reft order.Example:

    //..................................................................var myArray = [1,32,5265,"alok","monu","xyz"];

    for( elements in myArray){

    trace("elements of the array are: " + elements);

    }

    // result'll be xyz,monu,alok.....

    //-----------------------------------------------------------------

    Get max and min values in an array

    getMax = function (tmpArray) {tmpMax = 0;for (i=0; itmpMax) {tmpMax = tmpArray[i];

    }}return tmpMax;

    };getMin = function (tmpArray) {

    tmpMin = getMax(tmpArray);for (i=0; i

  • 8/3/2019 As Functions

    20/47

    20

    }x.push(position1, position2);

    }return x;

    }

    Array shuffler

    // This is just a shorter version of the previous.function sortRand () {

    return(( random(2) == 0)? -1: 1);}

    myArray = newArray(1,1,2,2,3,3);myArray.sort(sortRand);

    numerical sorting

    function sortN(arr) {var tmp = newArray();tmp[0] = arr[0];

    for ( var i=1; i

  • 8/3/2019 As Functions

    21/47

    21

    numArray[i]=Math.floor(Math.random()*(range+1))+minNum;while(j

  • 8/3/2019 As Functions

    22/47

    22

    Returns an array containing random numbers, the random numbers can be unique, they can have a

    range and you can specify how many random numbers you want in your array

    //_root.myuniquerandomnumbers=Number.randomnumbers(10,20,10,true)

    Number.randomnumbers=function(lowest,highest,count,unique){

    var randomnums=newArray()if(unique && count

  • 8/3/2019 As Functions

    23/47

    23

    GENERIC FUNCTIONS

    Popup manager

    /*** @author: Eric Feminella* @class: PopUpWindowHandler* @published: 04.04.06* @usage: Singleton which creates and manages popup window for mxml components* @param: PopUpWindowHandler.createPopUp(target:MovieClip, classObject:Object[mxmlcomponent);*/

    import mx.managers.PopUpManager;

    class PopUpWindowHandler{

    public static var popup:MovieClip;

    public static function createPopUp(target:MovieClip, classObject:Object):Void{

    if (PopUpWindowHandler.popup == null){

    PopUpWindowHandler.popup = PopUpManager.createPopUp(target,classObject, false, {});

    PopUpWindowHandler.popup.centerPopUp(scope);

    }}

    public static function close():Void{

    PopUpWindowHandler.popup.closeWindow();PopUpWindowHandler.popup = null;

    }

    public static function get getPopUp():MovieClip{

    return PopUpWindowHandler.popup;}

    }

    Transition Class

    /*****************************************************************************//name: Transition Class//description: a easy way to use mx.TransitionManager Class//made by: Carlos Queiroz//contact: [email protected]//date: 04-12-2005//update: 09-02-2006 (add events, change return obj)

  • 8/3/2019 As Functions

    24/47

    24

    ****************************************************************************>> available transitionstransition.blinds(obj, direction:Number, duration:Number, numStrips:Number,dimension:Number, easing:Function)transition.fade(obj, direction:Number, duration:Number, easing:Function)transition.fly(obj, direction:Number, duration:Number, startPoint:Number,easing:Function)transition.iris(obj, direction:Number, duration:Number, startPoint:Number, shape:Number,easing:Function)

    transition.photo(obj, direction:Number, duration:Number, easing:Function)transition.pixelDissolve(obj, direction:Number, duration:Number, xSections:Number,ySection:Number, easing:Function)transition.rotate(obj, direction:Number, duration:Number, ccw:Boolean, degrees:Number,easing:Function)transition.squeeze(obj, direction:Number, duration:Number, dimension:Number,easing:Function)transition.wipe(obj, direction:Number, duration:Number, startPoint:Number,easing:Function)transition.zoom(obj, direction:Number, duration:Number, easing:Function)>> returns a mx.TransitionManager object>> events: onTransitionChanged, onTransitionFinished*/class transition{

    //blindspublic static function blinds(obj, direction:Number, duration:Number,

    numStrips:Number, dimension:Number, easing:Function):Object{

    return (init(obj, {type:1, direction:direction, duration:duration,numStrips:numStrips, dimension:dimension, easing:easing}));

    }//fadepublic static function fade(obj, direction:Number, duration:Number,

    easing:Function):Object{

    return (init(obj, {type:2, direction:direction, duration:duration,easing:easing}));

    }//flypublic static function fly(obj, direction:Number, duration:Number,

    startPoint:Number, easing:Function):Object{

    return (init(obj, {type:3, direction:direction, duration:duration,startPoint:startPoint, easing:easing}));

    }//irispublic static function iris(obj, direction:Number, duration:Number,

    startPoint:Number, shape:Number, easing:Function):Object{

    return (init(obj, {type:4, direction:direction, duration:duration,startPoint:startPoint, shape:shape, easing:easing}));

    }//photopublic static function photo(obj, direction:Number, duration:Number,

    easing:Function):Object{

    return (init(obj, {type:5, direction:direction, duration:duration,easing:easing}));

    }

    //pixelDissolvepublic static function pixelDissolve(obj, direction:Number, duration:Number,xSections:Number, ySection:Number, easing:Function):Object

    {return (init(obj, {type:6, direction:direction, duration:duration,

    xSections:xSections, ySection:ySection, easing:easing}));}//rotatepublic static function rotate(obj, direction:Number, duration:Number,

    ccw:Boolean, degrees:Number, easing:Function):Object{

    return (init(obj, {type:7, direction:direction, duration:duration,ccw:ccw, degrees:degrees, easing:easing}));

  • 8/3/2019 As Functions

    25/47

    25

    }//squeezepublic static function squeeze(obj, direction:Number, duration:Number,

    dimension:Number, easing:Function):Object{

    return (init(obj, {type:8, direction:direction, duration:duration,dimension:dimension, easing:easing}));

    }//wipe

    public static function wipe(obj, direction:Number, duration:Number,startPoint:Number, easing:Function):Object

    {return (init(obj, {type:9, direction:direction, duration:duration,

    startPoint:startPoint, easing:easing}));}//zoompublic static function zoom(obj, direction:Number, duration:Number,

    easing:Function):Object{

    return (init(obj, {type:10, direction:direction, duration:duration,easing:easing}));

    }////init//private static function init(obj, specs:Object){

    var tm = new mx.transitions.TransitionManager(obj);////tm.onTransitionStarted = new Function();tm.onTransitionChanged = new Function();tm.onTransitionFinished = new Function();//var listener = new Object();//var transObj = {};//if (specs.direction == 0){

    transObj.direction = mx.transitions.Transition.IN;listener.allTransitionsInDone = function(evt:Object){

    clearInterval(interval);tm.onTransitionFinished();

    };tm.addEventListener("allTransitionsInDone", listener);

    }else{

    transObj.direction = mx.transitions.Transition.OUT;listener.allTransitionsOutDone = function(evt:Object){

    clearInterval(interval);tm.onTransitionFinished();

    };tm.addEventListener("allTransitionsOutDone", listener);

    }//transObj.duration = specs.duration;

    //transObj.easing = (specs.easing == undefined) ?mx.transitions.easing.None.easeNone : specs.easing;

    //switch (specs.type){

    case 1 ://blindstransObj.type = mx.transitions.Blinds;transObj.numStrips = specs.numStrips;transObj.dimension = specs.dimension;break;case 2 :

  • 8/3/2019 As Functions

    26/47

    26

    //fadetransObj.type = mx.transitions.Fade;break;case 3 ://flytransObj.type = mx.transitions.Fly;transObj.startPoint = specs.startPoint;break;case 4 :

    //iristransObj.type = mx.transitions.Iris;transObj.startPoint = specs.startPoint;transObj.shape = (specs.shape == 1) ? mx.transitions.Iris.SQUARE

    : mx.transitions.Iris.CIRCLE;break;case 5 ://phototransObj.type = mx.transitions.Photo;break;case 6 ://pixelDissolvetransObj.type = mx.transitions.PixelDissolve;transObj.xSection = specs.xSection;transObj.ySection = specs.ySection;break;case 7 ://rotatetransObj.type = mx.transitions.Rotate;transObj.degrees = specs.degrees;transObj.ccw = specs.ccw;break;case 8 ://squeezetransObj.type = mx.transitions.Squeeze;transObj.dimension = specs.dimension;break;case 9 ://wipetransObj.type = mx.transitions.Wipe;transObj.startPoint = specs.startPoint;break;case 10 ://zoomtransObj.type = mx.transitions.Zoom;break;

    }//obj._visible = true;//tm.startTransition(transObj);//tm.onTransitionStarted();//var interval = setInterval(function (){

    tm.onTransitionChanged();}, 0);//return (tm);

    }

    }//

  • 8/3/2019 As Functions

    27/47

    27

    DATE FUNCTIONS

    Count Down

    ///////////first frame////////////////today = newDate();seconds = Math.floor((event.getTime()-today.getTime())/1000);minutes = Math.floor(seconds/60);hours = Math.floor(minutes/60);days = Math.floor(hours/24);cday = days;if (cday

  • 8/3/2019 As Functions

    28/47

    28

    month = newArray("January", "February", "March", "April", "May", "June","July", "August", "September", "Octobert", "November", "December");

    diasemana = weekday[now.getDay()];mes = month[now.getMonth()];diadelmes = now.getDate();modifier = new CreateArray(31);var modifier = new

    String("thstndrdthththththththththththththththththstndrdthththththththst ");var loop = 0;

    do {modifier[loop] = modifier.substring(loop*2, 2+(loop*2));loop = loop+1;

    } while (loop

  • 8/3/2019 As Functions

    29/47

    29

    Month names in various langauges.EN - EnglishSP - SpanishFR - FrenchGR - GermanIT - Italian*/

    private var monthNameEN:Array = new Array("January", "February", "March",

    "April", "May", "June", "July", "August", "September", "October", "November","December");

    private var monthNameSP:Array = new Array("Enero", "Febrero", "Marzo", "Abril","Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");

    private var monthNameFR:Array = new Array("Janvier", "Fvrier", "Mars","Avril", "Mai", "Juin", "Juillet", "Aot", "Septembre", "Octobre", "Novembre","Dcembre");

    private var monthNameGR:Array = new Array("Januar", "Februar", "Marschiert","April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November","Dezember");

    private var monthNameIT:Array = new Array("Gennaio", "Febbraio", "Marzo","Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre","Dicembre");

    functionXDate(year:Number,month:Number,date:Number,hour:Number,min:Number,sec:Number,ms:Number){

    setYear(year);setMonth(month);setDate(date);this.setDaysInMonth();this.setWeeksInMonth();

    /*This class does not handle any time units lower than days at this point.setHours(hour);setMinutes(min);setSeconds(sec);setMilliseconds(ms);*/

    }

    /** Function: getDayOfWeek* Summary: Get the day of the week (0 = Sunday, 6 = Saturday),

    * based on theday of the month.

    * Parameters: day a day of the object's month* Return: Number (0-6) indicating the day of week*/public function getDayOfWeek(day:Number):Number {

    var dayBackup:Number = this.getDate(); //create backupof object's actual given date

    this.setDate(day); //set the var dayOfWeek:Number = super.getDay();this.setDate(dayBackup);

    //return object's day to original value

    return dayOfWeek;

    }

    /** Function: isSunday* Summary: Function to inidicate whether a day is Sunday* Parameters: day a day of the object's month* Return: Boolean indicating if the day is Sunday or not*/public function isSunday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==0) {return true;

    }return false;

  • 8/3/2019 As Functions

    30/47

    30

    }

    /** Function: isMonday* Summary: Read isSunday's comments for summary & details*/public function isMonday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==1) {return true;

    }return false;

    }

    /** Function: isTuesday* Summary: Read isSunday's comments for summary & details*/public function isTuesday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==2) {return true;

    }return false;

    }

    /** Function: isWednesday* Summary: Read isSunday's comments for summary & details*/public function isWednesday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==3) {return true;

    }return false;

    }

    /** Function: isThursday* Summary: Read isSunday's comments for summary & details*/public function isThursday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==4) {return true;

    }return false;

    }

    /** Function: isFriday* Summary: Read isSunday's comments for summary & details*/public function isFriday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==5) {return true;

    }return false;

    }

    /** Function: isSaturday

    * Summary: Read isSunday's comments for summary & details*/public function isSaturday(day:Number):Boolean {

    if(this.getDayOfWeek(day)==6) {return true;

    }return false;

    }

    /* Function: isWeekend* Summary: Checks to see if the day is part of the weekend* Parameters: day a day of the object's month* Return: Boolean indicating if the day is during the weekend

  • 8/3/2019 As Functions

    31/47

    31

    */public function isWeekend(day:Number):Boolean {

    if(this.getDayOfWeek(day)==6||this.getDayOfWeek(day)==0) {return true;

    }return false;

    }

    /*

    * Function: setDaysInMonth* Summary: Finds the total amount of days in the object's month* and sets 'daysInMonth' with the value*/function setDaysInMonth():Void {

    var tempDate = new Date(this.getYear(), this.getMonth()+1, 0);this.monthDays = tempDate.getDate();delete tempDate;

    }

    /** Function: daysInMonth* Summary: Returns the total number of days in the object's

    month* Return: The total number of days in the month*/function get daysInMonth():Number {

    return this.monthDays;}

    /** Function: getDaysLeftInMonth* Summary: Returns the total number of days left in the

    object's month* Return: The total number of days left in the month*/function getDaysLeftInMonth():Number {

    return this.daysInMonth-super.getDate();}

    /** Function: getDaysInYear* Summary: Finds the total amount of days in the object's year* primarily useful to detect leap years* Return: The total number of days in the year*/function get daysInYear():Number {

    var daysInYear:Number=0;var i:Number=0;var year:Number=13;while(++i

  • 8/3/2019 As Functions

    32/47

    32

    * Summary: Finds the day (i.e Monday, Tuesday, etc.)* that the last day of the object's month

    lands on*/function monthEndDate():Number {

    var dayBackup:Number = this.getDate();var lastDay:Number = this.daysInMonth;this.setDate(lastDay);var day:Number = super.getDay();

    this.setDate(dayBackup);return day;

    }

    /** Function: setWeeksInMonth* Summary: Sets the total number of weeks in the object's month*/function setWeeksInMonth():Void {

    monthWeeks=0;var days:Number = this.daysInMonth;var i:Number = 0;while(++i

  • 8/3/2019 As Functions

    33/47

  • 8/3/2019 As Functions

    34/47

    34

    break;case "GR":return monthNameGR[month];break;case "IT":return monthNameIT[month];break;default :return monthNameEN[month];

    break;}

    }else {

    return null}

    }}

    Digital clock

    myDate = newDate();timeTextField = (t = h+":"+m+":"+s);

    h = myDate.getHours();m = myDate.getMinutes();s = myDate.getSeconds();

    if (s 12) {

    hours -= 12;myAddOn = "PM";

    } else {myAddOn = "AM";

    }time = hours+":"+minutes+":"+seconds+""+myAddOn;

    set number to 2decimal places

    //set number to 2 decimal places//You can set this anywhere in your timeline and use as you need anywhere in your movie.Math.__proto__.dec2 = function (num){

    valor = String (Math.round(num * 100) / 100);dot = valor.indexOf(".");

    if(dot == -1){valor += ".0";}temp = valor.split(".");

  • 8/3/2019 As Functions

    35/47

    35

    addDecimals = 2 - temp[1].length;for(i=1; i0);//if (Major == diff2prev) {

    trace("floatnumber da chiudere all'intero precedente");return IsPos ? PrevInt : NextInt;

    }else {

    trace("floatnumber da chiudere all'intero successivo");return IsPos ? NextInt : PrevInt;

    }

    //}else {

    trace("case: 0,5 but non 0,5 periodico... ("add floatnumber add")");return floatnumber;

    }}////////////Usage:trace(Round2Nearest(0.000001));trace(Round2Nearest(10.89));trace(Round2Nearest(0.09));trace(Round2Nearest(0.5));

    trace(Round2Nearest(0.555555));trace(Round2Nearest(0.5555551));//this.onEnterFrame = function() {

    trace(Round2Nearest(Math.random()));};stop;

    format number with commas

    function addCommas(theNumber){

  • 8/3/2019 As Functions

    36/47

    36

    numString = theNumber + ""; //convert # to stringnewString = ""; //return stringindex = 1; // string indextrip = 0; // trip, as in triple.while(numString.length >= index){

    if (trip!=3){ //haven't reached 3 chars yetnewString = numString.charAt(numString.length - index) + newString; //add

    charindex++;

    trip++;}else{ //reached 3 chars, add comma

    newString = "," + newString;trip=0;

    }}return (newString);

    }

    Format numbers with commas efficiently

    /*** Formats the given Number with commas*/

    public static function formatNumberWithCommas(num) {var strNum:String = num+"";if (strNum.length < 4)return strNum;return formatNumberWithCommas(strNum.slice(0, -3))+","+strNum.slice(-3);

    }

    Random alpha numeric password generator

    function generatePassword (len){

    m = 0;pass = "";

    alf1 = "ABCDEFGHKJILMNOPQRSTUVWXYZ";

    alf2 = "1234567890";

    alfabet = alf1 + alf2;alf = alfabet.length;for (m = 0; m < len; m++){

    ran = Math.floor(Math.random() * (alf - 1));pass = pass + alfabet.charAt(ran);

    } // end of forreturn pass;

    }

    new_password = generatePassword (8);

    roman to Arabic

    roman2arabic = function (num) {var total:Number = 0;var values:Object = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};prev_value = 0;for (i=0; iprev_value) {

    total -= prev_value;} else {

    total += prev_value;}

  • 8/3/2019 As Functions

    37/47

    37

    prev_value = values[num.charAt(i)];}total += prev_value;return total;

    };trace(roman2arabic("IV"));

    Drag and drop class

    /*------------------------------------------------------------------------------------------------------------|| Author: Eric Feminella| Issued: 08.19.05| Copyright (c)2005 www.ericfeminella.com| Class: DragnDrop|-------------------------------------------------------------------------------------------------------------/|| Instantiate new instance of DragnDrop class as follows:| var varname:DragnDrop = new DragnDrop(dragObj, targetObj, _enabled, _alpha, _visible,_play, _mainPlay);|

    || Arguments for constructor are as follows:| 1.) dragObj:Object = Object to drag| 2.) targetObj:Object = Target Object| 3.) _enabled:Boolean = Disable Drag Object| 4.) alpha:Number = Change _alpha of Drap Object| 5.) _visible:Boolean = Visibility of Drag Object| 6.) _play:Number = Drag Object - play frame number| 7.) _mainPlay:Number = Main timeline / _level - play frame number||| Sample:| var dd:DragnDrop = new DragnDrop(this.circle, this.square, null, 80, true, null,null);||----------------------------------------------------------------------------------------

    ---------------------*/

    class DragnDrop

    {

    private var drag:Object;private var target:Object;private static var _this:Object;

    private var drag_x:Number;private var drag_y:Number;private var target_x:Number;private var target_y:Number;private var enabled:Boolean;private var alpha:Number;private var visible:Boolean;private var dragPlay:Number;private var mainPlay:Number;

    // constructor for DragnDrop class - dragObj, targetObj, _enabled, _alpha,_visible, _play, _mainPlay

    function DragnDrop(dragObj:Object, targetObj:Object, _enabled:Boolean,alpha:Number, _visible:Boolean, _play:Number, _mainPlay:Number) {

    DragnDrop._this = this;

  • 8/3/2019 As Functions

    38/47

    38

    this.drag = dragObj;this.target = targetObj;this.drag_x = dragObj._x;this.drag_y = dragObj._y;this.target_x = targetObj._x;this.target_y = targetObj._y;this.enabled = _enabled;this.alpha = alpha;this.visible - _visible;

    this.dragPlay = _play;this.mainPlay = _mainPlay;build();

    }

    private function build():Void {this.drag.onPress = function() {

    DragnDrop._this.Drag();};this.drag.onRelease = function() {

    DragnDrop._this.Drop();};

    }

    private function Drag():Void {this.drag.startDrag();

    }

    private function Drop():Void {this.drag.stopDrag();if (eval(this.drag._droptarget) == this.target) {

    this.drag.enabled = this.enabled;this.drag._alpha = this.alpha;this.drag.gotoAndPlay(this.dragPlay);this.drag._visible = this.visible;this.drag._x = this.target_x;this.drag._y = this.target_y;gotoAndStop(mainPlay);

    } else {this.drag._x = this.drag_x;this.drag._y = this.drag_y;

    }}

    }

  • 8/3/2019 As Functions

    39/47

    39

    Trace Object Class

    /*** @author: Eric Feminella* @version 1.1* @copyright: http://www.ericfeminella.com*/

    package {

    public final class TraceObject{

    public static function filterObject(obj:Object,recursivelyTraceAll:Boolean):void

    {if (obj is Array) {

    if (obj[0] != null) {

    e.trace("\nObject is of Type:Array[Indexed]\nIndexed as follows:");

    for (var i:Number = 0; i < obj.length; i++) {

    if (obj[i] is Object || obj[i] is Array){

    if (recursivelyTraceAll){

    TraceObject.filterObject(obj[i], true);}else{

    e.trace("\t[" + i + "] =

    " + obj[i] + "");}

    }else{

    e.trace("\t[" + i + "] = " +obj[i] + "");

    }}

    }else{

    e.trace("\nObject is of Type:Array[Associative]\nKeyed as follows:");

    for (var element:* in obj) {

    if (element is Object || element isArray)

    {if (recursivelyTraceAll){

    TraceObject.filterObject(element, true);}else{

    e.trace("\t['" + element+ "'] = " + obj[element]);

  • 8/3/2019 As Functions

    40/47

    40

    }}else{

    e.trace("\t['" + element + "'] =" + obj[element]);

    }}

    }

    }else if (obj is Object){

    e.trace("\nObject is of Type: " + typeof(obj));

    for (var prop:* in obj){

    if (prop is Object || prop is Array){

    if (recursivelyTraceAll){

    TraceObject.filterObject(prop,true);

    }else{

    e.trace("\t\t." + prop + " = " +obj[prop]);

    }}else{

    e.trace("\t\t." + prop + " = " +obj[prop]);

    }}

    }else if (obj == null){

    e.trace("A type of undefined has been set for: " + obj);}

    }}

    }

    Bad word filter

    // Function filters the wanted words ourt of the text// http://flash.andihaas.deString.prototype.changer = function(fil) {

    var a = this;var i, r, b;for (i in fil) {

    b = "xxx";for (r=0; r

  • 8/3/2019 As Functions

    41/47

    41

    //this ones kinda oldfunction rCons(myLetter):String {

    var cArray:Array = new Array("b", "c", "d", "f", "g", "h", "j", "k", "l", "m","n", "p", "qu", "r", "s", "t", "v", "w", "x", "y", "z", "z");

    var aNum:Number = new Number(Math.ceil(random(22)));myLetter = cArray[aNum];return (myLetter);

    }function rVowels(myLetter):String {

    var vArray:Array = new Array("a", "e", "i", "o", "u","u");var bNum:Number = new Number(Math.ceil(random(6)));myLetter = vArray[bNum];return (myLetter);

    }function genName(myExt, myString):String {

    var nNum2:Number = new Number(Math.floor(random(4)+3));var nText:String = new String("");for (i=0; i

  • 8/3/2019 As Functions

    42/47

    42

    sentence = "";itemlist = myString.split("\r");for (n=0; n

  • 8/3/2019 As Functions

    43/47

    43

    private var shadow_mc:MovieClip;

    // tip textprivate var tip:String;

    // constructorfunction Tooltip(t:String){

    thisObj = this;

    tip = t;

    createToolTip();

    }

    /**** CreateToolTip* - creates the tooltip***/

    private function createToolTip(Void):Void{

    var thisObj:Tooltip = this;

    // trace("creating tool tip");

    // create tooltip holder - send it way below for nowtext_mc = _level0.createEmptyMovieClip("text_holder", 15000, {_x:0,

    _y:0});

    // move text_mc - must be done after initialization to make sure thetext appears where its supposed to

    text_mc._x = _level0._xmouse;text_mc._y = _level0._ymouse;

    // create text field for tiptext_mc.createTextField("tooltip_txt", 10, 0, 21, 20, 20);

    tooltip_txt = text_mc.tooltip_txt;

    // set text field parameterstooltip_txt.html = true;tooltip_txt.backgroundColor = 0xFFFFEE;tooltip_txt.background = true;tooltip_txt.border = true;tooltip_txt.borderColor = 0x666666;tooltip_txt.autoSize = "left";tooltip_txt.multiline = false;tooltip_txt.wordWrap = false;tooltip_txt.textColor = 0x333333;tooltip_txt.selectable = false;

    // set texttooltip_txt.htmlText = this.tip;

    // add formattingvar theFormat:TextFormat = new TextFormat();theFormat.font = "Verdana";theFormat.size = 10;theFormat.rightMargin = 5;

    // set the formattooltip_txt.setTextFormat(theFormat);

    // draw the shadow

  • 8/3/2019 As Functions

    44/47

  • 8/3/2019 As Functions

    45/47

    45

    text_mc.removeMovieClip();}

    }

    Array Collection filter function

    publicfunction excludeEmpties(item:Object):Boolean

    {

    if(item==null||item=="")

    {

    returnfalse;// exclude the item

    }

    returntrue;// include the item

    }

    // set the filter function on the collection

    publicfunction applyFilter():void

    {

    this.collection.filterFunction=excludeEmpties;

    // call refresh to update the collection's "view"

    this.collection.refresh();

    }

    Flex 4.5 Center of Stage

    popUp.width = FlexGlobals.topLevelApplication.width - 40; //popup - leave side

    edges

    popUp.height = FlexGlobals.topLevelApplication.height - 40; //popup - leave top +

    bottom edges

    popUp.x = FlexGlobals.topLevelApplication.width/2 - popUp.width/2; //popup x coord

    popUp.y = FlexGlobals.topLevelApplication.height/2 - popUp.height/2; //popup y

    coord

    Array Collection to XML

    /**

    * The below two functions are used to convert array collection to xml

    */

    privatefunction arrCol2XML( arrCol:ArrayCollection ):XML {

    var xml:XML = new XML(

    );

    for ( var i:Number = 0; i < arrCol.length; i++ ) {

    var obj:Object = arrCol.getItemAt( i );

    xml.appendChild( recursive( obj ));

    }

    return xml;

    }

  • 8/3/2019 As Functions

    46/47

    46

    privatefunction recursive( obj:Object, str:String = 'Record' ):XML {

    var xml:XML = new XML( '' );

    xml.appendChild( XML( "" + obj.Field1.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field2.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field3.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field4.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field5.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field6.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field7.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field8.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field9.toString() + "" ));

    xml.appendChild( XML( "" + obj.Field10.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field11.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field12.toString() + ""

    ));xml.appendChild( XML( "" + obj.Field13.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field14.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field15.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field16.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field17.toString() + ""

    ));

    xml.appendChild( XML( "" + obj.Field18.toString() + ""

    ));

    return xml;

    }

    Unique Array Collection Values

    privatefunction uniqueACValues( myAC:ArrayCollection ):ArrayCollection {

    var unique:Object = {};

    var value:String;

    var array:Array = myAC.toArray();

    var result:Array = [];

    var i:int = 0;

    var n:int = array.length;

    for ( i; i < n; i++ ) {

    value = array[ i ].adId;

    if ( !unique[ value ]) {

    unique[ value ] = true;

    result.push( value );

  • 8/3/2019 As Functions

    47/47

    47

    }

    }

    returnnew ArrayCollection( result );

    }

    Convert XML TO ArrayCollection

    import mx.utils.ArrayUtil;

    import mx.rpc.xml.SimpleXMLDecoder;

    import mx.collections.ArrayCollection;

    private function convertXmlToArrayCollection( file:String ):ArrayCollection

    {

    var xml:XMLDocument = new XMLDocument( file );

    var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();

    var data:Object = decoder.decodeXML( xml );var array:Array = ArrayUtil.toArray( data.rows.row );

    return new ArrayCollection( array );

    }