/* $Id: script.js 102 2012-01-22 17:15:11Z dorian $ */

/*global $ */

var show_relative_time = false;

function relative_time(date) {
    "use strict";
    if (!show_relative_time) {
        return '';
    }
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - date) / 1000, 10);
    var r = '';
    if (delta < 60) {
        r = delta + ' Sekunden';
    } else if(delta < 120) {
        r = ' einer Minute';
    } else if(delta < (45*60)) {
        r = (parseInt(delta / 60, 10)).toString() + ' Minuten';
    } else if(delta < (2*60*60)) {
        r = ' einer Stunde';
    } else if(delta < (24*60*60)) {
        r = (parseInt(delta / 3600, 10)).toString() + ' Stunden';
    } else if(delta < (48*60*60)) {
        r = ' einem Tag';
    } else {
        r = (parseInt(delta / 86400, 10)).toString() + ' Tagen';
    }
    return 'vor ungefähr ' + r;
}


/*** Setup navigation menu on sub pages ***/

// Poor man's synchronization
var accordion_mutex = false;

function setup_accordion() {
    "use strict";
    
    $('ul.side-nav-sublevel').hide();
    $('ul#side-nav li h2').css('cursor', 'pointer');
    $('li.nav-open ul').show();
    $('ul#side-nav li.nav-sub h2').click(function (e) {
        e.preventDefault();
        if (accordion_mutex) {
            return;
        }
        accordion_mutex = true;
        if ($('ul.side-nav-sublevel', $(this).parent()).is(':visible')) {
            $(this).parent().toggleClass('nav-closed nav-open');
            $('ul.side-nav-sublevel', $(this).parent()).slideUp(250, function () {
                accordion_mutex = false;
            });
            return;
        } else {
            $(this).parent().toggleClass('nav-closed nav-open');
            $('ul.side-nav-sublevel', $(this).parent()).slideDown(250, function () {
                accordion_mutex = false;
            });
            return;
        }
    });
}


/*** Display loading indicators for Twitter and Blog feed ***/

function display_loader_img() {
    "use strict";
    $('.loading').show();
}

/*** Install mouse-over handlers for the Webrepublic island map ***/

function setup_map_handlers() {
    "use strict";
    function captions(id) {
        return $('#' + id + ' span.map-location').html();
    }
    
    // Poor man's synchronization
    var map_mutex = false;

    var cur_text = captions('map-default');

    var $map_cont = $('div#map-container');
    var $map_title = $('div#map-title');
    var $map_caption = $('span#map-caption-text');

    function animateCaption(new_text) {
        if (cur_text === new_text) return;
        if (map_mutex) return;
        map_mutex = true;
        var orig_css = {width: $map_cont.get(0).style.width, height: $map_cont.get(0).style.height};
        var prev_size = {width: $map_cont.width()+'px', height: $map_cont.height()+'px'};
        $map_cont.animate( {opacity: 0}, 200, function () {
            if (new_text == captions('map-default')) {
                $map_title.show();
            } else {
                $map_title.hide();
            }
            $map_caption.html(new_text);
            cur_text = new_text;
            var new_style = {width: $map_cont.width()+'px', height: $map_cont.height()+'px', opacity: 1};
            $map_cont.css(prev_size);
            $map_cont.animate(new_style, 200, function () {
                $map_cont.css(orig_css);
                map_mutex = false;
            });
        });
    }
 
    
    var handler_in = function () {
        $map_cont.stopTime();
        var id = $(this).parent().attr('id');
        animateCaption(captions(id));
    };
    
    var handler_out = function () {
        $map_cont.oneTime(1500, function () {
            animateCaption(captions('map-default'));
        });
    };
    
    $('div#map-icons span.map-icon').hover(handler_in, handler_out);
}

/*** Put latest blog post on the front page ***/

var posterous_handle = 'webrepublic';

