var clickHandler;
var clickMarker;
var marker;
var gmarkers = [];
var point;
var map;
var locations;
var idStation;
var twmag;
var twpoi;
var bounds;
var url_img_magasin = "http://minisite.tw.mezcalito.net";
var url_img_server = "http://map.tw.mezcalito.net";
var ci_path = '/proxy.php?proxy_url=http://map.tw.mezcalito.net/index.php';
var traduction = new Array;
var traduction_fr = new Array('Louez dans ce magasin');
var traduction_en = new Array('Hire from this shop');
var traduction_nl = new Array('Huren in deze winkel');
var traduction_es = new Array('Alquile en este almac&eacute;n');
traduction['fr'] = traduction_fr;
traduction['en'] = traduction_en;
traduction['nl'] = traduction_nl;
traduction['es'] = traduction_es;
var infowindows = new Array();


function loadMap(){
    initLibTooltip();
        if(TheidStation == 55){
            $("#mapmap").append('<div id="map_55" class="mygooglemap-surcouche" style="position:absolute; z-index:3000"><img src="'+url_img_server+'/images/carte-station/55.jpg" /></div>');
        }
        else {
	var mapLatlng = new google.maps.LatLng(45.1719932284, 6.65788650513);
        var myOptions = {
           
            scrollwheel : false,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scaleControl: true,
            scaleControlOptions: {
                position: google.maps.ControlPosition.BOTTOM_LEFT
            }
//            ,
//            navigationControl: true,
//            navigationControlOptions: {
//                style: google.maps.NavigationControlStyle.DEFAULT,
//                position: google.maps.ControlPosition.TOP_LEFT
//            }
        }
       map = new google.maps.Map(document.getElementById("mapmap"), myOptions);


      twmag = new google.maps.MarkerImage(url_img_server+"/images/twmag-ombre.png",
      new google.maps.Size(72,36),
      new google.maps.Point(0,0),
      new google.maps.Point(12,36));

      twpoi = new google.maps.MarkerImage(url_img_server+"/images/icone-ombre.png",
      new google.maps.Size(42, 36),
      new google.maps.Point(0,0),
      new google.maps.Point(12,36));

      bounds = new google.maps.LatLngBounds();

         ChargerLaStation();
       }
    }


function ChargerLaStation(){

			$('.mygooglemap-surcouche').remove();
			idMagasin = (idMagasin ? idMagasin : "non");
			window["idStation"] = TheidStation;
			this.lien_externe  = (lien_externe ? lien_externe : "default");
                        this.lien_externe = lien_externe;

			//$.get(ci_path+'/point/station/'+TheidStation ,	CenterOnStation );
			if(idMagasin != "non"){
				$.get(ci_path+'/point/getmag/'+TheidStation+'/print/'+idMagasin,	SetPointOnStation );
			} else {
				$.get(ci_path+'/point/getmag/'+TheidStation+'/print',	SetPointOnStation );
			}
}

// zoom sur la station
function CenterOnStation(content) {
	eval("locations = "+content);
	// modif 04/09/2007 [servane]
	// j'enleve le for (var i in locations) car il y a une conflit avec la librairie xajax... 
	// il vaut donc mieux utiliser un for (var i=0 etc...
	//for (var i in locations) {
	for (var i=0; i<locations.length;i++) {
		var element = locations[i];
		map.setCenter(new google.maps.LatLng(element['latitude'], element['longitude']));
		map.setZoom(element['zoom']);
	}
}


// Creer un marker
function createMarker(point, iconename ,content) {

    var image = new google.maps.MarkerImage(url_img_server+'/images/icone-'+iconename+'.png',
      new google.maps.Size(29,36),
      new google.maps.Point(-5,0),
      new google.maps.Point(20,36));


var marker = new google.maps.Marker({
                        position: point,
                        icon: image,
                        shadow: twpoi,
                        map: map,
                        zIndex: 20
                        });
marker.attachTipTool(content);
  bounds.extend(point);
   return marker;
}

//function importanceOrder (marker) {
//  return google.maps.Overlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
//}

