
//
// attach the mouseover listener to update the map points
//

if (!shape_selected) var shape_selected = -1;
if (!point_selected) var point_selected = -1;

var glob_timeout = 0;  // global timeout for mouseover map.panTo 

function loadShape(shape_id)
{
  var new_points = new Array();
  var new_markers = new Array();
  var ul = $("div.list.stops[shape_id='"+shape_id+"'] ul");
  var li_s = ul.find("li.stop[lat]");

  if (ul.attr('threshold') == undefined)
  {
    ul[0].shape = eval($("a[shape_id='"+shape_id+"']").attr('shape'));
    threshold = 0;
    if (li_s.length > 25)
    {
      c = li_s.length;
      while (c > 15)
      {
        threshold++;
        c = 0;
        li_s.each(function () {
          if ($(this).attr('num_connections') > threshold) c++;
        });
        if (threshold > 5) break;
      }
    }
    ul.attr('threshold', threshold);
    
    var hid = 0;
    var point_id = 0;
    
    if (li_s.length > 15)
    {
      li_s.each(function () {
        if ($(this).attr('num_connections') <= threshold)
        {
          $(this).hide();
          hid ++;
        }
      });
    }
    
    li_s.each(function () {
      $(this).mouseover(function (){
        $(this).addClass('current');
        //clearTimeout(glob_timeout);
        //glob_timeout = setTimeout('map.panTo(new GLatLng(parseFloat('+$(this).attr('lat')+'), parseFloat('+$(this).attr('lng')+')))',400);
        highlightPoint.setLatLng(new GLatLng(parseFloat($(this).attr('lat')), parseFloat($(this).attr('lng'))));
        highlightPoint.show();
      }).mouseout(function (){
        //clearTimeout(glob_timeout);
        $(this).removeClass("current");
        highlightPoint.hide();
      }).click(function (){
        showInfoWindow(this.marker);
        return false;
      });
    });
    if (hid > 0)
    {
      ul.append($('<li class="show_all"><em>'+hid+' stops hidden ... (click to show)</em></li>').css({'font-size':'0.7em',color:'#808080',cursor:'pointer'}).click(function(){
        $(this).siblings().show();
        $(this).hide();
      }));
    }
  }
}

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
        fromIndex = 0;
    } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var i = fromIndex, j = this.length; i < j; i++) {
        if (this[i] === obj)
            return i;
    }
    return -1;
  };
}

function showInfoWindow(marker)
{
  var li = $(marker.parent);
  var a = li.find('a').eq(0);
  
  var route_uri = window.location.pathname.match(/\/([\w\d_-]+)/i)[1];
  var branch_uri = $("a[shape_id=" + li.parent().parent().attr('shape_id') + "]").attr('href').substring(1);
  var stop_uri = a.attr('href');
	
  marker.openInfoWindowHtml("<b>" + a.html() + "</b><br /><br /><div id='stop_times' style='font-size:.8em'>loading ...</div>");
  
  $.getJSON('/'+stop_uri, function(data) {
    
    var html = "<a href=\"/" + data.uri + "\"><strong>" + data.name + "</strong></a>&nbsp;&nbsp;&nbsp;<br />";
		
		connecting_routes = new Array();
    jQuery.each(data['stops'], function (i, stop) {
      if (stop['routes'])
        jQuery.each(stop['routes'], function (j, route) {
          var short_name = parseInt(route['name']);
          if (isNaN(short_name))
          {
            if (route['name'] == 'Yonge-University-Spadina Subway') short_name = 'YUS';
            else if (route['name'] == 'Bloor-Danforth Subway') short_name = 'BD';
            else if (route['name'] == 'Sheppard Subway') short_name = 'SHEP';
            else if (route['name'] == 'Scarborough RT') short_name = 'S.RT';
          }
          else
          {
            route['name'] = route['name'].slice(String(short_name).length+1);
          }
          var link = "<a href=\""+route['uri']+"\" title=\""+route['name']+"\">"+short_name+"</a>";
          if (route['uri'] != route_uri && jQuery.inArray(link, connecting_routes) == -1)
            connecting_routes.push(link);
        })
    });
    
		var stop = jQuery.grep(data['stops'],function(v,k){ return v['uri'] == stop_uri})[0]
		var route = stop&&stop['routes'] ? jQuery.grep(stop['routes'],function(v,k){ return v['uri'] == route_uri})[0] : null;
		var stop_times = route&&route['stop_times'] ? jQuery.grep(route['stop_times'],function(v,k){return v['shape'].to_uri() == branch_uri}) : null;
		
    html = html + "<div style='font-size:.8em'>";
		if(route && stop_times.length>0) html = html + "<br/>Next 3 stop times:<br/>" + jQuery.map(stop_times,function(v,k){return "<span title=\"" + v['shape'] + "\">" + v['departure_time'] + "</span>"}).join(' - ') + "<br/>"
    else html = html + "There are no upcoming stoptimes for this branch at this stop.";
    if(connecting_routes.length>0) html = html + "<br/>Connecting Routes:<br/>" + connecting_routes.join(' - ')
    
    html = html + "<br /></div>";
    marker.openInfoWindowHtml(html);
  })
}

