var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;
var idArticleGeo = 346;
var inverseSens = {'A':'R','R':'A'};
if (ormont) idArticleGeo = 379;

function jsddm_close()
{
    if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer()
{
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer()
{
    if(closetimer)
    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

function jsddm_open()
{
   jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}



var timings;


function load_courses(id,quand)
{
    $('#times').hide(); 
    $('#loadingIndicator').show();
    $.getJSON('/zf/json/horaires/date/' + quand +'/num/'+id, function(data) {
        var currentTown ='';
        var html='';
        var stops = Array();
        var i =0;
        // on range tout les arrêts de départ dans un tableau stops
        for (var stopData in data.A)
        {
					if (stopData)
					{
            stops[i] = stopData;
            i++;
					}
        }
        
        // on va ensuite ajouter les arrêts qui manquent dans le sens retour
        
        // la variable next indique l'arrêt précédent celui qui manque, donc le suivant dans le sens Retour
        next = '';   
        pos = 0;     
        for (stopData in data.R)
        {
            temp = stopData.split('|');
            stop = temp[1].trim();
            found = false;
            
            // est ce que l'arrêt est déjà présent dans notre tableau ?
            for (i in stops)
            {
							if(stops[i]){
                temp = stops[i].split('|');
                checkStop = temp[1].trim();
                if (checkStop == stop) 
                {
                    found = true;
                    break;
                }
							}
            }
            
            // on a pas l'arrêt, dans ce cas on va l'ajouter :
            if (!found)
            {
                //  on regarde l'indice de next dans notre tableau stops pour savoir où faire l'insert
                for (i=stops.length-1; i>=0;i--)
                {
                    temp = stops[i].split('|');
                    stoptemp = temp[1].trim();
                    if (stoptemp == next)
                    {
                        pos = i;
                        break;
                    }
                }
                
                // on reconstitue le tableau (décalage)
                for (i=stops.length;i>pos;i--)
                {
                    stops[i] = stops[i-1];
                }
                //  on ajoute notre arrêt manquant
                stops[pos] = stopData;
                
            }
            
            next = stop;
            
        }
        for (i in stops)
        {
            stopData = stops[i];
            temp = stopData.split('|');
            stop =  temp[1].trim();
            temp = stop.split(':');
            town = temp[0];
            itl = temp[2];
            if (!itl) itl = '0';
            stop = temp[1].trim();
            if (currentTown != town)
            {
                html+='<option class="town" value="0">'+town+'</option>';
                currentTown = town;
            }
            html += '<option class="itl-'+itl+'" value="'+stopData+'" title="'+town + ' / ' + stop+'">&nbsp;&nbsp;&nbsp;&nbsp;'+stop+'</option>';
        }
        $('p.stop select').html(html);
        $('#explaination').hide();
        $('#stops').show();
        timings = data;
        $('#loadingIndicator').hide();
        if (Lstop)
        {
          $('#depart option').each(function(i){
            if ($(this).html().substr(24) == Lstop)
            {
              $(this).attr('selected','selected');
            }
          });
        }
        
    });
}




$(document).ready(function(){
    
    $("#playerContainer").overlay({
     mask: {
       color: '#FFF',
       loadSpeed: 200,
       opacity: 0.7
     },
      closeOnClick: true
    });
    $('#playerContainer').overlay().load();
    $('a.skip').click(function(){
          $('#playerContainer').overlay().close();
    });
    
    
    
    $('tr').live('mouseover mouseout',function(event){
        var temp = $(this).attr('id').split('-');
        if(temp.length && temp[1]!==undefined)
        {
            if (event.type=='mouseover')
                rollover(temp[1],temp[0]);
            else
                rollout();
        }

    });
    
    $('#article-18 .article-texte-18').each(function(){
      $.getJSON('/zf/json/lignes/', function(data) {  
        html = '<table class="spip"><tr><th>-</th><th>Nom de la ligne</th><th>horaires&nbsp;hiver</th><th>horaires&nbsp;été</th><th>plan</th></tr>';
        for (var i in data)
        {
					if (data[i])
					{
	          if (i%2) cl = "odd"; else cl="even";
	          html+='<tr class="row_'+cl+'">';
	          html+='<td><strong style="display:block;padding:3px 3px 3px 6px;border-left:5px solid #'+data[i].couleur+';">'+data[i].SL_NOM_COM+'</strong></td>';
	          html+='<td>'+data[i].libelle+'</td>';
	          html+='<td><a href="/medias/pdf/hiver/'+data[i].SL_NOM_COM+'.pdf">télécharger</a></td>';
	          html+='<td><a href="/medias/pdf/'+data[i].SL_NOM_COM+'.pdf">télécharger</a></td>';
	          html+='<td><a href="/medias/pdf/plan_'+data[i].SL_NOM_COM+'.pdf">télécharger</a></td>';
	          html+='</tr>';						
					}
        }
				html +='</table>';
        $('#article-18 .article-texte-18').append(html);
      });
    });

    $('#article-57 .galerie').each(function(){
      $.getJSON('/zf/json/lignes/', function(data) {  
        html = '';
        for (var i in data)
        {
					if (data[i])
					{
          if (i%5 === 0) html+= '<br class="cl"/>';
          html += '<div>';
          html += '<span style="color:#'+data[i].couleur+'">'+data[i].SL_NOM_COM+'</span>';
          html += '<a href="/medias/pdf/plan_'+data[i].SL_NOM_COM+'.jpg"><img src="/medias/pdf/thm_'+data[i].SL_NOM_COM+'.jpg" height="140" width="140"></a>';
          html += '<strong>'+data[i].libelle+'</strong>';
          html += '<p><a href="/medias/pdf/hiver/'+data[i].SL_NOM_COM+'.pdf">hiver</a><a href="/medias/pdf/'+data[i].SL_NOM_COM+'.pdf">ete</a></p>';
          html += '</div>'; 
				}
        }
        html += '<div>';
        html += '<span style="color:#992849">510</span>';
        html += '<a href="/medias/pdf/plan_510.jpg"><img src="/medias/pdf/thm_510.jpg" height="140" width="140"></a>';
        html += '<strong>510 FLEURY &ndash; GRIGNY</strong>';
        html += '<p><a href="/medias/pdf/hiver/510.pdf">hiver</a><a href="/medias/pdf/510.pdf">ete</a></p>';
        html += '</div>';
        html +='';
        $('#article-57 .galerie').append(html);
      });
    });

	// ORMONT
    $('#article-75 .galerie').each(function(){
      $.getJSON('/zf/json/lignes/', function(data) {  
        html = '';
        for (var i in data)
        {
					if (data[i])
					{
	          if (i%5 === 0) html+= '<br class="cl"/>';
	          html += '<div>';
	          html += '<span style="color:#'+data[i].couleur+'">'+data[i].SL_NOM_COM+'</span>';
	          html += '<a href="/medias/pdf/plan_'+data[i].SL_NOM_COM+'.jpg"><img src="/medias/pdf/thm_'+data[i].SL_NOM_COM+'.jpg" height="140" width="140"></a>';
	          html += '<strong>'+data[i].libelle+'</strong>';
	          html += '<p><a href="/medias/pdf/hiver/'+data[i].SL_NOM_COM+'.pdf">hiver</a><a href="/medias/pdf/'+data[i].SL_NOM_COM+'.pdf">ete</a></p>';
	          html += '</div>'; 
						
					}

        }
        html +='';
        $('#article-75 .galerie').append(html);
      });
    });


    
    if ($('#home').length)
    {
        
        /******************************
        *        gestion des trajets
        ******************************/

        $('.tda').val('rue, place, arrêt, lieu remarquable...');
        $('.tda').focus(function(){
            if($(this).val()=='rue, place, arrêt, lieu remarquable...') $(this).val('');
        }).blur(function(){
             if($(this).val()==='') $(this).val('rue, place, arrêt, lieu remarquable...');
        });
        $('.tdv').val('ville');
        $('.tdv').focus(function(){
            if($(this).val()=='ville') $(this).val('');
        }).blur(function(){
             if($(this).val()==='') $(this).val('ville');
        });    
        $($('#heure option').get(Date.now().getHours())).attr("selected","selected");
        $($('#minute option').get(Date.now().getMinutes())).attr("selected","selected");

        $.tools.dateinput.localize("fr",  {
               months:        'janvier,f&eacute;vrier,mars,avril,mai,juin,juillet,ao&ucirc;t,' +
                                 'septembre,octobre,novembre,d&eacute;cembre',
               shortMonths:   'jan,f&eacute;v,mar,avr,mai,jun,jul,ao&ucirc;,sep,oct,nov,d&eacute;c',
               days:          'dimanche,lundi,mardi,mercredi,jeudi,vendredi,samedi',
               shortDays:     'dim,lun,mar,mer,jeu,ven,sam'
        });

        $(":date").dateinput(
        {
                lang: 'fr', 
								format: 'dd/mm/yyyy',
								firstDay: 1
            }
        );

        $('#date_trajet').change(function(event,data){

            // var temp = $(this).split('/');
            $('#jour').val(data.getDate());
            $('#mois').val(data.getMonth()+1);
            $('#annee').val(data.getFullYear());
            // $('#mois').val(temp[1]);
            // $('#annee').val(temp[2]);
        });

         $('#close').click(function(){
            $('#times').hide(); 
         });
         // chargement des lignes
        populate_line(0);

        $('#filterByCLink').click(function(){
            // chargement des communes (à mettre en option)
            $('#loadingIndicator').show();
            $.getJSON('/zf/json/communes', function(data) {
                $('#ville').children().remove();
                $('#ville').append('<option value="">... filtrer par commune</option>');
                for(var i in data)
                {
									if (data[i])
									{
                    t = data[i];
                    if (t) $('#ville').append('<option value="' + i + '">'+t+'</option>');
										
									}
                }
                $('#loadingIndicator').hide();    
            });
            $('#filterByC').show('normal');
        });

         $('#id_ligne').change(function(){
             var id = $('#id_ligne').val();    
             var quand = $('input.date').val().split('/').join('-');
             if (id && quand)
             {   
                 load_courses(id,quand);            
             }
         });
         
         $("#date").change(function(event, date) {
             var m = date.getMonth() +1;
             if (m<10) m = '0' + m;
             var quand =date.getDate() +'-'+m+'-'+date.getFullYear();
             var id = $('#id_ligne').val();    
             if (id && quand)
             {   
                 load_courses(id,quand);            
             }             
         });

         $('p.stop select').change(function(){
             if($(this).find(':selected').hasClass('town'))
             {
                 $(this).find(':selected').attr('selected',null);
             }
             // $('#arrivee').get(0).selectedIndex>$('#depart').get(0).selectedIndex
             populate_timings(true);        
         });

         $('#ville').change(function(){
             populate_line($(this).val());
         });

    }
     

    setInterval(function(){
        date = new Date();
        $('#datejour').html('Nous sommes le ' + Date.today().getDate() + ' '  +Date.today().getMonthName() + ' ' + Date.today().getFullYear() +  ', il est '+Date.now().toString('HH:mm'));
    },5000);
    
    $('ul.menu > li').bind('mouseover', jsddm_open);
    $('ul.menu > li').bind('mouseout',  jsddm_timer);
});

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};


function populate_line(id_commune)
{
    var chainReaction = false;
    $('#loadingIndicator').show();
    if ($.browser.msie)
    {
      $('#depart').add('#arrivee').attr('size',22); 
    }
    $.getJSON('/zf/json/lignes/id_commune/'+id_commune, function(data) {
        $('#id_ligne').children().remove();
        $('#id_ligne').append('<option value="">... choisir une ligne</option>');                
        for(i in data)
        {
            l = data[i];
            var sel = '';
            if (Lligne && (Lligne == l.SL_NOM_COM || Lligne +' ' == l.SL_NOM_COM ))
            {
              sel= 'selected="selected"';
              chainReaction = true;
            }
            $('#id_ligne').append('<option class="'+l.SL_NOM_COM+'" value="' + l.SL_NOM_COM + '" style="background-color:#'+l.couleur+';" '+sel+'>' + l.libelle+'</option>');
        }
        $('#loadingIndicator').hide();        
        if (chainReaction)
        {
          var id = $('#id_ligne').val();    
          var quand = $('input.date').val().split('/').join('-');
          if (id && quand)
          {   
              load_courses(id,quand);            
          }
        }
    });
}

function rollover(id_course,sens)
{
    // console.log(id_course);
    $('body').prepend('<div id="canvas"></div>');            
    $('#canvas').css('top',$('#horaires').position().top + 15);
    $('#canvas').css('left',$('#horaires').offset().left + 15);
    var height = 400;
    var r = Raphael('canvas',200,height);
    var puces = r.set();
    var sPuces = r.set();
    var labels = r.set();
    var sLabels = r.set();
    var times = r.set();

    // tableau simple pour gérer les passages de la course
    var stops = Array();
    var start = 0;
    

    for(s in timings[sens])
    {
        for(idc in timings[sens][s])
        {
            if (idc == id_course && timings[sens][s][idc] !='-')
            {
                // désolé si quelqu'un reprend ça un jour, dernière fois que je stocke des données en string pourri
                var o = Object();
                var temp = s.split('|');
                temp = temp[1].split(':');
                o.nom = temp[1];
                o.time = timings[sens][s][idc];
                o.sel = ($('#depart option:selected').html() == '&nbsp;&nbsp;&nbsp;&nbsp;'+o.nom.substr(1) || $('#arrivee option:selected').html() == '&nbsp;&nbsp;&nbsp;&nbsp;'+o.nom.substr(1));
                // console.log(o.sel,o.nom,$('#depart option:selected').html(),$('#arrivee option:selected').html());
                hm = o.time.split(':');
                hm[0] = hm[0]*1;
                hm[1] = hm[1]*1;
                // premier arrêt ; l'écart avec le début est de 0. on stocke pour calculer
                if (start == 0)
                {
                    o.min = 0;
                    start = Object();
                    start.h = hm[0];
                    start.m = hm[1];
                } else {
                    
                    if(hm[0] == start.h)
                    {
                        o.min = hm[1]-start.m;
                    } else {
                        o.min = (60-start.m) + hm[1] + (hm[0]-start.h-1)*60;
                    }

                }
                stops.push(o);
                break;
            }   
        }
    }
    var pixPerMin = (height-40)/o.min; // durée totale en minute, pour le prorata

    // on a un tableau clean de notre course, avec la liste des arrêts désservis (nom, minutes écoulées depuis le départ, heure de passage)

    for (i in stops)
    {
        var s = stops[i];
        var y;
        if (stops.length>14)
        {
            y = 20 + (height-40)/stops.length*i;
        } else {
            y = 20 + s.min*pixPerMin;            
        }
        if (s.sel)
        {
            sPuces.push(r.circle(150,y,4));
            sLabels.push(r.text(140, y, s.nom));            
        } else {
            puces.push(r.circle(150,y,3));
            labels.push(r.text(140, y, s.nom));
        }
        
        times.push(r.text(160, y, s.time));
    }
    puces.attr({fill:'#6cbdb6',stroke:'#6cbdb6'});
    sPuces.attr({fill:'#f08a00',stroke:'#f08a00'});
    labels.attr({font: "11px Arial", fill: "#024342", "text-anchor": "end"});
    sLabels.attr({font: "11px Arial", fill: "#f08a00", "text-anchor": "end"});
    times.attr({font: "12px Arial", fill: "#024342", "text-anchor": "start"});
    
}
function rollout()
{
    $('#canvas').remove();
}

// contrôle si la ligne courante est circulaire ou non ;
// si on a plusieurs arrêt du même nom mais avec un ordre différent, elle est circulaire, sinon c'est une ligne classique
function isCirculaire()
{
    var firstStop ='';
    var checkArray = Array();
    var i = 0;
    for (label in timings.A)
    {
        temp = label.split('|');
        for (label2 in timings.A)
        {
            temp2 = label2.split('|');
            if (temp[1]==temp2[1] && temp[0]!=temp2[0])
            {
                return true;
            }
        }
    }
    return false;
}
function getKey(sens,circulaire,aSort,aLabel)
{
    if (sens == 'A' && !circulaire) return aSort + '|' + aLabel;
    // on regarde si notre arrêt est présent plusieurs fois, et si c'est le premier
    // pour ça on boucle sur les arrêt départ :
    var first = false;
    var found = false;
    var nb = 0;
    for (label in timings.A)
    {
        var temp = label.split('|');
        if (temp[1].trim() == aLabel.trim())
        {
            if( temp[0] == aSort && !found) first = true;
            nb++;
            found = true;
        } 
    }     
    // ensuite on boucle sur les arrets retour, et on renvoie le premier match, sauf si plusieurs arrêts et si pas premier en ALLER
    for(label in timings.R)
    {
        temp = label.split('|');
        if (temp[1].trim() == aLabel.trim())
        {
            if (first && nb>1)
            {
                first = false;
            } else {
                return label;
            }
        }
    }
    return false;
}

// renvoie la réféfence de l'arrêt dans le tableau
// inSens : le sens où la recherche est faite (A ou R) dans le tableau timings. Convention de stockage dans AMIWIN
// forSens : l'usage (trajet A ou R). Usage réel pour l'utilisateur.
// aLabel : nom de l'arrêt
// startPointA : l'arrêt que l'on recherche est notre premier arrêt dans le sens Aller
//			dans ce cas si sens == A on renvoie la 1° occurence, sinon la 2°
function getKey2(inSens,forSens,aLabel,startPointA)
{
	// console.log('on cherche "' + aLabel +'" dans le sens AW ' + inSens +' pour un usager qui fait le trajet ' + forSens +'. Classique ?' + startPointA );
	var first = false;
	var last  = false;
	for (label in timings[inSens])
	{
  	var temp = label.split('|');
		if (temp[1].trim() == aLabel.trim())
    {
			if (!first)
			{
				first = label; 
			} else {
				last = label;
			}
    }
	}
	
	if ( startPointA && ( (inSens == 'A' && forSens == 'A') || (inSens == 'R' && forSens == 'R') ) ) return first;
	if ( !startPointA && ( (inSens == 'A' && forSens == 'R') || (inSens == 'R' && forSens == 'A') ) ) return first;
	
	if (last)
		return last;
	else 
		return first;

}

$(document).ready(function(){
  $($('#main_navi li').get(0)).addClass('active');
  $("#scrollable").scrollable({

  	// basic settings
  	vertical: true,

  	// up/down keys will always control this scrollable
  	keyboard: 'static'

  // main navigator (thumbnail images)
  });
  $('#main_navi li').click(function()
  {
    $('.active').removeClass('active');
    $(this).addClass('active');
    var temp = $(this).attr('id').split('-');
    $("#scrollable").data('scrollable').seekTo(temp[1]-1);
  });
  $('#sec_navi li').click(function()
  {
    $('.active').removeClass('active');
    $(this).addClass('active');
    var temp = $(this).attr('id').split('-');
    $("#scrollable").data('scrollable').seekTo(1*temp[1]+6);
  });  
});
