﻿var regPhone = new RegExp(/^[0-9]{10}$/);
var regPhone = new RegExp(/^[0-9]{10}$/);
var regNum = new RegExp(/^[0-9]$/);
var mailReg = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/);


/************************************/

$(function(){
	
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	
	if(sPage == "index.php") {
	}
	
	setUpCountries();
	setUpStations();
	
	/*
	$("#fields_login,#fields_password,#fileds_numero,#fileds_email").focus(function(){
		$(this).val('');
	});
	$("#fields_date_retour,#fields_date_depart").focus(function(){
		$(this).val('');
	});
	*/
	
	$("#fields_password,#fileds_numero,#fileds_email").focus(function(){
		$(this).val('');
	});
	
	$("#fields_login").focus(function(){
		if ($("#fields_login").val() == "Identifiant") {
			$(this).val('');
		}
	});
	
	afficheMaps();
	validFormEspaceClient();
	validFormMailPerdu();
	validFormMouteurResera();
	
	//$('#fields_pays_location').bind('change',getVillesByPays);	
	//$('#fields_ville_depart').bind('change',getVillesRetourByDepart);
	
	if($('#popinOverlay').length){
		resizeBlocOverlay();
		resizeOverlayForPopin();	
	}
	
});

function afficheMaps(){
	$('#clique-maps').unbind('click');
	$('#clique-maps').bind('click',function(){
		load();
		return false;
	});	
}
function validFormMouteurResera(){		// fonction de validation des formulaires
	$('#reserver').unbind('click');
	$('#reserver').bind('click',function(){
		is_ok = true;
		$('label, input').removeClass('error');
		$('.inputOblig').each(function(){		// obligation des input	
			if(!$(this).val()){
				$('label',$(this).parents('p')).addClass('error');
	
				is_ok = false;
			}
		});
		$('.selectOblig').each(function(){		// obligation des select
			if($(this).attr("selectedIndex")==0){
				$('label',$(this).parents('p')).addClass('error');
				is_ok = false;
			}
		});
		
		
		
		var date_depart = $('#fields_date_depart').val();
		var date_retour = $('#fields_date_retour').val();
		var heure_depart = $('#fields_heure_depart').val();
		var heure_retour = $('#fields_heure_retour').val();
		var ville_depart = $('#fields_ville_depart').val();
		var ville_retour = $('#fields_ville_retour').val();
		var pays_location = $('#fields_pays_location').val();
		var pays_residence = $('#fields_pays_residence').val();
		var age = $('#fields_age').val();
		
		var exp = date_depart.split('/');
		var exp2 = heure_depart.split(":");
		var pickup_date = new Date(Number(exp[2]), (Number(exp[1])-1), Number(exp[0]), Number(exp2[0]), Number(exp2[1]), 0);
		

		var exp = date_retour.split('/');
		var exp2 = heure_retour.split(":");
		var return_date = new Date(Number(exp[2]), Number(exp[1]-1), Number(exp[0]), Number(exp2[0]), Number(exp2[1]), 0);
		
		var today =  new Date();
		today0 = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
		today3 = new Date(today.getFullYear(), today.getMonth(), today.getDate(), (Number(today.getHours()) + 3), today.getMinutes(), 0);
		
		var errorDate = "";
		if (pickup_date.getTime() <= today0.getTime()) {
			is_ok = false;
			$('label', $('#fields_date_depart').parents('p')).addClass('error');
			errorDate = "Veuillez choisir une date de départ supérieure ou égale à  celle du jour.";
		}
		else {
		
			
			//alert(pickup_date.toString() + " " + today3.toString());
			if (pickup_date.getTime() <= today3.getTime()) {
				is_ok = false;
				$('label', $('#fields_date_depart').parents('p')).addClass('error');
				errorDate = "Veuillez choisir une heure de départ supérieure de 3 heures à  l'heure du jour.";
			}
		}
		
		if(pickup_date.getTime() > return_date.getTime()){
			
			is_ok = false;
			$('label',$('#fields_date_retour').parents('p')).addClass('error');
			errorDate = "Veuillez choisir une heure de départ antérieur à la date de retour.";
		}
		
		if(age <  Number(19) ) {
			is_ok = false; 
			$('label',$('#fields_age').parents('p')).addClass('error');
		}
		
		
			
		if(errorDate != "") {
			alert(errorDate);
		}
		
		if(is_ok){
			//quick authentication
			var login = $('#fields_login').val();
			var password = $('#fields_password').val();

			var logme = true;
			if((login == "Identifiant") && (password == "Mot de passe")) logme = false;
			if((login == "") || (password == "") || (login == null) || (password == null)) logme = false;
			
			if(logme) {
				var vars = 'action=quick_auth&login='+login+'&password='+password;
				$.ajax({
					type: "POST",url:"./include/config.inc.php", data: vars,
					success: function(data){
						if (data != "") {
							alert(data);
						}	
						
						document.location="reservation/etape2.php?date_depart="+date_depart+"&date_retour="+date_retour+"&heure_depart="+heure_depart+"&heure_retour="+heure_retour+"&ville_depart="+ville_depart+"&ville_retour="+ville_retour+
						"&pays_location="+pays_location+"&pays_residence="+pays_residence+"&age="+age;
						return true;
					}
				}); 
				
				/*
				document.location="reservation/etape2.php?date_depart="+date_depart+"&date_retour="+date_retour+"&heure_depart="+heure_depart+"&heure_retour="+heure_retour+"&ville_depart="+ville_depart+"&ville_retour="+ville_retour+
				"&pays_location="+pays_location+"&pays_residence="+pays_residence+"&age="+age;
				return true;
				*/
			}else {
				document.location="reservation/etape2.php?date_depart="+date_depart+"&date_retour="+date_retour+"&heure_depart="+heure_depart+"&heure_retour="+heure_retour+"&ville_depart="+ville_depart+"&ville_retour="+ville_retour+
				"&pays_location="+pays_location+"&pays_residence="+pays_residence+"&age="+age;
				return true;
			}
			
		}	
		
	});
}
function validFormEspaceClient(){		// fonction de validation des formulaires
	$('#envoyer-client').unbind('click');
	$('#envoyer-client').bind('click',function(){
		error = true;
		$('label, input').removeClass('error');
		$('#form-identification .inputOblig').each(function(){		// obligation des input
			if(!$(this).val()){
				$('label').removeClass('label');
				$('#form-identification label',$(this).parents('#form-identification p')).addClass('error');
				
				error = false;
			}
		});
		if(!verfierEmail($('#email-client').val())){	// format de l'email
			error = false;
			$('label',$('#email-client').parents('p')).addClass('error');
		}
	
	});
}

