﻿/*--------------------------------------------
// Shelter Houseblinger JS
--------------------------------------------*/

//API Loaders
google.load("maps", "2.140", {"other_params":"sensor=false"}); //Do not update
google.load("search" , '1');
google.load("jquery", "1.3.2");


//===== Variables ======

//Global variables
var mapReady = false; //Required for AS3 - JS interaction
var map; //Google Maps applet container
var postcodeSearch; //Search container
var streetview; //Streetview container
var currentLocation; //Holds LatLng of current location
var currentPOV; //Holds current POV
var controlsInit=false;
var currentPostcode = "";
var currentID; //Holds ID of saved Bling if saved

function FamousPlace(lat,lng,yaw,pitch,zoom) {
	this.Lat = lat;
	this.Lng = lng;
	this.Yaw = yaw;
	this.Pitch = pitch;
	this.Zoom = zoom;
}
var fL = new Array(); //Famous locations array
//Famous places
	//England
	fL['housesofparliament'] = new FamousPlace(51.499393,-0.126085,68.59,-15.14,0); 
	fL['bigben'] = new FamousPlace(51.500797,-0.120922,251.59,-7.27,1); 
	fL['wembleystadium'] = new FamousPlace(51.558589,-0.281546,149.73,-10.84,0); 
	fL['royalalberthall'] = new FamousPlace(51.50156,-0.177986,140.06,-17.31,0);
	fL['leedstownhall'] = new FamousPlace(53.799554,-1.549632,354.01,-18.07,0);
	fL['roversreturn'] = new FamousPlace(53.477792,-2.255495,44.36,8.35,0);
	fL['newcastlebaltic'] = new FamousPlace(54.969132,-1.596779,295.9,-23.32,0);
	fL['oldestpub'] = new FamousPlace(52.949428,-1.152274,241.54,-4.05,0);
	//Wales
	fL['milleniumstadium'] = new FamousPlace(51.479737,-3.1812,212.55,-14.74,0);
	fL['milleniumcentre'] = new FamousPlace(51.464771,-3.164707,82.55,-7.3,0);
	//Scotland
	fL['edinburghcastle'] = new FamousPlace(55.947538,-3.203262,46.05,-16.88,1);
	fL['peoplespalace'] = new FamousPlace(55.851317,-4.236079,276.07,-7.77,1);
	fL['glasgowcathedral'] = new FamousPlace(55.862731,-4.236752,77.01,-2.77,1);
	//Europe
	fL['eiffeltower'] = new FamousPlace(48.855906,2.298203,313.8,-15,0); 
	fL['arcdetriomphe'] = new FamousPlace(48.873728,2.294127,86.07,-17.9); 
	fL['colisseum'] = new FamousPlace(41.889172,12.492164,13.59,-5.83); 
	fL['plazadecibeles'] = new FamousPlace(40.419478,-3.693174,139.4,-7.34); 
	fL['goldengatebridge'] = new FamousPlace(37.8289,-122.485847,137.46,0.89,1);
	fL['sydneyoperahouse'] = new FamousPlace(-33.858898,151.213419,36.78,-12.21,2);
	fL['empirestate'] = new FamousPlace(40.745906,-73.986389,12.52,-19.4,0);
	

