/*****************************************************************************
 * MADITUC
 *
 *****************************************************************************/

var madDeltaAjax = 500;
var madResultatRechercheMax = 70;
var madClicCarte = null;

var attenteReponse = 0;
var usager_id=0;
var trajetActif = null;

var madPrevSearch = null;
var browserHeight = null;
var browserWidth = null;

function majFenetre() {
	if (parseInt(navigator.appVersion)>3) {
	 if (navigator.appName=="Netscape") {
	  browserWidth = window.innerWidth;
	  browserHeight = window.innerHeight;
	 }
	 if (navigator.appName.indexOf("Microsoft")!=-1) {
	  browserWidth = document.body.offsetWidth;
	  browserHeight = document.body.offsetHeight;
	 }
	}
	//alert(browserHeight);
	//alert(browserWidth);
}

function madPosition() {
	majFenetre();
	var maHauteurO1 = Math.max(browserHeight-160,35);
	var maHauteurD1 = Math.max(browserHeight-210,35);
	$('search-results-o').style.height=maHauteurO1+'px';
	$('search-results-d').style.height=maHauteurD1+'px';

	var maHauteur2 = Math.max(browserHeight-215,100);
	//alert(maHauteur1);	
	var maHauteurC = Math.max(browserHeight-80,225);
	var maLargeurC = Math.max(browserWidth-435,438);
	$('madCorps2').style.height=maHauteur2+'px';
	if (madNsageo) {
		$('zonecarto').style.height=maHauteurC+'px';
		$('zonecarto').style.width=maLargeurC+'px';
	}
	var monTopP = Math.max(browserHeight-62,500);
	$('enpied').style.top=monTopP+'px';
}


/**
 * Source: Prototype-un.quatre.zero
 */
function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++)   {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}

function madInit(f) {
  toggleOnglet(0);
  madPosition();
  madZapLocal('o');
  madZapLocal('d');
  var now = new Date();
  now.setTime(now.getTime()+(5 * 60 * 1000));
  var nMaintenant = now.getHours();
  if (nMaintenant<3) {
    nMaintenant = nMaintenant+24;
  }
  $('hdep1').selectedIndex = nMaintenant-3;
  
  nMaintenant = now.getMinutes();
  nMaintenant = Math.floor(nMaintenant/5);
  $('hdep2').selectedIndex = nMaintenant;


  if (f==1) {
	  $('madLignes').innerHTML='';
	  Move(295932,5040550,64,0);
	  ChangeMode(0);
	  RemoveLabel();
	  envoyerEndPos(0,0);
	  envoyerStartPos(0,0);
	  $('madCorps2').style.display = 'none';  
	  $('madCorps2').innerHTML='';
	  $('madCorps2').scrollTop=0;
	  $('madForm').deparr[0].checked=true;

	  now.setTime(now.getTime()-(185 * 60 *1000));
	  var jourText = now.getDate()+'';
	  var moisText = (now.getMonth()+1)+'';
	  var dateText = now.getYear()+'.'+pad(moisText,2,'0',STR_PAD_LEFT)+'.'+pad(jourText,2,'0',STR_PAD_LEFT);
	  for (var i=0; i<$('jour').length; i++) {
	    if ($('jour').options[i].value==dateText) {
		$('jour').selectedIndex = i;
	    }
	  }

	  $('pmarc').checked=false;
	  $('ptrans').checked=false;
	  $('umetro').checked=true;
	  $('utrain').checked=false;
  }
}

function toggleOnglet(i) {
  if (i==0) {
    $('boutononglet1').style.background='mediumblue';
    $('boutononglet1').style.color='white';
    $('boutononglet2').style.color='black';
    $('boutononglet2').style.background='white';
    $('onglet1').style.display='block';
    $('onglet2').style.display='none';  
  }
  if (i==1) {
    $('boutononglet2').style.background='mediumblue';
    $('boutononglet1').style.color='black';
    $('boutononglet2').style.color='white';
    $('boutononglet1').style.background='white';
    $('onglet2').style.display='block';
    $('onglet1').style.display='none';
  }
}

function toggleParcours(i) {
  toggleOnglet(1);
  if (i==0) {
    if (!(null === $('divtrj0'))) {
    $('divtrj0').style.display='block';
    $('madLC0').style.background='mediumblue';
    $('madLC0').style.color='white';
    }
    if (!(null === $('divtrj1'))) {
    $('divtrj1').style.display='none';
    $('madLC1').style.background='white';
    $('madLC1').style.color='black';
    }
    if (!(null === $('divtrj2'))) {
    $('divtrj2').style.display='none';
    $('madLC2').style.background='white';
    $('madLC2').style.color='black';
    }
  }
  if (i==1) {
    if (!(null === $('divtrj0'))) {
    $('divtrj0').style.display='none';
    $('madLC0').style.background='white';
    $('madLC0').style.color='black';
    }
    if (!(null === $('divtrj1'))) {
    $('divtrj1').style.display='block';
    $('madLC1').style.background='mediumblue';
    $('madLC1').style.color='white';
    }
    if (!(null === $('divtrj2'))) {
    $('divtrj2').style.display='none';
    $('madLC2').style.background='white';
    $('madLC2').style.color='black';
    }
  }
  if (i==2) {
    if (!(null === $('divtrj0'))) {
    $('divtrj0').style.display='none';
    $('madLC0').style.background='white';
    $('madLC0').style.color='black';
    }
    if (!(null === $('divtrj1'))) {
    $('divtrj1').style.display='none';
    $('madLC1').style.background='white';
    $('madLC1').style.color='black';
    }
    if (!(null === $('divtrj2'))) {
    $('divtrj2').style.display='block';
    $('madLC2').style.background='mediumblue';
    $('madLC2').style.color='white';
    }
  }
  $('madCorps2').scrollTop = 0;  
}

