// Paramètres
var largeurTraitsZB = 1;
var couleurZB = '#000000';
var largeurTraitsHighlight = 5;
var couleurHighlight = '#FF0000';

// Constantes
var COUCHE_POLY = 0;
var COUCHE_LIN = 1;
var COUCHE_PT = 2;

var OUTIL_ZOOM_IN = 0;
var OUTIL_ZOOM_OUT = 1;
var OUTIL_PAN = 2;
var OUTIL_GEOCODAGE = 7;
var OUTIL_MESURE_LONGUEUR = 8;
var OUTIL_MESURE_SURFACE = 9;
var OUTIL_IDENTIFICATION = 10;
var OUTIL_IMPRESSION = 11;

var imagesAPrecharger = new Array("images/icon_zoomin.png", "images/icon_zoomout.png", "images/icon_pan.gif", "images/geocodage.png",
	"images/longueur.bmp", "images/surface.bmp", "images/icon_info.png", "images/icon_print.gif");
var infoBulleImages = new Array("Zoom avant", "Zoom arrière", "Déplacement", "Rechercher une adresse", "Mesurer une longueur",
	"Mesurer une surface", "Identifier", "Imprimer");


// Déclarations, initialisations
var jg;
var x1 = 0;
var x2 = 0;
var y1 = 0;
var y2 = 0;
var dx = 0;
var dy = 0;
var coordx, coordy;

var afficherZB = false;
var afficherCroix = false;
var boutonEnfonce = false;

var outilEnCours = -1; // Valeur initiale récupérée à partir du champ hidden
var outils = new Array();

var images = new Array();

var pts = new Entite();
var highlight = new Entite();
var croixGeocod = new Entite();

var nbCarTitre = 0;
var nbCarSousTitre = 0;

function AffichagePage(on)
{
	var charg=(on ? "invisible" : "visible");
	var rub=(on ? "visible" : "invisible");

	document.getElementById('image_chargement').className = charg;
	document.getElementById('tr_vue_ensemble').className = rub;
	document.getElementById('tr_thematiques').className = rub;
	document.getElementById('tr_outils').className = rub;
	document.getElementById('tr_echelle').className = rub;
	document.getElementById('mainmap_layer_clip').className = rub;
	document.getElementById('mainmap_layer').className = rub;
	document.getElementById('tr_copyright').className = rub;
	document.getElementById('N').className = rub;
	document.getElementById('NE').className = rub;
	document.getElementById('NO').className = rub;
	document.getElementById('O').className = rub;
	document.getElementById('E').className = rub;
	document.getElementById('S').className = rub;
	document.getElementById('SE').className = rub;
	document.getElementById('SO').className = rub;
	document.getElementById('poignee').className = rub;
	if (document.getElementById('association'))
		document.getElementById('association').className = rub;
	if (document.getElementById('identification'))
		document.getElementById('identification').className = rub;
	if (!on)
	{
		document.getElementById('tr_geocodage').className = rub;
		document.getElementById('tr_impression').className = rub;
		document.getElementById('tr_mesures').className = rub;
	}
}

function Recentrer()
{
	document.carto_form.bRecentrer.value=1;
	Soumettre();
}

function Precedent()
{
	if(document.carto_form.bPrecedent.value == -1)
		return;
	else
		document.carto_form.bPrecedent.value=1;

	Soumettre();
}

function SelectionnerOutilParEmplacement(numEmplacement)
{
	outilEnCours = outils[numEmplacement];
	SelectionnerOutil();
	if (outilEnCours == OUTIL_GEOCODAGE)
	{
		var x = parseFloat(min_geo_x) + (echellex * largeurPix / 2);
		var y = parseFloat(min_geo_y) + (echelley * hauteurPix / 2);
		document.getElementById('iframeGeocodage').src = "indexGeocodage.php?x="+x+"&y="+y;
	}
}

function SelectionnerOutil()
{
	document.carto_form.outil.value = outilEnCours;
	Dessin();
	MAJOutils();
	MAJActions();
}

function MouseEntre(numEmplacement)
{
	if (outilEnCours != outils[numEmplacement])
		document.images["outil" + numEmplacement].className = "outilOver";
}

function MouseSort(numEmplacement)
{
	if (outilEnCours != outils[numEmplacement])
		document.images["outil" + numEmplacement].className = "outilNonSelectionne";
}

