var weatherCode;
var temp_C;
var weatherIconUrl;
var weatherDesc;
var windspeedMiles;
var winddir16Point;
var precipMM;
var humidity;
var visibility;
var pressure;
var cloudCover;
var dayOrNight;

var osMap;
var startPos;
var markersPos = new Array();
markersPos[0] = new OpenLayers.LonLat(-0.028787,51.460544);
markersPos[1] = new OpenLayers.LonLat(-0.003998,51.483100);

var markerIcons = new Array();
var markerContent = new Array();
var	infoWindowAnchor = new OpenLayers.Pixel(16,16);
var	infoWindowSize = new OpenLayers.Size(500,290);
var	infoWindowOffset = new OpenLayers.Pixel(-16,-37);
var markerSize = new OpenLayers.Size(33, 45);
markerIcons[0] = new OpenSpace.Icon("http://openspace.ordnancesurvey.co.uk/osmapapi/img_versions/img_1.0.0/OS/images/markers/marker_blue.png",markerSize,infoWindowOffset,null,infoWindowAnchor);
markerIcons[1] = new OpenSpace.Icon("http://openspace.ordnancesurvey.co.uk/osmapapi/img_versions/img_1.0.0/OS/images/markers/marker_blue.png",markerSize,infoWindowOffset,null,infoWindowAnchor);
markerContent[0] = '<div id="popUp"></div>';

var windowHeight = $(window).height();
var windowWidth = $(window).width();


function shortenPhrase(phrase,maxLength){
	if(phrase.length > maxLength){
		phrase = phrase.substr(0,maxLength);
		phrase += "&hellip;";
	}
	return phrase;
}

function addMarkersToMap(){
	for (var i in markersPos){
		var gridProjection = new OpenSpace.GridProjection();
		var pos = gridProjection.getMapPointFromLonLat(markersPos[i]);
		var marker = osMap.createMarker(pos,markerIcons[i]);
	}
}

function showInfoWindow(i){
	osMap.openInfoWindow(markerIcons[i],startPos,markerContent[0],infoWindowSize);
	 $('#closeDiv').click(function(e){
		$('#clouds,#airplane_1,#airplane_2,#birds').fadeIn(1000);
		setPlanesBirdsPositions();
		animatePlanes();
		animateBirds();
	});
}

function centreMap(zoomLevel){
	var gridProjection = new OpenSpace.GridProjection();
	startPos = gridProjection.getMapPointFromLonLat(markersPos[1]);
	osMap.setCenter(startPos,zoomLevel);
}

function rndNo(limit){
	return Math.floor(Math.random()*limit);
}

function animatePlanes(){
	$('#airplane_1').delay(5000).animate({"bottom": "+="+(windowHeight+250)+"px"}, 20000, 'linear', function(){
		$('#airplane_2').delay(10000).animate({"left": "+="+(windowWidth+250)+"px"}, 25000, 'linear', function(){
			setPlanesPositions();
			animatePlanes();
		});
	});	
}

function animateBirds(){
	$('#birds').animate({"left": "+="+(windowWidth+200)+"px"}, 32000, 'linear', function(){
		$('#birds').css({"background":"transparent url(images/flying_stuff/twitter_birds_reverse.png)"});
		$('#birds').animate({"left": "-="+(windowWidth+200)+"px"}, 32000, 'linear', function(){
			$('#birds').css({"background":"transparent url(images/flying_stuff/twitter_birds.png)"});
			animateBirds();	
		});	
	});	
}

function animateThunder(){
	$('.cloud_grey_l').each(function(index) {
		$('.cloud_grey_l').animate({"background":"transparent url(images/weather/clouds/thunder_cloud_grey_l.png)"});
  	});
}

function animateLights(){
    var randomLight = "#light_" + Math.round(Math.random()*2000);
	$(randomLight).effect("pulsate", { times: 1 }, 500);
	setTimeout(function() { animateLights() }, 300);
}