//===== Constructor =====
function init() {
	if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1 && navigator.appVersion.indexOf("Win") > -1) {
			$('#app').html("<img src='design/chrome_fail.png' style='float:left;margin:10px' /><h2>Awfully sorry</h2><p>Currently, Shelter Housebling doesn't work on Google Chrome for Windows. Despite our best efforts we can't seem to get Housebling playing nice with Google Street View. We appreciate the irony. If you still want to use Housebling despite our epic fail, please use another browser such as Firefox or, at a push, Internet Explorer.</p>");
	} else {
		if (google.maps.BrowserIsCompatible()) {
			//Init Google Maps
			var greatBritain = new google.maps.LatLng(54.744492,-4.470312);
			map = new google.maps.Map2(document.getElementById("map"));
			google.maps.Event.addListener(map,"load",function() { mapReady = true }); //Sets map to true on load complete
			map.setCenter(greatBritain, 5); //Zoom level 5
			map.setMapType(G_SATELLITE_MAP);
			postcodeSearch = new google.search.LocalSearch();
			
			//Cache jQuery objects
			$dialogBox = $('#dialog_box');
			$dialogHolder = $('#dialog_holder');
			$dialogForm = $('#dialog_form'); //Container
			$postcodeForm = $('#postcode_search'); //Form
			$postcodeField = $('#postcode_field'); //Text field
			$dC = $('#dialog_container');
			$map = $('#map');
			$svQ = $('#streetview');
			
			//Create dialog AJAX
			$.ajaxSetup({
				url:'dialog.php',
				type:'GET',
				dataType:'html',
				success: loadDialogComplete,
				cache:false
			})
			
			/*if(so_flashvars.view=="none") { //If in create mode
				showDialog();
			}  else {
				loadDialog("loading","false");
			} */
			
			//Cache final jQuery objects
			$controlsWin = $('#controls');
			$infoText = $('#controls p');
			$streetview = document.getElementById("streetview");
			
			//Add live events
			$('a.fl_link').live("click",showFamousLandmark);
			$('a.famouslandmark').live("click",showLandmarks);
			$('.search_field').live('click',function() {
				if($(this).val()=='Postcode') { $(this).val('').css('color','#000');}
			});	
		} else {
			loadDialog("notcompatible","false");
		}
	}
}



//===== Methods =====


//Dialog handlers
function loadDialog(dialog,form) { 
	$.ajax({ data:{ message:dialog, form:form } });
}
function loadDialogComplete(data,status) {
	$dialogBox.html(data);
	showDialog();
	sendBothBack();	
}

function hideDialogOverlay() { $dialogHolder.fadeOut("Med"); }
function removeDialog(func) {
	$dialogHolder.animate({ width: "250px" }, 500, "linear", func).fadeIn();
	$dialogBox.fadeOut("Med");
}
function showDialog() {
	$dialogHolder.fadeIn().animate({ width: "950px" }, 500, "linear");
	$dialogBox.fadeIn("Med");
}

function showLandmarks() { 
	showControls();
	removeDialog(function() {
		changeInfo("Choose a famous location to decorate");
		$dialogBox.removeClass().addClass('fp_container');
		loadDialog("famousplaces", "false");
	});
	return false;
}

//Info and controls
function showControls(controlSet) { 
	$controlsWin.slideDown();
	$controlsWin.children('div').hide();
	if(controlSet!=null) { controlSet.slideDown(); }
	if (controlsInit==false) {
		controlsInit=true;
		initControls();
	}
}
function initControls() {
	$('#snapshot').click(lockStreetview).hover(function() {
		changeInfo("Take a nighttime photo of this scene");
		return false; });
	$('#mapview').click(function() {
		streetview.remove();
		showControls($('#c_mv'));
		bringMapFront();
		changeInfo("Click on an blue area near your chosen location to view in Streetview");
		return false;
	}).hover(function() { changeInfo("Choose another Streetview from your area"); });
	$('.postcodesearch').click(function() {
		callToActionscript("uninit_tools");
		streetview.remove();
		showControls(null);
		loadDialog("chooseanother","true");
		return false;
	}).hover(function() { changeInfo("Search for a new postcode"); });
	$('#adjustcam').click(unlockStreetview).hover(function() { changeInfo("Warning: This will remove all snow and decorations"); });
	$('#create').click(function() {
		bringStreetviewFront();
		showControls();
		callToActionscript("uninit_tools");
		loadDialog("welcome","true");
		return false;
	}).hover(function() { changeInfo("Create your own Housebling and share it with friends!"); });;
	$('#saveshare').click(saveScene).hover(function() { changeInfo("Save your Housebling and share it with friends!"); });
	$('#continue').click(function() { 
		$dialogBox.removeClass('share_box');
		showControls($('#c_hb'));
		removeDialog();
		hideDialogOverlay();
		callToActionscript("continue");
		return false;
	}).hover(function() { changeInfo("Not finished? Continue decorating your scene"); });

}
function changeInfo(message) { 
	if(message!=$infoText.html()){
		$infoText.fadeOut(100,function() { $(this).html(message).fadeIn(100); } );
	}
}

