Beautifl - Flash Gallery

Thumbnail : Twittenorion
Twittenorion
sakusan393 2010-11-02 MIT License

再生するにはFlash Playerが必要です。デスクトップのブラウザでご覧ください。

package{
    import flash.display.*;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.filters.*;
    import flash.geom.*;
    import flash.system.Capabilities;
    import flash.text.*;
    import net.hires.debug.Stats;
    import org.libspark.betweenas3.BetweenAS3;
    import org.libspark.betweenas3.easing.*;
    import org.libspark.betweenas3.tweens.ITween;
    import org.si.sion.events.SiONTrackEvent;
    import org.si.sion.sequencer.SiMMLTrack;
    import org.si.sion.SiONDriver;
    import org.si.sion.SiONVoice;
    import org.si.sion.utils.SiONPresetVoice;
    import org.si.sound.DrumMachine;
    

    public class Twittenorion extends Sprite {
        
        private var _countUpperStart:int = 30;
        private var _countLowerStart:int = 30;
        private var _countUpper:int = _countUpperStart;
        private var _countLower:int = _countLowerStart;
    
        private var _dotRadius:int = 8;
        private var _fontSize:int = 12;
        
        private var _tfUpper:TextField;
        private var _tfLower:TextField;
        
        private var _bdUpper:BitmapData;
        private var _bdLower:BitmapData;
        
        private var _circleArrayUpper:Array = [];
        private var _circleArrayLower:Array = [];
        
        private var _bdW:int = 28;
        private var _bdWHalf:int = _bdW/2;
        
        private var _bdH:int = 14;
        private var _bdHOffset:int = 2;
        
        private var _offsetX:int = 70;
        private var _offsetY:int = 70;
        
        private const BPM:int = 90;
        
        private var _containerUpper:Sprite = new Sprite();
        private var _containerLower:Sprite = new Sprite();
        
        private var _tweetLength:int = 1;
        
        // driver
        public var driver:SiONDriver = new SiONDriver();
        // preset voice
        public var presetVoice:SiONPresetVoice = new SiONPresetVoice();
        //音色が入る(16音分:縦の数)
        public var voicesUpper:Vector.<SiONVoice> = new Vector.<SiONVoice>(16);
        public var voicesLower:Vector.<SiONVoice> = new Vector.<SiONVoice>(16);
        //各音色の音階
        public var _notesUpper :Vector.<int> = Vector.<int>([36,48,60,72, 43,48,55,60, 65,67,70,72, 77,79,82,84]);
        public var _notesLower :Vector.<int> = Vector.<int>([65,67,70,72, 65,67,70,72, 77,79,82,84, 89,91,94,96]);
        //音色の伸ばす長さ
        public var _lengthUpper:Vector.<int> = Vector.<int>([ 1, 1, 1, 1,  1, 1, 1, 1,  2, 2, 2, 2,  2, 2, 2, 2]);
        public var _lengthLower:Vector.<int> = Vector.<int>([ 2, 2, 2, 2,  2, 2, 2, 2,  4, 4, 4, 4,  4, 4, 4, 4]);
        // beat counter
        public var beatCounter:int;
        
        private var drumMachine:DrumMachine;
        private var _textArray:Array /* of String */ = [];
        
        private var _tfIndex:int;
        private var _controller:Controller;
        private var _noKeyDownCountUpper:int;
        private var _noKeyDownCountLower:int;
        private var _fontString:String;
        private var _trackUpper:SiMMLTrack;
        private var _trackLower:SiMMLTrack;
        
        private var _isHitAlphabet:Boolean = false;
        private var _isHitNumber:Boolean = false;
        private var _upperVolume:int = 32;
        private var _lowerVolume:int = 32;
        private var _drumVolume:Number = .7;
        
        private var _coverWidth:int = 400;
        
        
        private function checkOS():void 
        {
            if (Capabilities.os.indexOf("Vista") != -1) 
            {
                _fontString = "メイリオ";
                _bdHOffset = 4;
            }
            if (Capabilities.os.indexOf("Windows 7") != -1) 
            {
                _fontString = "メイリオ";
                _bdHOffset = 4;
            }
            if (Capabilities.os.indexOf("XP") != -1)
            {
                _fontString = "MS Pゴシック";
                _bdHOffset = 4;
            }
            if (Capabilities.os.indexOf("Mac") != -1)
            {
                _fontString = "ヒラギノ角ゴ Pro W3";
                _bdHOffset = 2;
                
                _bdW = 14;
                _bdWHalf = _bdW / 2;
                _offsetX = 155;
                _countUpper = _countUpperStart = 15;
                _countLower = _countLowerStart = 15;
                _coverWidth = 235;
            }    
        }
        
        public function Twittenorion():void {
            checkOS();
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE , init);
        }
        
        
        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            
            stage.align = StageAlign.LEFT;
            
            _bdUpper = new BitmapData(_bdW, _bdH, false, 0x0);
            _bdLower = new BitmapData(_bdW, _bdH, false, 0x0);
            
            _tfUpper = createTextField("Hit Number Keys");
            _tfLower = createTextField("Hit Alphabet Keys");
            
            createDot(_containerUpper,_circleArrayUpper);
            createDot(_containerLower,_circleArrayLower);
            addChild(_containerUpper);
            
            addChild(_containerLower)
            _containerUpper.x = _offsetX;
            _containerUpper.y = _offsetY;
            _containerLower.x = _offsetX;
            _containerLower.y = _dotRadius * 1.5 * _bdH + _offsetY;
            
            //枠画像
            var coverWidth:int = _coverWidth;
            var coverHeight:int = 400;
            var coverDist:int = 32;
            var rLarge:int = 50;
            var rSmall:int = 10;
            var color:Array = [0xFF0000,0x660000,0x330000];
            var _mat:Matrix = new Matrix();
            var _radius2:int = 1400;
            _mat.createGradientBox(_radius2,_radius2, 0, -_radius2/2, -_radius2/2)
            var cover:Sprite = new Sprite();
            cover.graphics.beginGradientFill (
                GradientType.RADIAL,
                [color[0] , color[1] ,  color[2]],
                [     100 ,      100 ,  100],
                [       0 ,       128 ,  255],
                _mat,
                SpreadMethod.PAD,
                InterpolationMethod.LINEAR_RGB,
                0.0
            );
            cover.graphics.drawRoundRect(-coverWidth/2, -coverHeight/2, coverWidth, coverHeight, rLarge, rLarge);
            cover.graphics.drawRoundRect(-coverWidth/2+coverDist, -coverHeight/2+coverDist, coverWidth-coverDist*2, coverHeight-coverDist*2, rSmall, rSmall);
            cover.graphics.endFill();
            addChild(cover);
            cover.x = stage.stageWidth / 2;
            cover.y  = stage.stageHeight / 2;
            cover.filters = [new BevelFilter(4, 60, 0xFFCCCC, 1, 0x660000, 1)];
            
            _radius2 = _coverWidth;
            _mat.createGradientBox(_radius2, _radius2, 0, -_radius2 / 2, -_radius2 / 2);
            var shadow:Sprite = new Sprite();
            shadow.graphics.beginGradientFill (
                GradientType.LINEAR,
                [ 0  ,  0 , 0 ,  0],
                [ 10 , 0 , 0, 10],
                [ 0 , 60 ,255-60, 255],
                _mat,
                SpreadMethod.PAD,
                InterpolationMethod.LINEAR_RGB,
                0.0
            );
            shadow.graphics.drawRoundRect(-_radius2/2+coverDist, -coverHeight/2+coverDist, _radius2-coverDist*2, coverHeight-coverDist*2, rSmall, rSmall);
            shadow.graphics.endFill();
            addChild(shadow);
            shadow.x = stage.stageWidth / 2;
            shadow.y = stage.stageHeight / 2;
            
            //コントローラー
            addChild(_controller = new Controller());
            _controller.addEventListener(ControllerEvent.LOAD_COMPLETE,loadCompleteHandler)
            _controller.addEventListener(Controller.CHANGE_BPM, bpmChangeHandler);
            _controller.addEventListener(Controller.CHANGE_DRUM_ONOFF, drumChangeHandler);
            _controller.addEventListener(ControllerVolumeEvent.CHANGE_VOLUME, changeVolumeHandler);
            var iTween:ITween = BetweenAS3.delay(BetweenAS3.to(_controller, { y: -60 }, .2, Sine.easeOut), 1);
            iTween.onComplete = function():void {
                _controller.addEventListener(MouseEvent.ROLL_OVER, function():void {
                    BetweenAS3.to(_controller, { y:0 }, 0.2, Sine.easeOut).play();
                });
                _controller.addEventListener(MouseEvent.ROLL_OUT, function():void {
                    BetweenAS3.to(_controller, { y: -60 }, 0.2, Sine.easeOut).play();
                });
            }
            iTween.play();
            
            _controller.textArrayLower[0] = _tfLower.text;
            _controller.textArrayUpper[0] = _tfUpper.text;
            
            //キーボードイベントの設定
            setKeyBoardEvent();
            
            setSiON();
            //addChild(new Stats);
        }
        
        private function changeVolumeHandler(e:ControllerVolumeEvent):void 
        {
            if (e.position == "upper")
            {
                _upperVolume = e.vol;
            }
            else if (e.position == "lower")
            {
                _lowerVolume = e.vol;
            }
            else if (e.position == "drum")
            {
                drumMachine.volume = Number(e.vol / 100);
                _drumVolume = Number(e.vol / 100);
            }
        }
        
        private function drumChangeHandler(e:Event):void 
        {
            if (_controller.isDrumON) 
            {
                drumMachine = new DrumMachine(int(Math.random()*31),int(Math.random()*18),int(Math.random()*17),int(Math.random()*5),int(Math.random()*5),int(Math.random()*3));
                drumMachine.play();
                drumMachine.volume = _drumVolume;
            }
            else drumMachine.stop();
        }
        
        private function setKeyBoardEvent():void 
        {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyUpHandler);
        }
        private function keyUpHandler(e:KeyboardEvent):void {
            _noKeyDownCountUpper = 0;
            _noKeyDownCountLower = 0;
            //アルファベットは上段
            if(e.keyCode == 65 ) setCharacterString("a");
            else if(e.keyCode == 66 ) setCharacterString("b");
            else if(e.keyCode == 67 ) setCharacterString("c");
            else if(e.keyCode == 68 ) setCharacterString("d");
            else if(e.keyCode == 69 ) setCharacterString("e");
            else if(e.keyCode == 70 ) setCharacterString("f");
            else if(e.keyCode == 70 ) setCharacterString("f");
            else if(e.keyCode == 70 ) setCharacterString("f");
            else if(e.keyCode == 71 ) setCharacterString("g");
            else if(e.keyCode == 72 ) setCharacterString("h");
            else if(e.keyCode == 73 ) setCharacterString("i");
            else if(e.keyCode == 74 ) setCharacterString("j");
            else if(e.keyCode == 75 ) setCharacterString("k");
            else if(e.keyCode == 76 ) setCharacterString("l");
            else if(e.keyCode == 77 ) setCharacterString("m");
            else if(e.keyCode == 78 ) setCharacterString("n");
            else if(e.keyCode == 79 ) setCharacterString("o");
            else if(e.keyCode == 80 ) setCharacterString("p");
            else if(e.keyCode == 81 ) setCharacterString("q");
            else if(e.keyCode == 82 ) setCharacterString("r");
            else if(e.keyCode == 83 ) setCharacterString("s");
            else if(e.keyCode == 84 ) setCharacterString("t");
            else if(e.keyCode == 85 ) setCharacterString("u");
            else if(e.keyCode == 86 ) setCharacterString("v");
            else if(e.keyCode == 87 ) setCharacterString("w");
            else if(e.keyCode == 88 ) setCharacterString("x");
            else if(e.keyCode == 89 ) setCharacterString("y");
            else if (e.keyCode == 90 ) setCharacterString("z");
            //数字は下段
            else if(e.keyCode == 49 ) setNumberString("1");
            else if(e.keyCode == 50 ) setNumberString("2");
            else if(e.keyCode == 51 ) setNumberString("3");
            else if(e.keyCode == 52 ) setNumberString("4");
            else if(e.keyCode == 53 ) setNumberString("5");
            else if(e.keyCode == 54 ) setNumberString("6");
            else if(e.keyCode == 55 ) setNumberString("7");
            else if(e.keyCode == 56 ) setNumberString("8");
            else if(e.keyCode == 57 ) setNumberString("9");
            else if(e.keyCode == 48 ) setNumberString("0");
        }
        
        private function setNumberString(arg1:String):void 
        {
            if (!_isHitNumber) 
            {
                _controller.textArrayUpper = [];
                _controller.textArrayUpper[0] = "";
                _controller.lengthUpper = 1;
                _controller.indexUpper = 0;
                _isHitNumber = true;
                changeTextField("upper");
            }
            _tfUpper.appendText(arg1);
        }
        private function setCharacterString(arg1:String):void 
        {
            if (!_isHitAlphabet) 
            {
                _controller.textArrayLower = [];
                _controller.textArrayLower[0] = "";
                _controller.lengthUpper = 1;
                _controller.indexLower = 0;
                _isHitAlphabet = true;
                changeTextField("lower");
            }
            _tfLower.appendText(arg1);
        }
        
        private function bpmChangeHandler(e:Event):void 
        {
            driver.bpm = _controller.bpm;
        }
        
        private function loadCompleteHandler(e:ControllerEvent):void 
        {
            var _positonType:String = e.position;
            //
            if (_positonType == "upper") _isHitNumber = false;
            else _isHitAlphabet = false;
            
            changeTextField(_positonType);
        }
        
        private function changeTextField(positonType:String):void 
        {
            if (positonType == "upper")
            {
                _bdUpper = new BitmapData(_bdW, _bdH, false, 0x000000);
                //テキストがundefinedのときの処理
                if ( _controller.textArrayUpper[_controller.indexUpper] != null ) 
                _tfUpper.text = _controller.textArrayUpper[_controller.indexUpper];
                else _tfUpper.text = "SearchWord Fault";
                
                _controller.indexUpper++;
                if (_controller.lengthUpper <= _controller.indexUpper) _controller.indexUpper = 0;
                _countUpper = _countUpperStart;
            }
            else
            {
                _bdLower = new BitmapData(_bdW, _bdH, false, 0x000000);
                //テキストがundefinedのときの処理
                if(_controller.textArrayLower[_controller.indexLower] != null )
                _tfLower.text = _controller.textArrayLower[_controller.indexLower];
                else _tfLower.text = "SearchWord Fault";
                
                _controller.indexLower++;
                if (_controller.lengthLower <= _controller.indexLower) _controller.indexLower = 0;
                _countLower = _countLowerStart;
            }
        }
        
        private function createTextField(str:String = "" ):TextField 
        {
            
            var tf:TextField = new TextField();
            var tfm:TextFormat = new TextFormat();
            tf.textColor = 0xFF0000;
            tfm.size = _fontSize;
            tfm.font = _fontString;
            tf.defaultTextFormat = tfm;
            tf.background = true;
            tf.backgroundColor = 0x000000;
            tf.text = str;
            tf.autoSize = "left";
            tf.wordWrap = false;
            tf.antiAliasType = AntiAliasType.NORMAL;
            tf.height = 20;
            return tf;
        }
        
        private function setSiON():void 
        {
            // set voices from preset
            //パーカッションは配列となる
            var percusVoices:Array = presetVoice["valsound.percus"];
            
            //Upper
            voicesUpper[0] = percusVoices[0];  // bass drum
            voicesUpper[1] = percusVoices[27]; // snare drum
            voicesUpper[2] = percusVoices[16]; // close hihat
            voicesUpper[3] = percusVoices[22]; // open hihat
            var i:int;
            for (i=4; i<8;  i++) 
            {
                voicesUpper[i] = presetVoice["midi.bass2"];  // bass
            }
            for (i = 8; i < 16; i++)
            {
                voicesUpper[i] = presetVoice["midi.bass8"]; // e.piano            
            }
            
            //Lower
            for (i = 0; i < 4; i++)
            {
                voicesLower[i] = presetVoice["midi.piano6"]; //          
            }
            for (i = 4; i < 8; i++)
            {
                voicesLower[i] = presetVoice["midi.piano7"]; //          
            }
            for (i = 8; i < 16; i++)
            {
                voicesLower[i] = presetVoice["midi.piano8"]; //          
            }

            // listen
            //コールバック関数の呼ばれる間隔(1で16ビート)
            driver.setBeatCallbackInterval(1);
            //ビートイベント
            driver.addEventListener(SiONTrackEvent.BEAT, _onBeat);
            //タイマーの割り込み設定
            driver.setTimerInterruption(1, _onTimerInterruption);
            //bpmの設定
            driver.bpm = BPM;
            
            driver.play();
            driver.volume = 0.5;
            // ドラムマシンの生成
            drumMachine = new DrumMachine(int(Math.random()*16),int(Math.random()*16),int(Math.random()*16),int(Math.random()*16));
            drumMachine.volume = _drumVolume;
            drumMachine.play();
        }
        
        private function _onTimerInterruption():void 
        {
            _bdUpper.draw(_tfUpper, new Matrix(1, 0, 0, 1, _countUpper,-_bdHOffset), null, null);
            _bdLower.draw(_tfLower, new Matrix(1, 0, 0, 1, _countLower,-_bdHOffset), null, null);
            
            var i:int
            for(i = 0; i < _bdH; i++){
                if (_bdUpper.getPixel(_bdWHalf, i) > 8355840)  
                {
                    _trackUpper = driver.noteOn(_notesUpper[i], voicesUpper[i], _lengthUpper[i]);
                    _trackUpper.masterVolume = _upperVolume;
                }
                if (_bdLower.getPixel(_bdWHalf, i) > 8355840)  
                {
                    _trackLower = driver.noteOn(_notesLower[i], voicesLower[i], _lengthLower[i]);
                    _trackLower.masterVolume = _lowerVolume;
                }
            }
            _countUpper--;
            _countLower--;
        }
        //表示処理
        private function _onBeat(e:Event):void 
        {
            var i:int;
            var j:int;
            var isAllBlackUpper:Boolean = true;
            var isAllBlackLower:Boolean = true;
            
            _noKeyDownCountUpper++;
            _noKeyDownCountLower++;
            if (_noKeyDownCountUpper >= 4)
            {
                _noKeyDownCountUpper = 0;
                _tfUpper.appendText(" ");
            }
            if (_noKeyDownCountLower >= 4)
            {
                _noKeyDownCountLower = 0;
                _tfLower.appendText(" ");
            }
            
            
            for(i = 0; i < _bdH; i++){
                for (j = 0; j < _bdW; j++) {
                    //中央だけ判定処理
                    if (_bdW / 2 == j)
                    {
                        //Upper
                        if (_bdUpper.getPixel(j, i) >8355840)
                        {
                            _circleArrayUpper[i][j].changeYellowColor();
                            isAllBlackUpper = false;
                        }
                        else  _circleArrayUpper[i][j].changeBlackColor();
                        //Lower
                        if (_bdLower.getPixel(j, i) >8355840)
                        {
                            _circleArrayLower[i][j].changeYellowColor();
                            isAllBlackLower = false;
                        }
                        else _circleArrayLower[i][j].changeBlackColor();
                    }
                    //Upper
                    if (_bdUpper.getPixel(j, i) != 0x000000)
                    {
                        _circleArrayUpper[i][j].changeRedColor(_bdUpper.getPixel(j, i));
                        isAllBlackUpper = false;
                    }
                    else  _circleArrayUpper[i][j].changeBlackColor();
                    //Lower
                    if (_bdLower.getPixel(j, i) != 0x000000) 
                    {
                        _circleArrayLower[i][j].changeRedColor(_bdLower.getPixel(j, i));
                        isAllBlackLower = false;
                    }
                    else  _circleArrayLower[i][j].changeBlackColor();
                }
            }
            if (isAllBlackUpper && _countUpper < 0) 
            {
                changeTextField("upper");
                _countUpper = 30;
            }
            if (isAllBlackLower && _countLower < 0) 
            {
                changeTextField("lower");
                _countLower = 30;
            }
        }
        
        private function createDot(container:Sprite,circleArray:Array):void 
        {
            for(var i:int = 0; i < _bdH; i++){
                circleArray[i] = [];
                for (var j:int = 0; j < _bdW; j++) {
                    circleArray[i][j] =   new Circle(_dotRadius)
                    circleArray[i][j].y =  i * _dotRadius*1.5;
                    circleArray[i][j].x =  j * _dotRadius*1.5;
                    container.addChild(circleArray[i][j]);
                }
            }
        }
        
    }
}