function createMarkerShop(point, iconename ,content, relais) {
	relais = (relais ? relais : "non");
        if(relais == "oui"){
		var imageurl = url_img_server+'/images/relais.png';
	} else {
	//	image = url_img_server+'/images/twmag-'+iconename+'.png';
		var imageurl = url_img_server+'/images/twmag.png';
	}
        var icon = new google.maps.MarkerImage(imageurl,
      new google.maps.Size(70,36),
      new google.maps.Point(-5,0),
      new google.maps.Point(20,36));
	

        var marker = new google.maps.Marker({
                        position: point,
                        icon: icon,
//                        zIndexProcess:importanceOrder,
                        shadow: twmag,
                        map: map,
                        zIndex: 50
                        });
  marker.importance = 50;
bounds.extend(point);
attachMessage(marker, content);
	
  return marker;
}


// Chargement des points de la station
function SetPointOnStation(content) {
    
	eval("locations = "+content);
	var a = 1;
	// modif 04/09/2007 [servane]
	// j'enleve le for (var i in locations) car il y a une conflit avec la librairie xajax... 
	// il vaut donc mieux utiliser un for (var i=0 etc...
	//for (var l in locations) {
	for (var l=0; l<locations.length;l++) {
		var element = locations[l];
		var i = element['id_point'];
		var point = new google.maps.LatLng(element['lat_point'], element['long_point']);
		if(element['id_tpoint'] == 1 || element['id_tpoint'] == 15){
			if(element['id_tpoint'] == 15){
				content = '<div style="font-weight:bold; background-color:#9EC735; color:#fff; padding:3px; margin-bottom:4px; width:450px">'+element['name_point']+'</div>';
				content += '<div>'+element['detail_point']+'</div>';
				if(lien_externe == 'station' || lien_externe == 'oui'){
					content += '<div style="clear:both;"><a href="/rent/etape1/index/id_magasin/'+element['id_magasin']+'">'+traduction['fr'][0]+'</a></div>';
				} else if(lien_externe == 'groupe') {
					content += '<div style="clear:both;"><a href="#" onclick="SelectionneMagasinPourGroupe('+element['id_magasin']+')">'+traduction['fr'][0]+'</a></div>';
                                }
                                else if(lien_externe == 'hide') {
					content += '<div style="clear:both;"></div>';
				}
                                else{
					content += '<div style="clear:both;"><a href="#box-reserver" onclick="SelectionneMagasinDepuisCarte('+element['id_magasin']+')">'+traduction['fr'][0]+'</a></div>';
				}
				
				gmarkers[i] = createMarkerShop(point,a,content,'oui');
			} else {
				content = '<div style="font-weight:bold; background-color:#9EC735; color:#fff; padding:3px; margin-bottom:4px;  width:450px">'+element['name_point']+'</div>';
				if(element['photo_magasin'] != undefined){ 
					content += '<div style="float: left; width:150px; height: 150px;margin-right:5px"><img src="'+url_img_magasin+element['photo_magasin']+'"/></div>';
				}
				if(element['phrase'] != undefined){
					content += '<div style="font-weight:bold; background-color:#F2EFE9">'+element['phrase']+'</div>';
				} 
				content += '<div>'+element['detail_point']+'</div>';
				if(lien_externe == 'station' || lien_externe == 'oui'){
					content += '<div style="clear:both;"><a href="/rent/etape1/index/id_magasin/'+element['id_magasin']+'">'+traduction['fr'][0]+'</a></div>';
				} else if(lien_externe == 'groupe') {
					content += '<div style="clear:both;"><a href="#" onclick="SelectionneMagasinPourGroupe('+element['id_magasin']+')">'+traduction['fr'][0]+'</a></div>';
				}else if(lien_externe == 'hide') {
					content += '<div style="clear:both;"></div>';
				} else{
					content += '<div style="clear:both;"><a href="#box-reserver" onclick="SelectionneMagasinDepuisCarte('+element['id_magasin']+')">'+traduction['fr'][0]+'</a></div>';
				}
				gmarkers[i] = createMarkerShop(point,a,content);
			}
			a++;
		} else {
			gmarkers[i] = createMarker(point,element['id_tpoint'],element['name_point']);
		}
		
	}
        map.fitBounds(bounds);
        
        if ( map.getZoom() > 15 ) {
                map.setZoom(15);
            }
}