function AfficherMesure()
{
	longueur = pts.GetLongueur(x2, y2);
	if (longueur < 1000)
		texte = 'Longueur: ' + Math.round(longueur) + ' m';
	else
		texte = 'Longueur: ' + (Math.round(longueur / 10) / 100) + ' km';

	if ((outilEnCours == OUTIL_MESURE_SURFACE) && pts.saisieTerminee)
	{
		texte = '<table border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td>'+texte+'</td><td>';
		surface = pts.GetSurface();
		if (surface > 1000000)
			texte += 'Surface: ' + (Math.round(surface / 10000) / 100) + ' km²';
		else if (surface > 10000)
			texte += 'Surface: ' + (Math.round(surface / 100) / 100) + ' Ha';
		else
			texte += 'Surface: ' + Math.round(surface) + ' m²';
		texte += '</td></tr></table>';
	}
	document.getElementById('mesures').innerHTML = texte;
}


function MAJOutils()
{
	// Remplissage du tableau d'outils
	outils = new Array(OUTIL_ZOOM_IN, OUTIL_ZOOM_OUT, OUTIL_PAN, OUTIL_GEOCODAGE, OUTIL_IDENTIFICATION, OUTIL_MESURE_LONGUEUR, OUTIL_MESURE_SURFACE, OUTIL_IMPRESSION);

	// Affectation des outils
	for (i=0; i<outils.length; i++)
	{
		switch (outils[i])
		{
			case OUTIL_ZOOM_IN: 	numImage = 0; break;
			case OUTIL_ZOOM_OUT:	numImage = 1; break;
			case OUTIL_PAN:				numImage = 2; break;
			case OUTIL_GEOCODAGE:	numImage = 3; break;
			case OUTIL_MESURE_LONGUEUR: numImage = 4; break;
			case OUTIL_MESURE_SURFACE: numImage = 5; break;
			case OUTIL_IDENTIFICATION: numImage = 6; break;
			case OUTIL_IMPRESSION: numImage = 7; break;
		}

		nom = "outil"+i;
		document.images[nom].src = imagesAPrecharger[numImage];
		document.images[nom].title = infoBulleImages[numImage];
		document.images[nom].alt = infoBulleImages[numImage];
		if (outilEnCours == outils[i])
			document.images[nom].className = "outilSelectionne";
		else
			document.images[nom].className = "outilNonSelectionne";
	}
	for (i=outils.length; i<8; i++)
	{
		nom = "outil"+i;
		document.images[nom].className = "invisible";
	}
}


function MAJActions()
{
	document.getElementById('tr_geocodage').className = (outilEnCours == OUTIL_GEOCODAGE) ? "visible" : "invisible";
	document.getElementById('tr_mesures').className = ((outilEnCours == OUTIL_MESURE_LONGUEUR) || (outilEnCours == OUTIL_MESURE_SURFACE)) ? "visible" : "invisible";
	document.getElementById('tr_impression').className = (outilEnCours == OUTIL_IMPRESSION) ? "visible" : "invisible";

	pts.RAZ();
	if (outilEnCours == OUTIL_MESURE_LONGUEUR)
	{
		pts.typeCouche =  COUCHE_LIN;
		AfficherMesure();
		Dessin();
	}
	else if (outilEnCours == OUTIL_MESURE_SURFACE)
	{
		pts.typeCouche =  COUCHE_POLY;
		AfficherMesure();
		Dessin();
	}
	if (outilEnCours == OUTIL_IDENTIFICATION)
		document.getElementById('mainmap_layer').style.cursor = (document.all ? 'hand': 'pointer');
	else
		document.getElementById('mainmap_layer').style.cursor = 'default';
}


function Dessin()
{
	if (!jg) return;
	jg.clear();

	if (highlight.segsX.length > 0)
		highlight.Dessiner(jg, -1, -1);

	if (afficherCroix)
	{
		jg.setStroke(largeurTraitsZB);
		jg.setColor(couleurZB);
		jg.drawLine(x2 - 10, y2, x2 + 10, y2);
		jg.drawLine(x2, y2-10, x2, y2+10);
	}

	pts.Dessiner(jg, x2, y2);

	croixGeocod.Dessiner(jg, -1, -1);

	if (afficherZB)
	{
		jg.setStroke(largeurTraitsZB);
		jg.setColor(couleurZB);

		var _x1 = (x1 < x2 ? x1 : x2);
		var _y1 = (y1 < y2 ? y1 : y2);
		var _x2 = (x1 < x2 ? x2 : x1);
		var _y2 = (y1 < y2 ? y2 : y1);
		jg.drawRect(_x1, _y1, _x2-_x1, _y2-_y1);
	}

	jg.paint();
}


