Repository: as3/as3-utils Branch: master Commit: 838aad249f53 Files: 569 Total size: 431.8 KB Directory structure: gitextract_mxl70_5m/ ├── .gitignore ├── Contribution Guidelines.md ├── Libraries to integrate.md ├── NOTES.md ├── README.md ├── TODO.md ├── bin/ │ └── as3-utils.swc ├── build/ │ ├── flexunit/ │ │ └── flexUnitTasks-4.1.0-33.jar │ └── pmd/ │ ├── LICENSE.txt │ ├── as3-parser-1.1.jar │ ├── as3-parser-api-1.1.jar │ ├── as3-plugin-utils-1.1.jar │ ├── commons-lang-2.4.jar │ ├── dom4j-1.6.1.jar │ ├── flex-pmd-ant-task-1.1.jar │ ├── flex-pmd-command-line-1.1.jar │ ├── flex-pmd-command-line-api-1.1.jar │ ├── flex-pmd-core-1.1.jar │ ├── flex-pmd-cpd-1.1.jar │ ├── flex-pmd-cpd-ant-task-1.1.jar │ ├── flex-pmd-cpd-command-line-1.1.jar │ ├── flex-pmd-files-1.1.jar │ ├── flex-pmd-metrics-1.1.jar │ ├── flex-pmd-metrics-ant-task-1.1.jar │ ├── flex-pmd-metrics-command-line-1.1.jar │ ├── flex-pmd-ruleset-1.1.jar │ ├── flex-pmd-ruleset-api-1.1.jar │ ├── jsap-2.1.jar │ ├── plexus-utils-1.0.2.jar │ └── pmd-4.2.5.jar ├── build.properties ├── build.xml ├── libs/ │ ├── flexunit-4.1.0-33-as3_3.5.0.12683.swc │ ├── flexunit-cilistener-4.1.0-33-3.5.0.12683.swc │ ├── flexunit-uilistener-4.1.0-33-3.5.0.12683.swc │ ├── hamcrest-as3-flex-1.1.3.swc │ └── mockolate-0.9.3.swc ├── res/ │ └── flex-formatter.properties ├── src/ │ ├── .gitignore │ ├── deprecated/ │ │ ├── .gitignore │ │ ├── confine.as │ │ ├── constrain.as │ │ ├── getURL.as │ │ ├── randomBoolean.as │ │ ├── randomRangeFloat.as │ │ └── randomRangeInt.as │ └── utils/ │ ├── align/ │ │ ├── alignCenter.as │ │ ├── alignLeft.as │ │ ├── alignRight.as │ │ ├── alignToRectangleBottom.as │ │ ├── alignToRectangleCenter.as │ │ ├── alignToRectangleCenterMiddle.as │ │ ├── alignToRectangleLeft.as │ │ ├── alignToRectangleMiddle.as │ │ ├── alignToRectangleRight.as │ │ ├── alignToRectangleTop.as │ │ ├── getPositionToTheRightOf.as │ │ ├── getPositionUnder.as │ │ ├── gridAlignSpaceNumber.as │ │ ├── gridAlignSpaceNumberGap.as │ │ ├── horizontalAlign.as │ │ ├── horizontalAlignNoSpace.as │ │ ├── horizontalAlignSpaceArray.as │ │ ├── horizontalAlignSpaceNumber.as │ │ ├── interpolate.as │ │ ├── interpolateMultiX.as │ │ ├── interpolateMultiY.as │ │ ├── interpolateX.as │ │ ├── interpolateY.as │ │ ├── verticalAlign.as │ │ ├── verticalAlignNoSpace.as │ │ ├── verticalAlignSpaceArray.as │ │ ├── verticalAlignSpaceNumber.as │ │ ├── xAlignCenter.as │ │ ├── xAlignLeft.as │ │ ├── xAlignRight.as │ │ ├── yAlignCenter.as │ │ ├── yAlignLeft.as │ │ └── yAlignRight.as │ ├── array/ │ │ ├── addItemsAt.as │ │ ├── arrayContainsValue.as │ │ ├── arraysAreEqual.as │ │ ├── average.as │ │ ├── contains.as │ │ ├── containsAll.as │ │ ├── containsAny.as │ │ ├── copyArray.as │ │ ├── createUniqueCopy.as │ │ ├── equals.as │ │ ├── getHighestValue.as │ │ ├── getIndexOfDifference.as │ │ ├── getItemByKey.as │ │ ├── getItemByType.as │ │ ├── getItemsByKey.as │ │ ├── getItemsByType.as │ │ ├── getLowestValue.as │ │ ├── getRandomElement.as │ │ ├── randomize.as │ │ ├── removeDuplicates.as │ │ ├── removeItem.as │ │ ├── removeItems.as │ │ ├── removeValueFromArray.as │ │ ├── retainItems.as │ │ └── sum.as │ ├── assert/ │ │ ├── assertArrayContains.as │ │ ├── assertArrayItemsTypeOf.as │ │ ├── assertDictionaryKeysTypeOf.as │ │ ├── assertHasText.as │ │ ├── assertInstanceOf.as │ │ ├── assertIsTrue.as │ │ ├── assertNotNull.as │ │ └── assertState.as │ ├── boolean/ │ │ ├── randomBoolean.as │ │ └── randomChance.as │ ├── capabilities/ │ │ ├── getPlayerInfo.as │ │ ├── isAirApplication.as │ │ ├── isIDE.as │ │ ├── isMac.as │ │ ├── isPC.as │ │ ├── isPlugin.as │ │ ├── isStandAlone.as │ │ └── isWeb.as │ ├── color/ │ │ ├── HSLtoHSV.as │ │ ├── HSLtoRGB.as │ │ ├── HSVtoHSL.as │ │ ├── HSVtoRGB.as │ │ ├── HueToRGB.as │ │ ├── RGBToHue.as │ │ ├── RGBtoHSL.as │ │ ├── RGBtoHSV.as │ │ ├── averageBlue.as │ │ ├── averageColorProperty.as │ │ ├── averageGreen.as │ │ ├── averageHue.as │ │ ├── averageLightness.as │ │ ├── averageRed.as │ │ ├── averageSaturation.as │ │ ├── averageValue.as │ │ ├── changeContrast.as │ │ ├── getARGB.as │ │ ├── getColor.as │ │ ├── getColorFromDisplayObject.as │ │ ├── getHexStringFromARGB.as │ │ ├── getHexStringFromRGB.as │ │ ├── getRGB.as │ │ ├── getTransform.as │ │ ├── interpolateColor.as │ │ ├── invertColor.as │ │ ├── randomColor.as │ │ ├── resetColor.as │ │ ├── setARGB.as │ │ ├── setColor.as │ │ ├── setTransform.as │ │ ├── toColor.as │ │ ├── toGrayscale.as │ │ ├── toHTML.as │ │ ├── toHexString.as │ │ └── toRGBComponents.as │ ├── conversion/ │ │ ├── bitsToBytes.as │ │ ├── bitsToKilobits.as │ │ ├── bitsToKilobytes.as │ │ ├── bytesToBits.as │ │ ├── bytesToKilobits.as │ │ ├── bytesToKilobytes.as │ │ ├── daysToHours.as │ │ ├── daysToMilliseconds.as │ │ ├── daysToMinutes.as │ │ ├── daysToSeconds.as │ │ ├── degreesToRadians.as │ │ ├── hoursToDays.as │ │ ├── hoursToMilliseconds.as │ │ ├── hoursToMinutes.as │ │ ├── hoursToSeconds.as │ │ ├── kilobitsToBits.as │ │ ├── kilobitsToBytes.as │ │ ├── kilobitsToKilobytes.as │ │ ├── kilobytesToBits.as │ │ ├── kilobytesToBytes.as │ │ ├── kilobytesToKilobits.as │ │ ├── millisecondsToDays.as │ │ ├── millisecondsToHours.as │ │ ├── millisecondsToMinutes.as │ │ ├── millisecondsToSeconds.as │ │ ├── minutesToDays.as │ │ ├── minutesToHours.as │ │ ├── minutesToMilliseconds.as │ │ ├── minutesToSeconds.as │ │ ├── radiansToDegrees.as │ │ ├── secondsToDays.as │ │ ├── secondsToHours.as │ │ ├── secondsToMilliseconds.as │ │ └── secondsToMinutes.as │ ├── cookie/ │ │ ├── getCookie.as │ │ └── setCookie.as │ ├── date/ │ │ ├── Calendar.as │ │ ├── TimeRelationships.as │ │ ├── Timezone.as │ │ ├── addWeeks.as │ │ ├── ceil.as │ │ ├── clone.as │ │ ├── compareDates.as │ │ ├── dayAbbrNames.as │ │ ├── dayNames.as │ │ ├── equals.as │ │ ├── floor.as │ │ ├── formatDate.as │ │ ├── formatWeekOf.as │ │ ├── getAMPM.as │ │ ├── getCountdownUntil.as │ │ ├── getDayAbbrName.as │ │ ├── getDayAsString.as │ │ ├── getDayName.as │ │ ├── getDayOfTheYear.as │ │ ├── getDaysInMonth.as │ │ ├── getEarliestDate.as │ │ ├── getFormattedDifferenceFromUTC.as │ │ ├── getInternetTime.as │ │ ├── getLastMonday.as │ │ ├── getLastSunday.as │ │ ├── getLatestDate.as │ │ ├── getMeridiem.as │ │ ├── getMonthAbbrName.as │ │ ├── getMonthName.as │ │ ├── getNextDay.as │ │ ├── getPreviousDay.as │ │ ├── getShortHour.as │ │ ├── getShortYear.as │ │ ├── getStartOfWeek.as │ │ ├── getTimeBetween.as │ │ ├── getTimeElapsedString.as │ │ ├── getTimezone.as │ │ ├── getUTCDate.as │ │ ├── getWeekOfTheYear.as │ │ ├── isDaylightSavings.as │ │ ├── isInCurrentWeek.as │ │ ├── isLeapYear.as │ │ ├── isPast.as │ │ ├── iso8601ToDate.as │ │ ├── makeMorning.as │ │ ├── makeNight.as │ │ ├── monthAbbrNames.as │ │ ├── monthNames.as │ │ ├── parseW3CDTF.as │ │ ├── timeCode.as │ │ ├── toW3CDTF.as │ │ └── toggleAMPM.as │ ├── dictionary/ │ │ ├── CircularDictionary.as │ │ ├── getKeys.as │ │ └── getValues.as │ ├── display/ │ │ ├── Alignment.as │ │ ├── IDisplayObject.as │ │ ├── addChild.as │ │ ├── applyNaturalScrollRect.as │ │ ├── bringForward.as │ │ ├── bringToFront.as │ │ ├── centerWithin.as │ │ ├── createBitmap.as │ │ ├── createThumb.as │ │ ├── cropBitmapData.as │ │ ├── duplicateDisplayObject.as │ │ ├── filterChildrenByProps.as │ │ ├── findAncestor.as │ │ ├── findAncestorWithType.as │ │ ├── fitIntoRect.as │ │ ├── getChildren.as │ │ ├── getFullBounds.as │ │ ├── getParents.as │ │ ├── isVisible.as │ │ ├── localToLocal.as │ │ ├── moveBy.as │ │ ├── moveTo.as │ │ ├── originalHeight.as │ │ ├── originalWidth.as │ │ ├── relativePos.as │ │ ├── removeAllChildren.as │ │ ├── removeAllChildrenByType.as │ │ ├── removeChild.as │ │ ├── removeChildAt.as │ │ ├── scheduleForNextFrame.as │ │ ├── sendBackward.as │ │ ├── sendToBack.as │ │ ├── setProperties.as │ │ ├── showChildren.as │ │ ├── stopAllTimelines.as │ │ ├── sumProps.as │ │ ├── traceChildren.as │ │ ├── transformToFitRect.as │ │ └── wait.as │ ├── draw/ │ │ ├── createCircleShape.as │ │ ├── createEllipseShape.as │ │ ├── createRectangleShape.as │ │ ├── drawRoundRect.as │ │ └── drawWedge.as │ ├── error/ │ │ └── getStackTrace.as │ ├── frame/ │ │ ├── addFrameScript.as │ │ ├── getFrameNumberForLabel.as │ │ └── removeFrameScript.as │ ├── fullscreen/ │ │ └── toggleFullScreen.as │ ├── garbageCollection/ │ │ └── gc.as │ ├── geom/ │ │ ├── Direction.as │ │ ├── Ellipse.as │ │ ├── Point3d.as │ │ ├── Side.as │ │ ├── angle.as │ │ ├── cartesianToPolarCoordinates.as │ │ ├── getRectangleCenter.as │ │ ├── getRectanglePerimeter.as │ │ ├── polarToCartesianCoordinates.as │ │ ├── randomPoint.as │ │ ├── reverseRectangle.as │ │ ├── rotatePoint.as │ │ ├── roundPoint.as │ │ ├── simplifyAngle.as │ │ └── trimAngle.as │ ├── html/ │ │ ├── a.as │ │ ├── br.as │ │ ├── entities.as │ │ ├── img.as │ │ ├── p.as │ │ ├── span.as │ │ └── styledTag.as │ ├── js/ │ │ └── callJSFunction.as │ ├── library/ │ │ ├── getBitmapDataFromLibrary.as │ │ ├── getClassFromLibrary.as │ │ └── getClipFromLibrary.as │ ├── load/ │ │ ├── calculateBps.as │ │ ├── calculateBufferPercent.as │ │ ├── calculateKBps.as │ │ ├── calculateMillisecondsUntilBuffered.as │ │ └── checkDomain.as │ ├── location/ │ │ ├── getDomain.as │ │ ├── getLocationName.as │ │ ├── isDomain.as │ │ ├── locationNames.as │ │ ├── openURL.as │ │ ├── openWindow.as │ │ └── windowNames.as │ ├── math/ │ │ ├── Percent.as │ │ ├── Range.as │ │ ├── expressAsOdds.as │ │ └── gcd.as │ ├── mvc/ │ │ ├── AbstractController.as │ │ ├── AbstractModel.as │ │ ├── AbstractView.as │ │ ├── IController.as │ │ ├── IModel.as │ │ └── IView.as │ ├── number/ │ │ ├── addLeadingZeroes.as │ │ ├── clamp.as │ │ ├── createStepsBetween.as │ │ ├── fastMax2.as │ │ ├── fastMin2.as │ │ ├── format.as │ │ ├── getOrdinalSuffix.as │ │ ├── getWeightedAverage.as │ │ ├── hexChars.as │ │ ├── insertCommas.as │ │ ├── interpolate.as │ │ ├── isBetween.as │ │ ├── isEqual.as │ │ ├── isEven.as │ │ ├── isInteger.as │ │ ├── isNegative.as │ │ ├── isOdd.as │ │ ├── isPositive.as │ │ ├── isPrime.as │ │ ├── isRoughlyEqual.as │ │ ├── loopIndex.as │ │ ├── map.as │ │ ├── max.as │ │ ├── min.as │ │ ├── normalize.as │ │ ├── pad.as │ │ ├── randomIntegerWithinRange.as │ │ ├── randomSign.as │ │ ├── randomWithinRange.as │ │ ├── rol.as │ │ ├── ror.as │ │ ├── round.as │ │ ├── roundDecimalToPlace.as │ │ └── toHex.as │ ├── object/ │ │ ├── assign.as │ │ ├── clone.as │ │ ├── combine.as │ │ ├── contains.as │ │ ├── copy.as │ │ ├── create.as │ │ ├── createInstance.as │ │ ├── getKeys.as │ │ ├── hasAnyProperties.as │ │ ├── inspect.as │ │ ├── isEmpty.as │ │ ├── isNull.as │ │ ├── isSimple.as │ │ ├── isUniformPropertyType.as │ │ ├── merge.as │ │ ├── numProperties.as │ │ ├── toArray.as │ │ └── toString.as │ ├── range/ │ │ ├── center.as │ │ ├── isInRange.as │ │ ├── randomRangeDate.as │ │ ├── randomRangeSet.as │ │ └── resolve.as │ ├── ratio/ │ │ ├── defineRect.as │ │ ├── heightToWidth.as │ │ ├── scale.as │ │ ├── scaleHeight.as │ │ ├── scaleToFill.as │ │ ├── scaleToFit.as │ │ ├── scaleWidth.as │ │ └── widthToHeight.as │ ├── string/ │ │ ├── addSlashes.as │ │ ├── afterFirst.as │ │ ├── afterLast.as │ │ ├── arrayList.as │ │ ├── beforeFirst.as │ │ ├── beforeLast.as │ │ ├── beginsWith.as │ │ ├── between.as │ │ ├── constants.as │ │ ├── convertBytesString.as │ │ ├── detectBr.as │ │ ├── endsWith.as │ │ ├── equals.as │ │ ├── firstToUpper.as │ │ ├── getLettersFromString.as │ │ ├── htmlDecode.as │ │ ├── htmlEncode.as │ │ ├── ltrim.as │ │ ├── numberToString.as │ │ ├── padLeft.as │ │ ├── padRight.as │ │ ├── randomCharacters.as │ │ ├── randomLowercaseCharacters.as │ │ ├── randomNumberString.as │ │ ├── randomSequence.as │ │ ├── randomSpecialCharacters.as │ │ ├── remove.as │ │ ├── removeExtraWhitespace.as │ │ ├── removeSpaces.as │ │ ├── removeTabs.as │ │ ├── repeat.as │ │ ├── replace.as │ │ ├── reverse.as │ │ ├── reverseWords.as │ │ ├── rtrim.as │ │ ├── sanitizeNull.as │ │ ├── search.as │ │ ├── slashUnsafeChars.as │ │ ├── stringHasValue.as │ │ ├── stringsAreEqual.as │ │ ├── stripSlashes.as │ │ ├── stripTags.as │ │ ├── toDoubleQuote.as │ │ ├── toNumeric.as │ │ ├── toSingleQuote.as │ │ ├── toTitleCase.as │ │ ├── trim.as │ │ ├── trimCamel.as │ │ ├── truncate.as │ │ ├── truncate2.as │ │ ├── wordCount.as │ │ └── xtrim.as │ ├── swf/ │ │ └── SWFReader.as │ ├── textField/ │ │ ├── TextFieldWrapper.as │ │ ├── clearFields.as │ │ ├── createField.as │ │ ├── formatFields.as │ │ ├── getUsableFonts.as │ │ ├── hideFields.as │ │ ├── revealFields.as │ │ ├── setFormattedText.as │ │ ├── setStyledText.as │ │ ├── setTextColor.as │ │ ├── setTextFont.as │ │ ├── setTextLeading.as │ │ ├── setTextLetterSpacing.as │ │ ├── setTextSpaceWidth.as │ │ ├── styleFields.as │ │ ├── truncateMultilineText.as │ │ └── truncateText.as │ ├── type/ │ │ ├── PACKAGE_CLASS_SEPARATOR.as │ │ ├── convertFullyQualifiedName.as │ │ ├── describeInheritance.as │ │ ├── describeMethods.as │ │ ├── describeProperties.as │ │ ├── describeType.as │ │ ├── forInstance.as │ │ ├── forName.as │ │ ├── getClass.as │ │ ├── getClassByName.as │ │ ├── getClassName.as │ │ ├── getDisplayObjectClass.as │ │ ├── getFullyQualifiedName.as │ │ ├── getFullyQualifiedSuperClassname.as │ │ ├── getName.as │ │ ├── getNameFromFullyQualifiedName.as │ │ ├── getPropertyType.as │ │ ├── getSuperClassName.as │ │ ├── getType.as │ │ ├── isInterface.as │ │ ├── isPassedByValue.as │ │ ├── isType.as │ │ ├── newInstance.as │ │ ├── registerType.as │ │ ├── strictIs.as │ │ └── typeCache.as │ ├── validation/ │ │ ├── US_STATE_ABBREVIATIONS.as │ │ ├── encodeCreditCardNumber.as │ │ ├── getCreditCardProvider.as │ │ ├── isBlank.as │ │ ├── isCreditCard.as │ │ ├── isEmail.as │ │ ├── isNumeric.as │ │ ├── isPOBox.as │ │ ├── isURL.as │ │ ├── isUSAStateAbbreviation.as │ │ ├── isValidCreditCardNumber.as │ │ ├── isValidEmailAddress.as │ │ ├── isValidExpirationDate.as │ │ └── isValidPhoneNumber.as │ └── xml/ │ ├── XMLConstants.as │ ├── getNextSibling.as │ ├── getPreviousSibling.as │ ├── getSiblingByIndex.as │ └── isValidXML.as └── test/ ├── UtilsTestRunner.as ├── UtilsTestSuite.as └── utils/ ├── align/ │ ├── AlignLeftTest.as │ ├── AlignRightTest.as │ └── alignCenterTest.as ├── date/ │ ├── GetNextDayTest.as │ ├── GetPrevDayTest.as │ ├── GetTimeElapsedStringTest.as │ └── calendar/ │ └── CalendarTests.as ├── dictionary/ │ └── CircularDictionaryTest.as ├── display/ │ └── FindAncestorTest.as ├── geom/ │ ├── CartesianToPolarCoordinatesTest.as │ └── PolarToCartesianCoordinatesTest.as ├── number/ │ ├── ClampTest.as │ └── ToHexTest.as ├── object/ │ ├── CreateInstanceTest.as │ ├── CreateTest.as │ ├── MergeTest.as │ ├── cloneTest.as │ └── containsTest.as ├── range/ │ └── RandomRangeDateTest.as ├── string/ │ ├── numberToStringTest.as │ └── stringHasValueTest.as ├── type/ │ ├── IsPassedByValueTest.as │ └── StrictIsTest.as ├── validation/ │ ├── IsValidEmailAddressTest.as │ ├── encodeCreditCardNumberTest.as │ ├── getCreditCardProviderTest.as │ ├── isBlankTest.as │ ├── isCreditCardTest.as │ ├── isEmailTest.as │ ├── isNumericTest.as │ ├── isPOBoxTest.as │ ├── isUSAStateAbbreviationTest.as │ ├── isUrlTest.as │ ├── isValidCreditCardNumberTest.as │ ├── isValidExpirationDateTest.as │ └── isValidPhoneNumberTest.as └── xml/ ├── GetNextSiblingTest.as ├── GetPreviousSiblingTest.as ├── GetSiblingByIndexTest.as └── isValidXMLTest.as ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ src/FlexUnitApplication.mxml src/FlexUnitCompilerApplication.mxml target bin/FlexUnitApplication.swf bin-debug bin-release *.iml .actionScript* .flex* .Flex* .project .settings/ .DS_Store launch org.eclipse.core.resources.prefs ================================================ FILE: Contribution Guidelines.md ================================================ #Contribution Guidelines As developers, many of us have created our own working set of classes and functions for handling the common programming tasks we come across every day. But why reinvent the wheel? **AS3-Utils** is an attempt to gather together code from all of these disparate libraries into one place in hopes of creating a reusable, well-tested, well-documented, and freely-available unified collection. If you have code in a personal library / pile of snippets that you'd like to add, please refer to these guidelines. ##What to contribute ###Flash Player Versions AS3-utils targets Flash Player 10.0+. That said, most of the snippets will work for FP 9. If there is ever a significant need for a FP9 (or 11+) version of the library, we would encourage branching or forking the project to accommodate this. Please include the minimum Flash Player version in your ASDocs if it requires FP10 or later to compile. (See Documentation below) Nothing should rely on the Flex framework (or any external libraries). ###Functions vs. Classes We've been leaning towards a *functions only* approach. This means: 1. You can type `utils.foo.bar` to explore what's available in any IDE. 1. You only have to import the single function you need instead of a class. 1. Fewer dependencies on other pieces of the library. Less reading documents in order to use the functionality you want. If you have a utility class that you'd like to add to the library, try breaking it into smaller functions before adding it. In other words, don't add `com.you.ArrayUtil`, instead add the functions within as standalone .as files. As a general guideline, contributors should always favor "snippets" over more complex object-oriented functionality. Basically, you should be able to copy/paste the function into your own class and have it "just work". Anything more complex than that would need to have an argument as to why it belongs in a utils library rather than its own library. An exception could be made for support classes that are included as internal classes but aren't accessed on their own. ####Constants Constants that can be used in a general way can be added. If there is a single constant, Pi for example, you can add it as its own standalone .as file. // PI.as package utils.number { public const PI:Number = 3.141; } If the constant value is part of an enumeration of values, you may include it in an enumeration class. // CommonColors.as package utils.color { public class CommonColors { public const RED:uint = 0xFF0000; public const GREEN:uint = 0x00FF00; public const BLUE:uint = 0x0000FF; } } ###Integrating Libraries There's a list of libraries to integrate into AS3-utils. If you'd like to pull in the utility functions from them, please do so with respect to the licenses and authors of the original code. Again, this is a snippet library rather than a collection of classes so break down the code into atomic functions with as few dependencies as possible. ###Naming - Please use self-explanatory names for your functions and avoid using abbreviations. Strive for clarity over brevity. E.g. `truncateMultilineText()`, NOT `truncMLText()` - Function names should all begin with some kind of _descriptive_ verb. E.g. - `displayDialog()` NOT `dialog()` or `doDialog()` - `getName()` or `get name()` NOT `name()` - Predicate functions, functions that return a boolean must start with `is` (as if answering a question). E.g. `isEmptyString(value:String):Boolean` NOT `empty(value:String):Boolean` - Parameter names must be descriptive. E.g. `alignLeft(objectsToAlign:Array):void` instead of `alignLeft(a:Array):void` - Variable names must be descriptive. E.g. `var targetWidth:int = target.width` instead of `var tw:int = target.width` - Please use US English for all terms. E.g. `getColor()` not `getColour()` - Remember that in common practice the package name will not be included in people's code. Therefore, to make code more readable, avoid ambiguous names for functions and classes. Rather than relying on the package name to imply what the function does, include include it in the name of the function. E.g. * `convertHexStringToUint(hexString:String):uint`, NOT `convertToUint(s:String):uint` * `XMLConstants` or better yet, `XMLNodeType`, NOT `Constants` * `utils.foo.getFooAsString()`, NOT `utils.foo.toString()` - When in doubt, use naming conventions from ActionScript and the FlashPlayer API. ###Packages Here are general guidelines for how to pick a package. * Check to see what packages already exist before creating a new one. If possible, use one of the existing packages. **Do not** use your own package names (e.g. `com.mimswright`) * If a utility function operates mainly on a particular class from the Flash Player API, use the same package name as that class. E.g. if your function deals mostly with `Sprites`, use the `utils.display` package. * If your function is related to a root-level class in the Flash API, such as `Array`, use `utils.array`. * If you have a significant set of functions that relates to a specific class within a package, you may create a new package just for that class. For example, if you have several functions that all deal with `Point`, could go in `utils.geom.point`. * If you're Peter Piper, pick a peck of pickled packages. ##Deprecating and Replacing Existing Code What do you do if you want to contribute a piece of code that is very similar to one that already exists? * **First, always check for code that could function similarly to your code.** * If you find similar code to something you want to commit, think carefully. * If your code and their code do virtually the same thing the same way, suck it up and **keep the existing code**. * Only edit or replace existing code if there are tests. If there are not tests, write tests against the existing code then replace with your version. Ensure the tests still pass before committing. * Writing a note explaining why you made the change is encouraged. * If you find checked-in code that is a duplicate of another piece of code, keep the one that is clearer and more robust and remove the other. * You may make changes to names of functions if they are unclear or don't meet the naming requirements but in general, try not to change things around based only on your personal style. ##Unit Tests Needless to say, code should not cause any compile errors or warnings. New code snippets must be covered by tests. Tests should demonstrate correct usage, with as many unique scenarios as the code is expected to handle. Fringe cases that may throw errors should be demonstrated if possible, e.g. passing `null` to a function that expects a parameter of type `Array`. Tests should be written using FlexUnit 4.0+. If you come across code that needs a unit test written for it, you are encouraged to write one. You will earn much karma. More on FlexUnit and Testing on [Elad Elrom's Blog](http://elromdesign.com/blog/2010/03/10/test-driven-development-tdd-with-flexunit-4-complete-tutorial/). ##Documentation Please add [ASDoc](http://help.adobe.com/en_US/flex/using/WSd0ded3821e0d52fe1e63e3d11c2f44bb7b-7fe7.html)-style documentation to everything. Your code should have at least these tags in every function or class. * `@author Your Name` * `@param paramName Description.` if there are any params * `@return Type Description.` if not `void` * `@throws package.ErrorType Description.` if it throws an error * `@example code` for example code. (A good habit is write the example first, then the docs, then the tests, then the code.) * `@playerversion Flash 10.1` If your code will only work on a player later than 9.0 Example code is optional for simple functions but please include a description of what the code is designed to achieve and/or why you might want to use it. Include any licensing that applies to your functions. Feel free to add docs to other people's code if there are none. ##Merge Strategy Submitters should follow these steps when contributing code to the project. __SUBMITTERS:__ 1. Create a fork of the project. 1. Make your changes, test, and commit them. 1. When you're ready to integrate the changes into the main branch, create a pull request. 1. Don't merge your own pull request even if you're an admin. Instead, ask for assistance from someone else to review your pull request and merge it into the master. 1. If you're an admin and are anxious with waiting for your pull request to be handled, review and pull someone else's code while you wait. __ADMINS:__ 1. Review the commits by checking them out to a local repository. 1. Ask questions of the submitter or other admins! 1. Write tests & improve docs or request that the submitter do so. 1. Remember to run the test suite before merging code into master. 1. You can reformat the incoming code using the `res/flex-formatter.properties` file. (Optional) 1. Big changes can/should first be merged into a separate integration branch at your discretion. ###Why not merge your own code? This is a collection made for everyone made up of several people's personal code library. The chances of adding duplicate or idiosyncratic code is very high. Using the pull-request scheme is a great way for us to make sure all the code is being reviewed by *someone* other than the author. The more people who review code the less chance of checking in a duplicate or buggy piece of code. Furthermore, gitHub is set up to handle a distributed repository workflow very elegantly. If at any point you want to break out and work on your own personal code library, that's easy to do in your own fork. ================================================ FILE: Libraries to integrate.md ================================================ * Sekati - [http://code.google.com/p/sekati/](http://code.google.com/p/sekati/) * BumpSlide - [http://code.google.com/p/bumpslide/](http://code.google.com/p/bumpslide/) * as3MathLib - [http://code.google.com/p/as3mathlib/](http://code.google.com/p/as3mathlib/) * casaLib - [http://casalib.org/about/](http://http://casalib.org/about/) ================================================ FILE: NOTES.md ================================================ # as3-utils # ISSUES - parameter names are not descriptive - variable names are not descriptive - nomenclature is inconsistent -- use functional-programming names? -- use designer friendly names? -- provide aliases for common functions with multiple common names? - ASDocs -- missing tags -- incorrect descriptions -- incorrect tags # Refactoring Guidelines - predicate methods should be prefixed with is* # AUDIT The below is the results of a quick audit of the functions available in as3-utils, and their specific issues. # ALIGN alignLeft alignToRectangleLeft duplicates alignRight alignToRectangleRight duplicates align to edges distribute by edges grid alignment hAlign(targets:Array, hSpacing:int = 0, alignment:Alignment = Alignment.LEFT):Array vAlign(targets:Array, vSpacing:int = 0, alignment:Alignment = Alignment.TOP):Array gAlign(targets:Array, columns:int, rows:int, hSpacing:int = 0, vSpacing:int = 0, alignment:Alignment = Alignment.TOP_LEFT):Array gAlign = gridAlign /** * Aligns all the target DisplayObjects by their left edge to the left-most target. * * Similar to the Flash IDE Alignment panel. */ alignLeft(targets:Vector.):Vector. /** * Aligns all the target DisplayObjects by their right edge to the right-most target. * * Similar to the Flash IDE Alignment panel. */ alignRight(targets:Vector.):Vector. /** * Aligns all the target DisplayObjects by their top edges to the top-most target. * * Similar to the Flash IDE Alignment panel. */ alignTop(targets:Vector.):Vector. /** * Aligns all the target DisplayObjects by their bottom edges to the bottom-most target. * * Similar to the Flash IDE Alignment panel. */ alignBottom(targets:Vector.):Vector. /** * Aligns all the target DisplayObjects by their horizontal center edges to the horizontal center of the all the targets. * * Similar to the Flash IDE Alignment panel. */ alignHorizontalCenter(targets:Vector.):Vector. /** * Aligns all the target DisplayObjects by their vertical center edges to the vertical center of the all the targets. * * Similar to the Flash IDE Alignment panel. */ alignVerticalCenter(targets:Vector.):Vector. alignToLeftEdge(of:DisplayObject, ...targets) alignLeftEdges(...targets):Array alignRightEdges(...targets):Array alignTopEdges(...targets):Array alignBottomEdges(...targets):Array alignCenters(...targets):Array distributeByLeftEdge(...targets):Array distributeByRightEdge(...targets):Array distributeByTopEdge(...targets):Array distributeByBottomEdge(...targets):Array distributeByHorizontalCenter(...targets):Array distributeByVerticalCenter(...targets):Array # ARRAY utils.array.contains():int badly named, should be something like numReferencesInArray, arrayRefCount utils.array.copyArray() remove, pointless, use array.slice() instead. utils.array.createUniqueCopy utils.array.removeDuplicates duplicates asx.array.unique utils.array.arraysAreEqual utils.array.equals duplicates utils.array.getHighestValue utils.array.getLowestValue use the Array constants, not magic numbers utils.array.randomize too much code for what it does could be faster utils.array.removeItem utils.array.removeValueFromArray duplicates utils.array.retainItems duplicates asx.array.union utils.array.sum duplicates asx.array.sum # ASSERT utils.assert.* suggestion: use the assertions provided by hamcrest-as3 or flexunit should throw an AssertionError instead of Error utils.capabilities.getPlayerInfo dubious value # CAPABILITIES utils.capabilities.isMac utils.capabilities.isPC change isMac to be !isPC DRY # COLOR utils.color.randomColor implementation is whack, why convert to a Number to a String to a Number? utils.color.toGrayscale which reference was used for the mix ratios? # COOKIE utils.cookie.setCookie potential global javascript namespace pollution # DATE utils.date.toRFC822 missing result examples, and appears to reference the wrong RFC number utils.date.toW3CDTF missing result examples # DISPLAY utils.display.addTargetToParent dubious value uses a switch for two values uses magic numbers utils.display.Alignment values should be same as key move to utils.align.Alignment eg BOTTOM_LEFT:String = "BOTTOM_LEFT" utils.display.sumProps remove replace with utils.number.sum, asx.object.pluck # ERROR utils.error.getStackTrace no try-catch required return new Error().getStackTrace(); dubious value # EVENT utils.event.addTargetEventListener utils.event.removeTargetEventListener dubious value # FRAME utils.frame.addFrameScript utils.frame.removeFrameScript needs an appropriate error message can multiple framescripts exist on a single frame? # GEOM utils.geom.Point3D move static methods to instance method, both deal with Point3D as arguments, and there are already instance methods for add, subtract, offset # NUMBER utils.number.clamp utils.number.confine utils.number.constrain utils.range.resolve duplicates asx.number.bound replace with clamp utils.number.insertCommas there is easier way to do this, using reverse, split and join utils.number.isBetween duplicates asx.number.between # RANGE utils.range.resolve duplicates utils.number.clamp etc # STRING utils.string.addSlashes bad name, escapeChars is more accurate utils.string.slashUnsafeChars bad name, escapeRegExpChars is more accurate utils.string.constants bad name, separate to package level or rename utils.string.firstToUpper bad name, rename to capitalize utils.string.replace dubious value utils.string.stripSlashes bad name, unescapeChars ================================================ FILE: README.md ================================================ # as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? HEAPS, too much to list here right now. Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html - number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? Check out the [contribution guidelines](https://github.com/as3/as3-utils/blob/master/Contribution%20Guidelines.md). Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) - Joel Hooks [@jhooks](http://twitter.com/jhooks) - Mims H. Wright [@mimshwright](http://twitter.com/mimshwright) - Ian McLean [@ianmclean](http://twitter.com/ianmclean) - [You?](https://github.com/as3/as3-utils/blob/master/Contribution%20Guidelines.md) # Giving credit where credit is due Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. If you include your own code in the library, please be sure to add a credit for yourself in the comments or use an @author tag in the asDocs. # License Since many of the functions in the library are pulled or adapted from other sources, there is no single license that covers everything. However, the intent is for this code to be freely available and editable, a la the MIT license, except where otherwise noted. We've done our best to include appropriate attribution and license where required but if you see something that should not be in here, please let us know and we will remove it. ================================================ FILE: TODO.md ================================================ # TODO - combine with [asx](http://github.com/drewbourne/asx) - attribute all functions to proper authors - check utils for duplicates - clean package structure - clean parameter names to be descriptive - code formatting - build out tests - optimize - documentation - examples - replace default FlexPMD ruleset as it is awkward. ================================================ FILE: build/pmd/LICENSE.txt ================================================ Copyright (c) 2009, Adobe Systems, Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Adobe Systems, Incorporated. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: build.properties ================================================ project.name=as3-utils build.groupId=as3 build.artifactId=as3-utils build.version=0.1 build.artifact=${build.artifactId}-${build.version} test.runner=UtilsTestRunner test.runner.ext=as flexunit.version=4.1.0-33 flexsdk.version=3.5.0.12683 flexpmd.version=1.1 ================================================ FILE: build.xml ================================================ true true ================================================ FILE: res/flex-formatter.properties ================================================ #FlexFormatter settings #Sat Apr 10 22:47:59 EST 2010 ASRearr_UseModifierOrder_Function=true Actionscript.useBraceStyle=false ASRearr_ModifierOrder_Property=,override,native,public,private,protected,internal,static,dynamic,final ASRearr_UseSectionHeadersInMXML=false ASRearr_ModifierOrder_Class=,override,native,public,private,protected,internal,static,dynamic,final ASRearr_GroupGettersAndSettersWithStaticProperties=false ASRearr_ElementSortStaticProperties=true ASRearr_ElementStaticFunctionVisibilityOrder=public\:true,protected\:true,internal\:true,private\:true, MXML.attrWrapMode=52 ASRearr_UseElementStaticPropertyVisibilityOrder=true ASRearr_SortGettersAndSettersWithAssociatedProperties=true ASRearr_ElementSortImports=true ASRearr_ElementOrder=Import,Include,Namespace Definition,Default Namespace,Namespace Use,Static Property,Static Function,Static Initializer,Constructor,Property,Function, Actionscript.spacesAfterComma=1 Actionscript.advancedSpacesAroundEqualsInOptionalParameters=0 ASRearr_ElementFunctionVisibilityOrder=public\:true,protected\:true,internal\:true,private\:true, MXML.blankLinesAfterSpecificParentTags=0 MXML.onlyFormatASIfCDATABlock=false Actionscript.advancedWrappingElements=165 Actionscript.spacesBeforeComma=0 Actionscript.advancedSpacesInsideLiteralBraces=1 Actionscript.wrapArrayDeclMode=4 ASRearr_SectionHeaderMap=\#\n\#Sat Apr 10 22\:47\:59 EST 2010\n ASRearr_RemoveExistingCopyrightHeaders=false Actionscript.newLineBeforeBindableProperty=true Flex.useTabs=true ASRearr_ElementSortMetatags=false MXML.attrsToKeepOnSameLine=4 MXML.sortAttrMode=0 Actionscript.wrapMethodCallMode=4 Actionscript.spacesBeforeControlOpenParen=1 Actionscript.spacesAfterColons=0 Actionscript.useGlobalCRBeforeBrace=true Actionscript.blankLinesBeforeFunctions=1 MXML.spacesAroundEquals=0 ASRearr_AddDefaultHeaderForStaticProperties=1 ASRearr_UseModifierOrder_Class=true Actionscript.breakLinesBeforeComma=false Actionscript.spacesAroundAssignment=1 ASRearr_ElementSortIncludes=true MXML.wrapIndentStyle=1001 Actionscript.leaveExtraWhitespaceAroundVarDecls=false MXML.maxLineLength=200 Actionscript.putEmptyStatementsOnNewLine=true ActionScript.metatagsOnSameLineAsTargetProperty=Bindable Actionscript.wrapExpressionMode=4 ASRearr_UseElementStaticFunctionVisibilityOrder=true Actionscript.spacesAroundColons=0 ASRearr_UseSectionHeaders=false Actionscript.advancedUseSpacesAroundEqualsInOptionalParameters=true Actionscript.useAdvancedWrapping=false Actionscript.putOpenBraceOnNewLine=true MXML.blankLinesBeforeTags=0 Actionscript.blankLinesBeforeControlStatements=0 ASRearr_RemoveExistingSectionHeaders=false Actionscript.putWhileOnNewLine=true Actionscript.advancedCRBeforeBraceSettings=2047 Actionscript.dontIndentPackageItems=false Actionscript.keepBlankLines=true MXML.keepBlankLines=true ASRearr_BlankLinesBeforeElement= ASRearr_UseMetatagOrder=false ActionScript.spacesBeforeFormalParameters=0 MXML.attrGroups=name\=properties|sort\=11|includeStates\=true|wrap\=54|attrs\=allowDisjointSelection,allowMultipleSelection,allowThumbOverlap,allowTrackClick,autoLayout,autoRepeat,automationName,cachePolicy,class,clipContent,condenseWhite,conversion,creationIndex,creationPolicy,currentState,data,dataDescriptor,dataProvider,dataTipFormatFunction,dayNames,defaultButton,direction,disabledDays,disabledRanges,displayedMonth,displayedYear,doubleClickEnabled,emphasized,enabled,explicitHeight,explicitMaxHeight,explicitMaxWidth,explicitMinHeight,explicitMinWidth,explicitWidth,firstDayOfWeek,focusEnabled,fontContext,height,horizontalLineScrollSize,horizontalPageScrollSize,horizontalScrollBar,horizontalScrollPolicy,horizontalScrollPosition,htmlText,icon,iconField,id,imeMode,includeInLayout,indeterminate,label,labelField,labelFunction,labelPlacement,labels,layout,lineScrollSize,listData,liveDragging,maxChars,maxHeight,maxScrollPosition,maxWidth,maxYear,maximum,measuredHeight,measuredMinHeight,measuredMinWidth,measuredWidth,menuBarItemRenderer,menuBarItems,menus,minHeight,minScrollPosition,minWidth,minYear,minimum,mode,monthNames,monthSymbol,mouseFocusEnabled,pageScrollSize,pageSize,percentHeight,percentWidth,scaleX,scaleY,scrollPosition,selectable,selectableRange,selected,selectedDate,selectedField,selectedIndex,selectedRanges,showDataTip,showRoot,showToday,sliderDataTipClass,sliderThumbClass,snapInterval,source,states,stepSize,stickyHighlighting,styleName,text,text,thumbCount,tickInterval,tickValues,toggle,toolTip,transitions,truncateToFit,validationSubField,value,value,verticalLineScrollSize,verticalPageScrollSize,verticalScrollBar,verticalScrollPolicy,verticalScrollPosition,width,x,y,yearNavigationEnabled,yearSymbol,|data\=-1|\nname\=xml_namespaces|sort\=11|includeStates\=true|wrap\=54|attrs\=xmlns,xmlns\:.*,|data\=-1|\nname\=events|sort\=11|includeStates\=true|wrap\=54|attrs\=add,added,activate,addedToStage,buttonDown,change,childAdd,childIndexChange,childRemove,clickHandler,clear,click,complete,contextMenu,copy,creationComplete,currentStateChange,currentStateChanging,cut,dataChange,deactivate,doubleClick,dragComplete,dragDrop,dragEnter,dragExit,dragOver,dragStart,effectEnd,effectStart,enterFrame,enterState,exitFrame,exitState,focusIn,focusOut,frameConstructed,hide,httpStatus,init,initialize,invalid,ioError,itemClick,itemRollOut,itemRollOver,keyDown,keyFocusChange,keyUp,menuHide,menuShow,middleClick,middleMouseDown,middleMouseUp,mouseDown,mouseUp,mouseOver,mouseMove,mouseOut,mouseFocusChange,mouseWheel,mouseDownOutside,mouseWheelOutside,move,nativeDragComplete,nativeDragDrop,nativeDragEnter,nativeDragExit,nativeDragOver,nativeDragStart,nativeDragUpdate,open,paste,preinitialize,progress,record,remove,removed,removedFromStage,render,resize,rightClick,rightMouseDown,rightMouseUp,rollOut,rollOver,scroll,securityError,selectAll,show,tabChildrenChange,tabEnabledChange,tabIndexChange,thumbDrag,thumbPress,thumbRelease,toolTipCreate,toolTipEnd,toolTipHide,toolTipShow,toolTipShown,toolTipStart,updateComplete,unload,valid,valueCommit,|data\=-1|\nname\=styles|sort\=11|includeStates\=true|wrap\=54|attrs\=backgroundAlpha,backgroundAttachment,backgroundColor,backgroundDisabledColor,backgroundImage,backgroundSize,backgroundSkin,barColor,barSkin,borderColor,borderSides,borderSkin,borderStyle,borderThickness,bottom,color,cornerRadius,dataTipOffset,dataTipPrecision,dataTipStyleName,disabledColor,disabledIcon,disabledIconColor,disabledSkin,disbledOverlayAlpha,downArrowDisabledSkin,downArrowDownSkin,downArrowOverSkin,downArrowUpSkin,downIcon,downSkin,dropShadowColor,dropShadowEnabled,errorColor,fillAlphas,fillColors,focusAlpha,focusBlendMode,focusRoundedCorners,focusSkin,focusThickness,fontAntiAliasType,fontFamily,fontGridFitType,fontSharpness,fontSize,fontStyle,fontThickness,fontWeight,fontfamily,headerColors,headerStyleName,highlightAlphas,horizontalAlign,horizontalCenter,horizontalGap,horizontalScrollBarStyleName,icon,iconColor,indeterminateMoveInterval,indeterminateSkin,itemDownSkin,itemOverSkin,itemUpSkin,kerning,labelOffset,labelStyleName,labelWidth,leading,left,letterSpacing,maskSkin,menuStyleName,nextMonthDisabledSkin,nextMonthDownSkin,nextMonthOverSkin,nextMonthSkin,nextMonthUpSkin,nextYearDisabledSkin,nextYearDownSkin,nextYearOverSkin,nextYearSkin,nextYearUpSkin,overIcon,overSkin,paddingBottom,paddingLeft,paddingRight,paddingTop,prevMonthDisabledSkin,prevMonthDownSkin,prevMonthOverSkin,prevMonthSkin,prevMonthUpSkin,prevYearDisabledSkin,prevYearDownSkin,prevYearOverSkin,prevYearSkin,prevYearUpSkin,repeatDelay,repeatInterval,right,rollOverColor,rollOverIndicatorSkin,selectedDisabledIcon,selectedDisabledSkin,selectedDownIcon,selectedDownSkin,selectedOverIcon,selectedOverSkin,selectedUpIcon,selectedUpSkin,selectionColor,selectionIndicatorSkin,shadowColor,shadowDirection,shadowDistance,showTrackHighlight,skin,slideDuration,slideEasingFunction,strokeColor,strokeWidth,textAlign,textDecoration,textIndent,textRollOverColor,textSelectedColor,themeColor,thumbDisabledSkin,thumbDownSkin,thumbIcon,thumbOffset,thumbOverSkin,thumbUpSkin,tickColor,tickLength,tickOffset,tickThickness,todayColor,todayIndicatorSkin,todayStyleName,top,tracHighlightSkin,trackColors,trackHeight,trackMargin,trackSkin,upArrowDisabledSkin,upArrowDownSkin,upArrowOverSkin,upArrowUpSkin,upIcon,upSkin,verticalAlign,verticalCenter,verticalGap,verticalScrollBarStyleName,weekDayStyleName,|data\=-1|\nname\=effects|sort\=11|includeStates\=true|wrap\=54|attrs\=addedEffect,completeEffect,creationCompleteEffect,focusInEffect,focusOutEffect,hideEffect,mouseDownEffect,mouseUpEffect,moveEffect,removedEffect,resizeEffect,rollOutEffect,rollOverEffect,showEffect,|data\=-1|\n ASRearr_UseModifierOrder_Property=true ASRearr_MoveImportsOutsideClass=true Actionscript.maxLineLength=200 Actionscript.spacesInsideParens=0 ASRearr_ElementSortProperties=true Actionscript.advancedSpacesInsideArrayRefBrackets=0 Actionscript.blankLinesToKeep=0 Actionscript.keepElseIfOnSameLine=true Actionscript.blankLinesBeforeProperties=0 Actionscript.advancedWrappingEnforceMax=false Actionscript.spacesBeforeColons=0 Actionscript.advancedWrappingPreservePhrases=true Actionscript.alwaysGenerateIndent=false ASRearr_UseElementPropertyVisibilityOrder=true MXML.parentTagsToHaveBlankLinesAddedAfterThem= Actionscript.spacesAfterLabel=1 ASRearr_AddDefaultHeaderForProperties=1 Actionscript.wrapMethodDeclMode=4 ASRearr_UseCopyrightGeneration=false Actionscript.useGlobalSpacesAroundColons=true ASRearr_ModifierOrder_Function=,override,native,public,private,protected,internal,static,dynamic,final ASRearr_ElementStaticPropertyVisibilityOrder=public\:true,protected\:true,internal\:true,private\:true, MXML.sortExtraAttrs=false Actionscript.tabCountForHangingIndent=1 ASRearr_ElementSortFunctions=true ASRearr_ElementPropertyVisibilityOrder=public\:true,protected\:true,internal\:true,private\:true, MXML.blankLinesAfterParentTags=0 ASRearr_GroupGettersAndSettersWithProperties=false Actionscript.wrapEmbeddedXMLMode=2 ASRearr_UseElementOrder=true Actionscript.doRearrangeWhileFormatting=false ASRearr_UseGlobalModifierOrder=true Actionscript.useGlobalSpacesInsideParens=false ASRearr_MajorSectionHeader=style\=1|width\=60|blankLines\=4|fillChar\=-|text\=|linesBefore\=1| Actionscript.putCatchOnNewLine=true ASRearr_CopyrightHeader=style\=1|width\=80|blankLines\=2|fillChar\=-|text\= Copyright 2010\n All rights reserved.|linesBefore\=1| ASRearr_ElementSortNamespaces=true Actionscript.putElseOnNewLine=true MXML.spacesBeforeEmptyTagEnd=0 ASRearr_ElementSortStaticFunctions=true Actionscript.wrapIndentStyle=1001 ASRearr_MetatagOrder=ArrayElementType,Bindable,DefaultProperty,Deprecated,Effect,Embed,Event,Exclude,ExcludeClass,IconFile,Inspectable,InstanceType,NonCommittingChangeEvent,RemoteClass,Style,SWF,Transient, Actionscript.braceStyle=5 MXML.alwaysUseMaxLineLength=false ASRearr_UseElementFunctionVisibilityOrder=true Actionscript.spacesAroundBinarySymbolicOperator=1 Actionscript.keepSLCommentsOnColumn1=true Actionscript.newLineBeforeBindableFunction=true MXML.tagsCanFormat=mx\:List,fx\:List, MXML.sortAttrData= ASRearr_MinorSectionHeader=style\=1|width\=40|blankLines\=0|fillChar\=-|text\=|linesBefore\=1| Actionscript.blankLinesBeforeClasses=1 MXML.tagsToHaveBlankLinesAddedBeforeThem= MXML.useAttrsToKeepOnSameLine=false ASRearr_UseImportOrder=true MXML.blankLinesBetweenSiblingTags=0 Actionscript.collapseSpacesForAdjacentParens=true Actionscript.advancedSpacesInsideArrayDeclBrackets=1 Actionscript.advancedSpacesInsideParens=0 Actionscript.advancedWrappingGraceColumns=5 MXML.tagsCannotFormat=mx\:String,fx\:String, MXML.attrsPerLine=1 ASRearr_ImportOrder=adobe,com,flash,mx, MXML.addNewlineAfterLastAttr=false MXML.tagsWithASContent=.*\:add,.*\:added,.*\:activate,.*\:addedToStage,.*\:buttonDown,.*\:change,.*\:childAdd,.*\:childIndexChange,.*\:childRemove,.*\:clickHandler,.*\:clear,.*\:click,.*\:complete,.*\:contextMenu,.*\:copy,.*\:creationComplete,.*\:currentStateChange,.*\:currentStateChanging,.*\:cut,.*\:dataChange,.*\:deactivate,.*\:doubleClick,.*\:dragComplete,.*\:dragDrop,.*\:dragEnter,.*\:dragExit,.*\:dragOver,.*\:dragStart,.*\:effectEnd,.*\:effectStart,.*\:enterFrame,.*\:enterState,.*\:exitFrame,.*\:exitState,.*\:focusIn,.*\:focusOut,.*\:frameConstructed,.*\:hide,.*\:httpStatus,.*\:init,.*\:initialize,.*\:invalid,.*\:ioError,.*\:itemClick,.*\:itemRollOut,.*\:itemRollOver,.*\:keyDown,.*\:keyFocusChange,.*\:keyUp,.*\:menuHide,.*\:menuShow,.*\:middleClick,.*\:middleMouseDown,.*\:middleMouseUp,.*\:mouseDown,.*\:mouseUp,.*\:mouseOver,.*\:mouseMove,.*\:mouseOut,.*\:mouseFocusChange,.*\:mouseWheel,.*\:mouseDownOutside,.*\:mouseWheelOutside,.*\:move,.*\:nativeDragComplete,.*\:nativeDragDrop,.*\:nativeDragEnter,.*\:nativeDragExit,.*\:nativeDragOver,.*\:nativeDragStart,.*\:nativeDragUpdate,.*\:open,.*\:paste,.*\:preinitialize,.*\:progress,.*\:record,.*\:remove,.*\:removed,.*\:removedFromStage,.*\:render,.*\:resize,.*\:rightClick,.*\:rightMouseDown,.*\:rightMouseUp,.*\:rollOut,.*\:rollOver,.*\:scroll,.*\:securityError,.*\:selectAll,.*\:show,.*\:tabChildrenChange,.*\:tabEnabledChange,.*\:tabIndexChange,.*\:thumbDrag,.*\:thumbPress,.*\:thumbRelease,.*\:toolTipCreate,.*\:toolTipEnd,.*\:toolTipHide,.*\:toolTipShow,.*\:toolTipShown,.*\:toolTipStart,.*\:updateComplete,.*\:unload,.*\:valid,.*\:valueCommit,.*\:Script, ActionScript.metatagsOnSameLineAsTargetFunction=Bindable ASRearr_SortGettersAndSettersWithAssociatedStaticProperties=true ================================================ FILE: src/.gitignore ================================================ FlexUnitApplication.mxml ================================================ FILE: src/deprecated/.gitignore ================================================ ================================================ FILE: src/deprecated/confine.as ================================================ package deprecated { [Deprecated(replacement="utils.number.clamp")] /** * Restricts the value to the min and max * @param value the number to restrict * @param min the minimum number for value to be * @param max the maximum number for value to be * @return */ public function confine(value:Number, min:Number, max:Number):Number { return value < min ? min : (value > max ? max : value); } } ================================================ FILE: src/deprecated/constrain.as ================================================ package deprecated { [Deprecated(replacement="utils.number.clamp")] /** Determines if value falls within a range; if not it is snapped to the nearest range value. @param value: Number to determine if it is included in the range. @param firstValue: First value of the range. @param secondValue: Second value of the range. @return Returns either the number as passed, or its value once snapped to nearest range value. @usageNote The constraint values do not need to be in order. @example trace(NumberUtil.constrain(3, 0, 5)); // Traces 3 trace(NumberUtil.constrain(7, 0, 5)); // Traces 5 */ public function constrain(value:Number, firstValue:Number, secondValue:Number):Number { return Math.min(Math.max(value, Math.min(firstValue, secondValue)), Math.max(firstValue, secondValue)); } } ================================================ FILE: src/deprecated/getURL.as ================================================ package deprecated { import flash.net.URLRequest; import flash.net.navigateToURL; [Deprecated(replacement="utils.location.openURL")] /** * getURL for ActionScript 3.0. Similar * to getURL of ActionScript 2.0 in simplicity * and ease. Errors are suppressed and traced * to the output window. * * @author Trevor McCauley - www.senocular.com */ public function getURL(url:String, target:String = null):void { try { navigateToURL(new URLRequest(url), target); } catch(error:Error) { trace("[getURL] " + error); } } } ================================================ FILE: src/deprecated/randomBoolean.as ================================================ package deprecated { [Deprecated(replacement="utils.boolean.randomChance")] /** * Returns a Boolean. * Example code: *
	 *          RandomUtils.boolean(); // returns true or false (50% chance of true)
	 *      
* Another example code: *
	 *          RandomUtils.boolean(0.8); // returns true or false (80% chance of true)
	 *      
* @param chance Chance Number (0-1) * @return Float Number between min-max exclusive. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function randomBoolean(chance:Number = 0.5):Boolean { return(Math.random() < chance); } } ================================================ FILE: src/deprecated/randomRangeFloat.as ================================================ package deprecated { [Deprecated(replacement="utils.number.randomWithinRange")] /** * Returns a random float number within a given range */ public function randomRangeFloat(min:Number, max:Number):Number { return Math.random() * (max - min) + min; } } ================================================ FILE: src/deprecated/randomRangeInt.as ================================================ package deprecated { [Deprecated(replacement="utils.number.randomIntegerWithinRange")] /** * Returns a random int number within a given range */ public function randomRangeInt(min:Number, max:Number):Number { return Math.floor(Math.random() * (max - min + 1) + min); } } ================================================ FILE: src/utils/align/alignCenter.as ================================================ package utils.align { import flash.display.DisplayObject; /** * Center align object to target. */ public function alignCenter(item:DisplayObject, target:DisplayObject):void { xAlignCenter(item, target); yAlignCenter(item, target); } } ================================================ FILE: src/utils/align/alignLeft.as ================================================ package utils.align { /** * Aligns all the target DisplayObjects by their left edge to the left-most target. * * Similar to the Flash IDE Alignment panel. * * Given the following arrangement of targets: * * t1 * t2 * t3 * * * After calling alignLeft([ t1, t2, t3 ]) the arrangment will be: * * t1 * t2 * t3 * * * @param targets Array of DisplayObject (or Object with an x property like Point). * @return targets Array. * * @example * * var t1:Sprite = new Sprite(); * t1.x = 5; * * var t2:Sprite = new Sprite(); * t2.x = 30; * * var t3:Sprite = new Sprite(); * t3.x = 15; * * var targets:Array = [t1, t2, t3]; * alignLeft(targets); * * trace(t1.x, t2.x t3.x); * // 5 5 5 * * * @author drewbourne */ public function alignLeft(targets:Array):Array { var minX:Number = Number.MAX_VALUE; var targetX:Number; var target:Object; for each (target in targets) { targetX = target.x; if (targetX < minX) minX = targetX; } for each (target in targets) { target.x = minX; } return targets; } } ================================================ FILE: src/utils/align/alignRight.as ================================================ package utils.align { /** * Aligns all the target DisplayObjects by their left edge to the left-most target. * * Similar to the Flash IDE Alignment panel. * * Given the following arrangement of targets: * * t1 * t2 * t3 * * * After calling alignRight([ t1, t2, t3 ]) the arrangment will be: * * t1 * t2 * t3 * * * @param targets Array of DisplayObject * or Object with an x property like Point * or Object with an x and width properties like Rectangle. * * @return targets Array. * * @example * * * * * @author drewbourne */ public function alignRight(targets:Array):Array { var maxX:Number = Number.MIN_VALUE; var targetW:Number; var targetX:Number; var target:Object; for each (target in targets) { targetW = "width" in target ? target["width"] : 0; targetX = target.x + targetW; if (targetX > maxX) maxX = targetX; } for each (target in targets) { targetW = "width" in target ? target["width"] : 0; target.x = maxX - targetW; } return targets; } } ================================================ FILE: src/utils/align/alignToRectangleBottom.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the bottom of the bounding Rectangle. @param displayObject The DisplayObject to align. @param bounds The area in which to align the DisplayObject. @param snapToPixel Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. @param outside Align the DisplayObject to the outside of the bounds true, or the inside false. */ public function alignToRectangleBottom(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true, outside:Boolean = false):void { var y:Number = outside ? bounds.bottom : bounds.bottom - displayObject.height; displayObject.y = snapToPixel ? Math.round(y) : y; } } ================================================ FILE: src/utils/align/alignToRectangleCenter.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the horizontal center of the bounding Rectangle. @param displayObject: The DisplayObject to align. @param bounds: The area in which to align the DisplayObject. @param snapToPixel: Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. */ public function alignToRectangleCenter(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true):void { var centerX:Number = bounds.width * 0.5 - displayObject.width * 0.5 + bounds.x; displayObject.x = snapToPixel ? Math.round(centerX) : centerX; } } ================================================ FILE: src/utils/align/alignToRectangleCenterMiddle.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the horizontal center and vertical middle of the bounding Rectangle. @param displayObject: The DisplayObject to align. @param bounds: The area in which to align the DisplayObject. @param snapToPixel: Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. */ public function alignToRectangleCenterMiddle(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true):void { alignToRectangleCenter(displayObject, bounds, snapToPixel); alignToRectangleMiddle(displayObject, bounds, snapToPixel); } } ================================================ FILE: src/utils/align/alignToRectangleLeft.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the left side of the bounding Rectangle. @param displayObject: The DisplayObject to align. @param bounds: The area in which to align the DisplayObject. @param snapToPixel: Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. @param outside: Align the DisplayObject to the outside of the bounds true, or the inside false. */ public function alignToRectangleLeft(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true, outside:Boolean = false):void { var x:Number = outside ? bounds.left - displayObject.width : bounds.left; displayObject.x = snapToPixel ? Math.round(x) : x; } } ================================================ FILE: src/utils/align/alignToRectangleMiddle.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the vertical middle of the bounding Rectangle. @param displayObject: The DisplayObject to align. @param bounds: The area in which to align the DisplayObject. @param snapToPixel: Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. */ public function alignToRectangleMiddle(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true):void { var centerY:Number = bounds.height * 0.5 - displayObject.height * 0.5 + bounds.y; displayObject.y = snapToPixel ? Math.round(centerY) : centerY; } } ================================================ FILE: src/utils/align/alignToRectangleRight.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the right side of the bounding Rectangle. @param displayObject: The DisplayObject to align. @param bounds: The area in which to align the DisplayObject. @param snapToPixel: Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. @param outside: Align the DisplayObject to the outside of the bounds true, or the inside false. */ public function alignToRectangleRight(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true, outside:Boolean = false):void { var x:Number = outside ? bounds.right : bounds.right - displayObject.width; displayObject.x = snapToPixel ? Math.round(x) : x; } } ================================================ FILE: src/utils/align/alignToRectangleTop.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the top of the bounding Rectangle. @param displayObject: The DisplayObject to align. @param bounds: The area in which to align the DisplayObject. @param snapToPixel: Force the position to whole pixels true, or to let the DisplayObject be positioned on sub-pixels false. @param outside: Align the DisplayObject to the outside of the bounds true, or the inside false. */ public function alignToRectangleTop(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true, outside:Boolean = false):void { var y:Number = outside ? bounds.top - displayObject.height : bounds.top; displayObject.y = snapToPixel ? Math.round(y) : y; } } ================================================ FILE: src/utils/align/getPositionToTheRightOf.as ================================================ package utils.align { import flash.display.DisplayObject; import utils.ratio.widthToHeight; /** * Gets the position to the right of an object based on its width and x position * with an optional gap. * * This is useful when you need to cause object B to appear 20px to the right of object A. * * B.x = getPositionToTheRightOf(A, 20); * * @param displayObject An object to get the position under. * @param gap An optional amount to space out the position under. */ public function getPositionToTheRightOf(displayObject:DisplayObject, gap:int = 0):int { return displayObject.x + displayObject.width + gap; } } ================================================ FILE: src/utils/align/getPositionUnder.as ================================================ package utils.align { import flash.display.DisplayObject; /** * Gets the position under an object based on its height and y position with an optional gap. * * This is useful when you need to cause object B to appear 20px below object A. * * B.y = getPositionUnder(A, 20); * * @param displayObject An object to get the position under. * @param gap An optional amount to space out the position under. */ public function getPositionUnder(displayObject:DisplayObject, gap:int = 0):int { return displayObject.y + displayObject.height + gap; } } ================================================ FILE: src/utils/align/gridAlignSpaceNumber.as ================================================ package utils.align { /** * Aligns the items in the array in a grid based on the number of rows and columns. * Uses the same spacing for all. * * @example Alignment.hAlignSpaceNum( [ clip0, clip1, clip2], 10 ); * * @param items An array of items * @param rows The number of rows * @param cols The number of columns * @param spacing The spacing between items in pixels */ public function gridAlignSpaceNumber(items:Array, rows:Number, cols:Number, spacing:Number = 0):void { var col:Number = 0; var row:Number = 1; var yPos:Number = 0; var xPos:Number = 0; var maxHeightCurrentRow:Number = 0; var maxHeightPreviousRow:Number = 0; var n:int = items.length; for (var i:Number = 0; i < n; i++) { if (row <= rows) { items[i].x = xPos; if (col == (cols - 1)) { xPos = 0; row++; } else { xPos += items[(i)].width + spacing; } if (col == cols) { col = 0; /* * Get the max item height from previous row */ maxHeightPreviousRow = maxHeightCurrentRow; maxHeightCurrentRow = items[(i)].height; yPos += maxHeightPreviousRow + spacing; } else { /* * Calculate the max item height from previous row */ maxHeightCurrentRow = Math.max(maxHeightCurrentRow, items[(i)].height); } items[i].y = yPos; col++; } else { break; } } } } ================================================ FILE: src/utils/align/gridAlignSpaceNumberGap.as ================================================ package utils.align { /** * Aligns the items in the array in a grid based on the number of rows and columns. * Uses the same spacing for all * * @example Alignment.hAlignSpaceNum( [ clip0, clip1, clip2], 10 ); * * @param items An array of items * @param rows The number of rows * @param cols The number of columns * @param hGap The column width * @param vGap The row height * @param spacing The spacing between items in pixels */ public function gridAlignSpaceNumberGap(items:Array, rows:Number, cols:Number, hGap:Number, vGap:Number, spacing:Number = 0):void { var col:Number = 0; var row:Number = 1; var yPos:Number = 0; var xPos:Number = 0; var n:int = items.length; for (var i:Number = 0; i < n; i++) { if (row <= rows) { items[i].x = xPos; if (col == (cols - 1)) { xPos = 0; row++; } else { xPos += hGap + spacing; } if (col == cols) { col = 0; yPos += vGap + spacing; } items[i].y = yPos; col++; } else break; } } } ================================================ FILE: src/utils/align/horizontalAlign.as ================================================ package utils.align { /** * Convenient horizontal align method with optional alignment argument * @example Alignment.hAlign( [ clip0, clip1, clip2], 10 ); * @param items An array of items * @param args spacing The spacing between items in pixels as either a number or array or blank */ public function horizontalAlign(items:Array, ... args):void { if(args.length > 0) { if(args[0] is Array) horizontalAlignSpaceArray(items, args[0]); if(args[0] is Number) horizontalAlignSpaceNumber(items, args[0]); } else horizontalAlignNoSpace(items); } } ================================================ FILE: src/utils/align/horizontalAlignNoSpace.as ================================================ package utils.align { /** * Aligns each item horizontally to the one above it. * Uses no spacing. * * @example Alignment.hAlignNoSpace( [ clip0, clip1, clip2] ); * * @param items An array of items */ public function horizontalAlignNoSpace(items:Array):void { var n:int = items.length; for (var i:int = 1; i < n; i++) { items[i].x = items[(i - 1)].y + items[(i - 1)].width; } } } ================================================ FILE: src/utils/align/horizontalAlignSpaceArray.as ================================================ package utils.align { /** * Aligns each item in the array to the one preceding it. * Uses the correlating position in the spacing arr for the spacing. * @example Alignment.hAlignSpaceArr( [ clip0, clip1, clip2], [ 0, 5, 30 ] ); * @param items An array of items * @param spacing The array for spacing between items in pixels */ public function horizontalAlignSpaceArray(items:Array, spacing:Array):void { var n:int = items.length; for(var i:int = 1; i < n; i++) { items[i].x = items[(i - 1)].x + items[(i - 1)].width + spacing[i]; } } } ================================================ FILE: src/utils/align/horizontalAlignSpaceNumber.as ================================================ package utils.align { /** * Aligns the items in the array horizontally to each the one preceding it in the array. * Uses the same spacing for all. * * @example Alignment.hAlignSpaceNum( [ clip0, clip1, clip2], 10 ); * * @param items An array of items * @param spacing The spacing between items in pixels */ public function horizontalAlignSpaceNumber(items:Array, spacing:Number):void { var n:int = items.length; for (var i:int = 1; i < n; i++) { items[i].x = items[(i - 1)].x + items[(i - 1)].width + spacing; } } } ================================================ FILE: src/utils/align/interpolate.as ================================================ package utils.align { import flash.display.DisplayObject; /** * interpolate the DisplayObject at weight t == (0 <= t <= 1). a position 1 would position the object to the * right-most bounds, and tx=0 would position to the left * * @param object DisplayObject to position * @param tx weight of horizontal position from 0 to 1 * @param ty weight of verticle position from 0 to 1 * @param width width of horizontal constraint * @param height height of the verticle constraint * @offsetX the left offset of the horizontal constraint (default = 0) * @offsetY the topmost offset of verticle constraint (default = 0) */ public function interpolate(object:DisplayObject, tx:Number, ty:Number, width:Number, height:Number, offsetX:int = 0, offsetY:int = 0):void { object.x = (width * tx) + offsetX - (tx * object.width); object.y = (height * ty) + offsetY - (ty * object.height); } } ================================================ FILE: src/utils/align/interpolateMultiX.as ================================================ package utils.align { /** * interpolate multiple DisplayObjects at multiple weights at t == (0 less or equal t less or equal 1). at tx=1, the position of the object would be aligned to the right-most bounds, and tx=0 would position to the left * * @param DisplayObject DisplayObject to position * @param positionArray weight array of horizontal position from 0 to 1 * @param width width of horizontal constraint * @offsetX the left offset of the horizontal constraint (default = 0) */ public function interpolateMultiX(objectArray:Array, positionArray:Array, width:Number, offsetX:int = 0):void { var j:int = objectArray.length; for (var i:int = 0; i < j; i++) { interpolateX(objectArray[i], positionArray[i], width, offsetX); } } } ================================================ FILE: src/utils/align/interpolateMultiY.as ================================================ package utils.align { /** * interpolate multiple DisplayObjects at multiple weights at t == (0 less or equal t less or equal 1). at tx=1, the position of the object would be aligned to the right-most bounds, and ty=0 would position to the left * * @param DisplayObject DisplayObject to position * @param positionArray weight array of vertical position from 0 to 1 * @param height width of horizontal constraint * @param offsetY the left offset of the horizontal constraint (default = 0) */ public function interpolateMultiY(objectArray:Array, positionArray:Array, height:Number, offsetY:int = 0):void { var j:int = objectArray.length; for (var i:int = 0; i < j; i++) { interpolateX(objectArray[i], positionArray[i], height, offsetY); } } } ================================================ FILE: src/utils/align/interpolateX.as ================================================ package utils.align { import flash.display.DisplayObject; /** * interpolate the DisplayObject at weight t to the rectangle, ie, a weight of 1 would position the object to the right-most bounds * * @param DisplayObject DisplayObject to position * @param tx * @param width width of horizontal constraint * @param offsetX the left offset of the horizontal constraint (default = 0) */ public function interpolateX(object:DisplayObject, tx:Number, width:Number, offsetX:int = 0):void { object.x = (width * tx) + offsetX - (tx * object.width); } } ================================================ FILE: src/utils/align/interpolateY.as ================================================ package utils.align { import flash.display.DisplayObject; /** * interpolate the DisplayObject at weight t == (0 less or equal t less or equal 1). a position 1 would position the object to the right-most bounds, and tx=0 would position to the left * * @param DisplayObject DisplayObject to position * @param ty weight of verticle position from 0 to 1 * @param height height of the verticle constraint * @offsetY the left offset of the horizontal constraint (default = 0) */ public function interpolateY(object:DisplayObject, ty:Number, height:Number, offsetY:int = 0):void { object.y = (height * ty) + offsetY - (ty * object.height); } } ================================================ FILE: src/utils/align/verticalAlign.as ================================================ package utils.align { /** * Convenient vertical align method with optional alignment argument * @example Alignment.vAlign( [ clip0, clip1, clip2], 10 ); * @param items An array of items * @param spacingValues spacing The spacing between items in pixels as either a number or array or blank */ public function verticalAlign(items:Array, ... spacingValues):void { if(spacingValues.length > 0) { if(spacingValues[0] is Array) verticalAlignSpaceArray(items, spacingValues[0]); if(spacingValues[0] is Number) verticalAlignSpaceNumber(items, spacingValues[0]); } else verticalAlignNoSpace(items); } } ================================================ FILE: src/utils/align/verticalAlignNoSpace.as ================================================ package utils.align { /** * Aligns each item vertically to the one above it. * Uses no spacing. * * @example Alignment.valignNoSpace( [ clip0, clip1, clip2] ); * * @param items An array of items */ public function verticalAlignNoSpace(items:Array):void { var n:int = items.length; for (var i:int = 1; i < n; i++) { items[i].y = int(items[(i - 1)].y + items[(i - 1)].height); } } } ================================================ FILE: src/utils/align/verticalAlignSpaceArray.as ================================================ package utils.align { /** * Aligns each item in the array to the one preceding it. * Uses the correlating position in the spacing arr for the spacing. * @example Alignment.valignSpaceArr( [ clip0, clip1, clip2], [ 0, 5, 30 ] ); * @param items An array of items * @param spacing The array for spacing between items in pixels */ public function verticalAlignSpaceArray(items:Array, spacing:Array):void { var n:int = items.length; for(var i:int = 1; i < n; i++) { items[i].y = int(items[(i - 1)].y + items[(i - 1)].height + spacing[i]); } } } ================================================ FILE: src/utils/align/verticalAlignSpaceNumber.as ================================================ package utils.align { import flash.text.TextField; /** * Aligns the items in the array vertically to each the one preceding it in the array. * Uses the same spacing for all. * * @example Alignment.valignSpaceNum( [ clip0, clip1, clip2], 10 ); * * @param items An array of items * @param spacing The spacing between items in pixels */ public function verticalAlignSpaceNumber(items:Array, spacing:Number):void { var n:int = items.length; for (var i:int = 1; i < n; i++) { if (items[i - 1] is TextField) { items[i].y = int(items[(i - 1)].y + items[(i - 1)].textHeight + spacing); } else { items[i].y = int(items[(i - 1)].y + items[(i - 1)].height + spacing); } } } } ================================================ FILE: src/utils/align/xAlignCenter.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Point; import flash.geom.Rectangle; /** * Horizontal center align object to target. * Alignment algorithm taken from: * http://chargedweb.com/labs/2010/07/27/alignutil_align_objects_easily/ * Copyright 2010 Julius Loa | jloa@chargedweb.com * license: MIT {http://www.opensource.org/licenses/mit-license.php} * * This algorith takes the objects rotation and scale into account. */ public function xAlignCenter(item:DisplayObject, target:DisplayObject):void { //item.x = int(target.width / 2 - item.width / 2); var b:Rectangle = item.transform.pixelBounds; var bp:Point = target.globalToLocal(new Point(b.x, b.y)); b.x = bp.x; b.y = bp.y; item.x = int((target.width - b.width)/2 + item.x - b.x); } } ================================================ FILE: src/utils/align/xAlignLeft.as ================================================ package utils.align { import flash.display.DisplayObject; /** * Horizontal left align object to target. */ public function xAlignLeft(item:DisplayObject, target:DisplayObject):void { item.x = int(target.x); } } ================================================ FILE: src/utils/align/xAlignRight.as ================================================ package utils.align { import flash.display.DisplayObject; /** * Horizontal right align object to target. */ public function xAlignRight(item:DisplayObject, target:DisplayObject):void { item.x = int(target.width - item.width); } } ================================================ FILE: src/utils/align/yAlignCenter.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.geom.Point; import flash.geom.Rectangle; /** * Vertical center align object to target. * * Alignment algorithm taken from: * http://chargedweb.com/labs/2010/07/27/alignutil_align_objects_easily/ * Copyright 2010 Julius Loa | jloa@chargedweb.com * license: MIT {http://www.opensource.org/licenses/mit-license.php} * * This algorith takes the objects rotation and scale into account. */ public function yAlignCenter(item:DisplayObject, target:DisplayObject):void { var b:Rectangle = item.transform.pixelBounds; var bp:Point = target.globalToLocal(new Point(b.x, b.y)); b.x = bp.x; b.y = bp.y; item.y = int((target.height - b.height)/2 + item.y - b.y); } } ================================================ FILE: src/utils/align/yAlignLeft.as ================================================ package utils.align { import flash.display.DisplayObject; /** * Vertical left align object to target. */ public function yAlignLeft(item:DisplayObject, target:DisplayObject):void { item.y = int(target.y); } } ================================================ FILE: src/utils/align/yAlignRight.as ================================================ package utils.align { import flash.display.DisplayObject; /** * Vertical right align object to target. */ public function yAlignRight(item:DisplayObject, target:DisplayObject):void { item.y = int(target.height - item.height); } } ================================================ FILE: src/utils/array/addItemsAt.as ================================================ package utils.array { /** Modifies original Array by adding all the elements from another Array at a specified position. @param tarArray: Array to add elements to. @param items: Array of elements to add. @param index: Position where the elements should be added. @return Returns true if the Array was changed as a result of the call; otherwise false. @example var alphabet:Array = new Array("a", "d", "e"); var parts:Array = new Array("b", "c"); ArrayUtil.addItemsAt(alphabet, parts, 1); trace(alphabet); */ public function addItemsAt(tarArray:Array, items:Array, index:int = 0x7FFFFFFF):Boolean { if (items.length == 0) return false; var args:Array = items.concat(); args.splice(0, 0, index, 0); tarArray.splice.apply(null, args); return true; } } ================================================ FILE: src/utils/array/arrayContainsValue.as ================================================ package utils.array { /** * Determines whether the specified array contains the specified value. * * @param arr The array that will be checked for the specified value. * * @param value The object which will be searched for within the array * * @return True if the array contains the value, False if it does not. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function arrayContainsValue(arr:Array, value:Object):Boolean { return (arr.indexOf(value) != -1); } } ================================================ FILE: src/utils/array/arraysAreEqual.as ================================================ package utils.array { /** * Compares two arrays and returns a boolean indicating whether the arrays * contain the same values at the same indexes. * * @param arr1 The first array that will be compared to the second. * * @param arr2 The second array that will be compared to the first. * * @return True if the arrays contains the same values at the same indexes. False if they do not. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function arraysAreEqual(arr1:Array, arr2:Array):Boolean { if(arr1.length != arr2.length) { return false; } var len:Number = arr1.length; for(var i:Number = 0; i < len; i++) { if(arr1[i] != arr2[i]) { return false; } } return true; } } ================================================ FILE: src/utils/array/average.as ================================================ package utils.array { /** Averages the values in inArray. @param inArray: Array composed only of numbers. @return The average of all numbers in the inArray. @example var numberArray:Array = new Array(2, 3, 8, 3); trace("Average is: " + ArrayUtil.average(numberArray)); */ public function average(inArray:Array):Number { if (inArray.length == 0) return 0; return sum(inArray) / inArray.length; } } ================================================ FILE: src/utils/array/contains.as ================================================ package utils.array { /** Finds out how many instances of item Array contains. @param inArray: Array to search for item in. @param item: Object to find. @return The amount of item's found; if none were found returns 0. @example var numberArray:Array = new Array(1, 2, 3, 7, 7, 7, 4, 5); trace("numberArray contains " + ArrayUtil.contains(numberArray, 7) + " 7's."); */ public function contains(inArray:Array, item:*):uint { var i:int = inArray.indexOf(item, 0); var t:uint = 0; while (i != -1) { i = inArray.indexOf(item, i + 1); t++; } return t; } } ================================================ FILE: src/utils/array/containsAll.as ================================================ package utils.array { /** Determines if Array contains all items. @param inArray: Array to search for items in. @param items: Array of elements to search for. @return Returns true if inArray contains all elements of items; otherwise false. @example var numberArray:Array = new Array(1, 2, 3, 4, 5); trace(ArrayUtil.containsAll(numberArray, new Array(1, 3, 5))); */ public function containsAll(inArray:Array, items:Array):Boolean { var l:uint = items.length; while (l--) if (inArray.indexOf(items[l]) == -1) return false; return true; } } ================================================ FILE: src/utils/array/containsAny.as ================================================ package utils.array { /** Determines if Array inArray contains any element of Array items. @param inArray: Array to search for items in. @param items: Array of elements to search for. @return Returns true if inArray contains any element of items; otherwise false. @example var numberArray:Array = new Array(1, 2, 3, 4, 5); trace(ArrayUtil.containsAny(numberArray, new Array(9, 3, 6))); */ public function containsAny(inArray:Array, items:Array):Boolean { var l:uint = items.length; while (l--) if (inArray.indexOf(items[l]) > -1) return true; return false; } } ================================================ FILE: src/utils/array/copyArray.as ================================================ package utils.array { /** * Creates a copy of the specified array. * * Note that the array returned is a new array but the items within the * array are not copies of the items in the original array (but rather * references to the same items) * * @param arr The array that will be copies * * @return A new array which contains the same items as the array passed * in. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function copyArray(arr:Array):Array { return arr.slice(); } } ================================================ FILE: src/utils/array/createUniqueCopy.as ================================================ package utils.array { /** * Create a new array that only contains unique instances of objects * in the specified array. * * Basically, this can be used to remove duplication object instances * from an array * * @param arr The array which contains the values that will be used to * create the new array that contains no duplicate values. * * @return A new array which only contains unique items from the specified * array. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function createUniqueCopy(a:Array):Array { var newArray:Array = new Array(); var len:Number = a.length; var item:Object; for (var i:uint = 0; i < len; ++i) { item = a[i]; if (arrayContainsValue(newArray, item)) { continue; } newArray.push(item); } return newArray; } } ================================================ FILE: src/utils/array/equals.as ================================================ package utils.array { /** Determines if two Arrays contain the same objects at the same index. @param first: First Array to compare to the second. @param second: Second Array to compare to the first. @return Returns true if Arrays are the same; otherwise false. */ public function equals(first:Array, second:Array):Boolean { var i:uint = first.length; if (i != second.length) return false; while (i--) if (first[i] != second[i]) return false; return true; } } ================================================ FILE: src/utils/array/getHighestValue.as ================================================ package utils.array { /** Finds the highest value in inArray. @param inArray: Array composed only of numbers. @return The highest value in inArray. @example var numberArray:Array = new Array(2, 1, 5, 4, 3); trace("The highest value is: " + ArrayUtil.getHighestValue(numberArray)); */ public function getHighestValue(inArray:Array):Number { return inArray[inArray.sort(16 | 8)[inArray.length - 1]]; } } ================================================ FILE: src/utils/array/getIndexOfDifference.as ================================================ package utils.array { /** Compares two Arrays and finds the first index where they differ. @param first: First Array to compare to the second. @param second: Second Array to compare to the first. @param fromIndex: The location in the Arrays from which to start searching for a difference. @return The first position/index where the Arrays differ; if Arrays are identical returns -1. @example var color:Array = new Array("Red", "Blue", "Green", "Indigo", "Violet"); var colorsAlt:Array = new Array("Red", "Blue", "Green", "Violet"); trace(ArrayUtil.getIndexOfDifference(color, colorsAlt)); // Traces 3 */ public function getIndexOfDifference(first:Array, second:Array, fromIndex:uint = 0):int { var i:int = fromIndex - 1; while (++i < first.length) if (first[i] != second[i]) return i; return -1; } } ================================================ FILE: src/utils/array/getItemByKey.as ================================================ package utils.array { /** Returns the first element that matches match for the property key. @param inArray: Array to search for an element with a key that matches match. @param key: Name of the property to match. @param match: Value to match against. @return Returns matched Object; otherwise null. */ public function getItemByKey(inArray:Array, key:String, match:*):* { for each (var item:* in inArray) if (item[key] == match) return item; return null; } } ================================================ FILE: src/utils/array/getItemByType.as ================================================ package utils.array { /** Returns the first element that is compatible with a specific data type, clazz, or interface. @param inArray: Array to search for an element of a specific type. @param type: The type to compare the elements to. @return Returns all the matched elements. */ public function getItemByType(inArray:Array, type:Class):* { for each (var item:* in inArray) if (item is type) return item; return null; } } ================================================ FILE: src/utils/array/getItemsByKey.as ================================================ package utils.array { /** Returns every element that matches match for the property key. @param inArray: Array to search for object with key that matches match. @param key: Name of the property to match. @param match: Value to match against. @return Returns all the matched elements. */ public function getItemsByKey(inArray:Array, key:String, match:*):Array { var t:Array = new Array(); for each (var item:* in inArray) if (item[key] == match) t.push(item); return t; } } ================================================ FILE: src/utils/array/getItemsByType.as ================================================ package utils.array { /** Returns every element that is compatible with a specific data type, clazz, or interface. @param inArray: Array to search for elements of a specific type. @param type: The type to compare the elements to. @return Returns all the matched elements. */ public function getItemsByType(inArray:Array, type:Class):Array { var t:Array = new Array(); for each (var item:* in inArray) if (item is type) t.push(item); return t; } } ================================================ FILE: src/utils/array/getLowestValue.as ================================================ package utils.array { /** Finds the lowest value in inArray. @param inArray: Array composed only of numbers. @return The lowest value in inArray. @example var numberArray:Array = new Array(2, 1, 5, 4, 3); trace("The lowest value is: " + ArrayUtil.getLowestValue(numberArray)); */ public function getLowestValue(inArray:Array):Number { return inArray[inArray.sort(16 | 8)[0]]; } } ================================================ FILE: src/utils/array/getRandomElement.as ================================================ package utils.array { import utils.number.randomIntegerWithinRange; /** * Returns a random element from an array. */ public function getRandomElement(array:Array):* { return array[randomIntegerWithinRange(0, array.length-1)]; } } ================================================ FILE: src/utils/array/randomize.as ================================================ package utils.array { import utils.number.randomIntegerWithinRange; /** Creates new Array composed of passed Array's items in a random order. @param inArray: Array to create copy of, and randomize. @return A new Array composed of passed Array's items in a random order. @example var numberArray:Array = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); trace(ArrayUtil.randomize(numberArray)); */ public function randomize(inArray:Array):Array { var t:Array = new Array(); var r:Array = inArray.sort( function(a:*, b:*):int { return randomIntegerWithinRange(0, 1) ? 1 : -1; } , Array.RETURNINDEXEDARRAY); var i:int = -1; while (++i < inArray.length) t.push(inArray[r[i]]); return t; } } ================================================ FILE: src/utils/array/removeDuplicates.as ================================================ package utils.array { /** Creates new Array composed of only the non-identical elements of passed Array. @param inArray: Array to remove equivalent items. @return A new Array composed of only unique elements. @example var numberArray:Array = new Array(1, 2, 3, 4, 4, 4, 4, 5); trace(ArrayUtil.removeDuplicates(numberArray)); */ public function removeDuplicates(inArray:Array):Array { return inArray.filter( function(e:*, i:int, inArray:Array):Boolean { return (i == 0) ? true : inArray.lastIndexOf(e, i - 1) == -1; }); } } ================================================ FILE: src/utils/array/removeItem.as ================================================ package utils.array { /** Modifies original Array by removing all items that are identical to the specified item. @param tarArray: Array to remove passed item. @param item: Element to remove. @return The amount of removed elements that matched item, if none found returns 0. @example var numberArray:Array = new Array(1, 2, 3, 7, 7, 7, 4, 5); trace("Removed " + ArrayUtil.removeItem(numberArray, 7) + " items."); trace(numberArray); */ public function removeItem(tarArray:Array, item:*):uint { var i:int = tarArray.indexOf(item); var f:uint = 0; while (i != -1) { tarArray.splice(i, 1); i = tarArray.indexOf(item, i); f++; } return f; } } ================================================ FILE: src/utils/array/removeItems.as ================================================ package utils.array { /** Removes only the specified items in an Array. @param tarArray: Array to remove specified items from. @param items: Array of elements to remove. @return Returns true if the Array was changed as a result of the call; otherwise false. @example var numberArray:Array = new Array(1, 2, 3, 7, 7, 7, 4, 5); ArrayUtil.removeItems(numberArray, new Array(1, 3, 7, 5)); trace(numberArray); */ public function removeItems(tarArray:Array, items:Array):Boolean { var removed:Boolean = false; var l:uint = tarArray.length; while (l--) { if (items.indexOf(tarArray[l]) > -1) { tarArray.splice(l, 1); removed = true; } } return removed; } } ================================================ FILE: src/utils/array/removeValueFromArray.as ================================================ package utils.array { /** * Remove all instances of the specified value from the array, * * @param arr The array from which the value will be removed * * @param value The object that will be removed from the array. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function removeValueFromArray(arr:Array, value:Object):void { var len:uint = arr.length; for(var i:Number = len; i > -1; i--) { if(arr[i] == value) { arr.splice(i, 1); } } } } ================================================ FILE: src/utils/array/retainItems.as ================================================ package utils.array { /** Retains only the specified items in an Array. @param tarArray: Array to remove non specified items from. @param items: Array of elements to keep. @return Returns true if the Array was changed as a result of the call; otherwise false. @example var numberArray:Array = new Array(1, 2, 3, 7, 7, 7, 4, 5); ArrayUtil.retainItems(numberArray, new Array(2, 4)); trace(numberArray); */ public function retainItems(tarArray:Array, items:Array):Boolean { var removed:Boolean = false; var l:uint = tarArray.length; while (l--) { if (items.indexOf(tarArray[l]) == -1) { tarArray.splice(l, 1); removed = true; } } return removed; } } ================================================ FILE: src/utils/array/sum.as ================================================ package utils.array { /** Adds all items in inArray and returns the value. @param inArray: Array composed only of numbers. @return The total of all numbers in inArray added. @example var numberArray:Array = new Array(2, 3); trace("Total is: " + ArrayUtil.sum(numberArray)); */ public function sum(inArray:Array):Number { var t:Number = 0; var l:uint = inArray.length; while (l--) t += inArray[l]; return t; } } ================================================ FILE: src/utils/assert/assertArrayContains.as ================================================ package utils.assert { /** * Assert that the array contains the passed in item. */ public function assertArrayContains(array:Array, item:*, message:String = ""):void { if (array.indexOf(item) == -1) { if (message == null || message.length == 0) { message = "[Assertion failed] - this Array argument does not contain the item '" + item + "'"; } throw new Error(message); } } } ================================================ FILE: src/utils/assert/assertArrayItemsTypeOf.as ================================================ package utils.assert { /** * Assert that all items in the array are of the given type. * * @param array the array to check * @param type the type of the array items * @param message the error message to use if the assertion fails */ public function assertArrayItemsTypeOf(array:Array, type:Class, message:String = ""):void { for each (var item:* in array) { if (!(item is type)) { if (message == null || message.length == 0) { message = "[Assertion failed] - this Array must have items of type '" + type + "'"; } throw new Error(message); } } } } ================================================ FILE: src/utils/assert/assertDictionaryKeysTypeOf.as ================================================ package utils.assert { import flash.utils.Dictionary; /** * Assert that the given Dictionary contains only keys of the given type. */ public function assertDictionaryKeysTypeOf(dictionary:Dictionary, type:Class, message:String = ""):void { for (var key:Object in dictionary) { if (!(key is type)) { if (message == null || message.length == 0) { message = "[Assertion failed] - this Dictionary argument must have keys of type '" + type + "'"; } throw new Error(message); } } } } ================================================ FILE: src/utils/assert/assertHasText.as ================================================ package utils.assert { import utils.validation.isBlank; /** * Assert that the given String has valid text content; that is, it must not * be null and must contain at least one non-whitespace character. * * @param text the String to check * @param message the exception message to use if the assertion fails * @see StringUtils#hasText */ public function assertHasText(string:String, message:String = ""):void { if (isBlank(string)) { if (message == null || message.length == 0) { message = "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"; } throw new Error(message); } } } ================================================ FILE: src/utils/assert/assertInstanceOf.as ================================================ package utils.assert { /** * Assert that an object is an instance of a certain type.. *
Assert.instanceOf(value, type, "The value must be an instance of 'type'");
* @param object the object to check * @param message the error message to use if the assertion fails * @throws org.as3commons.lang.IllegalArgumentError if the object is not an instance of the given type */ public function assertInstanceOf(object:*, type:Class, message:String = ""):void { if (!(object is type)) { if (message == null || message.length == 0) { message = "[Assertion failed] - this argument is not of type '" + type + "'"; } throw new Error(message); } } } ================================================ FILE: src/utils/assert/assertIsTrue.as ================================================ package utils.assert { public function assertIsTrue(expression:Boolean, message:String = ""):void { if (!expression) { if (message == null || message.length == 0) { message = "[Assertion failed] - this expression must be true"; } throw new Error(message); } } } ================================================ FILE: src/utils/assert/assertNotNull.as ================================================ package utils.assert { /** * Assert that an object is null. *
Assert.isNull(value, "The value must be null");
* @param object the object to check * @param message the error message to use if the assertion fails * @throws org.as3commons.lang.IllegalArgumentError if the object is not null */ public function assertNotNull(object:Object, message:String = ""):void { if (object == null) { if (message == null || message.length == 0) { message = "[Assertion failed] - this argument is required; it must not null"; } throw new Error(message); } } } ================================================ FILE: src/utils/assert/assertState.as ================================================ package utils.assert { /** * Assert a boolean expression to be true. If false, an IllegalStateError is thrown. * @param expression a boolean expression * @param the error message if the assertion fails */ public function assertState(expression:Boolean, message:String = ""):void { if (!expression) { if (message == null || message.length == 0) { message = "[Assertion failed] - this state invariant must be true"; } throw new Error(message); } } } ================================================ FILE: src/utils/boolean/randomBoolean.as ================================================ package utils.boolean { /** * Randomly returns either true or false. * * @author Mims Wright */ public function randomBoolean():Boolean { return randomChance(0.5); } } ================================================ FILE: src/utils/boolean/randomChance.as ================================================ package utils.boolean { /** * Randomly returns true "percent"% of the time (where percent is a decimal between 0.0 and 1.0). * * @author Mims Wright */ public function randomChance(percent:Number):Boolean { return Math.random() < percent; } } ================================================ FILE: src/utils/capabilities/getPlayerInfo.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Returns a player and environment info string. */ public function getPlayerInfo():String { var debugger:String = (Capabilities.isDebugger) ? ' / Debugger' : ''; var info:String = String("Flash Platform: " + Capabilities.version + " / " + Capabilities.playerType + debugger + " / " + Capabilities.os + " / " + Capabilities.screenResolutionX + "x" + Capabilities.screenResolutionY); return info; } } ================================================ FILE: src/utils/capabilities/isAirApplication.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Determines if the runtime environment is an Air application. * @return true if the runtime environment is an Air application * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isAirApplication():Boolean { return Capabilities.playerType == "Desktop"; } } ================================================ FILE: src/utils/capabilities/isIDE.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Determines if the SWF is running in the IDE. * @return true if SWF is running in the Flash Player version used by the external player or test movie mode * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isIDE():Boolean { return Capabilities.playerType == "External"; } } ================================================ FILE: src/utils/capabilities/isMac.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Indicates whether the running OS is a Mac * @return */ public function isMac():Boolean { return Capabilities.os.toLowerCase().indexOf("mac os") != -1; } } ================================================ FILE: src/utils/capabilities/isPC.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Indicates whether the running OS is a PC * @return */ public function isPC():Boolean { return Capabilities.os.toLowerCase().indexOf("mac os") == -1; } } ================================================ FILE: src/utils/capabilities/isPlugin.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Determines if the SWF is running in a browser plug-in. * @return true if SWF is running in the Flash Player browser plug-in * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isPlugin():Boolean { return Capabilities.playerType == "PlugIn" || Capabilities.playerType == "ActiveX"; } } ================================================ FILE: src/utils/capabilities/isStandAlone.as ================================================ package utils.capabilities { import flash.system.Capabilities; /** * Determines if the SWF is running in the StandAlone player. * @return true if SWF is running in the Flash StandAlone Player * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isStandAlone():Boolean { return Capabilities.playerType == "StandAlone"; } } ================================================ FILE: src/utils/capabilities/isWeb.as ================================================ package utils.capabilities { import flash.display.DisplayObject; /** * Determines if the SWF is being served on the internet. * Example code: *
	 *          trace(isWeb(_root));
	 *      
* @param location DisplayObject to get location of * @return true if SWF is being served on the internet * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isWeb(location:DisplayObject):Boolean { return location.loaderInfo.url.substr(0, 4) == "http"; } } ================================================ FILE: src/utils/color/HSLtoHSV.as ================================================ package utils.color { /** * Convert HSL to HSV using RGB conversions: color preservation may be dubious. */ public function HSLtoHSV(hue:Number, luminance:Number, saturation:Number):Object { var rgbVal:Object = HSLtoRGB(hue, luminance, saturation); return RGBtoHSV(rgbVal.r, rgbVal.g, rgbVal.b); } } ================================================ FILE: src/utils/color/HSLtoRGB.as ================================================ package utils.color { /** * Convert HSL values to RGB values. * @param hue 0 to 360. * @param luminance 0 to 1. * @param saturation 0 to 1. * @return Object with R,G,B values on 0 to 1 scale. */ public function HSLtoRGB(hue:Number, luminance:Number, saturation:Number):Object { var delta:Number; if (luminance < 0.5) { delta = saturation * luminance; } else { delta = saturation * (1 - luminance); } return HueToRGB(luminance - delta, luminance + delta, hue); } } ================================================ FILE: src/utils/color/HSVtoHSL.as ================================================ package utils.color { /** * Convert HSV to HLS using RGB conversions: color preservation may be dubious. */ public function HSVtoHSL(hue:Number, saturation:Number, value:Number):Object { var rgbVal:Object = HSVtoRGB(hue, saturation, value); return RGBtoHSL(rgbVal.r, rgbVal.g, rgbVal.b); } } ================================================ FILE: src/utils/color/HSVtoRGB.as ================================================ package utils.color { /** * Convert HSV values to RGB values. * @param hue on 0 to 360 scale. * @param saturation on 0 to 1 scale. * @param value on 0 to 1 scale. * @return Object with R,G,B values on 0 to 1 scale. */ public function HSVtoRGB(hue:Number, saturation:Number, value:Number):Object { var min:Number = (1 - saturation) * value; return HueToRGB(min, value, hue); } } ================================================ FILE: src/utils/color/HueToRGB.as ================================================ package utils.color { /** * Convert hue to RGB values using a linear transformation. * @param min of R,G,B. * @param max of R,G,B. * @param hue value angle hue. * @return Object with R,G,B properties on 0-1 scale. */ public function HueToRGB(min:Number, max:Number, hue:Number):Object { const HUE_MAX:uint = 360; var mu:Number, md:Number, F:Number, n:Number; while (hue < 0) { hue += HUE_MAX; } n = Math.floor(hue / 60); F = (hue - n * 60) / 60; n %= 6; mu = min + ((max - min) * F); md = max - ((max - min) * F); switch (n) { case 0: return { r: max, g: mu, b: min }; case 1: return { r: md, g: max, b: min }; case 2: return { r: min, g: max, b: mu }; case 3: return { r: min, g: md, b: max }; case 4: return { r: mu, g: min, b: max }; case 5: return { r: max, g: min, b: md }; } return null; } } ================================================ FILE: src/utils/color/RGBToHue.as ================================================ package utils.color { import utils.range.center; /** * Convert RGB values to a hue using a linear transformation. * @param red value on 0 to 1 scale. * @param green value on 0 to 1 scale. * @param blue value on 0 to 1 scale. * @return hue degree between 0 and 360. */ public function RGBToHue(red:Number, green:Number, blue:Number):uint { var f:Number, min:Number, mid:Number, max:Number, n:Number; max = Math.max(red, Math.max(green, blue)); min = Math.min(red, Math.min(green, blue)); // achromatic case if (max - min == 0) { return 0; } mid = center(red, green, blue); // using this loop to avoid super-ugly nested ifs while (true) { if (red == max) { if (blue == min) n = 0; else n = 5; break; } if (green == max) { if (blue == min) n = 1; else n = 2; break; } if (red == min) n = 3; else n = 4; break; } if ((n % 2) == 0) { f = mid - min; } else { f = max - mid; } f = f / (max - min); return 60 * (n + f); } } ================================================ FILE: src/utils/color/RGBtoHSL.as ================================================ package utils.color { /** * Convert an RGB Hexadecimal value to HSL values * @param red 0 - 1 scale. * @param green 0 - 1 scale. * @param blue 0 - 1 scale. * @return Object with h (hue), l (lightness), s (saturation) values:
    *
  • h on 0 - 360 scale.
  • *
  • l on 0 - 255 scale.
  • *
  • s on 0 - 1 scale.
*/ public function RGBtoHSL(red:Number, green:Number, blue:Number):Object { var min:Number, max:Number, delta:Number, l:Number, s:Number, h:Number = 0; max = Math.max(red, Math.max(green, blue)); min = Math.min(red, Math.min(green, blue)); //l = (min + max) / 2; l = (min + max) * 0.5; // L if(l == 0) { return { h: h, l: 0, s: 1 }; } //delta = (max - min) / 2; delta = (max - min) * 0.5; if(l < 0.5) { // S s = delta / l; } else { s = delta / (1 - l); } // H h = RGBToHue(red, green, blue); return { h: h, l: l, s: s }; } } ================================================ FILE: src/utils/color/RGBtoHSV.as ================================================ package utils.color { /** * Convert RGB values to HSV values. * @param red 0 to 1 scale. * @param green 0 to 1 scale. * @param blue 0 to 1 scale. * @return Object with H,S,V values:
    *
  • h - on 0 to 360 scale
  • *
  • s - on 0 to 1 scale
  • *
  • v - on 0 to 1 scale
*/ public function RGBtoHSV(red:Number, green:Number, blue:Number):Object { var min:Number, max:Number, s:Number, v:Number, h:Number = 0; max = Math.max(red, Math.max(green, blue)); min = Math.min(red, Math.min(green, blue)); if (max == 0) { return { h: 0, s: 0, v: 0 }; } v = max; s = (max - min) / max; h = RGBToHue(red, green, blue); return { h: h, s: s, v: v }; } } ================================================ FILE: src/utils/color/averageBlue.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Blue (RGB) value from a display object or one of its region. * * @param src The DisplayObject * @param accuracy Percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average blue value on a scale of 0-255. */ public function averageBlue(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'b'); } } ================================================ FILE: src/utils/color/averageColorProperty.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * @private * * Sample & average a colorspace value (RGB or HSL) value from a display object or one of its region. * @param src of the display object. * @param region to sample from [Default: null = entire src object]. * @param accuracy percentage of pixels to sample when averaging. * @colorspace to be sampled. Valid arguments are 'r', 'g', 'b', 'h', 's', 'l', 'v'. * @return the sampled average value requested from the colorspace. */ public function averageColorProperty(src:DisplayObject, region:Rectangle = null, accuracy:Number = 0.01, colorspace:String = 'l'):Number { if (!region) { region = new Rectangle(0, 0, src.width, src.height); } var offset:int = 1 / accuracy; var total:int; var count:int; // loop thru x/y pixels by offset for (var i:int = region.x; i < (region.x + region.width); i += offset) { for (var j:int = region.y; j < (region.y + region.height); j += offset) { var hex:uint = getColorFromDisplayObject(src, i, j); var obj:Object = getRGB(hex); if (colorspace == "h" || colorspace == "s" || colorspace == "l") { var hsl:Object = RGBtoHSL(obj.r, obj.g, obj.b); obj = hsl; } if (colorspace == "v") { var hsv:Object = RGBtoHSV(obj.r, obj.g, obj.b); obj = hsv; } total += obj[colorspace]; count++; //trace( "colorspace: '" + colorspace + "' = " + obj[colorspace] ); } } // return the average value return total / count; } } ================================================ FILE: src/utils/color/averageGreen.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Green (RGB) value from a display object or one of its region. * * @param src The DisplayObject * @param accuracy Percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average green value on a scale of 0-255. */ public function averageGreen(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'g'); } } ================================================ FILE: src/utils/color/averageHue.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Hue (HSL) value from a display object or one of its region. * * @param src The DisplayObject * @param accuracy percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average hue value on a scale of 0-360. */ public function averageHue(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'h'); } } ================================================ FILE: src/utils/color/averageLightness.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Lightness (HSL) value from a display object or one of its region. * * @param src The DisplayObject * @param accuracy percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average lightness value on a scale of 0-255. */ public function averageLightness(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'l'); } } ================================================ FILE: src/utils/color/averageRed.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Red (RGB) value from a display object or one of its region. * * @param src The DisplayObject. * @param accuracy Percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average red value on a scale of 0-255. */ public function averageRed(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'r'); } } ================================================ FILE: src/utils/color/averageSaturation.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Saturation (HSL) value from a display object or one of its region. * * @param src The DisplayObject. * @param accuracy percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average saturation value on a scale of 0-1. */ public function averageSaturation(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):Number { return averageColorProperty(src, region, accuracy, 's'); } } ================================================ FILE: src/utils/color/averageValue.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Sample & average the Value (HSV) value from a display object or one of its region. * * @param src The DisplayObject * @param accuracy percentage of pixels to sample when averaging. * @param region to sample from [Default: null = entire src object]. * @return the sampled average lightness value on a scale of 0-1. */ public function averageValue(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):Number { return averageColorProperty(src, region, accuracy, 'v'); } } ================================================ FILE: src/utils/color/changeContrast.as ================================================ package utils.color { import utils.number.clamp; /** * Change the contrast of a hexadecimal Number by a certain increment * @param hex color value to shift contrast on * @param inc increment value to shift * @return new hex color value */ public function changeContrast(hex:Number, inc:Number):Number { var o:Object = getRGB(hex); o.r = clamp(o.r + inc, 0, 255); o.g = clamp(o.g + inc, 0, 255); o.b = clamp(o.b + inc, 0, 255); return toRGBComponents(o.r, o.g, o.b); } } ================================================ FILE: src/utils/color/getARGB.as ================================================ package utils.color { /** Converts a 32-bit ARGB color value into an ARGB object. @param color: The 32-bit ARGB color value. @return Returns an object with the properties a, r, g, and b defined. @example var myRGB:Object = ColorUtil.getARGB(0xCCFF00FF); trace("Alpha = " + myRGB.a); trace("Red = " + myRGB.r); trace("Green = " + myRGB.g); trace("Blue = " + myRGB.b); */ public function getARGB(color:uint):Object { var c:Object = {}; c.a = color >> 24 & 0xFF; c.r = color >> 16 & 0xFF; c.g = color >> 8 & 0xFF; c.b = color & 0xFF; return c; } } ================================================ FILE: src/utils/color/getColor.as ================================================ package utils.color { /** Converts a series of individual RGB(A) values to a 32-bit ARGB color value. @param r A uint from 0 to 255 representing the red color value. @param g A uint from 0 to 255 representing the green color value. @param b A uint from 0 to 255 representing the blue color value. @param a A uint from 0 to 255 representing the alpha value. Default is 255. @return Returns a hexidecimal color as a String. @example var hexColor : String = ColorUtil.getHexStringFromARGB(128, 255, 0, 255); trace(hexColor); // Traces 80FF00FF */ public function getColor(r:uint, g:uint, b:uint, a:uint = 255):uint { return (a << 24) | (r << 16) | (g << 8) | b; } } ================================================ FILE: src/utils/color/getColorFromDisplayObject.as ================================================ package utils.color { import flash.display.BitmapData; import flash.display.DisplayObject; import utils.number.clamp; /** * Return the (A)RGB hexadecimal color value of a DisplayObject. * @param src of the display object. * @param x position to sample. * @param y position to sample. * @param getAlpha if true return is RGBA, else RGB. */ public function getColorFromDisplayObject(src:DisplayObject, x:uint = 0, y:uint = 0, getAlpha:Boolean = false):uint { const MAX_SIZE_SAFE:int = 2880; var w:Number = clamp(src.width, 1, MAX_SIZE_SAFE); var h:Number = clamp(src.height, 1, MAX_SIZE_SAFE); var bmp:BitmapData = new BitmapData(w, h); bmp.lock(); bmp.draw(src); var color:uint = (!getAlpha) ? bmp.getPixel(int(x), int(y)) : bmp.getPixel32(int(x), int(y)); bmp.unlock(); bmp.dispose(); return color; } } ================================================ FILE: src/utils/color/getHexStringFromARGB.as ================================================ package utils.color { /** Converts a 32-bit ARGB color value into a hexadecimal String representation. @param a A uint from 0 to 255 representing the alpha value. @param r A uint from 0 to 255 representing the red color value. @param g A uint from 0 to 255 representing the green color value. @param b A uint from 0 to 255 representing the blue color value. @return Returns a hexadecimal color as a String. @example var hexColor : String = ColorUtil.getHexStringFromARGB(128, 255, 0, 255); trace(hexColor); // Traces 80FF00FF */ public function getHexStringFromARGB(a:uint, r:uint, g:uint, b:uint):String { var aa:String = a.toString(16); var rr:String = r.toString(16); var gg:String = g.toString(16); var bb:String = b.toString(16); aa = (aa.length == 1) ? '0' + aa : aa; rr = (rr.length == 1) ? '0' + rr : rr; gg = (gg.length == 1) ? '0' + gg : gg; bb = (bb.length == 1) ? '0' + bb : bb; return (aa + rr + gg + bb).toUpperCase(); } } ================================================ FILE: src/utils/color/getHexStringFromRGB.as ================================================ package utils.color { /** Converts an RGB color value into a hexadecimal String representation. @param r A uint from 0 to 255 representing the red color value. @param g A uint from 0 to 255 representing the green color value. @param b A uint from 0 to 255 representing the blue color value. @return Returns a hexadecimal color as a String. @example var hexColor : String = ColorUtil.getHexStringFromRGB(255, 0, 255); trace(hexColor); // Traces FF00FF */ public function getHexStringFromRGB(r:uint, g:uint, b:uint):String { var rr:String = r.toString(16); var gg:String = g.toString(16); var bb:String = b.toString(16); rr = (rr.length == 1) ? '0' + rr : rr; gg = (gg.length == 1) ? '0' + gg : gg; bb = (bb.length == 1) ? '0' + bb : bb; return (rr + gg + bb).toUpperCase(); } } ================================================ FILE: src/utils/color/getRGB.as ================================================ package utils.color { /** Converts a 24-bit RGB color value into an RGB object. @param color: The 24-bit RGB color value. @return Returns an object with the properties r, g, and b defined. @example var myRGB:Object = ColorUtil.getRGB(0xFF00FF); trace("Red = " + myRGB.r); trace("Green = " + myRGB.g); trace("Blue = " + myRGB.b); */ public function getRGB(color:uint):Object { var c:Object = {}; c.r = color >> 16 & 0xFF; c.g = color >> 8 & 0xFF; c.b = color & 0xFF; return c; } } ================================================ FILE: src/utils/color/getTransform.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.ColorTransform; /** * Returns the transform value set by the last setTransform() call. * @return An object containing the current offset and percentage values for the color. */ public function getTransform(src:DisplayObject):Object { var ct:ColorTransform = src.transform.colorTransform; return { ra: ct.redMultiplier * 100, rb: ct.redOffset, ga: ct.greenMultiplier * 100, gb: ct.greenOffset, ba: ct.blueMultiplier * 100, bb: ct.blueOffset, aa: ct.alphaMultiplier * 100, ab: ct.alphaOffset }; } } ================================================ FILE: src/utils/color/interpolateColor.as ================================================ package utils.color { import flash.geom.ColorTransform; import utils.math.Percent; import utils.number.interpolate; /** Interpolates (tints) between two colors. @param begin: The start color. @param end: The finish color. @param amount: The level of interpolation between the two colors. @return The new interpolated color. @usage var myColor:ColorTransform = new ColorTransform(); myColor.color = 0xFF0000; var box:Sprite = new Sprite(); box.graphics.beginFill(0x0000FF); box.graphics.drawRect(10, 10, 250, 250); box.graphics.endFill(); box.transform.colorTransform = ColorUtil.interpolateColor(new ColorTransform(), myColor, new Percent(0.5)); this.addChild(box); */ public function interpolateColor(begin:ColorTransform, end:ColorTransform, amount:Percent):ColorTransform { var interpolation:ColorTransform = new ColorTransform(); interpolation.redMultiplier = interpolate(amount, begin.redMultiplier, end.redMultiplier); interpolation.greenMultiplier = interpolate(amount, begin.greenMultiplier, end.greenMultiplier); interpolation.blueMultiplier = interpolate(amount, begin.blueMultiplier, end.blueMultiplier); interpolation.alphaMultiplier = interpolate(amount, begin.alphaMultiplier, end.alphaMultiplier); interpolation.redOffset = interpolate(amount, begin.redOffset, end.redOffset); interpolation.greenOffset = interpolate(amount, begin.greenOffset, end.greenOffset); interpolation.blueOffset = interpolate(amount, begin.blueOffset, end.blueOffset); interpolation.alphaOffset = interpolate(amount, begin.alphaOffset, end.alphaOffset); return interpolation; } } ================================================ FILE: src/utils/color/invertColor.as ================================================ package utils.color { import flash.display.DisplayObject; /** * Inverts the color of the DisplayObject. */ public function invertColor(src:DisplayObject):void { var t:Object = getTransform(src); setTransform(src, { ra: -t['ra'], ga: -t['ga'], ba: -t['ba'], rb: 255 - t['rb'], gb: 255 - t['gb'], bb: 255 - t['bb'] }); } } ================================================ FILE: src/utils/color/randomColor.as ================================================ package utils.color { /** * Returns a random color between 0x000000 and 0xFFFFFF * * @author Mims Wright */ public function randomColor():uint { return uint(Math.random() * 0xFFFFFF); } } ================================================ FILE: src/utils/color/resetColor.as ================================================ package utils.color { import flash.display.DisplayObject; /** * Reset the color of the DisplayObject to its original view (pre-ColorTransformed). */ public function resetColor(src:DisplayObject):void { setTransform(src, { ra: 100, ga: 100, ba: 100, rb: 0, gb: 0, bb: 0 }); } } ================================================ FILE: src/utils/color/setARGB.as ================================================ package utils.color { public function setARGB(a:Number, r:Number, g:Number, b:Number):uint { var argb:uint = 0; argb += (a << 24); argb += (r << 16); argb += (g << 8); argb += (b); return argb; } } ================================================ FILE: src/utils/color/setColor.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.ColorTransform; /** * Set the (A)RGB hexadecimal color value of a DisplayObject using ColorTransform. */ public function setColor(src:DisplayObject, hex:uint):void { var ct:ColorTransform = src.transform.colorTransform; ct.color = hex; src.transform.colorTransform = ct; } } ================================================ FILE: src/utils/color/setTransform.as ================================================ package utils.color { import flash.display.DisplayObject; import flash.geom.ColorTransform; /** * Set ColorTransform information for a DisplayObject. * *

The colorTransformObject parameter is a generic object that you create from the new Object constructor. It has parameters specifying the percentage and * offset values for the red, green, blue, and alpha (transparency) components of a color, entered in the format 0xRRGGBBAA.

* * @param transformObject An object created with the new Object constructor. This instance of the Object class must have the following properties * that specify color transform values: ra, rb, ga, gb, ba, bb, aa, ab. These properties are explained in the above summary for the setTransform() method. */ public function setTransform(src:DisplayObject, transformObject:Object):void { var t:Object = { ra: 100, rb: 0, ga: 100, gb: 0, ba: 100, bb: 0, aa: 100, ab: 0 }; for (var p:String in transformObject) { t[p] = transformObject[p]; } var ct:ColorTransform = new ColorTransform(t['ra'] * 0.01, t['ga'] * 0.01, t['ba'] * 0.01, t['aa'] * 0.01, t['rb'], t['gb'], t['bb'], t['ab']); src.transform.colorTransform = ct; } } ================================================ FILE: src/utils/color/toColor.as ================================================ package utils.color { /** * Parse a String representation of a color (hex or html) to uint. */ public function toColor(str:String):uint { if (str.substr(0, 2) == '0x') { str = str.substr(2); } else if (str.substr(0, 1) == '#') { str = str.substr(1); } return parseInt(str, 16); } } ================================================ FILE: src/utils/color/toGrayscale.as ================================================ package utils.color { public function toGrayscale(hex:uint):uint { var color:Object = getARGB(hex); var c:Number = 0; c += color.r * .3; c += color.g * .59; c += color.b * .11; color.r = color.g = color.b = c; return setARGB(color.a, color.r, color.g, color.b); } } ================================================ FILE: src/utils/color/toHTML.as ================================================ package utils.color { /** * Convert a hexadecimal number to a string representation with HTML notation: #rrggbb. */ public function toHTML(hex:uint):String { return "#" + (hex.toString(16)).toUpperCase(); } } ================================================ FILE: src/utils/color/toHexString.as ================================================ package utils.color { /** * Convert a hexadecimal number to a string representation with ECMAScript notation: 0xrrggbb. */ public function toHexString(hex:uint):String { return "0x" + (hex.toString(16)).toUpperCase(); } } ================================================ FILE: src/utils/color/toRGBComponents.as ================================================ package utils.color { /** * Convert individual R,G,B values to a hexadecimal value. */ public function toRGBComponents(r:uint, g:uint, b:uint):uint { var hex:uint = 0; hex += (r << 16); hex += (g << 8); hex += (b); return hex; } } ================================================ FILE: src/utils/conversion/bitsToBytes.as ================================================ package utils.conversion { /** Converts bits to bytes. @param bits: The number of bits. @return Returns the number of bytes. */ public function bitsToBytes(bits:Number):Number { return bits / 8; } } ================================================ FILE: src/utils/conversion/bitsToKilobits.as ================================================ package utils.conversion { /** Converts bits to kilobits. @param bits: The number of bits. @return Returns the number of kilobits. */ public function bitsToKilobits(bits:Number):Number { return bits / 1024; } } ================================================ FILE: src/utils/conversion/bitsToKilobytes.as ================================================ package utils.conversion { /** Converts bits to kilobytes. @param bits: The number of bits. @return Returns the number of kilobits. */ public function bitsToKilobytes(bits:Number):Number { return bits / 8192; } } ================================================ FILE: src/utils/conversion/bytesToBits.as ================================================ package utils.conversion { /** Converts bytes to bits. @param bytes: The number of bytes. @return Returns the number of bits. */ public function bytesToBits(bytes:Number):Number { return bytes * 8; } } ================================================ FILE: src/utils/conversion/bytesToKilobits.as ================================================ package utils.conversion { /** Converts bytes to kilobits. @param bytes: The number of bytes. @return Returns the number of kilobits. */ public function bytesToKilobits(bytes:Number):Number { return bytes / 128; } } ================================================ FILE: src/utils/conversion/bytesToKilobytes.as ================================================ package utils.conversion { /** Converts bytes to kilobytes. @param bytes: The number of bytes. @return Returns the number of kilobytes. */ public function bytesToKilobytes(bytes:Number):Number { return bytes / 1024; } } ================================================ FILE: src/utils/conversion/daysToHours.as ================================================ package utils.conversion { /** Converts days to hours. @param days: The number of days. @return Returns the number of hours. */ public function daysToHours(days:Number):Number { return days * 24; } } ================================================ FILE: src/utils/conversion/daysToMilliseconds.as ================================================ package utils.conversion { /** Converts days to milliseconds. @param days: The number of days. @return Returns the number of milliseconds. */ public function daysToMilliseconds(days:Number):Number { return secondsToMilliseconds(daysToSeconds(days)); } } ================================================ FILE: src/utils/conversion/daysToMinutes.as ================================================ package utils.conversion { /** Converts days to minutes. @param days: The number of days. @return Returns the number of minutes. */ public function daysToMinutes(days:Number):Number { return hoursToMinutes(daysToHours(days)); } } ================================================ FILE: src/utils/conversion/daysToSeconds.as ================================================ package utils.conversion { /** Converts days to seconds. @param days: The number of days. @return Returns the number of seconds. */ public function daysToSeconds(days:Number):Number { return minutesToSeconds(daysToMinutes(days)); } } ================================================ FILE: src/utils/conversion/degreesToRadians.as ================================================ package utils.conversion { /** Converts degrees to radians. @param degrees: The number of degrees. @return Returns the number of radians. */ public function degreesToRadians(degrees:Number):Number { return degrees * (Math.PI / 180); } } ================================================ FILE: src/utils/conversion/hoursToDays.as ================================================ package utils.conversion { /** Converts hours to days. @param hours: The number of hours. @return Returns the number of days. */ public function hoursToDays(hours:Number):Number { return hours / 24; } } ================================================ FILE: src/utils/conversion/hoursToMilliseconds.as ================================================ package utils.conversion { /** Converts hours to milliseconds. @param hours: The number of hours. @return Returns the number of milliseconds. */ public function hoursToMilliseconds(hours:Number):Number { return secondsToMilliseconds(hoursToSeconds(hours)); } } ================================================ FILE: src/utils/conversion/hoursToMinutes.as ================================================ package utils.conversion { /** Converts hours to minutes. @param hours: The number of hours. @return Returns the number of minutes. */ public function hoursToMinutes(hours:Number):Number { return hours * 60; } } ================================================ FILE: src/utils/conversion/hoursToSeconds.as ================================================ package utils.conversion { /** Converts hours to seconds. @param hours: The number of hours. @return Returns the number of seconds. */ public function hoursToSeconds(hours:Number):Number { return minutesToSeconds(hoursToMinutes(hours)); } } ================================================ FILE: src/utils/conversion/kilobitsToBits.as ================================================ package utils.conversion { /** Converts kilobits to bits. @param kilobits: The number of kilobits. @return Returns the number of bits. */ public function kilobitsToBits(kilobits:Number):Number { return kilobits * 1024; } } ================================================ FILE: src/utils/conversion/kilobitsToBytes.as ================================================ package utils.conversion { /** Converts kilobits to bytes. @param kilobits: The number of kilobits. @return Returns the number of bytes. */ public function kilobitsToBytes(kilobits:Number):Number { return kilobits * 128; } } ================================================ FILE: src/utils/conversion/kilobitsToKilobytes.as ================================================ package utils.conversion { /** Converts kilobits to kilobytes. @param kilobytes: The number of kilobits. @return Returns the number of kilobytes. */ public function kilobitsToKilobytes(kilobits:Number):Number { return kilobits / 8; } } ================================================ FILE: src/utils/conversion/kilobytesToBits.as ================================================ package utils.conversion { /** Converts kilobytes to bits. @param kilobytes: The number of kilobytes. @return Returns the number of bits. */ public function kilobytesToBits(kilobytes:Number):Number { return kilobytes * 8192; } } ================================================ FILE: src/utils/conversion/kilobytesToBytes.as ================================================ package utils.conversion { /** Converts kilobytes to bytes. @param kilobytes: The number of kilobytes. @return Returns the number of bytes. */ public function kilobytesToBytes(kilobytes:Number):Number { return kilobytes * 1024; } } ================================================ FILE: src/utils/conversion/kilobytesToKilobits.as ================================================ package utils.conversion { /** Converts kilobytes to kilobits. @param kilobytes: The number of kilobytes. @return Returns the number of kilobits. */ public function kilobytesToKilobits(kilobytes:Number):Number { return kilobytes * 8; } } ================================================ FILE: src/utils/conversion/millisecondsToDays.as ================================================ package utils.conversion { /** Converts milliseconds to days. @param milliseconds: The number of milliseconds. @return Returns the number of days. */ public function millisecondsToDays(milliseconds:Number):Number { return hoursToDays(millisecondsToHours(milliseconds)); } } ================================================ FILE: src/utils/conversion/millisecondsToHours.as ================================================ package utils.conversion { /** Converts milliseconds to hours. @param milliseconds: The number of milliseconds. @return Returns the number of hours. */ public function millisecondsToHours(milliseconds:Number):Number { return minutesToHours(millisecondsToMinutes(milliseconds)); } } ================================================ FILE: src/utils/conversion/millisecondsToMinutes.as ================================================ package utils.conversion { /** Converts milliseconds to minutes. @param milliseconds: The number of milliseconds. @return Returns the number of minutes. */ public function millisecondsToMinutes(milliseconds:Number):Number { return secondsToMinutes(millisecondsToSeconds(milliseconds)); } } ================================================ FILE: src/utils/conversion/millisecondsToSeconds.as ================================================ package utils.conversion { /** Converts milliseconds to seconds. @param milliseconds: The number of milliseconds. @return Returns the number of seconds. */ public function millisecondsToSeconds(milliseconds:Number):Number { return milliseconds / 1000; } } ================================================ FILE: src/utils/conversion/minutesToDays.as ================================================ package utils.conversion { /** Converts minutes to days. @param minutes: The number of minutes. @return Returns the number of days. */ public function minutesToDays(minutes:Number):Number { return hoursToDays(minutesToHours(minutes)); } } ================================================ FILE: src/utils/conversion/minutesToHours.as ================================================ package utils.conversion { /** Converts minutes to hours. @param minutes: The number of minutes. @return Returns the number of hours. */ public function minutesToHours(minutes:Number):Number { return minutes / 60; } } ================================================ FILE: src/utils/conversion/minutesToMilliseconds.as ================================================ package utils.conversion { /** Converts minutes to milliseconds. @param minutes: The number of minutes. @return Returns the number of milliseconds. */ public function minutesToMilliseconds(minutes:Number):Number { return secondsToMilliseconds(minutesToSeconds(minutes)); } } ================================================ FILE: src/utils/conversion/minutesToSeconds.as ================================================ package utils.conversion { /** Converts minutes to seconds. @param minutes: The number of minutes. @return Returns the number of seconds. */ public function minutesToSeconds(minutes:Number):Number { return minutes * 60; } } ================================================ FILE: src/utils/conversion/radiansToDegrees.as ================================================ package utils.conversion { /** Converts radians to degrees. @param radians: The number of radians. @return Returns the number of degrees. */ public function radiansToDegrees(radians:Number):Number { return radians * (180 / Math.PI); } } ================================================ FILE: src/utils/conversion/secondsToDays.as ================================================ package utils.conversion { /** Converts seconds to days. @param seconds: The number of seconds. @return Returns the number of days. */ public function secondsToDays(seconds:Number):Number { return hoursToDays(secondsToHours(seconds)); } } ================================================ FILE: src/utils/conversion/secondsToHours.as ================================================ package utils.conversion { /** Converts seconds to hours. @param seconds: The number of seconds. @return Returns the number of hours. */ public function secondsToHours(seconds:Number):Number { return minutesToHours(secondsToMinutes(seconds)); } } ================================================ FILE: src/utils/conversion/secondsToMilliseconds.as ================================================ package utils.conversion { /** Converts seconds to milliseconds. @param seconds: The number of seconds. @return Returns the number of milliseconds. */ public function secondsToMilliseconds(seconds:Number):Number { return seconds * 1000; } } ================================================ FILE: src/utils/conversion/secondsToMinutes.as ================================================ package utils.conversion { /** Converts seconds to minutes. @param seconds: The number of seconds. @return Returns the number of minutes. */ public function secondsToMinutes(seconds:Number):Number { return seconds / 60; } } ================================================ FILE: src/utils/cookie/getCookie.as ================================================ package utils.cookie { import flash.external.ExternalInterface; public function getCookie(cookieName:String):String { var r:String = ""; var search:String = cookieName + "="; var js:String = "function get_cookie(){return document.cookie;}"; var o:Object = ExternalInterface.call(js); var cookieVariable:String = o.toString(); if (cookieVariable.length > 0) { var offset:int = cookieVariable.indexOf(search); if (offset != -1) { offset += search.length; var end:int = cookieVariable.indexOf(";", offset); if (end == -1) end = cookieVariable.length; r = unescape(cookieVariable.substring(offset, end)); } } return r; } } ================================================ FILE: src/utils/cookie/setCookie.as ================================================ package utils.cookie { import flash.external.ExternalInterface; public function setCookie(cookieName:String, cookieValue:String):void { var js:String = "function sc(){"; js += "var c = escape('" + cookieName + "') + '=' + escape('" + cookieValue + "') + '; path=/';"; js += "document.cookie = c;"; js += "}"; ExternalInterface.call(js); } } ================================================ FILE: src/utils/date/Calendar.as ================================================ /** * User: John Lindquist * Date: 3/16/11 * Time: 11:27 AM */ package utils.date { /** * Calendar is an exception to the "package-level function" rule * * This class provides common dates (today, yesterday, tomorrow, last Sunday, next Thursday, the first of the year, the first of June, etc) * all based on "now" * * To determine whether or not a date belongs in "Calendar", simply ask yourself, "Is this date based on 'now'?" * * These properties will leverage many of the package-level functions such as "getNextDay", etc, but will simply be based on "now" */ public class Calendar { public var now:Date = new Date(); public var today:Date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0); } } ================================================ FILE: src/utils/date/TimeRelationships.as ================================================ package utils.date { public class TimeRelationships { // // Milliseconds // public static const YEAR_IN_MILLISECONDS:Number = 31536000000.0; public static const THIRTY_ONE_DAY_MONTH_IN_MILLISECONDS:Number = 2678400000.0; public static const THIRTY_DAY_MONTH_IN_MILLISECONDS:Number = 2592000000.0; public static const TWENTY_EIGHT_DAY_MONTH_IN_MILLISECONDS:Number = 2419200000.0; public static const WEEK_IN_MILLISECONDS:Number = 604800000.0; public static const DAY_IN_MILLISECONDS:Number = 86400000.0; public static const HOUR_IN_MILLISECONDS:Number = 3600000.0; public static const MINUTE_IN_MILLISECONDS:Number = 60000.0; // // Seconds // public static const YEAR_IN_SECONDS:Number = 31536000; public static const THIRTY_ONE_DAY_MONTH_IN_SECONDS:Number = 2678400; public static const THIRTY_DAY_MONTH_IN_SECONDS:Number = 2592000; public static const TWENTY_EIGHT_DAY_MONTH_IN_SECONDS:Number = 2419200; public static const WEEK_IN_SECONDS:Number = 604800; public static const DAY_IN_SECONDS:Number = 86400; public static const HOUR_IN_SECONDS:Number = 3600; public static const MINUTE_IN_SECONDS:Number = 60; } } ================================================ FILE: src/utils/date/Timezone.as ================================================ package utils.date { /* * Need to discuss how to refactor timezone logic into better utils * * This class currently only works with USA (the offsets default to EAST if the timezone is outside of the USA. * * */ public class Timezone { public static const EAST:String = "ET"; public static const WEST:String = "WT"; public static const ARIZONA:String = "AZ"; public static const MOUNTAIN:String = "MT"; public static const CENTRAL:String = "CT"; public static const PACIFIC:String = "PT"; public static const ALASKA:String = "AK"; public static const HAWAII:String = "HT"; private static var nonDstOffsetDate:Date = new Date(2010, 1, 1); private static var dstOffsetDate:Date = new Date(2010, 7, 1); private static var observesDST:Boolean = (nonDstOffsetDate.timezoneOffset != dstOffsetDate.timezoneOffset); private static var timezone:String = EAST; public static function get zuluOffset():String { var offset:Number = nonDstOffsetDate.timezoneOffset / 60; if(offset > 11 || offset <= 5) { offset = 4; //defaulting to east coast return String(offset); } return String(new Date().timezoneOffset / 60); } public static function get dstOffset():String { var offset:Number = dstOffsetDate.timezoneOffset / 60; if(offset > 10 || offset <= 4) { offset = 4; //defaulting to east coast } return String(offset); } public static function get nonDstOffset():String { var offset:Number = nonDstOffsetDate.timezoneOffset / 60; if(offset > 11 || offset <= 5) { offset = 5; //defaulting to east coast } return String(offset); } public static function get name():String { //Default to Eastern switch (nonDstOffset) { case "10": timezone = HAWAII; //Hawaii break; case "9": timezone = ALASKA; //Alaska break; case "8": timezone = PACIFIC;//Pacific break; case "7": timezone = MOUNTAIN;//Mountain if(!observesDST) timezone = ARIZONA; break; case "6": timezone = CENTRAL;//Central break; default: timezone = EAST; } return timezone; } } } ================================================ FILE: src/utils/date/addWeeks.as ================================================ package utils.date { public function addWeeks(date:Date, weeks:uint):Date { date.date += weeks * 7; return date; } } ================================================ FILE: src/utils/date/ceil.as ================================================ package utils.date { /** * Returns the rounded up date where the time is 12:00am. * If a date is not provided, the current date is used. * @param date the date to round up * @return */ public function ceil(date:Date = null):Date { if (!date) date = new Date(); date.date += 1.0; date.hours = 0.0; date.minutes = 0.0; date.seconds = 0.0; date.milliseconds = 0.0; return date; } } ================================================ FILE: src/utils/date/clone.as ================================================ package utils.date { public function clone(date:Date):Date { return new Date(date.fullYear, date.month, date.date, date.hours, date.minutes, date.seconds, date.milliseconds); } } ================================================ FILE: src/utils/date/compareDates.as ================================================ package utils.date { /** * Compares two dates and returns an integer depending on their relationship. * * Returns -1 if d1 is later than d2. * Returns 1 if d2 is later than d1. * Returns 0 if both dates are equal. * * @param d1 The date that will be compared to the second date. * @param d2 The date that will be compared to the first date. * * @return An int indicating how the two dates compare. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function compareDates(d1:Date, d2:Date):int { var d1ms:Number = d1.getTime(); var d2ms:Number = d2.getTime(); if (d1ms > d2ms) { return -1; } else if (d1ms < d2ms) { return 1; } else { return 0; } } } ================================================ FILE: src/utils/date/dayAbbrNames.as ================================================ package utils.date { public const dayAbbrNames:Array = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]; } ================================================ FILE: src/utils/date/dayNames.as ================================================ package utils.date { public const dayNames:Array = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; } ================================================ FILE: src/utils/date/equals.as ================================================ package utils.date { /** Determines if two Dates are the same time. @param first: First Date to compare to second. @param second: Second Date to compare to first. @return Returns true if Dates are the same; otherwise false. */ public function equals(first:Date, second:Date):Boolean { return first.valueOf() == second.valueOf(); } } ================================================ FILE: src/utils/date/floor.as ================================================ package utils.date { /** * Returns the rounded down date where the time is 12:00am. * If a date is not provided, the current date is used. * @param date the date to round down * @return */ public function floor(date:Date = null):Date { if (!date) date = new Date(); date.hours = 0.0; date.minutes = 0.0; date.seconds = 0.0; date.milliseconds = 0.0; return date; } } ================================================ FILE: src/utils/date/formatDate.as ================================================ package utils.date { import utils.conversion.minutesToSeconds; import utils.number.addLeadingZeroes; import utils.number.format; import utils.number.getOrdinalSuffix; /** * Formats a Date object for display. Acts almost identically to the PHP date() function. * You can prevent a recognized character in the format string from being expanded by escaping it with a preceding ^. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Format characterDescriptionExample returned values
dDay of the month, 2 digits with leading zeros.01 to 31
DA textual representation of a day, three letters.Mon through Sun
jDay of the month without leading zeros.1 to 31
lA full textual representation of the day of the week.Sunday through Saturday
NISO-8601 numeric representation of the day of the week.1 (for Monday) through 7 (for Sunday)
SEnglish ordinal suffix for the day of the month, 2 characters.st, nd, rd or th
wNumeric representation of the day of the week.0 (for Sunday) through 6 (for Saturday)
zThe day of the year (starting from 0).0 through 365
WISO-8601 week number of year, weeks starting on Monday.Example: 42 (the 42nd week in the year)
FA full textual representation of a month, such as January or March.January through December
mNumeric representation of a month, with leading zeros.01 through 12
MA short textual representation of a month, three letters.Jan through Dec
nNumeric representation of a month, without leading zeros.1 through 12
tNumber of days in the given month.28 through 31
LDetermines if it is a leap year.1 if it is a leap year, 0 otherwise
o or YA full numeric representation of a year, 4 digits.Examples: 1999 or 2003
yA two digit representation of a year.Examples: 99 or 03
aLowercase Ante meridiem and Post meridiem.am or pm
AUppercase Ante meridiem and Post meridiem.AM or PM
BSwatch Internet time.000 through 999
g12-hour format of an hour without leading zeros.1 through 12
G24-hour format of an hour without leading zeros.0 through 23
h12-hour format of an hour with leading zeros.01 through 12
H24-hour format of an hour with leading zeros.00 through 23
iMinutes with leading zeros.00 to 59
sSeconds, with leading zeros.00 through 59
IDetermines if the date is in daylight saving time.1 if Daylight Saving Time, 0 otherwise
ODifference to coordinated universal time (UTC) in hours.Example: +0200
PDifference to Greenwich time (GMT/UTC) in hours with colon between hours and minutes.Example: +02:00
e or TTimezone abbreviation.Examples: EST, MDT
ZTimezone offset in seconds.-43200 through 50400
cISO 8601 date.2004-02-12T15:19:21+00:00
rRFC 2822 formatted date.Example: Thu, 21 Dec 2000 16:01:07 +0200
USeconds since the Unix Epoch.Example: 1171479314
* Example code: *
	 *          trace(DateUtils.formatDate(new Date(), "l ^t^h^e dS ^of F Y h:i:s A"));
	 *      
* @param dateToFormat Date object you wish to format * @param formatString Format of the outputted date String. See the format characters options above. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function formatDate(dateToFormat:Date, formatString:String):String { var out:String = ""; var c:String; var i:int = -1; var l:uint = formatString.length; var t:Number; while(++i < l) { c = formatString.substr(i, 1); if(c == "^") { out += formatString.substr(++i, 1); } else { switch(c) { case "d" : // Day of the month, 2 digits with leading zeros out += addLeadingZeroes(dateToFormat.getDate()); break; case "D" : // A textual representation of a day, three letters out += getDayAbbrName(dateToFormat.getDay()); break; case "j" : // Day of the month without leading zeros out += String(dateToFormat.getDate()); break; case "l" : // A full textual representation of the day of the week out += getDayAsString(dateToFormat.getDay()); break; case "N" : // ISO-8601 numeric representation of the day of the week t = dateToFormat.getDay(); if(t == 0) t = 7; out += String(t); break; case "S" : // English ordinal suffix for the day of the month, 2 characters out += getOrdinalSuffix(dateToFormat.getDate()); break; case "w" : // Numeric representation of the day of the week out += String(dateToFormat.getDay()); break; case "z" : // The day of the year (starting from 0) out += String(addLeadingZeroes(getDayOfTheYear(dateToFormat))); break; case "W" : // ISO-8601 week number of year, weeks starting on Monday out += String(addLeadingZeroes(getWeekOfTheYear(dateToFormat))); break; case "F" : // A full textual representation of a month, such as January or March out += getMonthName(dateToFormat.getMonth()); break; case "m" : // Numeric representation of a month, with leading zeros out += addLeadingZeroes(dateToFormat.getMonth() + 1); break; case "M" : // A short textual representation of a month, three letters out += getMonthAbbrName(dateToFormat.getMonth()); break; case "n" : // Numeric representation of a month, without leading zeros out += String((dateToFormat.getMonth() + 1)); break; case "t" : // Number of days in the given month out += String(getDaysInMonth(dateToFormat.getMonth(), dateToFormat.getFullYear())); break; case "L" : // Whether it is a leap year out += (isLeapYear(dateToFormat.getFullYear())) ? "1" : "0"; break; case "o" : case "Y" : // A full numeric representation of a year, 4 digits out += String(dateToFormat.getFullYear()); break; case "y" : // A two digit representation of a year out += String(dateToFormat.getFullYear()).substr(-2); break; case "a" : // Lowercase Ante meridiem and Post meridiem out += getMeridiem(dateToFormat.getHours()).toLowerCase(); break; case "A" : // Uppercase Ante meridiem and Post meridiem out += getMeridiem(dateToFormat.getHours()); break; case "B" : // Swatch Internet time out += format(getInternetTime(dateToFormat), 3, null, "0"); break; case "g" : // 12-hour format of an hour without leading zeros t = dateToFormat.getHours(); if(t == 0) { t = 12; } else if(t > 12) { t -= 12; } out += String(t); break; case "G" : // 24-hour format of an hour without leading zeros out += String(dateToFormat.getHours()); break; case "h" : // 12-hour format of an hour with leading zeros t = dateToFormat.getHours() + 1; if(t == 0) { t = 12; } else if(t > 12) { t -= 12; } out += addLeadingZeroes(t); break; case "H" : // 24-hour format of an hour with leading zeros out += addLeadingZeroes(dateToFormat.getHours()); break; case "i" : // Minutes with leading zeros out += addLeadingZeroes(dateToFormat.getMinutes()); break; case "s" : // Seconds, with leading zeros out += addLeadingZeroes(dateToFormat.getSeconds()); break; case "I" : // Whether or not the date is in daylights savings time out += (isDaylightSavings(dateToFormat)) ? "1" : "0"; break; case "O" : // Difference to Greenwich time (GMT/UTC) in hours out += getFormattedDifferenceFromUTC(dateToFormat); break; case "P" : out += getFormattedDifferenceFromUTC(dateToFormat, ":"); break; case "e" : case "T" : // Timezone identifier out += getTimezone(dateToFormat); break; case "Z" : // Timezone offset (GMT/UTC) in seconds. out += String(int(minutesToSeconds(dateToFormat.getTimezoneOffset()))); break; case "c" : // ISO 8601 date out += dateToFormat.getFullYear() + "-" + addLeadingZeroes(dateToFormat.getMonth() + 1) + "-" + addLeadingZeroes(dateToFormat.getDate()) + "T" + addLeadingZeroes(dateToFormat.getHours()) + ":" + addLeadingZeroes(dateToFormat.getMinutes()) + ":" + addLeadingZeroes(dateToFormat.getSeconds()) + getFormattedDifferenceFromUTC(dateToFormat, ":"); break; case "r" : // RFC 2822 formatted date out += getDayAbbrName(dateToFormat.getDay()) + ", " + dateToFormat.getDate() + " " + getMonthAbbrName(dateToFormat.getMonth()) + " " + dateToFormat.getFullYear() + " " + addLeadingZeroes(dateToFormat.getHours()) + ":" + addLeadingZeroes(dateToFormat.getMinutes()) + ":" + addLeadingZeroes(dateToFormat.getSeconds()) + " " + getFormattedDifferenceFromUTC(dateToFormat); break; case "U" : // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) t = int(dateToFormat.getTime() / 1000); out += String(t); break; default : out += formatString.substr(i, 1); } } } return out; } } ================================================ FILE: src/utils/date/formatWeekOf.as ================================================ package utils.date { public function formatWeekOf(date:Date):String { date = getLastSunday(date); var string:String = ""; string = "Week of " + String(date.getUTCMonth() + 1) + "/" + String(date.getUTCDate()); return string; } } ================================================ FILE: src/utils/date/getAMPM.as ================================================ package utils.date { /** * Returns a string indicating whether the date represents a time in the * ante meridiem (AM) or post meridiem (PM). * * If the hour is less than 12 then "AM" will be returned. * * If the hour is greater than 12 then "PM" will be returned. * * @param d1 The Date from which to generate the 12 hour clock indicator. * * @return A String ("AM" or "PM") indicating which half of the day the * hour represents. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function getAMPM(d:Date):String { return (d.hours > 11) ? "PM" : "AM"; } } ================================================ FILE: src/utils/date/getCountdownUntil.as ================================================ package utils.date { import utils.conversion.daysToHours; import utils.conversion.hoursToMinutes; import utils.conversion.millisecondsToDays; import utils.conversion.minutesToSeconds; import utils.conversion.secondsToMilliseconds; /** Determines the time remaining until a certain date. @param startDate: The starting date. @param endDate: The ending date. @return Returns an Object with the properties days, hours, minutes, seconds and milliseconds defined as numbers. @example var countdown:Object = DateUtil.getCountdownUntil(new Date(2006, 11, 31, 21, 36), new Date(2007, 0, 1)); trace("There are " + countdown.hours + " hours and " + countdown.minutes + " minutes until the new year!"); */ public function getCountdownUntil(startDate:Date, endDate:Date):Object { var daysUntil:Number = millisecondsToDays(getTimeBetween(startDate, endDate)); var hoursUntil:Number = daysToHours(daysUntil % 1); var minsUntil:Number = hoursToMinutes(hoursUntil % 1); var secsUntil:Number = minutesToSeconds(minsUntil % 1); var milliUntil:Number = secondsToMilliseconds(secsUntil % 1); return { days: int(daysUntil), hours: int(hoursUntil), minutes: int(minsUntil), seconds: int(secsUntil), milliseconds: int(milliUntil)}; } } ================================================ FILE: src/utils/date/getDayAbbrName.as ================================================ package utils.date { /** * Returns the English abbreviation name of the provided day. * @param day the index of the day, where zero returns 'Sun' and six returns 'Sat' * @return */ public function getDayAbbrName(day:int):String { return dayAbbrNames[day]; } } ================================================ FILE: src/utils/date/getDayAsString.as ================================================ package utils.date { public function getDayAsString(day:Number):String { var dayNamesFull:Array = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); return dayNamesFull[day]; } } ================================================ FILE: src/utils/date/getDayName.as ================================================ package utils.date { /** * Returns the English name of the provided day. * @param day the index of the day, where zero returns 'Sunday' and six returns 'Saturday' * @return */ public function getDayName(day:int):String { return dayNames[day]; } } ================================================ FILE: src/utils/date/getDayOfTheYear.as ================================================ package utils.date { /** Gets the current day out of the total days in the year (starting from 0). @param d: Date object to find the current day of the year from. @return Returns the current day of the year (0-364 or 0-365 on a leap year). */ public function getDayOfTheYear(d:Date):uint { var firstDay:Date = new Date(d.getFullYear(), 0, 1); return (d.getTime() - firstDay.getTime()) / 86400000; } } ================================================ FILE: src/utils/date/getDaysInMonth.as ================================================ package utils.date { /** Finds the number of days in the given month. @param year: The full year. @param month: The month number (0 for January, 1 for February, and so on). @return The number of days in the month; 28 through 31. @example var myDate:Date = new Date(2000, 0, 1); trace(DateUtil.getDaysInMonth(myDate.getFullYear(), myDate.getMonth())); // Traces 31 */ public function getDaysInMonth(year:Number, month:Number):uint { return (new Date(year, ++month, 0)).getDate(); } } ================================================ FILE: src/utils/date/getEarliestDate.as ================================================ package utils.date { /** * Compares dates and returns the latest one. * * @param dates that will be compared. * @return The latest date. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @author Mims H. Wright */ public function getEarliestDate(... dates ):Date { var earliestDate:Date; if (dates.length() == 0) { throw new ArgumentError("Requires at least one argument"); } for each (var date:Date in dates) { if (!earliestDate) { earliestDate = date; continue; } if (date.getTime() > earliestDate.getTime()) { earliestDate = date; } } return earliestDate; } } ================================================ FILE: src/utils/date/getFormattedDifferenceFromUTC.as ================================================ package utils.date { import utils.conversion.minutesToHours; import utils.number.addLeadingZeroes; /** * Formats the difference to coordinated undefined time (UTC). * @param date Date object to find the time zone offset of * @param separator Character(s) that separates the hours from minutes * @return Formatted time difference from UTC */ public function getFormattedDifferenceFromUTC(date:Date, separator:String = ""):String { var pre:String = (-date.getTimezoneOffset() < 0) ? "-" : "+"; return pre + addLeadingZeroes(Math.floor(minutesToHours(date.getTimezoneOffset()))) + separator + addLeadingZeroes(date.getTimezoneOffset() % 60); } } ================================================ FILE: src/utils/date/getInternetTime.as ================================================ package utils.date { import utils.conversion.minutesToHours; import utils.conversion.secondsToHours; /** Converts current time into Swatch internet time or beats. @param d: Date object to convert. @return Returns time in beats (0 to 999). */ public function getInternetTime(d:Date):Number { var beats:uint = ((d.getUTCHours() + 1 + minutesToHours(d.getUTCMinutes()) + secondsToHours(d.getUTCSeconds())) / 0.024); return (beats > 1000) ? beats - 1000 : beats; } } ================================================ FILE: src/utils/date/getLastMonday.as ================================================ package utils.date { public function getLastMonday(date:Date):Date { date.date -= (date.day - 1); return date; } } ================================================ FILE: src/utils/date/getLastSunday.as ================================================ package utils.date { public function getLastSunday(date:Date):Date { var temp:Date = clone(date); temp.date -= temp.day; return temp; } } ================================================ FILE: src/utils/date/getLatestDate.as ================================================ package utils.date { /** * Compares dates and returns the latest one. * * @param dates that will be compared. * @return The latest date. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @author Mims H. Wright */ public function getLatestDate(... dates ):Date { var latestDate:Date; if (dates.length() == 0) { throw new ArgumentError("Requires at least one argument"); } for each (var date:Date in dates) { if (!latestDate) { latestDate = date; continue; } if (date.getTime() > latestDate.getTime()) { latestDate = date; } } return latestDate; } } ================================================ FILE: src/utils/date/getMeridiem.as ================================================ package utils.date { /** Determines if time is Ante meridiem or Post meridiem. @param hours: The hour to find the meridiem of (an integer from 0 to 23). @return Returns either "AM" or "PM" @example trace(DateUtil.getMeridiem(17)); // Traces PM */ public function getMeridiem(hours:Number):String { return (hours < 12) ? 'AM' : 'PM'; } } ================================================ FILE: src/utils/date/getMonthAbbrName.as ================================================ package utils.date { /** * Returns the English abbreviation name of the provided month. * @param month the index of the month, starting at zero * @return */ public function getMonthAbbrName(month:int):String { return monthAbbrNames[month]; } } ================================================ FILE: src/utils/date/getMonthName.as ================================================ package utils.date { /** * Returns the English name of the provided month. * @param month the index of the month, starting at zero * @return */ public function getMonthName(month:int):String { return monthNames[month]; } } ================================================ FILE: src/utils/date/getNextDay.as ================================================ package utils.date { /** Returns the next calender date following the provided Date. * If no Date is provided, the current date is used. * @param startDate The date you wish to get the next day of * @return */ public function getNextDay(startDate:Date=null):Date { const millisecondsPerDay:int = 1000 * 60 * 60 * 24; if(!startDate) startDate = new Date(); //scrub the time of day var tmpDate:Date = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()); tmpDate.setTime(tmpDate.getTime() + millisecondsPerDay); return tmpDate; } } ================================================ FILE: src/utils/date/getPreviousDay.as ================================================ package utils.date { /** Returns the previous calender date to the provided Date. * If no Date is provided, the current date is used. * @param startDate The date you wish to get the previous day of * @return */ public function getPreviousDay(startDate:Date=null):Date { const millisecondsPerDay:int = 1000 * 60 * 60 * 24; if(!startDate) startDate = new Date(); //scrub the time of day var tmpDate:Date = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()); return new Date(tmpDate.getTime() - millisecondsPerDay); } } ================================================ FILE: src/utils/date/getShortHour.as ================================================ package utils.date { /** * Returns a short hour (0 - 12) represented by the specified date. * * If the hour is less than 12 (0 - 11 AM) then the hour will be returned. * * If the hour is greater than 12 (12 - 23 PM) then the hour minus 12 * will be returned. * * @param d1 The Date from which to generate the short hour * * @return An int between 0 and 13 ( 1 - 12 ) representing the short hour. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function getShortHour(d:Date):int { var h:int = d.hours; if (h == 0 || h == 12) { return 12; } else if (h > 12) { return h - 12; } else { return h; } } } ================================================ FILE: src/utils/date/getShortYear.as ================================================ package utils.date { /** * Returns a two digit representation of the year represented by the * specified date. * * @param d The Date instance whose year will be used to generate a two * digit string representation of the year. * * @return A string that contains a 2 digit representation of the year. * Single digits will be padded with 0. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function getShortYear(d:Date):String { var dStr:String = String(d.getFullYear()); if (dStr.length < 3) { return dStr; } return (dStr.substr(dStr.length - 2)); } } ================================================ FILE: src/utils/date/getStartOfWeek.as ================================================ package utils.date { public function getStartOfWeek(date:Date):Date { var temp:Date = clone(date); temp.date -= temp.day; temp = makeMorning(temp); return temp; } } ================================================ FILE: src/utils/date/getTimeBetween.as ================================================ package utils.date { /** Determines the difference between two dates. @param startDate: The starting date. @param endDate: The ending date. @return Returns the difference in milliseconds between the two dates. @example trace(ConversionUtil.millisecondsToDays(DateUtil.getTimeBetween(new Date(2007, 0, 1), new Date(2007, 0, 11)))); // Traces 10 */ public function getTimeBetween(startDate:Date, endDate:Date):Number { return endDate.getTime() - startDate.getTime(); } } ================================================ FILE: src/utils/date/getTimeElapsedString.as ================================================ package utils.date { /** * Takes a Date object and returns a string in the format * "X UNITS ago" where X is a number and UNITS is a unit of * time. Also has some other strings like "yesterday". * * @author Mims Wright (with thanks to John Resig) * * @param date The date to convert to a past string. * @param now Optional time to compare against. Default will be the present. */ public function getTimeElapsedString(date:Date, now:Date = null):String { const SEC_PER_MINUTE:int = 60; const SEC_PER_HOUR:int = SEC_PER_MINUTE * 60; const SEC_PER_DAY:int = SEC_PER_HOUR * 24; const SEC_PER_WEEK:int = SEC_PER_DAY * 7; const SEC_PER_MONTH:int = SEC_PER_DAY * 30; const SEC_PER_YEAR:int = SEC_PER_MONTH * 12; // if now isn't defined, make it a new Date object (the present) if (!now) { now = new Date(); } // don't use secondsElapsed here because the values are // huge so they use uints and are never negative if (now.time < date.time) { return "in the future"; } // get the difference in seconds between the two values. var secondsElapsed:uint = Math.floor((now.time - date.time) / 1000); // seconds if (secondsElapsed < SEC_PER_MINUTE) { return "just now"; } // minutes if (secondsElapsed < SEC_PER_HOUR) { var minutes:int = int(secondsElapsed / SEC_PER_MINUTE); return formatAgoString(minutes, "minute"); } // hours if (secondsElapsed < SEC_PER_DAY) { var hours:int = int(secondsElapsed / SEC_PER_HOUR); return formatAgoString(hours, "hour"); } // days if (secondsElapsed < SEC_PER_WEEK) { var days:int = int(secondsElapsed / SEC_PER_DAY); if (days == 1) { return "yesterday"; } return formatAgoString(days, "day"); } // weeks if (secondsElapsed < SEC_PER_MONTH) { var weeks:int = int(secondsElapsed / SEC_PER_WEEK); return formatAgoString(weeks, "week"); } // months if (secondsElapsed < SEC_PER_YEAR) { var months:int = int(secondsElapsed / SEC_PER_MONTH); return formatAgoString(months, "month"); } // years return "more than a year ago"; // Returns a string in the format "count unit(s) ago" function formatAgoString(count:int, unit:String):String { return count + " " + unit + (count > 1 ? "s" : "") + " ago"; } } } ================================================ FILE: src/utils/date/getTimezone.as ================================================ package utils.date { /** Determines the time zone of the user from a Date object. @param d: Date object to find the time zone of. @return Returns the time zone abbreviation. @example trace(DateUtil.getTimezone(new Date())); */ public function getTimezone(d:Date):String { var timeZones:Array = new Array('IDLW', 'NT', 'HST', 'AKST', 'PST', 'MST', 'CST', 'EST', 'AST', 'ADT', 'AT', 'WAT', 'GMT', 'CET', 'EET', 'MSK', 'ZP4', 'ZP5', 'ZP6', 'WAST', 'WST', 'JST', 'AEST', 'AEDT', 'NZST'); var hour:uint = Math.round(12 + -(d.getTimezoneOffset() / 60)); if (isDaylightSavings(d)) hour--; return timeZones[hour]; } } ================================================ FILE: src/utils/date/getUTCDate.as ================================================ package utils.date { /** * Sort of converts a date into UTC. */ public function getUTCDate(d:Date):Date { var nd:Date = new Date(); var offset:Number = d.getTimezoneOffset() * 60 * 1000; nd.setTime(d.getTime() + offset); return nd; } } ================================================ FILE: src/utils/date/getWeekOfTheYear.as ================================================ package utils.date { import utils.conversion.millisecondsToDays; /** Determines the week number of year, weeks start on Mondays. @param d: Date object to find the current week number of. @return Returns the the week of the year the date falls in. */ public function getWeekOfTheYear(d:Date):uint { var firstDay:Date = new Date(d.getFullYear(), 0, 1); var dayOffset:uint = 9 - firstDay.getDay(); var firstMonday:Date = new Date(d.getFullYear(), 0, (dayOffset > 7) ? dayOffset - 7 : dayOffset); var currentDay:Date = new Date(d.getFullYear(), d.getMonth(), d.getDate()); var weekNumber:uint = (millisecondsToDays(currentDay.getTime() - firstMonday.getTime()) / 7) + 1; return (weekNumber == 0) ? getWeekOfTheYear(new Date(d.getFullYear() - 1, 11, 31)) : weekNumber; } } ================================================ FILE: src/utils/date/isDaylightSavings.as ================================================ package utils.date { /** Determines if or not the date is in daylight saving time. @param d: Date to find if it is during daylight savings time. @return Returns true if daylight savings time; otherwise false. */ public function isDaylightSavings(d:Date):Boolean { var months:uint = 12; var offset:uint = d.getTimezoneOffset(); var offsetCheck:Number; while (months--) { offsetCheck = (new Date(d.getFullYear(), months, 1)).getTimezoneOffset(); if (offsetCheck != offset) return (offsetCheck > offset); } return false; } } ================================================ FILE: src/utils/date/isInCurrentWeek.as ================================================ package utils.date { public function isInCurrentWeek(date:Date):Boolean { var today:Date = new Date(); var startOfWeek:Date = getStartOfWeek(today); var millisecondsDifference:Number = getTimeBetween(startOfWeek, date); var b:Boolean; b = millisecondsDifference < TimeRelationships.WEEK_IN_MILLISECONDS; b &&= millisecondsDifference >= 0; return b; } } ================================================ FILE: src/utils/date/isLeapYear.as ================================================ package utils.date { /** Determines if year is a leap year or a common year. @param year: The full year. @return Returns true if year is a leap year; otherwise false. @example var myDate:Date = new Date(2000, 0, 1); trace(DateUtil.isLeapYear(myDate.getFullYear())); // Traces true */ public function isLeapYear(year:Number):Boolean { return getDaysInMonth(year, 1) == 29; } } ================================================ FILE: src/utils/date/isPast.as ================================================ package utils.date { /** * Returns true if date is in the past. * If the date is exactly equal to the current time, it will return false. * * @author Mims H. Wright */ public function isPast(date:Date):Boolean { return (new Date().getTime() - date.getTime()) > 0; } } ================================================ FILE: src/utils/date/iso8601ToDate.as ================================================ package utils.date { import utils.conversion.minutesToHours; import utils.object.isEmpty; /** * Converts W3C ISO 8601 date String into a Date object. * Example code: *
	 *          trace(iso8601ToDate("1994-11-05T08:15:30-05:00").toString());
	 *      
* @param iso8601 Valid ISO 8601 formatted String * @return Date object of the specified date and time of the ISO 8601 String in universal time * @see http://www.w3.org/TR/NOTE-datetime (W3C ISO 8601 specification) * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function iso8601ToDate(iso8601:String):Date { var parts:Array = iso8601.toUpperCase().split("T"); var date:Array = parts[0].split("-"); var time:Array = (parts.length <= 1) ? [] : parts[1].split(":"); var year:uint = isEmpty(date[0]) ? 0 : Number(date[0]); var month:uint = isEmpty(date[1]) ? 0 : Number(date[1] - 1); var day:uint = isEmpty(date[2]) ? 1 : Number(date[2]); var hour:int = isEmpty(time[0]) ? 0 : Number(time[0]); var minute:uint = isEmpty(time[1]) ? 0 : Number(time[1]); var second:uint = 0; var millisecond:uint = 0; if(time[2] != undefined) { var index:int = time[2].length; var temp:Number; if(time[2].indexOf("+") > -1) { index = time[2].indexOf("+"); } else if(time[2].indexOf("-") > -1) { index = time[2].indexOf("-"); } else if(time[2].indexOf("Z") > -1) { index = time[2].indexOf("Z"); } if(isNaN(index)) { temp = Number(time[2].slice(0, index)); second = Math.floor(temp); millisecond = 1000 * (temp % 1); } if(index != time[2].length) { var offset:String = time[2].slice(index); var userOffset:Number = minutesToHours(new Date(year, month, day).getTimezoneOffset()); switch(offset.charAt(0)) { case "+" : case "-" : hour -= userOffset + Number(offset.slice(0)); break; case "Z" : hour -= userOffset; break; default: } } } return new Date(year, month, day, hour, minute, second, millisecond); } } ================================================ FILE: src/utils/date/makeMorning.as ================================================ package utils.date { /** * Converts a date into just after midnight. */ public function makeMorning(d:Date):Date { d = new Date(d.time); d.hours = 0; d.minutes = 0; d.seconds = 0; d.milliseconds = 0; return d; } } ================================================ FILE: src/utils/date/makeNight.as ================================================ package utils.date { /** * Converts a date into just before midnight. */ public function makeNight(d:Date):Date { d = new Date(d.time); d.hours = 23; d.minutes = 59; d.seconds = 59; d.milliseconds = 999; return d; } } ================================================ FILE: src/utils/date/monthAbbrNames.as ================================================ package utils.date { public const monthAbbrNames:Array = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; } ================================================ FILE: src/utils/date/monthNames.as ================================================ package utils.date { public const monthNames:Array = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; } ================================================ FILE: src/utils/date/parseW3CDTF.as ================================================ package utils.date { /** * Parses dates that conform to the W3C Date-time Format into Date objects. * * This function is useful for parsing RSS 1.0 and Atom 1.0 dates. * * @param str * * @returns Date * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext * * @see http://www.w3.org/TR/NOTE-datetime */ public function parseW3CDTF(str:String):Date { var finalDate:Date; try { var dateStr:String = str.substring(0, str.indexOf("T")); var timeStr:String = str.substring(str.indexOf("T") + 1, str.length); var dateArr:Array = dateStr.split("-"); var year:Number = Number(dateArr.shift()); var month:Number = Number(dateArr.shift()); var date:Number = Number(dateArr.shift()); var multiplier:Number; var offsetHours:Number; var offsetMinutes:Number; var offsetStr:String; if (timeStr.indexOf("Z") != -1) { multiplier = 1; offsetHours = 0; offsetMinutes = 0; timeStr = timeStr.replace("Z", ""); } else if (timeStr.indexOf("+") != -1) { multiplier = 1; offsetStr = timeStr.substring(timeStr.indexOf("+") + 1, timeStr.length); offsetHours = Number(offsetStr.substring(0, offsetStr.indexOf(":"))); offsetMinutes = Number(offsetStr.substring(offsetStr.indexOf(":") + 1, offsetStr.length)); timeStr = timeStr.substring(0, timeStr.indexOf("+")); } else // offset is - { multiplier = -1; offsetStr = timeStr.substring(timeStr.indexOf("-") + 1, timeStr.length); offsetHours = Number(offsetStr.substring(0, offsetStr.indexOf(":"))); offsetMinutes = Number(offsetStr.substring(offsetStr.indexOf(":") + 1, offsetStr.length)); timeStr = timeStr.substring(0, timeStr.indexOf("-")); } var timeArr:Array = timeStr.split(":"); var hour:Number = Number(timeArr.shift()); var minutes:Number = Number(timeArr.shift()); var secondsArr:Array = (timeArr.length > 0) ? String(timeArr.shift()).split(".") : null; var seconds:Number = (secondsArr != null && secondsArr.length > 0) ? Number(secondsArr.shift()) : 0; //var milliseconds:Number = (secondsArr != null && secondsArr.length > 0) ? Number(secondsArr.shift()) : 0; var milliseconds:Number = (secondsArr != null && secondsArr.length > 0) ? 1000 * parseFloat("0." + secondsArr.shift()) : 0; var utc:Number = Date.UTC(year, month - 1, date, hour, minutes, seconds, milliseconds); var offset:Number = (((offsetHours * 3600000) + (offsetMinutes * 60000)) * multiplier); finalDate = new Date(utc - offset); if (finalDate.toString() == "Invalid Date") { throw new Error("This date does not conform to W3CDTF."); } } catch (e:Error) { var eStr:String = "Unable to parse the string [" + str + "] into a date. "; eStr += "The internal error was: " + e.toString(); throw new Error(eStr); } return finalDate; } } ================================================ FILE: src/utils/date/timeCode.as ================================================ package utils.date { /** * Utility function for generating time code given a number seconds. * @param sec Seconds * @return Timecode * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function timeCode(sec:Number):String { var h:Number = Math.floor(sec / 3600); var m:Number = Math.floor((sec % 3600) / 60); var s:Number = Math.floor((sec % 3600) % 60); return (h == 0 ? "" : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + (m < 10 ? "0" + String(m) : String(m)) + ":" + (s < 10 ? "0" + String(s) : String(s)); } } ================================================ FILE: src/utils/date/toW3CDTF.as ================================================ package utils.date { /** * Returns a date string formatted according to W3CDTF. * * @param d * @param includeMilliseconds Determines whether to include the * milliseconds value (if any) in the formatted string. * * @returns String * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext * * @see http://www.w3.org/TR/NOTE-datetime */ public function toW3CDTF(d:Date, includeMilliseconds:Boolean = false):String { var date:Number = d.getUTCDate(); var month:Number = d.getUTCMonth(); var hours:Number = d.getUTCHours(); var minutes:Number = d.getUTCMinutes(); var seconds:Number = d.getUTCSeconds(); var milliseconds:Number = d.getUTCMilliseconds(); var sb:String = new String(); sb += String(d.getUTCFullYear()); sb += "-"; //thanks to "dom" who sent in a fix for the line below if (month + 1 < 10) { sb += "0"; } sb += String(month + 1); sb += "-"; if (date < 10) { sb += "0"; } sb += String(date); sb += "T"; if (hours < 10) { sb += "0"; } sb += String(hours); sb += ":"; if (minutes < 10) { sb += "0"; } sb += String(minutes); sb += ":"; if (seconds < 10) { sb += "0"; } sb += String(seconds); if (includeMilliseconds && milliseconds > 0) { sb += "."; sb += String(milliseconds); } sb += "-00:00"; return sb; } } ================================================ FILE: src/utils/date/toggleAMPM.as ================================================ package utils.date { /** * If a date is AM, changes it to PM and vice versa. * * @author Mims H. Wright * * @param date The Date to flip. * @returns A new date object, 12 hours later or earlier depending. */ public function toggleAMPM(date:Date):Date { var d:Date = new Date(date.time); if (getAMPM(date) == "PM") { d.hours -= 12; } else { d.hours += 12; } return d; } } ================================================ FILE: src/utils/dictionary/CircularDictionary.as ================================================ package utils.dictionary { import flash.errors.IllegalOperationError; import flash.utils.Dictionary; /** * A dictionary which allows a pairing of two values to point to each other. * For example, if you have two objects, A and B, A would point to B and * B would point to A. * * @example * var dict:CircularDictionary = new CircularDictionary(); * dict.addPair(A, B); * dict.getCounterpartTo(A); // B * dict.getCounterpartTo(B); // A * dict.getCounterpartTo(dict.getCounterpartTo(A)); // A * dict.dictionary[B]; // A. Same as getCounterpartTo(B) * dict.removePair(B); // removes both A and B. * * * @author Mims H. Wright */ public class CircularDictionary { private var _dictionary:Dictionary; public function get dictionary():Dictionary { return _dictionary; } /** * Constructor. * * @param useWeakReferences Indicates whether the internal dictionary should use weak references. */ public function CircularDictionary(useWeakReferences:Boolean = false) { _dictionary = new Dictionary ( useWeakReferences ); } /** * Adds a related pair of values. * * @throws IllegalOperationError If the same key is added more than once. * * @param a The first value (references b) * @param b The second value (references a) */ public function addPair(a:*, b:*):void { if ( _dictionary[a] == undefined && _dictionary[b] == undefined) { _dictionary[a] = b; _dictionary[b] = a; return; } throw new IllegalOperationError ("You cannot use the same key or value more than once."); } /** * Removes a related pair of values. * * @param aOrB Either value, a or b. Both references to each other are removed. * @returns The counterpart to whatever value you provided. */ public function removePair (aOrB:*):* { var counterpart:* = _dictionary[aOrB]; delete _dictionary[aOrB]; delete _dictionary[counterpart]; return counterpart; } /** * Returns the corresponding value to the key you provided. If key = a, * returns b, and vice versa. */ public function getCounterpartTo(key:*):* { return _dictionary[key]; } } } ================================================ FILE: src/utils/dictionary/getKeys.as ================================================ package utils.dictionary { import flash.utils.Dictionary; /** * Returns an Array of all keys within the specified dictionary. * * @param d The Dictionary instance whose keys will be returned. * * @return Array of keys contained within the Dictionary * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function getKeys(d:Dictionary):Array { var a:Array = new Array(); for (var key:Object in d) { a.push(key); } return a; } } ================================================ FILE: src/utils/dictionary/getValues.as ================================================ package utils.dictionary { import flash.utils.Dictionary; /** * Returns an Array of all values within the specified dictionary. * * @param d The Dictionary instance whose values will be returned. * * @return Array of values contained within the Dictionary * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function getValues(d:Dictionary):Array { var a:Array = new Array(); for each (var value:Object in d) { a.push(value); } return a; } } ================================================ FILE: src/utils/display/Alignment.as ================================================ package utils.display { /** * @author Justin Windle (justin(at)soulwire.co.uk) */ public class Alignment { /** * Specifies that alignment is at the bottom. */ public static const BOTTOM:String = "B"; /** * Specifies that alignment is in the bottom-left corner. */ public static const BOTTOM_LEFT:String = "BL"; /** * Specifies that alignment is in the bottom-right corner. */ public static const BOTTOM_RIGHT:String = "BR"; /** * Specifies that alignment is on the left. */ public static const LEFT:String = "L"; /** * Specifies that alignment is in the middle */ public static const MIDDLE:String = "C"; /** * Specifies that alignment is on the right. */ public static const RIGHT:String = "R"; /** * Specifies that alignment is at the top. */ public static const TOP:String = "T"; /** * Specifies that alignment is in the top-left corner. */ public static const TOP_LEFT:String = "TL"; /** * Specifies that alignment is in the top-right corner. */ public static const TOP_RIGHT:String = "TR"; } } ================================================ FILE: src/utils/display/IDisplayObject.as ================================================ package utils.display { import flash.display.DisplayObject; /** * An interface to work around the lack of interface for display objects. * Especially useful when you want to type a variable with an interface * and add it to the stage without type casting to DisplayObject each time * (and running the risk of an error). * * @example * var d:IDisplayObject = new ClassThatImplementsIDisplayObject(); * addChild(d.asDisplayObject()); * * * @author Mims H. Wright */ public interface IDisplayObject { /** * Returns a representation of the object as a DisplayObject. * Usually would return the object itself. */ function asDisplayObject():DisplayObject; } } ================================================ FILE: src/utils/display/addChild.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * Allows you to add a child without first checking that the child or parent exist. * Allows you to add a child at an index higher than the number of children without error. * Allows you to use the same function for addChild and addChildAt. * * @param child The child DisplayObject to add. * @param parent The container to add the child to. * @param atIndex The index to add the child at. Default is to add to the top (-1) * @return Boolean True if the child was added, false if something prevented it from being added. * * @author Mims Wright */ public function addChild(child:DisplayObject, parent:DisplayObjectContainer, atIndex:int = -1):Boolean { if (child && parent) { if (atIndex < 0 || atIndex > parent.numChildren) { atIndex = parent.numChildren; } parent.addChildAt(child, atIndex); return true; } return false; } } ================================================ FILE: src/utils/display/applyNaturalScrollRect.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Apply a scroll rect from (0,0) to (width,height) * @param dispObj Display object to apply on * @author Jackson Dunstan */ public function applyNaturalScrollRect(dispObj:DisplayObject):void { dispObj.scrollRect = new Rectangle(0, 0, dispObj.width, dispObj.height); } } ================================================ FILE: src/utils/display/bringForward.as ================================================ package utils.display { import flash.display.DisplayObject; import utils.number.clamp; /** * Brings the DisplayObject forward in the display list. The steps parameter can be used to jump more than one level. * @param object the DisplayObject to reorder * @param steps the number of levels bring the DisplayObject forward * @return the new index of the DisplayObject */ public function bringForward(object:DisplayObject, steps:uint = 1):int { if (!object.parent) return -1; var index:int = object.parent.getChildIndex(object) + steps; index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } ================================================ FILE: src/utils/display/bringToFront.as ================================================ package utils.display { import flash.display.DisplayObject; import utils.number.clamp; /** * Brings the DisplayObject to the front of the display list. The back parameter can be used to pull the DisplayObject back a few levels from the front. * @param object the DisplayObject to reorder * @param back the number of levels from the front of the display list * @return the new index of the DisplayObject */ public function bringToFront(object:DisplayObject, back:uint = 0):int { if (!object.parent) return -1; var index:int = object.parent.numChildren - (back + 1); index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } ================================================ FILE: src/utils/display/centerWithin.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Centers a display object within the bounds of another based on each of their sizes. * Note: does not add the object as a child or add to stage or resize either object. * * @param objectToPosition The DisplayObject that will be moved. * @param withinObject The DisplayObject to position within. If left blank, * will attempt to use the object's parent. * * @author Mims Wright */ public function centerWithin(objectToPosition:DisplayObject, withinObject:DisplayObject = null):void { if (!objectToPosition) { return; } if (!withinObject) { if (objectToPosition.parent) { withinObject = objectToPosition.parent; } else { return; } } objectToPosition.x = withinObject.x + (withinObject.width - objectToPosition.width)/2; objectToPosition.y = withinObject.y + (withinObject.height - objectToPosition.height)/2; } } ================================================ FILE: src/utils/display/createBitmap.as ================================================ package utils.display { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; /** * Returns a Bitmap instance of the supplied DisplayObject. */ public function createBitmap(source:DisplayObject, useSmoothing:Boolean = true):Bitmap { const bitmapData:BitmapData = new BitmapData(source.width, source.height, true, 0xffffff); bitmapData.draw(source); const bitmap:Bitmap = new Bitmap(bitmapData); bitmap.smoothing = useSmoothing; return bitmap; } } ================================================ FILE: src/utils/display/createThumb.as ================================================ package utils.display { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.PixelSnapping; /** * Creates a thumbnail of a BitmapData. The thumbnail can be any size as * the copied image will be scaled proportionally and cropped if necessary * to fit into the thumbnail area. If the image needs to be cropped in order * to fit the thumbnail area, the alignment of the crop can be specified * * @param image * * The source image for which a thumbnail should be created. The source * will not be modified * * @param width * * The width of the thumbnail * * @param height * * The height of the thumbnail * * @param align * * If the thumbnail has a different aspect ratio to the source image, although * the image will be scaled to fit along one axis it will be necessary to crop * the image. Use this parameter to specify how the copied and scaled image should * be aligned within the thumbnail boundaries. Use a constant from the Alignment * enumeration clazz * * @param smooth * * Whether to apply bitmap smoothing to the thumbnail */ public function createThumb(image:BitmapData, width:int, height:int, align:String = "C", smooth:Boolean = true):Bitmap { var source:Bitmap = new Bitmap(image); var thumbnail:BitmapData = new BitmapData(width, height, false, 0x0); thumbnail.draw(image, fitIntoRect(source, thumbnail.rect, true, align, false), null, null, null, smooth); source = null; return new Bitmap(thumbnail, PixelSnapping.AUTO, smooth); } } ================================================ FILE: src/utils/display/cropBitmapData.as ================================================ package utils.display { import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; /** * Crop the BitmapData source and return a new BitmapData. * @param source Source BitmapData * @param dest Crop area as Rectangle * @return Cropped source as BitmapData * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function cropBitmapData(source:BitmapData, dest:Rectangle):BitmapData { var o:BitmapData = new BitmapData(dest.width, dest.height); var point:Point = new Point(0, 0); o.copyPixels(source, dest, point); return o; } } ================================================ FILE: src/utils/display/duplicateDisplayObject.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.Graphics; import flash.geom.Rectangle; import flash.system.Capabilities; /** * duplicateDisplayObject * creates a duplicate of the DisplayObject passed. * similar to duplicateMovieClip in AVM1. If using Flash 9, make sure * you export for ActionScript the symbol you are duplicating * * @param source the display object to duplicate * @param autoAdd if true, adds the duplicate to the display list * in which source was located * @return a duplicate instance of source * * @author Trevor McCauley - www.senocular.com * @author cleaned up by Mims Wright */ public function duplicateDisplayObject(source:DisplayObject, autoAdd:Boolean = false):DisplayObject { var sourceClass:Class = Class(Object(source).constructor); var duplicate:DisplayObject = new sourceClass() as DisplayObject; // duplicate properties duplicate.transform = source.transform; duplicate.filters = source.filters; duplicate.cacheAsBitmap = source.cacheAsBitmap; duplicate.opaqueBackground = source.opaqueBackground; if(source.scale9Grid) { var rect:Rectangle = source.scale9Grid; // version check for scale9Grid bug if(Capabilities.version.split(" ")[1] == "9,0,16,0") { // Flash 9 bug where returned scale9Grid as twips rect.x /= 20,rect.y /= 20,rect.width /= 20,rect.height /= 20; } duplicate.scale9Grid = rect; } // todo: needs test if("graphics" in source) { var graphics:Graphics = Graphics(source["graphics"]); Graphics(duplicate["graphics"]).copyFrom(graphics); } // add to target parent's display list // if autoAdd was provided as true if(autoAdd && source.parent) { source.parent.addChild(duplicate); } return duplicate; } } ================================================ FILE: src/utils/display/filterChildrenByProps.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; public function filterChildrenByProps(container:DisplayObjectContainer, props:Object):Array { var filteredChildren:Array = []; var child:DisplayObject; for (var i:int = 0, l:int = container.numChildren; i < l; i++) { child = container.getChildAt(i); var isOK:Boolean = true; for (var prop:String in props) { if (child[prop] != props[prop]) { isOK = false; break; } } if (isOK) filteredChildren.push(child); } return filteredChildren; } } ================================================ FILE: src/utils/display/findAncestor.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Search the ancestry for a specific parent object. * @param child The display object whose parents to check. * @param ancestor The ancestor to check for. * @return The ancestor or null. * @author Mims H. Wright */ public function findAncestor(child:DisplayObject, ancestor:DisplayObject):DisplayObject { if (child == ancestor) { return ancestor; } if (child.parent == null) { return null; } if (child.parent == ancestor) { return ancestor; } return findAncestor(child.parent, ancestor); } } ================================================ FILE: src/utils/display/findAncestorWithType.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Search the ancestry for a specific parent object. * @param child The display object whose parents to check. * @param type The type to check for. Should be a class or interface. * @return The ancestor or null. * @author Mims H. Wright */ public function findAncestorWithType(child:DisplayObject, type:*):* { if (child.parent == null) { return null; } if (child.parent is type) { return child.parent; } return findAncestorWithType(child.parent, type); } } ================================================ FILE: src/utils/display/fitIntoRect.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.geom.Matrix; import flash.geom.Rectangle; /** * Fits a DisplayObject into a rectangular area with several options for scale * and alignment. This method will return the Matrix required to duplicate the * transformation and can optionally apply this matrix to the DisplayObject. * * @param displayObject * * The DisplayObject that needs to be fitted into the Rectangle. * * @param rectangle * * A Rectangle object representing the space which the DisplayObject should fit into. * * @param fillRect * * Whether the DisplayObject should fill the entire Rectangle or just fit within it. * If true, the DisplayObject will be cropped if its aspect ratio differs to that of * the target Rectangle. * * @param align * * The alignment of the DisplayObject within the target Rectangle. Use a constant from * the DisplayUtils clazz. * * @param applyTransform * * Whether to apply the generated transformation matrix to the DisplayObject. By setting this * to false you can leave the DisplayObject as it is but store the returned Matrix for to use * either with a DisplayObject's transform property or with, for example, BitmapData.draw() */ public function fitIntoRect(displayObject:DisplayObject, rectangle:Rectangle, fillRect:Boolean = true, align:String = "C", applyTransform:Boolean = true):Matrix { var matrix:Matrix = new Matrix(); var wD:Number = displayObject.width / displayObject.scaleX; var hD:Number = displayObject.height / displayObject.scaleY; var wR:Number = rectangle.width; var hR:Number = rectangle.height; var sX:Number = wR / wD; var sY:Number = hR / hD; var rD:Number = wD / hD; var rR:Number = wR / hR; var sH:Number = fillRect ? sY : sX; var sV:Number = fillRect ? sX : sY; var s:Number = rD >= rR ? sH : sV; var w:Number = wD * s; var h:Number = hD * s; var tX:Number = 0.0; var tY:Number = 0.0; switch (align) { case Alignment.LEFT: case Alignment.TOP_LEFT: case Alignment.BOTTOM_LEFT: tX = 0.0; break; case Alignment.RIGHT: case Alignment.TOP_RIGHT: case Alignment.BOTTOM_RIGHT: tX = w - wR; break; default: tX = 0.5 * (w - wR); } switch (align) { case Alignment.TOP: case Alignment.TOP_LEFT: case Alignment.TOP_RIGHT: tY = 0.0; break; case Alignment.BOTTOM: case Alignment.BOTTOM_LEFT: case Alignment.BOTTOM_RIGHT: tY = h - hR; break; default: tY = 0.5 * (h - hR); } matrix.scale(s, s); matrix.translate(rectangle.left - tX, rectangle.top - tY); if (applyTransform) { displayObject.transform.matrix = matrix; } return matrix; } } ================================================ FILE: src/utils/display/getChildren.as ================================================ package utils.display { import flash.display.DisplayObjectContainer; /** * Get the children of a container as an array * @param container Container to get the children of * @return The children of the given container as an array * @author Jackson Dunstan */ public function getChildren(container:DisplayObjectContainer):Array { var ret:Array = []; var numChildren:int = container.numChildren; for (var i:int = 0; i < numChildren; ++i) { ret.push(container.getChildAt(i)); } return ret; } } ================================================ FILE: src/utils/display/getFullBounds.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.geom.Matrix; import flash.geom.Rectangle; import flash.geom.Transform; /** * Determines the full bounds of the display object regardless of masking elements. * @param displayObject The display object to analyze. * @return the display object dimensions. */ public function getFullBounds(displayObject:DisplayObject):Rectangle { var bounds:Rectangle, transform:Transform, toGlobalMatrix:Matrix, currentMatrix:Matrix; transform = displayObject.transform; currentMatrix = transform.matrix; toGlobalMatrix = transform.concatenatedMatrix; toGlobalMatrix.invert(); transform.matrix = toGlobalMatrix; bounds = transform.pixelBounds.clone(); transform.matrix = currentMatrix; return bounds; } } ================================================ FILE: src/utils/display/getParents.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Get the parents of a display object as an array * @param obj Object whose parents should be retrieved * @param includeSelf If obj should be included in the returned array * @param stopAt Display object to stop getting parents at. Passing * null indicates that all parents should be included. * @return An array of the parents of the given display object. This * includes all parents unless stopAt is non-null. If stopAt is * non-null, it and its parents will not be included in the * returned array. * @author Jackson Dunstan */ public function getParents(obj:DisplayObject, includeSelf:Boolean = true, stopAt:DisplayObject = null):Array { var ret:Array = []; for (var cur:DisplayObject = includeSelf ? obj : obj.parent; cur != stopAt && cur != null; cur = cur.parent) { ret.push(cur); } return ret; } } ================================================ FILE: src/utils/display/isVisible.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Check if a display object is visible. This checks all of its * parents' visibilities. * @param obj Display object to check * @author Jackson Dunstan */ public function isVisible(obj:DisplayObject):Boolean { for (var cur:DisplayObject = obj; cur != null; cur = cur.parent) { if (!cur.visible) { return false; } } return true; } } ================================================ FILE: src/utils/display/localToLocal.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.geom.Point; /** * Translate DisplayObject container position in a new container. */ public function localToLocal(from:DisplayObject, to:DisplayObject):Point { var point:Point = new Point(); point = from.localToGlobal(point); point = to.globalToLocal(point); return point; } } ================================================ FILE: src/utils/display/moveBy.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Moves a display object by a given x and y position. * x and y parameters are optional and if either is omitted, the current position will not change. * * @author Mims Wright */ public function moveBy(displayObject:DisplayObject, x:Number = NaN, y:Number = NaN):void { if (isNaN(x)) { x = 0; } if (isNaN(y)) { y = 0; } displayObject.x += x; displayObject.y += y; } } ================================================ FILE: src/utils/display/moveTo.as ================================================ package utils.display { import flash.display.DisplayObject; /** * Moves a display object to a given x and y position. * x and y parameters are optional and if either is omitted, the current position will not change. * * @author Mims Wright */ public function moveTo(displayObject:DisplayObject, x:Number = NaN, y:Number = NaN):void { if (isNaN(x)) { x = displayObject.x; } if (isNaN(y)) { y = displayObject.y; } displayObject.x = x; displayObject.y = y; } } ================================================ FILE: src/utils/display/originalHeight.as ================================================ package utils.display { import flash.display.DisplayObject; public function originalHeight(obj:DisplayObject):Number { return obj.height / obj.scaleY; } } ================================================ FILE: src/utils/display/originalWidth.as ================================================ package utils.display { import flash.display.DisplayObject; public function originalWidth(obj:DisplayObject):Number { return obj.width / obj.scaleX; } } ================================================ FILE: src/utils/display/relativePos.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.geom.Point; public function relativePos(dO1:DisplayObject, dO2:DisplayObject):Point { var pos:Point = new Point(0, 0); pos = dO1.localToGlobal(pos); pos = dO2.globalToLocal(pos); return pos; } } ================================================ FILE: src/utils/display/removeAllChildren.as ================================================ package utils.display { import flash.display.DisplayObjectContainer; /** * Remove all children from a container and leave the bottom few * @param container Container to remove from * @param leave (optional) Number of bottom children to leave * @author Jackson Dunstan */ public function removeAllChildren(container:DisplayObjectContainer, leave:int = 0):void { while (container.numChildren > leave) { container.removeChildAt(leave); } } } ================================================ FILE: src/utils/display/removeAllChildrenByType.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * Remove all children of a specific type from a container. * * @example * var s:Sprite = new Sprite(); * s.addChild(new Shape()); * s.addChild(new Shape()); * s.addChild(new MovieClip()); * s.addChild(new Sprite()); * trace(s.numChildren); // 4 * removeAllChildrenByType(s, Shape); * trace(s.numChildren); // 2 * * * @param container Container to remove from * @param the type of children to remove * @author John Lindquist * @author Mims Wright - Rewrote 2012-10-11 */ public function removeAllChildrenByType(container:DisplayObjectContainer, type:Class):void { var i:int = 0 , l:int = container.numChildren , childrenToRemove:Array = [] , child:DisplayObject; for (;iparent property. * @return DisplayObject The child that was removed. * * @author Mims Wright */ public function removeChild(child:DisplayObject, parent:DisplayObjectContainer = null):DisplayObject { if (child) { if (!parent) { if (!child.parent) { // if parent and child.parent are null return null; } parent = child.parent; } if (parent == child.parent) { parent.removeChild(child); return child; } } return null; } } ================================================ FILE: src/utils/display/removeChildAt.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * Removes the child at the index specified in a container and returns it. * Automatically handles cases that could potentially throw errors such as the index * being out of bounds or the parent being null. * * @param parent The container to remove the child from. * @param index The index to remove. If left blank or if out of bounds, defaults to the top child. * @return DisplayObject The child that was removed. * * @author Mims Wright */ public function removeChildAt(parent:DisplayObjectContainer, index:int = -1):DisplayObject { if (parent && parent.numChildren > 0) { if (index < 0 || index > parent.numChildren) { index = parent.numChildren; } var child:DisplayObject = parent.removeChildAt(index); } return null; } } ================================================ FILE: src/utils/display/scheduleForNextFrame.as ================================================ package utils.display { import flash.display.Shape; import flash.events.Event; /** * Wait for a next frame. * Prevents high CPU state, when AVM doesn't send ENTER_FRAMES. It just simply waits until it gets one. * @param callback Function to call once when next frame is displayed * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function scheduleForNextFrame(callback:Function):void { var obj:Shape = new Shape(); obj.addEventListener(Event.ENTER_FRAME, function(ev:Event):void { obj.removeEventListener(Event.ENTER_FRAME, arguments.callee); callback(); }); } } ================================================ FILE: src/utils/display/sendBackward.as ================================================ package utils.display { import flash.display.DisplayObject; import utils.number.clamp; /** * Sends the DisplayObject back in the display list. The steps parameter can be used to jump more than one level. * @param object the DisplayObject to reorder * @param steps the number of levels send the DisplayObject backward * @return the new index of the DisplayObject */ public function sendBackward(object:DisplayObject, steps:uint = 1):int { if (!object.parent) return -1; var index:int = object.parent.getChildIndex(object) - steps; index = clamp(index, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } ================================================ FILE: src/utils/display/sendToBack.as ================================================ package utils.display { import flash.display.DisplayObject; import utils.number.clamp; /** * Sends the DisplayObject to the back of the display list. The forward parameter can be used to bring the DisplayObject forward a few levels from the back. * @param object the DisplayObject to reorder * @param forward the number of levels from the back of the display list * @return the new index of the DisplayObject */ public function sendToBack(object:DisplayObject, forward:uint = 0):int { if (!object.parent) return -1; var index:int = clamp(forward, 0, object.parent.numChildren - 1); object.parent.setChildIndex(object, index); return index; } } ================================================ FILE: src/utils/display/setProperties.as ================================================ package utils.display { import flash.display.DisplayObject; public function setProperties(children:Array, props:Object):void { var child:DisplayObject; for (var i:int = 0, l:int = children.length; i < l; i++) { child = children[i]; for (var prop:String in props) { child[prop] = props[prop]; } } } } ================================================ FILE: src/utils/display/showChildren.as ================================================ /** * Created by ${PRODUCT_NAME}. * User: jlindqui * Date: 3/9/11 * Time: 10:21 AM * To change this template use File | Settings | File Templates. */ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * * @param displayObjectContainer - the DisplayObjectContainer that you want to see all the children of * This is useful for visual debugging of hidden objects. */ public function showChildren(displayObjectContainer:DisplayObjectContainer):void { var i:int = 0; while (i < displayObjectContainer.numChildren) { var childAt:DisplayObject = displayObjectContainer.getChildAt(i); childAt.visible = true; if (childAt is DisplayObjectContainer) { showChildren(DisplayObjectContainer(childAt)); } i++; } } } ================================================ FILE: src/utils/display/stopAllTimelines.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.MovieClip; /** * Stops all timelines of the specified display object and its children. * @param displayObject The display object to loop through. */ public function stopAllTimelines(displayObject:DisplayObjectContainer):void { var numChildren:int = displayObject.numChildren; for (var i:int = 0; i < numChildren; i++) { var child:DisplayObject = displayObject.getChildAt(i); if (child is DisplayObjectContainer) { if (child is MovieClip) { MovieClip(child).stop(); } stopAllTimelines(child as DisplayObjectContainer); } } } } ================================================ FILE: src/utils/display/sumProps.as ================================================ package utils.display { public function sumProps(children:Array, prop:String):Number { var sum:Number = 0; for (var i:int = 0, l:int = children.length; i < l; i++) { sum += children[i][prop]; } return sum; } } ================================================ FILE: src/utils/display/traceChildren.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** * trace() children of the DisplayObjectContainer. * @param container DisplayObjectContainer to get children of * @param indentLevel Indentation level (default 0) * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function traceChildren(container:DisplayObjectContainer, indentLevel:int = 0):void { for(var i:int = 0; i < container.numChildren; i++) { var thisChild:DisplayObject = container.getChildAt(i); var output:String = ""; for(var j:int = 0; j < indentLevel; j++) { output += " "; } output += "+ " + thisChild.name + " = " + String(thisChild); trace(output); if(thisChild is DisplayObjectContainer) { traceChildren(DisplayObjectContainer(thisChild), indentLevel + 1); } } } } ================================================ FILE: src/utils/display/transformToFitRect.as ================================================ package utils.display { import flash.display.DisplayObject; import flash.geom.Rectangle; /** * Moves and resizes a display object to fit within a rectangle. * * @author Mims Wright */ public function transformToFitRect(displayObject:DisplayObject, rectangle:Rectangle):void { displayObject.x = rectangle.x; displayObject.y = rectangle.y; displayObject.width = rectangle.width; displayObject.height = rectangle.height; } } ================================================ FILE: src/utils/display/wait.as ================================================ package utils.display { import flash.display.Shape; import flash.events.Event; /** * Wait a given number of frames then call a callback * @param numFrames Number of frames to wait before calling the callback * @param callback Function to call once the given number of frames have passed * @author Jackson Dunstan */ public function wait(numFrames:uint, callback:Function):void { var obj:Shape = new Shape(); obj.addEventListener( Event.ENTER_FRAME, function(ev:Event):void { numFrames--; if (numFrames == 0) { obj.removeEventListener(Event.ENTER_FRAME, arguments.callee); callback(); } } ); } } ================================================ FILE: src/utils/draw/createCircleShape.as ================================================ package utils.draw { import flash.display.Graphics; import flash.display.Shape; /** * Create a shape that is a simple solid color-filled circle * * @param r Radius of the circle. * @param color Color of the circle. Default is black. * @param alpha Alpha of the circle. Default is full opacity. * @param x Initial x position * @param y Initial y position * @return The created shape * * @author Mims Wright */ public function createCircleShape (r:Number, color:uint = 0, alpha:Number = 1, x:Number = 0, y:Number = 0):Shape { var circle:Shape = new Shape(); var g:Graphics = circle.graphics; g.beginFill(color, alpha); g.drawCircle(0,0,r); g.endFill(); circle.x = x; circle.y = y; return circle; } } ================================================ FILE: src/utils/draw/createEllipseShape.as ================================================ package utils.draw { import flash.display.Graphics; import flash.display.Shape; /** * Create a shape that is a simple solid color-filled ellipse * * @param w Width of the ellipse. * @param h Height of the ellipse. * @param color Color of the ellipse. Default is black. * @param alpha Alpha of the ellipse. Default is full opacity. * @param x Initial x position * @param y Initial y position * @return The created shape * * @author Mims Wright */ public function createEllipseShape(w:Number, h:Number = 0, color:uint = 0, alpha:Number = 1, x:Number = 0, y:Number = 0):Shape { if (h <= 0) { h = w; } var ellipse:Shape = new Shape(); var g:Graphics = ellipse.graphics; g.beginFill(color, alpha); g.drawEllipse(0,0,w,h); g.endFill(); ellipse.x = x; ellipse.y = y; return ellipse; } } ================================================ FILE: src/utils/draw/createRectangleShape.as ================================================ package utils.draw { import flash.display.Graphics; import flash.display.Shape; /** * Create a shape that is a simple solid color-filled rectangle * * @param width Width of the rectangle * @param height Height of the rectangle * @param color Color of the rectangle. Default is black. * @param alpha Alpha of the rectangle. Default is full opacity. * @param x Initial x position * @param y Initial y position * @return The created shape * @author Jackson Dunstan, modified by Mims Wright */ public function createRectangleShape(width:uint, height:uint, color:uint = 0, alpha:Number = 1, x:Number = 0, y:Number = 0):Shape { var rect:Shape = new Shape(); var g:Graphics = rect.graphics; g.beginFill(color, alpha); g.drawRect(0, 0, width, height); g.endFill(); rect.x = x; rect.y = y; return rect; } } ================================================ FILE: src/utils/draw/drawRoundRect.as ================================================ package utils.draw { import flash.display.Graphics; /** Draws a rounded rectangle. Act identically to Graphics.drawRoundRect but allows the specification of which corners are rounded. @param graphics: The location where drawing should occur. @param x: The horizontal position of the rectangle. @param y: The vertical position of the rectangle. @param width: The width of the rectangle. @param height: The height of the rectangle. @param ellipseWidth: The width in pixels of the ellipse used to draw the rounded corners. @param ellipseHeight: The height in pixels of the ellipse used to draw the rounded corners. @param topLeft: Specifies if the top left corner of the rectangle should be rounded true, or should be square false. @param topRight:Specifies if the top right corner of the rectangle should be rounded true, or should be square false. @param bottomRight: Specifies if the bottom right corner of the rectangle should be rounded true, or should be square false. @param bottomLeft: Specifies if the bottom left corner of the rectangle should be rounded true, or should be square false. @usage this.graphics.beginFill(0xFF00FF); DrawUtil.drawRoundRect(this.graphics, 10, 10, 200, 200, 50, 50, true, false, true, false); this.graphics.endFill(); */ public function drawRoundRect(graphics:Graphics, x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number, ellipseHeight:Number, topLeft:Boolean = true, topRight:Boolean = true, bottomRight:Boolean = true, bottomLeft:Boolean = true):void { const radiusWidth:Number = ellipseWidth * 0.5; const radiusHeight:Number = ellipseHeight * 0.5; if (topLeft) graphics.moveTo(x + radiusWidth, y); else graphics.moveTo(x, y); if (topRight) { graphics.lineTo(x + width - radiusWidth, y); graphics.curveTo(x + width, y, x + width, y + radiusHeight); } else graphics.lineTo(x + width, y); if (bottomRight) { graphics.lineTo(x + width, y + height - radiusHeight); graphics.curveTo(x + width, y + height, x + width - radiusWidth, y + height); } else graphics.lineTo(x + width, y + height); if (bottomLeft) { graphics.lineTo(x + radiusWidth, y + height); graphics.curveTo(x, y + height, x, y + height - radiusHeight); } else graphics.lineTo(x, y + height); if (topLeft) { graphics.lineTo(x, y + radiusHeight); graphics.curveTo(x, y, x + radiusWidth, y); } else graphics.lineTo(x, y); } } ================================================ FILE: src/utils/draw/drawWedge.as ================================================ package utils.draw { import flash.display.Graphics; import utils.geom.Ellipse; /** Draws a circular wedge. @param graphics The location where drawing should occur. @param ellipse An Ellipse object that contains the size and position of the shape. @param startAngle The starting angle of wedge in degrees. @param arc The sweep of the wedge in degrees. @usage this.graphics.beginFill(0xFF00FF); DrawUtil.drawWedge(this.graphics, new Ellipse(0, 0, 300, 200), 0, 300); this.graphics.endFill(); */ public function drawWedge(graphics:Graphics, ellipse:Ellipse, startAngle:Number, arc:Number):void { if (Math.abs(arc) >= 360) { graphics.drawEllipse(ellipse.x, ellipse.y, ellipse.width, ellipse.height); return; } startAngle += 90; var radius:Number = ellipse.width * .5; var yRadius:Number = ellipse.height * .5; var x:Number = ellipse.x + radius; var y:Number = ellipse.y + yRadius; var segs:Number = Math.ceil(Math.abs(arc) / 45); var segAngle:Number = -arc / segs; var theta:Number = -(segAngle / 180) * Math.PI; var angle:Number = -(startAngle / 180) * Math.PI; var ax:Number = x + Math.cos(startAngle / 180 * Math.PI) * radius; var ay:Number = y + Math.sin(-startAngle / 180 * Math.PI) * yRadius; var angleMid:Number; graphics.moveTo(x, y); graphics.lineTo(ax, ay); var i:Number = -1; while (++i < segs) { angle += theta; angleMid = angle - (theta * .5); graphics.curveTo(x + Math.cos(angleMid) * (radius / Math.cos(theta * .5)), y + Math.sin(angleMid) * (yRadius / Math.cos(theta * .5)), x + Math.cos(angle) * radius, y + Math.sin(angle) * yRadius); } graphics.lineTo(x, y); } } ================================================ FILE: src/utils/error/getStackTrace.as ================================================ package utils.error { /** * Get a stack trace * @return A stack trace * @author Jackson Dunstan */ public function getStackTrace():String { return new Error().getStackTrace(); } } ================================================ FILE: src/utils/frame/addFrameScript.as ================================================ package utils.frame { import flash.display.MovieClip; /** Calls a specified method when a specific frame is reached in a MovieClip timeline. @param target: The MovieClip that contains the frame. @param frame: The frame to be notified when reached. Can either be a frame number (uint), or the frame label (String). @param notify: The function that will be called when the frame is reached. @return Returns true if the frame was found; otherwise false. @throws ArguementTypeError if you pass a type other than a String or uint to parameter frame. */ public function addFrameScript(target:MovieClip, frame:*, notify:Function):Boolean { if (frame is String) frame = getFrameNumberForLabel(target, frame); else if (!(frame is uint)) throw new Error('frame'); if (frame == -1 || frame == 0 || frame > target.totalFrames) return false; target.addFrameScript(frame - 1, notify); return true; } } ================================================ FILE: src/utils/frame/getFrameNumberForLabel.as ================================================ package utils.frame { import flash.display.MovieClip; /** Determines the frame number for the specified label. @param target: The MovieClip to search for the frame label in. @param label: The name of the frame label. @return The frame number of the label or -1 if the frame label was not found. */ public function getFrameNumberForLabel(target:MovieClip, label:String):int { var labels:Array = target.currentLabels; var l:int = labels.length; while (l--) if (labels[l].name == label) return labels[l].frame; return -1; } } ================================================ FILE: src/utils/frame/removeFrameScript.as ================================================ package utils.frame { import flash.display.MovieClip; /** Removes a frame from triggering/calling a function when reached. @param target: The MovieClip that contains the frame. @param frame: The frame to remove notification from. Can either be a frame number (uint), or the frame label (String). @throws ArguementTypeError if you pass a type other than a String or uint to parameter frame. */ public function removeFrameScript(target:MovieClip, frame:*):void { if (frame is String) frame = getFrameNumberForLabel(target, frame); else if (!(frame is uint)) throw new Error('frame'); if (frame == -1 || frame == 0 || frame > target.totalFrames) return; target.addFrameScript(frame - 1, null); } } ================================================ FILE: src/utils/fullscreen/toggleFullScreen.as ================================================ package utils.fullscreen { import flash.display.Stage; import flash.display.StageDisplayState; /** * Toggles the stage display state between normal and fullscreen. * * @param stage A reference to the stage object. * @returns String The new state. * * @author Mims Wright */ public function toggleFullScreen(stage:Stage):String { var state:String; if (stage.displayState == StageDisplayState.FULL_SCREEN) { state = StageDisplayState.NORMAL; } else { state = StageDisplayState.FULL_SCREEN; } stage.displayState = state; return state; } } ================================================ FILE: src/utils/garbageCollection/gc.as ================================================ package utils.garbageCollection { import flash.net.LocalConnection; // TODO: Needs documentation public function gc():void { try { new LocalConnection().connect("gc"); new LocalConnection().connect("gc"); } catch (e:Error) { var shouldTouchHere:Boolean = true; } } } ================================================ FILE: src/utils/geom/Direction.as ================================================ package utils.geom { /** * An enumeration of the four cardinal directions. * Mirrors the directions in Side. * * Make a hybrid direction using '|', e.g. var NW:int = NORTH | WEST; * * @author Mims Wright * * @see utils.geom.Side */ public class Direction { public static const UP:int = 1; public static const DOWN:int = 2; public static const LEFT:int = 4; public static const RIGHT:int = 8; public static const NORTH:int = UP; public static const SOUTH:int = DOWN; public static const WEST:int = LEFT; public static const EAST:int = RIGHT; public static const NONE:int = 0; public static const ALL:int = UP | DOWN | LEFT | RIGHT; } } ================================================ FILE: src/utils/geom/Ellipse.as ================================================ /* CASA Lib for ActionScript 3.0 Copyright (c) 2010, Aaron Clinger & Contributors of CASA Lib All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the CASA Lib nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package utils.geom { import flash.geom.Point; /** Stores position and size of an ellipse (circle or oval). @author Aaron Clinger @author Mike Creighton @version 04/13/08 */ public class Ellipse { protected var _x:Number; protected var _y:Number; protected var _width:Number; protected var _height:Number; /** Creates new Ellipse object. @param x: The horizontal position of the ellipse. @param y: The vertical position of the ellipse. @param width: Width of the ellipse at its widest horizontal point. @param height: Height of the ellipse at its tallest point. */ public function Ellipse(x:Number, y:Number, width:Number, height:Number) { this.x = x; this.y = y; this.width = width; this.height = height; } /** The horizontal coordinate of the point. */ public function get x():Number { return this._x; } public function set x(xPos:Number):void { this._x = xPos; } /** The vertical coordinate of the point. */ public function get y():Number { return this._y; } public function set y(yPos:Number):void { this._y = yPos; } /** The width of the ellipse. */ public function get width():Number { return this._width; } public function set width(width:Number):void { this._width = width; } /** The height of the rectangle. */ public function get height():Number { return this._height; } public function set height(height:Number):void { this._height = height; } /** The center of the ellipse. */ public function get center():Point { return new Point(this.x + this.width * 0.5, this.y + this.height * 0.5); } public function set center(c:Point):void { this.x = c.x - this.width * 0.5; this.y = c.y - this.height * 0.5; } /** The size of the ellipse, expressed as a Point object with the values of the width and height properties. */ public function get size():Point { return new Point(this.width, this.height); } /** The circumference of the ellipse. @usageNote Calculating the circumference of an ellipse is difficult; this is an approximation but should be fine for most cases. */ public function get perimeter():Number { return (Math.sqrt(.5 * (Math.pow(this.width, 2) + Math.pow(this.height, 2))) * Math.PI * 2) * 0.5; } /** The area of the ellipse. */ public function get area():Number { return Math.PI * (this.width * 0.5) * (this.height * 0.5); } /** Finds the x, y position of the degree along the circumference of the ellipse. @param degree: Number representing a degree on the ellipse. @return A Point object. @usageNote degree can be over 360 or even negitive numbers; minding 0 = 360 = 720, 540 = 180, -90 = 270, etc. */ public function getPointOfDegree(degree:Number):Point { var radian:Number = (degree - 90) * (Math.PI / 180); var xRadius:Number = this.width * 0.5; var yRadius:Number = this.height * 0.5; return new Point(this.x + xRadius + Math.cos(radian) * xRadius, this.y + yRadius + Math.sin(radian) * yRadius); } /** Finds if point is contained inside the ellipse perimeter. @param point: A Point object. @return Returns true if shape's area contains point; otherwise false. */ public function containsPoint(point:Point):Boolean { var xRadius:Number = this.width * 0.5; var yRadius:Number = this.height * 0.5; var xTar:Number = point.x - this.x - xRadius; var yTar:Number = point.y - this.y - yRadius; return Math.pow(xTar / xRadius, 2) + Math.pow(yTar / yRadius, 2) <= 1; } /** Determines if the Ellipse specified in the ellipse parameter is equal to this Ellipse object. @param ellipse: An Ellipse object. @return Returns true if object is equal to this Ellipse; otherwise false. */ public function equals(ellipse:Ellipse):Boolean { return this.x == ellipse.x && this.y == ellipse.y && this.width == ellipse.width && this.height == ellipse.height; } /** @return A new Ellipse object with the same values as this Ellipse. */ public function clone():Ellipse { return new Ellipse(this.x, this.y, this.width, this.height); } } } ================================================ FILE: src/utils/geom/Point3d.as ================================================ /* CASA Lib for ActionScript 3.0 Copyright (c) 2010, Aaron Clinger & Contributors of CASA Lib All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the CASA Lib nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package utils.geom { import utils.math.Percent; import utils.number.interpolate; /** Stores location of a point in a three-dimensional coordinate system, where x represents the horizontal axis, y represents the vertical axis, z represents the axis that is vertically perpendicular to the x/y axis or depth. @author Aaron Clinger @author David Bliss @author Mike Creighton @version 09/23/08 */ public class Point3d { protected var _x:Number; protected var _y:Number; protected var _z:Number; /** Creates a new Point3d. @param x: The horizontal coordinate of the point. @param y: The vertical coordinate of the point. @param z: The depth coordinate of the point. */ public function Point3d(x:Number = 0, y:Number = 0, z:Number = 0) { this.x = x; this.y = y; this.z = z; } /** The horizontal coordinate of the point. */ public function get x():Number { return this._x; } public function set x(position:Number):void { this._x = position; } /** The vertical coordinate of the point. */ public function get y():Number { return this._y; } public function set y(position:Number):void { this._y = position; } /** The depth coordinate of the point. */ public function get z():Number { return this._z; } public function set z(position:Number):void { this._z = position; } /** Adds the coordinates of another Point3d to the coordinates of this point to create a new Point3d. @param point: The point to be added. @return The new point. */ public function add(point:Point3d):Point3d { return new Point3d(this.x + point.x, this.y + point.y, this.z + point.z); } /** Subtracts the coordinates of another Point3d from the coordinates of this point to create a new Point3d. @param point: The point to be subtracted. @return The new point. */ public function subtract(point:Point3d):Point3d { return new Point3d(this.x - point.x, this.y - point.y, this.z - point.z); } /** Offsets the Point object by the specified amount. @param xOffset: The amount by which to offset the horizontal coordinate. @param yOffset: The amount by which to offset the vertical coordinate. @param zOffset: The amount by which to offset the depth coordinate. */ public function offset(xOffset:Number, yOffset:Number, zOffset:Number):void { this.x += xOffset; this.y += yOffset; this.z += zOffset; } /** Determines if the point specified in the point parameter is equal to this point object. @param point: A Point3d object. @return Returns true if shape's location is identical; otherwise false. */ public function equals(point:Point3d):Boolean { return this.x == point.x && this.y == point.y && this.z == point.z; } /** Creates a copy of this Point3d object. @return A new Point3d with the same values as this point. */ public function clone():Point3d { return new Point3d(this.x, this.y, this.z); } /** Determines the distance between the first and second points in 3D space. @param firstPoint: The first Point3d. @param secondPoint: The second Point3d. @return Distance between the two points. */ public static function distance(firstPoint:Point3d, secondPoint:Point3d):Number { var x:Number = secondPoint.x - firstPoint.x; var y:Number = secondPoint.y - firstPoint.y; var z:Number = secondPoint.z - firstPoint.z; return Math.sqrt(x * x + y * y + z * z); } /** Determines a point between two specified points. @param firstPoint: The first Point3d. @param secondPoint: The second Point3d. @param amount: The level of interpolation between the two points. If 0%, firstPoint is returned; if 100%, secondPoint is returned. @return The new, interpolated point. */ public static function interpolate(firstPoint:Point3d, secondPoint:Point3d, amount:Percent):Point3d { var x:Number = utils.number.interpolate(amount, firstPoint.x, secondPoint.x); var y:Number = utils.number.interpolate(amount, firstPoint.y, secondPoint.y); var z:Number = utils.number.interpolate(amount, firstPoint.z, secondPoint.z); return new Point3d(x, y, z); } } } ================================================ FILE: src/utils/geom/Side.as ================================================ package utils.geom { /** * An enumeration of the four sides of a rectangle. * Useful for working with tile engines, creating borders, etc. */ public class Side { public static const TOP:int = 1; public static const BOTTOM:int = 2; public static const LEFT:int = 4; public static const RIGHT:int = 8; public static const NONE:int = 0; public static const ALL:int = TOP | BOTTOM | LEFT | RIGHT; } } ================================================ FILE: src/utils/geom/angle.as ================================================ package utils.geom { import flash.geom.Point; /** Determines the angle/degree between the first and second point. @param first: The first Point. @param second: The second Point. @return The degree between the two points. */ public function angle(first:Point, second:Point):Number { return Math.atan2(second.y - first.y, second.x - first.x) / (Math.PI / 180); } } ================================================ FILE: src/utils/geom/cartesianToPolarCoordinates.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 11:56:07 AM */ package utils.geom { /** Converts cartesian coordinates to polar coordinates. @param x: The x value of the cartesian point. @param y: The y value of the cartesian point. @return Returns an array containing polar coordinates r and q. */ public function cartesianToPolarCoordinates(x:Number, y:Number) : Array { var r:Number = Math.sqrt(Math.pow(x,2) + Math.pow(y,2)); var q:Number = Math.atan(y/x) * (180/Math.PI); return [r, q]; } } ================================================ FILE: src/utils/geom/getRectangleCenter.as ================================================ package utils.geom { import flash.geom.Point; import flash.geom.Rectangle; //TODO: Author? /** * Calculates center Point of a Rectangle. * * @param value Rectangle to determine center Point of */ public function getRectangleCenter(value:Rectangle):Point { return new Point(value.x + (value.width / 2), value.y + (value.height / 2)); } } ================================================ FILE: src/utils/geom/getRectanglePerimeter.as ================================================ package utils.geom { import flash.geom.Rectangle; /** Calculates the perimeter of a rectangle. @param rect: Rectangle to determine the perimeter of. */ public function getRectanglePerimeter(rect:Rectangle):Number { return rect.width * 2 + rect.height * 2; } } ================================================ FILE: src/utils/geom/polarToCartesianCoordinates.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 1:00:51 PM */ package utils.geom { import flash.geom.Point; /** * Converts polar coordinates to cartesian coordinates. * @param r The r value of the polar coordinate. * @param q The q value of the polar coordinate in degrees. */ public function polarToCartesianCoordinates(r:Number, q:Number) : Point { var asRadian:Number = q * Math.PI/180; var x:Number = r * Math.cos(asRadian); var y:Number = r * Math.sin(asRadian); return new Point(x,y); } } ================================================ FILE: src/utils/geom/randomPoint.as ================================================ package utils.geom { import flash.geom.Point; import utils.number.randomIntegerWithinRange; /** * Returns a randomly generated point (containing int values) * * @author Mims H. Wright */ public function randomPoint(xLow:int, xHigh:int, yLow:int, yHigh:int):Point { return new Point( randomIntegerWithinRange(xLow, xHigh), randomIntegerWithinRange(yLow, yHigh) ); } } ================================================ FILE: src/utils/geom/reverseRectangle.as ================================================ package utils.geom { import flash.geom.Rectangle; // TODO: What's the point of this? Does this even work? Can a rect have a negative width or height? // TODO: Author? /** * Reverse a rectangle. * * @param value Source rectangle * @return Reversed rectangle */ public function reverseRectangle(value:Rectangle):Rectangle { return new Rectangle(value.left, value.top, -value.width, -value.height); } } ================================================ FILE: src/utils/geom/rotatePoint.as ================================================ package utils.geom { import flash.geom.Point; import utils.conversion.degreesToRadians; /** Rotates a Point around another Point by the specified angle. @param point: The Point to rotate. @param centerPoint: The Point to rotate this Point around. @param angle: The angle (in degrees) to rotate this point. */ public function rotatePoint(point:Point, centerPoint:Point, angle:Number):void { var radians:Number = degreesToRadians(angle); var baseX:Number = point.x - centerPoint.x; var baseY:Number = point.y - centerPoint.y; point.x = (Math.cos(radians) * baseX) - (Math.sin(radians) * baseY) + centerPoint.x; point.y = (Math.sin(radians) * baseX) + (Math.cos(radians) * baseY) + centerPoint.y; } } ================================================ FILE: src/utils/geom/roundPoint.as ================================================ package utils.geom { import flash.geom.Point; // todo: author? /** * Returns a new point with x and y values rounded down to the nearest int. * * @param value Source Point to be rounded. * @return Point A new point with x and y rounded down to an int. */ public function roundPoint(point:Point):Point { return new Point(int(point.x), int(point.y)); } } ================================================ FILE: src/utils/geom/simplifyAngle.as ================================================ package utils.geom { /** * Simplifies the supplied angle to its simplest representation. * Example code: *
	 *          var simpAngle:Number = simplifyAngle(725); // returns 5
	 *          var simpAngle2:Number = simplifyAngle(-725); // returns -5
	 *      
* @param angle Angle to simplify in degrees * @return Supplied angle simplified * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function simplifyAngle(angle:Number):Number { var _rotations:Number = Math.floor(angle / 360); return (angle >= 0) ? angle - (360 * _rotations) : angle + (360 * _rotations); } } ================================================ FILE: src/utils/geom/trimAngle.as ================================================ package utils.geom { /** * Trims the supplied angle to its 0..360 representation. * Example code: *
	 *          var simpAngle:Number = trimAngle(725); // returns 5
	 *      
* @param value Angle to trim * @return Supplied angle trimmed * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function trimAngle(value:Number):Number { var a:Number = value; while(a < 0) a += 360; while(a > 360) a -= 360; return a; } } ================================================ FILE: src/utils/html/a.as ================================================ package utils.html { /** * Generate an A HREF tag. */ public function a(href:String, text:String, styleClass:String = null):String { return '" + text + ""; } } ================================================ FILE: src/utils/html/br.as ================================================ package utils.html { /** * Inset a BR with optional newline. */ public function br(addNewline:Boolean = false):String { return "
" + (addNewline ? "\n" : ""); } } ================================================ FILE: src/utils/html/entities.as ================================================ package utils.html { import flash.utils.Dictionary; public const entities:Dictionary = new Dictionary(); entities["\""] = """; entities["'"] = "'"; entities["&"] = "&"; entities["<"] = "<"; entities[">"] = ">"; entities[" "] = " "; entities[""] = "¡"; entities[""] = "¤"; entities[""] = "¢"; entities[""] = "£"; entities[""] = "¥"; entities[""] = "¦"; entities[""] = "§"; entities[""] = "¨"; entities[""] = "©"; entities[""] = "ª"; entities[""] = "«"; entities[""] = "¬"; entities[""] = "­"; entities[""] = "®"; entities[""] = "™"; entities[""] = "¯"; entities[""] = "°"; entities[""] = "±"; entities[""] = "²"; entities[""] = "³"; entities[""] = "´"; entities[""] = "µ"; entities[""] = "¶"; entities[""] = "·"; entities[""] = "¸"; entities[""] = "¹"; entities[""] = "º"; entities[""] = "»"; entities[""] = "¼"; entities[""] = "½"; entities[""] = "¾"; entities[""] = "¿"; entities[""] = "×"; entities[""] = "÷"; entities[""] = "À"; entities[""] = "Á"; entities[""] = "Â"; entities[""] = "Ã"; entities[""] = "Ä"; entities[""] = "Å"; entities[""] = "Æ"; entities[""] = "Ç"; entities[""] = "È"; entities[""] = "É"; entities[""] = "Ê"; entities[""] = "Ë"; entities[""] = "Ì"; entities[""] = "Í"; entities[""] = "Î"; entities[""] = "Ï"; entities[""] = "Ð"; entities[""] = "Ñ"; entities[""] = "Ò"; entities[""] = "Ó"; entities[""] = "Ô"; entities[""] = "Õ"; entities[""] = "Ö"; entities[""] = "Ø"; entities[""] = "Ù"; entities[""] = "Ú"; entities[""] = "Û"; entities[""] = "Ü"; entities[""] = "Þ"; entities[""] = "ß"; entities[""] = "à"; entities[""] = "á"; entities[""] = "â"; entities[""] = "ã"; entities[""] = "ä"; entities[""] = "å"; entities[""] = "æ"; entities[""] = "é"; entities[""] = "ë"; entities[""] = "ì"; entities[""] = "í"; entities[""] = "î"; entities[""] = "ï"; entities[""] = "ð"; entities[""] = "ñ"; entities[""] = "ò"; entities[""] = "ó"; entities[""] = "ô"; entities[""] = "õ"; entities[""] = "ö"; entities[""] = "ø"; entities[""] = "ú"; entities[""] = "û"; entities[""] = "ü"; entities[""] = "ý"; entities[""] = "þ"; entities[""] = "ÿ"; entities[""] = "Œ"; entities[""] = "œ"; entities[""] = "Š"; entities[""] = "š"; entities[""] = "Ÿ"; entities[""] = "ˆ"; entities[""] = "˜"; entities[""] = "–"; entities[""] = "—"; entities[""] = "‘"; entities[""] = "’"; entities[""] = "‚"; entities[""] = "“"; entities[""] = "”"; entities[""] = "„"; entities[""] = "†"; entities[""] = "‡"; entities[""] = "…"; entities[""] = "‰"; entities[""] = "‹"; entities[""] = "›"; entities[""] = "€"; } ================================================ FILE: src/utils/html/img.as ================================================ package utils.html { /** * Generate an IMG tag. */ public function img(src:String, alt:String = "image", width:int = 0, height:int = 0):String { return '' + alt + ' 0) ? ' width="' + width.toString() + '"' : "") + ((height > 0) ? ' height="' + height.toString() + '"' : "") + '/>'; } } ================================================ FILE: src/utils/html/p.as ================================================ package utils.html { /** * Generate a P tag. */ public function p(text:String, styleClass:String = null):String { return styledTag("p", text, styleClass); } } ================================================ FILE: src/utils/html/span.as ================================================ package utils.html { /** * Generate a SPAN tag. */ public function span(text:String, styleClass:String = null):String { return styledTag("span", text, styleClass); } } ================================================ FILE: src/utils/html/styledTag.as ================================================ package utils.html { /** * Generate a styled tag. */ [ExludeClass] public function styledTag(tagName:String, text:String, styleClass:String):String { return '<' + tagName + ((styleClass) ? ' class="' + styleClass + '"' : "") + '>' + text + ''; } } ================================================ FILE: src/utils/js/callJSFunction.as ================================================ package utils.js { import flash.external.ExternalInterface; /** * Call a JS function. * @param func Name of the function to be called * @param arg1 Argument 1 * @param arg2 Argument 2 * @param arg3 Argument 3 * @param arg4 Argument 4 * @throws Error if empty function name supplied * @throws Error if SecurityError occurred * @throws Error if Error occurred * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function callJSFunction(func:String, arg1:* = null, arg2:* = null, arg3:* = null, arg4:* = null):void { if(func == "") { throw new Error("A valid function argument must be supplied"); } // track avea if a type is supplied if(ExternalInterface.available) { try { ExternalInterface.call(func, arg1, arg2, arg3, arg4); } catch(error:SecurityError) { throw new Error(func + " request failed. A SecurityError occurred: " + error.message + "\n"); } catch (error:Error) { throw new Error(func + " request failed. An Error occurred: " + error.message + "\n"); } } else { throw new Error(func + " request Failed. External interface is not available for this container. If you're trying to use it locally, try using it through an HTTP address."); } } } ================================================ FILE: src/utils/library/getBitmapDataFromLibrary.as ================================================ package utils.library { import flash.display.BitmapData; /** * Get an instance of a BitmapData from the clip library * @param className Name of the BitmapData's class (aka. linkage ID) * @return An instance of the BitmapData with the given name or null if * the class cannot be found or the BitmapData cannot be * instantiated * @author Jackson Dunstan */ public function getBitmapDataFromLibrary(className:String):BitmapData { var clazz:Class = getClassFromLibrary(className); if(!clazz) { return null; } try { // Need to pass a width and height, but they are ignored return new clazz(0, 0); } catch (err:ArgumentError) { return null; } return null; } } ================================================ FILE: src/utils/library/getClassFromLibrary.as ================================================ package utils.library { /** * Get a class from the clip library * @param className Name of the class to get * @return The class with the given name or null if it cannot be found * @author Jackson Dunstan */ public function getClassFromLibrary(className:String):Class { try { return Class(this.loaderInfo.applicationDomain.getDefinition(className)); } catch (refErr:ReferenceError) { return null; } catch (typeErr:TypeError) { return null; } return null; } } ================================================ FILE: src/utils/library/getClipFromLibrary.as ================================================ package utils.library { import flash.display.MovieClip; /** * Get an instance of a clip from the clip library * @param className Name of the clip class (aka. linkage ID) * @return An instance of the clip with the given name or null if the * class cannot be found or the clip cannot be instantiated * @author Jackson Dunstan */ public function getClipFromLibrary(className:String):MovieClip { var clazz:Class = getClassFromLibrary(className); if(!clazz) { return null; } try { return new clazz(); } catch (err:ArgumentError) { return null; } return null; } } ================================================ FILE: src/utils/load/calculateBps.as ================================================ package utils.load { import utils.conversion.millisecondsToSeconds; /** Calculates the load speed in bytes per second (Bps). @param bytesLoaded: Number of bytes that have loaded between startTime and elapsedTime. @param startTime: Time in milliseconds when the load started. @param elapsedTime: Time in milliseconds since the load started or time when load completed. @return Bytes per second. @usageNote This method returns BYTES per second, not bits per second. */ public function calculateBps(bytesLoaded:uint, startTime:uint, elapsedTime:uint):int { return Math.max(0, (bytesLoaded / millisecondsToSeconds(elapsedTime - startTime))); } } ================================================ FILE: src/utils/load/calculateBufferPercent.as ================================================ package utils.load { import utils.math.Percent; import utils.number.clamp; /** Calculates the percent the video has buffered. @param bytesLoaded: Number of bytes that have loaded between startTime and elapsedTime. @param bytesTotal: Number of bytes total to be loaded. @param startTime: Time in milliseconds when the load started. @param elapsedTime: The current time in milliseconds or time when load completed. @param lengthInMilliseconds: The total duration/length of the video in milliseconds. @return The percent buffered. */ public function calculateBufferPercent(bytesLoaded:uint, bytesTotal:uint, startTime:uint, elapsedTime:uint, lengthInMilliseconds:uint):Percent { var totalWait:Number = bytesTotal / (bytesLoaded / (elapsedTime - startTime)) - lengthInMilliseconds; var millisecondsRemaining:uint = calculateMillisecondsUntilBuffered(bytesLoaded, bytesTotal, startTime, elapsedTime, lengthInMilliseconds); return (totalWait == Number.POSITIVE_INFINITY) ? new Percent(0) : new Percent(clamp(1 - millisecondsRemaining / totalWait, 0, 1)); } } ================================================ FILE: src/utils/load/calculateKBps.as ================================================ package utils.load { import utils.conversion.bytesToKilobytes; /** Calculates the load speed in kilobytes per second (kBps). @param bytesLoaded: Number of bytes that have loaded between startTime and elapsedTime. @param startTime: Time in milliseconds when the load started. @param elapsedTime: Time in milliseconds since the load started or time when load completed. @return Kilobytes per second. @usageNote This method returns kiloBYTES per second, not kilobits per second. */ public function calculateKBps(bytesLoaded:uint, startTime:uint, elapsedTime:uint):Number { return bytesToKilobytes(calculateBps(bytesLoaded, startTime, elapsedTime)); } } ================================================ FILE: src/utils/load/calculateMillisecondsUntilBuffered.as ================================================ package utils.load { /** Calculates the remaining time until the video is buffered. @param bytesLoaded: Number of bytes that have loaded between startTime and elapsedTime. @param bytesTotal: Number of bytes total to be loaded. @param startTime: Time in milliseconds when the load started. @param elapsedTime: The current time in milliseconds or time when load completed. @param lengthInMilliseconds: The total duration/length of the video in milliseconds. @return The amount millisecond that remain before the video is buffered. */ public function calculateMillisecondsUntilBuffered(bytesLoaded:uint, bytesTotal:uint, startTime:uint, elapsedTime:uint, lengthInMilliseconds:uint):uint { return Math.max(Math.ceil((bytesTotal - bytesLoaded) / (bytesLoaded / (elapsedTime - startTime))) - lengthInMilliseconds, 0); } } ================================================ FILE: src/utils/load/checkDomain.as ================================================ package utils.load { import flash.display.LoaderInfo; import flash.errors.IOError; import flash.external.ExternalInterface; /** * Ensures that the domain that loaded the app is from an approved list of domains. * * @example * var approvedDomains:Array = [".*\.example\.com", ".*\.foo\.com", ".*\.me\.mysite\.com"]; * try { * var testPassed:Boolean = checkDomain(this.loaderInfo, approvedDomains); * } catch (e:IOError) { * // Domain check didn't pass. Stop the application. * } * // If there wasn't an error, continue the application. * * * @throws IOError If the domain isn't allowed. * * @param loaderInfo The LoaderInfo object for the main app. * This would probably be your application's main class' loaderInfo. * @param allowedDomains An array of approved domains as RegExp strings. e.g. ".*\.example.com" * @return Boolean True if domain check passed. * * @author Mims H. Wright */ public function checkDomain(loaderInfo:LoaderInfo, approvedDomains:Array):Boolean { var url:String; if (ExternalInterface.available) { url = ExternalInterface.call("window.location.href.toString"); } else { url = loaderInfo.loaderURL; } var allowedDomainsString:String = approvedDomains.join("|"); var allowedPattern:String = "(^"+allowedDomainsString+"/?)"; var domainCheck:RegExp = new RegExp(allowedPattern,"i"); var domainCheckResult:Object = domainCheck.exec(url); if (domainCheckResult == null) { // domain check failed, abort application throw new IOError("You are not permitted to load this file from this location " + url); return false; } else { // domain okay, proceed return true; } } } ================================================ FILE: src/utils/location/getDomain.as ================================================ package utils.location { import flash.display.DisplayObject; /** * Detects MovieClip domain location. * Function does not return folder path or file name. The method also treats "www" and sans "www" as the same; if "www" is present method does not return it. * Example code: *
	 *          trace(getDomain(_root));
	 *      
* @param location MovieClip to get location of * @return Full domain (including sub-domains) of MovieClip location * @author Aaron Clinger * @author Shane McCartney * @author David Nelson * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function getDomain(location:DisplayObject):String { var baseUrl:String = location.loaderInfo.url.split("://")[1].split("/")[0]; return (baseUrl.substr(0, 4) == "www.") ? baseUrl.substr(4) : baseUrl; } } ================================================ FILE: src/utils/location/getLocationName.as ================================================ package utils.location { import flash.external.ExternalInterface; import utils.capabilities.isStandAlone; /** * Return current location name. * @return Current location name * @author Aaron Clinger * @author Shane McCartney * @author David Nelson * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function getLocationName():String { var out:String; var browserAgent:String; if(isStandAlone()) { out = locationNames.STANDALONE_PLAYER; } else { if(ExternalInterface.available) { // uses external interface to reach out to browser and grab browser useragent info. browserAgent = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); // determines brand of browser using a find index. If not found indexOf returns (-1). // noinspection IfStatementWithTooManyBranchesJS if(browserAgent != null && browserAgent.indexOf("Firefox") >= 0) { out = locationNames.BROWSER_FIREFOX; } else if(browserAgent != null && browserAgent.indexOf("Safari") >= 0) { out = locationNames.BROWSER_SAFARI; } else if(browserAgent != null && browserAgent.indexOf("MSIE") >= 0) { out = locationNames.BROWSER_IE; } else if(browserAgent != null && browserAgent.indexOf("Opera") >= 0) { out = locationNames.BROWSER_OPERA; } else { out = locationNames.BROWSER_UNDEFINED; } } else { // standalone player out = locationNames.BROWSER_UNDEFINED; } } return out; } } ================================================ FILE: src/utils/location/isDomain.as ================================================ package utils.location { import flash.display.DisplayObject; /** * Detects if MovieClip embed location matches passed domain. * Check for domain: *
	 *          trace(isDomain(_root, "google.com"));
	 *          trace(isDomain(_root, "bbc.co.uk"));
	 *      
* You can even check for subdomains: *
	 *          trace(isDomain(_root, "subdomain.aaronclinger.com"))
	 *      
* @param location MovieClip to compare location of * @param domain Web domain * @return true if file's embed location matched passed domain * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function isDomain(location:DisplayObject, domain:String):Boolean { return getDomain(location).slice(-domain.length) == domain; } } ================================================ FILE: src/utils/location/locationNames.as ================================================ package utils.location { public class locationNames { /** Firefox */ public static const BROWSER_FIREFOX:String = "browserFirefox"; /** Safari */ public static const BROWSER_SAFARI:String = "browserSafari"; /** Internet Explorer */ public static const BROWSER_IE:String = "browserIE"; /** Opera */ public static const BROWSER_OPERA:String = "browserOpera"; /** Undefined browser */ public static const BROWSER_UNDEFINED:String = "browserUndefined"; /** Standalone player */ public static const STANDALONE_PLAYER:String = "standalonePlayer"; } } ================================================ FILE: src/utils/location/openURL.as ================================================ package utils.location { import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; import utils.capabilities.isIDE; /** * Simlifies navigateToURL by allowing you to either use a String or an URLRequest * reference to the URL. This method also helps prevent pop-up blocking by trying to use * openWindow() before calling navigateToURL. * @param request A String or an URLRequest reference to the URL you wish to open/navigate to * @param window Browser window or HTML frame in which to display the URL indicated by the request parameter * @throws Error if you pass a value type other than a String or URLRequest to parameter request. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function openURL(request:*, window:String = "_self" /* windowNames.WINDOW_SELF */):void { var r:* = request; if(r is String) { r = new URLRequest(r); } else if(!(r is URLRequest)) { throw new Error("request"); } if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE() && request._data == null) { if(openWindow(r.url, window)) return; } navigateToURL(r, window); } } ================================================ FILE: src/utils/location/openWindow.as ================================================ package utils.location { import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; /** * Open a new browser window and prevent browser from blocking it. * Based on script by Sergey Kovalyov (http://skovalyov.blogspot.com/2007/01/how-to-prevent-pop-up-blocking-in.html) * Based on script by Jason the Saj (http://thesaj.wordpress.com/2008/02/12/the-nightmare-that-is-_blank-part-ii-help) * Original: http://apdevblog.com/problems-using-navigatetourl * You also have to set the wmode inside your containing html file to "opaque" and the allowScriptAccess to "always". * @param url url to be opened * @param window Window target * @param features Additional features for window.open function * @author Sergey Kovalyov * @author Jason the Saj * @author Aron Woost (apdevblog.com) * @author Philipp Kyeck (apdevblog.com) */ public function openWindow(url:String, window:String = "_blank", features:String = ""):void { switch(getLocationName()) { case locationNames.BROWSER_FIREFOX: ExternalInterface.call("window.open", url, window, features); break; case locationNames.BROWSER_IE: ExternalInterface.call("function setWMWindow() {window.open('" + url + "');}"); break; default: // otherwise, use Flash's native 'navigateToURL()' function to pop-window. // this is necessary because Safari 3 no longer works with the above ExternalInterface work-a-round. navigateToURL(new URLRequest(url), window); } } } ================================================ FILE: src/utils/location/windowNames.as ================================================ package utils.location { public class windowNames { public static const WINDOW_SELF:String = "_self"; public static const WINDOW_BLANK:String = "_blank"; public static const WINDOW_PARENT:String = "_parent"; public static const WINDOW_TOP:String = "_top"; } } ================================================ FILE: src/utils/math/Percent.as ================================================ /* CASA Lib for ActionScript 3.0 Copyright (c) 2010, Aaron Clinger & Contributors of CASA Lib All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the CASA Lib nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package utils.math { /** Creates a standardized way of describing and storing percentages. You can store and receive percentages in two different formats; regular percentage or as an decimal percentage. If percent is 37.5% a regular percentage would be expressed as 37.5 while the decimal percentage will be expressed 0.375. @author Aaron Clinger @author Mike Creighton @version 02/16/09 */ public class Percent { protected var _percent:Number; /** Creates a new Percent. @param percentage: Percent formated at a percentage or an decimal percentage. @param isDecimalPercentage: Indicates if the parameter percentage is a decimal percentage true, or regular percentage false. */ public function Percent(percentage:Number = 0, isDecimalPercentage:Boolean = true) { super(); if (isDecimalPercentage) { this.decimalPercentage = percentage; } else { this.percentage = percentage; } } /** The percent expressed as a regular percentage. 37.5% would be expressed as 37.5. */ public function get percentage():Number { return 100 * this._percent; } public function set percentage(percent:Number):void { this._percent = percent * .01; } /** The percent expressed as a decimal percentage. 37.5% would be expressed as 0.375. */ public function get decimalPercentage():Number { return this._percent; } public function set decimalPercentage(percent:Number):void { this._percent = percent; } /** Determines if the percent specified in the percent parameter is equal to this percent object. @param percent: A Percent object. @return Returns true if percents are identical; otherwise false. */ public function equals(percent:Percent):Boolean { return this.decimalPercentage == percent.decimalPercentage; } /** @return A new percent object with the same value as this percent. */ public function clone():Percent { return new Percent(this.decimalPercentage); } public function valueOf():Number { return this.decimalPercentage; } public function toString():String { return this.decimalPercentage.toString(); } } } ================================================ FILE: src/utils/math/Range.as ================================================ /* CASA Lib for ActionScript 3.0 Copyright (c) 2009, Aaron Clinger & Contributors of CASA Lib All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the CASA Lib nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package utils.math { /** Creates a standardized way of describing and storing an extent of variation/a value range. @author Aaron Clinger @author Mike Creighton @version 10/19/08 */ public class Range { protected var _end:Number; protected var _start:Number; /** Creates and defines a Range object. @param start: Beginning value of the range. @param end: Ending value of the range. @usageNote You are not required to define the range in the contructor you can do it at any point by calling {@link #setRange}. */ public function Range(start:Number, end:Number) { super(); this.setRange(start, end); } /** Defines or redefines range. @param start: Beginning value of the range. @param end: Ending value of the range. */ public function setRange(start:Number, end:Number):void { this.start = start; this.end = end; } /** The start value of the range. */ public function get start():Number { return this._start; } public function set start(value:Number):void { this._start = value; } /** The end value of the range. */ public function get end():Number { return this._end; } public function set end(value:Number):void { this._end = value; } /** The minimum or smallest value of the range. */ public function get min():Number { return Math.min(this.start, this.end); } /** Tthe maximum or largest value of the range. */ public function get max():Number { return Math.max(this.start, this.end); } /** Determines if value is included in the range including the range's start and end values. @return Returns true if value was included in range; otherwise false. */ public function isWithinRange(value:Number):Boolean { return (value <= this.max && value >= this.min); } /** Calculates the percent of the range. @param percent: A {@link Percent} object. @return The value the percent represent of the range. */ public function getValueOfPercent(percent:Percent):Number { var min:Number; var max:Number; var val:Number; var per:Percent = percent.clone(); if (this.start <= this.end) { min = this.start; max = this.end; } else { per.decimalPercentage = 1 - per.decimalPercentage; min = this.end; max = this.start; } val = Math.abs(max - min) * per.decimalPercentage + min; return val; } /** Returns the percentage the value represents out of the range. @param value: An integer. @return A Percent object. */ public function getPercentOfValue(value:Number):Percent { return new Percent((value - this.min) / (this.max - this.min)); } /** Determines if the range specified by the range parameter is equal to this range object. @param percent: A Range object. @return Returns true if ranges are identical; otherwise false. */ public function equals(range:Range):Boolean { return this.start == range.start && this.end == range.end; } /** Determines if this range and the range specified by the range parameter overlap. @param A Range object. @return Returns true if this range contains any value of the range specified; otherwise false. */ public function overlaps(range:Range):Boolean { if (this.equals(range) || this.contains(range) || range.contains(Range(this)) || this.isWithinRange(range.start) || this.isWithinRange(range.end)) return true; return false; } /** Determines if this range contains the range specified by the range parameter. @param A Range object. @return Returns true if this range contains all values of the range specified; otherwise false. */ public function contains(range:Range):Boolean { return this.start <= range.start && this.end >= range.end; } /** @return A new range object with the same values as this range. */ public function clone():Range { return new Range(this.start, this.end); } } } ================================================ FILE: src/utils/math/expressAsOdds.as ================================================ package utils.math { /** * Expresses chances that an outcome will occur out of a number of total possible outcomes. * * @example
 
	 * // number of kings in a deck of cards.
	 * expressAsOdds(4, 52); // 1:13
	 * 
	 * @author Mims Wright
	 */
	public function expressAsOdds(numberOfChances:int, allPossibleOutcomes:int):String {
		var _gcd:int = gcd(numberOfChances, allPossibleOutcomes);
		return (numberOfChances / _gcd) + ":" + (allPossibleOutcomes / _gcd);	
	}
}

================================================
FILE: src/utils/math/gcd.as
================================================
package utils.math
{
	/**
	 * Returns the greatest common devisor between two ints.
	 * 
	 * @author Mims Wright
	 */
	public function gcd(a:int, b:int):int {
		if (b == 0) {
			return a;
		}
		return gcd (b, a%b);
	}
}

================================================
FILE: src/utils/mvc/AbstractController.as
================================================
package utils.mvc
{
	/**
	 * Provides basic implementation of the "controller" of
	 * a Model/View/Controller triad.
	 * 
	 * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/
	 */
	public class AbstractController implements IController
	{
		/**
		 * Constructor
		 *
		 * @param   model   The model this controller's view is observing.
		 */
		public function AbstractController( model : * )
		{
			this.model = model;
		}
		
		public function get model():* { return _model; }
		public function set model(model:*):void { _model = model; }
		protected var _model:*;
		
		
		public function get view():IView { return _view; }
		public function set view(view:IView):void { _view = view; }
		protected var _view:IView;
	}
}


================================================
FILE: src/utils/mvc/AbstractModel.as
================================================
package utils.mvc
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	/**
	 * Specifies the minimum functionality that the "model" of
	 * a Model/View/Controller triad must provide.
	 * 
	 * @author Mims Wright
	 */
	public class AbstractModel extends EventDispatcher implements IModel
	{
		public function AbstractModel()
		{
			super();
		}
	}
}

================================================
FILE: src/utils/mvc/AbstractView.as
================================================
package utils.mvc
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	
	/**
	 * A default implementation of IView based on MovieClip.
	 * 
	 * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/
	 */
	public class AbstractView extends MovieClip implements IView
	{
		
		/**
		 * Constructor. 
		 *
		 * @param model The data model that defines this view. 
		 * @param controller A specific controller to use (otherwise, the defaultController will be used)
		 */ 
		public function AbstractView ( model:*, controller:IController = null) {
			super();
			this.model = model;
			
			if (controller != null) {
				this.controller = controller;
			}
		}
		
		/** @inheritDoc */
		public function asDisplayObject():DisplayObject {
			return this;
		}
		
		/** @inheritDoc */
		public function get model():* { return _model; }
		public function set model(model:*):void { _model = model; }
		protected var _model:*;
		
		
		/** 
		 * The controller for the model that the view will use to modify it.
		 * If it is set to null, the default controller will be used.
		 */
		public function get controller():IController {
			// If a controller hasn't been defined yet...
			if (_controller == null) {
				// ...make one. Note that defaultController() is normally overridden 
				// by the AbstractView subclass so that it returns the appropriate
				// controller for the view.
				this.controller = getDefaultController( model );
				this.controller.view = this;
			}
			return controller;
		}
		public function set controller(controller:IController):void {
			_controller = controller;
			controller.view = this;
		}
		protected var _controller:IController;
		
		public function getDefaultController( model:* ):IController {
//			AbstractEnforcer.enforceMethod();
			return null;
		}
	}
}

================================================
FILE: src/utils/mvc/IController.as
================================================
package utils.mvc
{
	
	
	/**
	 * Specifies the minimum functionality that the "controller" of
	 * a Model/View/Controller triad must provide.
	 * 
	 * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/
	 */
	public interface IController
	{
		/**
		 * Sets the model for this controller.
		 */
		function set model (model:*):void;
		
		/**
		 * Returns the model for this controller.
		 */
		function get model ():*;
		
		/**
		 * Sets the view this controller is servicing.
		 */
		function set view (view:IView):void;
		
		/**
		 * Returns this controller's view.
		 */
		function get view ():IView;
	}
}

================================================
FILE: src/utils/mvc/IModel.as
================================================
package utils.mvc
{
	import flash.events.IEventDispatcher;
	
	/**
	 * Specifies the minimum functionality that the "model" of
	 * a Model/View/Controller triad must provide.
	 * 
	 * @author Mims Wright
	 */
	public interface IModel extends IEventDispatcher
	{
		
	}
}

================================================
FILE: src/utils/mvc/IView.as
================================================
package utils.mvc
{
	import utils.display.IDisplayObject;

	/**
	 * Specifies the minimum functionality that the "view" 
	 * of a Model/View/Controller triad must provide.
	 * 
	 * @author From original AS2 code by Colin Moock modified by Mims Wright  http://www.moock.org/lectures/mvc/
	 */
	public interface IView extends IDisplayObject
	{
		/** A reference to the model associated with this view. */
		function set model ( model:* ):void;
		function get model ():*;
		
		/** A reference to the model's controller. */
		function set controller ( controller:IController ):void;
		function get controller ():IController;
		
		/** 
		 * Returns an instance to a default implementation of the controller
		 * for the model.
		 */ 
		function getDefaultController ( model:* ):IController;
	}
}

================================================
FILE: src/utils/number/addLeadingZeroes.as
================================================
package utils.number
{
	/**
	 * Formats a number to include one or more leading zeroes if needed. 
	 * @example 	 * addLeadingZeroes(4); // "04"
	 * addLeadingZeroes(5, 3); // "0005"
	 * addLeadingZeroes(10, 1); // "10"
	 * addLeadingZeroes(10, 2); // "010"
	 * 
	 * 
	 * @param n The number that will be formatted. Ignores negative numbers.
	 * @return A string of the number with leading zeroes.
	 *
	 * @langversion ActionScript 3.0
	 * @playerversion Flash 9.0
	 * 
	 * @author updated by Mims Wright - original contributor unknown
	 */
	public function addLeadingZeroes(n:Number, zeroes:int = 1):String
	{
		var out:String = String(n);
		
		if (n < 0 || zeroes < 1) {
			return out;
		}

		while (out.length < zeroes + 1) {
			out = "0" + out;
		}

		return out;
	}
}

================================================
FILE: src/utils/number/clamp.as
================================================
package utils.number
{
	/**
	 * Constrains a value to the defined numeric boundaries.
	 * 
	 * @example 	 * clamp(3, 2, 5);   // this will give back 3 since it's within the range
	 * clamp(20, 2, 5);  // this will give back 5 since 5 is the upper boundary
	 * clamp(-5, 2, 5);  // this will give back 2 since 2 is the lower boundary
	 * 
	 * 
	 * @author Mims Wright
	 */
	public function clamp(val:Number, min:Number, max:Number):Number
	{
		return Math.max(Math.min(val, max), min);
	}
}

================================================
FILE: src/utils/number/createStepsBetween.as
================================================
package utils.number
{
	/**
	   Creates evenly spaced numerical increments between two numbers.

	   @param begin: The starting value.
	   @param end: The ending value.
	   @param steps: The number of increments between the starting and ending values.
	   @return Returns an Array composed of the increments between the two values.
	   @example
	   
	   trace(NumberUtil.createStepsBetween(0, 5, 4)); // Traces 1,2,3,4
	   trace(NumberUtil.createStepsBetween(1, 3, 3)); // Traces 1.5,2,2.5
	   
	 */
	public function createStepsBetween(begin:Number, end:Number, steps:Number):Array
	{
		steps++;

		var i:uint = 0;
		var stepsBetween:Array = new Array();
		var increment:Number = (end - begin) / steps;

		while (++i < steps)
			stepsBetween.push((i * increment) + begin);

		return stepsBetween;
	}
}

================================================
FILE: src/utils/number/fastMax2.as
================================================
package utils.number {



	/**
	 * Get fast max for two numbers.
	 * @param val1 Number A
	 * @param val2 Number B
	 * @return Max
	 * @author Jackson Dunstan (http://jacksondunstan.com/articles/445)
	 */
	public function fastMax2(val1:Number, val2:Number):Number {
		if((!(val1 <= 0) && !(val1 > 0)) || (!(val2 <= 0) && !(val2 > 0))) return NaN;
		return val1 > val2 ? val1 : val2;
	}
}


================================================
FILE: src/utils/number/fastMin2.as
================================================
package utils.number {



	/**
	 * Get fast min for two numbers.
	 * @param val1 Number A
	 * @param val2 Number B
	 * @return Min
	 * @author Jackson Dunstan (http://jacksondunstan.com/articles/445)
	 */
	public function fastMin2(val1:Number, val2:Number):Number {
		if((!(val1 <= 0) && !(val1 > 0)) || (!(val2 <= 0) && !(val2 > 0))) return NaN;
		return val1 < val2 ? val1 : val2;
	}
}


================================================
FILE: src/utils/number/format.as
================================================
package utils.number {



	/**
	 Formats a number.
	 @param value The number you wish to format.
	 @param minLength The minimum length of the number.
	 @param thouDelim The character used to separate thousands.
	 @param fillChar The leading character used to make the number the minimum length.
	 @return Returns the formatted number as a String.
	 @example
	 
	 trace(NumberUtil.format(1234567, 8, ",")); // Traces 01,234,567
	 
	 */
	public function format(value:Number, minLength:uint, thouDelim:String = null, fillChar:String = null):String {
		var num:String = value.toString();
		var len:uint = num.length;

		if(thouDelim != null) {
			var numSplit:Array = num.split('');
			var counter:uint = 3;
			var i:uint = numSplit.length;

			while(--i > 0) {
				counter--;
				if(counter == 0) {
					counter = 3;
					numSplit.splice(i, 0, thouDelim);
				}
			}

			num = numSplit.join('');
		}

		if(minLength != 0) {
			if(len < minLength) {
				minLength -= len;

				var addChar:String = (fillChar == null) ? '0' : fillChar;

				while(minLength--)
					num = addChar + num;
			}
		}

		return num;
	}
}


================================================
FILE: src/utils/number/getOrdinalSuffix.as
================================================
package utils.number
{
	/**
	   Finds the English ordinal suffix for the number given.

	   @param value: Number to find the ordinal suffix of.
	   @return Returns the suffix for the number, 2 characters.
	   @example
	   
	   trace(32 + NumberUtil.getOrdinalSuffix(32)); // Traces 32nd
	   
	 */
	public function getOrdinalSuffix(value:int):String
	{
		if (value >= 10 && value <= 20)
			return 'th';

		switch (value % 10)
		{
			case 0:
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
				return 'th';
			case 3:
				return 'rd';
			case 2:
				return 'nd';
			case 1:
				return 'st';
			default:
				return '';
		}
	}
}

================================================
FILE: src/utils/number/getWeightedAverage.as
================================================
package utils.number {



	/**
	 * Low pass filter algorithm for easing a value toward a destination value.
	 * Works best for tweening values when no definite time duration exists and
	 * when the destination value changes.
	 * When (0.5 < n < 1), then the resulting values will
	 * overshoot (ping-pong) until they reach the destination value.
	 * When n is greater than 1, as its value increases, the time
	 * it takes to reach the destination also increases. A pleasing value for
	 * n is 5.
	 * @param value The current value.
	 * @param dest The destination value.
	 * @param n The slowdown factor.
	 * @return The weighted average.
	 */
	public function getWeightedAverage(value:Number, dest:Number, n:Number):Number {
		return value + (dest - value) / n;
	}
}


================================================
FILE: src/utils/number/hexChars.as
================================================
package utils.number
{
	[ExcludeClass]
	/** String for quick lookup of a hex character based on index */
	public const hexChars:String = "0123456789abcdef";
}

================================================
FILE: src/utils/number/insertCommas.as
================================================
package utils.number
{
	/**
	 * Inserts commas every three digits in the integer of value
	 * @param value the number to insert commas into
	 * @return value as a String formatted with commas
	 */
	public function insertCommas(value:Number):String
	{
		// convert the value to a string
		var valueString:String = String(value);

		// determine the location of the point
		var commaIndex:int = valueString.indexOf(".");

		// if a point doesn't exist, consider it to be at the end of the value
		if (commaIndex == -1)
			commaIndex = valueString.length;

		do
		{
			// move to the left three digits
			commaIndex -= 3;

			// if index is beyond the beginning of the value, end the loop
			if (commaIndex <= 0)
				break;

			// insert the comma
			valueString = valueString.substring(0, commaIndex) + "," + valueString.substr(commaIndex);
		}
		while (true);

		// remove "0" if value is a decimal
		if (valueString.substr(0, 2) == "0.")
			valueString = valueString.substr(1);

		return valueString;
	}
}

================================================
FILE: src/utils/number/interpolate.as
================================================
package utils.number
{
	import utils.math.Percent;

	/**
	   Determines a value between two specified values.

	   @param amount: The level of interpolation between the two values. If 0%, begin value is returned; if 100%, end value is returned.
	   @param minimum: The lower value.
	   @param maximum: The upper value.
	   @example
	   
	   trace(NumberUtil.interpolate(new Percent(0.5), 0, 10)); // Traces 5
	   
	 */
	public function interpolate(amount:Percent, minimum:Number, maximum:Number):Number
	{
		return minimum + (maximum - minimum) * amount.decimalPercentage;
	}
}

================================================
FILE: src/utils/number/isBetween.as
================================================
package utils.number
{
	/**
	   Determines if the value is included within a range.

	   @param value: Number to determine if it is included in the range.
	   @param firstValue: First value of the range.
	   @param secondValue: Second value of the range.
	   @return Returns true if the number falls within the range; otherwise false.
	   @usageNote The range values do not need to be in order.
	   @example
	   
	   trace(NumberUtil.isBetween(3, 0, 5)); // Traces true
	   trace(NumberUtil.isBetween(7, 0, 5)); // Traces false
	   
	 */
	public function isBetween(value:Number, firstValue:Number, secondValue:Number):Boolean
	{
		return !(value < Math.min(firstValue, secondValue) || value > Math.max(firstValue, secondValue));
	}
}

================================================
FILE: src/utils/number/isEqual.as
================================================
package utils.number
{
	/**
	   Determines if the two values are equal, with the option to define the precision.

	   @param val1: A value to compare.
	   @param val2: A value to compare.
	   @param precision: The maximum amount the two values can differ and still be considered equal.
	   @return Returns true the values are equal; otherwise false.
	   @example
	   
	   trace(NumberUtil.isEqual(3.042, 3, 0)); // Traces false
	   trace(NumberUtil.isEqual(3.042, 3, 0.5)); // Traces true
	   
	 */
	public function isEqual(val1:Number, val2:Number, precision:Number = 0):Boolean
	{
		return Math.abs(val1 - val2) <= Math.abs(precision);
	}
}

================================================
FILE: src/utils/number/isEven.as
================================================
package utils.number
{
	/**
	   Determines if the number is even.

	   @param value: A number to determine if it is divisible by 2.
	   @return Returns true if the number is even; otherwise false.
	   @example
	   
	   trace(NumberUtil.isEven(7)); // Traces false
	   trace(NumberUtil.isEven(12)); // Traces true
	   
	 */
	public function isEven(value:Number):Boolean
	{
		return (value & 1) == 0;
	}
}

================================================
FILE: src/utils/number/isInteger.as
================================================
package utils.number
{
	/**
	   Determines if the number is an integer.

	   @param value: A number to determine if it contains no decimal values.
	   @return Returns true if the number is an integer; otherwise false.
	   @example
	   
	   trace(NumberUtil.isInteger(13)); // Traces true
	   trace(NumberUtil.isInteger(1.2345)); // Traces false
	   
	 */
	public function isInteger(value:Number):Boolean
	{
		return (value % 1) == 0;
	}
}

================================================
FILE: src/utils/number/isNegative.as
================================================
package utils.number {



	/**
	 * Determines whether or not the supplied Number is negative.
	 * @param value Number to evaluate
	 * @return Whether or not the supplied Number is negative
	 * @author Aaron Clinger
	 * @author Shane McCartney
	 * @author David Nelson
	 */
	public function isNegative(value:Number):Boolean {
		return !isPositive(value);
	}
}


================================================
FILE: src/utils/number/isOdd.as
================================================
package utils.number
{
	/**
	   Determines if the number is odd.

	   @param value: A number to determine if it is not divisible by 2.
	   @return Returns true if the number is odd; otherwise false.
	   @example
	   
	   trace(NumberUtil.isOdd(7)); // Traces true
	   trace(NumberUtil.isOdd(12)); // Traces false
	   
	 */
	public function isOdd(value:Number):Boolean
	{
		return !isEven(value);
	}
}

================================================
FILE: src/utils/number/isPositive.as
================================================
package utils.number {



	/**
	 * Determines whether or not the supplied Number is positive.
	 * @param value Number to evaluate
	 * @return Whether or not the supplied Number is positive
	 * @author Aaron Clinger
	 * @author Shane McCartney
	 * @author David Nelson
	 */
	public function isPositive(value:Number):Boolean {
		return Boolean(value >= 0);
	}
}


================================================
FILE: src/utils/number/isPrime.as
================================================
package utils.number
{
	/**
	   Determines if the number is prime.

	   @param value: A number to determine if it is only divisible by 1 and itself.
	   @return Returns true if the number is prime; otherwise false.
	   @example
	   
	   trace(NumberUtil.isPrime(13)); // Traces true
	   trace(NumberUtil.isPrime(4)); // Traces false
	   
	 */
	public function isPrime(value:Number):Boolean
	{
		if (value == 1 || value == 2)
			return true;

		if (isEven(value))
			return false;

		var s:Number = Math.sqrt(value);
		for (var i:Number = 3; i <= s; i++)
			if (value % i == 0)
				return false;

		return true;
	}
}

================================================
FILE: src/utils/number/isRoughlyEqual.as
================================================
package utils.number {
	
	/**
	 * Returns true if the two numbers are within "maxPercentDifferent" percent of each other. 
	 * 
	 * @example 	 * isRoughlyEqual(0.7, 0.69); // true
	 * isRoughlyEqual(0.7, 0.5); // false
	 * 
	 * isRoughlyEqual(123456789, 123450000); // true
	 * isRoughlyEqual(123456789, 100000000); // false
	 * isRoughlyEqual(123456789, 100000000, 0.25); // true
	 * 
	 * 
	 */
	public function isRoughlyEqual ( a:Number, b:Number, maxPercentDifferent:Number = 0.10 ):Boolean {
		return Math.abs((a/b) - 1.0) < maxPercentDifferent; 
	}
}

================================================
FILE: src/utils/number/loopIndex.as
================================================
package utils.number
{
	/**
	   Determines if index is included within the collection length otherwise the index loops to the beginning or end of the range and continues.

	   @param index: Index to loop if needed.
	   @param length: The total elements in the collection.
	   @return A valid zero-based index.
	   @example
	   
	   var colors:Array = new Array("Red", "Green", "Blue");

	   trace(colors[NumberUtil.loopIndex(2, colors.length)]); // Traces Blue
	   trace(colors[NumberUtil.loopIndex(4, colors.length)]); // Traces Green
	   trace(colors[NumberUtil.loopIndex(-6, colors.length)]); // Traces Red
	   
	 */
	public function loopIndex(index:int, length:uint):uint
	{
		if (index < 0)
			index = length + index % length;

		if (index >= length)
			return index % length;

		return index;
	}
}

================================================
FILE: src/utils/number/map.as
================================================
package utils.number
{
	/**
	   Maps a value from one coordinate space to another.

	   @param value: Value from the input coordinate space to map to the output coordinate space.
	   @param min1: Starting value of the input coordinate space.
	   @param max1: Ending value of the input coordinate space.
	   @param min2: Starting value of the output coordinate space.
	   @param max2: Ending value of the output coordinate space.
	   @example
	   
	   trace(NumberUtil.map(0.75, 0, 1, 0, 100)); // Traces 75
	   
	 */
	public function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
	{
		return min2 + (max2 - min2) * ((value - min1) / (max1 - min1));
	}
}

================================================
FILE: src/utils/number/max.as
================================================
package utils.number
{
	/**
	   Evaluates val1 and val2 and returns the larger value. Unlike Math.max this method will return the defined value if the other value is null or not a number.

	   @param val1: A value to compare.
	   @param val2: A value to compare.
	   @return Returns the largest value, or the value out of the two that is defined and valid.
	   @example
	   
	   trace(max(-5, null)); // Traces -5
	   trace(max(-5, "CASA")); // Traces -5
	   trace(max(-5, -13)); // Traces -5
	   
	 */
	public function max(val1:*, val2:*):Number
	{
		if (isNaN(val1) && isNaN(val2) || val1 == null && val2 == null)
			return NaN;

		if (val1 == null || val2 == null)
			return (val2 == null) ? val1 : val2;

		if (isNaN(val1) || isNaN(val2))
			return (isNaN(val2)) ? val1 : val2;

		return Math.max(val1, val2);
	}
}

================================================
FILE: src/utils/number/min.as
================================================
package utils.number
{
	/**
	   Evaluates val1 and val2 and returns the smaller value. Unlike Math.min this method will return the defined value if the other value is null or not a number.

	   @param val1: A value to compare.
	   @param val2: A value to compare.
	   @return Returns the smallest value, or the value out of the two that is defined and valid.
	   @example
	   
	   trace(min(5, null)); // Traces 5
	   trace(min(5, "CASA")); // Traces 5
	   trace(min(5, 13)); // Traces 5
	   
	 */
	public function min(val1:*, val2:*):Number
	{
		if (isNaN(val1) && isNaN(val2) || val1 == null && val2 == null)
			return NaN;

		if (val1 == null || val2 == null)
			return (val2 == null) ? val1 : val2;

		if (isNaN(val1) || isNaN(val2))
			return isNaN(val2) ? val1 : val2;

		return Math.min(val1, val2);
	}
}

================================================
FILE: src/utils/number/normalize.as
================================================
package utils.number
{
	import utils.math.Percent;

	/**
	   Determines a percentage of a value in a given range.

	   @param value: The value to be converted.
	   @param minimum: The lower value of the range.
	   @param maximum: The upper value of the range.
	   @example
	   
	   trace(NumberUtil.normalize(8, 4, 20).decimalPercentage); // Traces 0.25
	   
	 */
	public function normalize(value:Number, minimum:Number, maximum:Number):Percent
	{
		return new Percent((value - minimum) / (maximum - minimum));
	}
}

================================================
FILE: src/utils/number/pad.as
================================================
package utils.number {



	/**
	 * Pads the value with the set number of digits before and after the point.
	 * If the number of digits in the integer of value is less than beforePoint, the remaining digits are filled with zeros.
	 * If the number of digits in the decimal of value is less than afterPoint, the remaining digits are filled with zeros.
	 * @param value the number to pad
	 * @param beforePoint the number of digits to pad before the point
	 * @param afterPoint the number of digits to pad after the point
	 * @return value padded as a String
	 * @example
	 * 	 * NumberUtil.pad(.824, 0, 5); // returns ".82400"
	 * NumberUtil.pad(9, 3, 2); // returns "009.00"
	 * NumberUtil.pad(2835.3, 4, 2); // returns "2835.30"
	 * 
	 */
	public function pad(value:Number, beforePoint:uint, afterPoint:uint = 0):String {
		// separate the integer from the decimal
		var valueArray:Array = String(value).split(".");

		var integer:String = valueArray[0];

		// determine the sign of the value
		var negative:Boolean = integer.substr(0, 1) == "-";

		// remove the "-" if it exists
		if(negative)
			integer = integer.substr(1);

		// treat zeros as empty, so integer.length doesn't return 1 when integer is 0
		if(integer == "0") {
			integer = "";
		}

		var len:int = integer.length;

		// determine how many times "0" needs to be prepended
		var zeros:int = Math.max(0, beforePoint - len);

		// prepend "0" until zeros == 0
		while(zeros--)
			integer = "0" + integer;

		var decimal:String;

		// if a point didn't exist or the decimal is 0, empty the decimal
		if(valueArray.length == 1 || valueArray[1] == "0") {
			decimal = "";
		}
		else {
			decimal = valueArray[1];
		}

		len = decimal.length;

		// determine how many times "0" needs to be appended
		zeros = Math.max(0, afterPoint - len);

		// append "0" until zeros == 0
		while(zeros--)
			decimal += "0";

		// set sign if negative
		var sign:String = negative ? "-" : "";

		// set point if a decimal exists (or afterPoint > 0, determined earlier)
		var point:String = decimal ? "." : "";

		return sign + integer + point + decimal;
	}
}


================================================
FILE: src/utils/number/randomIntegerWithinRange.as
================================================
package utils.number
{
	/**
	   Creates a random integer within the defined range.

	   @param min: The minimum value the random integer can be.
	   @param min: The maximum value the random integer can be.
	   @return Returns a random integer within the range.
	 */
	public function randomIntegerWithinRange(min:int, max:int):int
	{
		return Math.round(randomWithinRange(min, max));
	}
}

================================================
FILE: src/utils/number/randomSign.as
================================================
package utils.number {



	/**
	 * Returns an int: -1 or 1.
	 * Example code:
	 *      
	 *          RandomUtils.sign(); // returns 1 or -1 (50% chance of 1)
	 *      
* Another example code: *
	 *          RandomUtils.sign(0.8); // returns 1 or -1 (80% chance of 1)
	 *      
* @param chance Chance Number (0-1) * @return int: -1 or 1. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function randomSign(chance:Number = 0.5):int { return(Math.random() < chance) ? 1 : -1; } } ================================================ FILE: src/utils/number/randomWithinRange.as ================================================ package utils.number { /** * Randomly generates a number in a range between min and max inclusively. * Automatically swaps max and min if min is higher than max. * * @param min The minimum value the random number can be. * @param min The maximum value the random number can be. * @return Returns a random number within the range. * * @author Mims Wright */ public function randomWithinRange(min:Number, max:Number):Number { if (min > max) { var temp:Number = max; max = min; min = temp; } return min + (Math.random() * (max - min)); } } ================================================ FILE: src/utils/number/rol.as ================================================ package utils.number { /** * Rotates x left n bits * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function rol(x:int, n:int):int { return (x << n) | (x >>> (32 - n)); } } ================================================ FILE: src/utils/number/ror.as ================================================ package utils.number { /** * Rotates x right n bits * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function ror(x:int, n:int):uint { var nn:int = 32 - n; return (x << nn) | (x >>> (32 - nn)); } } ================================================ FILE: src/utils/number/round.as ================================================ package utils.number { /** * Rounds a number to the nearest nth, where digits is n / 10. * @param value the number to round * @param digits the number of digits to show after the point * @return */ public function round(value:Number, digits:int):Number { digits = Math.pow(10, digits); return Math.round(value * digits) / digits; } } ================================================ FILE: src/utils/number/roundDecimalToPlace.as ================================================ package utils.number { /** Rounds a number's decimal value to a specific place. @param value: The number to round. @param place: The decimal place to round. @return Returns the value rounded to the defined place. @example trace(NumberUtil.roundToPlace(3.14159, 2)); // Traces 3.14 trace(NumberUtil.roundToPlace(3.14159, 3)); // Traces 3.142 */ public function roundDecimalToPlace(value:Number, place:uint):Number { var p:Number = Math.pow(10, place); return Math.round(value * p) / p; } } ================================================ FILE: src/utils/number/toHex.as ================================================ package utils.number { import flash.utils.Endian; /** * Converts a uint into a string in the format “0x123456789ABCDEF”. * This function is quite useful for displaying hex colors as text. * * @example * * getNumberAsHexString(255); // 0xFF * getNumberAsHexString(0xABCDEF); // 0xABCDEF * getNumberAsHexString(0x00FFCC); // 0xFFCC * getNumberAsHexString(0x00FFCC, 6); // 0x00FFCC * getNumberAsHexString(0x00FFCC, 6, false); // 00FFCC * getNumberAsHexString(0x12345, 1, false, Endian.BIG_ENDIAN); // 452301 (note 0 added to 1 to make a byte) * * * * @param number The number to convert to hex. Note, numbers larger than 0xFFFFFFFF may produce unexpected results. * @param minimumLength The smallest number of hexits to include in the output. * Missing places will be filled in with 0’s. * e.g. getNumberAsHexString(0xFF33, 6); // results in "0x00FF33" * @param showHexDenotation If true, will append "0x" to the front of the string. * @param endianness Flag to output the int as big or little endian. * Can be Endian.BIG_INDIAN/Endian.LITTLE_ENDIAN or true/false. * Default is BIG. * @return String representation of the number as a string starting with "0x" * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @see flash.utils.Endian * * @author Mims H. Wright (modified by Pimm Hogeling) */ public function toHex(n:int, minimumLength:uint = 1, showHexDenotation:Boolean = true, endianness:* = null):String { var bigEndian:Boolean; if (endianness == null) { endianness = Endian.BIG_ENDIAN; } if (endianness is Boolean) { bigEndian = Boolean(endianness); } else { bigEndian = endianness == Endian.BIG_ENDIAN; } // The string that will be output at the end of the function. var string:String = n.toString(16).toUpperCase(); // While the minimumLength argument is higher than the length of the string, add a leading zero. while (minimumLength > string.length) { string = "0" + string; } if (!bigEndian) { // reverse string. if (string.length %2 == 1) { string = "0" + string; } var i:int = 0; var reversed:Array = []; while (i < string.length) { var byte:String = string.charAt(i++) + string.charAt(i++); reversed.unshift(byte); } string = reversed.join(""); } // Return the result with a "0x" in front of the result. if (showHexDenotation) { string = "0x" + string; } return string; } } ================================================ FILE: src/utils/object/assign.as ================================================ package utils.object { /** * Assign properties from params to an Object. * @param obj Target Object * @param params Source Object * @return Resulting Object */ public function assign(obj:Object, params:Object):Object { var out:Object = (obj); for(var i:String in params) { //noinspection EmptyCatchBlockJS,UnusedCatchParameterJS try { out[i] = params[i]; } catch(err:Error) { } } return out; } } ================================================ FILE: src/utils/object/clone.as ================================================ package utils.object { import flash.net.registerClassAlias; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; /** * Creates a duplicate of the source object by storing it in a ByteArray and reading it back in, * The object will return untyped so you may need to cast it to the desired class. * AMF rules apply. Check out the documentation for more info. * NOTE: This will not work if the object has any required parameters in the constructor. * * @throws flash.errors.ArgumentError If the source's constructor requires any parameters. * * @example * * var example:Example = new Example(); * var clone:Example = Cloner.clone(example) as Example; * * * @see flash.net#registerClassAlias() * * @param source The object to duplicate. * @param autoRegisterClassAlias Determines whether the class will be registered before cloning. * Defaults to true, though advanced users may wish to register class aliases manually. * @return * A duplicate of the source object. * * @author Mims Wright */ public function clone(source:Object, autoRegisterClassAlias:Boolean = true):* { // automatically register the class so that the clone retains its class. if (autoRegisterClassAlias) registerClassAlias(getQualifiedClassName(source), source.constructor as Class); var copy:ByteArray = new ByteArray(); copy.writeObject(source); copy.position = 0; return copy.readObject(); } } ================================================ FILE: src/utils/object/combine.as ================================================ package utils.object { /** * Combines all of the properties from two objects into a single objects. Note that * duplicate properties will be overwritten by the values on the second parameter object. * * @param defaultVars * @param additionalVars * @return */ public function combine(defaultVars:Object, additionalVars:Object):Object { var combinedObject:Object = {}; var property:String; for (property in defaultVars) { combinedObject[property] = defaultVars[property]; } for (property in additionalVars) { combinedObject[property] = additionalVars[property]; } return combinedObject; } } ================================================ FILE: src/utils/object/contains.as ================================================ package utils.object { /** * Searches the first level properties of an Object for a another Object. * @param obj Object to search in. * @param member Object to search for. * @return true if Object was found * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function contains(obj:Object, member:Object):Boolean { for(var prop:String in obj) { if(obj[prop] == member) { return true; } } return false; } } ================================================ FILE: src/utils/object/copy.as ================================================ package utils.object { /** * Copy an object * @param obj Object to copy * @param into (optional) Object to copy into. If null, a new object * is created. * @return A one-level deep copy of the object or null if the argument * is null * @author Jackson Dunstan */ public function copy(obj:Object, into:Object = null):Object { if (into == null) { into = {}; } if (obj != null) { for (var o:Object in obj) { into[o] = obj[o]; } } return into; } } ================================================ FILE: src/utils/object/create.as ================================================ package utils.object { /** * Creates an instance of the given Class, * optionally passing arguments to the constructor, * and then decorating with properties. * * @param classToInstantiate Class to create an instance of. * @param constructorArguments Array of arguments to pass to the Class constructor. * @returns An instance of classToInstantiate * * @see utils.object#createInstance * @see utils.object#merge * * @example * * var sprite:Sprite = create(Sprite, null, { x: 50, y: 100 }); * * * @author drewbourne */ public function create(classToInstantiate:Class, constructorArguments:Array = null, properties:Object = null):Object { return merge(createInstance(classToInstantiate, constructorArguments), properties); } } ================================================ FILE: src/utils/object/createInstance.as ================================================ package utils.object { /** * Creates an instance of a given Class, * optionally passing arguments to the constructor. * * @param classToInstantiate Class to create an instance of. * @param constructorArguments Array of arguments to pass to the Class constructor. * * @return An instance of classToInstantiate * * @throws ArgumentError When the number of constructorArguments is more than 10. * * @see utils.object#create * * @example * * var event:Event = createInstance(Event, [Event.COMPLETE, true, false]); * * * @author drewbourne */ public function createInstance(classToInstantiate:Class, constructorArguments:Array = null):Object { var args:Array = constructorArguments || []; switch (args.length) { case 0: return new classToInstantiate(); case 1: return new classToInstantiate(args[0]); case 2: return new classToInstantiate(args[0], args[1]); case 3: return new classToInstantiate(args[0], args[1], args[2]); case 4: return new classToInstantiate(args[0], args[1], args[2], args[3]); case 5: return new classToInstantiate(args[0], args[1], args[2], args[3], args[4]); case 6: return new classToInstantiate(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new classToInstantiate(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return new classToInstantiate(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return new classToInstantiate(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return new classToInstantiate(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: throw new ArgumentError("Unable to instantiate:" + classToInstantiate + ", unsupported number of constructor arguments, received: " + args.join(', ')); } } } ================================================ FILE: src/utils/object/getKeys.as ================================================ package utils.object { /** Creates an Array comprised of all the keys in an Object. @param obj: Object in which to find keys. @return Array containing all the string key names. */ public function getKeys(obj:Object):Array { var keys:Array = new Array(); for (var i:String in obj) keys.push(i); return keys; } } ================================================ FILE: src/utils/object/hasAnyProperties.as ================================================ package utils.object { /** * Check if an object has any properties * @param obj Object to check for properties * @return If the specified object has any properties. If the * specified object is null, this is false. * @author Jackson Dunstan */ public function hasAnyProperties(obj:Object):Boolean { for each (var prop:Object in obj) { return true; } return false; } } ================================================ FILE: src/utils/object/inspect.as ================================================ package utils.object { import flash.utils.describeType; /** * Scan an Object. * @param obj Object to be scanned * @param depth Depth of scanning * @return Scan result */ public function inspect(obj:Object, depth:int = 10, prefix:String = "\t"):String { var scan:Function = function(obj:Object, depth:int, prefix:String):String { var out:String; if(depth < 1) { out = obj is String ? "\"" + obj + "\"" : String(obj); } else { const classDef:XML = describeType(obj); var str:String = ""; for each(var variable:XML in classDef.variable) { str += prefix + variable.@name + " = " + scan(obj[variable.@name], depth - 1, prefix + "\t") + "\n"; } for(var s:String in obj) { str += prefix + s + "=" + scan(obj[s], depth - 1, prefix + "\t") + "\n"; } //noinspection NestedConditionalExpressionJS,NegatedConditionalExpressionJS out = str == "" ? ((obj != null) ? (obj is String ? "\"" + obj + "\"" : obj + "") : "null") : ("[" + classDef.@name + "] {\n" + str + (prefix.substr(0, prefix.length - 1)) + "}"); } return out; }; return prefix + scan(obj, depth, prefix + "\t"); } } ================================================ FILE: src/utils/object/isEmpty.as ================================================ package utils.object { /** Determines if object contains no value(s). @param obj Object to determine if empty. @return Returns true if object is empty; otherwise false. @example var testNumber:Number; var testArray:Array = new Array(); var testString:String = ""; var testObject:Object = new Object(); trace(ObjectUtil.isEmpty(testNumber)); // traces "true" trace(ObjectUtil.isEmpty(testArray)); // traces "true" trace(ObjectUtil.isEmpty(testString)); // traces "true" trace(ObjectUtil.isEmpty(testObject)); // traces "true" */ public function isEmpty(obj:*):Boolean { if(obj == undefined) return true; if(obj is Number) return isNaN(obj); if(obj is Array || obj is String) return obj.length == 0; if(obj is Object) { for(var prop:String in obj) return false; return true; } return false; } } ================================================ FILE: src/utils/object/isNull.as ================================================ package utils.object { /** Uses the strict equality operator to determine if object is null. @param obj: Object to determine if null. @return Returns true if object is null; otherwise false. */ public function isNull(obj:Object):Boolean { return obj == null; } } ================================================ FILE: src/utils/object/isSimple.as ================================================ package utils.object { /** * Returns whether or not the given object is simple data type. * * @param the object to check * @return true if the given object is a simple data type; false if not */ public function isSimple(object:Object):Boolean { switch (typeof(object)) { case "number": case "string": case "boolean": return true; case "object": return (object is Date) || (object is Array); } return false; } } ================================================ FILE: src/utils/object/isUniformPropertyType.as ================================================ package utils.object { /** * Check if the properties of an object are all the same * @param obj Object whose properties should be checked * @param type Type to check the object's properties against * @return If all of the properties of the specified object are of the * specified type * @author Jackson Dunstan */ public function isUniformPropertyType(obj:Object, type:Class):Boolean { for each (var prop:Object in obj) { if (!(prop is type)) { return false; } } return true; } } ================================================ FILE: src/utils/object/merge.as ================================================ package utils.object { /** * Merge enumerable fields from a source Object to a target Object. * * NOTE no checks are made to determine if the property is readable or writable. * * @param target Target * @param source Source * @return target * * @example * * var source:Object = { a: 1, d: 4 }; * var target:Object = { a: 0, b: 2, c: 3 } * var result:Object = merge(target, source); * trace(result.a, result.b, result.c, result.d); * // 1 2 3 4 * * * @author drewbourne */ public function merge(target:Object, source:Object):Object { for (var field:Object in source || {}) { target[field] = source[field]; } return target; } } ================================================ FILE: src/utils/object/numProperties.as ================================================ package utils.object { /** * Count the properties in an object * @param obj Object to count the properties of * @return The number of properties in the specified object. If the * specified object is null, this is 0. * @author Jackson Dunstan */ public function numProperties(obj:Object):int { var count:int = 0; for each (var prop:Object in obj) { count++; } return count; } } ================================================ FILE: src/utils/object/toArray.as ================================================ package utils.object { /** * Convert the object to an array. Note that the order of the array is * undefined. * @param obj Object to convert * @return An array with all of the properties of the given object or * null if the given object is null * @author Jackson Dunstan */ public function toArray(obj:Object):Array { if (obj == null) { return null; } else { var ret:Array = []; for each (var prop:Object in obj) { ret.push(prop); } return ret; } } } ================================================ FILE: src/utils/object/toString.as ================================================ package utils.object { /** * Convert the object to a string of form: PROP: VAL&PROP: VAL * where: *
    *
  • PROP is a property
  • *
  • VAL is its corresponding value
  • *
  • & is the specified optional delimiter
  • *
* * @param obj Object to convert * @param delimiter (optional) Delimiter of property/value pairs * @return An string of all property/value pairs delimited by the * given string or null if the input object or delimiter is * null. * @author Jackson Dunstan */ public function toString(obj:Object = null, delimiter:String = "\n"):String { if (obj == null || delimiter == null) { return ""; } else { var ret:Array = []; for (var s:Object in obj) { ret.push(s + ": " + obj[s]); } return ret.join(delimiter); } } } ================================================ FILE: src/utils/range/center.as ================================================ package utils.range { // TODO: what is the purpose of this function? Needs documentation. public function center(a:Number, b:Number, c:Number):Number { if ((a > b) && (a > c)) { if (b > c) return b; else return c; } else if ((b > a) && (b > c)) { if (a > c) return a; else return c; } else if (a > b) { return a; } else { return b; } } } ================================================ FILE: src/utils/range/isInRange.as ================================================ package utils.range { /** * Check if a number is in range. */ public function isInRange(n:Number, min:Number, max:Number, blacklist:Array = null):Boolean { if (!blacklist) blacklist = new Array(); if (blacklist.length > 0) { for (var i:String in blacklist) if (n == blacklist[i]) return false; } return (n >= min && n <= max); } } ================================================ FILE: src/utils/range/randomRangeDate.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 26, 2010 * Time: 1:59:33 PM */ package utils.range { /** * Returns a random date within a given range */ public function randomRangeDate(date1:Date, date2:Date) : Date { if(date1.getTime() == date2.getTime()){ throw new Error("Dates specified are the same"); } if(date2.getTime() < date1.getTime() ){ var temp:Date = date1; date1 = date2; date2 = temp; } var diff:Number = date2.getTime() - date1.getTime(); var rand:Number = Math.random() * diff; var time:Number = date1.getTime() + rand; var d:Date = new Date(); d.setTime(time); return d; } } ================================================ FILE: src/utils/range/randomRangeSet.as ================================================ package utils.range { import utils.number.randomIntegerWithinRange; /** * Returns a set of random numbers inside a specific range (unique numbers is optional) */ public function randomRangeSet(min:Number, max:Number, count:Number, unique:Boolean):Array { var rnds:Array = new Array(); if(unique && count <= max - min + 1) { //unique - create num range array var nums:Array = new Array(); for(var i:Number = min; i <= max; i++) { nums.push(i); } for(var j:Number = 1; j <= count; j++) { // random number var rn:Number = Math.floor(Math.random() * nums.length); rnds.push(nums[rn]); nums.splice(rn, 1); } } else { //non unique for(var k:Number = 1; k <= count; k++) { rnds.push(randomIntegerWithinRange(min, max)); } } return rnds; } } ================================================ FILE: src/utils/range/resolve.as ================================================ package utils.range { /** * Resolve the number inside the range. If outside the range the nearest boundary value will be returned. */ public function resolve(val:Number, min:Number, max:Number):Number { return Math.max(Math.min(val, max), min); } } ================================================ FILE: src/utils/ratio/defineRect.as ================================================ package utils.ratio { import flash.geom.Rectangle; public function defineRect(size:Rectangle, width:Number, height:Number, snapToPixel:Boolean):Rectangle { var scaled:Rectangle = size.clone(); scaled.width = snapToPixel ? int(width) : width; scaled.height = snapToPixel ? int(height) : height; return scaled; } } ================================================ FILE: src/utils/ratio/heightToWidth.as ================================================ package utils.ratio { import flash.geom.Rectangle; /** * Determines the ratio of height to width. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function heightToWidth(rect:Rectangle):Number { return rect.height / rect.width; } } ================================================ FILE: src/utils/ratio/scale.as ================================================ package utils.ratio { import flash.geom.Rectangle; import utils.math.Percent; /** * Scales an area's width and height while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param amount Amount you wish to scale by * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scale(rect:Rectangle, amount:Percent, snapToPixel:Boolean = true):Rectangle { return defineRect(rect, rect.width * amount.decimalPercentage, rect.height * amount.decimalPercentage, snapToPixel); } } ================================================ FILE: src/utils/ratio/scaleHeight.as ================================================ package utils.ratio { import flash.geom.Rectangle; /** * Scales the height of an area while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param width Width to scale to * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleHeight(rect:Rectangle, width:Number, snapToPixel:Boolean = true):Rectangle { return defineRect(rect, width, width * heightToWidth(rect), snapToPixel); } } ================================================ FILE: src/utils/ratio/scaleToFill.as ================================================ package utils.ratio { import flash.geom.Rectangle; /** * Resizes an area to fill the bounding area while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param bounds Area to fill - the Rectangle's x and y values are ignored * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleToFill(rect:Rectangle, bounds:Rectangle, snapToPixel:Boolean = true):Rectangle { var scaled:Rectangle = scaleHeight(rect, bounds.width, snapToPixel); if(scaled.height < bounds.height) scaled = scaleWidth(rect, bounds.height, snapToPixel); return scaled; } } ================================================ FILE: src/utils/ratio/scaleToFit.as ================================================ package utils.ratio { import flash.geom.Rectangle; /** * Resizes an area to the maximum size of a bounding area without exceeding while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param bounds Area the rectangle needs to fit within - the Rectangle's x and y values are ignored * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleToFit(rect:Rectangle, bounds:Rectangle, snapToPixel:Boolean = true):Rectangle { var scaled:Rectangle = scaleHeight(rect, bounds.width, snapToPixel); if(scaled.height > bounds.height) scaled = scaleWidth(rect, bounds.height, snapToPixel); return scaled; } } ================================================ FILE: src/utils/ratio/scaleWidth.as ================================================ package utils.ratio { import flash.geom.Rectangle; /** * Scales the width of an area while preserving aspect ratio. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @param height Height to scale to * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function scaleWidth(rect:Rectangle, height:Number, snapToPixel:Boolean = true):Rectangle { return defineRect(rect, height * widthToHeight(rect), height, snapToPixel); } } ================================================ FILE: src/utils/ratio/widthToHeight.as ================================================ package utils.ratio { import flash.geom.Rectangle; /** * Determines the ratio of width to height. * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function widthToHeight(rect:Rectangle):Number { return rect.width / rect.height; } } ================================================ FILE: src/utils/string/addSlashes.as ================================================ package utils.string { /** * Returns the string with slashes prepended to all characters specified in the chars parameter * @param str the string to return slashed * @param chars the string of chars to slash * @return */ public function addSlashes(str:String, chars:String = "\""):String { // return the unaltered string if str or chars are null or empty if (!str || !chars) return str; // slash unsafe characters chars = slashUnsafeChars(chars); // build the regular expression that handles the slashing var regex:RegExp = new RegExp("([" + chars + "])", "g"); // add the slashes to the specified characters return str.replace(regex, "\\$1"); } } ================================================ FILE: src/utils/string/afterFirst.as ================================================ package utils.string { /** * Returns everything after the first occurrence of the provided character in the String. * @param value Input String * @param ch Character or sub-string * @returns Output String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function afterFirst(value:String, ch:String):String { var out:String = ""; if(value) { var idx:int = value.indexOf(ch); if(idx != -1) { idx += ch.length; out = value.substr(idx); } } return out; } } ================================================ FILE: src/utils/string/afterLast.as ================================================ package utils.string { /** * Returns everything after the last occurrence of the provided character in value. * @param value Input String * @param ch Character or sub-string * @return Output String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function afterLast(value:String, ch:String):String { var out:String = ""; if(value) { var idx:int = value.lastIndexOf(ch); if(idx != -1) { idx += ch.length; out = value.substr(idx); } } return out; } } ================================================ FILE: src/utils/string/arrayList.as ================================================ package utils.string { /** * Convert an Array to a list. * @param a Input Array * @return List as "item1, item2, item3" * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function arrayList(a:Array):String { var out:String = ""; for each(var i:String in a) { out += i + ", "; } return out.substr(0, out.length - 2); } } ================================================ FILE: src/utils/string/beforeFirst.as ================================================ package utils.string { /** * Returns everything before the first occurrence of the provided character in the String. * @param value Input String * @param ch Character or sub-string * @returns Everything before the first occurence of the provided character in the String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function beforeFirst(value:String, ch:String):String { var out:String = ""; if(value) { var idx:int = value.indexOf(ch); if(idx != -1) { out = value.substr(0, idx); } } return out; } } ================================================ FILE: src/utils/string/beforeLast.as ================================================ package utils.string { /** * Returns everything before the last occurrence of the provided character in the String. * @param value Input String * @param ch Character or sub-string * @returns Everything before the last occurrence of the provided character in the String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function beforeLast(value:String, ch:String):String { var out:String = ""; if(value) { var idx:int = value.lastIndexOf(ch); if(idx != -1) { out = value.substr(0, idx); } } return out; } } ================================================ FILE: src/utils/string/beginsWith.as ================================================ package utils.string { /** * Determines whether the specified string begins with the specified prefix. * @param input The string that the prefix will be checked against. * @param prefix The prefix that will be tested against the string. * @returns True if the string starts with the prefix, false if it does not. * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function beginsWith(input:String, prefix:String):Boolean { return (prefix == input.substring(0, prefix.length)); } } ================================================ FILE: src/utils/string/between.as ================================================ package utils.string { /** * Returns everything after the first occurrence of begin and before the first occurrence of end in String. * @param value Input String * @param start Character or sub-string to use as the start index * @param end Character or sub-string to use as the end index * @returns Everything after the first occurrence of begin and before the first occurrence of end in String. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function between(value:String, start:String, end:String):String { var out:String = ""; if(value) { var startIdx:int = value.indexOf(start); if(startIdx != -1) { startIdx += start.length; // RM: should we support multiple chars? (or ++startIdx); var endIdx:int = value.indexOf(end, startIdx); if(endIdx != -1) { out = value.substr(startIdx, endIdx - startIdx); } } } return out; } } ================================================ FILE: src/utils/string/constants.as ================================================ package utils.string { public class constants { public static const REGEX_UNSAFE_CHARS:String = "\\-^[]"; public static const TRIM_RIGHT_REGEX:RegExp = /[\s]+$/g; } } ================================================ FILE: src/utils/string/convertBytesString.as ================================================ package utils.string { import utils.conversion.bytesToKilobytes; /** * Convert bytes to a String ("X B" or "X kB") * @param value Bytes count * @return Result String * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function convertBytesString(value:uint):String { return (value <= 8192 ? (String(value) + " B") : (String(bytesToKilobytes(value)) + " kB")); } } ================================================ FILE: src/utils/string/detectBr.as ================================================ package utils.string { /** * Detect HTML line breaks. */ public function detectBr(str:String):Boolean { return str.split(" 1; } } ================================================ FILE: src/utils/string/endsWith.as ================================================ package utils.string { /** * Determines whether the specified string ends with the specified suffix. * @param input The string that the suffix will be checked against. * @param suffix The suffix that will be tested against the string. * @returns True if the string ends with the suffix, false if it does not. * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function endsWith(input:String, suffix:String):Boolean { return (suffix == input.substring(input.length - suffix.length)); } } ================================================ FILE: src/utils/string/equals.as ================================================ package utils.string { /** * Does a case insensitive compare or two strings and returns true if they are equal. */ public function equals(s1:String, s2:String, caseSensitive:Boolean = false):Boolean { return (caseSensitive) ? (s1 == s2) : (s1.toUpperCase() == s2.toUpperCase()); } } ================================================ FILE: src/utils/string/firstToUpper.as ================================================ package utils.string { /** * Capitalize the first character in the string. */ public function firstToUpper(str:String):String { return str.charAt(0).toUpperCase() + str.substr(1); } } ================================================ FILE: src/utils/string/getLettersFromString.as ================================================ package utils.string { public function getLettersFromString(source:String):String { var pattern:RegExp = /[^A-Z^a-z]/g; return source.replace(pattern, ''); } } ================================================ FILE: src/utils/string/htmlDecode.as ================================================ package utils.string { /** * Decode HTML. */ public function htmlDecode(s:String):String { s = replace(s, " ", " "); s = replace(s, "&", "&"); s = replace(s, "<", "<"); s = replace(s, ">", ">"); s = replace(s, "™", ''); s = replace(s, "®", ""); s = replace(s, "©", ""); s = replace(s, "€", ""); s = replace(s, "£", ""); s = replace(s, "—", ""); s = replace(s, "–", ""); s = replace(s, "…", ''); s = replace(s, "†", ""); s = replace(s, "·", ''); s = replace(s, "µ", ""); s = replace(s, "«", ""); s = replace(s, "»", ""); s = replace(s, "•", ""); s = replace(s, "°", ""); s = replace(s, "&ldquo", '"'); s = replace(s, "’", "'"); s = replace(s, "”", '"'); s = replace(s, """, '"'); return s; } } ================================================ FILE: src/utils/string/htmlEncode.as ================================================ package utils.string { /** * Encode HTML. */ public function htmlEncode(s:String):String { s = replace(s, "&", "&"); s = replace(s, " ", " "); s = replace(s, "<", "<"); s = replace(s, ">", ">"); s = replace(s, "", '™'); s = replace(s, "", '®'); s = replace(s, "", '©'); s = replace(s, "", "€"); s = replace(s, "", "£"); s = replace(s, "", "—"); s = replace(s, "", "–"); s = replace(s, "", "…"); s = replace(s, "", "†"); s = replace(s, "", "·"); s = replace(s, "", "µ"); s = replace(s, "", "«"); s = replace(s, "", "»"); s = replace(s, "", "•"); s = replace(s, "", "°"); s = replace(s, '"', """); return s; } } ================================================ FILE: src/utils/string/ltrim.as ================================================ package utils.string { /** * Removes whitespace from the front of the specified string. * * @param value The String whose beginning whitespace will will be removed. * * @returns A String with whitespace removed from the begining * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function ltrim(value:String):String { var out:String = ""; if(value) { out = value.replace(/^\s+/, ""); } return out; } } ================================================ FILE: src/utils/string/numberToString.as ================================================ package utils.string { /** * Converts a number to its text equivelant * * @params n The number to convert * @returns String equivelant of the number * @playerversion Flash 10.0 * @author Mims H. Wright */ public function numberToString(n:Number):String { var output:Vector. = new Vector.(); // output will temporarily hold the strings that make up str var isNegative:Boolean = false; // used for removing minus sign. var integers:Number; var decimals:Number; // check for NaN if (isNaN(n)) { return N.NAN; } // check for zero if (n == 0) { return N._0; } // check for negatives if (n < 0) { isNegative = true; n *= -1; } // solve for decimals var decimalPointIndex:int = n.toString().indexOf("."); if (decimalPointIndex > -1) { digits = Vector. (n.toString().substr(decimalPointIndex + 1).split("")); digits.reverse(); var i:int = 0; var digit:int; for (; i < digits.length; i += 1) { digit = int(digits[i]); if (digit == 0) { output.push(N._0 + " "); } else { output.push(N._1to9[digit]); } } output.push(N.decimal); } // solve for integers integers = Math.floor(n); var period:int = 0; var digits:Vector. = Vector.(integers.toString().split("")).reverse(); var hundreds:int; var tens:int; var ones:int; var next3:String; while (digits.length > 0) { // grab the next three digits and analyze them. next3 = digits.slice(0,3).join(""); if (next3 != "000") { output.push(N.periods[period]); } ones = int(digits[0]); try { tens = int(digits[1]); } catch (e:RangeError) { tens = NaN;} try { hundreds = int(digits[2]); } catch (e:RangeError) { hundreds = NaN; } if (!isNaN(tens)) { if (tens == 1) { output.push(N._10to19[ones]); } else { output.push(N._1to9[ones]); output.push(N._10to90[tens]); } } else { output.push(N._1to9[ones]); } if (!isNaN(hundreds)) { output.push(N._100to900[hundreds]); } // advance the period counter period++; // remove those three digits from the array of digits digits.splice(0, 3); } if (isNegative == true) { output.push(N.negative); n *= -1; } // reverse the output so that it will look correct output.reverse(); // save the output to the string var str:String = output.join(""); // remove any trailing spaces. if (str.charAt(str.length-1) == " ") { str = str.substr(0, str.length-1); } return str; } } internal class N { public static const NAN:String = "not a number"; public static const decimal:String = "point "; public static const negative:String = "negative "; public static const _0:String = "zero"; public static const _1:String = "one "; public static const _2:String = "two "; public static const _3:String = "three "; public static const _4:String = "four "; public static const _5:String = "five "; public static const _6:String = "six "; public static const _7:String = "seven "; public static const _8:String = "eight "; public static const _9:String = "nine "; public static const _10:String = "ten "; public static const _11:String = "eleven "; public static const _12:String = "twelve "; public static const _13:String = "thirteen "; public static const _14:String = "fourteen "; public static const _15:String = "fifteen "; public static const _16:String = "sixteen "; public static const _17:String = "seventeen "; public static const _18:String = "eighteen "; public static const _19:String = "nineteen "; public static const _20:String = "twenty "; public static const _30:String = "thirty "; public static const _40:String = "fourty "; public static const _50:String = "fifty "; public static const _60:String = "sixty "; public static const _70:String = "seventy "; public static const _80:String = "eighty "; public static const _90:String = "ninety "; public static const _100:String = "hundred "; public static const _1000:String = "thousand "; public static const _1000000:String = "million "; public static const _1000000000:String = "billion "; public static const _1000000000000:String = "trillion "; public static const _1000000000000000:String = "quadrillion "; public static const _1000000000000000000:String = "quintillion "; public static const _1000000000000000000000:String = "sextillion "; public static const _1000000000000000000000000:String = "septillion "; public static const _1000000000000000000000000000:String = "octillion "; public static const _1to9:Vector. = Vector.(["",_1,_2,_3,_4,_5,_6,_7,_8,_9]); public static const _10to19:Vector. = Vector.([_10,_11,_12,_13,_14,_15,_16,_17,_18,_19]); public static const _10to90:Vector. = Vector.(["",_10,_20,_30,_40,_50,_60,_70,_80,_90]); public static const _100to900:Vector. = Vector.(["",_1 + _100, _2 + _100, _3 + _100, _4 + _100, _5 + _100, _6 + _100, _7 + _100, _8 + _100, _9 + _100]); public static const periods:Vector. = Vector.( ["", _1000, _1000000, _1000000000, _1000000000000, _1000000000000000, _1000000000000000000, _1000000000000000000000, _1000000000000000000000000, _1000000000000000000000000000 ]); } ================================================ FILE: src/utils/string/padLeft.as ================================================ package utils.string { /** * Pads value with specified padChar character to a specified length from the left. * @param value Input String * @param padChar Character for pad * @param length Length to pad to * @returns Padded String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function padLeft(value:String, padChar:String, length:uint):String { var s:String = value; while(s.length < length) { s = padChar + s; } return s; } } ================================================ FILE: src/utils/string/padRight.as ================================================ package utils.string { /** * Pads value with specified padChar character to a specified length from the right. * @param value Input String * @param padChar Character for pad * @param length Length to pad to * @returns Padded String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function padRight(value:String, padChar:String, length:uint):String { var s:String = value; while(s.length < length) { s += padChar; } return s; } } ================================================ FILE: src/utils/string/randomCharacters.as ================================================ package utils.string { /** * Generate a random String. * @param amount String length (default 10) * @param charSet Chars used (default "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") * @return Random String */ public function randomCharacters(amount:Number, charSet:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):String { var alphabet:Array = charSet.split(""); var alphabetLength:int = alphabet.length; var randomLetters:String = ""; for(var j:uint = 0; j < amount; j++) { var r:Number = Math.random() * alphabetLength; var s:int = Math.floor(r); randomLetters += alphabet[s]; } return randomLetters; } } ================================================ FILE: src/utils/string/randomLowercaseCharacters.as ================================================ package utils.string { /** * Generate a set of random LowerCase characters. */ public function randomLowercaseCharacters(amount:Number):String { var str:String = ""; for (var i:int = 0; i < amount; i++) str += String.fromCharCode(Math.round(Math.random() * (122 - 97)) + 97); return str; } } ================================================ FILE: src/utils/string/randomNumberString.as ================================================ package utils.string { /** * Generate a set of random Number characters. */ public function randomNumberString(amount:Number):String { var str:String = ""; for (var i:int = 0; i < amount; i++) str += String.fromCharCode(Math.round(Math.random() * (57 - 48)) + 48); return str; } } ================================================ FILE: src/utils/string/randomSequence.as ================================================ package utils.string { import utils.number.randomIntegerWithinRange; /** * Get random sentence. * @param maxLength Max chars * @param minLength Min chars * @return Random sentence * @author Vaclav Vancura (http://vancura.org, http://twitter.com/vancura) */ public function randomSequence(maxLength:uint = 50, minLength:uint = 10):String { return randomCharacters(randomIntegerWithinRange(minLength, maxLength), " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); } } ================================================ FILE: src/utils/string/randomSpecialCharacters.as ================================================ package utils.string { /** * Generate a set of random Special and Number characters. */ public function randomSpecialCharacters(amount:Number):String { var str:String = ""; for (var i:int = 0; i < amount; i++) str += String.fromCharCode(Math.round(Math.random() * (64 - 33)) + 33); return str; } } ================================================ FILE: src/utils/string/remove.as ================================================ package utils.string { /** * Removes all instances of the remove string in the input string. * * @param input The string that will be checked for instances of remove * string * * @param remove The string that will be removed from the input string. * * @returns A String with the remove string removed. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function remove(input:String, remove:String):String { return replace(input, remove, ""); } } ================================================ FILE: src/utils/string/removeExtraWhitespace.as ================================================ package utils.string { /** * Removes extraneous whitespace (extra spaces, tabs, line breaks, etc) from the specified String. * @param value String whose extraneous whitespace will be removed * @returns Output String */ public function removeExtraWhitespace(value:String):String { var out:String = ""; if(value) { var str:String = trim(value); out = str.replace(/\s+/g, " "); } return out; } } ================================================ FILE: src/utils/string/removeSpaces.as ================================================ package utils.string { /** * Remove spaces from string. * @param str (String) * @return String */ public function removeSpaces(str:String):String { return replace(str, " ", ""); } } ================================================ FILE: src/utils/string/removeTabs.as ================================================ package utils.string { /** * Remove tabs from string. */ public function removeTabs(str:String):String { return replace(str, " ", ""); } } ================================================ FILE: src/utils/string/repeat.as ================================================ package utils.string { public function repeat(n:uint, str:String = " "):String { return new Array(n + 1).join(str); } } ================================================ FILE: src/utils/string/replace.as ================================================ package utils.string { /** * Replaces all instances of the replace string in the input string * with the replaceWith string. * * @param input The string that instances of replace string will be * replaces with removeWith string. * * @param replace The string that will be replaced by instances of * the replaceWith string. * * @param replaceWith The string that will replace instances of replace * string. * * @returns A new String with the replace string replaced with the * replaceWith string. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function replace(input:String, replace:String, replaceWith:String):String { return input.split(replace).join(replaceWith); } } ================================================ FILE: src/utils/string/reverse.as ================================================ package utils.string { /** * Returns the specified String in reverse character order. * @param value String that will be reversed * @returns Output String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function reverse(value:String):String { var out:String = ""; if(value) { out = value.split("").reverse().join(""); } return out; } } ================================================ FILE: src/utils/string/reverseWords.as ================================================ package utils.string { /** * Returns the specified String in reverse word order. * @param value String that will be reversed * @returns Output String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function reverseWords(value:String):String { var out:String = ""; if(value) { out = value.split(/\s+/).reverse().join(""); } return out; } } ================================================ FILE: src/utils/string/rtrim.as ================================================ package utils.string { /** * Removes whitespace from the end of the specified string. * * @param value The String whose ending whitespace will will be removed. * * @returns A String with whitespace removed from the end * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function rtrim(value:String):String { var out:String = ""; if(value) { out = value.replace(/\s+$/, ""); } return out; } } ================================================ FILE: src/utils/string/sanitizeNull.as ================================================ package utils.string { /** * Sanitize null strings for display purposes. */ public function sanitizeNull(str:String):String { return (str == null || str == "null") ? "" : str; } } ================================================ FILE: src/utils/string/search.as ================================================ package utils.string { /** * Search for key in string. */ public function search(str:String, key:String, caseSensitive:Boolean = true):Boolean { if (!caseSensitive) { str = str.toUpperCase(); key = key.toUpperCase(); } return (str.indexOf(key) <= -1) ? false : true; } } ================================================ FILE: src/utils/string/slashUnsafeChars.as ================================================ package utils.string { /** * @private * @param chars * @return */ public function slashUnsafeChars(chars:String):String { var unsafeChar:String; var m:uint = constants.REGEX_UNSAFE_CHARS.length; for (var i:uint = 0; i < m; ++i) { unsafeChar = constants.REGEX_UNSAFE_CHARS.substr(i, 1); if (chars.indexOf(unsafeChar) != -1) chars = chars.replace(unsafeChar, "\\" + unsafeChar); } return chars; } } ================================================ FILE: src/utils/string/stringHasValue.as ================================================ package utils.string { /** * Specifies whether the specified string is either non-null, or contains * characters (i.e. length is greater that 0) * * @param s The string which is being checked for a value * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function stringHasValue(s:String):Boolean { return (s != null && s.length > 0); } } ================================================ FILE: src/utils/string/stringsAreEqual.as ================================================ package utils.string { /** * Does a case insensitive compare or two strings and returns true if * they are equal. * * @param s1 The first string to compare. * * @param s2 The second string to compare. * * @returns A boolean value indicating whether the strings' values are * equal in a case sensitive compare. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function stringsAreEqual(s1:String, s2:String, caseSensitive:Boolean):Boolean { if (caseSensitive) { return (s1 == s2); } else { return (s1.toUpperCase() == s2.toUpperCase()); } } } ================================================ FILE: src/utils/string/stripSlashes.as ================================================ package utils.string { /** * Returns the string with slashes removed from all characters specified in the chars parameter * @param str the string to return stripped of slashes * @param chars the string of chars to remove slashes from * @return */ public function stripSlashes(str:String, chars:String = "\""):String { // return the unaltered string if str or chars are null or empty if (!str || !chars) return str; // slash unsafe characters chars = slashUnsafeChars(chars); // build the regular expression that removes the slashes var regex:RegExp = new RegExp("\\\\([" + chars + "])", "g"); // strip the slashes from the specified characters return str.replace(regex, "$1"); } } ================================================ FILE: src/utils/string/stripTags.as ================================================ package utils.string { /** * Strip HTML markup tags. */ public function stripTags(str:String):String { var s:Array = new Array(); var c:Array = new Array(); for (var i:int = 0; i < str.length; i++) { if (str.charAt(i) == "<") { s.push(i); } else if (str.charAt(i) == ">") { c.push(i); } } var o:String = str.substring(0, s[0]); for (var j:int = 0; j < c.length; j++) { o += str.substring(c[j] + 1, s[j + 1]); } return o; } } ================================================ FILE: src/utils/string/toDoubleQuote.as ================================================ package utils.string { /** * Convert single quotes to double quotes. */ public function toDoubleQuote(str:String):String { var sq:String = "'"; var dq:String = String.fromCharCode(34); return str.split(sq).join(dq); } } ================================================ FILE: src/utils/string/toNumeric.as ================================================ package utils.string { /** * Remove all formatting and return cleaned numbers from string. * @example * StringUtils.toNumeric("123-123-1234"); // returns 1221231234 * */ public function toNumeric(str:String):String { var len:Number = str.length; var result:String = ""; for (var i:int = 0; i < len; i++) { var code:Number = str.charCodeAt(i); if (code >= 48 && code <= 57) { result += str.substr(i, 1); } } return result; } } ================================================ FILE: src/utils/string/toSingleQuote.as ================================================ package utils.string { /** * Convert double quotes to single quotes. */ public function toSingleQuote(str:String):String { var sq:String = "'"; var dq:String = String.fromCharCode(34); return str.split(dq).join(sq); } } ================================================ FILE: src/utils/string/toTitleCase.as ================================================ package utils.string { /** * Transforms source String to per word capitalization. */ public function toTitleCase(str:String):String { var lstr:String = str.toLowerCase(); return lstr.replace(/\b([a-z])/g, function($0:*):* { return $0.toUpperCase(); }); } } ================================================ FILE: src/utils/string/trim.as ================================================ package utils.string { /** * Removes whitespace from the front and the end of the specified * string. * * @param value The String whose beginning and ending whitespace will * will be removed. * * @returns A String with whitespace removed from the begining and end * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ public function trim(value:String):String { var out:String = ""; if(value) { out = value.replace(/^\s+|\s+$/g, ""); } return out; } } ================================================ FILE: src/utils/string/trimCamel.as ================================================ package utils.string { /** * Trim spaces and camel notate String. */ public function trimCamel(str:String = null):String { str = (!str) ? "" : str; var o:String = new String(); for (var i:int = 0; i < str.length; i++) { if (str.charAt(i) != " ") { if (justPassedSpace) { o += str.charAt(i).toUpperCase(); justPassedSpace = false; } else { o += str.charAt(i).toLowerCase(); } } else { var justPassedSpace:Boolean = true; } } return o; } } ================================================ FILE: src/utils/string/truncate.as ================================================ package utils.string { /** * Returns the truncated string with an appended ellipsis (...) if the length of str is greater than len. * If the length of str is less than or equal to len, the method returns str unaltered. * @param str the string to truncate * @param len the length to limit the string to * @return */ public function truncate(str:String, len:int):String { // return the string if str is null, empty, or the length of str is less than or equal to len if (!str || str.length <= len) return str; // short str to len str = str.substr(0, len); // trim the right side of whitespace str = str.replace(constants.TRIM_RIGHT_REGEX, ""); // append the ellipsis return str + "..."; } } ================================================ FILE: src/utils/string/truncate2.as ================================================ package utils.string { /** * Returns a String truncated to a specified length with optional suffix. * @param value Input String * @param length Length the String should be shortened to * @param suffix (optional, default="...") String to append to the end of the truncated String * @returns String String truncated to a specified length with optional suffix */ public function truncate2(value:String, length:uint, suffix:String = "..."):String { var out:String = ""; var l:uint = length; if(value) { l -= suffix.length; var trunc:String = value; if(trunc.length > l) { trunc = trunc.substr(0, l); if(/[^\s]/.test(value.charAt(l))) { trunc = rtrim(trunc.replace(/\w+$|\s+$/, "")); } trunc += suffix; } out = trunc; } return out; } } ================================================ FILE: src/utils/string/wordCount.as ================================================ package utils.string { /** * Determines the number of words in a String. * @param value Input String * @returns Number of words in a String * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function wordCount(value:String):uint { var out:uint = 0; if(value) { out = value.match(/\b\w+\b/g).length; } return out; } } ================================================ FILE: src/utils/string/xtrim.as ================================================ package utils.string { /** * Extreme Trim: remove whitespace, line feeds, carriage returns from string */ public function xtrim(str:String = null):String { str = (!str) ? "" : str; var o:String = new String(); var TAB:Number = 9; var LINEFEED:Number = 10; var CARRIAGE:Number = 13; var SPACE:Number = 32; for(var i:int = 0; i < str.length; i++) { if(str.charCodeAt(i) != SPACE && str.charCodeAt(i) != CARRIAGE && str.charCodeAt(i) != LINEFEED && str.charCodeAt(i) != TAB) { o += str.charAt(i); } } return o; } } ================================================ FILE: src/utils/swf/SWFReader.as ================================================ package utils.swf { import flash.display.ActionScriptVersion; import flash.geom.*; import flash.utils.ByteArray; import flash.utils.Endian; /** * Reads the bytes of a SWF (as a ByteArray) to acquire * information from the SWF file header. Some of * this information is inaccessible to ActionScript * otherwise. * * @author Trevor McCauley - www.senocular.com */ public class SWFReader { // properties starting with those // found first in the byte stream /** * Indicates whether or not the SWF * is compressed. */ public var compressed:Boolean; /** * The major version of the SWF. */ public var version:uint; /** * The file size of the SWF. */ public var fileSize:uint; // compression starts here if SWF compressed: /** * The dimensions of the SWF in the form of * a Rectangle instance. */ public function get dimensions():Rectangle { return _dimensions; } private var _dimensions:Rectangle = new Rectangle(); // dimensions gets accessor since we don't // want people nulling the rect; it should // always have a value, even if 0-ed /** * Width of the stage as defined by the SWF. * Same as dimensions.width. */ public function get width():uint { return uint(_dimensions.width); } /** * Height of the stage as defined by the SWF. * Same as dimensions.height. */ public function get height():uint { return uint(_dimensions.height); } /** * When true, the bytes supplied in calls made to the tagCallback * function includes the RECORDHEADER of that tag which includes * the tag and the size of the tag. By default (false) this * information is not included. */ public function get tagCallbackBytesIncludesHeader():Boolean { return _tagCallbackBytesIncludesHeader; } public function set tagCallbackBytesIncludesHeader(value:Boolean):void { _tagCallbackBytesIncludesHeader = value; } private var _tagCallbackBytesIncludesHeader:Boolean = false; /** * The frame rate of the SWF in frames * per second. */ public var frameRate:uint; /** * The total number of frames of the SWF. */ public var totalFrames:uint; /** * ActionScript version. */ public var asVersion:uint; /** * Determines local playback security; when * true, indicates that when this file is * run locally, it can only access the network. * When false, only local files can be accessed. * This does not apply when the SWF is being * run in a local-trusted sandbox. */ public var usesNetwork:Boolean; /** * The background color of the SWF. */ public var backgroundColor:uint; /** * Determines if the SWF is protected from * being imported into an authoring tool. */ public var protectedFromImport:Boolean; /** * Determines if remote debugging is enabled. */ public var debuggerEnabled:Boolean; /** * The XMP metadata defined in the SWF. */ public var metadata:XML; /** * Maximun allowed levels of recursion. */ public var recursionLimit:uint; /** * Time in seconds a script will run in a * single frame before a timeout error * occurs. */ public var scriptTimeoutLimit:uint; /** * The level of hardware acceleration specified * for the SWF. 0 is none, 1 is direct, and 2 * is GPU (Flash Player 10+). */ public var hardwareAcceleration:uint; /** * A callback function that will be called when * a tag is read during the parse process. The * callback function should contain the parameters * (tag:uint, bytes:ByteArray). */ public var tagCallback:Function; /** * Indicates that the SWF bytes last provided * were successfully parsed. If the SWF bytes * were not successfully parsed, no SWF data * will be available. */ public var parsed:Boolean; /** * The Flash Player error message that resulted * from the error that caused a parse to fail. */ public var errorText:String = ""; // keeping track of data private var bytes:ByteArray; private var currentByte:int; // used in bit reading private var bitPosition:int; // used in bit reading private var currentTag:uint; // tag flags private var bgColorFound:Boolean; // constants private const GET_DATA_SIZE:int = 5; private const TWIPS_TO_PIXELS:Number = 0.05; // 20 twips in a pixel private const TAG_HEADER_ID_BITS:int = 6; private const TAG_HEADER_MAX_SHORT:int = 0x3F; private const SWF_C:uint = 0x43; // header characters private const SWF_F:uint = 0x46; private const SWF_W:uint = 0x57; private const SWF_S:uint = 0x53; private const TAG_ID_EOF:uint = 0; // recognized SWF tags private const TAG_ID_BG_COLOR:uint = 9; private const TAG_ID_PROTECTED:uint = 24; private const TAG_ID_DEBUGGER1:uint = 58; private const TAG_ID_DEBUGGER2:uint = 64; private const TAG_ID_SCRIPT_LIMITS:uint = 65; private const TAG_ID_FILE_ATTS:uint = 69; private const TAG_ID_META:uint = 77; private const TAG_ID_SHAPE_1:uint = 2; private const TAG_ID_SHAPE_2:uint = 22; private const TAG_ID_SHAPE_3:uint = 32; private const TAG_ID_SHAPE_4:uint = 83; /** * SWFHeader constructor. * @param swfBytes Bytes of the SWF in a ByteArray. * You can get the bytes of a SWF by loading it into * a URLLoader or using Loader.bytes once a SWF has * been loaded into that Loader. */ public function SWFReader(swfBytes:ByteArray = null) { parse(swfBytes); } /** * Provides a string presentation of the SWFHeader * object which outlines the different values * obtained from a parsed SWF * @return The String form of the instance */ public function toString():String { if (parsed) { var compression:String = (compressed) ? "compressed" : "uncompressed"; var frames:String = totalFrames > 1 ? "frames" : "frame"; return "[SWF" + version + " AS" + asVersion + ".0: " + totalFrames + " " + frames + " @ " + frameRate + " fps " + _dimensions.width + "x" + _dimensions.height + " " + compression + "]"; } // default toString if SWF not parsed return Object.prototype.toString.call(this) as String; } /** * Parses the bytes of a SWF file to extract * properties from its header. * @param swfBytes Bytes of a SWF to parse. */ public function parse(swfBytes:ByteArray):void { parseDefaults(); // null bytes, exit if (swfBytes == null) { parseError("Error: Cannot parse a null value."); return; } // assume at start parse completed successfully // on failure, this will be set to false parsed = true; // -------------------------------------- // HEADER // -------------------------------------- try { // try to parse the bytes. Failures // results in cleared values for the data bytes = swfBytes; bytes.endian = Endian.LITTLE_ENDIAN; bytes.position = 0; // get header characters var swfFC:uint = bytes.readUnsignedByte(); // F, or C if compressed var swfW:uint = bytes.readUnsignedByte(); // W var swfS:uint = bytes.readUnsignedByte(); // S // validate header characters if ((swfFC != SWF_F && swfFC != SWF_C) || swfW != SWF_W || swfS != SWF_S) { parseError("Error: Invalid SWF header."); return; } compressed = Boolean(swfFC == SWF_C); // == SWF_F if not compressed version = bytes.readUnsignedByte(); fileSize = bytes.readUnsignedInt(); // mostly redundant since we should have full bytes // if compressed, need to uncompress // the data after the first 8 bytes // (first 8 already read above) if (compressed) { // use a temporary byte array to // represent the compressed portion // of the SWF file var temp:ByteArray = new ByteArray(); bytes.readBytes(temp); bytes = temp; bytes.endian = Endian.LITTLE_ENDIAN; bytes.position = 0; temp = null; // temp no longer needed bytes.uncompress(); // Note: at this point, the original // uncompressed 8 bytes are no longer // part of the current bytes byte array } _dimensions = readRect(); bytes.position++; // one up after rect frameRate = bytes.readUnsignedByte(); totalFrames = bytes.readUnsignedShort(); } catch (error:Error) { // header parse error parseError(error.message); return; } // -------------------------------------- // TAGS // -------------------------------------- // read all the tags in the file // up until the END tag try { while (readTag()) { // noop } } catch (error:Error) { // error in tag parsing. EOF would throw // an error, but the END tag should be // reached before that occurs parseError(error.message); return; } // parse completed successfully! // null bytes since no longer needed bytes = null; } /** * Defines default values for all the class * properties. This is used to have accurate * values for properties which may not be * present in the SWF file such as asVersion * which is only required to be specified in * SWF8 and above (in FileAttributes tag). */ private function parseDefaults():void { compressed = false; version = 1; // SWF1 fileSize = 0; _dimensions = new Rectangle(); frameRate = 12; // default from Flash authoring (flex == 24) totalFrames = 1; metadata = null; asVersion = ActionScriptVersion.ACTIONSCRIPT2; // 2 if not explicit usesNetwork = false; backgroundColor = 0xFFFFFF; // white background protectedFromImport = false; debuggerEnabled = true; scriptTimeoutLimit = 256; recursionLimit = 15; hardwareAcceleration = 0; errorText = ""; // clear existing error text // tag helper flags bgColorFound = false; } /** * Clears variable data and logs an error * message. */ private function parseError(message:String = "Unkown error."):void { compressed = false; version = 0; fileSize = 0; _dimensions = new Rectangle(); frameRate = 0; totalFrames = 0; metadata = null; asVersion = 0; usesNetwork = false; backgroundColor = 0; protectedFromImport = false; debuggerEnabled = false; scriptTimeoutLimit = 0; recursionLimit = 0; hardwareAcceleration = 0; parsed = false; bytes = null; errorText = message; } /** * Utility to convert a unit value into a string * in hex style padding value with "0" characters. * @return The string representation of the hex value. */ private function paddedHex(value:uint, numChars:int = 6):String { var str:String = value.toString(16); while (str.length < numChars) str = "0" + str; return "0x" + str; } /** * Reads a string in the byte stream by * reading all bytes until a null byte (0) * is reached. * @return The string having been read. */ private function readString():String { // find ending null character that // terminates the string var i:uint = bytes.position; try { while (bytes[i] != 0) i++; } catch (error:Error) { return ""; } // null byte should have been found // return the read string return bytes.readUTFBytes(i - bytes.position); } /** * Reads RECT data from the current * location in the current bytes object * @return A rectangle object whose values * match those of the RECT read. */ private function readRect():Rectangle { nextBitByte(); var rect:Rectangle = new Rectangle(); var dataSize:uint = readBits(GET_DATA_SIZE); rect.left = readBits(dataSize, true) * TWIPS_TO_PIXELS; rect.right = readBits(dataSize, true) * TWIPS_TO_PIXELS; rect.top = readBits(dataSize, true) * TWIPS_TO_PIXELS; rect.bottom = readBits(dataSize, true) * TWIPS_TO_PIXELS; return rect; } private function readMatrix():Matrix { nextBitByte(); var dataSize:uint; var matrix:Matrix = new Matrix(); if (readBits(1)) { // has scale dataSize = readBits(GET_DATA_SIZE); matrix.a = readBits(dataSize, true); matrix.d = readBits(dataSize, true); } if (readBits(1)) { // has rotation dataSize = readBits(GET_DATA_SIZE); matrix.b = readBits(dataSize, true); matrix.c = readBits(dataSize, true); } // translation dataSize = readBits(GET_DATA_SIZE); matrix.tx = readBits(dataSize, true) * TWIPS_TO_PIXELS; matrix.ty = readBits(dataSize, true) * TWIPS_TO_PIXELS; return matrix; } /** * Reads a series of bits from the current byte * defined by currentByte based on the but at * position bitPosition. If more bits are required * than are available in the current byte, the next * byte in the bytes array is read and the bits are * taken from there to complete the request. * @param numBits The number of bits to read. * @return The bits read as a uint. */ private function readBits(numBits:uint, signed:Boolean = false):Number { var value:Number = 0; // int or uint var remaining:uint = 8 - bitPosition; var mask:uint; // can get all bits from current byte if (numBits <= remaining) { mask = (1 << numBits) - 1; value = (currentByte >> (remaining - numBits)) & mask; if (numBits == remaining) nextBitByte(); else bitPosition += numBits; // have to get bits from 2 (or more) // bytes the current and the next (recursive) } else { mask = (1 << remaining) - 1; var firstValue:uint = currentByte & mask; var over:uint = numBits - remaining; nextBitByte(); value = (firstValue << over) | readBits(over); } // convert to signed int if signed bitflag exists if (signed && value >> (numBits - 1) == 1) { remaining = 32 - numBits; // 32-bit uint mask = (1 << remaining) - 1; return int(mask << numBits | value); } // unsigned int return uint(value); } /** * Reads the next byte in the stream assigning * it to currentByte and resets the value of * bitPosition to 0. */ private function nextBitByte():void { currentByte = bytes.readByte(); bitPosition = 0; } /** * Parses the tag at the current byte location. * @return false if the tag read is the END tag; * true if more tags should be present in the file. */ private function readTag():Boolean { var currentTagPosition:uint = bytes.position; // read tag header var tagHeader:int = bytes.readUnsignedShort(); currentTag = tagHeader >> TAG_HEADER_ID_BITS; var tagLength:uint = tagHeader & TAG_HEADER_MAX_SHORT; // if a long tag, the tag length will be // set to its maximum. If so, set // the tag length to the long length if (tagLength == TAG_HEADER_MAX_SHORT) { tagLength = bytes.readUnsignedInt(); } // when the tag is read, the position // of the byte stream must be set to the // end of this tag for the start of the next // tag. This assures the correct position // no matter what happens in readTagData() var nextTagPosition:uint = bytes.position + tagLength; // read the data in the tag (if supported) var moreTags:Boolean = readTagData(tagLength, currentTagPosition, nextTagPosition); if (!moreTags) return false; // end tag // next tag bytes.position = nextTagPosition; return true; } /** * Called from readTag, this parses the value of individual * tag based on the tag id read in the tag header. * @param tag A tag object containing a tag's id and length. * @param start The start position of the full tag. * @param end The end position of the full tag. * @return false if the tag read is the END tag; * true if more tags should be present in the file. */ private function readTagData(tagLength:uint, start:uint, end:uint):Boolean { // if defined, call the tag callback with // the tag id and a copy of the bytes // specific to the tag if (tagCallback != null) { var tagBytes:ByteArray = new ByteArray(); if (_tagCallbackBytesIncludesHeader) { tagBytes.writeBytes(bytes, start, end - start); } else { if (tagLength) { tagBytes.writeBytes(bytes, bytes.position, tagLength); } } tagBytes.position = 0; tagCallback(currentTag, tagBytes); } // handle each tag individually based on // it's tag id switch (currentTag) { // FileAttributes tag was only required for // SWF 8 and later. Calling defaults() // assures default values for the properties // determined here if the tag is not present case TAG_ID_FILE_ATTS: nextBitByte(); // read file attributes in bits readBits(1); // reserved hardwareAcceleration = readBits(2); readBits(1); // hasMetaData; auto-determined by tag asVersion = (readBits(1) && version >= 9) ? ActionScriptVersion.ACTIONSCRIPT3 : ActionScriptVersion.ACTIONSCRIPT2; readBits(2); // reserved (2) usesNetwork = Boolean(readBits(1) == 1); // bunch of others reserved after this break; // Metadata in a SWF is in the format of // XMP XML. Though the FileAttributes will // determine if it is present, it's easier to // just check for the metadata tag id case TAG_ID_META: try { metadata = new XML(readString()); } catch (error:Error) { // error reading string or parsing as XML } break; // Many background colors could potentially exist // for a single SWF, but we're assuming there's // only one. If there are more, the first will be used case TAG_ID_BG_COLOR: // check the bg color found flag // if true, we want to ignore all other colors // since they would be added after this one if (!bgColorFound) { bgColorFound = true; backgroundColor = readRGB(); } break; // Only determines if the SWF is protected from // import; a password, if provided, will not // be retrieved from the SWF case TAG_ID_PROTECTED: protectedFromImport = Boolean(bytes.readUnsignedByte() != 0); // password if needed break; // the debugger 1 tag is for SWF5 only // the debugger 2 tag is for SWF6+ case TAG_ID_DEBUGGER1: if (version == 5) debuggerEnabled = true; // password if needed break; case TAG_ID_DEBUGGER2: if (version > 5) debuggerEnabled = true; // password if needed break; // for both timeout and recursion but I don't // think any tool lets you set recursion case TAG_ID_SCRIPT_LIMITS: recursionLimit = bytes.readUnsignedShort(); scriptTimeoutLimit = bytes.readUnsignedShort(); break; case TAG_ID_EOF: return false; // end of file break; default: // unrecognized tag by this parser; do nothing // if you want to support other tags // make sure they're caught above in // this switch statement. break; } // not last tag, continue reading return true; } private function readRGB():uint { return (bytes.readUnsignedByte() << 16) // R | (bytes.readUnsignedByte() << 8) // G | bytes.readUnsignedByte(); // B } private function readARGB():uint { return (bytes.readUnsignedByte() << 24) // A | (bytes.readUnsignedByte() << 16) // R | (bytes.readUnsignedByte() << 8) // G | bytes.readUnsignedByte(); // B } private function readRGBA():uint { var rByte:uint = bytes.readUnsignedByte(); // R var gByte:uint = bytes.readUnsignedByte(); // G var bByte:uint = bytes.readUnsignedByte(); // B var aByte:uint = bytes.readUnsignedByte(); // A return (aByte << 24) // A | (rByte << 16) // R | (gByte << 8) // G | bByte; // B } } } ================================================ FILE: src/utils/textField/TextFieldWrapper.as ================================================ package utils.textField { import flash.display.MovieClip; import flash.text.TextField; /** * Because TextFields are not MovieClips, you cannot do timeline * tweens on a TextField in Flash CSx without first making it a child * of a MovieClip. * * This class acts as a base class for creating these types of movieclips * so you don't need to create a new class for each text field that * does this. * * In the flash library, create a new movieclip symbol containing the * textField. Make sure you set the instance name for the text field to * "textField". Make the base class for the symbol * "util.textfield.TextFieldWrapper". Allow Flash to automatically * generate the class for you. * When referencing this MovieClip in your code, use the type * AbstractTextFieldWrapper insatead of MovieClip. You will be able to set * the text of the TextField using the .text property. * * @author Mims H. Wright */ public class TextFieldWrapper extends MovieClip { /** * Direct reference to the text field. */ public var textField:TextField; /** Passes the text through to the text field. */ public function set text(text:String):void { textField.text = text; } public function get text():String { return textField.text; } public function TextFieldWrapper() { super(); } } } ================================================ FILE: src/utils/textField/clearFields.as ================================================ package utils.textField { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.text.TextField; /** * Clear a TextField text or to all TextField's texts in a DisplayObjectContainer. * @param o DisplayObject that either is or contains TextField's. */ public function clearFields(o:DisplayObject):void { var tf:TextField; if (o is TextField) { tf = o as TextField; tf.text = tf.htmlText = ''; } else if (o is DisplayObjectContainer) { var container:DisplayObjectContainer = o as DisplayObjectContainer; for (var i:int = 0; i < container.numChildren; i++) { if (container.getChildAt(i) is TextField) { tf = container.getChildAt(i) as TextField; tf.text = tf.htmlText = ''; } } } } } ================================================ FILE: src/utils/textField/createField.as ================================================ package utils.textField { import flash.text.StyleSheet; import flash.text.TextField; import flash.text.TextFormat; /** * Create a TextField instance and return it. */ public function createField(str:String, x:Number = 0, y:Number = 0, width:Number = 200, height:Number = 20, multiline:Boolean = false, font:String = "Verdana", size:Number = 9, color:uint = 0, autoSize:String = 'left', embedFonts:Boolean = false, selectable:Boolean = false, css:StyleSheet = null):TextField { var tf:TextField = new TextField(); var fmt:TextFormat = new TextFormat(font, size, color); tf.x = x; tf.y = y; tf.width = width; tf.height = height; tf.autoSize = autoSize; tf.embedFonts = embedFonts; tf.selectable = selectable; tf.multiline = multiline; tf.textColor = color; tf.defaultTextFormat = fmt; tf.htmlText = str; tf.styleSheet = css; return tf; } } ================================================ FILE: src/utils/textField/formatFields.as ================================================ package utils.textField { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.text.TextField; import flash.text.TextFormat; /** * Apply a TextFormat to a TextField or to all TextField's in a DisplayObjectContainer. * @param o DisplayObject that either is or contains TextField's. * @param textFormat to apply to the TextField's. */ public function formatFields(o:DisplayObject, textFormat:TextFormat):void { var tf:TextField; if (o is TextField) { tf = o as TextField; tf.setTextFormat(textFormat); } else if (o is DisplayObjectContainer) { var container:DisplayObjectContainer = o as DisplayObjectContainer; for (var i:int = 0; i < container.numChildren; i++) { if (container.getChildAt(i) is TextField) { tf = container.getChildAt(i) as TextField; tf.setTextFormat(textFormat); } } } } } ================================================ FILE: src/utils/textField/getUsableFonts.as ================================================ package utils.textField { import flash.text.Font; /** * Searches the client's available fonts to see if any of the Font from the desiredFontList are available. * @param desiredFontList array of desired fontName's. * @return array of desired fonts which are available for use on the client's system. */ public function getUsableFonts(desiredFontList:Array):Array { var clientFontList:Array = Font.enumerateFonts(true); var availableFontList:Array = new Array(); for (var i:Number = 0; i < desiredFontList.length; i++) { for (var j:Number = 0; j < clientFontList.length; j++) { if (desiredFontList[i] == Font(clientFontList[j]).fontName) { availableFontList.push(desiredFontList[i]); } } } return (availableFontList.length >= 1) ? availableFontList : null; } } ================================================ FILE: src/utils/textField/hideFields.as ================================================ package utils.textField { import flash.text.TextField; /** * Hide a TextField or TextField's from display (visible false, alpha 0). * @see #reveal */ public function hideFields(... args):void { for (var i:int = 0; i < args.length; i++) { if (args[i] is TextField) { args[i].alpha = 0; args[i].visible = false; } } } } ================================================ FILE: src/utils/textField/revealFields.as ================================================ package utils.textField { import flash.text.TextField; /** * Reveal a TextField or TextField's (visible true, alpha 1) * @see #hide */ public function revealFields(... args):void { for (var i:int = 0; i < args.length; i++) { if (args[i] is TextField) { args[i].alpha = 1; args[i].visible = true; } } } } ================================================ FILE: src/utils/textField/setFormattedText.as ================================================ package utils.textField { import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFieldType; import flash.text.TextFormat; import utils.validation.isBlank; /** * Set the text of a TextField while preserving the formatting (leading, kerning, etc). * XXX - Warning: htmlText and styles can break the formatting: no known fix as of yet. */ public function setFormattedText(tf:TextField, str:String, autoSize:Boolean = true):void { var s:String = (isBlank(str)) ? " " : str; if (autoSize) { tf.autoSize = TextFieldAutoSize.LEFT; } var textFormat:TextFormat = tf.getTextFormat(); if (tf.type == TextFieldType.INPUT) { tf.text = s; } else { tf.htmlText = s; } tf.setTextFormat(textFormat); } } ================================================ FILE: src/utils/textField/setStyledText.as ================================================ package utils.textField { import flash.text.StyleSheet; import flash.text.TextField; /** * Apply a StyleSheet to a TextField & set its contents. * * @param tf TextField to display. * @param str of text to apply. * @param stylesheet to apply to the TextField's (Default: App.css). * * @see sekati.core.App#css */ public function setStyledText(tf:TextField, str:String, stylesheet:StyleSheet = null):void { styleFields(tf, stylesheet); tf.htmlText = str; } } ================================================ FILE: src/utils/textField/setTextColor.as ================================================ package utils.textField { import flash.text.TextField; /** * Set the TextField color formatting. */ public function setTextColor(tf:TextField, color:uint, backgroundColor:uint, borderColor:uint):void { tf.textColor = color; tf.background = true; tf.backgroundColor = backgroundColor; tf.border = true; tf.borderColor = borderColor; } } ================================================ FILE: src/utils/textField/setTextFont.as ================================================ package utils.textField { import flash.text.TextField; import flash.text.TextFormat; /** * Set the TextField font formatting. */ public function setTextFont(tf:TextField, fontName:String, fontSize:Number, isEmbedFont:Boolean = false, isBold:Boolean = false, isItalic:Boolean = false, isUnderline:Boolean = false):void { var fmt:TextFormat = tf.getTextFormat(); fmt.font = fontName; fmt.size = fontSize; fmt.italic = isItalic; fmt.bold = isBold; fmt.underline = isUnderline; tf.embedFonts = isEmbedFont; tf.setTextFormat(fmt); } } ================================================ FILE: src/utils/textField/setTextLeading.as ================================================ package utils.textField { import flash.text.TextField; import flash.text.TextFormat; /** * Set the TextField leading formatting. */ public function setTextLeading(tf:TextField, space:Number = 0):void { var fmt:TextFormat = tf.getTextFormat(); fmt.leading = space; tf.setTextFormat(fmt); } } ================================================ FILE: src/utils/textField/setTextLetterSpacing.as ================================================ package utils.textField { import flash.text.TextField; import flash.text.TextFormat; /** * Set the TextField letter spacing formatting. */ public function setTextLetterSpacing(tf:TextField, spacing:Number = 0):void { var fmt:TextFormat = tf.getTextFormat(); fmt.letterSpacing = spacing; tf.setTextFormat(fmt); } } ================================================ FILE: src/utils/textField/setTextSpaceWidth.as ================================================ package utils.textField { import flash.text.TextField; import flash.text.TextFormat; /** * Set the TextField's width for space characters. */ public function setTextSpaceWidth(tf:TextField, space:Number = 1):void { var fmt:TextFormat = new TextFormat(); fmt.letterSpacing = space; var i:int = 0; while (tf.text.indexOf(" ", i) > -1) { var index:int = tf.text.indexOf(" ", i); tf.setTextFormat(fmt, index, index + 1); i = index + 1; } } } ================================================ FILE: src/utils/textField/styleFields.as ================================================ package utils.textField { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.text.StyleSheet; import flash.text.TextField; /** * Apply the application stylesheet to a TextField or to all TextField's in a DisplayObjectContainer. * *

Warning: Unlike formatFields you must reset your htmlText to have the style applied.

* @param o DisplayObject that either is or contains TextField's. * @param stylesheet to apply to the TextField's (Default: App.css). * @see sekati.core.App#css */ public function styleFields(o:DisplayObject, stylesheet:StyleSheet):void { var tf:TextField; var css:StyleSheet = stylesheet; if (o is TextField) { tf = o as TextField; tf.styleSheet = css; } else if (o is DisplayObjectContainer) { var container:DisplayObjectContainer = o as DisplayObjectContainer; for (var i:int = 0; i < container.numChildren; i++) { if (container.getChildAt(i) is TextField) { tf = container.getChildAt(i) as TextField; tf.styleSheet = css; } } } } } ================================================ FILE: src/utils/textField/truncateMultilineText.as ================================================ package utils.textField { import flash.text.TextField; /** * Truncate a multiline TextField after the defined number of lines of text. * @param tf TextField to truncate. * @param numAlllowedLines before the remaining text is removed. * @param isEllipsed determines whether the text is ended with "..." or not. */ public function truncateMultilineText(tf:TextField, numAlllowedLines:uint, isEllipsed:Boolean = true):void { if (tf.bottomScrollV > numAlllowedLines) { var len:int = tf.text.length; for (var i:int = 0; i < len; i++) { tf.scrollV = tf.maxScrollV; if (tf.bottomScrollV > numAlllowedLines) { tf.text = tf.text.slice(0, -1); } else { var e:int = (isEllipsed) ? -3 : tf.text.lastIndexOf(" "); tf.text = tf.text.slice(0, e); tf.appendText("..."); break; } } } } } ================================================ FILE: src/utils/textField/truncateText.as ================================================ package utils.textField { import flash.text.TextField; import flash.text.TextFieldAutoSize; /** * Truncate a single-line TextField to a specific width. * @param tf the textfield to truncate. * @param maxWidth the desired text width to truncate at. * @param isEllipsed denotes whether to truncate with the ellipse char "...". * @param isLineEllipse gives the option to "ellipse" the entire width of the field. */ public function truncateText(tf:TextField, maxWidth:Number, isEllipsed:Boolean = true, isLineEllipse:Boolean = false):void { var ellipse:String = '...'; // save the autosize settings for renewal at the end ... var autoSizeSetting:String = tf.autoSize; tf.autoSize = TextFieldAutoSize.NONE; // subtract a touch of length from the max width to insure no visual overflow ... //maxWidth = (!isLongEllipse) ? (maxWidth - 5) : (maxWidth -= 10); // don't ellipse if we fit under the max width. if (tf.textWidth <= maxWidth && !isLineEllipse) { return; } // hide the field momentarily so the user doesnt see our tests ... //tf.visible = false; // save the original text string & it's length var str:String = tf.htmlText; var strLength:Number = str.length; // save the (stereotypical fonts) widest character's width: "W" tf.htmlText = "W"; var wCharWidth:Number = tf.textWidth; // save the (stereotypical fonts) medium character's width: "A" tf.text = "A"; var aCharWidth:Number = tf.textWidth; // the max num of (the largest) chars which our max desired width can hold. var ptr:Number = Math.floor(maxWidth / wCharWidth); // collect the portion of the string which represents the max large chars (ptr) and add it to the field. var checkStr:String = str.substr(0, ptr); tf.text = checkStr; // Now that we have a baseline set below our maxWidth we can start adding/testing characters: // in this way we optimize the number of loops which must be performed which *greatly* improves // performance rather than adding/testing thru the entire string (this is especially important // when using the method on many long texted TextFields: smart, huh? var cnt:Number; while (tf.textWidth < maxWidth) { // see if we can fit one or more standard characters in the space remaining: if we cant: bail. cnt = Math.floor((maxWidth - tf.textWidth) / aCharWidth); if (cnt == 0) { break; } // increase the max chars: if we accidentally went above the str length: fix er up ... ptr += cnt; ptr = (ptr > strLength) ? strLength : ptr; // once again set a slice of our max fitting chars to the field. checkStr = str.substr(0, ptr); tf.htmlText = checkStr; // if our max fitting chars is the same as the string length: bail too. if (strLength == ptr) { break; } } // if we want to ellipse apply it to the field. if (isEllipsed) { tf.appendText(ellipse); } // again check if we've exceeded the max desired width ... if (tf.textWidth > maxWidth) { // if we have remove a character and test again. while (tf.textWidth > maxWidth) { checkStr = checkStr.substr(0, -1); tf.htmlText = isEllipsed ? (checkStr + ellipse) : checkStr; } } // alright - things fit perfectly now! However; maybe you want it to // "ellipse" thru the entire length of the field for visual effect? // // TODO - Warning: this functions but is not perfect: can be optimized and made more accurate. // if (isLineEllipse) { var tmpField:TextField = new TextField(); tmpField.width = tf.width; tmpField.setTextFormat(tf.getTextFormat()); // save the (stereotypical fonts) smallest character's width: "." tmpField.htmlText = "."; var periodCharWidth:Number = tmpField.textWidth; tmpField.htmlText = ""; var whiteSpaceWidth:Number = tmpField.width - tf.textWidth; var i:Number = Math.floor(whiteSpaceWidth / periodCharWidth); while (i-- > 0) { tmpField.appendText("."); } if (whiteSpaceWidth < tmpField.textWidth) { while (whiteSpaceWidth < tmpField.textWidth) { tmpField.htmlText = tmpField.text.substr(0, -1); } } else if (whiteSpaceWidth > tmpField.textWidth) { while (tmpField.textWidth < whiteSpaceWidth) { tmpField.appendText("."); } tmpField.htmlText = tmpField.text.substr(0, -1); } tf.appendText(tmpField.text); } // restore the settings and make the text visible again... tf.autoSize = autoSizeSetting; //tf.visible = true; // defer rendering if the field is on stage to avoid the flickering of the char tests... //if(tf.stage != null) tf.stage.invalidate( ); } } ================================================ FILE: src/utils/type/PACKAGE_CLASS_SEPARATOR.as ================================================ package utils.type { [ExcludeClass] const PACKAGE_CLASS_SEPARATOR:String = "::"; } ================================================ FILE: src/utils/type/convertFullyQualifiedName.as ================================================ package utils.type { /** * Converts the double colon (::) in a fully qualified class name to a dot (.) */ public function convertFullyQualifiedName(className:String):String { return className.replace(PACKAGE_CLASS_SEPARATOR, "."); } } ================================================ FILE: src/utils/type/describeInheritance.as ================================================ package utils.type { /** * Targeted reflection describing an object's inheritance, including * extended classes and implemented interfaces. * * @param value The object or class to introspect. * * @return A list of XML inheritance descriptions. */ public function describeInheritance(value:Object):XMLList { return describeType(value).factory.*.(localName() == "extendsClass" || localName() == "implementsInterface"); } } ================================================ FILE: src/utils/type/describeMethods.as ================================================ package utils.type { /** * Targeted reflection describing an object's methods. * @param value The object or class to introspect. * @param metadataType Optional filter to return only those * method descriptions containing the * specified metadata. * @return A list of XML method descriptions. */ public function describeMethods(value:Object, metadataType:String = null):XMLList { var methods:XMLList = describeType(value).factory.method; return (metadataType == null) ? methods : methods.(child("metadata").(@name == metadataType).length() > 0); } } ================================================ FILE: src/utils/type/describeProperties.as ================================================ package utils.type { /** * Targeted reflection describing an object's properties, including both * accessor (getter/setters) and pure properties. * @param value The object or class to introspect. * @param metadataType Optional filter to return only those * property descriptions containing the * specified metadata. * @return A list of XML property descriptions. */ public function describeProperties(value:Object, metadataType:String = null):XMLList { var properties:XMLList = describeType(value).factory.*.(localName() == "accessor" || localName() == "variable"); return (metadataType == null) ? properties : properties.(child("metadata").(@name == metadataType).length() > 0); } } ================================================ FILE: src/utils/type/describeType.as ================================================ package utils.type { /** * Primary reflection method, producing an XML description of the object * or class specified. Results are cached internally for performance. * * @param value The object or class to introspect. * @param refreshCache Forces a new description to be generated, * useful only when a class alias has changed. * * @return An XML description, which format is * documented in the flash.utils * package. * * @see flash.utils#describeType */ import flash.utils.describeType; public function describeType(value:Object, refreshCache:Boolean = false):XML { if (!(value is Class)) { value = getType(value); } if (refreshCache || typeCache[value] == null) { typeCache[value] = flash.utils.describeType(value); } return typeCache[value]; } } ================================================ FILE: src/utils/type/forInstance.as ================================================ package utils.type { import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; /** * Returns a Class object that corresponds with the given * instance. If no corresponding class was found, a * ClassNotFoundError will be thrown. * @param instance the instance from which to return the class * @param applicationDomain the optional applicationdomain where the instance's class resides * @return the Class that corresponds with the given instance */ public function forInstance(instance:*, applicationDomain:ApplicationDomain = null):Class { applicationDomain = (applicationDomain == null) ? ApplicationDomain.currentDomain : applicationDomain; var className:String = getQualifiedClassName(instance); return forName(className, applicationDomain); } } ================================================ FILE: src/utils/type/forName.as ================================================ package utils.type { import flash.system.ApplicationDomain; /** * Returns a Class object that corresponds with the given * name. If no corresponding class was found in the applicationdomain tree, a * ClassNotFoundError will be thrown. * @param name the name from which to return the class * @param applicationDomain the optional applicationdomain where the instance's class resides * @return the Class that corresponds with the given name */ public function forName(name:String, applicationDomain:ApplicationDomain = null):Class { applicationDomain = (applicationDomain == null) ? ApplicationDomain.currentDomain : applicationDomain; var result:Class; if(!applicationDomain) { applicationDomain = ApplicationDomain.currentDomain; } while(!applicationDomain.hasDefinition(name)) { if(applicationDomain.parentDomain) { applicationDomain = applicationDomain.parentDomain; } else { break; } } try { result = applicationDomain.getDefinition(name) as Class; } catch (e:ReferenceError) { throw new Error("A class with the name '" + name + "' could not be found."); } return result; } } ================================================ FILE: src/utils/type/getClass.as ================================================ package utils.type { import flash.display.DisplayObject; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; /** * Get the class of an object * @param obj Object to get the class of * @return The class of the given object or null if the class cannot be * determined * @author Jackson Dunstan */ public function getClass(obj:Object):Class { if (obj == null) { return null; } try { var className:String = getQualifiedClassName(obj); var ret:Class = Class(getDefinitionByName(className)); if (ret == null && obj is DisplayObject) { ret = getDisplayObjectClass(DisplayObject(obj)); } return ret; } catch (refErr:ReferenceError) { return null; } catch (typeErr:TypeError) { return null; } return null; } } ================================================ FILE: src/utils/type/getClassByName.as ================================================ package utils.type { import flash.utils.getDefinitionByName; /** * Get a class by its fully-qualified name * @param className Fully-qualified name of the class * @return The class with the given name or null if none exists * @author Jackson Dunstan */ public function getClassByName(className:String):Class { try { return Class(getDefinitionByName(className)); } catch (refErr:ReferenceError) { return null; } catch (typeErr:TypeError) { return null; } return null; } } ================================================ FILE: src/utils/type/getClassName.as ================================================ package utils.type { import flash.utils.getQualifiedClassName; /** * Returns the exact class name, without package or path. * * @param value The object for which the class name is desired. * Any ActionScript value may be passed including * all ActionScript types, object instances, * primitive types such as uint, and class objects. */ public function getClassName(value:Object):String { return getQualifiedClassName(value).split("::").pop(); } } ================================================ FILE: src/utils/type/getDisplayObjectClass.as ================================================ package utils.type { import flash.display.DisplayObject; import flash.utils.getQualifiedClassName; /** * Get the class of a display object * @param obj Object to get the class of * @return The class of the given object or null if the class cannot be * determined * @author Jackson Dunstan */ public function getDisplayObjectClass(obj:DisplayObject):Class { try { return Class(obj.loaderInfo.applicationDomain.getDefinition(getQualifiedClassName(obj))); } catch (refErr:ReferenceError) { return null; } catch (typeErr:TypeError) { return null; } return null; } } ================================================ FILE: src/utils/type/getFullyQualifiedName.as ================================================ package utils.type { import flash.utils.getQualifiedClassName; /** * Returns the fully qualified name of the given class. * * @param clazz the class to get the name from * @param replaceColons whether the double colons "::" should be replaced by a dot "." * the default is false * * @return the fully qualified name of the class */ public function getFullyQualifiedName(clazz:Class, replaceColons:Boolean = false):String { var result:String = getQualifiedClassName(clazz); if (replaceColons) { result = convertFullyQualifiedName(result); } return result; } } ================================================ FILE: src/utils/type/getFullyQualifiedSuperClassname.as ================================================ package utils.type { import flash.utils.getQualifiedSuperclassName; /** * Returns the fully qualified name of the given class' superclass. * * @param clazz the class to get its superclass' name from * @param replaceColons whether the double colons "::" should be replaced by a dot "." * the default is false * * @return the fully qualified name of the class' superclass */ public function getFullyQualifiedSuperClassname(clazz:Class, replaceColons:Boolean = false):String { var result:String = getQualifiedSuperclassName(clazz); if (replaceColons) { result = convertFullyQualifiedName(result); } return result; } } ================================================ FILE: src/utils/type/getName.as ================================================ package utils.type { /** * Returns the name of the given class. * * @param clazz the class to get the name from * * @return the name of the class */ public function getName(clazz:Class):String { return getNameFromFullyQualifiedName(getFullyQualifiedName(clazz)); } } ================================================ FILE: src/utils/type/getNameFromFullyQualifiedName.as ================================================ package utils.type { /** * Returns the name of the class or interface, based on the given fully * qualified class or interface name. * * @param fullyQualifiedName the fully qualified name of the class or interface * * @return the name of the class or interface */ public function getNameFromFullyQualifiedName(fullyQualifiedName:String):String { var result:String = ""; var startIndex:int = fullyQualifiedName.indexOf(PACKAGE_CLASS_SEPARATOR); if (startIndex == -1) { result = fullyQualifiedName; } else { result = fullyQualifiedName.substring(startIndex + PACKAGE_CLASS_SEPARATOR.length, fullyQualifiedName.length); } return result; } } ================================================ FILE: src/utils/type/getPropertyType.as ================================================ package utils.type { import flash.utils.getDefinitionByName; /** * Determines the property type without accessing the property directly. * Evaluation is based on the property definition and not by its value. * * @param value An object or class containing the property * definition to evaluate. * @param property The name of the property to be evaluated * * @return The class definition of the property type, * as described by the property definition, or * null if no definition was found. */ public function getPropertyType(value:Object, property:String):Class { if (!(value is Class) && !(property in value)) { return null; } // retrieve the correct property from the property list var propList:XMLList = describeProperties(value).(@name == property); return (propList.length() > 0) ? getDefinitionByName(propList[0].@type) as Class : null; } } ================================================ FILE: src/utils/type/getSuperClassName.as ================================================ package utils.type { /** * Returns the name of the given class' superclass. * * @param clazz the class to get the name of its superclass' from * * @return the name of the class' superclass */ public function getSuperClassName(clazz:Class):String { var fullyQualifiedName:String = getFullyQualifiedSuperClassname(clazz); var index:int = fullyQualifiedName.indexOf(PACKAGE_CLASS_SEPARATOR) + PACKAGE_CLASS_SEPARATOR.length; return fullyQualifiedName.substring(index, fullyQualifiedName.length); } } ================================================ FILE: src/utils/type/getType.as ================================================ package utils.type { import flash.utils.Proxy; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; public function getType(value:Object):Class { if (value is Class) { return value as Class; } else if (value is Proxy) { return getDefinitionByName(getQualifiedClassName(value)) as Class; } else { return value.constructor as Class; } } } ================================================ FILE: src/utils/type/isInterface.as ================================================ package utils.type { /** * Returns whether the passed in Class object is an interface. * * @param clazz the class to check * @return true if the clazz is an interface; false if not */ public function isInterface(clazz:Class):Boolean { return (clazz == Object) ? false : (describeType(clazz).factory.extendsClass.length() == 0); } } ================================================ FILE: src/utils/type/isPassedByValue.as ================================================ package utils.type { /** * Checks to see if the class of instance is a primitive which will be copied by value * rather than by pointer. * The primitive types checked for are : * Number * int * uint * String * Boolean * * @author Mims Wright * * @param instance - the object whos class you want to check. * @return true if instance is is a primitive value or false if null or otherwise. */ public function isPassedByValue(instance:*):Boolean { if (instance == null) return false; //if (!isNaN(instance)) return true; if (instance is Number) return true; if (instance is int) return true; if (instance is uint) return true; if (instance is String) return true; if (instance is Boolean) return true; return false; } } ================================================ FILE: src/utils/type/isType.as ================================================ package utils.type { import flash.utils.getQualifiedClassName; /** * Evaluates whether an object or class is derived from a specific * data type, class or interface. The isType() method is comparable to * ActionScript's is operator except that it also makes * class to class evaluations. * * @param value The object or class to evaluate. * @param type The data type to check against. * * @return True if the object or class is derived from * the data type. */ public function isType(value:Object, type:Class):Boolean { if (!(value is Class)) { return value is type; } if (value == type) { return true; } var inheritance:XMLList = describeInheritance(value); return Boolean(inheritance.(@type == getQualifiedClassName(type)).length() > 0); } } ================================================ FILE: src/utils/type/newInstance.as ================================================ package utils.type { /** * Creates an instance of the given class and passes the arguments to * the constructor. * * * @param clazz the class from which an instance will be created * @param args the arguments that need to be passed to the constructor */ public function newInstance(clazz:Class, args:Array = null):* { var result:*; var a:Array = (args == null) ? [] : args; if(args.length > 10) throw new Error("newInstance has a limit of 10 arguments."); switch (a.length) { case 1: result = new clazz(a[0]); break; case 2: result = new clazz(a[0], a[1]); break; case 3: result = new clazz(a[0], a[1], a[2]); break; case 4: result = new clazz(a[0], a[1], a[2], a[3]); break; case 5: result = new clazz(a[0], a[1], a[2], a[3], a[4]); break; case 6: result = new clazz(a[0], a[1], a[2], a[3], a[4], a[5]); break; case 7: result = new clazz(a[0], a[1], a[2], a[3], a[4], a[5], a[6]); break; case 8: result = new clazz(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]); break; case 9: result = new clazz(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); break; case 10: result = new clazz(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9]); break; default: result = new clazz(); } return result; } } ================================================ FILE: src/utils/type/registerType.as ================================================ package utils.type { import flash.net.registerClassAlias; import flash.utils.getQualifiedClassName; /** * Ensures a class has a registered alias for object serialization and * remoting. If the class doesn't yet have an alias it will be * registered with it's full qualified class name, for example: * flight.utils.Type. If the class has already been * assigned an alias then its previous registration will be honored. * * @param value The object or class to register. * * @return True if the registration was successful, * otherwise the object already has an alias. * * @see flash.net#registerClassAlias */ public function registerType(value:Object):Boolean { if (!(value is Class)) { value = getType(value); } // if not already registered var alias:String = describeType(value).@alias; if (alias.length) { return false; } registerClassAlias(getQualifiedClassName(value).split("::").join("."), value as Class); return true; } } ================================================ FILE: src/utils/type/strictIs.as ================================================ package utils.type { /** * Checks the class of instance against the compareClass for strict * equality. If the classes are exactly the same, returns true. If * the classes are different even if the instance's class is a subclass * of compareClass, it returns false. * Does not work with interfaces. The compareClass must be a class. * * @author Mims Wright * * @example * var myBase:BaseClass = new BaseClass(); * var mySub:SubClass = new SubClass(); * trace(strictIs(myBase, BaseClass)); // true * trace(strictIs(mySub, SubClass)); // true * trace(strictIs(mySub, BaseClass)); // false * * * @param instance - the object whos class you want to check. * @param compareClass - the class to compare your object against. * @return true if instance is strictly of type compareClass. */ public function strictIs(instance:Object, compareClass:Class):Boolean { return compareClass == Class(instance.constructor); } } ================================================ FILE: src/utils/type/typeCache.as ================================================ package utils.type { import flash.utils.Dictionary; // global cache improves reflection performance significantly public var typeCache:Dictionary = new Dictionary(); } ================================================ FILE: src/utils/validation/US_STATE_ABBREVIATIONS.as ================================================ package utils.validation { public const US_STATE_ABBREVIATIONS:Array = [ 'ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy']; } ================================================ FILE: src/utils/validation/encodeCreditCardNumber.as ================================================ package utils.validation { /** * Encode a credit card number as a string and encode all digits except the * last digitsShown. * * @param strNumber credit card number as string * @param digitsShown display this many digits at the end of the card number for security purposes * @param encodeChar optional encoding character to use instead of default '*' * * @example * * trace(CreditCardValidator.EncodeNumber("1234567890123456")); // ************3456 * trace(CreditCardValidator.EncodeNumber("1234567890123456", 5, "x")); // xxxxxxxxxxx23456 * */ public function encodeCreditCardNumber(strNumber:String, digitsShown:uint = 4, encodeChar:String = "*"):String { var encoded:String = ""; for (var i:Number = 0; i < strNumber.length - digitsShown; i++) { encoded += encodeChar; } encoded += strNumber.slice(-digitsShown); return encoded; } } ================================================ FILE: src/utils/validation/getCreditCardProvider.as ================================================ package utils.validation { public function getCreditCardProvider(cardNumber:String):String { if (!isCreditCard(cardNumber)) return 'invalid'; if (cardNumber.length == 13 || cardNumber.length == 16 && cardNumber.indexOf('4') == 0) { return 'visa'; } else if (cardNumber.indexOf('51') == 0 || cardNumber.indexOf('52') == 0 || cardNumber.indexOf('53') == 0 || cardNumber.indexOf('54') == 0 || cardNumber.indexOf('55') == 0 && cardNumber.length == 16) { return 'mastercard'; } else if (cardNumber.length == 16 && cardNumber.indexOf('6011') == 0) { return 'discover'; } else if (cardNumber.indexOf('34') == 0 || cardNumber.indexOf('37') == 0 && cardNumber.length == 15) { return 'amex'; } else if (cardNumber.indexOf('300') == 0 || cardNumber.indexOf('301') == 0 || cardNumber.indexOf('302') == 0 || cardNumber.indexOf('303') == 0 || cardNumber.indexOf('304') == 0 || cardNumber.indexOf('305') == 0 || cardNumber.indexOf('36') == 0 || cardNumber.indexOf('38') == 0 && cardNumber.length == 14) { return 'diners'; } else return 'other'; } } ================================================ FILE: src/utils/validation/isBlank.as ================================================ package utils.validation { import utils.string.trim; /** * Validate if a strings contents are blank after a safety trim is performed. */ public function isBlank(s:String = null):Boolean { var str:String = trim(s); var i:int = 0; if (str.length == 0) { return true; } while (i < str.length) { if (str.charCodeAt(0) != 32) { return false; } i++; } return true; } } ================================================ FILE: src/utils/validation/isCreditCard.as ================================================ package utils.validation { /** Determines if credit card is valid using the Luhn formula. @param cardNumber: The credit card number. @return Returns true if String is a valid credit card number; otherwise false. */ public function isCreditCard(cardNumber:String):Boolean { if (cardNumber.length < 7 || cardNumber.length > 19 || Number(cardNumber) < 1000000) return false; var pre:Number; var sum:Number = 0; var alt:Boolean = true; var i:Number = cardNumber.length; while (--i > -1) { if (alt) sum += Number(cardNumber.substr(i, 1)); else { pre = Number(cardNumber.substr(i, 1)) * 2; sum += (pre > 8) ? pre -= 9 : pre; } alt = !alt; } return sum % 10 == 0; } } ================================================ FILE: src/utils/validation/isEmail.as ================================================ package utils.validation { /** Determines if String is a valid email address. @param email: String to verify as email. @return Returns true if String is a valid email; otherwise false. @see http://www.regular-expressions.info/email.html Read more about the regular expression used by this method. */ public function isEmail(email:String):Boolean { var pattern:RegExp = /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; return email.match(pattern) != null; } } ================================================ FILE: src/utils/validation/isNumeric.as ================================================ package utils.validation { /** * Validate if a string is composed entirely of numbers. */ public function isNumeric(str:String):Boolean { if (str == null) { return false; } var regx:RegExp = /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/; return regx.test(str); } } ================================================ FILE: src/utils/validation/isPOBox.as ================================================ package utils.validation { /** * Check if address is a Post Office Box */ public function isPOBox(address:String):Boolean { var look:Array = [ "PO ", "P O", "P.O", "P. O", "p o", "p.o", "p. o", "Box", "Post Office", "post office" ]; var len:Number = look.length; for (var i:int = 0; i < len; i++) { if (address.indexOf(look[i]) != -1) { return true; } } return false; } } ================================================ FILE: src/utils/validation/isURL.as ================================================ package utils.validation { /** * Validate as "http://" or "https://". */ public function isURL(str:String):Boolean { return (str.substring(0, 7) == "http://" || str.substring(0, 8) == "https://"); } } ================================================ FILE: src/utils/validation/isUSAStateAbbreviation.as ================================================ package utils.validation { import utils.array.contains; /** Determines if String is a valid USA state abbreviation. @param state: String to verify as two letter state abbreviation (includes DC). @return Returns true if String is a state abbreviation; otherwise false. */ public function isUSAStateAbbreviation(state:String):Boolean { return contains(US_STATE_ABBREVIATIONS, state.toLowerCase()) == 1; } } ================================================ FILE: src/utils/validation/isValidCreditCardNumber.as ================================================ package utils.validation { import utils.string.toNumeric; /** * Validate a credit card number as much as possible before submitting for approval. * @param strNumber credit card number as string * @example * var isValidNumber:Boolean = CreditCardValidator.isValidNumber("1234567890123456"); * */ public function isValidCreditCardNumber(strNumber:String):Boolean { var mod10:Function = function (strNumber:String):Boolean { // Seperate each number into it's own index in an array. var aNumbers:Array = strNumber.split(""); // Hold the sums of some calculations that will be made shortly. var nSum_1:Number = 0; var nSum_2:Number = 0; var nSum_Total:Number = 0; // Check to see if the length of the card number is odd or even. This will // be used to determine which indicies are doubled before being summed up. var nParity:Number = aNumbers.length % 2; // Loop through the card numbers. for (var i:uint = 0; i < aNumbers.length; i++) { // Type cast each digit to a number. var num:uint = uint(aNumbers[i]); aNumbers[i] = num; // Compare the parity of the index to the parity of the card number length // to determine how the value of the current index is handled. if (i % 2 == nParity) { // Double each number. aNumbers[i] *= 2; // If the resulting value is greater than '9', subtract '9' from it. aNumbers[i] = aNumbers[i] > 9 ? aNumbers[i] - 9 : aNumbers[i]; // Add each value together. nSum_1 += aNumbers[i]; } else { // Add each value together. nSum_2 += aNumbers[i]; } } // Find the total sum of the two groups. nSum_Total = nSum_1 + nSum_2; // If the sum is divisible by '10', the card number is valid. return (nSum_Total % 10 == 0); }; const MINIMUM_CARD_LENGTH:int = 13; const MAXIMUM_CARD_LENGTH:int = 16; var ccNumber:String = toNumeric(strNumber); if (ccNumber.length > 0 && !isNaN(ccNumber as Number) && (ccNumber.length >= MINIMUM_CARD_LENGTH && ccNumber.length <= MAXIMUM_CARD_LENGTH)) { return mod10(ccNumber); } return false; } } ================================================ FILE: src/utils/validation/isValidEmailAddress.as ================================================ package utils.validation { /** * Validate a string as a valid email address. */ public function isValidEmailAddress(str:String):Boolean { var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i; return emailExpression.test(str); } } ================================================ FILE: src/utils/validation/isValidExpirationDate.as ================================================ package utils.validation { /** * Validate a credit card's expiration date. * @example * var isValidDate:Boolean = CreditCardValidator.isValidExDate( 11, 2010 ); * */ public function isValidExpirationDate(month:int, year:int):Boolean { var d:Date = new Date(); var currentMonth:int = d.getMonth() + 1; var currentYear:int = d.getFullYear(); if ((year > currentYear) || (year == currentYear && month >= currentMonth)) { return true; } return false; } } ================================================ FILE: src/utils/validation/isValidPhoneNumber.as ================================================ package utils.validation { /** * Validate a string as a phone number. */ public function isValidPhoneNumber(str:String):Boolean { var phoneExpression:RegExp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/i; return phoneExpression.test(str); } } ================================================ FILE: src/utils/xml/XMLConstants.as ================================================ package utils.xml { /** * Contains references to XML related string constants. */ public class XMLConstants { /** * Constant representing a text node type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const TEXT:String = "text"; /** * Constant representing a comment node type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const COMMENT:String = "comment"; /** * Constant representing a processing instruction type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const PROCESSING_INSTRUCTION:String = "processing-instruction"; /** * Constant representing an attribute type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const ATTRIBUTE:String = "attribute"; /** * Constant representing a element type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const ELEMENT:String = "element"; } } ================================================ FILE: src/utils/xml/getNextSibling.as ================================================ package utils.xml { /** * Returns the next sibling of the specified node relative to the node's parent. * * @param x The node whose next sibling will be returned. * * @return The next sibling of the node. null if the node does not have * a sibling after it, or if the node has no parent. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public function getNextSibling(x:XML):XML { return getSiblingByIndex(x, 1); } } ================================================ FILE: src/utils/xml/getPreviousSibling.as ================================================ package utils.xml { /** * Returns the sibling before the specified node relative to the node's parent. * * @param x The node whose sibling before it will be returned. * * @return The sibling before the node. null if the node does not have * a sibling before it, or if the node has no parent. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public function getPreviousSibling(x:XML):XML { return getSiblingByIndex(x, -1); } } ================================================ FILE: src/utils/xml/getSiblingByIndex.as ================================================ package utils.xml { /** * Returns the sibling at the index specified relative to the node's parent. * * @param x The node whose sibling will be returned. * * @return The sibling of the node at the specified position. null if the node does not have * a sibling at that position, or if the node has no parent. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * * @example Getting a sibling 2 positions behind a node * * var x:XML = * value1 * value2 * value3 * ; * * //Request sibling 2 positions before "value3" * var sibling:XML = getSiblingByIndex(x.stuff[2], -2); * * //returns "value1" * */ public function getSiblingByIndex(x:XML, count:int):XML { var out:XML; try { out = x.parent().children()[x.childIndex() + count]; } catch (e:Error) { return null; } return out; } } ================================================ FILE: src/utils/xml/isValidXML.as ================================================ package utils.xml { /** * Checks whether the specified string is valid and well formed XML. * * @param data The string that is being checked to see if it is valid XML. * * @return A Boolean value indicating whether the specified string is * valid XML. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public function isValidXML(data:String):Boolean { var xml:XML; try { xml = new XML(data); } catch (e:Error) { return false; } return xml.nodeKind() == XMLConstants.ELEMENT; } } ================================================ FILE: test/UtilsTestRunner.as ================================================ package { import flash.display.Sprite; import org.flexunit.internals.TraceListener; import org.flexunit.listeners.CIListener; import org.flexunit.runner.FlexUnitCore; import org.fluint.uiImpersonation.IVisualTestEnvironment; import org.fluint.uiImpersonation.VisualTestEnvironmentBuilder; public class UtilsTestRunner extends Sprite { private var core:FlexUnitCore; private var env:IVisualTestEnvironment; public function UtilsTestRunner() { super(); // make the stage available to tests env = VisualTestEnvironmentBuilder.getInstance(this).buildVisualTestEnvironment(); // run core = new FlexUnitCore(); core.addListener(new TraceListener()); core.addListener(new CIListener()); core.run( UtilsTestSuite ); } } } ================================================ FILE: test/UtilsTestSuite.as ================================================ package { import org.flexunit.runners.Suite; import utils.align.AlignCenterTest; import utils.align.AlignLeftTest; import utils.align.AlignRightTest; import utils.date.GetNextDayTest; import utils.date.GetPrevDayTest; import utils.date.GetTimeElapsedStringTest; import utils.date.calendar.CalendarTests; import utils.dictionary.CircularDictionaryTest; import utils.geom.CartesianToPolarCoordinatesTest; import utils.geom.PolarToCartesianCoordinatesTest; import utils.number.ClampTest; import utils.number.ToHexTest; import utils.object.CloneTest; import utils.object.ContainsTest; import utils.object.CreateInstanceTest; import utils.object.CreateTest; import utils.object.MergeTest; import utils.range.RandomRangeDateTest; import utils.string.NumberToStringTest; import utils.string.StringHasValueTest; import utils.type.IsPassedByValueTest; import utils.type.StrictIsTest; import utils.validation.EncodeCreditCardNumberTest; import utils.validation.GetCreditCardProviderTest; import utils.validation.IsBlankTest; import utils.validation.IsCreditCardTest; import utils.validation.IsEmailTest; import utils.validation.IsNumericTest; import utils.validation.IsPOBoxTest; import utils.validation.IsUSAStateAbbreviationTest; import utils.validation.IsUrlTest; import utils.validation.IsValidCreditCardNumberTest; import utils.validation.IsValidEmailAddressTest; import utils.validation.IsValidExpirationDateTest; import utils.validation.IsValidPhoneNumberTest; import utils.xml.GetNextSiblingTest; import utils.xml.GetPreviousSiblingTest; import utils.xml.GetSiblingByIndexTest; import utils.xml.IsValidXMLTest; Suite; [RunWith("org.flexunit.runners.Suite")] [Suite] public class UtilsTestSuite { // utils.align public var alignCenterTest:AlignCenterTest; public var alignLeftTest:AlignLeftTest; public var alighRightTest:AlignRightTest; // utils.date.calendar public var calendarTest:CalendarTests; // utils.date public var getNextDayTest:GetNextDayTest; public var getPrevDayTest:GetPrevDayTest; public var getTimeElapsedStringTest:GetTimeElapsedStringTest; // utils.dictionary public var circularDictionaryTest:CircularDictionaryTest; // utils.geom public var cartesianToPolarCoordinatesTest:CartesianToPolarCoordinatesTest; public var polarToCartesianCoordinatesTest:PolarToCartesianCoordinatesTest; // utils.number public var clampTest:ClampTest; public var toHexTest:ToHexTest; // utils.object public var cloneTest:CloneTest; public var containsTest:ContainsTest; public var createInstanceTest:CreateInstanceTest; public var createTest:CreateTest; public var mergeTest:MergeTest; // utils.range public var randomRangeDateTest:RandomRangeDateTest; // utils.string public var numberToStringTest:NumberToStringTest; public var stringHasValueTest:StringHasValueTest; // utils.type public var isPassedByValueTest:IsPassedByValueTest; public var strictIsTest:StrictIsTest; // utils.validation // public var encodeCreditCardNumberTest:EncodeCreditCardNumberTest; // public var getCreditCardProviderTest:GetCreditCardProviderTest; // public var isBlankTest:IsBlankTest; // public var isCreditCardTest:IsCreditCardTest; // public var isEmailTest:IsEmailTest; // public var isNumericTest:IsNumericTest; // public var isPOBoxTest:IsPOBoxTest; // public var isUrlTest:IsUrlTest; // public var isUSAStateAbbreviation:IsUSAStateAbbreviationTest; public var isValidCreditCardNumberTest:IsValidCreditCardNumberTest; public var isValidEmailAddress:IsValidEmailAddressTest; public var isValidExpirationDate:IsValidExpirationDateTest; public var isValidPhoneNumberTest:IsValidPhoneNumberTest; // utils.xml public var getNextSiblingTest:GetNextSiblingTest; public var getPreviousSiblingTest:GetPreviousSiblingTest; public var getSiblingByIndexTest:GetSiblingByIndexTest; public var isValidXMLTest:IsValidXMLTest; } } ================================================ FILE: test/utils/align/AlignLeftTest.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.display.Sprite; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.object.hasProperties; import utils.object.create; public class AlignLeftTest { public var targets:Array; [Before] public function setup():void { targets = [ create(Sprite, null, { x: 5, y: 15 }) , create(Sprite, null, { x: 15, y: 50 }) , create(Sprite, null, { x: 50, y: 5 }) ]; } [Test] public function alignLeftShouldAlignLeftEdgesOfTargetsToLeftMostTarget():void { assertThat( "alignLeft set the x of each target to 5" , alignLeft(targets) , array(hasProperties({ x: 5, y: 15 }) , hasProperties({ x: 5, y: 50 }) , hasProperties({ x: 5, y: 5 }) )); } } } ================================================ FILE: test/utils/align/AlignRightTest.as ================================================ package utils.align { import flash.display.DisplayObject; import flash.display.Shape; import flash.display.Sprite; import flash.geom.Point; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.object.hasProperties; import utils.object.create; public class AlignRightTest { public var targets:Array; [Before] public function setup():void { targets = [ create(Square, [20], { x: 5, y: 15 }) , create(Square, [100], { x: 15, y: 50 }) , create(Square, [50], { x: 50, y: 5 }) ]; } [Test] public function alignRightShouldAlignRightEdgesOfTargetsToRightMostTarget():void { assertThat( "alignRight" , alignRight(targets) , array(hasProperties({ x: 95, y: 15 }) , hasProperties({ x: 15, y: 50 }) , hasProperties({ x: 65, y: 5 }) )); } [Test] public function alignRightShouldWorkForWidthlessObjects():void { targets = [ new Point(5, 15) , new Point(15, 50) , new Point(50, 5) ]; assertThat( "alignRight" , alignRight(targets) , array(hasProperties({ x: 50, y: 15 }) , hasProperties({ x: 50, y: 50 }) , hasProperties({ x: 50, y: 5 }) )); } } } import flash.display.Shape; internal class Square extends Shape { public function Square(size:int = 50) { graphics.beginFill(0xFFFFFF, 1.0); graphics.drawRect(0, 0, size, size); graphics.endFill(); } override public function toString():String { return "[Square" + " x=" + x + " y=" + y + " w=" + width + " h=" + height + "]"; } } ================================================ FILE: test/utils/align/alignCenterTest.as ================================================ package utils.align { import flash.display.Sprite; import org.fluint.uiImpersonation.UIImpersonator; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class AlignCenterTest { [Test] public function alignCenter_aligns_display_object_centers_x():void { var item:Sprite = drawSprite(10,10,10,10); var target:Sprite = drawSprite(20,20,10,10); addItemAndTargetToStage(item, target); alignCenter(item, target); assertThat(item.x, equalTo(target.x)); } [Test] public function alignCenter_aligns_display_object_centers_y():void { var item:Sprite = drawSprite(10,10,10,10); var target:Sprite = drawSprite(20,20,10,10); addItemAndTargetToStage(item, target); alignCenter(item, target); assertThat(item.y, equalTo(target.y)); } private function drawSprite(x:int, y:int, width:int, height:int):Sprite { var sprite:Sprite = new Sprite(); sprite.graphics.beginFill(0x000000); sprite.graphics.drawRect(0,0,width,height); sprite.x = x; sprite.y = y; return sprite; } private function addItemAndTargetToStage(item:Sprite, target:Sprite):void { var container:Sprite = new Sprite(); container.addChild(item); container.addChild(target); UIImpersonator.addChild(container); } } } ================================================ FILE: test/utils/date/GetNextDayTest.as ================================================ package utils.date { import org.flexunit.asserts.assertTrue; import org.flexunit.asserts.fail; import utils.date.getNextDay; public class GetNextDayTest { [Test] public function returnsNextDay():void { var jan14:Date = new Date(2010, 0, 14); var jan15:Date = new Date(2010, 0, 15); assertTrue(getNextDay(jan14).getTime() == jan15.getTime()); } [Test] public function passingNoDateUsesToday():void { var today:Date = new Date(); var tomorrow:Date = getNextDay(today); assertTrue(getNextDay().getTime() == tomorrow.getTime()); } [Test] public function wrapsToNextMonth():void { var endOfMonth:Date = new Date(2010, 0, 31); assertTrue(getNextDay(endOfMonth).getMonth() == 1); } [Test] public function wrapsToNextMonthForFebruary():void { var endOfFeb:Date = new Date(2011, 1, 28); assertTrue(getNextDay(endOfFeb).getMonth() == 2); } [Test] public function doesntWrapToNextMonthForFebruaryInLeapYear():void { var endOfFeb:Date = new Date(2012, 1, 28); assertTrue(getNextDay(endOfFeb).getMonth() == 1); } [Test] public function wrapsToNextYear():void { var endOfYear:Date = new Date(2010, 11, 31); assertTrue(getNextDay(endOfYear).getFullYear() == 2011); } } } ================================================ FILE: test/utils/date/GetPrevDayTest.as ================================================ package utils.date { import org.flexunit.asserts.assertTrue; import org.flexunit.asserts.fail; import utils.date.getPreviousDay; public class GetPrevDayTest { [Test] public function returnsPrevDay():void { var jan14:Date = new Date(2010, 0, 14); var jan15:Date = new Date(2010, 0, 15); assertTrue(getPreviousDay(jan15).getTime() == jan14.getTime()); } [Test] public function passingNoDateUsesToday():void { var today:Date = new Date(); var yesterday:Date = getPreviousDay(today); assertTrue(getPreviousDay().getTime() == yesterday.getTime()); } [Test] public function wrapsToPrevMonth():void { var startOfMonth:Date = new Date(2010, 0, 1); assertTrue(getPreviousDay(startOfMonth).getMonth() == 11); } [Test] public function wrapsToPrevYear():void { var startOfYear:Date = new Date(2011, 0, 1); assertTrue(getPreviousDay(startOfYear).getFullYear() == 2010); } } } ================================================ FILE: test/utils/date/GetTimeElapsedStringTest.as ================================================ package utils.date { import flexunit.framework.Assert; import utils.date.getTimeElapsedString; /** * DateFormatterTest * * @author Mims H. Wright */ public class GetTimeElapsedStringTest { [Test] public function testGetTimeElapsedString():void { // create a custom date for now to ensure that subtracting time from // each field will create a valid date var now:Date = new Date(2010, 11, 30, 12, 50, 50); var secondsAgo:Date = new Date(now.fullYear, now.month, now.date, now.hours, now.minutes, now.seconds - 5); var minutesAgo:Date = new Date(now.fullYear, now.month, now.date, now.hours, now.minutes - 5); var hoursAgo:Date = new Date(now.fullYear, now.month, now.date, now.hours - 5); var yesterday:Date = new Date(now.fullYear, now.month, now.date - 1); var daysAgo:Date = new Date(now.fullYear, now.month, now.date - 5); var weeksAgo:Date = new Date(now.fullYear, now.month, now.date - 8); var monthsAgo:Date = new Date(now.fullYear, now.month - 5, now.date ); var yearsAgo:Date = new Date(now.fullYear - 2, now.month, now.date); var future:Date = new Date(now.fullYear + 1, now.month, now.date); Assert.assertEquals("just now", getTimeElapsedString(secondsAgo, now)); Assert.assertEquals("5 minutes ago", getTimeElapsedString(minutesAgo, now)); Assert.assertEquals("5 hours ago", getTimeElapsedString(hoursAgo, now)); Assert.assertEquals("yesterday", getTimeElapsedString(yesterday, now)); Assert.assertEquals("5 days ago", getTimeElapsedString(daysAgo, now)); Assert.assertEquals("1 week ago", getTimeElapsedString(weeksAgo, now)); Assert.assertEquals("5 months ago", getTimeElapsedString(monthsAgo, now)); Assert.assertEquals("more than a year ago", getTimeElapsedString(yearsAgo, now)); Assert.assertEquals("in the future", getTimeElapsedString(future, now)); } } } ================================================ FILE: test/utils/date/calendar/CalendarTests.as ================================================ /** * User: John Lindquist * Date: 3/16/11 * Time: 11:14 AM */ package utils.date.calendar { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.date.Calendar; public class CalendarTests { [Test] public function now_should_be_the_current_time():void { var calendar:Calendar = new Calendar(); assertThat(calendar.now.toString(), equalTo(new Date().toString())); } } } ================================================ FILE: test/utils/dictionary/CircularDictionaryTest.as ================================================ package utils.dictionary { import flexunit.framework.Assert; import utils.dictionary.CircularDictionary; public class CircularDictionaryTest { [Test] public function testAddAndRemovePair():void { var a:Object = {foo:"bar"}; var b:int = 42; var dict:CircularDictionary = new CircularDictionary(); dict.addPair(a,b); Assert.assertEquals(a, dict.getCounterpartTo(b)); Assert.assertEquals(b, dict.getCounterpartTo(a)); var result:* = dict.removePair(a); Assert.assertUndefined(dict.getCounterpartTo(a), dict.getCounterpartTo(b)); Assert.assertEquals(result, b); } } } ================================================ FILE: test/utils/display/FindAncestorTest.as ================================================ package flexUnitTests { import flash.display.MovieClip; import flash.display.Shape; import flash.display.Sprite; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNull; import utils.display.findAncestor; import utils.display.findAncestorWithType; public class FindAncestorTest { [Test] public function findAncestorTest():void { var a:MovieClip = new MovieClip(); var b:Sprite = new Sprite(); var c:Shape = new Shape(); var d:Sprite = new Sprite(); // not in chain a.addChild(b); b.addChild(c); assertEquals(findAncestor(c, a), a); assertEquals(findAncestor(c, b), b); assertEquals(findAncestor(c, c), c); assertNull(findAncestor(a, c)); assertNull(findAncestor(c, d)); assertEquals(findAncestorWithType(c, MovieClip), a); assertEquals(findAncestorWithType(c, Sprite), b); assertNull(findAncestorWithType(c, Shape)); } } } ================================================ FILE: test/utils/geom/CartesianToPolarCoordinatesTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 11:50:50 AM */ package utils.geom { import org.flexunit.asserts.assertTrue; import utils.geom.cartesianToPolarCoordinates; public class CartesianToPolarCoordinatesTest { [Before] public function setup():void { } [Test] public function CartesianToPolarCoordinatesReturnsProperCoords():void { var polarCoord:Array = cartesianToPolarCoordinates(3, 4); assertTrue(polarCoord[0] == 5 && polarCoord[1] == 53.13010235415598) } } } ================================================ FILE: test/utils/geom/PolarToCartesianCoordinatesTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: Sep 30, 2010 * Time: 11:50:50 AM */ package utils.geom { import flash.geom.Point; import org.flexunit.asserts.assertTrue; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.geom.cartesianToPolarCoordinates; import utils.geom.polarToCartesianCoordinates; public class PolarToCartesianCoordinatesTest { [Test] public function PolarToCartesianCoordinatesReturnsProperCoords():void { //R is 12, theta is 195 degrees var cartesianPoint:Point = polarToCartesianCoordinates(12, 195); assertThat(cartesianPoint.x, equalTo(-11.59110991546882)); assertThat(cartesianPoint.y, equalTo(-3.1058285412302444)); } } } ================================================ FILE: test/utils/number/ClampTest.as ================================================ package utils.number { import flexunit.framework.Assert; import utils.number.clamp; public class ClampTest { [Test] public function testClamp():void { var low:int = 0; var high:int = 100; Assert.assertEquals("Values between low and high are passed thru.", clamp(50, low, high), 50); Assert.assertEquals("Values lower than low value are limited to the low value.", clamp(low - 100, low, high), low); Assert.assertEquals("Values higher than the high value are limited to the high value.", clamp(high + 100, low, high), high); Assert.assertEquals("If any values are NaN, return NaN.", clamp(5, NaN, high), NaN); } } } ================================================ FILE: test/utils/number/ToHexTest.as ================================================ package utils.number { import flash.utils.Endian; import flexunit.framework.Assert; import utils.number.toHex; import utils.string.endsWith; public class ToHexTest { [Test] public function testToHex ():void { Assert.assertEquals("Big endian", "0xFC00", toHex(0xFC00, 1, true, Endian.BIG_ENDIAN)); Assert.assertEquals("Little endian", "0x00FC", toHex(0xFC00, 1, true, Endian.LITTLE_ENDIAN)); Assert.assertEquals("Add leading 0 if there aren't enough numbers to make a byte", "0x452301", toHex(0x12345, 1, true, Endian.LITTLE_ENDIAN)); Assert.assertEquals("Converting from digital number to hex produces hex string", "0xFF", toHex(255)); Assert.assertEquals("Convert 0 to 0x0", "0x0", toHex(0)); Assert.assertEquals("Floats round down", "0x1", toHex(1.6)); Assert.assertEquals("Converting from hex number to hex produces hex string", "0xABCDEF", toHex(0xABCDEF)); Assert.assertEquals("Hide '0x'", "ABC", toHex(0xABC, 1, false)); Assert.assertEquals("Leading 0's", "0x0033CC", toHex(0x0033CC, 6)); // todo: test endian param. } } } ================================================ FILE: test/utils/object/CreateInstanceTest.as ================================================ package utils.object { import flash.display.Sprite; import flash.events.Event; import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import org.hamcrest.object.hasProperties; import org.hamcrest.object.instanceOf; public class CreateInstanceTest { [Test] public function createsAnInstanceOfGivenClass():void { assertThat( "creates an instance of given class" , createInstance(Sprite) , instanceOf(Sprite) ); } [Test] public function createsAnInstanceOfGivenClassWithConstructorArguments():void { assertThat( "creates an instance of given class with constructor arguments" , createInstance(Event, ["eventType", true, false]) , hasProperties({}) ); } [Test] public function worksForUpToTenConstructorArguments():void { assertThat(createInstance(Consumer).consumed, equalTo([])); assertThat(createInstance(Consumer, []).consumed, equalTo([])); assertThat(createInstance(Consumer, [1]).consumed, equalTo([1])); assertThat(createInstance(Consumer, [1, 2]).consumed, equalTo([1, 2])); assertThat(createInstance(Consumer, [1, 2, 3]).consumed, equalTo([1, 2, 3])); assertThat(createInstance(Consumer, [1, 2, 3, 4]).consumed, equalTo([1, 2, 3, 4])); assertThat(createInstance(Consumer, [1, 2, 3, 4, 5]).consumed, equalTo([1, 2, 3, 4, 5])); assertThat(createInstance(Consumer, [1, 2, 3, 4, 5, 6]).consumed, equalTo([1, 2, 3, 4, 5, 6])); assertThat(createInstance(Consumer, [1, 2, 3, 4, 5, 6, 7]).consumed, equalTo([1, 2, 3, 4, 5, 6, 7])); assertThat(createInstance(Consumer, [1, 2, 3, 4, 5, 6, 7, 8]).consumed, equalTo([1, 2, 3, 4, 5, 6, 7, 8])); assertThat(createInstance(Consumer, [1, 2, 3, 4, 5, 6, 7, 8, 9]).consumed, equalTo([1, 2, 3, 4, 5, 6, 7, 8, 9])); assertThat(createInstance(Consumer, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).consumed, equalTo([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); } [Test(expected="ArgumentError")] public function explodesIfYouPassTooManyConstructorArguments():void { createInstance(Consumer, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); } [Test(expected="ArgumentError")] public function explodesIfYouForgetRequiredConstructorArguments():void { createInstance(Event); } } } // a little something to help test createInstance internal class Consumer { private var _consumed:Array; public function Consumer(...rest) { _consumed = rest; } public function get consumed():Array { return _consumed; } } ================================================ FILE: test/utils/object/CreateTest.as ================================================ package utils.object { import flash.display.Sprite; import flash.events.Event; import flash.events.EventDispatcher; import flash.filters.GlowFilter; import org.hamcrest.assertThat; import org.hamcrest.core.throws; import org.hamcrest.number.closeTo; import org.hamcrest.object.hasProperties; import org.hamcrest.object.instanceOf; public class CreateTest { [Test] public function createShouldCreateAnInstanceOfTheGivenClass():void { assertThat( "should create an instance of the given Class" , create(Sprite) , instanceOf(Sprite) ); } [Test] public function createShouldUseConstructorArguments():void { assertThat( "should use constructor arguments if given" , create(Event, [Event.COMPLETE, true]) , hasProperties({ type: Event.COMPLETE, bubbles: true }) ); } [Test] public function createShouldPopulateTheGivenPropertiesOnTheInstance():void { assertThat( "should use constructor arguments if given" , create(Sprite, null, { x: 50, y: 10 }) , hasProperties({ x: 50, y: 10 }) ); } [Test] public function createShouldSupportBothConstructorArgumentsAndProperties():void { assertThat( "should constructor arguments THEN properties" , create(GlowFilter, [0xFF3333, 1.0], { alpha: 0.5 }) , hasProperties({ color: 0xFF3333, alpha: closeTo(0.5, 0.01) }) ); } } } ================================================ FILE: test/utils/object/MergeTest.as ================================================ package utils.object { import org.hamcrest.assertThat; import org.hamcrest.object.hasProperties; public class MergeTest { [Test] public function copiesEnumerablePropertiesAndValuesFromSourceToTarget():void { var source:Object = { a: 1, d: 4 }; var target:Object = { a: 0, b: 2, c: 3 } assertThat(merge(target, source), hasProperties({ a: 1, b: 2, c: 3, d: 4 })); } } } ================================================ FILE: test/utils/object/cloneTest.as ================================================ package utils.object { import org.hamcrest.assertThat; import org.hamcrest.object.hasProperties; public class CloneTest { [Test] public function clone_creates_object_with_equal_properties():void { var originalObject:SimpleObject = new SimpleObject(); var cloneObject:Object; cloneObject = clone(originalObject); assertThat( "cloned object properties equal original object properties", cloneObject, hasProperties({propOne:"propOne",propTwo:true,propThree:10}) ); } } } class SimpleObject { public var propOne:String = "propOne"; public var propTwo:Boolean = true; public var propThree:int = 10; } ================================================ FILE: test/utils/object/containsTest.as ================================================ package utils.object { import flexunit.framework.Assert; import utils.object.contains; public class ContainsTest { [Test] public function testContains():void { var o:Object = {foo:"bar", baz:42}; var p:Object = {foo:o}; Assert.assertTrue("Object contains 'bar'", contains(o, "bar")); Assert.assertFalse("Doesn't check property names", contains(o, "foo")); Assert.assertTrue("Object contains other objects", contains(p, o)); } } } ================================================ FILE: test/utils/range/RandomRangeDateTest.as ================================================ package utils.range { import org.flexunit.asserts.assertTrue; import org.flexunit.asserts.fail; public class RandomRangeDateTest { [Before] public function setup():void { } [Test] public function randomDateReturnsWithinRange():void { var firstDate:Date = new Date(); firstDate.month = 5; var secondDate:Date = new Date(); secondDate.month = 10; var date:Date = randomRangeDate(firstDate,secondDate) ; assertTrue(date.getTime() > firstDate.getTime() && date.getTime() < secondDate.getTime()); } [Test] public function randomDateReturnWithinRangeWithValuesSwapped():void { var firstDate:Date = new Date(); firstDate.month = 10; var secondDate:Date = new Date(); secondDate.month = 5; var date:Date = randomRangeDate(firstDate,secondDate) ; assertTrue(date.getTime() < firstDate.getTime() && date.getTime() > secondDate.getTime()); } [Test] public function randomDateThrowsErrorWhenDatesAreTheSame():void { var firstDate:Date = new Date(); var secondDate:Date = new Date(); try{ var date:Date = randomRangeDate(firstDate,secondDate) ; } catch(e:Error) { assertTrue(1 == 1); return; } fail("Error was not thrown"); } } } ================================================ FILE: test/utils/string/numberToStringTest.as ================================================ package utils.string { import org.flexunit.asserts.*; public class NumberToStringTest { [Before] public function setup():void { } [Test] public function numberToStringTestPositiveNumbers():void { assertEquals("eleven", numberToString(11)); assertEquals("ten thousand", numberToString(10000)); assertEquals("one billion two hundred thirty four million five hundred sixty seven thousand eight hundred ninety", numberToString(1234567890)); } [Test] public function numberToStringTestDecimalNumbers():void { assertEquals("point one two three four five", numberToString(0.12345)); assertEquals("one hundred one point zero zero one", numberToString(101.001)); } [Test] public function numberToStringTestNegativeNumbers():void { assertEquals("negative one", numberToString(-1)); } [Test] public function numberToStringTestZero():void { assertEquals("zero", numberToString(0)); } [Test] public function numberToStringTestNaN():void { assertEquals("not a number", numberToString(NaN)); assertEquals("not a number", numberToString(undefined)); } } } ================================================ FILE: test/utils/string/stringHasValueTest.as ================================================ package utils.string { import org.hamcrest.assertThat; import org.hamcrest.object.isFalse; import org.hamcrest.object.isTrue; public class StringHasValueTest { [Test] public function stringHasValue_is_true_for_a_string_with_a_value():void { var stringDoesHaveValue:Boolean; stringDoesHaveValue = stringHasValue("someString"); assertThat( "The string has a value.", stringDoesHaveValue, isTrue() ); } [Test] public function stringHasValue_is_false_for_a_string_with_no_value():void { var noCharStringHasValue:Boolean; noCharStringHasValue = stringHasValue(""); assertThat( "The string has no value.", noCharStringHasValue, isFalse() ); } [Test] public function stringHasValue_is_false_for_null():void { var nullHasValueAsString:Boolean; nullHasValueAsString = stringHasValue(null); assertThat( "Null has no value.", nullHasValueAsString, isFalse() ); } } } ================================================ FILE: test/utils/type/IsPassedByValueTest.as ================================================ package utils.type { import flexunit.framework.Assert; import utils.type.isPassedByValue; public class IsPassedByValueTest { [Test] public function testIsPassedByValue():void { Assert.assertTrue("uint is passed by value", isPassedByValue(uint(5))); Assert.assertTrue("int is passed by value", isPassedByValue(int(5))); Assert.assertTrue("Number is passed by value", isPassedByValue(5.5)); Assert.assertTrue("String is passed by value", isPassedByValue("foo")); Assert.assertTrue("Boolean is passed by value", isPassedByValue(true)); Assert.assertFalse("null values don't indicate the type of the variable container.", isPassedByValue(null)); var xml:XML =

hello

; Assert.assertFalse("XML is not passed by value even though it's a primitive", isPassedByValue(xml)); } } } ================================================ FILE: test/utils/type/StrictIsTest.as ================================================ package utils.type { import flash.display.MovieClip; import flash.display.Sprite; import flexunit.framework.Assert; import utils.type.strictIs; public class StrictIsTest { [Test] public function testStrictIs():void { var s:Sprite = new Sprite(); var m:MovieClip = new MovieClip(); Assert.assertTrue("Sprite instance is Sprite", s is Sprite); Assert.assertTrue("MovieClip instance is Sprite", m is Sprite); Assert.assertFalse("Sprite instance is not MovieClip", s is MovieClip); Assert.assertTrue("Sprite instance is strictly Sprite", strictIs(s, Sprite)); Assert.assertFalse("MovieClip instance is strictly not a Sprite", strictIs(m, Sprite)); Assert.assertFalse("Sprite instance is strictly not a MovieClip", strictIs(s, MovieClip)); } } } ================================================ FILE: test/utils/validation/IsValidEmailAddressTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:47 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.IsValidEmailAddressTest; public class IsValidEmailAddressTest { [Test] public function goodEmailPasses() : void { assertThat(isValidEmailAddress("test@test.com"), equalTo(true)) } [Test] public function emailWithSpaceFails() : void { assertThat(isValidEmailAddress("test@ test.com"), equalTo(false)) } [Test] public function emailWithoutAtSymbolFails() : void { assertThat(isValidEmailAddress("testtest.com"), equalTo(false)) } [Test] public function emailWithInvalidCharacterFails() : void { assertThat(isValidEmailAddress("test@te$t.com"), equalTo(false)) } } } ================================================ FILE: test/utils/validation/encodeCreditCardNumberTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 3:07 PM */ package utils.validation { public class EncodeCreditCardNumberTest { public function EncodeCreditCardNumberTest() { } } } ================================================ FILE: test/utils/validation/getCreditCardProviderTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 1:26 PM */ package utils.validation { public class GetCreditCardProviderTest { public function GetCreditCardProviderTest() { } } } ================================================ FILE: test/utils/validation/isBlankTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:48 AM */ package utils.validation { public class IsBlankTest { public function IsBlankTest() { } } } ================================================ FILE: test/utils/validation/isCreditCardTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:44 AM */ package utils.validation { public class IsCreditCardTest { public function IsCreditCardTest() { } } } ================================================ FILE: test/utils/validation/isEmailTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:39 AM */ package utils.validation { public class IsEmailTest { public function IsEmailTest() { } } } ================================================ FILE: test/utils/validation/isNumericTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:37 AM */ package utils.validation { public class IsNumericTest { public function IsNumericTest() { } } } ================================================ FILE: test/utils/validation/isPOBoxTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:35 AM */ package utils.validation { public class IsPOBoxTest { public function IsPOBoxTest() { } } } ================================================ FILE: test/utils/validation/isUSAStateAbbreviationTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:24 AM */ package utils.validation { import org.flexunit.asserts.fail; public class IsUSAStateAbbreviationTest { [Test] public function IsUSAStateAbbreviationTest() { new Array('ak', 'al', 'ar', 'az', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga', 'hi', 'ia', 'id', 'il', 'in', 'ks', 'ky', 'la', 'ma', 'md', 'me', 'mi', 'mn', 'mo', 'ms', 'mt', 'nb', 'nc', 'nd', 'nh', 'nj', 'nm', 'nv', 'ny', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'va', 'vt', 'wa', 'wi', 'wv', 'wy'); // assertThat(isUSAStateAbbreviation("DE"), // equalTo()) fail("test remains to be implemented") } } } ================================================ FILE: test/utils/validation/isUrlTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/24/11 * Time: 11:29 AM */ package utils.validation { public class IsUrlTest { public function IsUrlTest() { } } } ================================================ FILE: test/utils/validation/isValidCreditCardNumberTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:52 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidCreditCardNumber; public class IsValidCreditCardNumberTest { [Test] public function ccBelowMinimum13ShouldFail() : void { assertThat(isValidCreditCardNumber("1234"), equalTo(false)); } [Test] public function ccAboveMaximum16ShouldFail() : void { assertThat(isValidCreditCardNumber("123413123123213421341123412423412412341232314"), equalTo(false)); } //Even CC length integrity testing //Each number is examined //if a number is divisible by 2 with no remainder (even) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. //if a number is divisible by 2 with a remainder (odd) it gets added to the second group //The first group plus the second group should be divisible by 10 with no remainder [Test] public function ccEvenNumberLengthWithBadIntegrityShouldFail() : void { assertThat(isValidCreditCardNumber("12345678901234"), equalTo(false)); } [Test] public function ccEvenNumberLengthWithGoodIntegrityShouldPass() : void { assertThat(isValidCreditCardNumber("72345678901234"), equalTo(true)); } //Odd CC length integrity testing //Each number is examined //if a number is divisible by 1 with no remainder (odd) it gets doubled and added to the first group. If the result is number is greater than 9 then 9 is subtracted. //if a number is divisible by 1 with a remainder (even) it gets added to the second group //The first group plus the second group should be divisible by 10 with no remainder [Test] public function ccOddNumberLengthWithBadIntegrityShouldFail() : void { assertThat(isValidCreditCardNumber("123456789012345"), equalTo(false)); } [Test] public function ccOddNumberLengthWithGoodIntegrityShouldPass() : void { assertThat(isValidCreditCardNumber("323456789012345"), equalTo(true)); } } } ================================================ FILE: test/utils/validation/isValidExpirationDateTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/20/11 * Time: 1:34 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidExpirationDate; public class IsValidExpirationDateTest { [Test] public function expirationOfNextYearShouldPass() : void { assertThat(isValidExpirationDate(1, new Date().getFullYear() + 1), equalTo(true)); } [Test] public function expirationOfLastYearShouldFail() : void { assertThat(isValidExpirationDate(1, new Date().getFullYear() - 1), equalTo(false)); } [Test] public function expirationOfSameYearButUpcomingMonthShouldPass() : void { assertThat(isValidExpirationDate(new Date().getMonth() + 1, new Date().getFullYear()), equalTo(true)); } [Test] public function expirationOfSameYearButPastMonthShouldFail() : void { assertThat(isValidExpirationDate(new Date().getMonth() - 1, new Date().getFullYear()), equalTo(false)); } [Test] public function expirationOfUpcomingYearWithMonthOfZeroShouldFail() : void { assertThat(isValidExpirationDate(0,new Date().getFullYear() + 1), equalTo(true)); } } } ================================================ FILE: test/utils/validation/isValidPhoneNumberTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 5:32 PM */ package utils.validation { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; import utils.validation.isValidPhoneNumber; public class IsValidPhoneNumberTest { [Test] public function validNumberPasses() : void { assertThat(isValidPhoneNumber("123 456-7789"), equalTo(true)); } [Test] public function validNumberNoDashesPasses() : void { assertThat(isValidPhoneNumber("123 456 7789"), equalTo(true)); } //TODO: Should this be the intended behavior? [Test] public function validNumberWithPrefixFails() : void { assertThat(isValidPhoneNumber("1 123 456-7789"), equalTo(false)); } } } ================================================ FILE: test/utils/xml/GetNextSiblingTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 2:28 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class GetNextSiblingTest { [Test] public function requestedIndexShouldReturnNextNode() : void { var x:XML = value1 value2 value3 var sibling:* = getNextSibling(x.stuff[1]); assertThat(sibling, equalTo(x.stuff[2])); } } } ================================================ FILE: test/utils/xml/GetPreviousSiblingTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 2:08 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class GetPreviousSiblingTest { [Test] public function callShouldReturnPreviousNode() : void { var x:XML = value1 value2 value3 var sibling:* = getPreviousSibling(x.stuff[2]); assertThat(sibling, equalTo(x.stuff[1])); } } } ================================================ FILE: test/utils/xml/GetSiblingByIndexTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/3/11 * Time: 12:04 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class GetSiblingByIndexTest { [Test] public function requestedIndexShouldReturnProperNode() : void { var x:XML = value1 value2 value3 var sibling:* = getSiblingByIndex(x.stuff[2], -1); assertThat(sibling, equalTo(x.stuff[1])) } } } ================================================ FILE: test/utils/xml/isValidXMLTest.as ================================================ /** * Created by IntelliJ IDEA. * User: Ian McLean * Date: 5/2/11 * Time: 4:40 PM */ package utils.xml { import org.hamcrest.assertThat; import org.hamcrest.object.equalTo; public class IsValidXMLTest { [Test] public function validXMLShouldReturnTrue() : void { var s:String = ""; assertThat(isValidXML(s), equalTo(true)) } [Test] public function invalidXMLShouldReturnFalse() : void { var s:String = ""; assertThat(isValidXML(s), equalTo(false)) } } }