//displays the map with a single journey
//enables sending a message to a user with ajax
jQuery(function(jQuery) {
  
  /* Facebook sharer */
  jQuery('.fb_share_link').bind( 'click' , function() {
    var u = location.href;
    var t = document.title;
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
  } );

  //attached the ajax form to the message box
  jQuery('#journey-send-message form').submit(function() {
    var options = {
            type : 'post',
            //on success display a message that the message has been sent
            success: function(data) {
              if(data == 1) {
                jQuery('#journey-send-message form').addClass('hide');
                jQuery('#journey-send-success').removeClass('hide');
              }
              else{
                jQuery('#journey-send-message form').addClass('hide');
                jQuery('#journey-send-error').removeClass('hide');
              }
            },
            //on error display a message that there was a problem sending the message 
            error: function() {
              jQuery('#journey-send-message form').addClass('hide');
              jQuery('#journey-send-error').removeClass('hide');
            }
          }
    jQuery(this).ajaxSubmit(options);
    return false;
  });
  
  //initiate the map
  simpleMap.mapCont = document.getElementById(simpleMap.mapId);
  if(!simpleMap.mapCont) {
    return;
  }
  
  google.load("maps", "2", {'callback' : simpleMap.initMap,
                            'language' : currentLang});
});


var simpleMap              = {};
simpleMap.jMap             = null;
simpleMap.jDirs            = null;
simpleMap.mapId            = 'map';
simpleMap.mapAddrId        = 'map-address';
simpleMap.iconsArr         = {};
simpleMap.wayPointsDataArr = [];

simpleMap.centerOnBasePosition = function() {
  //check whether we have a base position
  if(basePos && baseZoom) {
    var basePosArr = basePos.split(';');
    simpleMap.jMap.checkResize();
    simpleMap.jMap.setCenter(new google.maps.LatLng(basePosArr[0], basePosArr[1]), baseZoom);
    simpleMap.jMap.checkResize();
  }
  else {
    //europe (centered on strasbourg)
    simpleMap.jMap.setCenter(new google.maps.LatLng(47.783635, 6.020508), 4);
    simpleMap.jMap.checkResize();  
  }
}

simpleMap.initMap = function() {
  if (!google.maps.BrowserIsCompatible()) {
    return;
  }
  simpleMap.jMap = new google.maps.Map2(simpleMap.mapCont);
  simpleMap.centerOnBasePosition();
  
  simpleMap.jMap.addControl(new google.maps.LargeMapControl);
  simpleMap.jMap.addControl(new google.maps.OverviewMapControl());
  
  google.maps.Event.addListener(simpleMap.jMap, "click", function() {
    if(!simpleMap.jMap.scrollWheelZoomEnabled()) {      
      simpleMap.jMap.enableScrollWheelZoom();
    }
  });
      
  //the directions
  simpleMap.jDirs = new google.maps.Directions(simpleMap.jMap, null);
  google.maps.Event.addListener(simpleMap.jDirs, "addoverlay", simpleMap.onGDirectionsAddOverlay);
  google.maps.Event.addListener(simpleMap.jDirs, "error", simpleMap.onGDirectionsError);

  simpleMap.initIcons();  
  simpleMap.loadJourney();
    
  jQuery(document.body).unload(GUnload);
}

simpleMap.loadJourney = function() {
  //the addresses are in the div with id map-address
  var addressElem = document.getElementById(simpleMap.mapAddrId);
  if(addressElem && addressElem.innerHTML) {
    var addressArr       = addressElem.innerHTML.split('|');
    var addressParts     = [];
    var wayPointsArr     = [];
    //create the waypointArr for the directions
    for(var i = 0; i < addressArr.length; i++) {
      if(addressArr[i].indexOf(';') < 0) {
        continue;
      }
      addressParts = addressArr[i].split(';');
      if(addressParts[0] && addressParts[1]) {
        wayPointsArr.push(new google.maps.LatLng(parseFloat(addressParts[0]), parseFloat(addressParts[1])));
        simpleMap.wayPointsDataArr.push(addressParts[2]);
      }
    }
    //if we have some waypoints, get the directions
    if(wayPointsArr.length > 0) {
      simpleMap.jDirs.loadFromWaypoints(wayPointsArr);
    }
    else{
      //show an error message
      var errMsgElem = document.getElementById('map-msg');
      if(errMsgElem) {
        errMsgElem.style.display = 'block';
      }
    }
  }
}

