



rxmaps = new rxnetwork({language:'fr'});





function initRC()
{    
    rxmaps.load();     
}

function initMap()
{        
    rxmaps.mapsLoad();    
}





$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};


function rxnetwork(settings) {
    
   this.mapelementid = 'map';
   this.map = null;
   this.gdir = null;
   
   this.isDragging = 0;
    
   this.language = settings.language;
         
   this.mapMode = null;
   
   this.avoidHighWays = false;
   
   this.baseIMGURL = "http://maps.google.com/intl/en_ALL/mapfiles/marker_green";
   
   this.centerSyctomGeoXML = null;
   this.desitesGeoXML = null;
   
   this.metworkGeoXML = null;
   
   this.geocoder = null;
   
   this.networkOn = true;
   
   this.networkOverlayAdded = false;
   
   this.flashFixed = false;
   
   this.currentPanoLocation = null;
   
   //What mode we are street view o map view ?
   this.mapMode = true;
   
   // Default map type
   this.maptype = 'm';
   
   this.printMode = false;
   
   // Default panorama values
   this.defaultPanYaw = null;
   this.defaultPanPitch = null;
   this.defaultPanZoom = null;
   
   this.defaultPanLat = null;
   this.defaultPanLng = null;
   
   //Default values
   this.defaultLat = 48.861101;
   this.defaultLng = 2.345581;
   this.defaultZoom = 12;
     
   
   this.markerMapsIcons = {
        0:"A.png",
        1:"B.png",
        2:"C.png",
        3:"D.png",
        4:"E.png",
        5:"F.png",
        6:"G.png",
        7:"H.png",
        8:"I.png",
        9:"J.png",
        10:"K.png",
        11:"L.png",
        12:"M.png",
        13:"N.png",
        14:"O.png",
        15:"P.png",
        16:"Q.png",
        17:"R.png",
        18:"S.png",
        19:"T.png",
        20:"U.png",
        21:"V.png",
        22:"W.png",
        23:"X.png",
        24:"Y.png",
        25:"Z.png"   
   };
   
   //Street view person icon
   this.streetViewMarker = null;
   
   this.searchResultMarker = null;
   
   //Street overlay, shows where i can point it.
   this.streetViewOverlay = null;
      
   //Pano view object
   this.panoView = null;
   
   // Street viw client, used while draging pointer to change it image.GStreetviewClient
   this.gstreetviewclient = null; 
   
   // allow street view, during dragin we change this pointer
   this.streetViewEnabled = true;
   
   // Last marker drag position
   this.lastDragMarkerPosition = null;
   
   this.isInDragMode = false;
   
   this.fmode = false;
   
   this.setIsInDragMode = function(value)
   {
        this.isInDragMode = value;
   }
   
   this.setPrintMode = function()
   {
       this.printMode = true;
   }
   
   this.load = function (){      
          //google.load("maps", "2.x", {"callback" : initMap, "language" : "fr"});
    }; 

    // If previous marker position match current, we can check it's pano data. More optimised way
    this.previousDragPosition = null;
      
    this.onResize = function ()
    {
        if (this.printMode == false)
        {
             //$("#map").css({height:($(window).scrollTop()+$(window).height()-138)+"px"}); 
             //$("#street-content").css({height:($(window).scrollTop()+$(window).height()-138)+"px"});         
            if (this.map != null) { this.map.checkResize(); }
            if (this.panoView != null){this.panoView.checkResize()}     
              
        }
    };
    
    
    
   this.mapsLoad  = function ()  {
      
       //       
        if (GBrowserIsCompatible()) {
                                               
            if (this.printMode == false)
            {
                //$("#map").css({height:($(window).scrollTop()+$(window).height()-138)+"px"});
            }                      
                
                this.map = new google.maps.Map2(document.getElementById('map')); 
                this.map.enableContinuousZoom();
        		this.map.enableDoubleClickZoom();
        		this.map.enableScrollWheelZoom();    
                    
        		if (this.printMode == false)
                {
        		  this.map.setUIToDefault();
                }      
                       		
                if (this.printMode == false)
                {
                	//this.map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: false}));
                }
                
        		var d = new Date();
        		
        	    this.metworkGeoXML = new GGeoXml("http://"+WWW_HOST+"/worksalert_ajax/workskml/"+d.getDate()+d.getHours());  
        	           	    
        	        	 
                this.centerSyctomGeoXML = new GGeoXml("http://"+WWW_HOST+"/extension/rxnetwork/google/network.kml");
                //this.desitesGeoXML = new GGeoXml("http://"+WWW_HOST+WWW_DIR+"/network/kmldesites/"+d.getDate()+d.getHours());                
                
                this.map.addOverlay(this.metworkGeoXML);
                
        	    if (this.networkOn == true)
        	    {      
            	    this.map.addOverlay(this.centerSyctomGeoXML);
            	    //this.map.addOverlay(this.desitesGeoXML);
            	                	    
            	    this.networkOverlayAdded = true;
        	    } else {
        	        $('#hideNetworkID').attr('checked','checked');
        	    }

        	                
                if (window.attachEvent) {
                  window.attachEvent("onresize",
                    function() {this.rxmaps.onResize()});
                } else { 
                  window.addEventListener("resize",
                    function() {this.rxmaps.onResize()},
                    false);
                }
  
                this.map.setCenter(new GLatLng(this.defaultLat, this.defaultLng),this.defaultZoom);                
                this.streetViewOverlay = new GStreetviewOverlay();	
                	      	
			   			    			    
                var icon = new GIcon();           
			    var imageUrl = "http://"+WWW_HOST+"/extension/rxnetwork/design/standard/images/man_arrow.png";
                icon.image = imageUrl;
                icon.iconSize = new GSize(49,52);
                icon.iconAnchor =  new GPoint(25,36);
                icon.infoWindowAnchor = new GPoint(25,6);      
                
                
                 // Street viw client, used while draging pointer to change it image.GStreetviewClient
                this.gstreetviewclient = new GStreetviewClient();
                                
                var latlang = this.map.fromContainerPixelToLatLng(new GPoint(37,320)); 
                
                this.streetViewMarker = new GMarker(latlang, {"icon":icon, "draggable":true});
                
                this.searchResultMarker = new GMarker(latlang);
                
                
                 GEvent.addListener(this.map,'moveend',function(){
                     rxmaps.updateStreetViewMaker();
                 });
                 
                 GEvent.addListener(this.map,'move',function(){
                     rxmaps.updateStreetViewMaker();
                 });
                
                 
                 GEvent.addListener(this.searchResultMarker, "click", function()
                    {   
                        rxmaps.hideResultMarker(); 
                    }
                );
                
		        GEvent.addListener(this.streetViewMarker, "dragstart", function()
                    {   
                        rxmaps.setStreetViewDisabled(); 
                        rxmaps.setIsInDragMode(true);
                        //rxmaps.addNetworkOverlay();
                        //rxmaps.exitStreetView();
                    }
                );
                
                GEvent.addListener(this.streetViewMarker, "drag", function drag(){  rxmaps.dragMarker(this); });
                                                	
                GEvent.addListener(this.streetViewMarker, "dragend", function(overlay,latlang)
                   {            
                        rxmaps.setIsInDragMode(false);                       
                        //rxmaps.removeNetworkOverlay();                        
//			            rxmaps.dragEndStreetView(this);
			            rxmaps.openWindow();
                   }
                );
                
                
                if (this.printMode == false)
                {      
                    this.map.addOverlay(this.searchResultMarker);
                    this.searchResultMarker.hide();
                    
                    //Adding the street view to the page. If you don't want street view just comment the following line.
            		this.map.addOverlay(this.streetViewMarker);
                }		       
        		
                this.avoidHighWays = false;                
                                
                if (this.maptype == 'h')
                {
                    this.map.setMapType(G_SATELLITE_MAP);              
                }
                
                if (this.maptype == 'p')
                {        
                    this.map.setMapType(G_PHYSICAL_MAP);              
                }  
                
             
                if (this.mapMode == false) 
                {
                    this.openWindowPermanent();
                }
        
                          
              }
            };

    this.toggleOverlays = function(elm)
    {        
        if (elm.is(':checked'))
        {      
            this.showNetwork();
            this.networkOn = true;                        
        } else {    
            this.hideNetwork();
            this.networkOn = false;          
        }
    }   

    this.setFullScreenMode = function(isfullscren)
    {
        this.fmode = isfullscren;
    }
    
    this.hideResultMarker = function()
    {
        this.searchResultMarker.hide();
    }
    
    this.printMap = function()
    {
        window.open('http://'+WWW_HOST+WWW_DIR+'/layout/set/print/network/print/?'+this.getMapPosition(),'printwindow',"menubar=1,resizable=1,width=768,height=720"); 
    }
    
    this.setDefaultMapType = function(mt)
    {
        this.maptype = mt;
    }
    
    this.hideNetwork = function()
    {
  
//        this.metworkGeoXML.hide();
        this.centerSyctomGeoXML.hide();
        //this.desitesGeoXML.hide();
    }
    
    this.showNetwork = function()
    {
        if (this.networkOverlayAdded == false)
        { 
//            this.map.addOverlay(this.metworkGeoXML);
            this.map.addOverlay(this.centerSyctomGeoXML);
            //this.map.addOverlay(this.desitesGeoXML);
            this.networkOverlayAdded = true;
        }
        
//        this.metworkGeoXML.show();
        this.centerSyctomGeoXML.show();
        //this.desitesGeoXML.show();
        
       
        
    }
    
    //Default value setters    
    this.setDefaultNetwork = function(ison)
    {
        this.networkOn = ison;
    }
    
    this.setDefaultZoom = function(zoom)
    {
        this.defaultZoom = zoom;
    }
      
    this.setDefaultLat = function(lat)
    {
        this.defaultLat = lat;
    }  
    
    this.setDefaultLng = function(lng)
    {
        this.defaultLng = lng;
    }
     
    //Panorama views
    this.setDefaultPanYaw = function(Yaw)
    {        
        this.defaultPanYaw = Yaw;
    } 
    
    this.setDefaultPanPitch = function(Pitch)
    {        
        this.defaultPanPitch = Pitch;
    } 
    
    this.setDefaultPanZoom = function(Zoom)
    {        
        this.defaultPanZoom = Zoom;
    }
    
    this.setDefaultPanLat = function(Lat)
    {        
        this.defaultPanLat = Lat;
    }
    
    this.setDefaultPanLng = function(Lng)
    {        
        this.defaultPanLng = Lng;
    }

     
    this.dragMarker = function(marker)
    {     
        if (this.isDragging == 0) 
        {           
            this.isDragging = 1;
            this.gstreetviewclient.getNearestPanorama(marker.getLatLng(),function(panodata){ rxmaps.updateDragMarkerIcon(panodata) });
            this.lastDragMarkerPosition = null;
            
        } else {
            // To catch last draggend endpoint and synchronize it.
            this.lastDragMarkerPosition = marker;
            setTimeout("rxmaps.updateLasDragMarkerPosition()",1000);
        }
    }
    
    
    this.setStreetViewDisabled = function()
    {
        this.streetViewEnabled = false;
        this.streetViewMarker.setImage("http://"+WWW_HOST+"/extension/rxnetwork/design/standard/images/man_arrow-0_in.png");
    }
    
    this.setisDragging = function(value)
    {
        this.isDragging = value;
    } 
    
    
    this.doSearch = function()
    {
       if ($('#IDSearchText').val() != '')
       {
           if (this.geocoder == null)
           {
               this.geocoder = new GClientGeocoder();
           }

           $('#status-search').html('Searching...');
                   
           this.geocoder.getLatLng(
           $('#IDSearchText').val(),
           function(point) {
              if (!point) {
                alert($('#IDSearchText').val() + " not found");
              } else {                  
                   rxmaps.showSearchResult(point); 
              }
              
              $('#status-search').html('Pour rechercher une adresse, utilisez la forme: code postal, ville, numero et nom de la rue');
           }
          );  
       }
       
       return false;
    }
     
    this.showSearchResult = function(point)
    {
        if (this.mapMode == true){
            this.searchResultMarker.show();
            this.searchResultMarker.setLatLng(point);
            this.map.setCenter(point, 14); 
        }
        else
            this.panoView.setLocationAndPOV(point);
    }
      
    
    this.updateLasDragMarkerPosition = function()
    {
        if (this.isInDragMode == true && this.isDragging == 0 && this.lastDragMarkerPosition != null)
        {                      
            this.dragMarker(this.lastDragMarkerPosition);
        }
    }
   
    this.updateDragMarkerIcon = function(panodata)
    {
        if (panodata.code != 200) {
                    
            if (this.streetViewEnabled == true)
            {
                this.currentPanoLocation=false;            
                this.streetViewEnabled = false;
                this.streetViewMarker.setImage("http://"+WWW_HOST+"/extension/rxnetwork/design/standard/images/man_arrow-0_in.png");
            }
            
        } else {
            if (this.streetViewEnabled == false)
            {
                this.currentPanoLocation=panodata.location;
                this.streetViewEnabled = true;
                this.streetViewMarker.setImage("http://"+WWW_HOST+"/extension/rxnetwork/design/standard/images/man_arrow.png");
            }
        }
        
        this.isDragging = 0;
    }
    
        
    this.openWindow = function()
	{   
	    //GStreetviewPanorama object holds an instance of the Flash Street View in Panorama viewer	    
	    if (this.streetViewEnabled == true)	
	    {	               
	        
            $('#map').hide();
                      
	        $('#street').show(); 
	        $('#close_street').show(); 
	        
	        //$('#street').css({'width': '10px','height': '10px'});
	        this.onResize(); 
	         
	        var panoOpts = {
              features: {
                streetView: true,
                userPhotos: false
              }
            };
	        	         	              
	        this.panoView = new GStreetviewPanorama(document.getElementById("street-content"),panoOpts);		
	        
	        
	         GEvent.addListener(this.panoView, "zoomchanged", function(number)
                    {   
                       rxmaps.loadedFlash();
                    }
                );
                
             GEvent.addListener(this.panoView, "initialized", function(location)
             {   
                rxmaps.panoLocationUpdate(location);
             }
             );
               	        
	        
    		var latlang = this.streetViewMarker.getLatLng();
    		this.panoView.setLocationAndPOV(latlang);    		
    		this.mapMode = false;  
    		    	
    			    		
    		this.gstreetviewclient.getNearestPanorama(latlang,function(panodata){    		    
    		    if (panodata.code == 200)
    		      rxmaps.panoLocationUpdate(panodata.location);    		
    		});
    		
    		
    		
	    } else {
	         this.updateStreetViewMaker();
	         
	    }
	}
	
	
	this.openWindowPermanent = function()
	{   
	    //GStreetviewPanorama object holds an instance of the Flash Street View in Panorama viewer	    
	   	               
	        
            $('#map').hide();                      
	        $('#street').show(); 
	        $('#close_street').show(); 
	        $('#street').css({'width': '10px','height': '10px'});
	        this.onResize();  

	         var panoOpts = {
              features: {
                streetView: true,
                userPhotos: false
              }
            };
                    
	        this.panoView = new GStreetviewPanorama(document.getElementById("street-content"),panoOpts);		
	        	        
	         GEvent.addListener(this.panoView, "zoomchanged", function(number)
                    {   
                       rxmaps.loadedFlash();
                    }
                );
                
             GEvent.addListener(this.panoView, "initialized", function(location)
             {   
                rxmaps.panoLocationUpdate(location);
             }
             );

            var pov = { yaw:this.defaultPanYaw, pitch: this.defaultPanPitch, zoom:this.defaultPanZoom }; 
    		this.panoView.setLocationAndPOV(new GLatLng(this.defaultPanLat,this.defaultPanLng),pov);    		
    		this.mapMode = false;  
    		
	}

	this.panoLocationUpdate = function(location)
	{
	    this.currentPanoLocation = location;
	}
	
	this.clear = function(a)
	{ 
	    
	    for(var i=0; i < a.length; i++)  
        {  
            a[i].outerHTML=a[i].outerHTML;  
        }   
	}

	
	this.loadedFlash = function()
	{
	    if (this.flashFixed == false)
	    {	           
	          	   //setTimeout("rxmaps.fixFlashBorder()", 5000);
	          	    
	             this.flashFixed = true;
	             $('#panoflash1').attr("wmode","transparent");
	             $('#panoflash2').attr("wmode","transparent");
	             $('#panoflash3').attr("wmode","transparent");	             
	             $("#panoflash1").prepend('<param name="wmode" value="transparent" />');
	             $("#panoflash2").prepend('<param name="wmode" value="transparent" />');
	             $("#panoflash3").prepend('<param name="wmode" value="transparent" />');
	             if (this.fmode == false)	             
	               $('#street').css({'width': '100%','height': '341px'});	    
	             else
	               $('#street').css({'width': '100%','height': '100%'});
	               	 	                       
	             this.onResize();	 
	                           
	            
	             
                
	    }
	}
	
	this.fixFlashBorder = function()
	{
	    this.clear(document.getElementsByTagName("object"));  
        this.clear(document.getElementsByTagName("embed")); 
	}
	
	this.showMap = function()
	{
	    this.mapMode = true;  
	    
	    if (this.panoView != null) this.panoView.remove();
	    
	    $('#street').hide();
	    $('#close_street').hide(); 
	    $('#map').show();
	    
	    
	    this.onResize();
	}
	
	this.updateStreetViewMaker = function()
	{
	    var latlang = this.map.fromContainerPixelToLatLng(new GPoint(37,320));
	    this.streetViewMarker.setLatLng(latlang);
	    this.streetViewMarker.setImage("http://"+WWW_HOST+"/extension/rxnetwork/design/standard/images/man_arrow.png");
	}
	
	this.exitStreetView = function()
	{
	    if (this.panoView != null) this.panoView.remove();
	}
	
    this.removeNetworkOverlay = function()
    {
        this.map.removeOverlay(this.streetViewOverlay);
    }
                
    this.addNetworkOverlay = function()
    {
        this.map.addOverlay(this.streetViewOverlay);
    }        
            
               
    this.handleErrors = function () {
              
    var message = "An unknown error occurred.";

    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        message = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        message = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        message = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        message = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        message = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;

    alert("<strong>Message:</strong>" + message);
    };
    
    this.getMapPosition = function()
    {
        var options = "";
        
        
        if (this.mapMode == true)
        {
            var tmp = this.map.getCenter();
            
            options = "&z="+this.map.getZoom();              
            options = options + "&ll="+tmp.lat()+","+tmp.lng();
            
            if (this.networkOn == true)
                options = options + "&nw=true";
            else
                options = options + "&nw=false";
           
            tmp = this.map.getCurrentMapType();
           
            options = options + "&mt="+tmp.getUrlArg();  
            options = options + "&mode=map";
            
            return options;
            
        } else {
            
           var tmp = this.panoView.getPOV();                 
           options = "&panoid="+this.currentPanoLocation.panoId;
           options = options + "&ll="+this.currentPanoLocation.latlng.lat()+","+this.currentPanoLocation.latlng.lng();           
           options = options + "&pov="+tmp.yaw+","+tmp.pitch+","+tmp.zoom;
           options = options + "&mode=flash";           
           return options;
           
        }         
    }
    
    this.sendLink = function()
    {
        var append = this.getMapPosition();
        
        var data = {
            email:  $('#EmailID').val(),          
            message:  $('#MessageID').val()        
        }
            
         $.postJSON(WWW_DIR+'/network/sendmail/?'+ append,data, function(data){ 
	        // If no error
	        if (data.error == 'false')
	        {	 
                $("#dialog-send").dialog( 'close');
	        } else {
	            $("#WarningSendMail").show();
	            $("#WarningSendMail").html(data.result);
	        }		
    	});
    }
    
    this.abstractDialog = function(element_id,title,url)
	{
	    if ($("#"+element_id).hasClass("ui-dialog-content"))
	    {	    
	        if (this.mapMode == false)
	        {
	             //$('#street').hide();
	             /*$('#panoflash1').attr("wmode","transparent");
	             $('#panoflash2').attr("wmode","transparent");
	             $('#panoflash3').attr("wmode","transparent");	             
	             $("#panoflash1").prepend('<param name="wmode" value="transparent" />');
	             $("#panoflash2").prepend('<param name="wmode" value="transparent" />');
	             $("#panoflash3").prepend('<param name="wmode" value="transparent" />');*/
	        }
	        
	       $("#"+element_id).dialog('open');
	       $(".warning-errors").hide();
	       
	    } else {	
	     
	        if (this.mapMode == false)
	        {
	             //$('#street').hide();	             
	            /* $('#panoflash1').attr("wmode","transparent");
	             $('#panoflash2').attr("wmode","transparent");
	             $('#panoflash3').attr("wmode","transparent");	             
	             $("#panoflash1").prepend('<param name="wmode" value="transparent" />');
	             $("#panoflash2").prepend('<param name="wmode" value="transparent" />');
	             $("#panoflash3").prepend('<param name="wmode" value="transparent" />');*/
	        }
	    
	        
        $("#"+element_id).load(url).dialog({
             title: title,
             modal: true,
             autoOpen: true, 
             width: 500,
             close: function(event, ui) { rxmaps.dialogClose(); }
          });
            
	    }	   
	}
		
	this.dialogClose = function()
	{
	    if (this.mapMode == false)
        {
             $('#street').show();
             $('#close_street').show();
        }
	}
	
    this.changeMapMode = function(elm)
    {
        if (elm.val() == 'Walking')
        {
            this.mapMode = G_TRAVEL_MODE_WALKING;
        } else {
            this.mapMode = G_TRAVEL_MODE_DRIVING;
        }     
       this.updateDirection();
    };
    
    this.changeAvoidHighways = function(elm)
    {
        if (elm.is(':checked'))
        {
           this.avoidHighWays = true;
        }  else {
           this.avoidHighWays = false;
        }  
        this.updateDirection();  
    };
    
    this.setMapMode = function(mode)
    {
       this.mapMode =  mode;
    }; 
    
    this.setAvoidHighways = function(avoid)
    {
       this.avoidHighWays =  avoid;
    };
    
    
    
};