function shake(element) { element.animate({'left':'4px'},50).animate({'left':'-4px'},50).animate({'left':'4px'},50).animate({'left':'0px'},25);	}

//Map manipulation
function bringMapFront() { 
	$map.css('z-index','22');
	$svQ.css({'display':'block','z-index':'21'});
}
function bringStreetviewFront() {
	$map.css('z-index','21');
	$svQ.css({'display':'block','z-index':'22'});
} 
function sendBothBack() { $map.css('z-index','0'); $svQ.css('z-index','1'); } 


//Map functions
function postcodeLookup() {
	postcodeSearch.setSearchCompleteCallback(null, function() {
		if(postcodeSearch.results[0]) { //Top result
			var point = new google.maps.LatLng(postcodeSearch.results[0].lat,postcodeSearch.results[0].lng);
			pcLookupSuccess(point);
		} else { //If nothing found
			loadDialog("postcodenotfound","true");
		}
	});
	
	postcodeSearch.execute(currentPostcode);
	return false;
}

function pcLookupSuccess(point,pov) {
	//Set map type
	map.setCenter(point,18);
	map.setMapType(G_HYBRID_MAP); 
	
	//Add Controls
	map.addControl(new google.maps.LargeMapControl());
	map.addControl(new google.maps.MenuMapTypeControl());
	
	//Add Marker
	var marker = new google.maps.Marker(point);
	map.addOverlay(marker);
	
	//Add Streetview blue overlay
	svOverlay = new google.maps.StreetviewOverlay(); 
	map.addOverlay(svOverlay); 
	streetview = new google.maps.StreetviewPanorama($streetview); //Create SV object
	streetviewSearch = new google.maps.StreetviewClient();
	
	streetviewSearch.getNearestPanoramaLatLng(point,initStreetview); //Load
	
	//Add map event
	google.maps.Event.addListener(map,"click",function(overlay,latlng) {	
		streetviewSearch.getNearestPanoramaLatLng(latlng,initStreetview);
	});
}

function initStreetview(latlng) {
	if(latlng==null) {//Fail
		loadDialog("nostreetview","true");
	} else { //Success
		currentLocation = latlng;
		streetview.setLocationAndPOV(currentLocation,currentPOV);
		addLatLngChange();
		bringStreetviewFront();
		removeDialog();
		changeInfo("Use Streetview to choose a scene to decorate!");
		showControls($('#c_sv'));
	}
} 

function addLatLngChange() {
	google.maps.Event.addListener(streetview,"initialized",function(location) {	
		currentLocation=location.latlng;
	});
}

function showFamousLandmark() {
	var l = $(this).attr("name");
	var thisLocation = new google.maps.LatLng(fL[l].Lat,fL[l].Lng);
	currentPOV = { yaw:fL[l].Yaw,pitch:fL[l].Pitch,zoom:fL[l].Zoom };
	pcLookupSuccess(thisLocation,currentPOV);
	return false;
}


//Actionscript communication
function isReady() { return mapReady; } //Tells AS3 if map is ready for communication

