//Variables globales
var map = null;
var geocoder = null;
var number = null;
var rootLink = null;
var dataFolder = null;
var recursiveSearch = null;
var polylines = new Array();
var refresh = true;
var contextPath = null;
var selectedName = null;
var selectedIndex = null;
var imgPath = null;
var arrayLink = '';
var arrayCount = 0;
var result_label_to_display = 'default';

// Retourne un marker
function createMarker(point, number, texte, imagepath, shadowpath, shadowIsDisabled, imageWidth, imageHeight, shadowWidth, shadowHeight,offsetWidth, offsetHeight) {
	
	var customImagePath = 'http://'+location.host+imagepath;
	var customShadowPath = 'http://'+location.host+shadowpath;
	
	/*if(number ==1 ){
		alert('imagePath = '+imagepath+' - customImagePath = '+customImagePath);
	}*/
	
	
	var customIcon = new GIcon(G_DEFAULT_ICON);
	customIcon.image = customImagePath;
	customIcon.shadow = customShadowPath;
	
	customIcon.iconSize = new GSize(parseFloat(imageWidth),parseFloat(imageHeight));
	customIcon.shadowSize = new GSize(parseFloat(shadowWidth),parseFloat(shadowHeight));
	
	/*if(number == '1'){
		alert(parseFloat(imageWidth));
		alert(parseFloat(imageHeight));
	}*/
	
	
	if(String(shadowIsDisabled) == 'true'){
		customIcon.shadow = '';
		customIcon.shadowSize = new GSize(parseFloat(imageWidth),parseFloat(imageHeight));
	}
	
	var anchorWidth = parseInt(imageWidth)/2+parseInt(offsetWidth);
	var anchorHeight = parseInt(imageHeight)+parseInt(offsetHeight);
	customIcon.iconAnchor  = new  GPoint(anchorWidth,anchorHeight);

	                
	// Set up our GMarkerOptions object
	markerOptions = { icon:customIcon };

	
	var marker = new GMarker(point, markerOptions);
	marker.value = number;
	// Ajoute un ecouteur sur le marker
	GEvent.addListener(marker, "click", function() {
		refresh = false;
		selectedName = $('marker[id=' + number + ']').attr('name');
		selectedIndex = number;
		map.openInfoWindowHtml(point, generatePopupInfo(number));
		displayInfos(number);
		refreshRightList();
		/*var top = document.getElementById('partner'+number).offsetTop - document.getElementById('div_locations').offsetTop;
		document.getElementById('div_locations').scrollTop = top ;*/
		var top = $('#partner'+number).offset().top - $('#div_locations').offset().top
		$('#div_locations').scrollTop(top);
		
	});
	return marker;
}

function getURLToDiplay(completeURL) {
	var regex = new RegExp("[H|h][T|t][T|t][P|p]([S|s]){0,1}://", "gim");
	return completeURL.replace(regex, '');
}

//generation du contenu de la popup
function generatePopupInfo(number) {
	var xml = $('marker[id=' + number + ']');

	var v_name = xml.attr('name');
	var v_adress = xml.attr('address');
	var v_code = xml.attr('cp');
	var v_city = xml.attr('city');
	var v_country = xml.attr('country');
	var v_email = xml.attr('email');
	var v_phone = xml.attr('telephone');
	var v_data = xml.attr('description');
	var v_fax = xml.attr('fax');
	var v_url = xml.attr('web');

	var myHtml = '';
	myHtml = '<div class="info_bulle">';
	myHtml += '<p class="name">' + v_name + '</p>';
		
	myHtml += '<div class="coord">';
	if ((v_adress != undefined && v_adress != '' && v_adress != ' ')
			|| (v_code != undefined && v_code != '' && v_code != ' ')
			|| (v_city != undefined && v_city != '' && v_city != ' ')
			|| (v_country != undefined && v_country != '' && v_country != ' ')) {
		myHtml += '<table><tr class="adress"><td class="picto">';
		myHtml += '<img src="' + imgPath + 'book_open.gif" alt="address"/>';
		myHtml += '</td><td class="value">';
		myHtml += v_adress + '<br/>' + v_code + '&nbsp;' + v_city + '<br/>'
				+ v_country;
		myHtml += '</td></tr></table>';
	}
	if (v_email != undefined && v_email != '' && v_email != ' ') {
		myHtml += '<table><tr class="email"><td class="picto">';
		myHtml += '<img src="' + imgPath + 'email_edit.gif" alt="email"/>';
		myHtml += '</td><td class="value">';
		myHtml += v_email;
		myHtml += '</td></tr></table>';
	}
	if (v_phone != undefined && v_phone != '' && v_phone != ' ') {
		myHtml += '<table><tr class="phone"><td class="picto">';
		myHtml += '<img src="' + imgPath + 'phone.gif" alt="phone"/>';
		myHtml += '</td><td class="value">';
		myHtml += v_phone;
		myHtml += '</td></tr></table>';
	}
	if (v_fax != undefined && v_fax != '' && v_fax != ' ') {
		myHtml += '<table><tr class="phone"><td class="picto">';
		myHtml += '<img src="' + imgPath + 'fax.gif" alt="phone"/>';
		myHtml += '</td><td class="value">';
		myHtml += v_fax;
		myHtml += '</td></tr></table>';
	}
	if (v_url != undefined && v_url != '' && v_url != ' ') {
		var urlToDisplay = getURLToDiplay(v_url);
		myHtml += '<table><tr class="url"><td class="picto">';
		myHtml += '<img src="' + imgPath + 'page_world.gif" alt="Url"/>';
		myHtml += '</td><td class="value">';
		myHtml += '<a target="_blank" href="' + v_url + '">' + urlToDisplay
				+ '</a>';
		myHtml += '</td></tr></table>';
	}
	myHtml += '</div>';
	if ((v_data != undefined && v_data != '' && v_data != ' ')) {
		myHtml += '<div class="data">' + v_data + '</div>';
	}
	myHtml += '</div>';


	return myHtml;
}