/**
 * Affiche du texte informatif
 * @param (string) t Texte à afficher 
 */
function madDialogueOn(t) {
  $('madDialogue').innerHTML=t;
}


/**
 * Efface le texte informatif
 */
function madDialogueOff() {
  $('madDialogue').innerHTML='';
}


/**
 * Calcul la difference entre deux heures
 * @param (int) h1
 * @param (int) h2
 * @return Int 
 */
function heureDiff(h1,h2) {

  dep = new Date( );
  arr = new Date( );

  if (h1.length==3) 
  {
    dep.setHours(h1.substr(0,1));
    dep.setMinutes(h1.substr(1,2));
  } 
  else 
  {
    dep.setHours(h1.substr(0,2));
    dep.setMinutes(h1.substr(2,2));
  }

  if (h2.length==3) 
  {
    arr.setHours(h2.substr(0,1));
    arr.setMinutes(h2.substr(1,2));
  } 
  else 
  {
    arr.setHours(h2.substr(0,2));
    arr.setMinutes(h2.substr(2,2));
  }

  return (arr.getTime() - dep.getTime()) / (1000*60);
}


/**
 * Heure en texte
 * @pars h Int
 * @return String
 */
function heureTexte(h) 
{
  if (h.length==2) 
  {
    return '00h'+h.substr(0,2);
  } 
  else if (h.length==3) 
  {
    return '0'+h.substr(0,1)+'h'+h.substr(1,2);
  } 
  else 
  {
    if (h.substr(0,2)>=24) 
    {
      var hh = h.substr(0,2)-24;
      return '0'+hh+'h'+h.substr(2,2);
    } 
    else 
    {
      return h.substr(0,2)+'h'+h.substr(2,2);
    }    
  }
}


/**
 * Determine si un object est nul
 * @pars a 
 * @return Bool
 */
function isNull(a) 
{
    return typeof a == 'object' && !a;
}


/**
 * Active/desactive la banniere attenteTxt
 * @pars p 
 */
function waitTxt(p) 
{
  var oWait = $('waitTxt');
  if (p=='on' && oWait.style.display == 'none') 
  {
    if (oWait) 
    {
      oWait.style.display = 'block';
    }
  } 
  else 
  {
    oWait.style.display = 'none';
  }
}

/**
 * Active/desactive la banniere attenteRecherche
 * @pars p 
 */
function waitRecherche(p) 
{
  var oWait = $('waitRecherche');
  if (p=='on' && oWait.style.visibility == 'hidden') 
  {
    if (oWait) 
    {
      oWait.style.visibility = 'visible';
    }
  } 
  else 
  {
    oWait.style.visibility = 'hidden';
  }
}


//MADITUC {


function madNetPart (t) 
{

  var argv = madNetPart.arguments;
  var argc = argv.length;


  if (argc==2) 
  {
    if (!(t=='BOULEVARD' || t=='MONTEE DE LIESSE')) 
    {
      t = madNetPartTyp(t);
    }
    t = madNetPartDir(t);
    t = madNetPartNum(t);
  }

  t = madNetPartPre(t);
    
    if (t.length==0) 
    {
      t = '%';
    }
    
    return t;

}


/**
 * Enlève la direction dans une chaîne caractères
 * @pars t string
 * @return string
 */
function madNetPartDir (t) 
{
    t = t.replace(/\s(NORD|SUD|EST|OUEST|NORTH|SOUTH|EAST|WEST)$/,'');
    return t;
}


/**
 * Enlève le préfixe dans une chaîne caractères
 * @pars t string
 * @return string
 */