function SelectionneMagasinDepuisCarte(id_magasin){
	window.parent.jQuery('select[name=id_magasin] > option[selected]').removeAttr('selected');
	window.parent.jQuery('select[name=id_magasin] > option[value='+id_magasin+']').attr('selected', 'selected');
	//window.parent.xajax_chargeInfos('magasin',window.parent.xajax.getFormValues('formEtape1'));
	window.parent.afficheMagasin(id_magasin);
	window.parent.jumpToResa();
}
function SelectionneMagasinPourGroupe(id_magasin){
	window.parent.jQuery('select[name=id_magasin] > option[selected]').removeAttr('selected');
	window.parent.jQuery('select[name=id_magasin] > option[value='+id_magasin+']').attr('selected', 'selected');
}


function attachMessage(marker, html)  {
    var infowindow = new google.maps.InfoWindow(
      {content: html,
        maxWidth : 460
      });
  google.maps.event.addListener(marker, 'mouseover', function() {
    
    for (var l=0; l < (infowindows.length);l++) {
            infowindows[l].close();
    }
    infowindow.open(map,marker);
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
      google.maps.event.addListener(infowindow, 'closeclick', function() {
         var zoom1 = map.getZoom();
        map.fitBounds(bounds);
        map.setZoom(zoom1);
      });
  google.maps.event.addListener(map, 'zoom_changed', function() {
      infowindow.close();
    });
//  google.maps.event.addListener(map, 'center_changed', function() {
//      infowindow.close();
//    });

infowindows.push(infowindow);

}

//fonction callback apelé une fois que l'api est chargé et appelle en callback elle même la fonction qui va charger la map.
function loadMaps() {
  google.load("maps", "3",  {other_params:"sensor=false", "callback" : loadMap});
}

//chargement de l'api en de façon asyncrone
function initLoaderMap() {
  var script = document.createElement("script");
  script.src = "http://www.google.com/jsapi?callback=loadMaps";
  script.type = "text/javascript";
  document.getElementsByTagName("head")[0].appendChild(script);
}



 


function initLibTooltip() {


/**
 ************************** NOTE: V3 ONLY *********************
 * @name TipTool
 * @author Esa
 * @copyright (c) 2009 Esa I Ojala
 * @fileoverview TipTool is an extension to Gmaps api v3 for creating divs as custom tooltip assistants.
 * Facilities to attach TipTool to Markers. Control by mouseover/mouseout.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * @version 0.1
 * 0.1 first release
 */
var TIPTOOL_VERSION = "0.1";


/**
 * @constructor TipTool()
 * @extends OverlayView
 * @param {Map} map The map where the TipTool shall be overlayed
 * @param {LatLng} point The location where the TipTool shall be overlayed
 * @param {Object} opt_options Optional object.
 */
function TipTool(map, point, opt_options) {
  this.opts = opt_options || {};
  this.point = point;
  this.setMap(map);
  this.map = map;
};

//subclass of OverlayView()
TipTool.prototype = new google.maps.OverlayView();

/**
 * onAdd(). Called internally by API when added on map.
 * to be called just once
 */
TipTool.prototype.onAdd = function() {
  this.div_ = document.createElement('div');
  this.div_.style.position = "absolute";
  this.div_.style.overflow = "hidden";
  this.zIndex = this.opts.zIndex || 0;
  this.div_.className = this.opts.cssClass || this.opts.className || 'tiptool';
  this.div_.innerHTML = this.opts.html || "";
  google.maps.event.addDomListener(this.div_, "click", function(event) {
    google.maps.event.trigger(me, "click", event);
  });
  var panes = this.getPanes();
  var paneId = this.opts.pane || "floatPane";
  panes[paneId].appendChild(this.div_);
  this.opacity = this.opts.opacity * 1 || 1;
  this.div_.style.filter = 'alpha(opacity:' + this.opacity*100 + ')';
  this.div_.style.opacity = this.opacity;
}

/**
 * called internally by API when map moves.
 */
TipTool.prototype.draw = function() {
  var pixPoint = this.getProjection().fromLatLngToDivPixel(this.point);
  this.div_.style.left = pixPoint.x + 'px';
  this.div_.style.top = pixPoint.y + 'px';
  var SEx = pixPoint.x + this.div_.offsetWidth;
  var SEy = pixPoint.y + this.div_.offsetHeight;
  var pixSE = new google.maps.Point(SEx, SEy);
  this.opts.SE = this.getProjection().fromDivPixelToLatLng(pixSE);
  this.opts.point = this.point;
};

/**
 * Sets latLng position of tooltip
 * @param {LatLng} point The location where the TipTool shall be moved
 */

TipTool.prototype.setPosition = function(pint) {
  if(!this.div_) return false;
  this.point = pint;
  this.draw();
  return true
};
/**
 * Removes the div from DOM
 * @returns true if success, false if the div was not found
 */
TipTool.prototype.onRemove = function() {
  if(!this.div_) return false;
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
  return true;
};
/**
 * Sets the div display:none
 * @returns true if success, false if the div was not found
 */
TipTool.prototype.hide = function() {
  if(!this.div_) return false;
  this.div_.style.display = "none";
  return true;
};
/**
 * Sets the div display: block
 * @returns true if success, false if the div was not found
 */
TipTool.prototype.show = function() {
  if(!this.div_) return false;
  this.div_.style.display = "block";
  return true;
};

/**
 * Sets innerHTML of the div
 * @param {String}
 * @returns true if success, false if the div was not found
 */
TipTool.prototype.setContent = function(html) {
  if(!this.div_) return false;
  this.div_.innerHTML = html;
  return true;
};

/**
 * Copies properties of given options object to internal this.opts
 * @param optional object
 * @returns the updated internal this.opts object
 */
TipTool.prototype.props = function(options) {  // needs work for more properties
  var opts = options || {};
  for(var prop in opts){
    this.opts[prop] = opts[prop];
  }
  return this.opts;
};
/**
 * @returns The location of the div
 * @type LatLng object (null if the div was not found)
 */
TipTool.prototype.getPosition = function() {
  if(!this.div_) return null;
  return this.bounds_.getCenter();
};
/**
 * @returns True if TipTool is in viewport
 * @type boolean
 */
TipTool.prototype.isVisible = function() {
  var bounds = this.map.getBounds();
  var visible = (bounds.contains(this.opts.point) && bounds.contains(this.opts.SE));
  return visible;
};
/**
 * pans map to bring TipTool in viewport
 */
TipTool.prototype.bringVisible = function() {
  if(this.isVisible()){
    this.map.setCenter(this.map.getCenter());
  }else{
    this.map.panTo(this.opts.point);
  }
};



/**
 * attachTipTool() binds TipTool to a Marker
 * Creates an InfoWindow instance if it does not exist already
 * @extends Marker
 * @param InfoWindow options
 * @author Esa 2009
 */

google.maps.Marker.prototype.attachTipTool = function (html, opt_options){
  var map_ = this.getMap();
  var position = this.getPosition();
  map_.tiptool_ = map_.tiptool_ || new TipTool(map_, position, opt_options);  // todo
  google.maps.event.addListener(this, 'mouseover', function () {
    map_.tiptool_.setPosition(position);
    map_.tiptool_.setContent(html);
    map_.tiptool_.show();
    clearTimeout(map_.tiptool_.timer);
  });
  google.maps.event.addListener(this, 'mouseout', function () {
    clearTimeout(map_.tiptool_.timer);
    map_.tiptool_.timer = setTimeout(function(){
      map_.tiptool_.hide();
    }, 200);
  });
}

/**
 * accessTipTool()
 * @extends Map
 * @returns {TipTool} reference to the TipTool object instance
 * Creates an TipTool instance if it does not exist already
 */
google.maps.Map.prototype.accessTipTool = function (){  // needs work
  //this.tiptool_ = this.tiptool_ || new TipTool();
  //return this.tiptool_;
}

/////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * attachInfoWindow() binds InfoWindow to a Marker
 * Creates an InfoWindow instance if it does not exist already
 * @extends Marker
 * @param InfoWindow options
 * @author Esa 2009
 */

google.maps.Marker.prototype.attachInfoWindow = function (options){
  var map_ = this.getMap();
  map_.bubble_ = map_.bubble_ || new google.maps.InfoWindow();
  google.maps.event.addListener(this, 'click', function () {
    map_.bubble_.setOptions(options);
    map_.bubble_.open(map_, this);
  });
  map_.infoWindowClickShutter = map_.infoWindowClickShutter ||
  google.maps.event.addListener(map_, 'click', function () {
    map_.bubble_.close();
  });
}

/**
 * accessInfoWindow()
 * @extends Map
 * @returns {InfoWindow} reference to the InfoWindow object instance
 * Creates an InfoWindow instance if it does not exist already
 * @author Esa 2009
 */
google.maps.Map.prototype.accessInfoWindow = function (){
  this.bubble_ = this.bubble_ || new google.maps.InfoWindow();
  return this.bubble_;
}

}