/*
 * contact.js
 * js de la section contact, comprenant la google map
 * simon - egzakt.com
 * 2009-03-04
 */

// Config


// Variables GMap
var map;
var directionsPanel;
var directions;
var cadIcon;
var geo;

var res = new Object();		// resultat par defaut

function loadMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"),{size: new GSize(723,390)});
		
		var cadPoint1 = new google.maps.LatLng(parseFloat(default_lat),parseFloat(default_lon));		// Default
		var centre = new GLatLng(cadPoint1.lat(), cadPoint1.lng());
		map.setCenter(centre, default_zoom);
		
		map.setMapType(G_NORMAL_MAP);
		map.addControl(new GSmallZoomControl());
		map.addControl(new GMapTypeControl());
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		//map.enableScrollWheelZoom();
		
		myKBHandler = new GKeyboardHandler(map);
		
		directionsPanel = document.getElementById("directions");
		directions = new GDirections(map, directionsPanel);
		
		GEvent.addListener(directions, "load", onGDirectionsLoad);

		geo = new GClientGeocoder();
	}
}


function getDirections_init(a,from,to) {
	if (!a)
		return false;
	if (!from) {
		return code_postal_erreur();
	}
	if (!to) {
		return false;
	}
	getDirections(from,to);
	$('#storeslist .store').removeClass('storeselected');
	$(a).addClass('storeselected');
	return code_postal_corrige();
}

function getDirections(from,to){
	dirString = "from: "+from+" to: " + to;
	directions.load(dirString);
}

function onGDirectionsLoad(){
	document.getElementById("directions").style.display = "block";
	map.setMapType(G_NORMAL_MAP);
}

function onGDirectionsError(){
	$("#directions").show();
	//console.log(directions.getStatus());
}

function getPostalCodeLatLon(f,postal) {
	geo.getLatLng(postal, function(point){
		if (!point){
			res.message = erreur_code_postal;
			code_postal_erreur();
			return axerror(res);
		}else{
			return searchstores(f,point);
		}
	});
}

// Selectionner un magasin a partir du code
function selectstorebycode(a) {
	axloading(true);
	$.ajax({
		type: "POST",
		url: $(a).attr('href')+'ax/',
		data: '',
		dataType: "json",
		//async: true,
		success: function(resultat){
			if (!resultat.erreur) {
				var no_distance = resultat.GeoLatitude==''||resultat.GeoLongitude=='';
				clearresults();						// vider le container (div#storelist), les markers, les directions
				printstore(resultat,no_distance);	// afficher le magasin (div.store)
				if (no_distance == false) {
					positionstore(resultat);// mettre le marker sur la gmap
					centerstoresmap(resultat,12);		// centrer la carte sur le resultat
				}
				selectstorevalue(resultat);			// afficher le magasin dans le bon faux select (selectqcstores/selectmastores)
				code_postal_corrige();
				axloading(false);
			} else {
				code_postal_erreur();
				return axerror(resultat);
			}
		},
		error: function(resultat){
			return axerror(resultat);
		}
	});
	return false;
}

// Afficher un magasin
function printstore(resultat,no_distance) {

	var store_id = 'store_'+resultat.IdStore;
	$('#storedefault').clone().appendTo('#storeslist');
	$('#storeslist').children('.store:last').attr('id',store_id)
	
	//$('#storeslist').children('.store')[0].id = store_id;
	$('#'+store_id).children('.name').html(resultat.StoreName);
	$('#'+store_id).children('.address').html(resultat.StoreAddress+' ');		// ' ' Bug IE6
	$('#'+store_id).children('.city').html(resultat.StoreCity+', ');
	$('#'+store_id).children('.state').html(resultat.StoreState+' ');
	$('#'+store_id).children('.postalcode').html(resultat.StorePostal+' ');
	$('#'+store_id).children('.phone').children('.value').html(resultat.StorePhone);
	$('#'+store_id).children('.fax').children('.value').html(resultat.StoreFax);
	if (resultat.StoreHours) {
		$('#'+store_id).children('.hours').children('.value').html(resultat.StoreHours);
	} else {
		$('#'+store_id).children('.hours').hide();
	}
	
	if (resultat.distance)
		$('#'+store_id).children('.distance').html(parseInt(resultat.distance)+" km").show();

	if (no_distance == false) {
		$('#'+store_id).click(function () { return getDirections_init(this,$('#codepostal').val(),resultat.StorePostal); });
	} else {
		$('#'+store_id).click(function () { return false; });
		$('#'+store_id).addClass('store_no_distance');
	}
	
	$('#'+store_id).show();
	$('#stores').show();
}


