<?php
// $Id: location.fr.inc,v 1.2 2007/05/08 06:53:38 thierrygd Exp $

/**
 * Returns a lat/lon pair of the approximate center of the given postal code in the given country
 *
 * @param $location
 *   An associative array $location where
 *     'street'       => the street portion of the location
 *     'supplemental' => additional street portion of the location
 *     'province'     => the province, state, or territory
 *     'country'      => lower-cased two-letter ISO code (REQUIRED)
 *     'postal_code'  => the international postal code for this location (REQUIRED)
 *
 * @return
 *   An associative array where
 *      'lat' => approximate latitude of the center of the postal code's area
 *      'lon' => approximate longitude of the center of the postal code's area
 *
 */
function location_latlon_rough_fr($location = array()) {
	
  if (!isset($location['postal_code'])) {
    return NULL;
  }
 
  // CAS N°1 : Ville avec code postal unique -> requete sur "Code postal + ville"
  // Exemple : "40000 Mont de Marsan" (Prefectures de province, hors grandes villes)
  
  $result_double	= db_query("SELECT latitude, longitude FROM {zipcodes} WHERE country = '%s' AND zip = '%s' AND city = '%s'", $location['country'], substr(str_pad($location['postal_code'], 5, '0', STR_PAD_LEFT), 0, 5), $location['city']);

  if ($row = db_fetch_object($result_double)) {
    return array('lat' => $row->latitude, 'lon' => $row->longitude);
  }  
  else{

  	// CAS N°2 : Ville non reconnue -> Requete sur "Code postal" uniquement
 	// Exemple : "Saint Denis les Bourg" au lieu de "Saint Denis lès Bourg" (problème d'accent, de tiret, saint/st ...)

 	$result_zipcode 	= db_query("SELECT latitude, longitude FROM {zipcodes} WHERE country = '%s' AND zip = '%s'", $location['country'], substr(str_pad($location['postal_code'], 5, '0', STR_PAD_LEFT), 0, 5));

 	if ($row = db_fetch_object($result_zipcode)){
	    return array('lat' => $row->latitude, 'lon' => $row->longitude);
	}
	else{
	  	
	  	// CAS N°3 : Code postal non reconnu -> Requete sur "Ville" uniquement
		// Exemple : "75016 Paris" (Arrondissement des grandes villes françaises)
  
		$result_city 		= db_query("SELECT latitude, longitude FROM {zipcodes} WHERE country = '%s' AND city = '%s'", $location['country'], $location['city']);

		if ($row = db_fetch_object($result_city)){
		    return array('lat' => $row->latitude, 'lon' => $row->longitude);
		
		}
		else{
			return NULL;
		}
	  }
  }
}

/**
 * Returns a lat/lon pair of the approximate center of the given postal code in the given country
 *
 * @param $location
 *   An associative array $location where only postal code and country are necessary, but can have the keys:
 *     'street'       => the street portion of the location
 *     'supplemental' => additional street portion of the location
 *     'province'     => the province, state, or territory
 *     'country'      => lower-cased two-letter ISO code (REQUIRED)
 *     'postal_code'  => the international postal code for this location (REQUIRED)
 *
 * @return
 *   An associative array where
 *      'lat' => approximate latitude of the center of the postal code's area
 *      'lon' => approximate longitude of the center of the postal code's area
 *
 */
function location_get_postalcode_data_fr($location = array()) {
  $dash_index = strpos($location['postal_code'], '-');
  // First we strip slash off if we're dealing with a 9-digit US zipcode
  if (!($dash_index === FALSE)) {
    $location['postal_code'] = substr($location['postal_code'], 0, $dash_index);
  }
  
  // Now we pad the thing and query.
  $res = db_query("SELECT * FROM {zipcodes} where country = '%s' AND zip = '%s'", $location['country'], str_pad($location['postal_code'], 5, "0", STR_PAD_LEFT));
  if ($row = db_fetch_object($res)) {
    return array('lat' => $row->latitude, 'lon' => $row->longitude, 'city' => $row->city, 'province' => $row->state, 'country' => $row->country);
  }
  else {
    return NULL;
  } 
}

/**
 * Parameters:
 *   An associative array $location where
 *     'street'       => the street portion of the location
 *     'supplemental' => additional street portion of the location
 *     'province'     => the province, state, or territory
 *     'country'      => lower-cased two-letter ISO code (REQUIRED)
 *     'postal_code'  => the international postal code for this location (REQUIRED)
 *
 *
 */
function location_latlon_exact_fr($location = array()) {
  //return NULL;
  // By uncommenting the line of code below, you legally acknowledge that you understand that you can only
  // do so under the terms of the Non-Commercial Share-alike license described at http://creativecommons.org/licenses/by-nc-sa/2.0/
  return location_geocode_fr_google($location);
}

function location_map_link_fr_google($location = array()) {
  $query_params = array();
  
//  foreach (array('street', 'city', 'province', 'postal_code', 'country') as $field) {
  foreach (array('street', 'city', 'postal_code', 'country') as $field) {
    if (isset($location[$field])) {
      $query_params[] = $location[$field];
    }
  }
  
  if (count($query_params)) {
    return ('http://maps.google.com?q='. urlencode(implode(", ", $query_params)));
  }
  else {
    return NULL;
  }
}

