/**
 * @author igor@dlma.nl
 * @projectDescription JS used to manage jams for Google Maps (polyline)
 */
var jams = new Array();
var lat_lang = new Array();
var points = new Array();
var start = null;
var poly = null;
var icon_start = null;
var center_index = null;

var flag = getFlagValue();
var RadarBoundaries = new GLatLngBounds(new GLatLng(48.895,0), new GLatLng(55.974,10.856));
var RadarOverlay = new GGroundOverlay("http://mijn.buienradar.nl/gps/maps.gif", RadarBoundaries);
var cloudFlag = getCloudFlag();

function stripslashes(str){
    str = str.replace(/\\'/g, '\'');
    str = str.replace(/\\"/g, '"');
    str = str.replace(/\\\\/g, '\\');
    str = str.replace(/\\0/g, '\0');
    return str;
}

function showJams(){

    if (inMap != null) {
        updateData(true);
    }
}

function hideJams(){

    if (inMap != null) {
        $.each(jams, function(i, jam){
            inMap.GMap.removeOverlay(jam);
        });
    }
}


      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);
      
      // === 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 ) {
        // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
        // 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;
      }
       
      // === A function to create the arrow head at the end of the polyline ===
      function arrowHead(points) {
        // == obtain the bearing between the last two points
        var p1=points[points.length-1];
        var p2=points[points.length-2];
        var dir = bearing(p2,p1);
        // == round it to a multiple of 3 and cast out 120s
        var dir = Math.round(dir/3) * 3;
        while (dir >= 120) {dir -= 120;}
        // == use the corresponding triangle marker 
        arrowIcon.image = "/dynamic_map/images/arrows/dir_"+dir+".png";
        return new GMarker(p1, arrowIcon);
      }
      
      // === A function to put arrow heads at intermediate points
      /*
      function midArrows(points) {
        for (var i=1; i < points.length-1; i++) {  
          var p1=points[i-1];
          var p2=points[i+1];
          var dir = bearing(p1,p2);
          // == round it to a multiple of 3 and cast out 120s
          var dir = Math.round(dir/3) * 3;
          while (dir >= 120) {dir -= 120;}
          // == use the corresponding triangle marker 
          console.debug(dir);
          arrowIcon.image = "http://www.google.com/intl/en_ALL/mapfiles/dir_"+dir+".png";
          map.addOverlay(new GMarker(points[i], arrowIcon));
        }
      }
      */




function updateData(){
    flag = getFlagValue();
    
    hideJams();

    cloudFlag = getCloudFlag();
    if (cloudFlag)
    {
        inMap.GMap.removeOverlay(RadarOverlay);
        RadarOverlay = new GGroundOverlay("http://mijn.buienradar.nl/gps/maps.gif", RadarBoundaries);
        inMap.GMap.addOverlay(RadarOverlay);    
    }
    
    $.getJSON('/dynamic_map/clouds_json.php', function(data){
          $('#p_update_clouds').css('background-image', "url('" + data.image + "')");
          $('#clouds_summary').html(data.text);  
        }
        );

    $.getJSON('/dynamic_map/jam_json.php', function(data){
    
    $("#jam_summary").html(data.tekst);
    
    


    $.each(data.jams, function(i, item){
        icon_start          = new GIcon(G_DEFAULT_ICON);
        icon_start.image = "/dynamic_map/images/icons-jam.png";
        icon_start.iconSize             = new GSize( 30, 31 );
        icon_start.iconAnchor       = new GPoint( 14, 33 );
        icon_start.infoWindowAnchor     = new GPoint( 30, 5 );
        if (item.enc_points != "" && item.enc_points != "??" && item.enc_points != "BB")
        {
	        poly = new GPolyline.fromEncoded({
	                    color: "#FF0000",
	                    weight: 8,
						opacity : 0.9,
	                    points: item.enc_points,
	                    levels: item.enc_levels,
	                    zoomFactor: 32,
	                    numLevels: 4
	              });
            var iVertecsCount = poly.getVertexCount();
            var points = new Array();
            if (iVertecsCount > 2)
            {
                points[0] = poly.getVertex(iVertecsCount-2);
                points[1] = poly.getVertex(iVertecsCount-1);
            }
           
            var oArrowHead = arrowHead(points);
	        try
	        {
	            jams.push(poly);
                jams.push(oArrowHead);
		        if (polybounds = poly.getBounds())
		        {
			        start = new GMarker(polybounds.getCenter(), {
			                title:  item.gevolg,
			                icon: icon_start
			            });
			        
			        jams.push(start);
			        
			        
			        if (flag) {
			            inMap.GMap.addOverlay(start);
                        
			        }
			        
			        if(item.oorzaak == "") {
			            item.oorzaak = "onbekend.";
			        }
			        
			        GEvent.addListener(start, 'click', function(para){
			            inMap.GMap.openInfoWindowHtml(para, "<div class='jam_popup'><h4>" + item.wegnr + ": van " + item.van + ", " + item.vansub  + " naar " + item.naar  + ", " + item.naarsub + "</h4>" + 
			            "<div>" + item.gevolg + ". " + item.trendtekst + "</div>" + 
			            "<div>Lengte: " + item.afstand + " km, " +
			            "van hectometerpaal " + item.hectostart + " tot " + item.hectoeind + ".</div>" +
			            "<div>Oorzaak: " + item.oorzaak + "</div></div>");
			        });
			    }
			    
			    if (flag) {
                    inMap.GMap.addOverlay(poly);
                    inMap.GMap.addOverlay(oArrowHead);
                }
		    }
		    catch(exception)
		    {
		        //alert('111');
		    }
	                
	              
	        
        }
    });
});
}

function getFlagValue()
{
  if (is_home())
  {
      return true;
  }
  else
  {
      return ($("input#u_jams:checked").length > 0);    
  }
  
}

function getCloudFlag()
{
    return ($("input#u_clouds:checked").length > 0);
}

function updateClouds()
{
    cloudFlag = getCloudFlag();
    if (inMap) {
        inMap.GMap.removeOverlay(RadarOverlay);
        if (cloudFlag) {
            inMap.GMap.addOverlay(RadarOverlay);
        }
        
    }
}

function update_jams(){
    flag = getFlagValue();
    //alert(flag);
    if (inMap) {
        if (flag) {
            showJams();
        }
        else {
            hideJams();
        }
    }
}
/*
$(document).ready(function(){
    updateData();
});
*/


// Decode an encoded polyline into a list of lat/lng tuples.
function decodeLine(encoded){
    var len = encoded.length;
    var index = 0;
    var array = [];
    var lat = 0;
    var lng = 0;
    
    while (index < len) {
        var b;
        var shift = 0;
        var result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        }
        while (b >= 0x20);
        var dlat = ((result & 1) ? ~ (result >> 1) : (result >> 1));
        lat += dlat;
        
        shift = 0;
        result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        }
        while (b >= 0x20);
        var dlng = ((result & 1) ? ~ (result >> 1) : (result >> 1));
        lng += dlng;
        
        array.push([lat * 1e-5, lng * 1e-5]);
    }
    
    return array;
}

// Decode an encoded levels string into a list of levels.
function decodeLevels(encoded){
    var levels = [];
    
    for (var pointIndex = 0; pointIndex < encoded.length; ++pointIndex) {
        var pointLevel = encoded.charCodeAt(pointIndex) - 63;
        levels.push(pointLevel);
    }
    
    return levels;
}
