var APP = (function ($) { 
    var app = {}, reel, lastfm = $('#lastfm'), src = 'https://s3.amazonaws.com/blenderbox/bg.jpg', $bg = $('#bg'), bg, img;

    function bg() {
        bg = new Image();
        bg.onload = onBgLoad;
        bg.src = src;
    }
    function onBgLoad() {
        img = $('<img/>').attr('src', src).hide();
        $bg.append(img);
        if(img.width() < 1) { setTimeout(showBg, 500); }
        else { showBg(); }
    }
    function showBg() {
        img.css('marginLeft', -img.width() * .5);
        img.hide().fadeIn();
    }
    function onProjectOver(e){
        var el = $(e.currentTarget), copy = el.find('.copy');
        copy.stop();
        el.find('p').show();
        copy.animate({ top: el.find('img').height() - copy.height()}, 300);
    }
    function onProjectOut(e){
        var el = $(e.currentTarget), copy = el.find('.copy');
        copy.stop().animate({ top:el.find('img').height() - (!el.parent().hasClass('featured') ? 32 : 44)}, function(){ el.find('p').hide(); });
    }

    app.placeholder = function(id, text) {
        if (Modernizr.input.placeholder){ return; }
        var d = text, $id = $(id);
        $id.focus(function() { 
            if (this.value === d) { this.value = ''; }
        });
        $id.blur(function() { 
            if ($.trim(this.value) === '') { this.value = d; }
        });
        $id.blur();
    }
    app.hideReel = function() {
        reel.remove();
        reel=undefined;
    };
    app.lastfm = function() {
        if(lastfm.length<=0) { return; }
        $.ajax({ url: '/blocks/lastfm', success: app.onLastFMReturn });
    };
    app.onLastFMReturn = function(r) {
        var cur = r[0], last = r[1], html = '';
        // move to a template
        html += '<a href="http://www.last.fm/music/'+cur.artist+'" target="_blank">';
        if(cur.image!=='') { html += '<img src="'+cur.image+'" alt="'+cur.name+'" height="56" width="56" />'; }
        else { html += '<img src="/images/icons/album.jpg" alt="'+cur.name+'" height="56" width="56" />'; }
        html += '</a>';
        html += cur.name;
        html += '<br/><a href="http://www.last.fm/music/'+cur.artist+'" target="_blank">'+cur.artist+'</a>';
        lastfm.find('.listening').html(html);
        lastfm.find('.last').html('<strong>LAST:</strong> '+last.name+', <a href="http://www.last.fm/music/'+last.artist+'" target="_blank">'+last.artist+'</a>');
    };
    app.projects = function() {
      if($('a.project').length<=0){ return; }
      $('a.project').live('mouseenter', onProjectOver);
      $('a.project').live('mouseleave', onProjectOut);
    };
    app.reel = function() {
        if($('#reel').length<=0){ return; }
        $('#reel').click(app.showReel);
    };
    app.search = function() {
        var s=$('#search'), i='#searchInput';
        if(window.is_search && is_search===true){
            $(i).val(q);
            s.show();
        }
        app.placeholder(i, 'Search');
        $('#searchLink').click(function(){ s.slideToggle(); return false; });
        $('#searchBtn').click(function(){ $('#searchForm').submit(); });
        var options = {
            noCache: true,
            serviceUrl:'/search/autocomplete',
            onSelect: function(value, data){ 
              $('#url').val(data);
              window.location = data;
              return false;
            }
        };
        var a = $('#searchInput').autocomplete(options);
    };
    app.showReel = function() {
      if(reel!==undefined) { return false; }
        reel = $('<div id="reelContainer"><iframe src="http://player.vimeo.com/video/16282402?byline=0&amp;autoplay=1" width="651" height="366" frameborder="0"></iframe><a href="javascript:;">close</a></div>');
        reel.find('a').click(app.hideReel);
        $('body').append(reel);
        return false;
    };
    app.init = function() {
        var token = $("meta[name='csrf-token']").attr("content");
        $.ajaxSetup({
            beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRF-Token", token); },
            cache: false,
            error: function(x, e) {
                var txt = '';
                switch (x.status) {
                    case 404: txt = 'Oops, the URL I was trying to use wasn\'t found.'; break;
                    case 500: txt = 'A server error!\nIf it continues to happen, contact someone.'; break;
                };
                switch (e) {
                    case 'parsererror': txt = 'Couldn\'t parse the JSON'; break;
                    case 'timeout': txt = 'Oh no! Time Out!'; break;
                };
                if(txt!==''){
                    try{ console.log(txt); } catch(e) { }
                }
            },
            type: "POST"
        });
        $('form:not(.validate)').submit(function(e) {
            $('form input[type=submit]').attr('disabled', 'disabled');
            return true;
        });
        
        if($('#followUs').length>0){
            var bub = $('#followUs').find('.bubble');
            $('#followUs').mouseenter(function(){
                bub.animate({ top:10 }, { duration: 150, complete:function() { 
                    bub.animate({ top:19 }, { duration: 100 }); }
                });
            }).mouseleave(function() {
                bub.stop().animate({ top:19 }, { duration: 150 });
            });
        }
        app.projects();
        app.reel();
        app.search();
        app.lastfm();
        bg();
        if(!Modernizr.csstransitions) { $.getScript('/javascripts/css3.js'); }
    };
    return app;
}(jQuery));

$(function(){
    APP.init();
});