function setPlanesPositions(){
	var ap1Pos = rndNo(windowWidth-250)+"px";
	var ap2Pos = rndNo(windowHeight-250)+"px";
	$('#airplane_1').css({'bottom':'-250px','left':ap1Pos});
	$('#airplane_2').css({'bottom':ap2Pos,'left':'-250px'});
}

function setBirdsPositions(){
	var birdsPos = rndNo(windowHeight-200)+"px";
	$('#birds').css({'left':'-150px','top':birdsPos});
	$('#birds').css({"background":"transparent url(images/flying_stuff/twitter_birds.png)"});		
}

function setDayOrNight(sTime){
	var currentTime = new Date();
	var sunsetTimeArr = sTime.split(":");
	var sunsetHours = parseInt(sunsetTimeArr[0]);
	var sunsetMinutes = parseInt(sunsetTimeArr[1]);
	var sunsetDateTime = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate(), sunsetHours, sunsetMinutes, 0);

	if(currentTime < sunsetDateTime){
		dayOrNight = "day";
		centreMap(9);
		setTimeout(function() { animatePlanes();animateBirds(); }, 5000);
	}
	else{
		dayOrNight = "night";
		$('#dayOrNight').css({'background-color':'black'}).css({ opacity:0.6 });
		$('#content').css({'-webkit-box-shadow':'0px 0px 0px black'});
		$('#content').css({'-moz-box-shadow':'0px 0px 0px black'});
		$('#content').css({'border':'6px solid #444'});
		$('#content').css({'background':'#444'});
		setLights();
		centreMap(7);
	}
	getWeather();
}

function setLights(){
	for(var i=0;i<=2000;i++){
		var lId = "light_" + i;
		$('#lights').append('<div id="' + lId + '" class="light">&bull;</div>');
		var lXPos = rndNo(windowWidth)+"px";
		var lYPos = rndNo(windowHeight)+"px";
		$('#'+lId).css({'top':lYPos,'left':lXPos});
		$('#'+lId).css({'font-size':rndNo(10)+'px'});
		switch(rndNo(5))
		{
			case 0,1,2:
			$('#'+lId).css({'color':'#FFDA90'});
			break;
			case 3:
			$('#'+lId).css({'color':'#CD9856'});		
			break;
			case 4:
			$('#'+lId).css({'color':'#AFD38D'});		
			break;			
		}		
	}
	animateLights();
}

