// $Id: bee.js,v 1.3 2010/02/10 01:10:09 sap Exp $


/****************
*               *
*   animation   *
*               *
****************/

var wWidth;
var wHeight;
var currentPoint = 0;
var cPos = [-100, 400]

var xMoveMax = 600;
var yMoveMax = 100;
var keyPoints = 6;
var bWait = 3000;
var bee_counter = 0;
var bee_counter_max = 7; // number of iterations @ 4s ea?



$(window).load(function(){
    
    
    
    //var soundManager = new SoundManager();
    //alert('xxx');
    //window.setTimeout(do_nothing, 0);
    //if (soundManager)
    //{
        
    //if (soundManagerInit()) {
        
    //soundManager.play('bumble');

// setup
    wWidth = $(window).width();
    wHeight = $(window).height();
    $('body').append('<div id="bcontainer"><div id="fbee"><img src="/img/bee1.gif" alt="" /></div></div>');
    $('#bcontainer').css({
        position: 'absolute',
        top: '0',
        left: '0',
        width: '1px',
        height: '1px'
    });
    
    $('#fbee').click(function(){
        $(this).fadeOut();
    })
    .css({
        position: 'absolute',
        top: cPos[1]+'px',
        left: cPos[0]+'px',
        zIndex: '999',
        width: '84px',
        height: '84px'
    });
    
    // start the animation
    window.setTimeout(do_sound_and_motion, bWait);
});

function do_sound_and_motion () {
    window.setTimeout('soundManager.play(\'bumble\')', 0);
    window.setTimeout('bAnimate()', 2000);
}

// move the bee
function bAnimate() {

        if (bee_counter == bee_counter_max) return false; // stop

    bee_counter++;

    bWait = randomBetween(20, 200);
    nPos = bKeyPoint(cPos);

    if(currentPoint >= keyPoints) {
        nPos[0] = -100;
        keyPoints = randomBetween(6, 12);
        currentPoint = 0;
        bWait = randomBetween(3000, 6000);
    } else {
        currentPoint++;
    }

    dX = nPos[0] - cPos[0];
    dY = nPos[1] - cPos[1];
    cPos = nPos;
    dist = Math.sqrt(dX*dX + dY*dY);
    bSpeed = Math.log(dist) * 150;

    //alert('dX ' + dX)
    //alert('dY ' + dY)
    
    if(dX > 0) {
        $('#fbee img').attr({src: '/img/bee2.gif'});
    } else {
        $('#fbee img').attr({src: '/img/bee1.gif'});
    }

    $('#fbee').animate({left: nPos[0]+'px', top: nPos[1]+'px'}, bSpeed, function(){
        window.setTimeout(bAnimate, bWait);
    });
}

// generate key points
function bKeyPoint(point) {
    xMin = point[0] - xMoveMax;
    xMax = point[0] + xMoveMax;
    yMin = point[1] - yMoveMax;
    yMax = point[1] + yMoveMax;

    if(xMin<100) xMin = 100;
    if(yMin<100) yMin = 100;
    if(xMax>(wWidth-200)) {
        xMax = wWidth-200;
    }
    if(yMax>(wHeight-200)) {
        yMax = wHeight-200;
    }

    x = randomBetween(xMin, xMax);
    y = randomBetween(yMin, yMax);

    return [x, y];
}

// preload the images
$('body').append('<img alt="" src="/img/bee1.gif" style="position: absolute; left: -200px" />')
$('body').append('<img alt="" src="/img/bee2.gif" style="position: absolute; left: -200px" />')

// get the new window size on resize
function onResize() {
    wWidth = $(window).width();
    wHeight = $(window).height();
    $('#bcontainer').css({
        width: wWidth+'px',
        height: wHeight+'px'
    });
};

var resizeTimer = null;
$(window).bind('resize', function() {
    if (resizeTimer) clearTimeout(resizeTimer);
    resizeTimer = setTimeout(onResize, 100);
});

// random number generators
function random(X) {
    return Math.floor(X * (Math.random() % 1));
}
function randomBetween(MinV, MaxV) {
    return MinV + random(MaxV - MinV + 1);
}



