(function(jQuery) {
    jQuery.fn.upUpDownDown = function(o){
        var options = jQuery.extend({
                                        watchFor : [38,38,40,40,37,39,37,39,66,65],
                                        callback : function() { }
                                    }, o);
        
        var key_accum = [];
        var match = options.watchFor;
 
        $(document).keyup(function(e){
            len = key_accum.push(e.keyCode ? e.keyCode : e.charCode);
            
            if(len > match.length) key_accum.shift();
            
            if (key_accum.join('-') == match.join('-'))
            {
                key_accum = [];
                if (options.callback)
                {
                    options.callback($(this));
                }
            }
        });
    }
})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var Feedback = {
    timeout: null,
    time_to_live: 5000,
    show: function(text, posneg) {
        // Reset the timeout if there is one
        if(this.timeout) {
            window.clearTimeout(this.timeout);
        }
        
        // Define wich type of feedback has to be showed
        switch(posneg) {
            case 'negative':
            case 0:
            case false:
            case 'false':
                this.negative(text);
            break;
            
            case 'positive':
            case 1:
            case true:
            case 'true':
                this.positive(text);
            break;
            
            case 'loading':
                this.time_to_live = -1;
                this.loading(text);
            break;
        }
        
        this.fade();
    },
    positive: function(text) {
        $('#feedback').hide();
        $('#feedback .content').removeClass('loading').removeClass('negative').addClass('positive');
        $('#feedback .content p').html(text);
    },
    negative: function(text) {
        $('#feedback').hide();
        $('#feedback .content').removeClass('loading').removeClass('positive').addClass('negative');
        $('#feedback .content p').html(text);

    },
    loading: function(text) {
        $('#feedback').hide();
        $('#feedback .content').removeClass('negative').removeClass('positive').addClass('loading');
        $('#feedback .content p').html(text);
    },
    setHide: function() {
        if (this.time_to_live > 0) {
            this.timeout = window.setTimeout('Feedback.hide();', this.time_to_live);
        }
    },
    hide: function() {
        $('#feedback').css('height', $('#feedback').height());
        
        $('#feedback .content').fadeOut('slow', function() {
            $('#feedback').slideUp(function() {
                $('#feedback .content p').html('');
            });
        });
        
    },
    fade: function() {
        $('#feedback').css('height', $('#feedback').height());
        $('#feedback .content').hide();
        
        $('#feedback').slideDown(function() {
            $('#feedback .content').fadeIn('slow');
        });
        
        this.setHide();
    }
};

var Trail = {
    current_filter: null,
    
    init: function(filter) {
        this.filter(filter);
    },
    
    filter: function(filter) {
        this.current_filter = filter;
        
        $('.filter li').each(function(i, n) {
            if($(n).hasClass('filter_nav_' + filter)){
                $(n).addClass('current');
            }
            else {
                $(n).removeClass('current');
            }
        });
        
        this.cleanup();
        
        return false;
    },
    
    cleanup: function() {
        var total = 0;
        var filter = this.current_filter;
        
        $('#no_updates').show();
        
        $('#latest_updates li.filter-li').each(function(i, n) {
            if(filter == 'all' || $(n).hasClass('filter_' + filter)) {
                $(n).show();
                total++;
            }
            else {
                $(n).hide();
            }
        });
        
        if(total > 0) {
            $('#no_updates').hide();
        }
    },
    
    hide: function(message) {
        var conf = confirm("Are you sure you want to remove this message?");
        if(conf) {
            var id = $(message).parent('div').parent("li.filter-li").attr('id');
            id = id.replace('trail_message_', '');
        
            $(message).parent('div').parent("li.filter-li").hide().remove();
        
            // Ajax delete
            $.post('/trail/delete.js', {message_id: id}, function(transport){ 
                if(transport.result == 'ok') {
                    Feedback.show('The message has been removed.', 1);
                }
                else {
                    Feedback.show('The message could not be removed.', 0);
                }
            }, 'json');
        
            this.cleanup();
        }
        
        
        return false;
    }
};

