function pad(num){
	if(num < 10) num = '0'+num;
	return num;
}
function offSet(hours){
	return (hours % 3);
}
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

var Maps = function(area){
	this.area = area;
	this.d = new Date();
	this.d.setMinutes(0);
	this.startTime = this.d.getHours() - offSet(this.d.getHours())
	this.dates = this.getDays();
	this.images = this.populateDays();
	this.currentImage = 0;
	this.increment(0);
}
Maps.prototype.increment = function(i){
	if((this.currentImage + i) > -1 && (this.currentImage + i) < this.images.length){
		this.currentImage = this.currentImage + i;
		next = this.currentImage;
		var i = new Image();
		i.src = this.images[next].url;
		i.onload = function(){
			document.getElementById('loading').style.display = "none";			
		}
		document.getElementById('map').src = this.images[next].url;
		var display_hour = this.images[next].date.getHours();
		if(display_hour < 10) display_hour = '0'+display_hour;
		var t = days[this.images[next].date.getDay()] + ' ' + display_hour + ':00';
		document.getElementById('date').innerHTML = t;
	} else {
		document.getElementById('loading').style.display = "none";
		return false;
	}
}
Maps.prototype.getDays = function(){
	var dates = new Array(4);
	for(var i = 0; i < 5; i++){
		var year = String(this.d.getFullYear()).substring(2);
		var month = pad(this.d.getMonth()+1);
		var date = pad(this.d.getDate());
		dates[i] = {"date": new Date(this.d), "url": year+month+date};
		this.d.setDate(this.d.getDate()+1);
	}
	return dates;
}
Maps.prototype.populateDays = function(){
	var j = 0;
	var hour = this.startTime;
	var images = new Array()
	for(date in this.dates){
		if(j > 0){
			hour = 0;
		}
		while(hour < 24){
			if(hour == 24){
				url_hour = '00' 
			} else {
				url_hour = pad(hour);
			}
//			var url = "http://www.bbc.co.uk/weather/charts/uk/"+this.area+"_cloudrain_" + this.dates[date].url + url_hour + ".jpg";
			var url = "http://uk-weather-app-maps.appspot.com/image?date=" + this.dates[date].url + url_hour + "&location="+this.area;
//			var i = new Image();
//			i.src = url;
			var i = '';
			images[j++] = {
				"url" : url,
				"image" : i,
				'date': new Date(this.dates[date].date.setHours(hour)) };
			if(j < 9){
				hour = hour + 3;
			} else {
				if(hour < 12)
					hour = 12;
				else 
					hour = 24;
			}

		}
	}
	return images;
}
var currentMaps;

function areWeWebClip(){
	// We want an iPhone or iPod Touch
	if (navigator.appVersion.indexOf('iPhone OS ') < 0) {
		// if this gets fired we can give a preview of the app as webkit functionality is requierd. .
		document.getElementById("wrapper").addEventListener('webkitTransitionEnd', showFullSafari, false);
		document.getElementById('wrapper').className += " notCompatible";
		document.getElementById('nonTouchDevice').style.display = 'block';
	} else if (!window.navigator.standalone) {
		// We have an iPhone but we are
		// not running as an installed app
		alert('This app works best when added to your home screen. To do this click the plus in the bottom bar and click "Add to Home Screen".');
		
	}
}
function showFullSafari(){
	document.getElementById('nonTouchDevice').style.display = 'none';
	document.getElementById('wrapper').className += " fullSafari";
	document.getElementById('fullSafari').style.display = "block";
	document.getElementById('wrapper').style.left = '50%';
}
function init(){
	areWeWebClip(); // really the interface is so much nicer if it is
	var currentMaps = null;
	var currentLocation = null;
	var sliding = document.getElementById('sliding');
	var locations = document.getElementsByClassName("location");
	try { 
  	var db = openDatabase('user', '1.0', 'UserConfig', 2 * 1024);
    db.transaction(function (tx) {
      tx.executeSql('CREATE TABLE IF NOT EXISTS Config (key TEXT, value TEXT)');
    });
	} catch(e){}
	
	function showCurrentLocation(){
		currentMaps = new Maps(currentLocation);
		sliding.removeEventListener('webkitTransitionEnd', showCurrentLocation, false);
	}
	function showLoadingMaps(){
		document.getElementById("map").src = 'loading.jpg';
		sliding.removeEventListener('webkitTransitionEnd', showLoadingMaps, false);
	}
	function removeOverlay(){
		sliding.removeEventListener('webkitTransitionEnd', removeOverlay, false);
	  document.getElementById('overlay').style.display = "none";
	}
	function getLastScreen(){
	  try { 
	    db.transaction(function(tx){
	      tx.executeSql("SELECT * FROM Config WHERE key='last'", [], function(tx, result){
	        if(result.rows.length){
	          var last = result.rows.item(0).value.split('|');
	          if(last[0] == 'location'){
	            currentLocation = last[1];
	            showCurrentLocation();
	            sliding.style.left = "-320px";
	            sliding.addEventListener('webkitTransitionEnd', removeOverlay, false)
//	            sliding.style.webkitTransitionDuration = ".5s";
	          } else {
	            removeOverlay();
	          }
	        } else {
	          removeOverlay();
	        }
	      });
	    });
	  } catch(e){
	    removeOverlay();
	  }
	}
	getLastScreen();
	function saveLastScreen(screen){
	  try {
	    db.transaction(function(tx){
	      tx.executeSql("SELECT * FROM Config WHERE key='last'", [], function(tx, result){
	        if(result.rows.length){
	          tx.executeSql('UPDATE Config SET value=? WHERE key=?', [screen,'last']);
	        } else {
	            tx.executeSql('INSERT INTO Config (key, value) VALUES (?, ?)', ['last', screen]);
	        }
        });
	    });
	  } catch(e){}
	}

	
	for(var i=0, j=locations.length; i<j; i++){
		addEvent( locations[i], 'click', function(){
			currentLocation = this.getAttribute('location');
			saveLastScreen('location|'+currentLocation);
			sliding.addEventListener('webkitTransitionEnd', showCurrentLocation, false);
			sliding.style.left = "-320px";
		});
	}
	addEvent( document.getElementById('goHome'), 'click', function(){
		saveLastScreen('home');
		sliding.addEventListener('webkitTransitionEnd', showLoadingMaps, false);
		document.getElementById('sliding').style.left = "0px";
	});
	addEvent( document.getElementById('back'), 'click', function(){
		document.getElementById('loading').style.display = "block";
		currentMaps.increment(-1);
	});
	addEvent( document.getElementById('forward'), 'click', function(){
		document.getElementById('loading').style.display = "block";
		currentMaps.increment(+1);
	});
	addEvent( document.getElementById('map'), 'click', function(){
		document.getElementById('loading').style.display = "block";
		currentMaps.increment(+1);
	});
}


// A Good Enough addEvent 
// http://ilfilosofo.com/blog/2008/04/14/addevent-preserving-this/
var addEvent = function( obj, type, fn ) {
  if (obj.addEventListener)
    obj.addEventListener(type, fn, false);
  else if (obj.attachEvent) 
    obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event));});
}

// Sucks if you can't grab one of these. But then again you probably fail at life anyway.
var onReady = function( fn ) {
	if ( document.addEventListener ) {
    document.addEventListener( "DOMContentLoaded", fn, false );
  } else if ( document.attachEvent ) {
    window.attachEvent( "onload", fn );
  }
} 
onReady(init);