//remove the standard direction markers and replace with ours
simpleMap.onGDirectionsAddOverlay = function() {
  var wayPointCnt = simpleMap.jDirs.getNumGeocodes();
  var currMarker  = null;
  var currLatLng  = null;
  var icon        = null
  for(var i = 0; i < wayPointCnt; i++) {
    currMarker = simpleMap.jDirs.getMarker(i);
    currLatLng = currMarker.getLatLng();
    currMarker.hide();
    switch(i) {
      case 0:
        icon = 'dep';
      break;
      case (wayPointCnt - 1):
        icon = 'dest';
      break;
      default:
        icon = 'stop';
    }
    
    simpleMap.jMap.addOverlay(simpleMap.createMarker(currLatLng, icon, simpleMap.wayPointsDataArr[i]));
  }
    
  //add the length, duration, cost and co2 of this journey
  //length
  var distanceObject = simpleMap.jDirs.getDistance();
  var meters = distanceObject['meters'] || 0;
  var km     = (meters / 1000) || false;
  var kmHtml = distanceObject['html'];
  var durationObject = simpleMap.jDirs.getDuration();
  var duration       = durationObject['seconds'];
  var durationHtml   = durationObject['html'];
  //the cost is the length in km times the average petrol usage times the avergae petrol price for this country
  var cost = km * 6/100 * AVG_PETROL_PRICE;
  var co2  = km * 6/100 * 2.424; //this is the co2 per litre normal petrol;
  
  //if we don't have the length, we don't want to see anything
  if(km && kmHtml) {
    jQuery('#journey-length').html(kmHtml);
    jQuery('#journey-facts ul').show();
    
    if(durationHtml) {
    jQuery('#journey-duration').html(durationHtml);
    }
    else{
      jQuery('#journey-duration').hide();
    }
    if(!isNaN(cost)) {
      cost = cost.toFixed(2).toString().replace('.', DECIMAL_SEPARATOR);
      var obj = jQuery('#journey-cost');
      obj.html(obj.html().replace('x', cost));
    }
    else{
      jQuery('#journey-cost').hide();
    }
    if(co2) {
      co2 = co2.toFixed(2).toString().replace('.', DECIMAL_SEPARATOR);
      var obj = jQuery('#journey-co2');
      obj.html(obj.html().replace('x', co2));
    }
    else{
      jQuery('#journey-co2').hide();
    }
  
    //update the database with the length and duration of the journey  
    var params   = {};
    params['m']        = meters;
    params['sec']      = duration;
    params['jid']      = JOURNEY_ID;
    params['action']   = 'addkm';
    jQuery.ajax({
      data: params
    })     
  }
}

//remove the standard direction markers and replace with ours
simpleMap.onGDirectionsError = function() {  
  var statusCode = simpleMap.jDirs.getStatus().code;
  
  //show an error message
  var errMsgElem = document.getElementById('map-msg');
  if(errMsgElem) {
    errMsgElem.style.display = 'block';
  }
  var errorMsg   = '';
  switch(statusCode) {
    case G_GEO_UNKNOWN_ADDRESS :
      errorMsg = ("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: " + statusCode);
    break;
    case G_GEO_SERVER_ERROR :
      errorMsg = ("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + statusCode);
    break;
    case G_GEO_MISSING_QUERY :
      errorMsg = ("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: " + statusCode);
    break;
    case G_GEO_BAD_KEY :
      errorMsg = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + statusCode);
    break;
    case G_GEO_BAD_REQUEST :
      errorMsg = ("A directions request could not be successfully parsed.\n Error code: " + statusCode);
    break;
    default:
      errorMsg = ("An unknown error occurred." + statusCode);    
  }
   
  //update the database with the length and duration of the journey  
  var params   = {};
  params['m']        = -1;
  params['sec']      = statusCode;
  params['jid']      = JOURNEY_ID;
  params['action']   = 'addkm';
  jQuery.ajax({
    data: params
  })
}

simpleMap.createMarker = function(latLng, icon, info) {
  var icon = simpleMap.iconsArr[icon] || null;
  var marker  = new google.maps.Marker(latLng, {icon:icon});
  if(info) {
    marker.bindInfoWindowHtml(info);
  }
  return marker;
}

simpleMap.initIcons = function() {
  var journeyIcon = new google.maps.Icon(); 
  journeyIcon.image  = mediaPath + '/map/green.png';
  journeyIcon.shadow = mediaPath + '/map/shadow.png';
  journeyIcon.iconSize = new google.maps.Size(12, 20);
  journeyIcon.shadowSize = new google.maps.Size(22, 20);
  journeyIcon.iconAnchor = new google.maps.Point(6, 20);
  journeyIcon.infoWindowAnchor = new google.maps.Point(5, 1);
  
  var countryIcon    = new google.maps.Icon(journeyIcon); 
  countryIcon.image  = mediaPath + '/map/red.png'; 
  
  var depIcon    = new google.maps.Icon(journeyIcon); 
  depIcon.image  = mediaPath + '/map/yellow.png'; 
  
  var destIcon    = new google.maps.Icon(journeyIcon); 
  destIcon.image  = mediaPath + '/map/black.png';
  
  var stopIcon    = new google.maps.Icon(journeyIcon); 
  stopIcon.image  = mediaPath + '/map/blue.png';
  
  var parkingIcon      = new google.maps.Icon(journeyIcon); 
  parkingIcon.image    = mediaPath + '/map/parking.png';
  
  simpleMap.iconsArr['country'] = countryIcon;
  simpleMap.iconsArr['journey'] = journeyIcon;
  simpleMap.iconsArr['p']       = parkingIcon;
  simpleMap.iconsArr['dep']     = depIcon;
  simpleMap.iconsArr['dest']    = destIcon;
  simpleMap.iconsArr['stop']    = stopIcon;  
}