//Place les contours des departements sur la carte 
function showPolylines() {
	for ( var i = 0; i < polylines.length; i++) {
		var url = polylines[i];
		map.addOverlay(new GGeoXml(url));
	}
}

//Initialise la carte 
function initialize(servletContextPath, entriesFolder, recursiveFolder,
		polylines_array, jspContextPath, partenaire_label, forcedValue,
		forcedLatitude, forcedLongitude, forcedZoom, autoSearch) {

	if (GBrowserIsCompatible()) {
		rootLink = servletContextPath;
		dataFolder = entriesFolder;
		recursiveSearch = recursiveFolder;
		contextPath = jspContextPath;
		result_label_to_display = partenaire_label;
		imgPath = servletContextPath + '../../../../resources/images/';
		polylines = polylines_array;
		map = new GMap2(document.getElementById('map_canvas'));
		map.setCenter(new GLatLng(48.8948986, 2.2006881), 10);
		map.setUIToDefault();
		geocoder = new GClientGeocoder();
		updateDataEntries(true, forcedValue, forcedLatitude, forcedLongitude,
				forcedZoom,autoSearch );
		// $('#div_locations').css('height', $('#infoColumn').height());
		// Gestion du drag & drop de la carte
		GEvent.addListener(map, "moveend", function() {
			updateDataEntries(false, false, forcedLatitude, forcedLongitude,
					forcedZoom,autoSearch);
		});		
		
	}
}



//Fonction pour le champs de recherche
function showAddress(address,label) {
	if (geocoder) {
		geocoder.getLatLng(address, function(point) {
			if (!point) {
				if(label != null && label != '' && label != '??? partnermap.form.labelerror ???'){
					alert(address + ' ' + label);
				}else{
					alert(address + " not found");
				}
			} else {
				map.setCenter(point, 13);
			}
		});
	}
}

function centerMap(data) {
	var reg = new RegExp(
			"<initlng>(.*)</initlng><initlat>(.*)</initlat><initzoom>(.*)</initzoom>",
			"g");
	reg.exec(data);
	var initX = parseFloat(RegExp.$1);
	var initY = parseFloat(RegExp.$2);
	var initZoom = parseInt(RegExp.$3);
	//alert('initX = '+initX+'\ninitY = '+initY+'\ninitZoom = '+initZoom);
	if (initX != '' && initY != '' && initZoom != '' && !isNaN(initX)
			&& !isNaN(initY) && !isNaN(initZoom)) {
		map.setCenter(new GLatLng(initY, initX), initZoom);
	}
	//alert('fin centermap');
}

//affiche les infos associe a un marqueur
function displayInfos(number) {
	var myHtml = $("#partner" + number).clone();
	$("#partner" + number).remove();
	$('#div_locations').prepend(myHtml);
}