var Avatar = {
    set: function(src) {
        $('#user img.avatar').attr('src', src);
        
        return false;
    }
};
// Hide the feedback
$('#feedback').ready(function() {   
    if($('#feedback .content p span:not(:empty)').length) {
        Feedback.fade();
    }
});

// Initialize the overlay
$('#overlay').ready(function() {
    $('#overlay').bind('click', function(e) {
        if($(e.target).attr('id') == 'overlay') {
            $('#overlay').hide();
            $('#overlay .btn-cancel').trigger('click');
        }
    });

    $('#overlay .btn-cancel').bind('click', function() {
        $('#overlay').hide();
        return false;
    });
});

$(window).bind('resize', function() {
    if($('#overlay :visible')) {
        if($('#push').offset().top <  $('#overlay .overlay .heading').offset().top + $('#overlay .overlay .heading').height()+ $('#overlay .overlay .content').height()) {
            $('#push').height($('#overlay .overlay').offset().top + $('#overlay .overlay').height() - $('#push').offset().top);
        }
    }
});

function showArtoo(destroy) {
    if($.cookie('artoo_visible') == 'true' && destroy == true) {
        $('#artoo').remove();
        $.cookie('artoo_visible', false);
    }
    else if($.cookie('artoo_visible') == 'true' || destroy == true) {
        $('body').append("<img id='artoo' src='http://qkpic.com/d7926' width='50' />");
        $(document).mousemove(function(e){
           $("#artoo").show();
           $("#artoo").css({
               top: (e.pageY +10)  + "px",
               left: (e.pageX+10) + "px",
               position: 'absolute'
           });
        });
        $.cookie('artoo_visible', true);
    }
}

var MyNameisE = {
    Overlay: {
        init: function() {
            $('#overlay').ready(function() {
                $('#overlay').bind('click', function(e) {
                    if($(e.target).attr('id') == 'overlay') {
                        $('#overlay').hide();
                        $('#overlay .btn-cancel').trigger('click');
                    }
                });

                $('#overlay .btn-cancel').bind('click', function() {
                    $('#overlay').hide();
                    return false;
                });
            });

            $(window).bind('resize', function() {
                if($('#overlay :visible')) {
                    if($('#push').offset().top <  $('#overlay .overlay .heading').offset().top + $('#overlay .overlay .heading').height()+ $('#overlay .overlay .content').height()) {
                        $('#push').height($('#overlay .overlay').offset().top + $('#overlay .overlay').height() - $('#push').offset().top);
                    }
                }
            });
        },
        login: function() {
            this.show();

            return false;
        },
        show: function() {
            $("body").animate({ scrollTop: 0 }, "slow"); 
            this.fix_height();

            $('#overlay').show();

            // Fix the footer push
            if($('#push').offset().top <  $('#overlay .overlay .heading').offset().top + $('#overlay .overlay .heading').height()+ $('#overlay .overlay .content').height()) {
                $('#push').height($('#overlay .overlay').offset().top + $('#overlay .overlay').height() - $('#push').offset().top + 50);
                // Added an extra 50 px for estethic reasons
            }

            return false;
        },
        setContent: function(html) {
            $('#overlay .overlay').html(html);
        },
        loadContent: function(url) {
            $('#overlay .overlay').load(url);
        },
        fix_height: function() {
            $('#overlay').height($(document).height()); 
        },
        hide: function() {
            $('#overlay').hide();

            return false;
        }
    }
};

MyNameisE.Overlay.init();
var userAgent = navigator.userAgent.toLowerCase();
var userBrowserName  = navigator.appName.toLowerCase();
// Figure out what browser is being used
$.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
	safari: /webkit/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ),
	name:userBrowserName
};
$(document).ready(function() {
    showArtoo(false);
    $('body').upUpDownDown({
        callback: function() {
            $('#wrapper').fadeOut('fast', function() {
                showArtoo(true);
            }).fadeIn('fast');
        }
    });
    
    $("a[rel*='external'][href!='#']").attr('target', '_blank');
    $("a[rel*='me'][href!='#']").attr('target', '_blank');
});
