// TorchRelay map page related JavaScript
var markers;

// initialized by js code that will be
// injected by code-behind
var centerLat;
var centerLng;
var centerZoomLevel;
var videos = [];
var carousel_itemList;
var infoWindowVideoHeight;
var infoWindowVideoWidth;

function loadMap() {
  if (GBrowserIsCompatible()) {  
    var map = new GMap2(document.getElementById("_map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(centerLat, centerLng), centerZoomLevel);

    // load markers for each video
    // (we have videos injected by code behind)
    // custom marker marker icon
    var markerIcon = new GIcon();
    markerIcon.image = "skins/map/mapicon.png";
    markerIcon.shadow = "skins/map/mapicon-shadow2.png";
    markerIcon.iconSize = new GSize(23, 35);
    markerIcon.shadowSize = new GSize(48, 35);
    markerIcon.iconAnchor = new GPoint(10, 35);
    markerIcon.infoWindowAnchor = new GPoint(13, 4);

    // arrow icon information
    var arrowIcon = new GIcon();
    arrowIcon.iconSize = new GSize(24,24);
    arrowIcon.shadowSize = new GSize(1,1);
    arrowIcon.iconAnchor = new GPoint(12,12);
    arrowIcon.infoWindowAnchor = new GPoint(0,0);

    markers = new Array( videos.length );
    var points = new Array( videos.length );
    for (var i = videos.length-1; i >= 0; i--) {
      var item = videos[i];
      markerIcon.image = "skins/map/mapicon"+item.colour+".png";
      markers[i] = new GMarker(new GLatLng(item.lat, item.lng), { title: item.title, icon:markerIcon });
        //{title: item.title, icon:markerIcon});
      GEvent.addListener(markers[i], "click", makeOpenMarkerInfoWindowFunction(i));      
      map.addOverlay(markers[i]);      
      // add polyline (skip polyline for day 5 ->- day 85)
      if((i > 0) & (i < videos.length-1) & (i != videos.length - 5)) {
        itemNext = videos[i-1];
        points[0] = new GLatLng(item.lat, item.lng);        
        points[1] = new GLatLng(itemNext.lat, itemNext.lng);
        // compute direction
        var dir = bearing(points[0],points[1]);
        // round it to a multiple of 3 and cast out 120s
        var dir = Math.round(dir/3) * 3;
        
        if (item.colour >1) {
            while (dir >= 120) {dir -= 120;}
            //blue line #00B5E0 goes after blue (colour #2) or gray (3) points  (in the past)
            var route = new GPolyline(points, "#00B5E0", 3, 0.8);
            map.addOverlay(route);        
            // use the corresponding triangle marker             
            arrowIcon.image = "skins/map/blue-arrow/dir_"+dir+".png";
            map.addOverlay(new GMarker(route.getBounds().getCenter(), arrowIcon));
        } else {
            // orange #FCB645 goas after red (1) points (in the future)
            var route = new GPolyline(points, "#FCB645", 3, 0.8);
            map.addOverlay(route);
            // use the corresponding triangle marker 
            arrowIcon.image = "skins/map/orange-arrow/dir_"+dir+".png";
            map.addOverlay(new GMarker(route.getBounds().getCenter(), arrowIcon));
        }            
      }
    }    
    

    // open the last marker with video
    if (carousel_itemList.length > 0)
    {
        openMarkerInfoWindow(carousel_itemList[0].marker_index);
    }


  } else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}

function makeOpenMarkerInfoWindowFunction(i) {
    return function() { openMarkerInfoWindow(i); }
}

function highlightCarouselItem(markerIndex) {
    $(".jcarousel-item").removeClass("selected"); 
    for (var i = 0; i < carousel_itemList.length; i++) {
        if (carousel_itemList[i].marker_index == markerIndex) {
            $(".jcarousel-item-"+(i+1)).addClass("selected");              
        }    
    }
}

function openMarkerInfoWindow(markerIndex) {
    markers[markerIndex].openInfoWindowHtml(getMarkerInfoWindow(markerIndex));    
    highlightCarouselItem(markerIndex);
}

function getMarkerInfoWindow(markerIndex) {
    var item = videos[markerIndex];
    var videoHtml = '';
    // if we have video id, append video
    if(item.id) {
        videoHtml = '<br /><object width="'
            + infoWindowVideoWidth
            + '" height="'
            + infoWindowVideoHeight
            + '"><param name="movie" value="http://www.youtube.com/v/'
            + item.id
            + '&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'
            + item.id
            + '&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'
            + infoWindowVideoWidth
            + '" height="'
            + infoWindowVideoHeight
            + '" wmode="transparent"></embed></object>';
    }     

    var textHtml = '<div class="info-window-title">' + item.title + '</div><hr>'
        + '<div class="info-window-description">' + item.description + '</div>';
        
    return '<div class="info-window">' + videoHtml + textHtml + '</div>';
}

function videoBarItemLoadCallback(carousel, state)
{
    for (var i = carousel.first; i <= carousel.last; i++) {     
      
        if (carousel.has(i)) {
            continue;
        }

        if (i > carousel_itemList.length) {
            break;
        }

        carousel.add(i, getVideoBarItemHTML(carousel_itemList[i-1]));
    }
}

function getVideoBarItemHTML(item)
{
    var html = '<img src="http://img.youtube.com/vi/' + item.id + '/hqdefault.jpg"'
         + ' width="170" height="128" alt="' + item.title
         + '" onClick="openMarkerInfoWindow(' + item.marker_index + ');"/>'
         +'<div>' + item.title + '</div>';
    return html;
}

// === Returns the bearing in degrees between two points. ===
// North = 0, East = 90, South = 180, West = 270.
var degreesPerRadian = 180.0 / Math.PI;
function bearing( from, to ) {
    // Convert to radians.
    var lat1 = from.latRadians();
    var lon1 = from.lngRadians();
    var lat2 = to.latRadians();
    var lon2 = to.lngRadians();

    // Compute the angle.
    var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
    if ( angle < 0.0 )
    angle  += Math.PI * 2.0;

    // And convert result to degrees.
    angle = angle * degreesPerRadian;
    angle = angle.toFixed(1);

    return angle;
}

function loadCarouselItemList() {
    var c = 0;
    var item;
    carousel_itemList = new Array();
    
    for (var i = 0; i < videos.length; i++) {    
      item = videos[i];
      
      if(item.id > "") {
        item.marker_index = i;
        carousel_itemList[c++] = item;
      }  
    }      
}

jQuery(document).ready(function() {
    // add points with videos to carouselS
    loadCarouselItemList();    
    // load map
    loadMap();
    // load videobar
    jQuery('#_videobar').jcarousel({
        size: carousel_itemList.length,
        scroll: 2,        
        itemLoadCallback: {onBeforeAnimation: videoBarItemLoadCallback}
    });
    // highlight latest video
    highlightCarouselItem(carousel_itemList[0].marker_index);
});

$(window).unload( function () { GUnload(); } );