function get_last_post_id() {
    "use strict";
    var hostname = $(location).attr('hostname'); /* LOL at using jQuery to get the hostname */
    var url = '//' + hostname + '/last_blog_post_id';
    var last_post_id = '73750436';
    $.ajax({
        url:        url,
        dataType:   'text',
        success:    function (data, status, jqXHR) {
            if (data) {
                last_post_id = data;
            }
        },       
        async:      false
    });
    return last_post_id;
}

function load_blog_post() {
    "use strict";
    var posterous_url = '//posterous.com/api/2/sites/' + posterous_handle + '/posts/public?since_id=' + get_last_post_id() + '&callback=?';
    $('#blog-title').hide();
    $('#blog-time').hide();
    $('#blog-link').hide();
    $('#blog-link').css('visibility', 'visible');
    
    // jquery.excerpt does not work when the containing block is hidden, that is why #blog-text is
    // already invisible. #blog-link was also invisible so that we don't show the red "link arrow"
    // before the deep link is available
    
    $.getJSON(posterous_url, function (data) {
        var first_post = data[0];
        var full_url = first_post['full_url'];
        var title = first_post['title'];
        var time = relative_time(Date.parse(first_post['display_date']));
        var raw_html = first_post['body_full'];
        // We need to remove img tags as jQuery will download them when building a DOM from the string
        raw_html = raw_html.replace(/<img[^>]*\/>/gi,'');
        var pure_text = $(raw_html).text();
        
        $('#blog-title').html(title);
        $('#blog-time').html(time);
        $('#blog-link').attr('href', full_url);
        $('#blog-link').html("Mehr&hellip;");
        $('#blog-text').html(pure_text);
        
        // Build the excerpt while the block is invisible
        $('#blog-text').excerpt( {lines: 5} );
        // Then hide it so we can use .show()
        $('#blog-text').hide();
        // And set visibility back to visible 
        $('#blog-text').css('visibility', 'visible');
        
        $("#blog-loading").animate({ opacity : 0 }, 500, function () {
            $('#blog-loading').hide();
            $('#blog-title').show(300);
            $('#blog-time').show(300);
            $('#blog-text').show(300);
            $('#blog-link').show(300);
        });
    });
}


/*** Put latest Tweet on the front page ***/

// Copied & adapted from the jquery.tweet lib
function parse_tweet_date(date_str) {
    "use strict";
    // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
    // cannot handle in IE. We therefore perform the following transformation:
    // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
    return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
}

function update_tweet (tweet) {
    "use strict";
    var tweet_text = '';
    var tweet_time = '';
    if (tweet === null) {
         tweet_text = "Keine Tweets gefunden.";
         tweet_time = relative_time();
    } else {
        var raw_text = tweet['text'];
        var raw_time = tweet['created_at'];
        tweet_text = $([raw_text]).linkUrl().linkUser().linkHash()[0];
        tweet_time = relative_time(parse_tweet_date(raw_time));
    }
    $("#tweet-text").html(tweet_text);
    $("#tweet-time").html(tweet_time);
    
    $("#tweet-loading").animate({ opacity : 0 }, 500, function () {
        $("#tweet-loading").hide(); 
        $("#tweet-time").show(300);
        $("#tweet-text").show(300);
    });
}

function load_json(tweet_url, tweet_count) {
    "use strict";
    if (tweet_count > 20) { // apparently there are only retweets, give up
        update_tweet(null);
    } else {
        $.getJSON(tweet_url.replace('%TWEET_COUNT%', tweet_count), function (data) {
            if (data.length > 0) {
                update_tweet(data[0]);
            } else {
                load_json(tweet_url, tweet_count + 1);
            }
        });
    }
}

var twit_handle = 'webrepublic_ch';

function load_tweet(count) {
    "use strict";
    $("#tweet-text").hide();
    $("#tweet-time").hide();
    var tweet_url = "//twitter.com/status/user_timeline/" + twit_handle + ".json?count=%TWEET_COUNT%&callback=?";
    load_json(tweet_url, 1);
}

