var is_authorized;
$(window).load(function(){
    // {{{ data prep
    var pathname = document.location.pathname;
    var screen_name = (pathname.search(/^\/person\//) == -1 ) 
        ? '' 
        : pathname.replace(/\//g, '').replace(/person/, '');
    is_authorized = $(document).data('js_auth');
    $(document).data('js_response', null);
    $(document).data('js_action', null);
    var reply_html = '<li class="response">'
    reply_html += '<div class="heading"><span class="char-counter">140</span>';
    reply_html += is_authorized 
        ? '<span class="response-type">Reply</span>' 
        : '<a class="response-type">Sign in with Twitter to reply</a>';
    reply_html += '</div><div class="text-area">';
    reply_html += '<textarea rows="3" class="post-text"></textarea>';
    reply_html += '</div><ul class="button"><li><input type="text" value="http://example.com" name="tinyurl" /></li><li class="tiny-url"><a class="tiny-url">Add URL</a></li>';
    reply_html += '<li class="twit-pic"><a>Add&nbsp;Pic</a></li>';
    reply_html += '<li class="cancel">Cancel</li><li class="post">Post</li>';
    reply_html += '<input type="hidden" class="status_id" /></ul></li>';
    var reply_box = $(reply_html).hide();
    $('a.response-type', reply_box).live('click', twitter_auth);
    $(document).data('reply_box', reply_box);

    // }}}
    // {{{ new feeds
    $(document).everyTime(60000, 'tweets', function(){
        var service_page = ($(document).data('js_action') == null) 
            ? '/service/tweets/' 
            : '/service/'+$(document).data('js_action')+'/';
        $.getJSON(service_page, { user: screen_name }, function(data){
            get_new_feeds(data, false);
        });
    }, 0, true);

    // }}}
    // {{{ more feeds
    $('#footer .more').click(function(){
        var tweet_count = $('#tweets > li.cleared > div.tweet').length + 1;
        var service_page = ($(document).data('js_action') == null) 
            ? '/service/tweets/' 
            : '/service/'+$(document).data('js_action')+'/';
        ajax_load();
        $.getJSON(service_page, { offset: tweet_count, user: screen_name }, function(data){
            get_new_feeds(data, 'append');
            ajax_unload();
        });
    });

    // }}}
    // {{{ shortcut feeds
    $('#site-head > .nav > .latest').click(function(){
        if ($(document).data('js_action') == null)
        {
            return false;
        }
        ajax_load();
        $.getJSON('/service/tweets/', { offset: 0, count: 15, reverse: true }, function(data){
            get_new_feeds(data, 'replace');
            $(document).data('js_action', null);
            ajax_unload();
        });
    });
    $('#site-head > .nav > .most-recent').click(function(){
        if ($(document).data('js_action') == 'most_recent')
        {
            return false;
        }
        ajax_load();
        $.getJSON('/service/most_recent/', { offset: 0, count: 15, reverse: true }, function(data){
            get_new_feeds(data, 'replace');
            $(document).data('js_action', 'most_recent');
            ajax_unload();
        });
    });
    $('#site-head > .nav > .most-followers').click(function(){
        if ($(document).data('js_action') == 'most_followers')
        {
            return false;
        }
        ajax_load();
        $.getJSON('/service/most_followers/', { offset: 0, count: 15, reverse: true }, function(data){
            get_new_feeds(data, 'replace');
            $(document).data('js_action', 'most_followers');
            ajax_unload();
        });
    });
    
    // }}}
    // {{{ create response box and actions
    $('a.retweet, a.reply').live('click', function(e){
        e.preventDefault();
        var el = $(this);
        var this_tweet = el.closest('li.cleared');
        var r_box = this_tweet.next('li');
        if (!r_box.hasClass('response'))
        {
            r_box = $(document).data('reply_box').clone();
            this_tweet.after(r_box);
        }
        var status_id = el.attr('id');
        if (!is_authorized)
        {
            $(document).data('js_response', status_id);
            $('input, textarea', r_box).attr('disabled', 1);
        }
        $('input.status_id').val(status_id.match(/\d+$/));
        $('li.response').each(function(){
            var r_li = $(this);
            if (r_box.html() != r_li.html())
            {
                r_li.slideUp();
                $('a.retweet, a.reply', r_li.prev()).removeClass('active');
            }
        });
        if (el.hasClass('active'))
        {
            return false;
        }
        else
        {
            el.parent().siblings().children().removeClass('active');
        }
        el.addClass('active');
        // {{{ manipulate text
        var post_text = $('> .text-area > .post-text', r_box), counter = $('> .heading > .char-counter', r_box);
        post_text.data('counter', counter);
        var r_mention = '@'+$('> .tweet > h1 > a:first-child', this_tweet).attr('href').match(/\w+$/);
        if (el.hasClass('reply'))
        {
            if (is_authorized)
            {
                post_text.val(r_mention);
                $('> .heading > .response-type', r_box).text('Reply');
            }
            else
            {
                post_text.val('Click the link above to sign in, then type your reply here');
                $('> .heading > .response-type', r_box).text('Sign in with Twitter to reply');
            }
        }
        else
        {
            if (is_authorized)
            {
                post_text.val('RT "'+el.closest('ul.meta').prev('p').text()+'" via '+r_mention);
                $('> .heading > .response-type', r_box).text('Retweet');
            }
            else
            {
                post_text.val('Click the link above to sign in, then type your reply here');
                $('> .heading > .response-type', r_box).text('Sign in with Twitter to retweet');
            }
        }
        $('> .button input[name="tinyurl"]', r_box).focus(function(){
            $(this).val('');
        });

        // }}}
        // {{{ slidedown and attach upload
        r_box.slideDown('normal',function(){
            if (is_authorized)
            {
                $('> .button > .twit-pic > a', r_box).upload({
                    name: 'twitpic',
                    action: '/service/twitpic/',
                    enctype: 'multipart/form-data',
                    params: {},
                    autoSubmit: true,
                    onSubmit: function() {
                        ajax_load();
                    },
                    onComplete: function(response) {
                        if (response != 'fail')
                        {
                            post_text.val(post_text.val()+' '+response);
                        }
                        $("input[name='twitpic']").val("");
                        ajax_unload();
                    },
                    onSelect: function() {}
                });
                if ($.browser.safari())
                {
                    $('> .button > .twit-pic form input', r_box).css('margin-left', '-25px');
                }
                else if ($.browser.msie())
                {
                    $('> .button > .twit-pic form input', r_box).css('margin-left', '-75px');
                }
            }
        });
        
        // }}}
        post_text.keyup();
    });

    // }}}
    // {{{ cancel
    $('.response > .button > li.cancel').live('click', function(){
        var r_box = $(this).closest('li.response');
        r_box.slideUp();
        $('a.retweet, a.reply', r_box.prev()).removeClass('active');
        $(document).data('js_response', null);
    });

    // }}}
    // {{{ post
    $('.response > .button > li.post').live('click', function(){
        if (!is_authorized)
        {
            return false;
        }
        var el = $(this);
        var r_box = el.closest('li.response');
        var tweet = el.parent().prev('.text-area').children('.post-text').val();
        var status_id = el.siblings('input.status_id:hidden').val();
        ajax_load();
        $.getJSON('/service/send_tweet/', { status: tweet, in_reply_to_status_id: status_id }, function(data){
            $('> .tweet > .meta .active', r_box.prev('li')).removeClass('active');
            r_box.slideUp();
            if (data.success)
            {
                r_box.after('<li class="success">Your message has been posted.</li>');
            }
            else
            {
                r_box.after('<li class="error">There was an error processing your request.</li>');
            }
            ajax_unload();
        });
    });

    // }}}
    // {{{ character counter
    $('.response > .text-area > .post-text').live('keyup', function(){
        var el = $(this), r_text = el.val();
        if (r_text.length > 140)
        {
            el.data('counter').css('color','red');
        }
        else
        {
            if (el.data('counter').css('color') == 'red')
            {
                el.data('counter').css('color','white');
            }
        }
        el.data('counter').text(140-r_text.length);
    });

    // }}}
    // {{{ tinyurl
    $('.response > .button > .tiny-url').live('click', function(e){
        e.preventDefault();
        if (!is_authorized)
        {
            return false;
        }
        ajax_load();
        var el = $(this);
        var post_text = el.parent().prev('.text-area').children('.post-text');
        var address = el.prev('li').children('input');
        $.post('/service/tinyurl/', { url: address.val() }, function(data){
            post_text.val(post_text.val()+' '+data);
            address.val('');
            ajax_unload();
        });
    });

    // }}}
    // {{{ move google ads
    if ($.browser.msie() && $.browser.version.number() >= 8)
    {
        $('#hidden-ad-zone-200 > iframe').appendTo($('#ad-zone-200')).removeClass('hidden');
        $('#hidden-ad-zone-200-images > iframe').appendTo($('#ad-zone-200-images')).removeClass('hidden');
    }
    else
    {
        $('#hidden-ad-zone-200 > ins').appendTo($('#ad-zone-200')).removeClass('hidden');
        $('#hidden-ad-zone-200-images > ins').appendTo($('#ad-zone-200-images')).removeClass('hidden');
    }

    // }}}
    // {{{ copy url field
    $('#featured-tweet input.copy-url').keydown(function(e){
        if (e.metaKey != 1 && e.ctrlKey != 1 && e.altKey != 1)
        {
            e.preventDefault();
        }
    });
    $('#featured-tweet input.copy-url').click(function(){
        $(this).select();
    });

    // }}}
    // {{{ go to reply box after login
    if (is_authorized != null && $(document).data('js_response') != null)
    {
        $.scrollTo('#'+$(document).data('js_response'), 700, { onAfter: function(){
            $('#'+$(document).data('js_response')).trigger('click');
        }});
    }

    // }}}
    // {{{ follow
    $('a.follow').live('click', function(e){
        e.preventDefault();
        if (!is_authorized)
        {
            return false;
        }
        var el = $(this);
        var user_id = el.attr('href');
        ajax_load();
        $.getJSON('/service/follow_user/', { id: user_id, text: el.text() }, function(data){
            if (data.success)
            {
                $('a.follow[href="'+user_id+'"]').each(function(){
                    if (data.text != '')
                    {
                        $(this).text(data.text);
                    }
                });
                var this_tweet = el.closest('li.cleared');
                if (this_tweet.next('li').hasClass('response'))
                {
                    this_tweet = this_tweet.next('li');
                }
                var success_html = (el.text().toLowerCase() == 'follow') 
                    ? '<li class="success">You are no longer following' 
                    : '<li class="success">You are now following'; 
                this_tweet.after(success_html+' '+el.prev('a').text()+'</li>');
            }
            ajax_unload();
        });
    });

    // }}}
    // {{{ misc
    $('span.source > a').live('new_tweets', function(){
        $(this).attr('target', '_blank');
    });
    $('span.timeago').live('new_tweets', function(){
        $(this).timeago();
    });
    if (pathname.search(/\/about\//) != -1 
        || pathname.search(/\/statuses\//) != -1
        || pathname.search(/\/terms\//) != -1)
    {
        $(document).stopTime('tweets');
    }

    // }}}
    trigger_new_tweets();
});
// {{{ function ajax_load()
function ajax_load()
{
    if ($.browser.msie())
    {
        //IE 6+ in 'standards compliant mode'
        winWidth = document.documentElement.clientWidth;
        winHeight = document.documentElement.clientHeight;
    }
    else
    {
        winWidth = window.innerWidth;
        winHeight = window.innerHeight;
    }
    $('#ajax-loader').width(winWidth).height(winHeight).fadeIn(500);
}

// }}}
// {{{ function ajax_unload()
function ajax_unload()
{
    $('#ajax-loader').fadeOut();
}

// }}}
// {{{ function trigger_new_tweets()
function trigger_new_tweets()
{
    $('span.source > a').trigger('new_tweets');
    $('span.timeago').trigger('new_tweets');
}

// }}}
// {{{ function create_tweet_html(tweet, new_tweet)
function create_tweet_html(tweet, new_tweet)
{
    var li_class = 'cleared hidden', user = tweet.User;
    if (new_tweet == true)
    {
        li_class += ' new-tweet';
    }
    var html = '<li class="'+li_class+'">';
    html += '<div class="avatar"><img src="'+user.profile_image_url+'" /><div class="corners" title="'+user.display_name+' - '+user.description+'"></div></div>';
    html += '<div class="tweet"><h1>';
    html += '<a href="/person/'+user.screen_name+'" title="'+user.display_name+' - '+user.description+'">'+user.display_name+'</a>';
    html += user.following 
        ? '<a class="follow" href="#'+tweet.user_id+'">Unfollow</a>' 
        : '<a class="follow" href="#'+tweet.user_id+'">Follow</a>';
    html += '</h1><p>'+tweet.text+'</p><ul class="meta">';
    html += '<li class="time"><span class="timeago" title="'+tweet.time+'">'+tweet.time_units+'</span> <span class="source">via '+tweet.source+'</span></li>';
    html += '<li><a href="/statuses/'+tweet.id+'/">Link</a></li>';
    html += '<li><a id="reply-'+tweet.id+'" class="reply">Reply</a></li>';
    html += '<li><a id="retweet-'+tweet.id+'" class="retweet">Share</a></li>';
    html += '</ul></div></li>';
    return html;
}

// }}}
// {{{ function get_new_feeds(data, action)
function get_new_feeds(data, action)
{
    if (data.new_tweets == 0)
    {
        return false;
    }
    var items = data.data, tweet_obj = $('#tweets'); 
    if (action == 'append')
    {
        for (var i=0; i<data.new_tweets; i++)
        {
            tweet_obj.append(create_tweet_html(items[i], false));
        }
    }
    else
    {
        var old_feature = $('#featured-tweet ul');
        if (action == 'replace')
        {
            tweet_obj.empty();
            var new_tweet = false;
        }
        else
        {
            tweet_obj.prepend(old_feature.html());
            var new_tweet = true;
            $('.new-tweet', tweet_obj).removeClass('new-tweet');
        }
        old_feature.empty();
        for (var i=0; i<data.new_tweets; i++)
        {
            if (i == (data.new_tweets-1))
            {
                old_feature.prepend(create_tweet_html(items[i], new_tweet));
            }
            else
            {
                tweet_obj.prepend(create_tweet_html(items[i], new_tweet));
            }
        }
        $('> .hidden', old_feature).fadeIn(1000).removeClass('hidden');
    }
    // {{{ stats
    var most_talkative = data.most_talkative, html_li = '';
    for (var j in most_talkative)
    {
        html_li += '<li class="cleared"><div class="avatar"><img src="'+most_talkative[j].profile_image_url+'" /><div class="corners" title="'+most_talkative[j].display_name+' - '+most_talkative[j].description+'"></div></div>';
        html_li += '<div class="tweet"><a href="/person/'+most_talkative[j].screen_name+'/" title="'+most_talkative[j].display_name+' - '+most_talkative[j].description+'">'+most_talkative[j].display_name+'</a><p>'+most_talkative[j].count_week+' Tweets</p></div></li>';
    }
    $('#most-talkative ul').html(html_li);
    
    // }}}
    $('#todays-tweets').html('<h2>'+data.total+' recent dead tweets</h2>');
    $('> li.hidden', tweet_obj).fadeIn(1000).removeClass('hidden');
    trigger_new_tweets();
}

// }}}
// {{{ function twitter_auth()
function twitter_auth()
{
	window.open("/twitter/redirect/","twitter_child",'width=800,height=400,left=150,top=100,scrollbar=no,resize=no');
    return false;
}

// }}}
