$(document).ready( function(){
  
  var scrolls = 0, scrollLimit = 5;
  $('body').addClass('js');
  
  // https://gist.github.com/738720
  var supports3d = function() {
  	var div = document.createElement('div'),
	ret = false,
	properties = ['perspectiveProperty', 'WebkitPerspective'];
	for (var i = properties.length - 1; i >= 0; i--){
		ret = ret ? ret : div.style[properties[i]] != undefined;
	};
	if (ret){
		var st = document.createElement('style');
		st.textContent = '@media (-webkit-transform-3d){#test3d{height:3px}}';
		document.getElementsByTagName('head')[0].appendChild(st);
		div.id = 'test3d';
		document.body.appendChild(div);
		ret = div.offsetHeight === 3;
		st.parentNode.removeChild(st);
		div.parentNode.removeChild(div);
    }
    return ret;
  },
  supportsMobile = function() {
  	var ua = navigator.userAgent;
	return (ua.match(/iPhone/i) || ua.match(/iPod/i) || ua.match(/iPad/i) || ua.match(/Android/i) || ua.match(/Windows Phone/i) || ua.match(/BlackBerry/i) || ua.match(/Nokia/i));
  },
  supportsIOS5 = function() {
  	var ua = navigator.userAgent;
	return (ua.match(/iPhone/i) || ua.match(/iPod/i) || ua.match(/iPad/i)) && ua.match(/OS ([5-9]|[0-9]{2,})/i);
  },
  supportsFixed = function() {
	  var container = document.body;
	  
	  if (document.createElement && container && container.appendChild && container.removeChild) {
		var el = document.createElement('div');
		
		if (!el.getBoundingClientRect) return null;
			
		el.innerHTML = 'x';
		el.style.cssText = 'position:fixed;top:100px;';
		container.appendChild(el);
	
		var originalHeight = container.style.height,
			originalScrollTop = container.scrollTop;
	
		container.style.height = '3000px';
		container.scrollTop = 500;
	
		var elementTop = el.getBoundingClientRect().top;
		container.style.height = originalHeight;
		
		var isSupported = (elementTop === 100);
		container.removeChild(el);
		container.scrollTop = originalScrollTop;
	
		return isSupported;
	  }
	  return null;
  };
  
  var support = {
  	threeD: supports3d() && !supportsMobile(),
  	fixed: supportsFixed() || supportsIOS5()
  },
  hideInstructions = function() {
  	if (scrolls > scrollLimit) $('#instructions').fadeOut();
  },
  cardlist = {};
  
  $('#cardpile').addClass('active');
  if (support.threeD) {
  	$('#cardpile').addClass('transform-3d');
  }
  
  var w = {w: null, h: null},
  c = {w: null, h: null},
  cn = null,
  ph = null,
  dh = null,
  index = 1,
  scrollAnim = true,
  init = function() {
    w.h = $(window).height(), 
    w.w = $(window).width(),
    c.w = $('#cardpile ul li:first').width(),
    c.h = $('#cardpile ul li:first').height(),
    cn  = $('#cardpile ul li').length + 1,
    dh  = $(document).height()-w.h,
    ph  = $('#cardpile').height();
  };
  init();
  
  $('#cardpile ul li').each(function(i){
    if (!this.id) {
      this.id = index, index++;
    }
    /*
    var l = $('<a />', {
    	'class':    'anchor',
    	href:       '#' + this.id,
    	html:       '&#x2022;'
    });
    $(this).prepend(l);
    */
    var start = Math.round((dh/cn)*i);
    cardlist[start] = this.id;
    
    $('#cardlist ol').append('<li>' + (i+1) + '.</li>');
  });
  
  var actions = {
    _findTop: function(id) {
	  var st = $(window).scrollTop(),
	  top = null;
	  for (var i in cardlist) {
		if (cardlist[i] == id) {
		  top = i;
		  break;
	    }
	  }
	  return top;
	},
    _go: function(target) {
		if (!!target) {
		  var top = actions._findTop(target.attr('id'));
		  if (!!top || top === 0) {
			$(window).scrollTop(top);
		  }
		}
    },
	first: function() {
	  actions._go($('#cardpile ul li:first'));
	},
	last: function() {
	  actions._go($('#cardpile ul li:last'));
	},
	prev: function() {
	  actions._go($('#cardpile ul li.visible').prev());
	},
	next: function() {
	  actions._go($('#cardpile ul li.visible').next());
	}
  },
  keys = function() {
    var events = {
      33: actions.prev,
      32: actions.next,
      34: actions.next
    };
    $(window).keydown(function(e) {
      if (!!events[e.keyCode]) {
        e.preventDefault();
        events[e.keyCode]();
      }
    });
  },
  buttons = function() {
  	$('<ul>', {id: 'buttons'}).appendTo('body');
  	$('<li>', {id: 'button-first', html: '&#8676;', title: 'First', 'data-binding': 'first'}).appendTo('#buttons');
  	$('<li>', {id: 'button-prev', html: '&larr;', title: 'Previous', 'data-binding': 'prev'}).appendTo('#buttons');
  	$('<li>', {id: 'button-next', html: '&rarr;', title: 'Next', 'data-binding': 'next'}).appendTo('#buttons');
  	$('<li>', {id: 'button-last', html: '&#8677;', title: 'Last', 'data-binding': 'last'}).appendTo('#buttons');
  	
  	var toggledBinder = null;
  	
  	$('#buttons li').click(function(){
  	  $(this).addClass('toggled');
  	  var binding = $(this).data('binding');
  	  if (!!actions[binding] && typeof actions[binding] == 'function') {
  	  	actions[binding]();
  	  }
  	  toggledBinder = setTimeout(function(){
  	  	$('.toggled').removeClass('toggled');
  	  }, 1000);
  	});
  };
  
  if (supportsMobile()) {
  	// $('#cardlist').show();
  	buttons();
  	$('#instructions').text('Scroll page / Buttons at top of screen');
  }
  else {
    keys();
  }
  
  var sizeWindow = function() {  
    init();
    if (support.fixed) {
    	$('#cardpile').css('height', ph + 'px');
		$('#cardpile ul li').css('position', 'absolute');
		$('#cardpile ul').css('position', 'fixed').css({
		  'top':  (w.h-c.h)/2 + 'px',
		  'left': (w.w-c.w)/2 + 'px'
		});
		
		if ($('#cardpile ul li.visible').length == 0) {
		  $('#cardpile ul li:first').addClass('visible');
		}
    }
    else {
    	$('#cardpile').removeClass('active');
    }
    if ($('body').hasClass('loading')) {
	  setTimeout(function(){
	  	$('body').removeClass('loading');
	  }, 400);
    }
  },
  windowEvents = {
    resize: function() {
      sizeWindow();
    },
    scroll: function(e) {
      hideInstructions();
      scrolls++;
      var st = $(window).scrollTop(),
      	  index = null;
      for (var i in cardlist) {
      	if (st >= i) {
      		index = cardlist[i];
      	}
      	if (st < i) {
      		break;
      	}
      }
      if (!!index) {
      	$('#cardpile ul li.visible').removeClass('visible');
      	$('#cardpile ul li#' + index).addClass('visible');
      }
      
      $('#buttons').css('top', $(window).scrollTop() + 'px');
    }
  };
  
  for (var i in windowEvents) {
    $(window).bind( i, windowEvents[i] );
  }
  setTimeout(function(){
  	sizeWindow();
  }, 250);
});