function validFormMailPerdu(){		// fonction de validation des formulaires
	$('#envoyer-client-email').unbind('click');
	$('#envoyer-client-email').bind('click',function(){
		$('#pass_msg').hide();
		isOk = true;
		$('label, input').removeClass('error');
		if(!verfierEmail($('#login-perdu').val())){ 	// format de l'email
			isOk = false;
			$('label').removeClass('label');
			$('label',$('#login-perdu').parents('p')).addClass('error');
		}
		
		if(isOk) {
			$("#form-mail").submit();
		}
		
	});
}

function verfierEmail(email){
	var reg = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]-{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');
	if(reg.test(email))
		return true;
	else
		return false;
}

function getVillesByPays(){
}
function getVillesRetourByDepart(){
}

function authenticate(){
	var login = $('#fields_login').val();
	var password = $('#fields_password').val();
	alert(login + "  " + password);
	if((login == "Identifiant") && (password == "Mot de passe")) return;
	if((login == "") || (password == "")) return;
	
	var vars = 'action=quick_auth&login='+login+'&password='+password;
	$.ajax({
		type: "POST",url:"./include/config.inc.php", data: vars,
		success: function(data){
			alert(data);
		}
	}); 
	
}

/*********************************************form resa dynamics**********************************************/
var countriesList;
var stations;
var resCountryCode;


function setUpCountries() {
	var vars = 'action=getCountries';
	$.ajax({
		type: "POST",url:"./include/config.inc.php", data: vars,
		success: function(data){
			var data = data.split("</head>");
			var countries = data[1].split(";");
			var country;
			for(var i = 0; i < countries.length; i++) {
				country =  countries[i].split("|");
				if(countries[i] == "") continue;
				
				countriesList += '<option value="'+countries[i]+'">' + country[0].toUpperCase() +'</option>';
			}
		}
	}); 
	//afficher les pays aprÃ¨s un passage de la souris
	//$('#form_resa').bind('mouseover', showCountries);
	
	runShowingTimeout();
	
}

function runShowingTimeout() {
	setTimeout(function(){
		showCountries();
		if( $("#fields_pays_residence").val() == "0" || $("#fields_pays_residence").val() == null || $("#fields_pays_location").val() == null || $("#fields_pays_location").val() == "0") {
			runShowingTimeout();
		}
	}, 100);
}