function madNetPartPre (t) 
{

    t = t.replace("’","'");
    t = t.replace(/^(DE L'|D'|L')/,'');
    t = t.replace(/^(DE LA|DE L'|DES|THE|LA|DE|DU|D'|L'|)\s/,'');
    return t;

}


/**
 * Enlève le type de rue dans une chaîne caractères
 * @pars t string
 * @return string
 */
function madNetPartTyp (t) 
{

    t = t.replace(/^(RUE|AVENUE|BOULEVARD|AV|AVE|BOUL|PLACE|PROM|TERRASSE|TERR|AUT|CH|CHEMIN|AUTOROUTE|CR|CROISSANT|JAR|JARDIN|MTEE|MONTEE|PL|PROM|PROMENADE|RLLE|RUELLE|RUEL|VOIE)\s/,'');
    t = t.replace(/\s(RUE|RU|AVENUE|AV|AVE|STREET|BLVD|DRIVE|ST|AVENUE|AVE|CIRCLE|GARDEN)$/,'');
    return t;

}


/**
 * Enlève le type de rue dans une chaîne caractères
 * @pars t string
 * @return string
 */
function madNetPartNum (t) 
{

    //t = t.replace(/^\d{1,3}(E)/,t.substring(0,t.length-1));
    //t = t.replace(/^\d{1,3}(RE|ST|ND|RD|TH)/,t.substring(0,t.length-2));
    t = t.replace(/^\d{1,3}(E)/,t.substring(0,t.indexOf('E')));
    t = t.replace(/^\d{1,3}(RE|RD)/,t.substring(0,t.indexOf('R')));
    t = t.replace(/^\d{1,3}(ST)/,t.substring(0,t.indexOf('S')));
    t = t.replace(/^\d{1,3}(ND)/,t.substring(0,t.indexOf('N')));
    t = t.replace(/^\d{1,3}(TH)/,t.substring(0,t.indexOf('T')));
    return t;

}


/**
 * Valide le texte fourni par l'usager pour effectuer la bonne recherche AJAX
 * @pars t
 * @pars l
 */
function validLocal(t,l) {
  var typeRecherche = null;

  if (madPrevSearch == t) {
  
  } else {
  
  madPrevSearch = t;

  if (t.length==0 && $('search-results-'+l).style.display=='block') {
      $('search-results-'+l).innerHTML = aideRecherche;
      //$('search-results-'+l).style.display = 'block';
      //selectIEBug(0);
    return;
  }

  t = t.toUpperCase();
  
  if (t.indexOf('(')>0) {
    t = t.substring(0,t.indexOf('('));
  }
  
  t = t.replace(/É|Ë|Ê|È/g,'E');
  t = t.replace(/Â|À/g,'A');
  t = t.replace(/Î|Ï/g,'I');
  t = t.replace("Ô",'O');
  t = t.replace("Ù",'U');
  t = t.replace("Ç",'C');
  t = t.replace("’","'");
  t = t.replace(/\s$/,'');
  t = t.replace(/^\s/,'');

  t = t.replace(/-|"/g,' ');
  t = t.replace(/\./g,'');

  t = t.replace(/^(SAINTE|SAINT|STE|ST)\s/,'S. ');
  t = t.replace(/\x2F(SAINTE|SAINT|STE|ST)\s/,'/S. ');
  t = t.replace(/\s(SAINTE|SAINT|STE|ST)\s/g,' S. ');

   var a = t.split(/ ET |\//);
  var b = t.split(',');
  t = t.replace(/,/g,'');
  var c = t.split(' ');

  if (a.length == 2) {
    if (a[0].length>2 || a[0]>0) {
      t = madNetPart(a[0].replace(/ $/g,''),1)+'/'+madNetPart(a[1].replace(/ $/g,''),1);
      typeRecherche = 'int';
    }
  }

  if (b.length == 2) {
    if (b[0]>200000 && b[0]<400000 && b[1]>5000000 && b[1]<6000000) {
      //madDialogueOn('coordonnées');
      typeRecherche = 'cxy';
      t = b[0]+','+b[1];
    } else {
      t = t.replace(/,/g,'');
      c = t.split(' ');
    }
  }

  // ACCEPTE un générateur style 'POLYTECHNIQUE EDIFICE PRINCIPAL [UNIVERSITE], 2500, ch. de Polytechnique (Montréal)'
  if (b.length > 1 && !(b[0]>0)) {
    c = b[0].split(' ');
    t = b[0].replace(/,/g,'');
  }

  if (t.length==6 && /\D\d\D\d\D\d/.test(t)) {
      typeRecherche = 'cod';
  }
  

  if (c.length>1) {

    if (c[0]>0 && c[1].length>1 && typeRecherche == null) {
      //madDialogueOn('recherche d\'adresse');
      typeRecherche = 'adi';
      t = c[0]+' '+madNetPart(t.substring(t.indexOf(' ')+1),1);
    }

    if (c[0] == 'METRO' && c[1].length>0) {
      //madDialogueOn('recherche de station de métro');
      typeRecherche = 'met';
      t = c[0]+' '+madNetPart(t.substring(t.indexOf(' ')+1));
    }

    if (c[0] == 'GARE' && c[1].length>0) {
      //madDialogueOn('recherche de gare de train');
      typeRecherche = 'gar';
      t = t.replace(/\//,'/ ');
      t = c[0]+' '+madNetPart(t.substring(t.indexOf(' ')+1));
    }

    if (c[0] == 'ARRET' && c[1]>9999 && c[1]<1000000 && c[1].length == 5) {
      //madDialogueOn('recherche de gare de train');
      typeRecherche = 'aut';
      t = c[1];
    }
    
    if (c[0].length==3 && c[1].length==3) {
      //madDialogueOn('recherche d\'adresse');
      typeRecherche = 'cod';
      t = c[0]+c[1];
    }
    

    if (c[0].length>1 && c[1].length>0 && typeRecherche == null) {
      //madDialogueOn('recherche de générateur');
      typeRecherche = 'gen';
      t = madNetPart(t);
    }
  } else {

    if (c[0] == 'METRO') {
      t = c[0]+' %';
      typeRecherche = 'met';
    }

    if (c[0] == 'GARE') {
      t = c[0]+' %';
      typeRecherche = 'gar';
    }
  
    if (c[0].length>1 && !(c[0]>0) && typeRecherche == null) {
      //madDialogueOn('recherche de générateur');
      typeRecherche = 'gen';
      t = madNetPart(t);
    }
    if (c[0]>9999 && c[0]<1000000 && c[0].length == 5 ) {
      //madDialogueOn('recherche numéro AUTOBUS');
      typeRecherche = 'aut';
    }
  }
  if (typeRecherche == null) {
    //madDialogueOn('?');
  } else {
    $('madDialogueRegEx').innerHTML = t;
    clearTimeout(window.reqAjax);
    window.reqAjax = setTimeout('rechercheLocal(\'q='+ escape(t) + '&r='+escape(l)+'&t=' + typeRecherche+'\',\''+typeRecherche+'\')',madDeltaAjax);
  }
  }
}



    var http_request = false;

   function makeRequest(url) {

       if (window.XMLHttpRequest) { // Mozilla, Safari,...
           http_request = new XMLHttpRequest();
       } else if (window.ActiveXObject) { // IE
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
       }
       http_request.onreadystatechange = alertContents;
       http_request.open('GET', url, true);
       http_request.send(null);

   }

   function alertContents() {

       if (http_request.readyState == 4) {
           if (http_request.status == 200) {
           	rechercheLocalCB(http_request);
               //alert(http_request.responseText);
           } else {
               alert('There was a problem with the request.');
           }
       }

   } 
/**
 * Initialise une requete AJAX pour obtenir une localisation
 * @pars l
 */
function rechercheLocal(pars,typeRecherche) {
  //wait('on');
  var url = 'madRecherche.php';
  madDialogueOn(typeRecherche);
  if (attenteReponse == 0 ) {
    attenteReponse = 1;
    //waitRecherche('on');
    makeRequest(url+'?'+pars);
    
  } else {
    clearTimeout(window.reqAjax);
    window.reqAjax = setTimeout('rechercheLocal(\''+pars+'\',\''+typeRecherche+'\')',madDeltaAjax);
  }
} 

/**
 * Traitement du resulat XML de recherche
 * @pars o Object XML
 */

var madRechercheResultats = null;

function rechercheLocalCB(o) {
  //alert(o);
  if (attenteReponse==1) {
    attenteReponse=0;
    //waitRecherche('off');
    var x = o.responseXML;
    var nb = x.getElementsByTagName('nbLocal')[0].firstChild.data;
    madDialogueOn('nombre de résultat(s): '+nb+' '+x.getElementsByTagName('typeLocal')[0].firstChild.data);
    var m = x.getElementsByTagName('Message')[0].firstChild.data;
    var nomOD = '';
    switch (m) {
    case 'o':
    case 'l':
      nomOD = 'Origine';
      break;
    case 'd':
      nomOD = 'Destination';
      break;
    case 'automatique':
      nomOD = 'Origine';
      break;
    }

    if (madClicCarte==1 && nb==1) {
        madClicCarte = 0;
        madRechercheResultats = x;
        madSauveLocal(0,m);
        return;
    }
    
    if (nb>=1 && nb<madResultatRechercheMax) {
      var txt2 ='<table width="100%" id="tbl'+nomOD+'" border="0" cellspacing="4">';
      txt2 += '<tr><td><b>'+selectionLocalisation+':</b></td></tr>';
      var ido = 0;
      var idd = 0;
      for (var i = 0; i<nb; i++) {
        madRechercheResultats = x;

	txt2 +='<tr id="ld'+nomOD+'_'+i+'" \
	onkeydown="navFleche(this,event,'+i+');">';
	if (i%2==0) {
	  txt2 += '<td style="background:#EEE;">';
	} else {
	  txt2 += '<td>';
	}
	txt2 += '<span onmouseover="this.style.cursor=\'pointer\';" \
	onclick="madSauveLocal('+i+',\''+m+'\');selectIEBug(1);" liste="" value="">\
	'+x.getElementsByTagName('Descrip')[i].firstChild.data+'</span></td>';

        //txt2 += '<td align="right">'+x.getElementsByTagName('Munic')[i].firstChild.data+'</td>';
        txt2 +='</tr>';
      }
      txt2 += '</table>';
      $('search-results-'+m).innerHTML = txt2;
      $('search-results-'+m).style.display = 'block';
      selectIEBug(0);
    } else {
      if (nb==0) {
      $('search-results-'+m).innerHTML = aideRecherche;
      $('search-results-'+m).style.display = 'block';
      selectIEBug(0);
//      } else if (nb==1) {
//        madRechercheResultats = x;
//        madSauveLocal(0);
      } else {
      $('search-results-'+m).innerHTML = 'Trop de résultats; veuillez préciser.';
      $('search-results-'+m).style.display = 'block';
      selectIEBug(0);
      }
      //$('search-results-'+m).style.display = 'none';
      //selectIEBug(1);
    }
  } else {
    $('search-results-'+m).style.display = 'none';
    selectIEBug(1);
  }
}

function selectIEBug(visible) {
  if (visible) {
	$('jour').style.visibility='visible';
	$('hdep1').style.visibility='visible';
	$('hdep2').style.visibility='visible';
  } else {
	$('jour').style.visibility='hidden';
	$('hdep1').style.visibility='hidden';
	$('hdep2').style.visibility='hidden';
  }
}

function madSauveLocal(n,m) {
  //alert(n);

  x = madRechercheResultats;
  var xy = x.getElementsByTagName('XY')[n].firstChild.data.split(' ');

  if (m=='o') {
    LocalOD = 'Origine';
    envoyerStartPos(xy[0],xy[1]);
    //document.madFormTA.odint[1].checked = true;
  } else {
    LocalOD = 'Destination';
    envoyerEndPos(xy[0],xy[1]);
    //document.madFormTA.odint[0].checked = true;
  }

  $(LocalOD).value = x.getElementsByTagName('Descrip')[n].firstChild.data.replace('’',"'");
  $(LocalOD).lieu = x.getElementsByTagName('Descrip')[n].firstChild.data.replace('’',"'");
  $(LocalOD).region = x.getElementsByTagName('Region')[n].firstChild.data;
  $(LocalOD).xcoord = xy[0];
  $(LocalOD).ycoord = xy[1];
  $('Localisation-'+m).value = x.getElementsByTagName('Descrip')[n].firstChild.data.replace('’',"'");
  $('madCorps1').style.display= 'block';
  $('madCorps2').style.display = 'none';

  $('madLignes').innerHTML='';
  ChangeMode(0);
  RemoveLabel();
  $('madCorps2').innerHTML='';

  $('search-results-'+m).style.display='none';
  selectIEBug(1);
  //$('Localisation').value='';
  madPrevSearch = x.getElementsByTagName('Descrip')[n].firstChild.data.replace('’',"'");
  //madToggleCalculer();
}


function madZapLocal(m) {
  //alert(n);

  if (m=='o') {
    LocalOD = 'Origine';
  } else {
    LocalOD = 'Destination';
  }

  $(LocalOD).value = '';
  $(LocalOD).lieu = '';
  $(LocalOD).region = 0;
  $(LocalOD).xcoord = 0;
  $(LocalOD).ycoord = 0;
  $('Localisation-'+m).value = '';
  $('search-results-'+m).style.display='none';
  selectIEBug(1);
  madPrevSearch = '';
  //madToggleCalculer()
}

function madToggleCalculer() {
  if ($('Origine').xcoord>0 && $('Destination').xcoord>0) {
    if ($('Origine').xcoord!=$('Destination').xcoord && $('Origine').ycoord!=$('Destination').ycoord) {
      if (($('Origine').xcoord-$('Destination').xcoord)*($('Origine').xcoord-$('Destination').xcoord)+($('Origine').ycoord-$('Destination').ycoord)*($('Origine').ycoord-$('Destination').ycoord)>62500 ) {
        //$('tdCalculer').style.visibility='visible';
        $('tdCalculerInfo').innerHTML = '';
        return 1;
      } else {
        //$('tdCalculer').style.visibility='hidden';
        $('tdCalculerInfo').innerHTML = 'Distance de moins de 250m entre l\'origine et la destination.';
        return 0;
      }
    } else {
      //$('tdCalculer').style.visibility='hidden';
      $('tdCalculerInfo').innerHTML = 'L\'origine est égale à la destination.';
      return 0;
    }
  } else {
    //$('tdCalculer').style.visibility='hidden';
    if ($('Origine').xcoord>0) {
      $('tdCalculerInfo').innerHTML = 'La destination n\'est pas valide.';
      return 0;
    } else {
      $('tdCalculerInfo').innerHTML = 'L\'origine n\'est pas valide.';
      return 0;
    }
  }
}


/**
 * Initialisation de la requete AJAX pour calculer des trajets
 */
function calculTrajetsTxt() {

  var url = 'madCalculWS.php';
  //if ($('Origine').xcoord>0 && $('Origine').ycoord>0 && $('Destination').xcoord>0 && $('Destination').ycoord>0) {
  //} else {
  //  alert('veuillez choisir une origine et une destination');
//    wait('off');
  //  return;
  //}
  if (!madToggleCalculer()) {
  	return;
  }
  var pars = 'x1='+$('Origine').xcoord;
  pars += '&y1='+$('Origine').ycoord;
  pars += '&ro='+$('Origine').region;
  pars += '&x2='+$('Destination').xcoord;
  pars += '&y2='+$('Destination').ycoord;
  pars += '&rd='+$('Destination').region;

  if ($('deparr').checked) {
    pars += '&da=d';
  } else {
    pars += '&da=a';
  }

  pars += '&d='+$('jour').value;
  pars += '&h='+$('hdep1').value+':'+$('hdep2').value;
  if ($('pmarc').checked) {
    pars += '&ma=1';
  } else {
    pars += '&ma=0';
  }
  if ($('umetro').checked) {
    pars += '&me=1';
  } else {
    pars += '&me=0';
  }
  if ($('utrain').checked) {
    pars += '&tr=1';
  } else {
    pars += '&tr=0';
  }
  if ($('ptrans').checked) {
    pars += '&co=1';
  } else {
    pars += '&co=0';
  }
  pars += '&lo='+escape($('Origine').lieu);
  pars += '&ld='+escape($('Destination').lieu);
  if (usager_id>0) {
    pars += '&uid='+usager_id;
  } else {
    pars += '&uid=0';
  }
  pars += '&id='+Math.ceil(Math.random()*100);
  pars += '&lng='+sLangue;
  pars += '&crt='+madNsageo;
  //madDialogueOn(pars);
  //$('madCorps1').style.display='block';
  //return;
  //waitTxt('on');
  if (madNsageo) {
  	thisMovie("nsademo").StartBusy();
  }
  MoveExtent($('Origine').xcoord,$('Origine').ycoord,$('Destination').xcoord,$('Destination').ycoord);
  makeRequest2(url+'?'+pars);
  //alert(url+'?'+pars);
}

    var http_request = false;

   function makeRequest2(url) {

       if (window.XMLHttpRequest) { // Mozilla, Safari,...
           http_request = new XMLHttpRequest();
       } else if (window.ActiveXObject) { // IE
           http_request = new ActiveXObject("Microsoft.XMLHTTP");
       }
       http_request.onreadystatechange = alertContents2;
       http_request.open('GET', url, true);
       http_request.send(null);

   }

   function alertContents2() {

       if (http_request.readyState == 4) {
           if (http_request.status == 200) {
           	madCalculTxtAjaxCB(http_request);
               //alert(http_request.responseText);
           } else {
               alert('There was a problem with the request.');
           }
       }

   } 

var aGeom = new Array();
var aEtiq = new Array();
var madPrint = '';

/**
 * Traite le resultat de calcul de parcours
 * @pars o Object XML
 */
function madCalculTxtAjaxCB (o) {
  //alert(o);
  //waitTxt('off');
  if (madNsageo) {
    thisMovie("nsademo").StopBusy();
  }  
  resultat = true;
  //alert(o.responseText.indexOf('{'));
  var myObject = eval('(' + o.responseText.substr(o.responseText.indexOf('{')) + ')');
  if (myObject.message!='OK') {
    alert(myObject.message);
  } else {
  $('madCorps2').innerHTML = myObject.html;
  $('madLignes').innerHTML = myObject.htmlU;
  madPrint = myObject.htmlP;
  //$('madCorps1').style.display= 'none';
  $('madCorps2').style.display = 'block';

  ChangeMode(0);

  if (typeof myObject.geom0 != 'undefined') {
  aGeom[0] = myObject.geom0.split(',');
  aEtiq[0] = myObject.etiq0.replace(/~/gi,'"');
  }
  madAfficheItin(0,0);
  if (typeof myObject.geom1 != 'undefined') {
  aGeom[1] = myObject.geom1.split(',');
  aEtiq[1] = myObject.etiq1.replace(/~/gi,'"');
  }
  if (typeof myObject.geom2 != 'undefined') {
  aGeom[2] = myObject.geom2.split(',');
  aEtiq[2] = myObject.etiq2.replace(/~/gi,'"');
  }

  $('boutononglet3').innerHTML = 'id: '+myObject.monID;
  $('boutononglet6').style.display = 'block';
  }
  
}




/**
 * Information 
 */
function infoRecherche() {
  var txt = '';
  txt += '<table cellpadding="5" border="1">';
  txt += '<tr><th>type de recherche</th><th>exemple</th></tr>';
  txt += '<tr><td><b>Adresse</b><br><li>numéro nom<br></td><td>900, rue de la Gauchetière ouest<br>900 gauchetiere</td></tr>';
  txt += '<tr><td><b>Intersection</b><br><li>nom/nom</td><td>rue de la Gauchetière ouest/rue University<br>gauchetiere/univ</td></tr>';
  txt += '<tr><td><b>Générateur</b><br><li>nom</td><td>place bonaventure<br>bonaventure</td></tr>';
  txt += '<tr><td><b>Métro</b><br><li>METRO nom</td><td>métro bonaventure<br>metro bonav</td></tr>';
  txt += '<tr><td><b>Gare</b><br><li>GARE nom</td><td>gare centrale<br>gare</td></tr>';
  txt += '<tr><td><b>AUTOBUS</b><br><li>numéro</td><td>52587</td></tr>';
  txt += '<tr><td><b>Code postal</b><br><li>A1A 1A1</td><td>H5A 1K6</td></tr>';
  //txt += '<tr><td><b>Coordonnées</b></td><td>numéro,numéro</td></tr>';
  txt += '</table>';
  //txt += 'ne pas inclure le type de la rue<br>';
  //txt += 'ne pas utiliser de caractères accentués';
  //$('madCorps2').innerHTML = txt;
  //$('madCorps1').style.display= 'none';
  //$('madCorps2').style.display = 'block';
  $('search-results').innerHTML = txt;
  $('search-info').style.visibility = 'visible';

}



/**
 * 
 */
function dispx() {
  $('madCorps2').style.display = 'none';
  $('madCorps1').style.display= 'block';
  $('madB7').style.visibility = 'hidden';
}



/**
 * 
 */
function dispxsr() {
  $('search-results').style.display = 'none';
  $('search-results2').style.display = 'none';
}



/**
 * 
 */
function localisations() {
  if (usager_id>0) {
    textRecherche = usager_id;
    typeRecherche='usa';
    rechercheLocal('o');
    setTimeout("rechercheLocal('d')",200);
  }
}



/**
 * Formulaire pour se logger sur le site
 */
function login() {

  //var txt = htmlEntete;
  var txt = '';
  txt += '<table cellpadding="0">';
  txt += '<tr><td><b>nom d\'usager</b></td><td><input type="text" size="10" id="madTAnom"></td></tr>';
  txt += '<tr><td><b>mot de passe</b></td><td><input type="password" size="10" id="madTApasse"></td></tr>';
  txt += '</table>';
  txt += '<input type="button" value="soumettre" onclick="javascript:bienvenue();">';
  $('madCorps2').innerHTML = txt;
  $('madCorps1').style.display= 'none';
  $('madCorps2').style.display = 'block';
}



/**
 * Sauvegarde cette localisation
 */
function bienvenue() {
    var url = 'usagers_login.php';
    var pars = 'u=' + escape($('madTAnom').value) + '&p='+escape($('madTApasse').value);
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: bienvenueCB });
}



/**
 * Sauvegarde cette localisation
 */
function bienvenueCB(o) {
  var oXml = o.responseXML;
  //var txt = htmlEntete;
  var txt = '';
  txt += oXml.getElementsByTagName('Message_usager')[0].firstChild.data+'<br>';
  var txt2 = 'vous avez '+oXml.getElementsByTagName('nbLocal')[0].firstChild.data+' localisations';
  txt += txt2;
  usager_id=oXml.getElementsByTagName('Usager_id')[0].firstChild.data;
  $('madCorps2').innerHTML = txt;
  $('madCorps1').style.display= 'block';
  $('madCorps2').style.display = 'none';
  madDialogueOn(txt2);
  $('madB3').src='sommaire_fichiers/madlock.gif';
  $('madC1B1').style.visibility='visible';
  textRecherche = usager_id;
  typeRecherche='usa';
  rechercheLocal('automatique');
//  $('madB5').style.visibility='visible';
}



/**
 * Sauvegarde cette localisation
 */
function navFleche(o,e,i) {
  //alert(t.type);
  if (e.keyCode==40) {
    if (o.id == 'Origine') {
      o.disabled=true;
      var j = i+1;
      //$('ldOrigine_'+j).style.background = '#999';
      $('tblOrigine').style.background = '#EEE';
      o.disabled=false;
    } else {
      var j = i+1;
      $('ldOrigine_'+j).style.background = '#999';
    }
  }
}


function madMajCirc() {
  $('madCorps1').style.display='none';
  $('madCirc08').style.display='block';
  $('madCorps2').style.display = 'none';
}

function madMajOD() {
  $('madCorps1').style.display='block';
  $('madCirc08').style.display='none';
  $('madCorps2').style.display='none';
}

function madMajInverse() {
  RemoveLabel();
  var stValue = $('Origine').value;
  var stLieu = $('Origine').lieu;
  var stRegion = $('Origine').region;
  var stXcoord = $('Origine').xcoord;
  var stYcoord = $('Origine').ycoord;
  var stLocalisation = $('Localisation-o').value;

  $('Origine').value = $('Destination').value;
  $('Origine').lieu = $('Destination').lieu;
  $('Origine').region = $('Destination').region;
  $('Origine').xcoord = $('Destination').xcoord;
  $('Origine').ycoord = $('Destination').ycoord;
  $('Localisation-o').value = $('Localisation-d').value;
  envoyerStartPos($('Destination').xcoord,$('Destination').ycoord);

  $('Destination').value = stValue;
  $('Destination').lieu = stLieu;
  $('Destination').region = stRegion;
  $('Destination').xcoord = stXcoord;
  $('Destination').ycoord = stYcoord;
  $('Localisation-d').value = stLocalisation;
  envoyerEndPos(stXcoord,stYcoord);
  
  $('madCorps2').style.display = 'none';
  calculTrajetsTxt();
  
}

function madMajCircPlus30() {
  var nH1taille = $('hdep1').length;
  var nH2taille = $('hdep2').length;
  if ($('hdep2').selectedIndex<nH2taille/2) {
    $('hdep2').selectedIndex = $('hdep2').selectedIndex+(nH2taille/2);
  } else {
    if ($('hdep1').selectedIndex<nH1taille-1) {
      $('hdep1').selectedIndex = $('hdep1').selectedIndex+1;
      $('hdep2').selectedIndex = $('hdep2').selectedIndex-(nH2taille/2);
    } else {
      if ($('hdep2').selectedIndex<nH2taille-1) {
        $('hdep2').selectedIndex = nH2taille-1;
      } else {
        alert('maximum');
        return;
      }
    }
  }
  
  $('madCorps2').style.display = 'none';
  calculTrajetsTxt();

}

function madMajCircMoins30() {
  var nH1taille = $('hdep1').length;
  var nH2taille = $('hdep2').length;
  if ($('hdep2').selectedIndex>=nH2taille/2) {
    $('hdep2').selectedIndex = $('hdep2').selectedIndex-(nH2taille/2);
  } else {
    if ($('hdep1').selectedIndex>0) {
      $('hdep1').selectedIndex = $('hdep1').selectedIndex-1;
      $('hdep2').selectedIndex = $('hdep2').selectedIndex+(nH2taille/2);
    } else {
      if ($('hdep2').selectedIndex>0) {
        $('hdep2').selectedIndex = 0;
      } else {
        alert('minimum');
        return;
      }
    }
  }
  
  $('madCorps2').style.display = 'none';
  calculTrajetsTxt();

}


function madMajCircDefaut() {
  alert('en développement');
}


/**
 * recois les coordonnées x,y de l'application Flash
 * @pars x
 * @pars y
 */
function recevoirOri(x,y) {
  //alert("RECU : " + x + " , " + y);
  madZapLocal('o');
  var sx = Math.round(x);
  var sy = Math.round(y);
  madClicCarte = 1;
  validLocal(sx+","+sy,'o');
  toggleOnglet(0);
  $('madLignes').innerHTML='';
  RemoveLabel();
  $('Localisation-o').value = attenteRecherche;
/*
  $('Origine').value = x+','+y;
  $('Origine').lieu = x+','+y;
  $('Origine').region = 1;
  $('tdOrigine').innerHTML=x+','+y;
  $('Origine').xcoord = x;
  $('Origine').ycoord = y;
*/
}

/** recois les coordonnées x,y de l'application Flash
 * @pars x
 * @pars y
 */
function recevoirDesti(x,y) {
  //alert("RECU : " + x + " , " + y);
  madZapLocal('d');
  var sx = Math.round(x);
  var sy = Math.round(y);
  madClicCarte = 1;
  validLocal(sx+","+sy,'d');
  toggleOnglet(0);
  $('madLignes').innerHTML='';
  RemoveLabel();
  $('Localisation-d').value = attenteRecherche;
/*
  $('Destination').value = x+','+y;
  $('Destination').lieu = x+','+y;
  $('Destination').region = 1;
  $('tdDestination').innerHTML=x+','+y;
  $('Destination').xcoord = x;
  $('Destination').ycoord = y;
  $('tdCalculer').style.visibility='visible';
*/
}

function choisirLieu(params) {
  var aParams = params.split('|');
  var nom = aParams[0];
  var od = aParams[1];
  madZapLocal(od);
  madClicCarte = 1;
  toggleOnglet(0);
  $('madLignes').innerHTML='';
  RemoveLabel();
  $('Localisation-'+od).value = 'recherche en cours...';
  validLocal(nom,od);
}

//} MADITUC

function addslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: "kevin\'s birthday"
 
    return str.replace('/(["\'\])/g', "\\$1").replace('/\0/g', "\\0");
}


function thisMovie(movieName) 
{
 	if (navigator.appName.indexOf("Microsoft") != -1)
 	{
 		//return window[movieName];
		return $(movieName);
 	} else 
 	{
        	return document[movieName];
 	}
 }
/**
 * TEST - Envoyer position
 * @pars b
 * @pars t
 */
function envoyerStartPos(x,y) {
  if (madNsageo) {
    thisMovie("nsademo").setStart(x,y);
  }
}

/**
 * TEST - Envoyer position
 * @pars b
 * @pars t
 */
function envoyerEndPos(x,y) {
  if (madNsageo) {
	thisMovie("nsademo").setEnd(x,y)
  }
}

function ChangeMode(n) {
  if (madNsageo) {
	thisMovie("nsademo").ChangeMode(n);
  }
}

function SegmentClick(id) {
	//alert(id);
}

function madAfficheItin(n,rezoom) {
  if (madNsageo) {
  madPrepareRouting(aGeom[n],rezoom);
  thisMovie("nsademo").AddMarkers(eval(aEtiq[n].replace(/&nbsp;/gi," ")));
  //alert(aEtiq[n].replace(/&nbsp;/gi," "));
  }
  toggleParcours(n);
  $('boutononglet6').style.display='block';
}

function madPrepareRouting(o,rezoom) {
//alert('routing');
//ConcatÃ©nation des points formatÃ©s en object Flex
//alert(o);
	RemoveLabel();
	var nb = o.length;
	var st = 0;
	var reponseFla = '[';
	var c1 = '';
	for (var n = 0; n < nb; n++)
	{
		var attrib = o[n].split('|');
		reponseFla += c1+'{"styleId":"'+attrib[0]+'","segId":"'+attrib[1]+'","points": [';
		var pts = attrib[2].split(';');
		var c2 = '';
		for (var m = 0; m < pts.length; m++)
		{
			var xy = pts[m].split(' ');
			reponseFla += c2+'{"x":"' + xy[0] + '","y":"' + xy[1] + '"}';
			c2 = ',';
		}
		reponseFla += ']}'
		c1 = ',';
	}
		reponseFla += ']';
		
		//ConcatÃ©nation des directions formatÃ©es en object Flex
		var reponseDirFla = '[{"text":"texte","distance":"1"},{"text":"texte","distance":"1"}';
		reponseDirFla += "]";
		//alert("reponseDirFla:"+reponseDirFla);
//alert(reponseFla);		
//reponseFla = '[{"styleId":"0","segId":"2","points": [{"x":"299000","y":"5040000"},{"x":"299500","y":"5040000"},{"x":"299500","y":"5045000"}]},{"styleId":"2","segId":"33","points": [{"x":"299500","y":"5040500"},{"x":"298500","y":"5040500"},{"x":"299000","y":"5040000"}]}]';
		
		//Renvoie les donnÃ©es directement au Flash
		returnTrajet(reponseDirFla,reponseFla,rezoom);
		
}

/**
* Envoyer Label
* @pars direction 
* @pars points
* 
*/
function returnTrajet(direction,points,rezoom)
{
  if (madNsageo) {
  thisMovie("nsademo").setDirectionTC(eval(direction.replace(/<\/?[^>]+>/gi, "")),eval(points.replace(/&nbsp;/gi," ")),rezoom);
  }
}


/**
* Clear Label
*/
function RemoveLabel() {

 if (madNsageo) {
   thisMovie("nsademo").RemoveMarkers();
   //alert("ok");
 }
 $('boutononglet6').style.display='none';
} 


function Move(x,y,zoom,transition) {

 if (madNsageo) {
   thisMovie("nsademo").Move(x,y,zoom,transition);
 }
} 

function MoveExtent(x1,y1,x2,y2) {

 if (madNsageo) {
   thisMovie("nsademo").MoveExtent(x1,y1,x2,y2);
 }
}

function afficheJourSpecial(d) {

  if (typeof descjour[d] != 'undefined') {
    $('affjour').innerHTML=descjour[d];
  } else {
    $('affjour').innerHTML='';
  }
}


var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;
 
function pad(str, len, pad, dir) {
 
	if (typeof(len) == "undefined") { var len = 0; }
	if (typeof(pad) == "undefined") { var pad = ' '; }
	if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }
 
	if (len + 1 >= str.length) {
 
		switch (dir){
 
			case STR_PAD_LEFT:
				str = Array(len + 1 - str.length).join(pad) + str;
			break;
 
			case STR_PAD_BOTH:
				var right = Math.ceil((padlen = len - str.length) / 2);
				var left = padlen - right;
				str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
			break;
 
			default:
				str = str + Array(len + 1 - str.length).join(pad);
			break;
 
		} // switch
 
	}
 
	return str;
 
}