/**
 * @return 
 *   An array where 
 *     -> the key is the word that helps identify the name of function that builds the link.  For example, a key of 'yahoo' means the name of the
 *        the function that builds a link to a map on Yahoo! Maps would be 'location_map_link_fr_yahoo'
 *     -> the value is itself an array with 3 key/value pairs:
 *          'name' => points to the name of the mapping service.  For 'yahoo', this would be 'Yahoo! Maps'
 *          'url' => the url of the main page of the mapping service.  For 'yahoo', this would be 'http://maps.yahoo.com'
 *          'tos' => the url of the page that explains the map providers Terms of Service, or Terms of Use. For 'yahoo', this would be
 *                   'http://help.yahoo.com/help/us/maps/maps-24.html'
 */
function location_map_link_fr_providers() {
  return array('google' => array('name' => 'Google Maps', 'url' => 'http://maps.google.com', 'tos' => 'http://www.google.com/help/terms_local.html'),
//               'yahoo' => array('name' => 'Yahoo! Maps', 'url' => 'http://maps.yahoo.com', 'tos' => 'http://help.yahoo.com/help/us/maps/maps-24.html')
              );
}


/**
 * @return
 *   An array of values that work as keys to the array returned by location_map_link_fr_providers.  The idea is that if the
 *   administrator of the site has not yet had a chance to visit the "Map Links" subtab on the location module's settings page,
 *   that we can provide deep-linking to a relatively safe default.  By 'relatively safe', we mean that the Terms Of Service of
 *   the provider of the maps are flexible enough for most parties.
 *
 *   For the case of the U.S., 'google' has relatively flexible Terms Of Service, whereas Yahoo! Maps and MapQuest have more
 *   restrictive Terms Of Service.
 *
 */
function location_map_link_fr_default_providers() {
  return array('google');
}

function location_geocode_fr_providers() {
  return array(
//    'yahoo' => array('name' => 'Yahoo! Maps Web Services', 'url' => 'http://developer.yahoo.com/maps/rest/V1/geocode.html', 'tos' => 'http://developer.yahoo.com/maps/mapsTerms.html'),
    
    'google' => array('name' => 'Google Maps API', 'url' => 'http://www.google.com/apis/maps/', 'tos' => 'http://www.google.com/apis/maps/terms.html')
  
  );
}

function location_geocode_fr_google($location = array()) {

  $service_url = 'http://maps.google.com/maps/geo?output=xml&key='. variable_get('location_geocode_fr_google_apikey', '') .'&q=';

  $address = location_address2singleline($location);
  
  $http_reply = drupal_http_request($service_url . urlencode($address));

  $status_code_match = array();
  preg_match('/<code>(.*)<\/code>/', $http_reply->data, $status_code_match);
  $status_code = $status_code_match[1];
  if ($status_code != 200) {
    return NULL;
  }
  
  $accuracy_code_match = array();
  preg_match('/Accuracy="([0-9])"/', $http_reply->data, $accuracy_code_match);
  $accuracy_code = $accuracy_code_match[1];
  
  // Abaissemenent à un niveau de précision de 6 par rapport à la version us
  if ($accuracy_code != 8 && $accuracy_code != 7 && $accuracy_code != 6) {
    return NULL;
  }
  
  $latlon_match = array();
  preg_match('/<coordinates>(.*)<\/coordinates>/', $http_reply->data, $latlon_match);
  
  $latlon_exploded = explode(',', $latlon_match[1]);

  // En cours : standardisation du nom de la ville pour correspondre à la table zipcodes
  // Doit insérer node->locations[$index]['city'] dans location.module au niveau de la ligne 886
  preg_match('/<LocalityName>(.*)<\/LocalityName>/', $http_reply->data, $city_match);

  return array('city' => $city_match[1], 'lat' => $latlon_exploded[1], 'lon' => $latlon_exploded[0]);
}

function location_geocode_fr_google_settings(){
  $form = array();

  $form['location_geocode_fr_google_apikey'] = array(
    '#type' => 'textfield',
    '#title' => t('Google Maps API Key'),
    '#size' => 64,
    '#maxlength' => 128,
    '#default_value' => variable_get('location_geocode_fr_google_apikey', ''),
    '#description' => t('In order to use the Google Maps API geocoding web-service, you will need a Google Maps API Key.  You can obtain one at the !sign_up_link for the !google_maps_api.', array('!sign_up_link' => '<a href="http://www.google.com/apis/maps/signup.html">sign-up page</a>', '!google_maps_api' => '<a href="http://www.google.com/apis/maps/">Google Maps API</a>'))
  );

  return $form;
}


/**
 * Theme du style de l'adresse postale
 *   -> Code postal puis ville sur la même ligne
 *   -> Pas de notion de province
 */
