var App = function() { 
    this.primary = $('#primary');
    this.secondary = $('#secondary');
    this.elephant = $('#primary .elephant');
    
    if (this.secondary.length == 0)
        this.secondary = null;
        
    this._hash = null;
}

App.prototype.attachEvents = function()
{
    $(window).resize(function() { App.resize() });
    
    this.elephant.click(this.sunToggle);
}

App.prototype.resize = function()
{
    var win = $(window);
    var space = 40;
    var english = 40;
    
    var p = {
        top: win.height() / 2 - this.primary.height() / 2 - english,
        left: win.width() / 2 - this.primary.width() / 2 - english
    };
    
    var s = {
        top: 0,
        left: 0,
    };
    
    if (this.secondary)
    {
        s.top = win.height() / 2 - this.secondary.height() / 2 - english * 1.5;
        s.left = (win.width() / 2) - english;
        if (s.left + this.secondary.width() > win.width())
            s.left = win.width() - this.secondary.width();
        p.left = s.left / 2 - (this.primary.width() / 2);
    }
        
    if (p.top < 10)
        p.top = 10;
    if (p.left < 0)
        p.left = 0;
    if (s.top < 10)
        s.top = 10;
    
    if (this.secondary && p.left + this.primary.width() + space > s.left)
    {
        this.primary.css('position', 'absolute');
        
        p.left = win.width() / 2 - this.primary.width() / 2;
        p.top = 10;
        s.left = space;
        s.top = p.top + this.primary.height();
    }
    else
    {
        this.primary.css('position', 'fixed');
    }
        
    if (this.primary._ready == undefined)
    {
        this.primary.hide();
        this.primary.css({
            left: p.left,
            top: p.top
        });
        this.primary.fadeIn();
        this.primary._ready = true;
    }
    else
    {
        this.primary.animate({
            left: p.left,
            top: p.top
        });
    }
    
    if (this.secondary)
    {    
        if (this.secondary._ready == undefined)
        {
            this.secondary.hide();
            this.secondary.css({
                position: 'absolute',
                left: s.left,
                top: s.top
            });
            this.secondary.fadeIn();
            this.secondary._ready = true;
        }
        else
        {
            this.secondary.css({
                left: s.left,
                top: s.top
            });
        } 
    }
    
    this._ready = true;
}

App.prototype.sunrise = function()
{
    $(document.body).removeClass('night');
    $.cookie('night', null);
}

App.prototype.sunset = function()
{
    $(document.body).addClass('night');
    $.cookie('night', 'yes');
}

App.prototype.sunToggle = function()
{
    if ($(document.body).hasClass('night')) {
        App.sunrise();
    }
    else {
        App.sunset();
    }
}

$(function() {
    App = new App(); 
    App.attachEvents();
    App.resize();
});