import com.bit101.components.CheckBox;
import com.bit101.components.HUISlider;
import com.bit101.components.InputText;
import com.bit101.components.Label;
import com.bit101.components.PushButton;
import flash.display.GradientType;
import flash.display.InterpolationMethod;
import flash.display.SpreadMethod;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.geom.Matrix;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import org.libspark.betweenas3.BetweenAS3;
import org.libspark.betweenas3.tweens.ITween;

class Circle extends Sprite{
    private var _mat:Matrix = new Matrix();
    private var _radius:int;
    private var _radius2:int;
    private var _redCircle:Sprite;
    private var _blackCircle:Sprite;
    
    private var _redColorArray:Array = [0xFFCCCC, 0xFF6666, 0xFF0000];
    private var _redColorArrayLow:Array = [0xFFCCCC, 0xFF9999, 0xFF6666];
    private var _blackColorArray:Array = [0xCCCCCC, 0x666666, 0x000000];
    private var _yellowColorArray:Array = [0xFFFFCC, 0xFFFF66, 0x000000];
    private var _yellowCircle:Sprite;
    private var _redTween:ITween;
    private var _yellowTween:ITween;
    private var _redCircleLow:Sprite;
    private var _colorArray:Array = [];

    
    public function Circle(radius:int = 8):void
    {
        _radius = radius;
        _radius2 = radius * 2;
        
        _blackCircle = new Sprite();
        createColor(_blackColorArray,_blackCircle);
        addChild(_blackCircle);

        _redCircle =  new Sprite();
        createColor(_redColorArray,_redCircle);
        addChild(_redCircle);
            
        _yellowCircle =  new Sprite();
        createColor(_yellowColorArray,_yellowCircle);
        addChild(_yellowCircle);
        
        _redCircle.visible = false;
        _yellowCircle.visible = false;
        
        _redCircle.filters = [new GlowFilter()];
        
    }
    public function createColor(color:Array,container:Sprite):void
    {
        container.graphics.clear();
        _mat.createGradientBox(_radius2,_radius2, 0, -_radius2*3/4, -_radius2*3/4)
        container.graphics.clear();
        container.graphics.beginGradientFill (
            GradientType.RADIAL,
            [color[0] , color[1] ,  color[2]],
            [     100 ,      100 ,  100],
            [       0 ,       80 ,  255],
            _mat,
            SpreadMethod.PAD,
            InterpolationMethod.LINEAR_RGB,
            0.0
        );
        container.graphics.drawCircle(0, 0,_radius);
        container.graphics.endFill();        
    }
    public function changeRedColor(color:int = 0):void
    {
        _redCircle.alpha = color / 16711680;
        _redCircle.visible = true;
    }
    public function changeYellowColor():void
    {
        _yellowCircle.visible = true;
        if (_yellowTween) _yellowTween.stop();
        _yellowCircle.scaleX = _yellowCircle.scaleY = 1.5;
        _yellowTween = BetweenAS3.delay(BetweenAS3.to(_yellowCircle, { scaleX:0,scaleY:0 }, .2), .2);
        _yellowTween.play();
    }
    public function changeBlackColor():void
    {
        _redCircle.visible = false;
        _yellowCircle.visible = false;
    }
}