function theme_location_fr($location = array(), $hide = array()) {

	$output = '';
	  
	if (count($location)) {
    $output .= "\n";
    $output .= '<div class="location vcard"><div class="adr">'."\n";
    if (!empty($location['name']) && !in_array('name', $hide)) {
       $output .= '<div class="fn">'. $location['name'] .'</div>';
    }

    if (!empty($location['street']) && !in_array('street', $hide)) {
      $output .= '<div class="street-address">'. $location['street'];
      if (!empty($location['additional']) && !in_array('street', $hide)) {
        $output .= ' ' . $location['additional'];
      }
      $output .='</div>';
    }

    if (!empty($location['city']) && !in_array('city', $hide)) {
      $city_province_postal[] = $location['city'];
    }

    if ((!empty($location['city']) && !in_array('city', $hide)) ||
        (!empty($location['province']) && !in_array('province', $hide)) ||
        (!empty($location['postal_codet']) && !in_array('postal_code', $hide))) {

      $city_province_postal = array();

      if (!empty($location['postal_code']) && !in_array('postal_code', $hide)) {
        $city_province_postal[] = '<span class="postal-code">'. $location['postal_code'] .'</span>';
      }      
      
      if (!empty($location['city']) && !in_array('city', $hide)) {
        $city_province_postal[] = '<span class="locality">'. $location['city'] .'</span>';
      }

      if (!empty($location['province']) && !in_array('province', $hide)) {
//        $city_province_postal[] = '<br /><span class="region">'. $location['province'] .'</span>';
      }

//    $output .= implode(', ', $city_province_postal);
      $output .= implode(' ', $city_province_postal);
    }

    if (!empty($location['country']) && !in_array('country', $hide)) {
      $countries = _location_get_iso3166_list();
      $output .= '<div class="country-name">'. t($countries[$location['country']]) .'</div>';
    }

    if (isset($location['latitude']) && isset($location['longitude'])) {
      $output .=  '<div class="geo"><abbr class="latitude" title="'. $location['latitude'] .'" /><abbr class="longitude" title="'. $location['latitude'] .'" /></div>';
    }

    $output .= '</div></div>';
  }

  return $output;
}


function location_province_list_fr() {
  return array('A67' => "Bas-Rhin - Alsace",
    'A68' => "Haut-Rhin - Alsace",
    'B24' => "Dordogne - Aquitaine",
    'B33' => "Gironde - Aquitaine",
    'B40' => "Landes - Aquitaine",
    'B47' => "Lot-et-Garonne - Aquitaine",
    'B64' => "Pyrenees-Atlantiques - Aquitaine",
    'B79' => "Deux-Sevres - Aquitaine",
    'C03' => "Allier - Auvergne",
    'C15' => "Cantal - Auvergne",
    'C43' => "Haute-Loire - Auvergne",
    'C63' => "Pu-de-Dome - Auvergne",
    'D21' => "Cote-d'Or - Bourgogne",
    'D58' => "Nievre - Bourgogne",
    'D71' => "Saone-et-Loire - Bourgogne",
    'D89' => "Yonne - Bourgogne",
    'E22' => "Cotes-d'Armor - Bretagne",
    'E29' => "Finistere - Bretagne",
    'E35' => "Ille-et-Vilaine - Bretagne",
    'E56' => "Morbihan - Bretagne",
    'F18' => "Cher - Centre",
    'F28' => "Eure-et-Loir - Centre",
    'F36' => "Indre - Centre",
    'F37' => "Indre-et-Loire - Centre",
    'F41' => "Loir-et-Cher - Centre",
    'F45' => "Loiret - Centre",
    'G08' => "Ardennes - Champagne-Ardenne",
    'G10' => "Aube - Champagne-Ardenne",
    'G51' => "Marne - Champagne-Ardenne",
    'G52' => "Haute-Marne - Champagne-Ardenne",
    'H2A' => "Corse-du-Sud - Corse",
    'H2B' => "Haute-Corse - Corse",
    'I25' => "Doubs - Franche-Comte",
    'I39' => "Jura - Franche-Comte",
    'I70' => "Haute-Saone - Franche-Comte",
    'I90' => "Haute-Saone - Territoire de Belfort",
    'J75' => "Paris - Ile-de-France",
    'J77' => "Seine-et-Marne - Ile-de-France",
    'J78' => "Yvelines - Ile-de-France",
    'J91' => "Essonne - Ile-de-France",
    'J92' => "Hauts-de-Seine - Ile-de-France",
    'J93' => "Seine-Saint-Denis - Ile-de-France",
    'J94' => "Val-de-Marne - Ile-de-France",
    'J95' => "Val-d'Oise - Ile-de-France",
    'U04' => "Alpes-de-Haute-Provence - Provence-Alpes-Cote d'Azur",
    'U05' => "Hautes-Alpes - Provence-Alpes-Cote d'Azur",
    'U06' => "Alpes-Maritimes - Provence-Alpes-Cote d'Azur",
    'U13' => "Bouches-du-Rhone - Provence-Alpes-Cote d'Azur",
    'U83' => "Var - Provence-Alpes-Cote d'Azur",
    'U84' => "Vaucluse - Provence-Alpes-Cote d'Azur");
}

