// Devstrom WebPhone GeoPresence Script
// copyright www.devstrom.com

webphone = new function() {

	 //reference to this
	var self = this;

	
	//private member variables
	var random = Math.round(Math.random()*1000000);
	var elementId = "WebPhone_embedded_"+random;
	var uri = null;
	var center = null;
	var gMarkers = new Array();
	var infoWindows = new Array();
	var myMarker = null;
	
	var infoWindowOptions = { 
		maxWidth: 100
	};
	
	var appletCodebase = 'http://www.devstrom.com/jfxphone.com/nightly/';
	var appletArchives = 'SipApplet.jar';
	var appletResources = 'Resources_A1.jar, lib/tritonus_share-0.3.6.jar, lib/tritonus_gsm-0.3.6.jar'
	var appletDefaultLanguage = '';
	

	
	
	
	
	this.loadApplet = function() {
		if(deployJava != null) {
			var appletAttributes = {
				codebase:appletCodebase,
				code:'com.devstrom.sipwidget.launch.DevstromPhone.class',
				archive:appletArchives + ', ' + appletResources,
				width:'100%', height:'100%',
				mayscript:"true",
				id:elementId,
				boxbgcolor: "transparent",
				draggable: "true",
				java_arguments: "-Djnlp.packEnabled=true"} ; // 
			var appletVersion = '1.5' ;
			var appletParameters = {language:appletDefaultLanguage};
			deployJava.runApplet(appletAttributes, appletParameters, appletVersion);
		} else {
			alert("http://java.com/js/deployJava.js not included");
		}
	}
	
	
	this.setAppletCodebase = function(source) {
		appletCodebase = source;
	}
	
	this.setAppletResources = function(packages) {
		appletResources = packages;
	}
	
	this.setAppletDefaultLanguage = function(language) {
		appletDefaultLanguage = language;
	}
	
	
	
	// CALLBACK onRun
	var onRun = function () {}; // do nothing

	this.setOnRunCallback=function(callbackFunction) {
		onRun=callbackFunction;
	}
	
	this.fireOnRunCallback = function() {
		onRun();
	}
	
	
	// CALLBACK onCallStateChanged
	var onCallStateChanged = function () {}; // do nothing
	
	this.setOnCallStateChangedCallback=function(callbackFunction) {
		onCallStateChanged=callbackFunction;
	}
	
	this.fireOnCallStateChangedCallback = function(callState, uri) {
		console.log("fireOnCallStateChangedCallback: " + callState + " " + uri)
		onCallStateChanged();
	}
	
	//this.onPresenceStateChanged = function () {}; // do nothing
	
	
	
	// returns tue if Google Maps has been loaded, otherwise false
	this.isMapsLoaded = function() {
		if(map != null) {
			//alert(map.isLoaded());
			return map.isLoaded();
		}
		return false;
	}
	
	this.jsRemoveMyLocation = function() {
		if(myMarker != null) {
			myMarker.closeInfoWindow();
			myMarker.bindInfoWindowHtml(null);
			if(map!=null) {
				map.removeOverlay(myMarker);
			}
			myMarker = null;
					
		}
	}
	
	// 
	this.clearMapOverlays = function() {
		gMarkers = new Array();
		infoWindows = new Array();
		myMarker = null;
		uri = null;
		self.jsRemoveMyLocation();
		if(map!=null) {
			map.clearOverlays();
		}
	}
	


	function panTo(lat, lng) {
	
		var point = new GLatLng(parseFloat(lat),parseFloat(lng));
		map.panTo(point);
	}


	this.createTextNode = function(lat, lng, text) {
		var point = new GLatLng(parseFloat(lat),parseFloat(lng));
		map.openInfoWindow(point,document.createTextNode(text));
	}

	this.addMarker = function(lat, lng, title) {
		self.addMarker(lat, lng, title, "", "", "");
	 }

	this.addMarker = function(lat, lng, statetext, title, mood) {
		self.addMarker(lat, lng, statetext, title, mood, "");
	 }
 
	this.addMarker = function(lat, lng, statetext, uri, mood, state) {

		self.removeOverlay(uri);
	
		var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
	
		if (latlng) {
		
			var icon = new GIcon(G_DEFAULT_ICON);
			icon.iconSize = new GSize(32, 32);
			icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
			
			if (state == 'ONLINE')
				icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png";
			if (state == 'BUSY' || state == 'ON_THE_PHONE')
				icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/orange-dot.png";
			
			var options = { 
				uri: uri,
				icon: icon
			};
	
		
			var marker = new GMarker(latlng, options);
			marker.disableDragging();
			gMarkers[uri] = marker;
			map.addOverlay(marker);
		
			geocoder.getLocations(latlng, function(addresses) {
			var infotext;
			var buttons = '<a href="javascript:webphone.call(\''+uri+'\');"><img style="border: medium none;" src="http://www.jfxphone.com/images/phone-16x16.png"/></a>&nbsp;<a href="javascript:webphone.showMessageWindow(\''+uri+'\');"><img style="border: medium none;"  src="http://www.jfxphone.com/images/chat-16x16.png"/></a>';
				  if(addresses.Status.code != 200) {
					 infotext = '<div style="color:black; text-align:left; font-size:12px;"><b>'+uri+'</b> - '+statetext+'<br/>'+mood+'<br/>'+buttons+'</div>';
				  }
				  else {
					address = addresses.Placemark[0];
					var myHtml = address.address;
					infotext = '<div style="color:black; text-align:left; font-size:12px;"><b>'+uri+'</b> - '+statetext+'<br/>'+myHtml+'<br/>'+mood+'<br/>'+buttons+'<br/>';
					
				  }
	
				  infoWindows[uri] = infotext;
				  marker.bindInfoWindowHtml(infotext, infoWindowOptions);
			});
		}
	}

	

	

	
	this.jsSetMyLocationToPoint  = function(title, gLatLng) {
		self.jsSetMyLocation(title, gLatLng.lat(), gLatLng.lng());
	}

	
	this.jsSetMyLocation = function(title, lat, lng) {
		
		uri = title;
		var myIcon = new GIcon(G_DEFAULT_ICON);
		myIcon.image = "http://maps.google.com/mapfiles/ms/micons/man.png";
		myIcon.shadow = "http://maps.google.com/mapfiles/ms/micons/man.shadow.png";
		myIcon.iconSize = new GSize(32, 32);
		myIcon.shadowSize = new GSize(59, 32);
		myIcon.iconAnchor = new GPoint(16, 32);
		myIcon.infoWindowAnchor = new GPoint(16, 1);
	
		
		var options = { 
			title: title,
			icon: myIcon,
			draggable: true,
			zIndexProcess:  function() {return 100000;  }
		};
	
		var pos = new GLatLng(parseFloat(lat), parseFloat(lng));
			if(myMarker != null) {
				map.removeOverlay(myMarker);
			}
			myMarker = new GMarker(pos, options);
			myMarker.enableDragging();
		map.addOverlay(myMarker);
		
		GEvent.addListener(myMarker, "dragend", 
			function() {
			self.publishLocation();
			}
		);
		GEvent.addListener(myMarker, "dragstart", 
			function() {
				map.closeInfoWindow();
			}
		);
	
		self.publishLocation();
		map.panTo(pos);
		map.closeInfoWindow();
	
	}


	this.tryGoogleClientLocation = function() {
		var googleClientLocation = google.loader.ClientLocation;
		if(googleClientLocation != null){
			self.jsSetMyLocation(uri, googleClientLocation.latitude, googleClientLocation.longitude);  
		} else {
			self.jsSetMyLocation(uri, center.lat(), center.lng());  
		}
	}



    this.geoLocationSuccessCallback = function(position) {
		  // By using the 'maximumAge' option above, the position
		  // object is guaranteed to be at most 10 minutes old.
    	self.jsSetMyLocation(uri, position.coords.latitude, position.coords.longitude);
		
    }

    this.geoLocationErrorCallback = function(error) {
    
    	self.tryGoogleClientLocation();
    }

	

	this.jsStartLocationDetection = function(title){
		
		uri = title;
		if (navigator.geolocation) {
			// Request a position. We accept positions whose age is not
			// greater than 10 minutes. If the user agent does not have a
			// fresh enough cached position object, it will automatically
			// acquire a new one.
			navigator.geolocation.getCurrentPosition(self.geoLocationSuccessCallback,
													self.geoLocationErrorCallback,
													 {maximumAge:600000});
		} else {
			self.tryGoogleClientLocation();
		}
	
	}


	this.removeOverlay = function(title) {
		var oldmarker = gMarkers[title];
		if(oldmarker != null){
			oldmarker.closeInfoWindow();
			oldmarker.bindInfoWindowHtml(null);
			map.removeOverlay(oldmarker);
			gMarkers[title] = null;
			infoWindows[title] = null;
		}
	}



	this.markersSet = function(markers) {
	  // note: markers is an array of LocalResult
	  if (markers.length > 1) {
	    // grab the title of the 2nd result object
	    // if it matches starbucks, then alert
	    var title = markers[1].result.titleNoFormatting;
	
	  }
	}

	this.markerHtmlCallback = function(gMarker, htmlInfoText, globalSearchResult) {
		if(self.getWebPhone != null && uri != null) {
			var setMyLocationButton = '<a href="javascript:webphone.jsSetMyLocation(\''+uri+'\', '+gMarker.getLatLng().lat()+', '+gMarker.getLatLng().lng()+');">set as my location</a>'; // <img style="border: medium none;" src="http://www.jfxphone.com/images/phone-16x16.png"/>
			return setMyLocationButton;
		} else {
			return htmlInfoText;
		}
	}

	// Callback function which gets called from Google Maps when the map is ready, is clears the map and local vars
	this.onMapInitialized = function() {
		self.clearMapOverlays();
	}


	this.onMapsLoaded = function() {
		center = new google.maps.LatLng(48.20, 16.35);
			geocoder = new GClientGeocoder();	
	
			var barOptions = {
					onMarkersSetCallback : self.markersSet, // request an "on markers set" callback.
					onGenerateMarkerHtmlCallback : self.markerHtmlCallback,
					//suppressInitialResultSelection : true, // request the the initial search result info window should not be  auto-opened
					style : 'new',
					showOnLoad : true
				};
			
			var gMapOptions = {
				googleBarOptions:barOptions
				};
			
			
			map = new google.maps.Map2(document.getElementById("map_canvas"),gMapOptions);
			
			map.setCenter(center, 4);
			map.enableScrollWheelZoom();
			
			
	
			map.addControl(new google.maps.LargeMapControl());
			map.addControl(new google.maps.MapTypeControl());
			map.enableGoogleBar();
			map.load = self.onMapInitialized;
	
	}


	
	this.getWebPhone = function() {
		return document.getElementById(elementId);
	}
	
	this.showInfoWindow = function(title) {
		var infoWindowText = infoWindows[title];
		var gMarker = gMarkers[title];
		

		if(infoWindowText != null && gMarker != null) {
		
			gMarker.openInfoWindowHtml(infoWindowText, infoWindowOptions);
		}
	}
	
	
	this.publishLocation = function() {
		var app = self.getWebPhone();
		if(app != null) {
			var myPosition = myMarker.getPoint();
			app.setMyLocation(String(myPosition.lat()), String(myPosition.lng()));
			
			geocoder.getLocations(myPosition, function(response) {
				
				var addressText = 'my location';
				  if(response.Status.code == 200) {
						var place = response.Placemark[0];
						
						if ( place && place.address ) {
							addressText = place.address;
							
							//infoWindows[uri] = infotext;
							if ( place.AddressDetails && place.AddressDetails.Country && place.AddressDetails.Country.AdministrativeArea ) {
								if ( place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea ) { 
									//county= place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName; 
									var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; 
									//streetLine = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName; 
									//zip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber; 
									} 
								else if ( place.AddressDetails.Country.AdministrativeArea.Locality ) { 
									var city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName; 
								
								}
								if(city) {
									app.setMyLocationName(city);
								}
							}
						}
						
				  }
				  var infoText = '<div style="color:black; text-align:left; font-size:12px;"><b>'+uri+'</b><br/>'+addressText;
				  var addLocationFavButton = '<a href="javascript:webphone.addLocationFavourite(\''+addressText+'\', \''+myPosition.lat()+'\', \''+myPosition.lng()+'\');">add to location favourites</a>';
				  var htmlText = infoText +'<br/>' + addLocationFavButton;
				  myMarker.bindInfoWindowHtml(htmlText, infoWindowOptions);
				  myMarker.openInfoWindowHtml(htmlText, infoWindowOptions);
					
				});
			
		}
	}
	
	this.addLocationFavourite = function(name, lat, lng) {
		var app = self.getWebPhone();
		if(app != null) {
			app.jsAddLocationFavourite(name, lat, lng);
		}
	}
	
	this.call = function(number) {
		var app = self.getWebPhone();
		if(app != null) {
			app.call(number);
		}
	}
	
	this.showMessageWindow = function(number) {
		var app = self.getWebPhone();
		if(app != null) {
			app.showMessageWindow(number);
		}
	}
	
	this.loadGoogleMaps = function()
	{
		if(google != null) {
			google.load("maps", "2.x", {"callback" : self.onMapsLoaded});
			//google.load("search", "1", {"callback" : onSearchLoaded});
			//google.load("elements", "1", {packages : ["localsearch"]});

			// google.setOnLoadCallback(onLoadCallback);  // Do not use as http://code.google.com/intl/de-DE/apis/ajax/documentation/#GettingStarted
		}
	}
	
	this.loadJava = function(callback) {
		loadJavaScriptFile('http://java.com/js/deployJava.js', callback);
	}
	
	
}


var geocoder = null;
var map = null;

if (window['google'] != undefined && window['google']['loader'] != undefined) {
	//google.loader.writeLoadTag("script", "http://java.com/js/deployJava.js", true);
} 

