﻿BenefulMap.StreetView = Class.extend({
	init: function(wrapper, canvas, infoWin) {
        this.wrapper = wrapper;
        this.canvas = canvas;
        this.infoWin = infoWin;
        this.errorDiv = canvas + " #error";
        this.point = BenefulMap.Constants.CENTER_LATLNG;
        this.streetView;
        
        this.load();
        this.linkListener();
        this.locationUpdatedListener();
	},
	getWrapper: function() {
	   return this.wrapper;
	},
	getCanvas: function() {
	   return this.canvas;
	},
	getInfoWin: function() {
	   return this.infoWin;
	},
	getErrorDiv: function() {
	   return this.errorDiv;
	},
	getPoint: function() {
	   return this.point;
	},
	setPoint: function(point) {
	   this.point = point;
	},
	getStreetView: function() {
	  return this.streetView;
	},
	setStreetView: function(streetView) {
	   this.streetView = streetView;
	},
	show: function() {
	    $(this.getWrapper()).show();
 	    $(this.getInfoWin() + " .options").hide();
 	    $(this.getInfoWin() + " .info").hide();
	},
	hide: function() {
	    $(this.getErrorDiv()).text("");
	    $(this.getWrapper()).hide();
 	    $(this.getInfoWin() + " .options").show();
 	    $(this.getInfoWin() + " .info").show();
	},
	load: function() {
        panoramaOptions = { latlng: this.getPoint() };
        var myCanvas = $(this.getCanvas()).get(0);

        streetView = new GStreetviewPanorama(myCanvas, panoramaOptions);
        this.setStreetView(streetView);
        
        var self = this;
        GEvent.addListener(this.getStreetView(), "error", function(errorCode) {
            var errorText;
            switch(errorCode) {
        		case 600:
                		errorText = "No Google Street View data for this location was found.";	
            			break;
        		case 603:
            			errorText = "You must have Flash to view Google Street View.";
            			break;
        		default:
            			errorText = "An unknown error with Google Street View occurred.";
                        console.log(errorCode);
        	}
            $(self.getErrorDiv()).text(errorText);
        });
	},
	locationUpdatedListener: function() {
	   var self = this;
	   $(document).bind("streetview.update", function(event, point) {
	       self.updateView(point);
	   });
	},
	updateView: function(point) {
	   console.log("streetview coords updated", point);
	   this.setPoint(point);
	   this.getStreetView().setLocationAndPOV(point);
	   // TODO update streetview to point to new point here
	},
	linkListener: function() {
	   var self = this;
	   $("#launch-street-view").click( function(event) {
	       event.preventDefault();
    	   self.show();
	   });
	   $("#close-street-view").click( function(event) {
	       event.preventDefault();
	       self.hide();
	   });
	   $(document).bind("infowin.close", function() {
	      self.hide();
	   });
	}
});