function thisMovie(movieName) { //Depending on browser returns correct .swf reference
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function callToActionscript(value) { thisMovie("houseblinger").sendToActionscript(value); }

function rN(n, d) { //Round n(umber) to d(ecimal place)
	var r = Math.round(n*Math.pow(10,d))/Math.pow(10,d);
	return r;
}

function saveScene() {
	var sv_lat = String(currentLocation.lat());
	var sv_lng = String(currentLocation.lng());
	var sv_yaw = String(rN(streetview.getPOV().yaw,2));
	var sv_pitch = String(rN(streetview.getPOV().pitch,2));
	var sv_zoom = String(rN(streetview.getPOV().zoom,2));
	thisMovie("houseblinger").sendToActionscript("save",sv_lat,sv_lng,sv_yaw,sv_pitch,sv_zoom);
	return false;
}

function saveComplete(id) { 
	showControls($('#c_save'));
	changeInfo("Share your decorate scene with your friends and donate to Shelter");
	currentID = id;
	//$dialogBox.html("");
	$.ajax({url:'dialog.php',
			type:'GET',
			dataType:'html',
			success: shareDialogComplete,
			data:{ message:"saveshare", form:"false" }
	});
}

function emailDialogComplete(data,status) {
	removeDialog(function() {
		$dialogBox.html(data).removeClass().addClass('email_box');
		showDialog();
		showControls();	
		$('#email_form textarea').html("Hello,\n \nI just decorated my house on Google Streetview with Christmas lights using Shelter Housebling. It’s a great new website that lets you bring a bit of bling to your office or street without a scary electricity bill, while showing your support for Shelter, the housing and homelessness charity.\n\nTake a look at mine to see how it works: http://www.housebling.org.uk/?view=" + currentID + "\n\nMerry Christmas");
		$('#destination_address').focus(function() { 
			if ($(this).val()=='Seperate addresses with a comma') { $(this).removeClass('not_selected').val('') }
		});
		$('#email_form').bind("submit", function() {
			if($('#email_form input').val() == "") {
				$(this).css("color","#FF0000");
				shake($('#sendemail'));
			} else {
				$.ajax({url:'email.php',
					type:'POST',
					dataType:'html',
					success: emailComplete,
					data:{ sender_name:$('#sender_name').val(), sender_address:$('#sender_address').val(), destination_address:$('#destination_address').val(), your_message:$('#your_message').val() }
				});	
			}
			return false;
		});
		$('#cancelemail').click(function() { removeDialog(saveScene); return false;} );
	});	
}

function emailComplete(data) {
	if(data=="Success") {
		removeDialog(saveScene);
	} else {
		shake($('#sendemail'));
	}
}

function shareDialogComplete(data,status) {
	$dialogBox.html(data).removeClass().addClass('share_box');
	//Share
	var shareURL = "http%3A%2F%2Fwww.housebling.org.uk%2F%3Fview%3D" + currentID;
	//$('#button_facebook').attr("href","http://www.facebook.com/sharer.php?u=" + shareURL + "");
	$('#button_facebook').click(function() {
		newwindow=window.open("http://www.facebook.com/sharer.php?u=" + shareURL + "&t=My%20house%20on%20Shelter%20Housebling",'fbshare','height=300,width=600');
		if (window.focus) { newwindow.focus() }
		return false;
	});
	$('#button_twitter').attr("href","http://twitter.com/?status=I just decorated my house for Christmas on Streetview with Shelter %23Housebling – take a look: " + shareURL);
	$('#button_email').click(function() {
		$.ajax({url:'dialog.php',
				type:'GET',
				dataType:'html',
				success: emailDialogComplete,
				data:{ message:"email", form:"false" }
		});
		return false;						  
	});
	//Donate
	var $custom_field = $('#amount_custom');
	var $custom_radio = $('#amount_c');
	$custom_field.bind('click',function() { $custom_radio.attr('checked','checked'); });
	$('#donate_panel').bind('submit',function() {
		if($custom_field.val()!="") { $custom_radio.val($custom_field.val()); }
	});
	$('#share_field').val("http://www.housebling.org.uk/?view=" + currentID);
	showDialog();
	sendBothBack();
}

function loadScene() { callToActionscript("load"); return false; }
function loadComplete(sv_lat,sv_lng,sv_yaw,sv_pitch,sv_zoom) {
	var thisLocation = new google.maps.LatLng(sv_lat,sv_lng);
	currentPOV = { yaw:parseFloat(sv_yaw),pitch:parseFloat(sv_pitch),zoom:parseFloat(sv_zoom) };
	streetview = new google.maps.StreetviewPanorama($streetview);
	streetview.setLocationAndPOV(thisLocation,currentPOV);
	$svQ.show();
	changeInfo("You are currently viewing a friend's Housebling");
	showControls($('#c_lsv'));
	sendBothBack();
	removeDialog();
	return false;
}

function lockStreetview() {
	sendBothBack();
	callToActionscript("init_tools");
	hideDialogOverlay();
	showControls($('#c_hb'));
	changeInfo("Use the left menu to add decorations and snow");
	return false;
}

function unlockStreetview() {
	bringStreetviewFront();
	showControls($('#c_sv'));
	callToActionscript("uninit_tools");
	$dialogHolder.fadeIn();
	return false;
}

google.setOnLoadCallback(init);