$(document).ready(function(){

    // NO IE6!
    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        $('body').noIE6();
    }

    // replace scroll bar on body for smaller viewport
    var replaceScroll = function() {
        if ($(window).width() < 960) {
            $('body').css({'overflow':'visible'});
            $('#out-of-bounds').hide();
        } else {
            $('body').css({'overflow':'hidden'});
            $('#out-of-bounds').show();
        }
    }
    replaceScroll();
    $(window).resize(replaceScroll);

    // Header search
    $('header input')
        .focus(function(){ $(this).val(''); })
        .blur(function(){ if (this.value == '') $(this).attr('value', 'Search'); });



    /*
     *  Twitter feed
     */
    if ($("#twitter").length) {

       $.ajax({
                url             : 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=worldwideholen1',
                dataType	: 'jsonp',
                success		: function(json){

                    $('#twitter .tweet.js-only').remove();
                    $('#twitter .tweet.no-js').remove();

                    for (var i=0; i<json.length; i++) {
                      
                        var posted = timeAgo(json[i].created_at);

                        var regexp = new RegExp('#','g');
                        var str = json[i].text.replace(regexp, '<span class="hash">#</span>');

                        var tweet = $("<div class='tweet'></div>");
                        tweet.append($(
                                        "<p>"+str.withClickableURLs()+"</p><a title='Permalink' class='permalink' href='http://twitter.com/WWSRisks/status/"+json[i].id_str+"'>"+posted+"</a>"
                                    ));
                        $("#twitter .optionsWindow").append(tweet);
                        if (i==0) tweet.fadeIn().addClass('active');
                    }
                }
        });

        function Tweeter(fn, delay) {
            var timerId;
            this.play = function() {
                timerId = window.setInterval(fn, delay);
            }
            this.pause = function() {
                window.clearTimeout(timerId);
            }
            this.play();
        }

        // Start tweets scrolling
        var tweetTimer = new Tweeter(function(){
            var curr = $("#twitter div.active");
            var nxt = (curr.next().length) ? curr.next() : $("#twitter div.tweet").first();

            curr.hide().removeClass('active').css({'opacity':'1'});
            nxt.addClass('active').show();
        }, 8000);

        // Listen for mouse overs to pause tweets
        $('footer').hover(tweetTimer.pause, tweetTimer.play);
        $('#twitter').hover(tweetTimer.pause, tweetTimer.play);
    }


    /*
     *  "Have you thought about..." random chooser
     */
    if (
        $('body#default #blockThoughtAbout').length ||
        $('body#formpage #blockThoughtAbout').length ||
        $('body#contact #blockThoughtAbout').length
       ) {

        var lis = $('#blockThoughtAbout li');
        var rand = Math.floor(Math.random()*lis.length);

        lis.each(function(i, el){
            if (i==rand) $(el).fadeIn();
        });
    }


    /*
     *      News pages
     */
    if ($('body#news').length) {
        $('#news-prev-next a').each(function(i, el){
           if (!$(el).attr('href')) {
               $(el)
                    .attr('href', '#')
                    .css({
                        'backgroundColor'   : '#C3E6AA',
                        'cursor'            : 'default'
                    })
                    .click(function(e){
                        e.preventDefault();
                        return;
                    });
           }
        });
    }


    /*
     *      Contact page
     */
    if ($('#form-wrap').length) {

        var fElems = $('#form-wrap input').add('#form-wrap textarea');

        fElems
            .focus(function(){$(this).prev().hide();})
            .blur(function(){if ($(this).val() == '') $(this).prev().show();});


        // Hide labels if each input has data (on page load)
        fElems.each(function(i,el){
            if ($(this).val() != '') $(this).prev().hide(); else $(this).prev().show();
        });
    }

});


function loadScript(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    $("head").append(script);
}

String.prototype.withClickableURLs = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
		return url.link(url);
	});
};

function parseDate(str) {
  var v=str.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
}


function timeAgo(time){

    time = parseDate(time);

    var date = new Date(time),
        secsago = (((new Date()).getTime() - date.getTime()) / 1000),
        minsago = Math.floor(secsago / 60),
        hoursago = Math.floor(minsago / 60),
        daysago = Math.floor(secsago / 86400),
        weeksago = Math.floor(daysago / 7),
        yearsago = Math.floor(weeksago / 52);

    if (secsago < 60)   return "Posted a moment ago";
    if (minsago < 60)   return "Posted "+minsago+" minutes ago";
    if (hoursago < 24)  return "Posted "+hoursago+" hours ago";
    if (daysago == 1)   return "Posted yesterday";
    if (daysago < 7)    return "Posted "+daysago+" days ago";
    if (weeksago == 1)  return "Posted a week ago";
    if (weeksago < 52)  return "Posted "+weeksago+" weeks ago";
    return (isNaN(yearsago)) ? "" : "Posted "+yearsago+" years ago";
}



