var ohoa = {
    loadSoundManager: function(options, onload) {
        if (typeof options == 'function') {
            onload = options;
            options = {};
        }
        loadLibrary('soundmanager2.js', function() {
            var soundManager = ohoa.createSoundManager(options);
            soundManager.onready(function(status) {
                onload(soundManager);
            });
        });
    },
    
    createSoundManager: function(options) {
        if (!window.soundManager) {
            options = options || {};
            var soundManager = new SoundManager();
            soundManager.beginDelayedInit();
            soundManager.debugMode = false;
            soundManager.debugFlash = false;
            soundManager.useConsole = true;
            soundManager.consoleOnly = true;
            soundManager.url = '/flash/soundmanager2_flash9.swf?2';
            soundManager.flashVersion = 9;
            for (var k in options) {
                soundManager[k] = options[k];
            }
            window.soundManager = soundManager;
        }
        return window.soundManager;
    }
};

//
// Music Player

function MusicPlayer(soundManager, root) {
    var self = this;
    
    this.soundManager = soundManager;
    
    this.$root = $(root);
    this.$status = this.$root.find('.player-status');
    this.$controls = this.$root.find('.controls a');
    this.playlist = [];
    this.curr = 0;
    
    this.$root.find('.playlist a').each(function() {
        self.playlist.push({ url: $(this).attr('href'), title: $(this).text() });
    });
    
    this.$controls.click(function() { self[this.getAttribute('rel')](); return false; });
    
    this._go(0);
    this._activate('stop');
};

MusicPlayer.prototype = {
    _getTrack: function() {
        var self = this;
        var entry = this.playlist[this.curr];
        if (!entry.sound) {
            entry.sound = this.soundManager.createSound({
                id: 'track' + this.curr,
                url: entry.url,
                volume: 100,
                autoLoad: false,
                autoPlay: false,
                multiShot: false,
                stream: true,
                onfinish: function() { self.next(); self.play(); }
            });
        }
        return entry;
    },
    _go: function(offset) {
        this.curr += offset;
        if (this.curr < 0) this.curr = this.playlist.length - 1;
        if (this.curr >= this.playlist.length) this.curr = 0;
        this.$status.text(this._getTrack().title);
    },
    _activate: function(action) {
        this.$controls.removeClass('active').filter('[rel=' + action + ']').addClass('active');
    },
    prev: function() {
        var trk = this._getTrack().sound, wasPlaying = trk.playState, pos = trk.position;
        this.stop();
        if (pos < 3000) this._go(-1);
        if (wasPlaying) this.play();
    },
    next: function() {
        var wasPlaying = this._getTrack().sound.playState;
        this.stop();
        this._go(1);
        if (wasPlaying) this.play();
    },
    stop: function() {
        this._getTrack().sound.stop();
        this._activate('stop');
    },
    play: function() {
        this._getTrack().sound.play();
        this._activate('play');
    }
};

MusicPlayer.init = function(command) {
    ohoa.loadSoundManager(function(soundManager) {
        var player = new MusicPlayer(soundManager, '#music-player');
        player[command]();
    });
};

//
// Load library

function loadLibrary(library, onload) {
    if (library.match(/^http:\/\//)) {
        var scriptPath = library;
    } else {
        var scriptPath = '/javascripts/' + library + '?1', loaded = false;
    }
    $('script').each(function() {
        if ((this.src || '').indexOf(scriptPath) >= 0) {
            loaded = true;
            onload();
        }
    });
    if (!loaded) {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = scriptPath;
        s.onload = onload;
        s.onreadystatechange = function() { if (this.readyState == 'complete') onload(); }
        document.getElementsByTagName('head')[0].appendChild(s);
    }
}

//
// All the other stuff

$(function() {
    
    $('#music-player .controls a').one('click', function() {
        MusicPlayer.init($(this).attr('rel'));
        return false;
    });
        
    $('input').each(function() { $(this).addClass(this.type); });
    $('.rollover').simpleImageRollover();
    
    $('.bg-fader').hover(function() {
        $(this).find('.bg-fade').stop().animate({opacity: 1}, 200);
    }, function() {
        $(this).find('.bg-fade').stop().animate({opacity: 0}, 200);
    });
    
    var nextZ = 2000;
    $('#social-links li').each(function() {
        var cancel = false, $dialog = $(this).find('.dialog'), animating = false;
        $dialog.append('<div class="arrow" />');
        $dialog.css({opacity: 0, display: 'none'});
        $(this).hover(function() {
            cancel = true;
            $dialog.css({zIndex: nextZ++, display: 'block'}).stop().animate({opacity: 0.9});
        }, function() {
            var sef = this;
            cancel = false;
            setTimeout(function() {
                if (!cancel) {
                    $dialog.stop().animate({opacity: 0}, function() {
                        $(this).css({display: 'none'});
                    });
                    }
            }, 200);
        });
    });
    
    $('#sidebar .nav a:not(.selected)').hover(function() {
        $(this).stop().css({backgroundColor: 'white', color: 'black'})
                      .animate({backgroundColor: 'black', color: 'white'}, 300);
    }, function() {
        
    });
    
    //
    // Retweets
    
    var retweetCount = 0;
    
    function makeRetweetHandler(element) {
        return function(data) {
            var res;
            for (var r in data.results) { res = data.results[r]; break; }
            var title = element.title || document.title;
            element.href = "http://twitter.com/home?status=" + encodeURIComponent('RT ' + title + ' ' + res.shortUrl);
            $(element).data('state.bitly', 'complete');
            window.location = element.href;
        }
    }
    
    $('.retweet').click(function() {
        var state = $(this).data('state.bitly'), self = this;
        if (state == 'busy') {
            alert('Please wait... URL shortening in progress.');
            return false;
        } else if (state == 'complete') {
            return true;
        } else {
            $(this).data('state.bitly', 'busy');
            var bitlyUser = 'retweetjs';
            var bitlyKey  = 'R_6287c92ecaf9efc6f39e4f33bdbf80b1';
            loadLibrary('http://bit.ly/javascript-api.js?version=latest&login=' + bitlyUser + '&apiKey=' + bitlyKey, function() {
                var fn = 'retweetShortenResponse' + (retweetCount++);
                window[fn] = makeRetweetHandler(self);
                BitlyClient.shorten(window.location, fn);
            });
            return false;
        }
    });
    
    //
    // Contact Form
    
    $('#contact-actuator').click(function() {
      loadLibrary('jquery.boxy.js', function() {
        new Boxy($('#contact-form'), {
          clone: true,
          title: "Contact",
          unloadOnHide: true,
          behaviours: function(ele) {
            var self = this;
            ele.find('input[type=submit]').click(function() {
              $.ajax({
                type: 'POST',
                url: '/contact.php',
                data: {
                  name: ele.find('[name=name]').val(),
                  email: ele.find('[name=email]').val(),
                  subject: ele.find('[name=subject]').val(),
                  comments: ele.find('[name=comments]').val()
                },
                dataType: 'json',
                success: function() {
                  alert("Thanks!");
                  self.hide();
                },
                error: function(xhr, status) {
                  alert("Fail. Please complete all fields and ensure your email address is valid.");
                }
              });
              return false;
            });
          }
        });
      });
      return false;
    });
    
    //
    // Pixel FX
	
  	var grid = new PixelGrid($('#pixels tbody')[0], 300, 1);
  	grid.fillRandom([325, 0.974, 0.8980], [5, 0.05, 0.15]);
  	new PixelGrid.Glimmer(grid, 30);
	
});
