onDomReady(function () {
	// init
	moviemap.initialize();
});

			
var moviemap = {
    theMap:null,
    locationData:null,
    myMode:false,
    isLive:false,
    userTimer:0,
    updateTime: 7000,
    hereMarker:null, 
    
    initialize: function()
    {
        if(GBrowserIsCompatible())
        {
            moviemap.theMap = new GMap2(document.getElementById("movieMapContainer"));
            moviemap.theMap.enableScrollWheelZoom();            
            moviemap.theMap.addControl(new GSmallZoomControl3D());
            moviemap.theMap.addControl(new GMapTypeControl());
            window.onunload = moviemap.Unload;
        }
        moviemap.locAccElement = document.getElementById("locAcc");
        var hereIcon = new GIcon(G_DEFAULT_ICON);
        hereIcon.image = "/images/map/here.gif";
        //hereIcon.iconSize = new GSize(40,30);
        //hereIcon.iconAnchor = new GPoint(15, 25);
        markerOptionsH = { icon:hereIcon };
        moviemap.hereMarker = new GMarker(new GLatLng(37.4419, -122.1419), markerOptionsH); 
        moviemap.previouslastIndexForCurrentRoute = -1; 
       // moviemap.previousLatLng =  new GLatLng(37.4419, -122.1419);     
    },
    
    start: function(locationData,myMode,isLive)
    {
        moviemap.myMode = myMode;
        moviemap.isLive = isLive;
        if(moviemap.locationData)
        {
            moviemap.theMap.clearOverlays(); 
            var elC = document.getElementById("movieMapHeaderCountry");
            elC.innerHTML = "";
            var elNH = document.getElementById("movieMapHeaderNH");
            elNH.innerHTML = "";
            if(moviemap.isRoute == true)
            {
                //also stop timer and restart it in execute
                clearTimeout(moviemap.userTimer); 
                moviemap.isRoute = false;
            }
           var elCC; 
           if(moviemap.myMode)
           {
             elCC = document.getElementById("movieMapFrameCoverMyMode");
           }
           else
           {
             elCC = document.getElementById("movieMapFrameCover");
           }
           elCC.style.display = "none";
            
        } // End of if
        //TODO:://we should clear the previous session
        moviemap.locationData = locationData;
        
        moviemap.execute();
    },
    execute: function()
    {
       if(moviemap.locationData.displayLevel > 0)
       {

            moviemap.Draw();
       }
       else
       {
           moviemap.locAccElement.innerHTML = "Location Accuracy: Hidden";

           //TODO: put a black transparent layer on top of the map.
           moviemap.theMap.setCenter(new GLatLng(37.4419, -122.1419), 1);

           var elCC; 
           if(moviemap.myMode)
           {
             elCC = document.getElementById("movieMapFrameCoverMyMode");
           }
           else
           {
             elCC = document.getElementById("movieMapFrameCover");
           }
           elCC.style.display = "";
       }
    
    
    },
    Draw: function()
    {
       moviemap.theMap.setMapType(G_HYBRID_MAP);
       
       var el = document.getElementById("movieMapHeaderCountry");
       if(moviemap.locationData.locationLabelCountry)
       {
          el.innerHTML = moviemap.locationData.locationLabelCountry;
       }
       else
       {
           el.innerHTML =  "Broadcast Location";
       
       }
       if(moviemap.locationData.locationLabelNH)
       {
           var elNH = document.getElementById("movieMapHeaderNH");
           elNH.innerHTML = moviemap.locationData.locationLabelNH;
       }
       //map center:
       var center;
       
       if(moviemap.locationData.single)
       {
           center = new GLatLng(moviemap.locationData.single.lat,moviemap.locationData.single.lng); 
           moviemap.hereMarker.setLatLng(center);
           moviemap.theMap.addOverlay(moviemap.hereMarker);
       }
       else // its a polygon
       {
           moviemap.isRoute = true;
           moviemap.DrawRoute(); 
       }
       if(moviemap.locationData.displayLevel == 1)
       {
            moviemap.locAccElement.innerHTML = "Location Accuracy: Manually entered by user";
            moviemap.theMap.setCenter(center, 2);
       }
       else // display level is 2
       {
           if(moviemap.isRoute == true)
           {
              moviemap.DrawRoute(); 
           }
           else
           {
              moviemap.locAccElement.innerHTML = "Location Accuracy: Approximation";
              moviemap.theMap.setCenter(center, 16);
           }
       }
    
    },
    DrawRoute: function()
    {
        moviemap.locAccElement.innerHTML = "Location Accuracy: GPS (Route)";
        //get the first point
        moviemap.points = new Array();
        var startIcon = new GIcon(G_DEFAULT_ICON);
        startIcon.iconSize = new GSize(30,20);
        startIcon.iconAnchor = new GPoint(12,1);
        startIcon.image = "/images/map/pointer_start.png";
        markerOptionsS = { icon:startIcon };
        var endIcon = new GIcon(G_DEFAULT_ICON);
        endIcon.image = "/images/map/pointer_end.png";
        endIcon.iconSize = new GSize(30,20);
        endIcon.iconAnchor = new GPoint(12,1);
        markerOptionsE = { icon:endIcon };
        for(var i=0;i < moviemap.locationData.polygon.length;i++)
        {
             var point = new GLatLng(moviemap.locationData.polygon[i].lat,moviemap.locationData.polygon[i].lng); 
             moviemap.points.push(point);
             if(i==0)
             {
                 //add the start icon to the beginning of the route
                 var marker = new GMarker(point, markerOptionsS);       
                //now add the new overlay and pan the map to that point
                 moviemap.theMap.addOverlay(marker);        
             
             }
             else if(i == (moviemap.locationData.polygon.length-1) &&(movie.isLive == false))
             {
                 //add the end icon to the end of the route
                 var marker = new GMarker(point, markerOptionsE);       
                //now add the new overlay and pan the map to that point
                 moviemap.theMap.addOverlay(marker);        
             }
        } // End of for
        moviemap.polyline = new GPolyline(moviemap.points,"#FFFFFF", 5,0.8);
        moviemap.theMap.addOverlay(moviemap.polyline);
        //var color = RGB2HTML(33,153,183);
        //debugger;
        moviemap.polylineInner = new GPolyline(moviemap.points,"#6495ED", 3,1);
        moviemap.theMap.addOverlay(moviemap.polylineInner);
        
        
        moviemap.theMap.setCenter(moviemap.points[0], 15);
         //start the where am i timer
        moviemap.userTimer = setTimeout("moviemap.askwhereami()", moviemap.updateTime);               
        
    },
    askwhereami: function()
    {                         
       //this may happen if a new movie is loaded
       if(!moviemap.locationData.polygon) return;

       var playerts = movie.whereami(); //in seconds
       if(playerts <= moviemap.locationData.polygon[0].ts)
       {
           moviemap.currentLatLng = new GLatLng(moviemap.locationData.polygon[0].lat,moviemap.locationData.polygon[0].lng);  
           //for  draw current route
           moviemap.lastIndexForCurrentRoute =  0; 
       }
      else if(playerts >= moviemap.locationData.polygon[moviemap.locationData.polygon.length-1].ts)
       {
             //alert("last point");  
            moviemap.currentLatLng = new GLatLng(moviemap.locationData.polygon[moviemap.locationData.polygon.length-1].lat,moviemap.locationData.polygon[moviemap.locationData.polygon.length-1].lng); 

            moviemap.lastIndexForCurrentRoute =  moviemap.locationData.polygon.length-1;
 
       } 
       else 
       {
           for(var i=0;i<moviemap.locationData.polygon.length-1;i++)
           {
             moviemap.lastIndexForCurrentRoute =  i; 
               if(playerts <= moviemap.locationData.polygon[i+1].ts)
               { 
                    var point1 = moviemap.locationData.polygon[i];
                    var point2 = moviemap.locationData.polygon[i+1];
                    var  latts = ((playerts - point1.ts)*(point2.lat-point1.lat)/(point2.ts-point1.ts)) ;  
                    var  lonts =  ((playerts - point1.ts)*(point2.lng-point1.lng)/(point2.ts-point1.ts));  
                    var lattsgg = parseFloat(point1.lat + latts);
                    var lonsgg = parseFloat(point1.lng + lonts);
                    //debugger;
                    moviemap.currentLatLng = new GLatLng(lattsgg,lonsgg);
                    break;
               }    
           }
       } // End of else
       
       //add the overlay but remove the previous one if exists
       if(moviemap.previouslastIndexForCurrentRoute !=  moviemap.lastIndexForCurrentRoute)
       {
            if(moviemap.theMap.currentOverlay)  moviemap.theMap.removeOverlay(moviemap.theMap.currentOverlay);
           //create the current overlay
           moviemap.hereMarker.setLatLng(moviemap.currentLatLng);
           moviemap.theMap.currentOverlay = moviemap.hereMarker;       
           //now add the new overlay and pan the map to that point
           moviemap.DrawCurrentRoute();
           moviemap.theMap.addOverlay(moviemap.theMap.currentOverlay);
           
           moviemap.previouslastIndexForCurrentRoute =  moviemap.lastIndexForCurrentRoute;    

           moviemap.theMap.panTo(moviemap.currentLatLng);
       }
       
       
       //when movie is in live, and we reached the last point,poll the server for next points (if available)
       if(movie.isLive && (moviemap.lastIndexForCurrentRoute ==  moviemap.locationData.polygon.length-1 ))
       {
           moviemap.GetLiveData();
       } 
       
       
       moviemap.userTimer = setTimeout("moviemap.askwhereami()", moviemap.updateTime);               
    },
    DrawCurrentRoute: function()
    {
       //remove the previous polyline if exists
       if(moviemap.currentPolyline)
       {
           moviemap.theMap.removeOverlay(moviemap.currentPolyline);
           moviemap.theMap.removeOverlay(moviemap.currentPolylineInner);
           
       }
       
       //now redraw the current polyline
        var pts = new Array();
        for(var i=0;i < moviemap.locationData.polygon.length;i++)
        {
             if(i <=  moviemap.lastIndexForCurrentRoute)
             {
                 var point = new GLatLng(moviemap.locationData.polygon[i].lat,moviemap.locationData.polygon[i].lng); 
                 pts.push(point);
             }
             else
             {
                 //if(i!=0) debugger;
                 break;
             }
        } // End of for
        // add the current point to the current polyline
        if(pts.length < 1) return;
        pts.push(moviemap.currentLatLng);
        moviemap.currentPolyline = new GPolyline(pts,"#FFFF00", 5,0.8);
        moviemap.theMap.addOverlay(moviemap.currentPolyline);
        moviemap.currentPolylineInner = new GPolyline(pts,"#FF0000", 3,1);
        moviemap.theMap.addOverlay(moviemap.currentPolylineInner);
    
    },
    GetLiveData: function()
    {
    
 var updater = new Ajax('/movie/GetWayPoints?movieId='+movie.currentMovieId+"&fromIndex="+moviemap.locationData.polygon.length , {method: 'get', onComplete:function(){
        var root = this.transport.responseXML.documentElement;
        var nodes = root.childNodes;
        for (var i=0;i<nodes.length;i++)   
        {
          if(typeof(nodes[i].tagName) != "undefined") 
          {
              if(nodes[i].tagName == "wp")
              {
                  var tmp = new LL(nodes[i].getAttribute('lat'),nodes[i].getAttribute('lng'),nodes[i].getAttribute('ts')); 
                  //add it to the polygon member

                  moviemap.locationData.polygon.push(tmp); 
                  //add a vertex to the existing polyline
                  var point = new GLatLng(tmp.lat,tmp.lng); 
                  moviemap.polyline.insertVertex(moviemap.locationData.polygon.length-1,point); 
                  moviemap.polylineInner.insertVertex(moviemap.locationData.polygon.length-1,point); 
              } // End of if
          } // End of if
        } // End of for
        }}).request();    
    },
    
    Unload: function()
    {
       GUnload();
    }
}
function RGB2HTML(red, green, blue)
{
    var decColor = red + 256 * green + 65536 * blue;
    return decColor.toString(16);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
