// Remy Sharp's Infinite Carousel
// http://www.jqueryfordesigners.com

$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 350, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 

                currentPage = page;
            });                
            
            return false;
        }
        
        $(this).bind('next', function(){
        	gotoPage(currentPage + 1);
        });
    });  
};

// twitter feed
function urlToLink(text) {
	var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	return text.replace(exp,"<a href='$1'>$1</a>");
}

function relTime(time_value) {
	time_value = time_value.replace(/(\+[0-9]{4}\s)/ig,"");
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
	if (timeago < 60) return 'less than a minute ago';
	else if(timeago < 120) return 'about a minute ago';
	else if(timeago < (45*60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
	else if(timeago < (90*60)) return 'about an hour ago';
	else if(timeago < (24*60*60)) return 'about ' + (parseInt(timeago / 3600)).toString() + ' hours ago';
	else if(timeago < (48*60*60)) return '1 day ago';
	else return (parseInt(timeago / 86400)).toString() + ' days ago';
}

// Background image scroller
var scrollSpeed = 100;
var step = 1;
var current = 0;
var imageWidth = 324; 
var headerWidth = 1021;     
var restartPosition = -(imageWidth - headerWidth);

function scrollBg(){
current -= step;
if (current == restartPosition){
current = 0;
}
$('.infiniteCarousel').css("background-position", -current+"px 0");
}
var init = setInterval("scrollBg()", scrollSpeed);



//ON PAGE LOAD
$(document).ready(function () {
  var autoscrolling = true;
  
  $('.infiniteCarousel').infiniteCarousel().mouseover(function(){
  	autoscrolling = false;
  	}).mouseout(function(){
  	autoscrolling = true;
  	});
  
  setInterval(function(){
  if(autoscrolling){
  	$('.infiniteCarousel').trigger('next');	
  }
  }, 8000);
  
  
  //contact pull down
  $('p.contact').toggle(function() {
  	
 	$('#contact').animate( {height: "400px"}, 200);
     $('header').animate({marginTop: "400px"}, 200);   
    
      //Form Autofocus
     // if (!("autofocus" in document.createElement("textarea"))) {
      //	$("#message").focus();
     // }

  }, function() {
      $('#contact').animate( {height: "7px"}, 200);
      $('header').animate({marginTop: "0px"}, 200);
 
  });

//contact links in page:
$('a.top').toggle(function() {
	$("html").animate({ scrollTop: 0 }, 600);
	$("body").animate({ scrollTop: 0 }, 600, function(){
	$('#contact').animate( {height: "400px"}, 200);
	$('header').animate({marginTop: "400px"}, 200);		
	});   
	}, function() {
	$('#contact').animate( {height: "7px"}, 200);
	$('header').animate({marginTop: "0px"}, 200);
});
  
  
  $('#twitter').toggle(function(){
  	$('#tweet-list').slideDown(200);
  	$('.infiniteCarousel').animate({opacity: 0.2}, 200);
  	  //css('opacity','0.25')
  }, function(){
  $('#tweet-list').slideUp(200);
  	$('.infiniteCarousel').animate({opacity:1}, 200);
  });
  
  //call twitter feed
  $.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=rawewebdesign&count=5&callback=?", function(tweetdata) {
  	var tl = $("#tweet-list");
  	$.each(tweetdata, function(i,tweet) {
  		tl.append("<li>" + urlToLink(tweet.text) + "<span>" + relTime(tweet.created_at) + "</span></li>");
  	});
  });	
  
  
});