function showCountries() {
	
	if(countriesList == null) return;
	$("#fields_pays_residence, #fields_pays_location, #ctl00_C_ux_id_com_pays").html('<option value="0">S&eacute;lectionner une destination</option>' + countriesList);
	//$('#form_resa').unbind('mouseover');

	try{
  		if (selectedResCountry != null) {
			$("#fields_pays_residence").val(selectedResCountry);
			
		}
  	}
	catch(err) {
		getCountryCodeFormIp();
	}
	
	if (selectedCountry != null) {
		
		try{
	  		if(age != null) $("#fields_age").val(age);
	  	}
		catch(err) {}
		
		$("#fields_pays_location").val(selectedCountry);
		showStations();
	} 
}

function setUpStations() {
	$('#fields_pays_location').bind('change', showStations);
	$("#fields_ville_depart").bind('change', showReturnStations);
}

function showStations() {
	var country = $("#fields_pays_location").val();
	var vars = 'action=getStations&country=' + country;
	$.ajax({
		type: "POST",url:"./include/config.inc.php", data: vars,
		success: function(data){
			var data = data.split("</head>");
			stations = data[1].split(";");
			var station;
			var stationsList;
			for(var i = 0; i < stations.length; i++) {
				station =  stations[i].split("|");
				if(stations[i] == "") continue;
				
				stationsList += '<option value="'+stations[i]+'">' + station[0].toUpperCase() +'</option>';
			}
			$("#fields_ville_depart").html('<option value="0">S&eacute;lectionner une ville</option>' + stationsList);	
			$("#fields_ville_retour").html('<option value="0">S&eacute;lectionner une ville</option>' + stationsList);		
			
			if (selectedPickupStation != null) {
				$("#fields_ville_depart").val(selectedPickupStation);
				showReturnStations();
				
				//selectedPickupStation = null;
			}
			
		}
	}); 
}

function getCountryCodeFormIp() {
	var vars = "";
	$.ajax({
		type: "POST",url:"./ip_country.php", data: vars,
		success: function(data){
			
			$("#fields_pays_residence").val(data);
		}
	}); 
}


function showReturnStations(){
	var station;
	var stationsList;
	for(var i = 0; i < stations.length; i++) {
		station =  stations[i].split("|");
		if(stations[i] == "") continue;
		
		if (stations[i] == $("#fields_ville_depart").val()) {
			stationsList += '<option value="' + stations[i] + '" selected>' + station[0].toUpperCase() + '</option>';
		}
		else {
			stationsList += '<option value="' + stations[i] + '">' + station[0].toUpperCase() + '</option>';
		}
	}
	$("#fields_ville_retour").html('<option value="0">S&eacute;lectionner une ville</option>' + stationsList);	
	
	if (selectedReturnStation != null) {
		$("#fields_ville_retour").val(selectedReturnStation);
		selectedReturnStation = null;
	}
	
}


/*********************************************la popine**********************************************/
function showPopin(id){	
	var overlay = $('#popinOverlay');	
	overlay.css({
		opacity: 0.7,
		display: 'block'
	}).fadeIn();
	
	$('#'+id).show();
	
	setPopinPosition(id);
	$('.btClose,.btReset').bind('click', function(){
		closePopin(id);
		return false;
	})
}
function closePopin(id){
	var overlay = $('#popinOverlay');
	overlay.hide();
	$('#'+id).hide();
}
function setPopinPosition(id){
	
	var dim = getPageSize();
	var scroll = getPageScroll();
	
	var popin = $('#'+id);

	popin.css({
		top: scroll[1] + (dim[3] / 10),
		left: (dim[2]-$(popin).width())/2,
		opacity: 1,
		display: 'block'
	}).fadeIn();
	
}
function resizeOverlayForPopin(){
	$(window).bind('resize',function(){
		resizeBlocOverlay();
	});
	
	$(window).bind('scroll',function(){
		resizeBlocOverlay();
	});	
}	

function resizeBlocOverlay(){
	
	var scroll = getPageScroll();
	var overlay = $('#popinOverlay');
	var hi = getHeight() + scroll[1];
	overlay.height(hi);
}

function getHeight(){
	if(window.innerHeight || window.innerWidth)
		return window.innerHeight ;
	return document.documentElement.clientHeight ;
}

function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};

function getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

/********************************************/
/***envoie newsletter**/

function registerNewsletter() {
	var errorMsg = "email invalide";
	
	if($("#fileds_email").val() != "" && $("#fileds_email").val() != null ) {
		Exp = new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,}")
		if (!Exp.test($("#fileds_email").val())) {
			alert(errorMsg);
		}else {
			$("#newsletter_loader").show();
			var vars = 'email=' + $("#fileds_email").val();
			$.ajax({
			type: "POST",url:"./include/newsletter_registration.php", data: vars,
			success: function(data){
					if(data == "0") {
						alert("Vous Ãªtes dÃ©jÃ  abonnÃ© la newsletter Ooloc");
					} else if (data == "1") {
						alert("Vous Ãªtes dÃ©sormais inscrit Ã  la newsletter Ooloc");
					}
					$("#fileds_email").val("Votre email ici");
					$("#newsletter_loader").hide();
				}
			}); 
		}
		
	} else {
		alert(errorMsg);
	}
	
}