// Positionner le magasin sur la carte
function positionstore(resultat) {
	// Positionnement du point
	if (Math.abs(parseFloat(resultat.GeoLatitude)) > 0) {
		var cadPoint = new google.maps.LatLng(parseFloat(resultat.GeoLatitude),parseFloat(resultat.GeoLongitude));
	
		//marker = new GMarker(cadPoint);
		//map.addOverlay(marker);

		marker = new PdMarker(cadPoint);
		if (parseInt(resultat.distance) > 0) {
			marker.setTooltip(resultat.StoreName+"<br />("+parseInt(resultat.distance)+" km)");
		} else {
			marker.setTooltip(resultat.StoreName);
		}
		marker.onClick = function() {
			$("#"+resultat["StorePath_"+langue]).click();
		}
		//var html = resultat.StoreName+"<br />"+resultat.StoreAddress+"<br />"+resultat.StoreCity+" ("+resultat.StoreState+")"+"<br />"+resultat.StorePostal+"<br />"+resultat.StorePhone+"<br />"+resultat.StoreFax;
		//marker.setDetailWinHTML(html);
		//marker.setHoverImage("http://www.google.com/mapfiles/dd-start.png");
		map.addOverlay(marker);
	}
}


// Changer la valeur du select
function selectstorevalue(resultat) {
	// Changer la valeur du (faux) select
	selectstorevaluedefault();
	if (resultat.IdState == 1) {
		$('#selectqcstores .selection a.action').html(resultat.StoreName);
	} else {
		$('#selectmastores .selection a.action').html(resultat.StoreName);
	}
}

function selectstorevaluedefault() {
	// Changer la valeur du (faux) select
	$('.selectbycategory .selection a.action').html(default_selectstores_val);
}



// Chercher les magasins
function searchstores_init(f,postal) {
	axloading(true);
	return getPostalCodeLatLon(f,postal);
}

function searchstores(f,point) {
	if (!point) {
		res.message = erreur_code_postal;
		return axerror(res);
	}
	$.ajax({
		type: "POST",
		url: f.action+'ax/',
		data: 'geolat='+point.lat()+'&geolng='+point.lng(),
		dataType: "json",
		//async: true,
		success: function(resultat){
			if (!resultat.erreur) {
				clearresults();
				printstores(resultat);
				code_postal_corrige();
				axloading(false);
			} else {
				return axerror(resultat);
			}
		},
		error: function(resultat){
			return axerror(resultat);
		}
	});
	return false;
}

function loadstores(f) {
	$.ajax({
		type: "POST",
		url: f.action+'ax/',
		data: 'geolat=&geolng=',
		dataType: "json",
		//async: true,
		success: function(resultat){
			if (!resultat.erreur) {
				clearresults();
				printstores(resultat,true); // true indique qu'on est sur le load
				code_postal_corrige();
				axloading(false);
			} else {
				return axerror(resultat);
			}
		},
		error: function(resultat){
			return axerror(resultat);
		}
	});
	return false;
}

// Afficher des magasins
function printstores(resultat,load) {

	selectstorevaluedefault();
	
	for (store in resultat) {
		resultat[store];
		if (!load) {
			printstore(resultat[store],false);	// false : la requete retourne toujours les magasins avec une distance
		}
		positionstore(resultat[store]);		// mettre le marker sur la gmap
	}
	
	//centerstoresmap(resultat[store]);	// centrer la map sur le premier resultat
}


// Center the map
function centerstoresmap(resultat,zoom) {
	var cadPoint = new google.maps.LatLng(parseFloat(resultat.GeoLatitude),parseFloat(resultat.GeoLongitude));
	var centre = new GLatLng(cadPoint.lat(), cadPoint.lng());
	
	map.setCenter(centre, zoom ? zoom : default_zoom);
}


// Vider les resultats
function clearresults() {
	$('#storeslist').children().remove();
	$('#directions').hide();
	directions.clear();
	map.clearOverlays();
}

// Ajout au document_ready (voir la documentready.js)
function document_ready_store() {
	$('#stores').hide();
	$('.selectbycategory .selcategories a').click(function() {
			$('.selectbycategory .selcategories').hide();
		return selectstorebycode(this);
	});
	loadMap();
	
		// Recherche par code postal
	$('#fsearchstore').submit(function() {
		searchstores_init(this,$('#codepostal').val());
		return false;
	});
	
	// Recherche venant d'une autre section, afficher la page de resultats
	if (startOnloadSearch && document.fsearchstore) {
		if ($('#codepostal').val() != "")
			searchstores_init(document.fsearchstore,$('#codepostal').val());
	}
	
	// On place les points sur la map
	loadstores($('#fsearchstore')[0]);
}

// Erreur de code postal
function code_postal_erreur() {
	$('#fsearchstore .searchbykeyword h4').addClass('erreur').next().addClass('erreur');
	$('#codepostal').addClass('erreur');
	return false;
}
function code_postal_corrige() {
	$('#fsearchstore .searchbykeyword h4').removeClass('erreur').next().removeClass('erreur');
	$('#codepostal').removeClass('erreur');
	return true;
}