//Met a jour le XML en fonction de la zone visible de la carte
function updateDataEntries(init, forcedValue, forcedLatitude, forcedLongitude,
		forcedZoom, autoSearch) {
	//alert('search = '+search);
	if (refresh == false) {
		refresh = true;
	} else {
		//affiche l'image de chargement
		$('#loadingbox').css('display', 'block');
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var lngSpanWest = southWest.lng();
		var latSpanWest = southWest.lat();
		var lngSpanEast = northEast.lng();
		var latSpaneast = northEast.lat();
		if (init) {
			lngSpanWest = 0;
			latSpanWest = 0;
			lngSpanEast = 0;
			latSpaneast = 0;
		}
		var link = rootLink + "updateData.jsp?entriesFolder=" + dataFolder
				+ "&lngSpanWest=" + lngSpanWest + "&latSpanWest=" + latSpanWest
				+ "&lngSpanEast=" + lngSpanEast + "&latSpanEast=" + latSpaneast
				+ "&recursiveSearch=" + recursiveSearch + "&forcedValue="
				+ forcedValue + "&forcedLatitude=" + forcedLatitude
				+ "&forcedLongitude=" + forcedLongitude + "&forcedZoom="
				+ forcedZoom
				+ "&autoSearch="+autoSearch;

		$.get(link, function(data) {
			$('#partnermap_data').html(data);
			if (init == true || search == true) {
				centerMap(data);
				search = false;
//			} else {
			}
				refreshRightList();
				updateMarkers();
			//}
		});
	}
}

//Met a jour les markers contenu dans le XML, et les place sur la carte
function updateMarkers() {
	map.clearOverlays();
	showPolylines();
	var markers = document.getElementsByTagName('marker');
	number = markers.length;
	for ( var i = 0; i < markers.length; i++) {
		var point2 = new GLatLng(parseFloat(markers[i].getAttribute('y')),
								 parseFloat(markers[i].getAttribute('x')));
		map.addOverlay(createMarker(point2, 
									i + 1, 
									markers[i].getAttribute('description'),
									markers[i].getAttribute('image'),
									markers[i].getAttribute('shadow'),
									markers[i].getAttribute('shadow_disabled'),
									markers[i].getAttribute('image_width'),
									markers[i].getAttribute('image_height'),
									markers[i].getAttribute('shadow_width'),
									markers[i].getAttribute('shadow_height'),
									markers[i].getAttribute('offset_width'),
									markers[i].getAttribute('offset_height')
						));
	}
}

//Affiche les informations
function openInfo(number, lat, lng) {
	var content = $('#partner' + number + ' tbody');
	if (content.css('display') == 'none') {
		content.css('display', 'block');
		selectedName = $('marker[id=' + number + ']').attr('name');
		selectedIndex = number;
	} else
		content.css('display', 'none');
	refresh = false;
	map.openInfoWindowHtml(new GLatLng(parseFloat(lat), parseFloat(lng)),
			generatePopupInfo(number));
	refreshRightList();
}

//Met a jour la liste des resultats
function refreshRightList() {
	
	var html = '';
    
	var markerArray = document.getElementsByTagName('marker') ;
	
	$('#nbResults').html(markerArray.length + ' ' + result_label_to_display);
	
	var i = 1;
	for ( var i = 1; i <= markerArray.length; i++) {

		var xml = markerArray[i-1];

		var v_x = xml.getAttribute('x');
		var v_y = xml.getAttribute('y');
		var v_image = xml.getAttribute('image');
		var v_name = xml.getAttribute('name');
		var v_adress = xml.getAttribute('address');
		var v_code = xml.getAttribute('cp');
		var v_city = xml.getAttribute('city');
		var v_country = xml.getAttribute('country');
		var v_email = xml.getAttribute('email');
		var v_phone = xml.getAttribute('telephone');
		var v_data = xml.getAttribute('description');
		var v_fax = xml.getAttribute('fax');
		var v_url = xml.getAttribute('web');

		var myHtml = '';
		if (v_name == selectedName && v_name != '' && v_name != ' ' && selectedIndex==i) {
			myHtml = '<table class="partnerEntry partnerEntryOnMap" id="partner' + i + '">';
		} else {
			myHtml = '<table class="partnerEntry partnerEntryOnMapClosed" id="partner' + i + '">';
		}

		myHtml += '<thead><tr><th colspan="2" onclick="openInfo(\'' + i
				+ '\', \'' + v_y + '\',\'' + v_x + '\');">' + '<p><a id=\"idanchor'+i+'\" name=\"anchor'+i+'\"/>';
		if (v_image != undefined && v_image != '' && v_image != ' ') {
			myHtml += '<img src="' +  v_image
					+ '" alt="marker" title="' + v_name + '" /> ';
		}
		myHtml += v_name + '</p></th></tr></thead>';

		myHtml += '<tbody><tr><td class="coord">';

		myHtml += '<table cellspacing="0">';
		if ((v_adress != undefined && v_adress != '' && v_adress != ' ')
				|| (v_code != undefined && v_code != '' && v_code != ' ')
				|| (v_city != undefined && v_city != '' && v_city != ' ')
				|| (v_country != undefined && v_country != '' && v_country != ' ')) {
			myHtml += '<tr class="adress"><td class="picto">';
			myHtml += '<img src="' + imgPath + 'book_open.gif" alt="address"/>';
			myHtml += '</td><td class="value">';
			myHtml += v_adress + '<br/>' + v_code + '&nbsp;' + v_city + '<br/>'
					+ v_country;
			myHtml += '</td></tr>';
		}
		if (v_email != undefined && v_email != '' && v_email != ' ') {
			myHtml += '<tr class="email"><td class="picto">';
			myHtml += '<img src="' + imgPath + 'email_edit.gif" alt="email"/>';
			myHtml += '</td><td class="value">';
			myHtml += v_email;
			myHtml += '</td></tr>';
		}
		if (v_phone != undefined && v_phone != '' && v_phone != ' ') {
			myHtml += '<tr class="phone"><td class="picto">';
			myHtml += '<img src="' + imgPath + 'phone.gif" alt="phone"/>';
			myHtml += '</td><td class="value">';
			myHtml += v_phone;
			myHtml += '</td></tr>';
		}
		if (v_fax != undefined && v_fax != '' && v_fax != ' ') {
			myHtml += '<tr class="phone"><td class="picto">';
			myHtml += '<img src="' + imgPath + 'fax.gif" alt="fax"/>';
			myHtml += '</td><td class="value">';
			myHtml += v_fax;
			myHtml += '</td></tr>';
		}
		if (v_url != undefined && v_url != '' && v_url != ' ') {
			var urlToDisplay = getURLToDiplay(v_url);
			myHtml += '<tr class="url"><td class="picto">';
			myHtml += '<img src="' + imgPath + 'page_world.gif" alt="Url"/>';
			myHtml += '</td><td class="value">';
			myHtml += '<a target="_blank" href="' + v_url + '">' + urlToDisplay
					+ '</a>';
			myHtml += '</td></tr>';
		}
		myHtml += '</table>';

		// myHtml += '</td></tr><tr><td class="data">';

		// if(v_data!=undefined && v_data!='' && v_data!=' '){
		// myHtml += v_data.substring(0,180);
		// }

		myHtml += '</td></tr></tbody></table>';

		
		html = html + myHtml;
		
	}
	$('#div_locations').html(html);
	$('#loadingbox').css('display', 'none');
}

// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// Fonctions de calcul des g�olocalisations
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------

function calculCoordinateAddress(rootLink, address, resName, gallery, context,
		folder, multi) {
	var geocoder = new GClientGeocoder();
	var link = rootLink + 'calculGeomap.jsp?action=update&resource=' + resName
			+ '&gallery=' + gallery + '&multi=' + multi;
	if (geocoder) {
		geocoder
				.getLatLng(
						address,
						function(point) {
							if (point) {
								link += '&y=' + point.lat().toFixed(5) + '&x='
										+ point.lng().toFixed(5);
								if (multi) {
									$.ajax( {
												url : link,
												success : function(data,
														textStatus) {
													nbrRemainingCall -= 1;
													if (nbrRemainingCall == 0) {
														if (gallery == 'true')
															window.location = context + '/system/workplace/quickadmin/explorer_galleries.jsp?resource=/system/workplace/&mode=galleryview&quickadmintype=partnermapentry';
														else
															window.location = context + '/system/workplace/views/explorer/explorer_files.jsp?mode=explorerview';
													}
												},
												error : function(
														XMLHttpRequest,
														textStatus, errorThrown) {
													nbrRemainingCall -= 1;
													if (nbrRemainingCall == 0) {
														if (gallery == 'true')
															window.location = context + '/system/workplace/quickadmin/explorer_galleries.jsp?resource=/system/workplace/&mode=galleryview&quickadmintype=partnermapentry';
														else
															window.location = context + '/system/workplace/views/explorer/explorer_files.jsp?mode=explorerview';
													}
												}
											});

								} else {    //if !multi
									window.location = link;
								}
							} else { //if point == null
								if (multi) {
									nbrRemainingCall -= 1;
									if (nbrRemainingCall == 0) {
										if (gallery == 'true')
											window.location = context + '/system/workplace/quickadmin/explorer_galleries.jsp?resource=/system/workplace/&mode=galleryview&quickadmintype=partnermapentry';
										else
											window.location = context + '/system/workplace/views/explorer/explorer_files.jsp?mode=explorerview';
									}									
								}else{ //if !multi
									window.location = link;
								}
							}

						});
	} else {
		window.location = link;
	}
}

var nbrRemainingCall = 0;

function calculMassCoordinateAddress(rootLink, addressArray, resNameArray,
		gallery, context, folder) {
	var geocoder = new GClientGeocoder();
	nbrRemainingCall = addressArray.length;
	for ( var i = 0; i < addressArray.length; i++) {
		calculCoordinateAddress(rootLink, addressArray[i], resNameArray[i],
				gallery, context, folder, true);
	}
}

