var updateDelay = 2000;
var maxRequests = 100;
var requests = 0;
var showing = 3;
var count = showing + 1;
var currentJson;
var i = 1;
var ts = 0;
var items = new Array(showing);
var serverDelay = 0;
var time = 0;
var showFirstTime = true;
var firstLaunch = true;
var scanDebug = false;

function showTime() {
  var currentTime = new Date();
  $('#productTime').html(relativeTime(Math.floor(currentTime.getTime()/1000) - time - serverDelay));
}

function update() {
  showTime();
 	$.get("/api/request", {"data" : { "p" : "get_lastscan", "ts" : ts }}, gotData);
 	var currentTime = new Date();
	for (index = 0; index < showing; index++) {
	  j = count - index - 1;
	  if (items[index]) { 
			$('#rtime'+j).html(relativeTime(Math.floor(currentTime.getTime()/1000) - items[index].time - serverDelay));
		}
	}
}

function relativeTime(delay) {
	if (delay < 2) {
		return 'il y a une seconde';
	} else if (delay < 60) {
		return 'il y a ' + delay + ' secondes';
	} else if (delay < 120) {
		return 'il y a une minute';
	} else if (delay < 3600) {
		return 'il y a ' + Math.floor(delay / 60) + ' minutes';
	} else if (delay < 7200) {
		return 'il y a une heure';
	} else {
		return 'il y a ' + Math.floor(delay / 3600) + ' heures';
	}
}

function buildItem(json, index) {
  var rtime = relativeTime(json.servertime - json.time);   
  var display = json.index ? 'block' : 'none';
  var location = "";
  if (json.location) {
    location = " à <font color='#444'>" + json.location + "</font>";
  }
  var result = '<div style="display:' + display + '" id="recent' + index + '"><li><img onerror="this.style.visibility = \'hidden\'" src="' + json.url_img + '" style="width:25px; height:25px"><p><a href="http://www.prixing.fr/product/' 
                + json.ean +'">' + json.title + '</a></p><p>Scanné <span id="rtime' + index + '">' 
                + rtime + '</span>' + location + '</p></li></div>';
	return result;
}

function shift() {
	var toShow = count;
  $('#recent'+count).slideDown(1000, move(i));
  $('#recent'+i).slideUp(1000, move(i));
  i++;
  count++;
}    
function move(idx) {
  return function() {
    $('#recent'+idx).remove();
  }
}

function addHistory(json) {
  $('#liveContent').prepend(buildItem(json, json.index ? count - json.index : count));
  if (showFirstTime) {
   	$("#liveHistory").show();
   	showFirstTime = false;
  }
  for (idx = showing - 1; idx > 0; idx--) {
	  items[idx] = items[idx-1];
  }
  items[0] = json;
}

function gotData(json) {
  if (!firstLaunch && requests++ < maxRequests) {
	  if (scanDebug) { console.log("liveScan: request update in " + updateDelay) }
    setTimeout('update()', updateDelay);
	}
  if (!json) {
    return;
  }
 	var currentTime = new Date();
  serverDelay = Math.floor(currentTime.getTime()/1000) - json.servertime;
  if (json.index == 0 || isNaN(json.index)) {
    ts = json.time;
    if (json.title != "undefined" && (!currentJson || currentJson.url_img != json.url_img)) {
      if (currentJson && currentJson.index == 0) {
        addHistory(currentJson);
  	    shift();
      }
	    addMarker(json);
	  }
	  if (firstLaunch) {
  	  setTimeout('update()', 500);
  	  firstLaunch = false;
  	}
  } else {
    addHistory(json);
    addMarker(json);
    if (scanDebug) { console.log("liveScan: API request " + json.index) }
  	$.get("/api/request", {"data" : { "p" : "get_lastscan", "ts" : "0", "index": json.index - 1 }}, gotData);
  }
  currentJson = json;
}

$(document).ready(function() {
	map = new google.maps.Map(document.getElementById("map"), myOptions);
	map.setCenter(new google.maps.LatLng(48.82,2.34));
	if (scanDebug) { console.log("liveScan: API request " + showing) }
	$.get("/api/request", {"data" : { "p" : "get_lastscan", "ts" : "0", "index" : showing }}, gotData);
});
  
var map;
var geocoder;

var myOptions = {
		zoom: 8,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		draggable: false,
		mapTypeControl: false,
		scrollwheel: false,
		streetViewControl: false
};

var bounds = new google.maps.LatLngBounds();
var marker;

function addMarker(json) {
 	if (json.lat != 0 && json.lng != 0 && map != null) {
   	var point = new google.maps.LatLng(json.lat, json.lng);
   	if (marker != null) {
   		marker.setMap(null);
   	}
   	var max = 72;
   	var w,h;
   	var ratio = json.width / json.height;
   	if (json.width > json.height) {
   	  w = max;
   	  h = json.height / json.width * max
   	} else {
   	  w = json.width / json.height * max
   	  h = max
   	}
   	var icon = new google.maps.MarkerImage(json.url_img, null, null, new google.maps.Point(max/2, 100-(max-h)/2), new google.maps.Size(w, h))
   	marker = new google.maps.Marker({
   		position: point,
 			map: map,
 			icon: icon,
      shadow: new google.maps.MarkerImage("/images/backgrounds/map_pin.png"),
      zIndex: -200
   	});
   	time = json.time;
   	var currentTime = new Date();
    var location = "";
    if (json.location) {
      location = " à <font color='#444'>" + json.location + "</font>";
    }
    serverDelay = Math.floor(currentTime.getTime()/1000) - json.servertime;
   	$("#productTitle").html(json.title);
   	$("#productLocation").html(location);
   	$("#productLink").attr("href", "/product/" + json.ean);
   	$("#liveProduct").show();
   	showTime();
   	map.setCenter(point);	   		
   	map.panBy(0,-60);
  }
}