class Controller extends Sprite
{
    static public const UPPER_LOAD_COMPLETE:String = "upperLoadComplete";
    static public const LOWER_LOAD_COMPLETE:String = "lowerLoadComplete";
    static public const CHANGE_BPM:String = "changeBpm";
    static public const CHANGE_DRUM_ONOFF:String = "changeDrumOnoff";
    private var _inputUpper:InputText;
    private var _inputLower:InputText;
    private var _textArrayUpper:Array = [];
    private var _textArrayLower:Array = [];
    
    private var _indexUpper:int = 0;
    private var _indexLower:int = 0;
    private var _lengthUpper:int = 1;
    private var _lengthLower:int = 1;
    
    
    private var _urlLoaderUpper:URLLoader = new URLLoader();
    private var _urlLoaderLower:URLLoader = new URLLoader();
    private var _bpm:int;
    private var _isDrumON:Boolean;
    private var _tfUpper:TextField;
    private var _tfLower:TextField;
    private var _volumeSliderUpper:HUISlider;
    private var _volumeSliderLower:HUISlider;
    private var _volumeSliderDrum:HUISlider;
    
    private var _demoTextArray:Array = [
    "You can't get Tweets,Please try another keyword"
    ];
    
    public function Controller()
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }
    
    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        
        //背景
        var bg:Sprite =  new Sprite();
        bg.graphics.beginFill(0xdedefe);
        bg.graphics.drawRect(0, 0, 465, 80);
        bg.graphics.endFill();
        addChild(bg).alpha = .8;
        
        _tfUpper = createTextField("FlashCS5");
        _tfUpper.x = 53;
        _tfUpper.y = 5;
        addChild(_tfUpper);
        _tfLower = createTextField("wonderfl");
        _tfLower.x = 53;
        _tfLower.y = 25;
        addChild(_tfLower);
        
        var upper:Label = new Label(this, 20, 7, "Upper");
        var lower:Label = new Label(this, 20, 27, "Upper");

        
        var buttonUpper:PushButton = new PushButton(this, 130, 5, "TWITTER SEARCH", onMouseClick);
        buttonUpper.name = "upper";
        var buttonLower:PushButton = new PushButton(this, 130, 25, "TWITTER SEARCH", onMouseClick);
        buttonLower.name = "lower";
        
        var resetUpper:PushButton = new PushButton(this, 235, 5, "RESET", resetClick);
        resetUpper.name = "upper";
        resetUpper.width = 50;
        var resetLower:PushButton = new PushButton(this, 235, 25, "RESET", resetClick);
        resetLower.name = "lower";
        resetLower.width = 50;
        
        var check1:CheckBox = new CheckBox(this, 235, 49, "DRUM KIT", drumCheckHandlerk);
        check1.selected = true;
        
        var bpmLabl:Label = new Label(this, 20, 45, "BPM");
        var slider:HUISlider = new HUISlider(this, 44, 45, "", onChange);
        slider.maximum = 200; // 上限
        slider.minimum = 60; // 下限
        slider.value = 80;
        slider.width = 200;
        
        var volUpper:Label = new Label(this, 325, 5, "VOL:UPPER");
        _volumeSliderUpper = new HUISlider(this, 370, 5, null, onChangeVolumeHandler);
        _volumeSliderUpper.maximum = 100; // 上限
        _volumeSliderUpper.minimum = 0; // 下限
        _volumeSliderUpper.value = 32;
        _volumeSliderUpper.width = 100;
        
        var volLower:Label = new Label(this, 325, 25, "VOL:LOWER");
        _volumeSliderLower = new HUISlider(this, 370, 25, null, onChangeVolumeHandler);
        _volumeSliderLower.maximum = 100; // 上限
        _volumeSliderLower.minimum = 0; // 下限
        _volumeSliderLower.value = 32;
        _volumeSliderLower.width = 100;
        
        var volDrum:Label = new Label(this, 325, 45, "VOL:DRUM");
        _volumeSliderDrum = new HUISlider(this, 370, 45, null, onChangeVolumeHandler);
        _volumeSliderDrum.maximum = 100; // 上限
        _volumeSliderDrum.minimum = 0; // 下限
        _volumeSliderDrum.value = 70;
        _volumeSliderDrum.width = 100;
    }
    
    private function onChangeVolumeHandler(e:Event):void 
    {
        var type:String;
        if (e.target == _volumeSliderUpper)
        {
            type = "upper";
        }
        else if(e.target == _volumeSliderLower)
        {
            type = "lower";
        }
        else
        {
            type = "drum";
        }
        dispatchEvent(new ControllerVolumeEvent(ControllerVolumeEvent.CHANGE_VOLUME, type, e.target.value));
    }
    
    private function createTextField(str:String = "",fontSize:int = 12 ):TextField 
    {
        var tf:TextField = new TextField();
        var tfm:TextFormat = new TextFormat();
        tf.textColor = 0x666666;
        tfm.size = fontSize;
        tfm.font = "_ゴシック";
        tf.defaultTextFormat = tfm;
        tf.background = true;
        tf.border = true;
        tf.borderColor = 0x999999;
        tf.backgroundColor = 0xCCCCCC;
        tf.type = TextFieldType.INPUT;

        tf.text = str;
        tf.width = 70;
        tf.wordWrap = false;
        tf.height = 19;
        return tf;
    }
    
    private function drumCheckHandlerk(e:MouseEvent):void 
    {
        _isDrumON = e.currentTarget.selected;
        dispatchEvent(new Event(Controller.CHANGE_DRUM_ONOFF));
    }
    
    private function resetClick(e:MouseEvent):void 
    {
        if (e.target.name == "upper")
        {
            _indexUpper = 0;
            _textArrayUpper = [];
            _lengthUpper = 1;
            _textArrayUpper[0] = "";
        }
        else
        {
            _indexLower = 0;
            _textArrayLower = [];
            _lengthLower = 1;
            _textArrayLower[0] = "";
        }
        dispatchEvent(new ControllerEvent(ControllerEvent.LOAD_COMPLETE,e.target.name));
    }
    
    private function onChange(e:Event):void 
    {
        _bpm = e.currentTarget.value;
        dispatchEvent(new Event(Controller.CHANGE_BPM));
    }
    public function onMouseClick(e:MouseEvent):void 
    {
        var searchWord:String;
        var xmlURL:String = "http://search.twitter.com/search.atom?lang=ja&page=1&rpp=10&q=";
        var urlLoader:URLLoader
        if (e.target.name == "upper")
        {
            searchWord = _tfUpper.text;
            urlLoader = _urlLoaderUpper;
        }
        else
        {
            searchWord = _tfLower.text;
            urlLoader = _urlLoaderLower;
        }
        urlLoader.addEventListener(Event.COMPLETE, twitterLoadCompleteHandler);
        urlLoader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
        xmlURL += encodeURIComponent(searchWord);
        urlLoader.load(new URLRequest(xmlURL));
    }
    
    private function ioErrorHandler(e:Event):void 
    {
        var urlLoader:URLLoader = URLLoader(e.target);
        var type:String;
        if (urlLoader == _urlLoaderUpper) type = "upper";
        else type = "lower";
        setDummyText(type);
    }
    private function shuffleArray(myArray:Array):void{
        var i:Number = myArray.length;
        while(i){
            var randomNumber:Number = Math.floor(Math.random()*(i--));
            var temp:Object = myArray[i];
            myArray[i] = myArray[randomNumber];
            myArray[randomNumber] = temp;
        }
    }
    private function setDummyText(type:String):void 
    {
        //ダミーのテキストをセット
        var length:int;
        var array:Array;
        if (type == "upper")
        {
            _lengthUpper = _demoTextArray.length;
            length = _lengthUpper;
            _indexUpper = 0;
            _textArrayUpper = [];
            array = _textArrayUpper;
        }
        else
        {
            _lengthLower = _demoTextArray.length;
            length = _lengthLower;
            _indexLower = 0;
            _textArrayLower = [];
            array = _textArrayLower;
        }
        for (var i:int = 0; i < _lengthUpper; i++)
        {
            array.push(_demoTextArray[i]);
        }
        dispatchEvent(new ControllerEvent(ControllerEvent.LOAD_COMPLETE,type));
    }
    private function twitterLoadCompleteHandler(e:Event):void 
    {
        var xml:XML = new XML(e.target.data);
        default xml namespace = new Namespace("http://www.w3.org/2005/Atom");
        var urlLoader:URLLoader = URLLoader(e.target);
                
        var array:Array;
        var position:String;
        if (urlLoader == _urlLoaderUpper)
        {
            if (_lengthUpper < 1)
            {
                setDummyText("upper");
                return;
            }
            _indexUpper = 0;
            _textArrayUpper = [];
            _lengthUpper = xml.entry.length();
            array = _textArrayUpper;
            position = "upper";
        }
        else
        {
            if (_lengthLower < 1)
            {
                setDummyText("lower");
                return;
            }
            _indexLower = 0;
            _textArrayLower = [];
            _lengthLower = xml.entry.length();
            array = _textArrayLower;
            position = "lower";
        }
        for each(var obj:String in xml.entry.title)
        {
            array.push(obj);
        }
        shuffleArray(array);
        dispatchEvent(new ControllerEvent(ControllerEvent.LOAD_COMPLETE,position));
    }
    
    public function get textArrayUpper():Array { return _textArrayUpper; }
    
    public function set textArrayUpper(value:Array):void 
    {
        _textArrayUpper = value;
    }
    
    public function get textArrayLower():Array { return _textArrayLower; }
    
    public function set textArrayLower(value:Array):void 
    {
        _textArrayLower = value;
    }
    
    public function get indexUpper():int { return _indexUpper; }
    
    public function set indexUpper(value:int):void 
    {
        _indexUpper = value;
    }
    
    public function get indexLower():int { return _indexLower; }
    
    public function set indexLower(value:int):void 
    {
        _indexLower = value;
    }
    
    public function get lengthUpper():int { return _lengthUpper; }
    
    public function get lengthLower():int { return _lengthLower; }
        
    public function get bpm():int { return _bpm; }
    
    public function get isDrumON():Boolean { return _isDrumON; }
    
    public function set lengthUpper(value:int):void 
    {
        _lengthUpper = value;
    }
    
    public function set lengthLower(value:int):void 
    {
        _lengthLower = value;
    }
}

class ControllerEvent extends Event
{
    static public const LOAD_COMPLETE:String = "LoadComplete";
    
    public var position:String;
    
    public function ControllerEvent(type:String,position:String, bubbles:Boolean = false, cancelable:Boolean = false):void
    {
        this.position = position;
        super(type,bubbles,cancelable);

    }
    public override function clone():Event {
        return new (type,position,bubbles,cancelable);
    }
  
    public override function toString():String {
        return formatToString("ControllerEvent","position","bubbles","cancelable");
    }
}
class ControllerVolumeEvent extends Event
{
    static public const CHANGE_VOLUME:String = "changeVolume";
    
    public var position:String;
    public var vol:int;
    
    public function ControllerVolumeEvent(type:String,position:String,vol:int, bubbles:Boolean = false, cancelable:Boolean = false):void
    {
        this.vol = vol;
        this.position = position;
        super(type,bubbles,cancelable);

    }
    public override function clone():Event {
        return new (type,position,vol,bubbles,cancelable);
    }
  
    public override function toString():String {
        return formatToString("ControllerVolumeEvent","position","vol","bubbles","cancelable");
    }
}