$(document).ready(function(){	 	
    $('#puce7').css('opacity','0.6');
    $('#puce8,#english,#english-accueil').css('opacity','0.8');    
    $('.opacity0').css('opacity','0');
    $('.disabled').attr("disabled","disabled").css('opacity','0.5');
    $("#tabs-compte").tabs();
    $("#tabs-resa").tabs().css('background-color','#969696').css('padding','0').css('margin-left','2px');
    $("#tabs-compte ul,#tabs-resa ul").removeClass('ui-helper-reset').removeClass('ui-helper-clearfix').removeClass('ui-widget-header');
    $("#tabs-compte ul").addClass('ui-fix-compte');
    $("#tabs-resa ul").addClass('ui-fix-resa');
    $("#tabs-1-resa,#tabs-2-resa").css('background-color','#797979');
	
    $("#open,#ouvre_login").click(function(){$("div#panel").slideDown("slow");});
    $("#ouvre_login,#toggle span").click(function(){$("#toggle span").toggle();});    
    $("#close").click(function(){$("div#panel").slideUp("slow");});    
    $(".toggle_infos_commandes").click(function(){
        var a = $(this).attr('rel');
        $("#infos_commande-"+a).slideToggle("slow")
    });	
    
    $('#english-accueil,#english').hover(function(){
        $(this).stop().animate({opacity:1},{duration:500})
    },function(){
        $(this).stop().animate({opacity:0.8},{duration:500})
    });
    
    $("#date-110,#date-210,#date-details,#date-retour-details").datepicker({showOn: 'both', buttonImage: '/images/calendar.gif', dateFormat: 'dd/mm/yy', buttonImageOnly: true});
    $("#window_cgv").dialog({bgiframe: true,autoOpen: false,closeOnEscape: true,modal: true,resizable: false,minHeight: 100,buttons: {Ok: function() {$(this).dialog('close');}}});
    $("#cgv").dialog({bgiframe: true,autoOpen: false,closeOnEscape: true,modal: true,resizable: false,title: 'General terms and conditions of sale',height: 600,width: 750,buttons: {Close: function() { $(this).dialog('close'); }}});
    $("#date_manquante").dialog({bgiframe: true,autoOpen: false,closeOnEscape: true,minHeight:50,modal: true,buttons: {Ok: function() {$(this).dialog('close');}}});
    $("#dialog_resa").dialog({bgiframe: true,autoOpen: false,resizable: false,closeOnEscape: true,minHeight:140,width:500,modal: true,buttons: {'Cancel' : function() { $(this).dialog('close');}}});    
    $("#confirm_modif_compte").dialog({bgiframe: true,autoOpen: false,title: 'Recording information',closeOnEscape: true,minHeight:70,modal: true,buttons: {Ok: function() {$(this).dialog('close');}}});  
    $("#confirm_login").dialog({bgiframe: true,autoOpen: false,title: 'Reservation form',closeOnEscape: true,minHeight:70,modal: true,buttons: {Ok: function() {$(this).dialog('close');}}});
    
    $('a.panier').livequery('click',function(){
        var c = $(this).attr('rel');
        $("#window_suppression p").attr('id',c);
        $("#window_suppression").dialog({bgiframe:true,autoOpen:false,closeOnEscape:true,modal:true,resizable:false,minHeight:100,width:280,title:'Delete item',buttons:{
                'Confirm deletion':function(){
                var b= $('p',this).attr('id');
                $.get('/modules/boutique/ajax/delete_panier.php',{'id':b},function(){
                    b=null;
                    $.get('/modules/boutique/ajax/reload_panier.php',function(a){
                        $('#panier').empty().append(a);
                    })
                });
                $(this).dialog('close')
                },
                'Cancel':function(){$(this).dialog('close')}
            }
        });        
        $("#window_suppression").dialog('open')
    });
	
	$("#window_date").dialog({bgiframe: true,autoOpen: false,closeOnEscape: true,modal: true,resizable: false,minHeight: 100,width: 300,buttons: {
			'Confirm date': function(){$(this).attr('rel','valide').dialog('close');},
			'Cancel': function(){$(this).dialog('close');}
		}
    });
	
    $("#oubli_mdp").dialog({bgiframe: true,autoOpen: false,height: 300,modal: true,buttons: {
		    'Send email': function() {
			var email = $("#email_mdpp").val();
			var email_confirm = $("#email_confirm").val();			
			if(email == email_confirm){			    
			    jQuery.get('/cgi/ajax/check_mail.php', {'email': email}, function(data){
				$('div#panel .content').empty().append(data);
			    });
			    $("#oubli_mdp").dialog('close');
			}else{
			    $('#validateTips').empty().append("Emails are different.").addClass('msg_erreur');			    
			}
		    },
		    'Cancel': function() {$(this).dialog('close');}
	    }
    });
	
    $("#oubli_mdp_boutique").dialog({bgiframe: true,autoOpen: false,height: 300,modal: true,buttons: {
		    'Send email': function() {
			var email = $("#emailBoutique").val();
			var email_confirm = $("#email_confirmBoutique").val();			
			if(email == email_confirm){			    
			    jQuery.get('/cgi/ajax/check_mail.php', {'email': email}, function(data){
				$('#validateTipsBoutique').empty().append("The email has been sent.").addClass('msg_valide');
			    });
			}else{
			    $('#validateTipsBoutique').empty().append("Emails are different.").addClass('msg_erreur');			    
			}
		    },
		    'Close': function() {
			    $(this).dialog('close');
			    $('#validateTipsBoutique').empty().append("For better security, you will be sent an e-mail with a new password.").removeClass('msg_valide')
			    $("#emailBoutique").val('');
			    $("#email_confirmBoutique").val('');
		    }
	    }
    });
	
    $('#depart-110').change(function(){		
		var idStationDepart = $("#depart-110").val();
		var idStationDestination = $("#destination-110").val();	
		$.get('/cgi/ajax/update_horaire_station.php', {'idStationDepart': idStationDepart, 'idStationDestination': idStationDestination}, function(data){
			$('#horaire-110').empty().append(data);	
		});
		var idHoraire = $("#horaire-110").val();
		$.get('/cgi/ajax/update_liste_station.php', {'idStationDepart': idStationDepart, 'idStationDestination': idStationDestination, 'idHoraire': idHoraire}, function(data){
			$('#destination-110').empty().append(data);
		});	
	});
	
    $('#destination-110').change(function(){	
		var idStationDepart = $("#depart-110").val();
		var idStationDestination = $("#destination-110").val();			    
		$.get('/cgi/ajax/update_horaire_station.php', {'idStationDepart': idStationDepart, 'idStationDestination': idStationDestination}, function(data){
			$('#horaire-110').empty().append(data);	
		});
    });
    
    $('#depart-210').change(function(){		
		var idStationDepart = $("#depart-210").val();
		var idStationDestination = $("#destination-210").val();	
		$.get('/cgi/ajax/update_horaire_station.php', {'idStationDepart': idStationDepart, 'idStationDestination': idStationDestination}, function(data){
			$('#horaire-210').empty().append(data);	
		});
		var idHoraire = $("#horaire-210").val();
		$.get('/cgi/ajax/update_liste_station.php', {'idStationDepart': idStationDepart, 'idStationDestination': idStationDestination, 'idHoraire': idHoraire}, function(data){
			$('#destination-210').empty().append(data);
		});	
	});
	
    $('#destination-210').change(function(){	
		var idStationDepart = $("#depart-210").val();
		var idStationDestination = $("#destination-210").val();			    
		$.get('/cgi/ajax/update_horaire_station.php', {'idStationDepart': idStationDepart, 'idStationDestination': idStationDestination}, function(data){
			$('#horaire-210').empty().append(data);	
		});
    });
    
    // Chargement de formulaire selon ligne choisie
    
        $('#l110-details').livequery('click', function(){
            if( $('#l110-details:checked') ){
                $.post('/cgi/ajax/reload_form.php',{'idLigne': 1},function(data){
                    $('#form-voyage').empty().append(data);
                    $.datepicker.regional['fr'];
                    $("#date-details,#date-retour-details").datepicker({showOn:'both',buttonImage:'/images/calendar.gif',dateFormat:'dd/mm/yy',buttonImageOnly:true});
                });
            }
        });
        
        $('#l210-details').livequery('click', function(){
            if( $('#l210-details:checked') ){
                $.post('/cgi/ajax/reload_form.php',{'idLigne': 2},function(data){
                    $('#form-voyage').empty().append(data);
                    $.datepicker.regional['fr'];
                    $("#date-details,#date-retour-details").datepicker({showOn:'both',buttonImage:'/images/calendar.gif',dateFormat:'dd/mm/yy',buttonImageOnly:true}); 
                });                
            }
        });
    
    // Aller simple / Aller retour
    
        $('#simple').live('click', function(){
            if( $('#simple:checked') ){
                $('#bloc-type-voyage').slideUp();
            }
        });
        
        $('#retour').live('click', function(){
            if( $('#retour:checked') ){
                $('#bloc-type-voyage').slideDown();
            }
        });
        
    // Chargement du select pour le nombre de passager
    
        if($('#nbr-passagers').size() > 0){
            var max = 99;
            var options = ""; 
            for(var i = 2;i < max;i++){
                options = "<option value='"+i+"'>"+i+"</option>";
                $('#nbr-passagers').append(options);
                
            }
        }
    
    // Ajout / suppression de li selon nombre de passager
    
        $('#nbr-passagers, #nbr-passagers-modif').livequery('change', function(){
            var nbrPassager = $(this).val();
            var nbrLi = $('#ul-passagers li').size();
            if(nbrPassager > nbrLi){
                
                var i=nbrLi;
                var j=0;
                var liPassager = "";
                
                for(var i;i < nbrPassager;i++){
                    j = i+1;
                    liPassager = "<li id='li_"+j+"'><strong>Passenger n&deg;"+j+" :</strong><p>Age of passenger :<br /><br /><label for='moins26_"+j+"'>Under 26 years old</label>&nbsp;<input type='radio' name='age_"+j+"' id='moins26_"+j+"' value='1' />&nbsp;&nbsp;&nbsp;&nbsp;<label for='plus26_"+j+"'>Over 26 years old</label>&nbsp;<input type='radio' name='age_"+j+"' id='plus26_"+j+"' checked='checked' value='2' /></p></li>";
                    $('#ul-passagers').append(liPassager);
                    
                }
                
            }else{
                $('#ul-passagers li').each(function(){
                    var sId = $(this).attr('id');
                    var aId = sId.split('_');
                    var id  = aId[1];
                    
                    if(parseInt(id) > parseInt(nbrPassager)){
                        $(this).remove();
                    }
                });
            }
        });
        
    // Changement de la station de départ
    
        $('#depart').livequery('change', function(){
            var depart  = $("#depart").val();
            var arrivee = $("#arrivee").val();
            $.get('/cgi/ajax/update_horaire_station.php',{'idStationDepart':depart,'idStationDestination':arrivee},function(data){
                $('#horaire-depart').empty().append(data);
            });
            var horaire = $('#horaire-depart').val();
            $.get('/cgi/ajax/update_liste_station.php',{'idStationDepart':depart,'idStationDestination':arrivee,'idHoraire':horaire},function(data){
                $('#arrivee').empty().append(data);
            })
        });
        
    // Test de la validité du bon de remise
    
        $('#check-bon-details').live('click',function(){
            var bon = $("#bon").val();
            $.post('/cgi/ajax/check_remise.php',{'bon': bon}, function(data){
                if(data){
                    $('#rem').val(data);
                    $('#remise-message').empty().append('Your discount is valid.').removeClass('erreur').addClass('valide');
                    $('#check-bon-details,#bon').attr('disabled','disabled');
                }else{
                    $('#remise-message').empty().append('Your discount isn\'t valid.').removeClass('valide').addClass('erreur');
                }
            });
        });
    
    // PANIER >> Modification d'un voyage
        
        $('a.edit-panier').livequery('click',function(){
            var index = $(this).attr('rel');
            var url = '/booking/edition-ticket,'+index+'.html';
            $(location).attr('href',url);
        });
        
    // Annulation des modifs      
        $('#cancel-form-details').livequery('click',function(){
            var url = '/order/step,1/your-reservations.html';
            $(location).attr('href',url);
        });
        
        
    // Test avant envoi du formulaire
        $('#sumbit-form-details').live('click',function(){
            
            var ligne       = $('#ligne').val();
            var depart 	    = $('#depart').val();
            var destination = $('#arrivee').val();
            var date 	    = $('#date-details').val();
            var horaire 	= $('#horaire-depart').val();
            var isAR 	    = $('#type-voyage').val();
            var dateR 	    = $('#date-retour-details').val();
            var horaireR 	= $('#arrivee-retour').val();
            
            var erreurStation   = "<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>There are no buses serving this station at the times selected.";
            var erreurDateR     = "The date chosen is earlier than the date you chose to leave on.<span class='ui-icon ui-icon-closethick' id='close_dialog_resa_erreur>";
            var erreurHoraireR  = "There are no buses serving<br /> this station at the times selected.<br /><span class='ui-icon ui-icon-closethick' id='close_dialog_resa_erreur>";
            var erreurBL        = "This time is only possible from Monday to Friday,<br /> excluding bank holidays.<br /><span class='ui-icon ui-icon-closethick' id='close_dialog_resa_erreur>";
    
            if(date != ''){
                
                $.get('/cgi/ajax/check_date.php', {'date': date, 'horaire': horaire}, function(valid){
                    
                    if(valid == "ok" ){
                        
                        $.get('/cgi/ajax/test_reservation.php', {'depart': depart,'destination': destination,'date': date,'horaire': horaire}, function(data){
                            
                            if(data == 1){
                                
                                $.get('/cgi/ajax/horairesAR.php', {'depart': depart,'destination': destination}, function(data){
                                        
                                        if($('#retour').is(':checked')){
                                            
                                            if(dateR != ""){
                                            
                                                $.get('/cgi/ajax/get_horaire_arrivee.php', {'depart': destination,'destination': depart, 'horaire': horaireR}, function(data){
                                                    
                                                    if(data != 7){
                                                        
                                                        $.get('/cgi/ajax/check_date_horaireR.php', {'destination': destination, 'date': date, 'horaire': horaire, 'dateR': dateR, 'horaireR': horaireR}, function(data){
                                                                                                                    
                                                            if(data == 1){
                                                                $('#details-resa').submit();
                                                            }
                                                            if(data == 2){
                                                                $('#erreurs-form').empty().append('This time is only possible from Monday to Friday, excluding bank holidays.').slideDown();
                                                            }
                                                            if(data == 3){
                                                                $('#erreurs-form').empty().append('The date chosen is earlier than the date you chose to leave on.').slideDown();
                                                            }
                                                            
                                                        });
                                                    
                                                    }else{
                                                        $('#erreurs-form').empty().append('There are no buses serving this station at the times selected').slideDown();
                                                    }
                                                });
                                                
                                            }else{
                                                $('#erreurs-form').empty().append('Please specify a date.').slideDown();
                                            }
                                            
                                        }else{
                                            $('#details-resa').submit();
                                        }
                                    
                                });
                                
                            }
                            if(data == 2){
                                $('#erreurs-form').empty().append('There are no buses serving this station at the times selected.').slideDown();
                            }
                        });
                    }else{
                        $('#erreurs-form').empty().append(valid).slideDown();
                    }
                });
                
            }else{
                $('#erreurs-form').empty().append('Please specify a date.').slideDown();
            }
        });
    
    $("#valid_resa-110").click(function(){
        var l=$('#depart-110').val();
        var m=$('#destination-110').val();
        var n=$('#date-110').val();
        var o=$('#horaire-110').val();
        
        var r="<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>There are no buses serving this station at the times selected.";
       
        if(n!=''){
            $.get('/cgi/ajax/check_date.php',{'date':n,'horaire':o},function(k){
                if(k=="ok"){
                    $.get('/cgi/ajax/test_reservation.php',{'depart':l,'destination':m,'date':n,'horaire':o},function(j){
                        if(j==1){
                            $('#formReservation110').submit();
                        }
                        if(j==2){
                            $('#date_manquante').empty().append(r).dialog('open')
                        }
                    })
                }else{
                    $('#date_manquante').empty().append(k).dialog('open')
                }
            })
        }else{
            $("#date_manquante").dialog('open')
        }
    });
    
    $("#valid_resa-210").click(function(){
        var l=$('#depart-210').val();
        var m=$('#destination-210').val();
        var n=$('#date-210').val();
        var o=$('#horaire-210').val();
        
        var r="<span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>There are no buses serving this station at the times selected.";
        
        if(n!=''){
            $.get('/cgi/ajax/check_date.php',{'date':n,'horaire':o},function(k){
                if(k=="ok"){
                    $.get('/cgi/ajax/test_reservation.php',{'depart':l,'destination':m,'date':n,'horaire':o},function(j){
                        if(j==1){
                            $('#formReservation210').submit();
                        }
                        if(j==2){
                            $('#date_manquante').empty().append(r).dialog('open')
                        }
                    })
                }else{
                    $('#date_manquante').empty().append(k).dialog('open')
                }
            })
        }else{
            $("#date_manquante").dialog('open')
        }
    });
	
    $("#modif_compte").click(function(){	
		var id = $('#id_compte_client').val();
		var email = $('#email_compte').val();
		var confirmation_email = $('#confirmation_email').val();
		var mot_de_passe = $('#mot_de_passe').val();
		var confirmation_mot_de_passe = $('#confirmation_mot_de_passe').val();
		var nom = $('#nom').val();
		var prenom = $('#prenom').val();
		var societe = $('#societe').val();
		var adresse = $('#adresse').val();
		var code_postal = $('#code_postal').val();
		var ville = $('#ville').val();
		var pays = $('#pays').val();
		var telephone = $('#telephone').val();
		var mobile = $('#mobile').val();
		var fax = $('#fax').val();						
		if($('#email_compte').val() == $('#confirmation_email').val()){
		    if($('#mot_de_passe').val() == $('#confirmation_mot_de_passe').val()){	
				$.post('/cgi/ajax/update_compte.php', {'id': id,'email': email,'mot_de_passe': mot_de_passe,'nom': nom,'prenom': prenom,'societe': societe,'adresse': adresse,'code_postal': code_postal,'ville': ville,'pays': pays,'telephone': telephone,'mobile': mobile,'fax': fax}, function(data){    
					$('#confirm_modif_compte').empty().append(data).dialog('open');
				}, 'script');		
		    }else{		    
			    var data = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Passwords are different, please try again.';
				$('#confirm_modif_compte').empty().append(data).dialog('open');		
		    }
		}else{
		    var data = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Emails are different, please try again.';
		    $('#confirm_modif_compte').empty().append(data).dialog('open');	    
		}
    });
    
    $("#bt_connect").livequery('click', function(){   	
		var login = $("#login").val();
		var mdp = $("#mdp").val();		
		if(login != ''){
		    if(mdp != ''){
				$.post('/cgi/ajax/check_ident.php', {'login': login, 'mdp': mdp}, function(data){ $('div#panel .content').empty().append(data); });
		    }else{		
				var data = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please enter your login.';
				$('#confirm_login').empty().append(data).dialog('open');			
		    }
		}else{
		    var data = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please enter your password.';
		    $('#confirm_login').empty().append(data).dialog('open');		    
		}
    });
    
    $("#bt_deco").livequery('click', function(){
        $.post('/cgi/ajax/deco.php', function(data){ $(location).attr('href','/home.html'); });
    });
    
    $("#lien_deco").livequery('click', function(){
        $.post('/cgi/ajax/deco.php', function(data){ $(location).attr('href','/home.html'); });
    });    
    
    $("#bt_re").livequery('click', function(){    
		$.post('/cgi/ajax/recharge_formulaire.php', function(data){ $('div#panel .content').empty().append(data); });
    });
    
    $("#bt_compte").livequery('click', function(){ $(location).attr('href','/my-account.html'); });
    
    $("#link_mdp").livequery('click', function(){ $("#oubli_mdp").dialog('open'); });
    
    $("#link_mdp_boutique").livequery('click', function(){ $("#oubli_mdp_boutique").dialog('open'); });
    
    $("#open_cgv").livequery('click', function(){
		$("#cgv").dialog('open');
		$("#content_cgv").load('/cgi/ajax/cgv.php', function(){});
    });
    
    if(!$.browser.msie){
		$('#isAR').livequery('change',function(){ $('#afficheFormAR').slideToggle('slow'); })
    }
    
    $('#labelAR').livequery('click',function(){ $('#isAR').checked; });
    
    $('#continuer,#recommencer').livequery('click',function(){ $('#dialog_resa').dialog('close'); });
	
    $('#poursuivre').livequery('click',function(){ $(location).attr('href','/order/step,1/your-reservations.html'); });
    
    $('#close_dialog_resa_erreur').livequery('click',function(){ $('#dialog_resa_erreur').fadeOut(); });
    
    $('#impression-ticket').livequery('click',function(){
		var url = $(this).attr('rel');
		window.open(url, '_blank');
    });
    
    $('#identifiant').livequery('click',function(){ $(this).val(''); });
    
    $('#password').livequery('click',function(){ $(this).val(''); });
	
    $("input.quantite").livequery('keyup', function(){		
		var id = $(this).attr('rel');
		var quantite = $(this).val();
		jQuery.get('/modules/boutique/ajax/update_panier.php', {'id':id, 'quantite':quantite}, function(data){
			$('#panier').empty();
			$('#panier').append(data);
		});
	});
    
    $("#formCgv").livequery('submit', function(){
		if( $('#valid_cgv').is(':checked') ){
				return true;
		}else{
			$("#window_cgv").dialog('open');
			return false;
		}
    });
    
    
    /*** Remise jeunes *********************************************************/
    
        $("#isjeune").livequery('click',function(){
            if( $(this).is(':checked') ){
                $("#valjeune").val( 1 );
            }else{
                $("#valjeune").val( 0 );
            }
           $("#remise-jeune ").submit();
        });
    
    /***************************************************************************/
});

