if(!window['chattup']) {
	window['chattup'] = {};
	var chattup = window['chattup'];
}

var iPhone = ($.browser.safari && navigator.userAgent.match(/Mobile/));

$(document).ready(function() {
	chattup.friends();
	chattup.tabs();
  chattup.iPhoneTabs();
  chattup.live();
  if(window.location.hash && !iPhone) {
    $('a[href=' + window.location.hash + ']').click();
    window.location.hash = '';
  } else if(!iPhone) {
    $('.tabs a[href=#tweets]').addClass('selected');
  }
  $('a[href^=http]').each(function() {
    $(this).attr({'target':'_blank'});
  });
});

$(window).load(function() {
	if(iPhone) {
	  $(document).scroll(function(){
	    chattup.iPhoneTabs();
	  });
    if(!window.location.hash) {
  		setTimeout(function() {
  			window.scrollTo(0,0);
  		},10);
    }
	}
});

chattup.iPhoneTabs = function() {
  if(!iPhone) { return; }
  if(typeof chattup.iPhoneTabs.bar == 'undefined') {
    chattup.iPhoneTabs.bar = $('ul.tabs').eq(0).clone(true);
    $('ul.tabs').eq(0).after(chattup.iPhoneTabs.bar);
  }
  chattup.iPhoneTabs.bar.animate({'top': (window.pageYOffset > chattup.iPhoneTabs.bar.height() ? window.pageYOffset : 0) + 'px'},1000);
}

chattup.tabs = function() {
	var tabs = $('ul.tabs li a[href^=#]');
	tabs.each(function() {
		var tab = $(this);
		tab.click(function(c) {
		  if(iPhone) {
		    setTimeout(function(){
		      chattup.iPhoneTabs();
		    },500);
		    return;
		  }
  		tabs.filter('.selected').removeClass('selected');
  		tab.addClass('selected');
			c.preventDefault();
			if($('div.section:animated').size()) { return; }
			var section = $('div.section[id=' + tab.attr('href').replace(/\#/,'') + ']');
			var otherSections = $('div.section[id!=' + tab.attr('href').replace(/\#/,'') + ']:visible');
			section.fadeIn('normal');
			otherSections.fadeOut('normal');
			if(section.is('#friends')) {
				if(!$('#friends .pagination a.current').size()) {
					$('#friends .pagination .link-1 a').addClass('current');
				}
			}
		});
	});
	
	if(window.location.hash != '') {
		tabs.filter('[href=' + window.location.hash + ']').click();
	} else {
		tabs.eq(0).click();
	}
}

chattup.friends = function() {
	if(iPhone) { return; }

	var friends = $('#friends .friend');
	var max = 35;
	var pages = new Array();
	for(var i = 0; i < Math.ceil(friends.size() / max); i++) {
		pages[i] = (i+1);
	}
	
	var nav = $(jQuery('<ul class="pagination"></ul>'));
	var prev = $(jQuery('<a href="#prev" title="Previous">&laquo;</a>'));
	var next = $(jQuery('<a href="#next" title="Next">&raquo;</a>'));
	prev.appendTo(nav).wrap('<li class="first" />');

	$.each(pages, function() {
		var num = this;
		var link = $(jQuery('<a href="#group-' + num +'" title="' + num + '">' + num + '</a>'));
		var div = $(jQuery('<div id="group-' + num + '" class="friend-group" />'));
		div.appendTo($('#friends'));
		if(this > 1) {
			div.css({'display':'none'});
		}
		link.click(function(c) {
			c.preventDefault();
			if($('div.friend-group:animated').size() || link.is('.current')) { return; }
			nav.find('a.current').removeClass('current');
			link.addClass('current');
			$('div.friend-group:visible').slideUp('normal');
			div.slideDown('normal');
		});
		link.appendTo(nav).wrap('<li class="page link-' + num + '" />');
	});
	
	next.appendTo(nav).wrap('<li class="last" />');
	
	var page = 1;
	friends.each(function(index) {
		if(index % 35 == 0 && index > 0) {
			page = page + 1;
		}
		var div = $('div#group-' + page + '.friend-group');
		$(this).remove().appendTo(div);
	});
	
	prev.click(function(c) {
		c.preventDefault();
		if($('div.friend-group:animated').size()) { return; }
		
		currentGroup = $('.friend-group:visible');
		if(currentGroup.prev('.friend-group').size()) {
			nav.find('a[href=#' + currentGroup.attr('id') + ']').parent('li.page').prev('li.page').find('a').click();
		}
	});

	next.click(function(c) {
		c.preventDefault();
		if($('div.friend-group:animated').size()) { return; }
		
		currentGroup = $('.friend-group:visible');
		if(currentGroup.next('.friend-group').size()) {
			nav.find('a[href=#' + currentGroup.attr('id') + ']').parent('li.page').next('li.page').find('a').click();
		}
	});
	
	nav.prependTo('#friends');
}

chattup.live = function() {
  $.ajaxSetup({'cache': false});

  var months = new Array();
  months[0] = 'January';
  months[1] = 'February';
  months[2] = 'March';
  months[3] = 'April';
  months[4] = 'May';
  months[5] = 'June';
  months[6] = 'July';
  months[7] = 'August';
  months[8] = 'September';
  months[9] = 'October';
  months[10] = 'November';
  months[11] = 'December';

  setInterval(function(){
    $.getJSON('/search_wrapper',
      {
        "since_id": $('#tweets').attr('data-since-id')
      },
     function(json){
       if(typeof json.results != 'undefined') {
         $.each(json.results, function(index, tweet) {
           if($('.tweet[id=tweet-' + tweet.id + ']').size()) { return; }
           var date = new Date(Date.parse(tweet.created_at));
           date = months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' at ' + (date.getHours() > 11 ? date.getHours() - 12 : date.getHours() !== 0 ? date.getHours() : '12') + ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + (date.getHours() > 11 ? 'pm' : 'am');
           var div = $(jQuery('<div class="tweet" id="tweet-' + tweet.id + '"><a class="avatar" href="http://twitter.com/' + tweet.from_user + '" target="_blank"><img src="' + tweet.profile_image_url + '" /></a><p>' + tweet.text + '</p><p class="meta">' + date + '</p></div>'));
           $('#tweets .tweet').eq(0).before(div);
         });
       }
       $('#tweets').attr({'data-since-id': json.max_id});
    });
    
  },60 * 1000); // run this every minute
}