/***info tel**/

function phoneRequest() {
	var errorMsg = "Tapez votre numÃ©ro de tÃ©lÃ©phone.";
	
	if ($("#fileds_numero").val() != "" && $("#fileds_numero").val() != null && $("#fileds_numero").val() != "Votre numÃ©ro ici") {
		$("#info_loader").show();
		var vars = 'telephone=' + $("#fileds_numero").val();
		$.ajax({
			type: "POST",url:"./mail/mail_tele.php", data: vars,
			success: function(data){
					if(data == "0") {
						alert("Une erreur s'est produite, vos informations n'ont pas pu Ãªtre envoyÃ©es. Veuillez rÃ©essayer plus tard.");
					} else if (data == "1") {
						alert("Vos informations viennent de nous parvenir, un conseiller va prendre contact avec vous rapidement.");
					}
					$("#fileds_numero").val("Votre numÃ©ro ici");
					$("#info_loader").hide();
				}
			}); 
	} else {
		alert(errorMsg);
	}
	
}

/****************Contact****************************/

function contactRequest() {
	$("#contact_loader").show();
	//$("label[for^='contact_nom']").attr("style", "color:red");
	$("label[for^='contact_nom']").attr("style", "");
	$("label[for^='contact_prenom']").attr("style", "");
	$("label[for^='contact_email']").attr("style", "");
	$("label[for^='contact_tel']").attr("style", "");
	$("label[for^='fields_pays_residence']").attr("style", "");
	$("label[for^='contact_message']").attr("style", "");
	
	var errors = 0;
	
	if(($("#contact_nom").val() == "")) {
		$("label[for^='contact_nom']").attr("style", "color:red");
		errors++;
	}
	
	if(($("#contact_prenom").val() == "")) {
		$("label[for^='contact_prenom']").attr("style", "color:red");
		errors++;
	}
	
	if(($("#contact_email").val() == "")) {
		$("label[for^='contact_email']").attr("style", "color:red");
		errors++;
	}else {
		Exp = new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,}")
		if(!Exp.test($("#contact_email").val())) {
			$("label[for^='contact_email']").attr("style", "color:red");
			errors++;
		}
	}
	
	if(($("#contact_tel").val() == "")) {
		$("label[for^='contact_tel']").attr("style", "color:red");
		errors++;
	}
	
	if(($("#fields_pays_residence").val() == 0)) {
		$("label[for^='fields_pays_residence']").attr("style", "color:red");
		errors++;
	}
	
	if(($("#contact_lang").val() == 0)) {
		$("label[for^='contact_lang']").attr("style", "color:red");
		errors++;
	}
	
	if(($("#contact_objet").val() == 0)) {
		$("label[for^='contact_objet']").attr("style", "color:red");
		errors++;
	}
	
	if(($("#contact_message").val() == "")) {
		$("label[for^='contact_message']").attr("style", "color:red");
		errors++;
	}
	
	if(errors <= 0) {
		var vars = "nom=" + $("#contact_nom").val() + "&prenom=" + $("#contact_prenom").val() 
				 + "&email=" + $("#contact_email").val() + "&tel=" + $("#contact_tel").val()
				 + "&pays=" + $("#fields_pays_residence").val() + "&message=" + $("#contact_message").val()
				 + "&lang=" + $("#contact_lang").val() + "&objet=" + $("#contact_objet").val();
		$.ajax({
			type: "POST",url:"mail/mail_contact.php", data: vars,
			success: function(data){
					//alert(data);
						
					if (data == "1") {
						alert("Votre demande vient de nous parvenir, elle sera traitÃ©e dans les plus brefs dÃ©lais.");
					}else {
						alert("Une erreur s'est produite, vos informations n'ont pas pu Ãªtre envoyÃ©es. Veuillez rÃ©essayer plus tard.");
					}
					$("#contact_nom").val("");
					$("#contact_prenom").val("");
					$("#contact_email").val("");
					$("#contact_tel").val("");
					$("#fields_pays_residence").val(0);
					$("#contact_lang").val(1);
					$("#contact_objet").val(1);
					$("#contact_message").val("");
					$("#contact_loader").hide();
				}
			}); 
	}else {
		$("#contact_loader").hide();
	}
	
	
	
}