/*
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
    everyTime: function(interval, label, fn, times) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        global: [],
        guid: 1,
        dataKey: "jQuery.timer",
        regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseFloat(result[1]);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times) {
            var counter = 0;
            
            if (jQuery.isFunction(label)) {
                if (!times) 
                    times = fn;
                fn = label;
                label = interval;
            }
            
            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval < 0)
                return;

            if (typeof times != 'number' || isNaN(times) || times < 0) 
                times = 0;
            
            times = times || 0;
            
            var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
            
            if (!timers[label])
                timers[label] = {};
            
            fn.timerID = fn.timerID || this.guid++;
            
            var handler = function() {
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
            };
            
            handler.timerID = fn.timerID;
            
            if (!timers[label][fn.timerID])
                timers[label][fn.timerID] = window.setInterval(handler,interval);
            
            this.global.push( element );
            
        },
        remove: function(element, label, fn) {
            var timers = jQuery.data(element, this.dataKey), ret;
            
            if ( timers ) {
                
                if (!label) {
                    for ( label in timers )
                        this.remove(element, label, fn);
                } else if ( timers[label] ) {
                    if ( fn ) {
                        if ( fn.timerID ) {
                            window.clearInterval(timers[label][fn.timerID]);
                            delete timers[label][fn.timerID];
                        }
                    } else {
                        for ( var fn in timers[label] ) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }
                    
                    for ( ret in timers[label] ) break;
                    if ( !ret ) {
                        ret = null;
                        delete timers[label];
                    }
                }
                
                for ( ret in timers ) break;
                if ( !ret ) 
                    jQuery.removeData(element, this.dataKey);
            }
        }
    }
});

jQuery(window).bind("unload", function() {
    jQuery.each(jQuery.timer.global, function(index, item) {
        jQuery.timer.remove(item);
    });
});


/********************
*                   *
*   sound manager   *
*                   *
********************/

var isIE = navigator.appName.toLowerCase().indexOf('internet explorer')+1;
var isMac = navigator.appVersion.toLowerCase().indexOf('mac')+1;