function setWeather(d){
	
	weatherCode = d.data.current_condition[0].weatherCode;
	temp_C = d.data.current_condition[0].temp_C;
	weatherIconUrl = d.data.current_condition[0].weatherIconUrl[0].value;
	weatherIconUrl = weatherIconUrl.replace("http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/","");
	weatherDesc = d.data.current_condition[0].weatherDesc[0].value;
	windspeedMiles = d.data.current_condition[0].windspeedMiles;
	winddir16Point = d.data.current_condition[0].winddir16Point;
	precipMM = d.data.current_condition[0].precipMM;
	humidity = d.data.current_condition[0].humidity;
	visibility = d.data.current_condition[0].visibility;
	pressure = d.data.current_condition[0].pressure;
	cloudCover = d.data.current_condition[0].cloudcover;

	var weatherString = "<a href='http://www.worldweatheronline.com/' alt='Free local weather content provider'><img src='images/weather/icons/"+weatherIconUrl+"' alt="+weatherDesc+" /> <span><em>"+weatherDesc+"</em>, "+temp_C+"&#186;C, "+cloudCover+"% cloud cover, "+windspeedMiles+"mph "+winddir16Point+" wind, "+visibility+"km visibility</a></span>";
	$("#weather").html(weatherString);

	// Set clouds
	if(weatherTypes[weatherCode] == "rain" || weatherTypes[weatherCode] == "thunder"){
		var colour = "grey";
		var cNo = 4;
	}
	else{
		var colour = "white";
		var cNo = 4;
	}
	
	if(dayOrNight == "night"){
		var colour = "black";	
		var cNo = 3;
	}
	
	for(var i=0;i<=cloudCover;i++){
		var cId = "cloud_" + i;
		if(cloudCover > 25){
			switch(rndNo(cNo))
			{
				case 0,3:
				var cClass = "cloud_s cloud_"+colour+"_s";
				var size = "s";
				break;
				case 1:
				var cClass = "cloud_m cloud_"+colour+"_m";
				var size = "m";
				break;
				case 2:
				var cClass = "cloud_l cloud_"+colour+"_l";  				
				var size = "l";
				break;
			}
		}
		else{
			var cClass = "cloud_s cloud_"+colour+"_s";
			var size = "s";
		}
		$('#clouds').append('<div id="'+cId+'" class="'+cClass+'"></div>');
		var cloudXPos = rndNo(windowWidth-250)+"px";
		var cloudYPos = rndNo(windowHeight-140)+"px";
		$('#'+cId).css({'top':cloudYPos,'left':cloudXPos});
		if(jQuery.browser.msie){				
			switch(rndNo(3))
			{
				case 0,1:
				$('#'+cId).css({ 'background': 'transparent url(images/weather/clouds/ie/cloud_'+colour+'_'+size+'.png)' });
				break;
				case 2:
				$('#'+cId).css({ 'background': 'transparent url(images/weather/clouds/cloud_'+colour+'_'+size+'.png)' });
				break;
			}
		}
		else{
			if(dayOrNight == "day"){
				var op = rndNo(11)/10;
				$('#'+cId).css({ opacity: op });			
			}
			else{
				$('#'+cId).css({ opacity: '0.2' });			
			
			}
			
		}
	}

	if(cloudCover >= 90){
		$('#weatherMask').css({'background-color':colour}).css({ opacity:0.3 });
	}

	// Set visibility
	if(visibility < 1){
		$('#weatherMask').css({'background-color':'black'}).css({ opacity:visibility });
	}

	// Set fog
	if(weatherTypes[weatherCode] == "fog"){
		$('#weatherMask').css({'background-color':'black'}).css({ opacity:0.2 });
	}
	
	// Set snow
	if(weatherTypes[weatherCode] > 0){
		$('#weatherMask').css({'background-color':'white'}).css({ opacity:0.8 });
	}
	
	// Set cold/frost
	if(temp_C < 0){
		$('#weatherMask').css({'background-color':'white'}).css({ opacity:0.6 });
	}
	
	// Set thunder
	//if(weatherTypes[weatherCode] == "rain" || weatherTypes[weatherCode] == "thunder"){
	//	setTimeout(function() { animateThunder(); }, 5000);
	//}

}

function getWeather(){
	$.getJSON("http://free.worldweatheronline.com/feed/weather.ashx?q=SE10&format=json&num_of_days=1&key=9020e25170185046110301&callback=?",
		function(data){			
			setWeather(data);
	});
}

function getSunsetTime(){
	$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20description%20from%20rss(1)%20where%20url%3D%22http%3A%2F%2Fnewsrss.bbc.co.uk%2Fweather%2Fforecast%2F2574%2FNext3DaysRSS.xml%3Farea%3DSE4%22&format=json&diagnostics=true&callback=?",
		function(data){	
			var desc = data.query.results.item.description;
			var sunsetPos = desc.search("Sunset:");
			var sunsetTime = desc.slice(sunsetPos+8,sunsetPos+13);
			setDayOrNight(sunsetTime);
	});
}

function getTweet(){
	$.getJSON("http://twitter.com/status/user_timeline/eddequincey.json?count=1&callback=?",
		function(data){
			$(".twitter").html("<a href='http://twitter.com/#!/eddequincey/status/"+data[0].id_str+"'>"+shortenPhrase(data[0].text,38)+"</a>");
			$("ul").slideDown(1000, function(){});
	});
}

function getFlickr(){
	$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=93863074@N00&format=json&jsoncallback=?",
		function(data){
			$.each(data.items, function(i,item){
				$(".flickr").html("<a href='"+item.link+"'>"+shortenPhrase(item.title,38)+"</a>");
				if ( i == 0 ) return false;
			});
	});	
}

