var map;
var restaurants = [];
var lastAccuracy = 0;
var user = false;

function initialize() {
	var myOptions = {
		zoom: 4,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false,
		navigationControl: false
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//	map.addControl(new GSmallZoomControl());
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(search);
		window.setTimeout( updateLocation, 10000 );
	} else {
		alert('This application is designed to be used with a location aware device such as an iPhone or and Android phone. A demo location has been chosen for you to demo the functionality.');
		search({
		  "coords" : {
			"latitude" : "51.515244",
			"longitude" : "-0.132177"
		  }
		});
	}
}
function updateLocation(){
  navigator.geolocation.getCurrentPosition(
    function(position){
      if(lastAcuracy < position.coords.accuracy && ((position.coords.accuracy / lastAcuracy) < 0.9)){
        lastAcuracy = position.coords.accuracy;
        for(var i = 0, ii = restaurants.length; i<ii; i++){ restaurants[i].setMap(null); }
        search(position);
      }
    }
  );
	window.setTimeout( updateLocation, 10000 );
}
function search(center) {
  lastAccuracy = center.coords.accuracy;
  
	var searchUrl = './map/loadData2.php?'+'lat='+center.coords.latitude+'&lon=' + center.coords.longitude;
//		console.log(searchUrl);
	var script = document.createElement("script");
	script.src = searchUrl;
	document.getElementsByTagName("head")[0].appendChild(script);
	
	var position = new google.maps.LatLng(center.coords.latitude,center.coords.longitude);
	if(user){
	  user.setPosition(position);
	} else {
  	user = new google.maps.Marker({
  		position: position,
  		map: map,
  		icon: './map/user.png'
  	});
  }
}
function addPoints(markers){
	var bounds = new google.maps.LatLngBounds();
	var infowindow = new google.maps.InfoWindow();
	
	for (var i = 0, ii = markers.length; i < ii; i++) {
		(function(i){
			var position = new google.maps.LatLng(markers[i].lat,markers[i].lng);
			var infoContent = createInfo(markers[i]);
			var marker = new google.maps.Marker({
			    position: position,
			    map: map,
				icon: './map/pin.png'
			});
      
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setOptions( { maxWidth: 300, content: infoContent });
				infowindow.open(map,marker);
			});
			restaurants.push(marker);
			bounds.extend(position);
		})(i);
	}
	map.setCenter(bounds.getCenter());
	map.fitBounds(bounds);
}
function createInfo(place) {
	var phone = '<a href="tel:'+place.bookingtel.split('/')[0].replace(/ /g,'')+'">'+place.bookingtel.split('/')[0]+'</a>'
	var html = '<div id="marker"><div class="name"><p>' + place.name + '<br />' + place.address + '<br />Cuisine: ' + place.cuisine + '<br />Bookings: ' + phone + '</p></div>';
	
	html += '<div class="icons"><img src="./map/img/' + place.restaurantCardUseType + '" alt="Offer Type" />';
	if(place.restaurantPhoneBookings !== '0') {
		html += '<img src="./map/img/' + place.restaurantPhoneBookings + '" alt="Bookings Only" />';
	}
	html += '<img src="./map/img/' + place.restaurantCardUse + '" alt="Card Use" />';
	if(place.availableSat !== '0') {
		html += '<img src="./map/img/' + place.availableSat + '" alt="Not Available Saturday" />';
	}
	if(place.availableFri !== '0') {
		html += '<img src="./map/img/' + place.availableFri + '" alt="Not Available Friday" />';
	}
	html += '</div>';
	return html;
}


var cacheStatusValues = [];
cacheStatusValues[0] = 'uncached';
cacheStatusValues[1] = 'idle';
cacheStatusValues[2] = 'checking';
cacheStatusValues[3] = 'downloading';
cacheStatusValues[4] = 'updateready';
cacheStatusValues[5] = 'obsolete';

var cache = window.applicationCache;
cache.addEventListener('cached', logEvent, false);
cache.addEventListener('checking', logEvent, false);
cache.addEventListener('downloading', logEvent, false);
cache.addEventListener('error', logEvent, false);
cache.addEventListener('noupdate', logEvent, false);
cache.addEventListener('obsolete', logEvent, false);
cache.addEventListener('progress', logEvent, false);
cache.addEventListener('updateready', logEvent, false);

function logEvent(e) {
    var online, status, type, message;
    online = (navigator.onLine) ? 'yes' : 'no';
    status = cacheStatusValues[cache.status];
    type = e.type;
    message = 'online: ' + online;
    message+= ', event: ' + type;
    message+= ', status: ' + status;
    if (type == 'error' && navigator.onLine) {
        message+= ' (prolly a syntax error in manifest)';
    }
    console.log(message);
}

window.applicationCache.addEventListener(
    'updateready',
    function(){
        window.applicationCache.swapCache();
        console.log('swap cache has been called');
    },
    false
);