function SetZB()
{
	if ((x1 == x2) || (y1 == y2))
	{
		afficherZB = false;
		Dessin();
		return;
	}
	document.carto_form.zbx1.value = x1;
	document.carto_form.zby1.value = y1;
	document.carto_form.zbx2.value = x2;
	document.carto_form.zby2.value = y2;
	Soumettre();
}

function SubmitPan()
{
	if ((x1 == x2) && (y1 == y2))
		return;
	document.carto_form.panX.value = (largeurPix/2) - dx;
	document.carto_form.panY.value = (hauteurPix/2) - dy;
	Soumettre();
}

function Soumettre()
{
	AffichagePage(false);

	document.carto_form.submit();
}

function TestMaxCarTitre()
{
	elt = document.getElementById('titre');
	if ((elt.value.length == 30) && (nbCarTitre < 30))
		alert('Le nombre de caractères du titre est limité à 30.');
	nbCarTitre = elt.value.length;
}
function TestMaxCarSousTitre()
{
	elt = document.getElementById('soustitre');
	if ((elt.value.length == 30) && (nbCarSousTitre < 30))
		alert('Le nombre de caractères du titre est limité à 30.');
	nbCarSousTitre = elt.value.length;
}

function Start()
{
	var mainMapListener = new EventListener(DynAPI.document);

	//jg = new jsGraphics("mainmap_layer");
	jg = new jsGraphics("blank_layer");


	if (isNaN(largeurPix) || isNaN(hauteurPix) || isNaN(min_geo_x) || isNaN(min_geo_y) || isNaN(echellex) || isNaN(echelley))
		return '';

	images = new Array(imagesAPrecharger.length);
	for (i=0; i<imagesAPrecharger.length; i++)
	{
		images[i] = new Image();
		images[i].src = imagesAPrecharger[i];
	}

	outilEnCours = parseInt(document.forms[0].outil.value);
	SelectionnerOutil();
	if (outilEnCours == OUTIL_GEOCODAGE)
	{
		var x = parseFloat(min_geo_x) + (echellex * largeurPix / 2);
		var y = parseFloat(min_geo_y) + (echelley * hauteurPix / 2);
		document.getElementById('iframeGeocodage').src = "indexGeocodage.php?x="+x+"&y="+y;
	}

	croixGeocod.typeCouche = COUCHE_PT;

	if (document.carto_form.type_highlight.value != '')
	{
		highlight.largeurTraits = largeurTraitsHighlight;
		highlight.couleur = couleurHighlight;
		highlight.rayonPoints = 12;
		highlight.typeCouche = document.carto_form.type_highlight.value;
		highlight.fill = true;
		highlight.opacity = 40;

		var points = document.carto_form.coords_highlight.value.split(',');
		for (i=0; i<points.length; i++)
		{
			coords = points[i].split(' ');
			xGeo = coords[0];
			yGeo = coords[1];

			xPix = (xGeo - parseFloat(min_geo_x)) / echellex -1;
			yPix = hauteurPix - ((yGeo - parseFloat(min_geo_y)) / echelley) -1;
			highlight.AjoutPt(xPix, yPix, xGeo, yGeo);
		}
		if (highlight.typeCouche == COUCHE_POLY)
			highlight.TerminerSaisie();

		Dessin();
	}

	if(document.carto_form.bPrecedent.value == -1)
		document.getElementById('vuePrecedente').src = "images/vuePrecOff.png";
	else
		document.getElementById('vuePrecedente').src = "images/vuePrecOn.png";

	mainMapListener.onmousedown = function(e)
	{
		boutonEnfonce = true;
		x1 = x2;
		y1 = y2;
		dx = 0;
		dy = 0;

		afficherZB = (outilEnCours == OUTIL_ZOOM_IN);
		Dessin();

		return false;
	}

	mainMapListener.onmousemove=function(e)
	{
		var pixx, pixy;
		if (is.ie)
		{
			pixx = e.getPageX();
			pixy = e.getPageY();
		}
		else
		{
			pixx = e.getPageX() - DynAPI.document.all.mainmap_layer.getPageX();
			pixy = e.getPageY() - DynAPI.document.all.mainmap_layer.getPageY();
		}
		pixy = hauteurPix - pixy;
		if (is.ie)
		{
			pixx -= (document.all ? document.body.scrollLeft : window.pageXOffset);
			pixy += (document.all ? document.body.scrollTop : window.pageYOffset);
		}

		coordx = parseFloat(min_geo_x) + (echellex * pixx);
		coordy = parseFloat(min_geo_y) + (echelley * pixy);

		var x2prec = x2;
		var y2prec = y2;
		x2 = pixx;
		y2 = hauteurPix - pixy;

		document.getElementById('idCoordonneeX').innerHTML = 'x='+Math.round(coordx);
		document.getElementById('idCoordonneeY').innerHTML = 'y='+Math.round(coordy);

		IB_TestPolygones(x2, y2);

		switch (outilEnCours)
		{
			case OUTIL_ZOOM_IN:
				if (x2 < 0) x2 = 0;
				if (x2 > largeurPix) x2 = largeurPix;
				if (y2 < 0) y2 = 0;
				if (y2 > hauteurPix) y2 = hauteurPix;
				if (boutonEnfonce)
					Dessin();
				break;

			case OUTIL_PAN:
				if (!boutonEnfonce)
					return;

				var ddx, ddy;
				if (is.ie) {
					ddx = x2 - x1; ddy = y2 - y1;
				}
				else {
					ddx = x2 - x1; ddy = y2 - y1;
//						ddx = x2 - x2prec; ddy = y2 - y2prec;
				}
				dx += ddx;
				dy += ddy;
				DynAPI.document.all['mainmap_layer'].moveBy(ddx, ddy);

				document.getElementById('mainmap_layer_clip').style.backgroundImage="";

				if ((x1 + dx < 0) || (x1 + dx > largeurPix) || (y1 + dy < 0) || (y1 + dy > hauteurPix))
				{
					boutonEnfonce = false;
					Soumettre();
				}
				break;

			case OUTIL_MESURE_LONGUEUR :
				if (pts.saisieEnCours)
				{
					AfficherMesure();
					Dessin();
				}
				break;

			case OUTIL_MESURE_SURFACE :
				if (pts.saisieEnCours)
				{
					AfficherMesure();
					Dessin();
				}
				break;
		}
	}


	mainMapListener.onmouseup = function(e)
	{
		if (!boutonEnfonce)
			return;
		boutonEnfonce = false;
		afficherZB = false;

		switch(outilEnCours)
		{
			case OUTIL_ZOOM_IN:
				SetZB();
				break;

			case OUTIL_ZOOM_OUT:
				if(x2!=0)
				{
					document.carto_form.mainmap_x.value = x2;
					document.carto_form.mainmap_y.value = y2;
					afficherCroix = true;
					Dessin(x2, y2);
				}
				Soumettre();
				break;

			case OUTIL_PAN:
				SubmitPan();
				break;

			case OUTIL_MESURE_LONGUEUR:
			case OUTIL_MESURE_SURFACE:
			  pts.saisieEnCours = true;
				pts.MouseClick(x2, y2, coordx, coordy);
				AfficherMesure();
				Dessin();
				break;

			case OUTIL_IDENTIFICATION:
				document.carto_form.mainmap_x.value = coordx;
				document.carto_form.mainmap_y.value = coordy;
				Soumettre();
				break;
		}
	}

	mainMapListener.onmouseout=function(e)
	{
		if (boutonEnfonce)
		{
			boutonEnfonce = false;
			if (outilEnCours == OUTIL_ZOOM_IN)
				SetZB();
			else if (outilEnCours == OUTIL_PAN)
				SubmitPan();
		}
	}

	mainMapListener.onclick=function(e)
	{
		e.browserReturn=false;
	}

	mainMapListener.ondblclick=function(e)
	{
		if (((outilEnCours == OUTIL_MESURE_LONGUEUR) && (pts.segsX.length >= 2)) ||
			(((outilEnCours == OUTIL_MESURE_SURFACE) && (pts.segsX.length >= 3))))
		{
			pts.TerminerSaisie();
			AfficherMesure();
			Dessin();
		}
	}

	DynAPI.document.all['mainmap_layer_clip'].addEventListener(mainMapListener);



	var overviewListener = new EventListener(DynAPI.document);
	overviewListener.onclick=function(e)
	{
		if (is.ie)
		{
			overviewPixX = e.getPageX();
			overviewPixY = e.getPageY();
		}
		else
		{
			overviewPixX = e.x;
			overviewPixY = e.y;
		}

		document.carto_form.overview_x.value = overviewPixX;
		document.carto_form.overview_y.value = overviewPixY;
		Soumettre();
	}
	DynAPI.document.all['overview'].addEventListener(overviewListener);


	AffichagePage(true);
	return true;
}

function Imprimer()
{
	if ((document.getElementById('titre').value == '') && (document.getElementById('soustitre').value != '')) {
		alert('Pour afficher un sous-titre, veuillez indiquer un titre, SVP.'); return false;
	}
	return true;
}