Date.prototype.toRelativeTime = function(now_threshold) {
  var delta = new Date() - this;
 
  now_threshold = parseInt(now_threshold, 10);
 
  if (isNaN(now_threshold)) {
    now_threshold = 0;
  }
 
  if (delta <= now_threshold) {
    return 'Just now';
  }
 
  var units = null;
  var conversions = {
    millisecond: 1, // ms    -> ms
    sekund: 1000,   // ms    -> sec
    minut: 60,     // sec   -> min
    timme:   60,     // min   -> hour
    dag:    24,     // hour  -> day
    månad:  30,     // day   -> month (roughly)
    år:   12      // month -> year
  };
 
  for (var key in conversions) {
    if (delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }
 
  // pluralize a unit when the difference is greater than 1.
  delta = Math.floor(delta);
  if (delta !== 1) { 
	//units += "s"; 
	switch(units){
		case 'sekund':
		case 'minut':
		case 'månad':
			units += 'er';
			break;
		case 'timme':
			units = 'timmar';
			break;
		case 'dag':
			units += 'ar';
			break;
	}
   }
  return [delta, units, "sen"].join(" ");
};
 
/*
 * Wraps up a common pattern used with this plugin whereby you take a String
 * representation of a Date, and want back a date object.
 */
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};

$(function(){
	
	$.getJSON('http://bluraystore.se/api/news?callback=?', function(response){
		var html = '<div class="box" id="push_movies"><ul id="latest_news"><h4>Senaste betygen</h4>'
		$.each(response, function(index, item){
			var post_time = new Date(item.timestamp).toRelativeTime()
			
			html += '<li><img src="' + item.coverimage + '" width="32" border="0" /><a href="/film/' + item.slug + '">' + item.title + '</a> fick betyg ' + item.rating + ' av 5 för ' + post_time + '</li>'
		});
		html += '</ul></div>';
		
		$('#context').append(html);
	});
	

	
	
	
	
	$("a[rel=shadowbox]").fancybox();
	
	$("#show_to_first_visitor").fancybox({
			width:480,
			height:300,
			autoScale : false,
			showCloseButton : false,
			centerOnScroll : true
	});
	
	$(".mongo #show_to_first_visitor").trigger('click');
	
	$('ul li:last-child').addClass('last-child');
	
	$("p.row :input").focus(function(){
		$(this).parent().find('span.item-msg').show();
	}).blur(function(){
		$(this).parent().find('span.item-msg').hide();
	});
	
	$("#profile").keyup(function(){
		var profile_name = $(this).val();
		profile_name = profile_name.replace(/\W/g,'');
		$(this).val(profile_name);
		$("#profile_url_slug").html(profile_name);
	});
	
	
	$("#query").autocomplete('/tools/partial').result(function(event, data, formatted){
		location.href = '/film/' + data[1];
	});
	
	
	$('html').addClass('js_loaded').removeClass('js_loading');
});

$(window).load(function(){
	$('img').each(function(){
			var img = this;
			var exchange = false;
		    if (!img.complete) {
		        //return false;
		exchange = true;
		    }

		    // However, they do have two very useful properties: naturalWidth and
		    // naturalHeight. These give the true size of the image. If it failed
		    // to load, either of these should be zero.
		    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
		       // return false;
			exchange = true;
		    }
		
			if(exchange) {
				//alert("byt út");
				this.src = 'http://bluraystore.se/images/default_cover.png';
				//$(this).attr('src' : 'http://bluraystore.se/images/default_cover.png');
			}

		    // No other way of checking: assume it's ok.
		    //return true;
	});
})