function getDelicious(){
	$.getJSON("http://feeds.delicious.com/v2/json/eddequincey/?callback=?",
		function(data){
			$(".delicious").html("<a href='"+data[0].u+"'>"+shortenPhrase(data[0].d,38)+"</a>");
	});
}

function getLastFM(){
	$.getJSON("http://ws.audioscrobbler.com/2.0/?format=json&method=user.getrecenttracks&user=eddequincey&limit=1&callback=?&api_key=7998bb363fd0a6b5ade4831610060bca",
		function(data){
			if(!data.recenttracks.track.url){
				$(".lastfm").html("<a href='"+data.recenttracks.track[0].url+"'>"+shortenPhrase("Listening to: "+data.recenttracks.track[0].name+" by "+data.recenttracks.track[0].artist["#text"],38) +"</a>");
			}
			else{
				$(".lastfm").html("<a href='"+data.recenttracks.track.url+"'>"+shortenPhrase(data.recenttracks.track.name+" by "+data.recenttracks.track.artist["#text"],38) +"</a>");			
			}
	});
}

function setTipPosition(id){
	var idWidth = $("#"+id).width()/2 -4;
	var idPos = $("#"+id).offset();
	var tipPos = idWidth+idPos.left+"px";
	$("#tip").animate({"left":tipPos},500);
}

$(document).ready(function(){
	
	var controls = [new OpenLayers.Control.Navigation(),
					new OpenLayers.Control.KeyboardDefaults(),
					new OpenSpace.Control.CopyrightCollection(),
					new OpenLayers.Control.ArgParser()];

	osMap = new OpenSpace.Map('map', {controls: controls});
	var position = new OpenSpace.Control.ControlPosition(OpenSpace.Control.ControlAnchor.ANCHOR_TOP_RIGHT);
	osMap.addControl(new OpenSpace.Control.LargeMapControl(), position);
	addMarkersToMap();
	setPlanesPositions()
	setBirdsPositions();		
	getSunsetTime();
	getTweet();
	getFlickr();
	getDelicious();
	getLastFM();
		
	$('#logo').click(function(e){
		e.preventDefault();
		$('#tip').css({"background-image":"url(images/bgs/tip-green.png)"});
		setTipPosition('logo');
		$('#aboutMe,#research,#contact').hide();
		$('#content').fadeIn("slow").css({"width":"300px" },1000);
		$('#web2point0').show();
	});
	$('#aboutMeLink').click(function(e){
		e.preventDefault();
		$('#tip').css({"background-image":"url(images/bgs/tip-blue.png)"});
		setTipPosition('aboutMeLink');
		$('#research,#contact,#web2point0').hide();
		var h1Width = $('h1').width() -12 + "px";
		$('#content').fadeIn("slow").css({"width":h1Width },1000);
		$('#aboutMe').show();
	});
	$('#researchLink').click(function(e){
		e.preventDefault();
		$('#tip').css({"background-image":"url(images/bgs/tip-blue.png)"});
		setTipPosition('researchLink');
		$('#aboutMe,#contact,#web2point0').hide();
		var h1Width = $('h1').width() -12 + "px";
		$('#content').fadeIn("slow").css({"width":h1Width },1000);
		$('#research').show();
	});
	$('#contactLink').click(function(e){
		e.preventDefault();
		$('#tip').css({"background-image":"url(images/bgs/tip-blue.png)"});
		setTipPosition('contactLink');
		$('#research,#aboutMe,#web2point0').hide();
		var h1Width = $('h1').width() -12 + "px";
		$('#content').fadeIn("slow").css({"width":h1Width },1000);
		$('#contact').show();
	});
	 $('#closeLink').click(function(e){
		e.preventDefault();
		$('#content').fadeOut("slow");
		$('#tip').css({"background-image":"url()"});			
	});		
	
});