function showShape(shape_id)
{
  var ul = $("div.list.stops[shape_id='"+shape_id+"'] ul");
  var li_s = ul.find("li.stop[lat]");
  
  if (li_s && li_s[0] && li_s[0].marker == undefined)
  {
    li_s.each(function () {
      var li = $(this);
      
      var title = li.find("a").html();
      var icon = "/images/red_10_dot.gif";
      //var icon = new GIcon(reddoticon);
      
      if (title.indexOf('Eastbound')!=-1) icon = "/images/red_10_dot_e.gif";
      else if (title.indexOf('Westbound')!=-1) icon = "/images/red_10_dot_w.gif";
      else if (title.indexOf('Northbound')!=-1) icon = "/images/red_10_dot_n.gif";
      else if (title.indexOf('Southbound')!=-1) icon = "/images/red_10_dot_s.gif";
      
      if (li.attr('num_connections') > ul.attr('threshold'))
        var marker = new ngIcon(new GLatLng(parseFloat(li.attr('lat')), parseFloat(li.attr('lng'))),title,icon,10,10);
        //var marker = new GMarker(new GLatLng(parseFloat(li.attr('lat')), parseFloat(li.attr('lng'))), {icon:icon, title: title, zIndexProcess:function (marker,b){ return 50; }});
      else
        var marker = new ngIcon(new GLatLng(parseFloat(li.attr('lat')), parseFloat(li.attr('lng'))),title,icon,6,6);
        //var marker = new GMarker(new GLatLng(parseFloat(li.attr('lat')), parseFloat(li.attr('lng'))), {icon:icon, title: title, zIndexProcess:function (marker,b){ return 20; }});
      
      map.addOverlay(marker);
      marker.shape_id = ul.attr('shape_id');
      marker.parent = li;
      
      GEvent.addListener(marker, "click", function()
      {
        showInfoWindow(marker);
        if (document.getElementById("pano"))
        {
    	    prev_position = new GLatLng(parseFloat($(marker.parent).attr('lat')), parseFloat($(marker.parent).attr('lng')));    	
    	    document.getElementById("pano").panoClient.getNearestPanorama(prev_position, showPanoData);
  	    }
      });
      GEvent.addListener(marker, "mouseover", function() { marker.parent.addClass('current'); });
      GEvent.addListener(marker, "mouseout", function() { marker.parent.removeClass('current'); });
      li[0].marker = marker;
    });
  }

  if (ul[0] && ul[0].polyline == undefined)
  {
    var latlng_array = new Array();
    $.each(ul[0].shape, function (i, point) {
      var latlng = new GLatLng(parseFloat(point[0]), parseFloat(point[1]));
      latlng_array.push(latlng);
    });
    
    //ul[0].polyline = new BDCCArrowedPolyline(latlng_array, "#FF5555", 4, 0.5, null, 60, 8, "#DD5555", 2, 0.5);
    if (ul[0]) ul[0].polyline = new GPolyline(latlng_array);
    if (ul[0]) map.addOverlay(ul[0].polyline);
  }
  
  li_s.each(function () {
    if ($(this)[0].marker) $(this)[0].marker.show();
  });
  
  if (ul[0]) ul[0].polyline.show();
}

function hideShape(shape_id)
{
  var ul = $("div.list.stops[shape_id='"+shape_id+"'] ul");
  var li_s = ul.find("li[lat]");
  if (ul[0] && ul[0].polyline)
    ul[0].polyline.hide();
  
  li_s.each(function () {
    if ($(this)[0].marker) $(this)[0].marker.hide();
  });
}

$(function() {

  if (!map) return;

  $.each($('a[shape_id]'), function (i, li) {
    loadShape($(this).attr('shape_id'));
  }).click(function() {
    if (shape_selected != -1) hideShape(shape_selected);
    shape_selected = $(this).attr('shape_id');
    var shape_id = $(this).attr('shape_id');

    $(this).blur()

    $(this).parents('li').siblings('li').removeClass('selected')
    $(this).parents('li').addClass('selected')
    //$(this).parent().parent().find('li a').css('font-weight','normal');
    //$(this).css('font-weight','bold');
    map.closeInfoWindow();
    
    showShape(shape_id);

    $(".stops.list[shape_id]").not(".stops.list[shape_id='"+shape_id+"']").slideUp();
    if( $(".stops.list[shape_id='"+shape_id+"']").css('display')!='block' )
      $(".stops.list[shape_id='"+shape_id+"']").slideDown();
    var ul = $(".stops.list[shape_id='"+shape_id+"'] ul");
    
    map.setCenter(ul[0].polyline.getBounds().getCenter());
    if (map.getCurrentMapType().getName() != 'Transit')
      map.setZoom(map.getBoundsZoomLevel(ul[0].polyline.getBounds()));
  }).mouseover(function() {
    var shape_id = $(this).attr('shape_id');

    if (shape_selected != shape_id) hideShape(shape_selected);
    if (shape_selected != shape_id) $(this).addClass('current');

    showShape(shape_id);
  }).mouseout(function() {
    var shape_id = $(this).attr('shape_id');
    $(this).removeClass('current');
    
    if (shape_selected == -1)
    {
      //startPoint.hide();
      hideShape(shape_id);
    }
    else if (shape_selected != shape_id)
    {
      hideShape(shape_id);
      showShape(shape_selected);
    }
  });
  
  if (document.location.hash.length > 0 && $('a[href='+document.location.hash+']').length > 0)
    setTimeout("$('a[href='+document.location.hash+']').eq(0).click()", 500);
  else
    setTimeout("$('a[shape_id]').eq(0).click()", 500);
});


String.prototype.to_uri = function(){
   return this
  .toLowerCase()
  .replace(/'/g,"") // remove single quotes
  .replace(/[^A-Za-z0-9+@=\-\/\\ ]/g, " ") // remove unwanted caracters
  .replace(/[ _\/\\]+/g, " ") // remove certain duplicates
  .replace(/^\s*/, "") // trim start whitespace
  .replace(/\s*$/, "") // trim end whitespace
  .replace(/\s/g, "_") // spaces to underscores
}