function SoundManager(container) {
  // DHTML-controlled sound via Flash
  var self = this;
  this.movies = []; // movie references
  this.container = container;
  this.unsupported = 0; // assumed to be supported
  this.defaultName = 'default'; // default movie
  
  this.FlashObject = function(url) {
    var me = this;
    this.o = null;
    this.loaded = false;
    this.isLoaded = function() {
      if (me.loaded) return true;
      if (!me.o) return false;
      me.loaded = ((typeof(me.o.readyState)!='undefined' && me.o.readyState == 4) || (typeof(me.o.PercentLoaded)!='undefined' && me.o.PercentLoaded() == 100));
      return me.loaded;
    }
    this.mC = document.createElement('div');
    this.mC.className = 'movieContainer';
    with (this.mC.style) {
      // "hide" flash movie
      position = 'absolute';
      left = '-256px';
      width = '64px';
      height = '64px';
    }
    
    // mod...
    var url2 = '/soundcontroller.swf';
  
    var html = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="' + url2 + '"><param name="quality" value="high"></object>','<embed src="' + url2 + '" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'];
    if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
      this.mC.innerHTML = html[0];
      this.o = this.mC.getElementsByTagName('object')[0];
    } else {
      this.mC.innerHTML = html[1];
      this.o = this.mC.getElementsByTagName('embed')[0];
    }
    
    document.getElementsByTagName('div')[0].appendChild(this.mC);
  }

  this.addMovie = function(movieName,url) {
    self.movies[movieName] = new self.FlashObject(url);
  }

  this.checkMovie = function(movieName) {
    movieName = movieName||self.defaultName;
    if (!self.movies[movieName]) {
      self.errorHandler('checkMovie','Exception: Could not find movie',arguments);
      return false;
    } else {
      return (self.movies[movieName].isLoaded())?self.movies[movieName]:false;
    }
  }

  this.errorHandler = function(methodName,message,oArguments,e) {
    writeDebug('<div class="error">soundManager.'+methodName+'('+self.getArgs(oArguments)+'): '+message+(e?' ('+e.name+' - '+(e.message||e.description||'no description'):'')+'.'+(e?')':'')+'</div>');
  }

  this.play = function(soundID,loopCount,noDebug,movieName) {
    if (self.unsupported) return false;
    movie = self.checkMovie(movieName);
    if (!movie) return false;
    if (typeof(movie.o.TCallLabel)!='undefined') {
      try {
        self.setVariable(soundID,'loopCount',loopCount||1,movie);
        movie.o.TCallLabel('/'+soundID,'start');
        if (!noDebug) writeDebug('soundManager.play('+self.getArgs(arguments)+')');
      } catch(e) {
        self.errorHandler('play','Failed: Flash unsupported / undefined sound ID (check XML)',arguments,e);
      }
    }
  }

  this.stop = function(soundID,movieName) {
    if (self.unsupported) return false;
    movie = self.checkMovie(movieName);
    if (!movie) return false;
    try {
      movie.o.TCallLabel('/'+soundID,'stop');
      writeDebug('soundManager.stop('+self.getArgs(arguments)+')');
    } catch(e) {
      // Something blew up. Not supported?
      self.errorHandler('stop','Failed: Flash unsupported / undefined sound ID (check XML)',arguments,e);
    }
  }

  this.getArgs = function(params) {
    var x = params?params.length:0;
    if (!x) return '';
    var result = '';
    for (var i=0; i<x; i++) {
      result += (i&&i<x?', ':'')+(params[i].toString().toLowerCase().indexOf('object')+1?typeof(params[i]):params[i]);
    }
    return result
  }

  this.setVariable = function(soundID,property,value,oMovie) {
    // set Flash variables within a specific movie clip
    if (!oMovie) return false;
    try {
      oMovie.o.SetVariable('/'+soundID+':'+property,value);
      // writeDebug('soundManager.setVariable('+self.getArgs(arguments)+')');
    } catch(e) {
      // d'oh
      self.errorHandler('setVariable','Failed',arguments,e);
    }
  }

  this.setVariableExec = function(soundID,fromMethodName,oMovie) {
    try {
      oMovie.o.TCallLabel('/'+soundID,'setVariable');
    } catch(e) {
      self.errorHandler(fromMethodName||'undefined','Failed',arguments,e);
    }
  }

  this.callMethodExec = function(soundID,fromMethodName,oMovie) {
    try {
      oMovie.o.TCallLabel('/'+soundID,'callMethod');
    } catch(e) {
      // Something blew up. Not supported?
      self.errorHandler(fromMethodName||'undefined','Failed',arguments,e);
    }
  }

  this.callMethod = function(soundID,methodName,methodParam,movieName) {
    movie = self.checkMovie(movieName||self.defaultName);
    if (!movie) return false;
    self.setVariable(soundID,'jsProperty',methodName,movie);
    self.setVariable(soundID,'jsPropertyValue',methodParam,movie);
    self.callMethodExec(soundID,methodName,movie);
  }

  this.setPan = function(soundID,pan,movieName) {
    self.callMethod(soundID,'setPan',pan,movieName);
  }

  this.setVolume = function(soundID,volume,movieName) {
    self.callMethod(soundID,'setVolume',volume,movieName);
  }

  // constructor - create flash objects

  if (isIE && isMac) {
    this.unsupported = 1;
  }

  if (!this.unsupported) {
    this.addMovie(this.defaultName,'soundcontroller.swf');
    // this.addMovie('rc','rubber-chicken-audio.swf');
  }

}

function SoundManagerNull() {
  // Null object for unsupported case
  this.movies = []; // movie references
  this.container = null;
  this.unsupported = 1;
  this.FlashObject = function(url) {}
  this.addMovie = function(name,url) {}
  this.play = function(movieName,soundID) {
    return false;
  }
  this.defaultName = 'default';
}

function writeDebug(msg) {
  var o = document.getElementById('debugContainer');
  if (!o) return false;
  var d = document.createElement('div');
  d.innerHTML = msg;
  o.appendChild(d);
}

var soundManager = null;

function soundManagerInit() {
  soundManager = new SoundManager();
}
