$(function() {
    // console.log('homepage-std.js');
    // patch up for non-javascript compatibility measures
    // $('.crouching-tiger').css({ display: 'block' });

    // tweet scroller
    $('#twitter-latest').ifExists(function() {
        var $self = this;
        $.getJSON('/feed/twitter/uniofadelaide.json', function (data, status) {
            var i, len, message, value, unit, offset;
	    var today = new Date();
	    var timestamp = new Date();
            var $container = $('<div class="twitter-items" />');
            $self.empty().append($container);

            for (i=0, len=data.posts.length; i<len; i++) {
	        timestamp.setTime(parseInt((data.posts[i].timestamp))*1000);
                offset = today.getTime() - timestamp.getTime();
                message = null;
	            if (offset > 604800000) {
                    message = 'more than a week ago';
                } else if (offset > 86400000) {
                    value = Math.round(offset / 86400000);
                    unit = 'day';
                } else if (offset > 3600000)  {
                    value = Math.round(offset / 3600000);
                    unit = 'hour';
	            } else if (offset > 60000) {
                    value = Math.round(offset / 60000);
                    unit = 'minute';
                } else {
                    message = 'less than a minute ago';
                }

                message = message || value + ' ' + unit + (value == 1 ? '' : 's') + ' ago';

                var $item = $('<div />');
                $item.append('<p style="margin-bottom: 0"><a href="https://twitter.com/#!/UniofAdelaide" title="The University&apos;s Twitter account"><span class="twitter-title">@' + data.username + '</span></a>, <a href="https://twitter.com/#!/search?q=%23Adelaide"<span class="twitter-address">Adelaide, SA</span></a> ... <span class="twitter-timestamp">' + message + '</span></p>');
                $item.append('<p class="twitter-content">' + data.posts[i].content + '</p>');
                $item.css({
                    height: '84px'
                });

                $container.append($item);
            }

            $container.css({
                float: 'left',
                width: ($self.width()-20)+'px',
                height: '84px',
                margin: 0,
                padding: 0
            });

            var $controls = $('<table class="twitter-controls"><tr><td><a href="#" class="twitter-controls-prev" title="Scroll Twitter feed up">&nbsp;</a></td></tr><tr><td><a href="#" class="twitter-controls-next" title="Scroll Twitter feed down">&nbsp;</td></tr></table>');
            
            $controls.css({
                float: 'left',
                width: '20px',
                height: '84px',
                margin: 0,
                padding: 0
            });

            function build_control_handler(direction) {
                return function() {
                    $container.cycle(direction);
                    // stop cycling - manual mode now
                    $container.cycle('pause');
                    // prevent resumption of auto cycling
                    var opts = $container.data('cycle.opts');
                    opts['timeout'] = 0;
                    $container.data('cycle.opts', opts);
                    return false;
                };
            }

            var $prev = $controls.find('.twitter-controls-prev').click(build_control_handler('prev'));
            var $next = $controls.find('.twitter-controls-next').click(build_control_handler('next'));

            $self.append($controls);

            $container.cycle({
                pause: true,
                nowrap: 1,
                rev: 1,
                fx: 'scrollVert',
                timeout: 6500,
                delay:  2000,
                before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
                    var elt = forwardFlag ? nextSlideElement.nextSibling : nextSlideElement.previousSibling;
                    $prev.css({visibility: elt || forwardFlag ? 'visible' : 'hidden'});
                    $next.css({visibility: elt || ! forwardFlag ? 'visible' : 'hidden' });
                },
                end: function(options) {
                    options['timeout'] = 0;
                }
            });
            // this doesn't work when included in the source of $controls
            $prev.css({visibility:'hidden'});
        });
    });

    $.wait(300).then(function() {
        // tweet button
        // TODO: replace with local equivalent
        $('#tweet')
            .append('<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?text=' + escape('Uni of Adelaide') + '&amp;via=UniofAdelaide&count=vertical" style="width:60px; height:70px;"></iframe>');

        // facebook like
        if ($('div.fb-like').length) {
            $('body')
                .append('<div id="fb-root"></div>')
                .append('<script>\
  window.fbAsyncInit = function() {\
    FB.init({\
      appId      : "275885659109551",\
      channelUrl : "//www.adelaide.edu.au/global/v/redesign1/includes/infra/xfbml-channel.html",\
      status     : true,\
      cookie     : true,\
      xfbml      : true\
    });\
  };\
\
  (function(d){\
     var js, id = "facebook-jssdk"; if (d.getElementById(id)) {return;}\
     js = d.createElement("script"); js.id = id; js.async = true;\
     js.src = "//connect.facebook.net/en_US/all.js";\
     d.getElementsByTagName("head")[0].appendChild(js);\
   }(document));\
</script>');
        }
    });
});

