
// Location selectors texts
var Textes	= { go_from: "", go_dest: "", back_from: "", back_dest: "" };
var Cart	= { pidGo: 0, pidBack :0, qty: 0 };

/*
 var backup = {
	go:   { time: {date: "", hour: ""}, from: {type: "", zipcode: "", LatLng: ""}, dest: {type: "", zipcode: "", LatLng: ""} },
	back: { time: {date: "", hour: ""}, from: {type: "", zipcode: "", LatLng: ""}, dest: {type: "", zipcode: "", LatLng: ""} }
};
*/

$(document).ready( function()
{
	/***********************************/
	/****    Common to ALL steps    ****/
	/***********************************/
	
	var step = $("#next_step").val() - 1;
	
	// Auto bind on change event
	$("input.JQ_refresh").each( function ()
	{
		$(this).change( function() { Get_Rates($(this)); })
	});
	$("select.JQ_refresh").each( function ()
	{
		$(this)
		.change( function() { Get_Rates($(this)); })
		.keydown( function(e) { if (e.keyCode==38 || e.keyCode==40 || e.keyCode == 33 || e.keyCode == 34)  Get_Rates($(this)); });
	});
	
	// Special case on change event
	$("#is_round").change( function()
	{
		if (RESULT.GO.rate == 0)		Get_Rates("GO");
		else if (RESULT.BACK.rate == 0)	Get_Rates("BACK");
		else if ($(this).val() == 1)	{ Calculate("BACK"); Calculate_Total(); }
		else							{ Calculate("GO");	 Calculate_Total(); }
	});
	
	// Location selectors
	$("input.location").each( function ()
	{
		Textes[$(this).attr("id")] = $(this).val();
		
		$(this)
		.focus( function()
		{
			if($(this).val() == Textes[$(this).attr("id")])
			{
				$(this).val("").Enable(false);
			}
		})
		.blur( function()
		{
			if($(this).val() == "")
			{
				$(this).val(Textes[$(this).attr("id")]);
				var step = $("#next_step").val() - 1;
				if (step == 1)  $(this).Enable(true);
			}
		})
		.keydown( function(e)
		{
			// Backspace = 8, Delete = 46, Alpha = 48-90, NumPad 96-111, Special > 185
			if	(e.keyCode==8 || e.keyCode==46 || e.keyCode > 185 ||
				(e.keyCode > 47 && e.keyCode < 91) || (e.keyCode > 95 && e.keyCode < 112))
			{
				$(this).Enable(false);
			}
		})
		.autocomplete("modules/ata_resa/getlocations.php" ,
		{
			extraParams: {ajax: 1},
			cacheLength: 50,
			matchContains: true,
			selectFirst: false,
			minChars: 3,
			max: 0,
			formatItem: function(value)   { return value[0] + " (" + value[2] + ")"; },
			formatResult: function(value) { return value[0]; }
		})
		.result( function(event, data , formatted)
		{
			var trip = $(this).attr("id").split("_");
			
			ATA[trip[0]][trip[1]].type		= data[1];
			ATA[trip[0]][trip[1]].zipcode	= data[2];
			ATA[trip[0]][trip[1]].LatLng	= data[3];
			
			$(this).Enable(true);  Get_Rates($(this));
		})
	});
	
	/*******************************/
	/****    ONLY for step 0    ****/
	/*******************************/
	if (step == 0)
	{
		$("#next_step_btn").addClass("disabled");
	}

	/*******************************/
	/****    ONLY for step 1    ****/
	/*******************************/
	if (step == 1)
	{
		$("#go_from").Enable(true);		$("#go_dest").Enable(true);
		$("#back_from").Enable(true);	$("#back_dest").Enable(true);
		
		$('#nb_adults').change(		function() { Calculate_Total(); });
		$('#nb_children').change(	function() { Calculate_Total(); });
		$('#nb_babies').change(		function() { Calculate_Total(); });
		
		Calculate("GO");  Calculate("BACK");  Calculate_Total();
		
		$("#is_round").click( function()
		{
			if ($("#is_round").is(":checked"))	$("#abs_box_BACK").hide();
			else								$("#abs_box_BACK").show();
		});
		
		$('#previous_step_btn').click( function() { window.location = '/'; } );
		
		$('#next_step_btn').click( function()
		{
			if ($(this).hasClass("disabled"))  return;
			
			$(this).addClass("disabled");
			$("#Total_Price").addClass("ac_loading");
			
			$.ajax({
				url: 'modules/ata_resa/step1_manager.php',
				dataType: "json",
				processData: false,
				dataFilter: function(data) { return data.replace("Array", ""); },	// JSON Bug
				data:
					"ajax=1&is_round=" + ($("#is_round").is(":checked") * 1) +
					"&go_from=" + URLEncode($("#go_from").val()) + "&go_dest=" + URLEncode($("#go_dest").val()) +
					"&go_minute=" + $("#go_minute").val() + "&back_minute=" + $("#back_minute").val() +
					"&back_from=" + URLEncode($("#back_from").val()) + "&back_dest=" + URLEncode($("#back_dest").val()) +
					"&nb_adults=" + $('#nb_adults').val() + "&nb_children=" + $("#nb_children").val() + "&nb_babies=" + $("#nb_babies").val() + "&nb_luggages=" + $("#nb_luggages").val(),
				success: function(data)
				{
					$("#Total_Price").removeClass("ac_loading");
					
					var resp = data;
					
					if (data.error)
						$(this).removeClass("disabled");
					else
					{
						if (resp.pidGo || resp.pidBack)
						{
							Cart.pidGo		= resp.pidGo;
							Cart.pidBack	= resp.pidBack;
							Cart.qty		= resp.qty;
							
							window.setTimeout(Check_to_Submit, 100);
						}
					}
				}
			});
		});
		
		// Add to cart products with delay
		function Check_to_Submit()
		{
			if (Cart.pidGo)
			{
				ajaxCart.add(Cart.pidGo, null, false, $('#GO_cart_add'), Cart.qty);
				Cart.pidGo = 0;
			}
			else if (Cart.pidBack)
			{
				if ( typeof($('#GO_cart_add').attr("disabled")) === "undefined" ||
					 $('#GO_cart_add').attr("disabled") === false )
				{
					ajaxCart.add(Cart.pidBack, null, false, $('#BACK_cart_add'), Cart.qty);
					Cart.pidBack = 0;
				}
			}
			
			if ( (typeof($('#GO_cart_add').attr("disabled")) === "undefined" && typeof($('#BACK_cart_add').attr("disabled")) === "undefined") ||
				 ($('#GO_cart_add').attr("disabled") === false && $('#BACK_cart_add').attr("disabled") === false) )
			{
				$('#frm-order').submit();
			}
			else
				window.setTimeout(Check_to_Submit, 250);
		}
	}       
	
	/*******************************/
	/****    ONLY for step 2    ****/
	/*******************************/
	if (step == 2)
	{
		$("#cancel_insurance_cart_lnk").click( function()
		{
			var quantity = 1 + (1 * $("#is_round").val());
			
			ajaxCart.add('14', null, false, $("#cancel_insurance_cart_lnk"), quantity * $("#persons").val());
		});
		
		$("#next_step_btn").click( function()
		{
			window.location = 'order-opc.php';
		});
	}
});

$(function ()
{
	$("#go_date")
	.datepicker({
		firstDay: 1,
		dateFormat: "dd/mm/yy",
		minDate: +2,
		showOn: "button",
		buttonImage: "themes/ata/img/calendar.gif",
		buttonImageOnly: true,
		nextText: "Suivant",
		prevText: "Précédent",
		dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
		dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre']
	})
	.change( function()
	{
		$( "#back_date" ).datepicker( "option", "minDate", $( "#go_date" ).val() );
	});
	
	$("#back_date")
	.datepicker({
		firstDay: 1,
		dateFormat: "dd/mm/yy",
		minDate: +1,
		showOn: "button",
		buttonImage: "themes/ata/img/calendar.gif",
		buttonImageOnly: true,
		nextText: "Suivant",
		prevText: "Précédent",
		dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
		dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre']
	});
	
	var minDate = $( "#back_date" ).datepicker( "option", "maxDate" );
});

function ataResaAddToCart(productId, multiply)	/****    ONLY for step 2    ****/
{
	var prodCatId	= $("#prod_cat_" + productId).val();
	var quantity	= 1;
	
	quantity += (1 * $("#is_round").val()); // if it's a round trip we have to add 2 times the product
	quantity *= multiply;					// if it's a vehicle, we have to multiply by needed cars
	
	if ((1 * prodCatId) == 5 || (1 * prodCatId) == 7)
	{
		if($("#abs_box_" + prodCatId).hasClass('shopping-off'))  return false;
		
		$("#abs_box_" + prodCatId).addClass('shopping-off');
		$("#abs_box_" + prodCatId).show();
	}
	
	ajaxCart.add(productId, null, false, $("#ata_product_lnk_" + productId), quantity);
	return true;
}

function Get_Rates(element)
{
	var compute		= true;
	var container	= "";
	
	$("input.location").each( function () { if ( ! $(this).hasClass("ac_OK") ) compute = false;  return compute; });
	
	if ( ! compute)  return;
	
	if (typeof element == "string")
		container = element;
	else
	{
		var trip	= element.attr("id");
		container	= trip.substring(0, trip.indexOf("_")).toUpperCase();
		// Container exists ?
		if ($("#" + container).length == 0)  container = "GO";
	}
	
	compute = false;
	var step = $("#next_step").val() - 1;
	if (step == 0)
	{
		// Step 0 : we use the same values as for "Go" (Reverse from <-> to) 
		ATA.back.from = ATA.go.dest;
		ATA.back.dest = ATA.go.from;
	}
	else if (step == 1)
	{
		if (typeof element != "string")
		{
			if (element.hasClass("location"))
			{
				// TODO : Step 1 : use the same values as for "Go" in waiting of coherent 
				// system for managing at least 4 adresses (Go from,dest & Back from,dest)
				ATA.back.from = ATA.go.dest;
				ATA.back.dest = ATA.go.from;
				$("#back_from").val($("#go_dest").val());
				$("#back_dest").val($("#go_from").val());
				compute = true;
			}
		}
	}
	
	$("#" + container + " .PriceBox").addClass("ac_loading");
	
	var send =
		"ajax=1&container=" + container + "&CalculateBoth=" + compute +
		"&go="	+ $("#go_date").val() + "|" + $("#go_hour").val() + "|" + $("#go_minute").val() + "|" +
				+ ATA.go.from.type + "|" + ATA.go.from.zipcode + "|" + ATA.go.from.LatLng + "|" +
				+ ATA.go.dest.type + "|" + ATA.go.dest.zipcode + "|" + ATA.go.dest.LatLng +
		"&back="+ $("#back_date").val() + "|" + $("#back_hour").val() + "|" + $("#back_minute").val() + "|" +
				+ ATA.back.from.type + "|" + ATA.back.from.zipcode + "|" + ATA.back.from.LatLng + "|" +
				+ ATA.back.dest.type + "|" + ATA.back.dest.zipcode + "|" + ATA.back.dest.LatLng;
	
	$.ajax({
		url: "modules/ata_resa/getrate.php",
		dataType: "json",
		processData: false,
		dataFilter: function(data) { return data.replace("Array", ""); },	// JSON Bug
		data: send,
		success: function(data)
		{
			if(data.error)
			{
				$("#" + data.container + " .JQ_detail").hide();
				$("#" + data.container + " .JQ_choose").slideDown();
				$("#next_step_btn").addClass("disabled");
			}
			else
			{
				var step			= $("#next_step").val() - 1;
				RESULT.GO.rate		= data.result.go.rate;
				RESULT.GO.taxi		= data.result.go.taxi;
				RESULT.BACK.rate	= data.result.back.rate;
				RESULT.BACK.taxi	= data.result.back.taxi;
				
				// TODO : remove this when 4 adresses become available
				if (data.CalculateBoth)	{ Calculate("GO"); Calculate("BACK"); }
				else					Calculate(data.container);
				
				if (step == 1)			Calculate_Total();
				// END TODO
			}
		},
		error: function(jqXHR, textStatus, errorThrown)
		{
			console.log("Ajax error : " + textStatus);
			console.log("Content    : " + jqXHR.responseText);
		},
		complete: function()
		{
			if ($("#GO .PriceBox").length > 0)	 $("#GO .PriceBox").removeClass("ac_loading");
			if ($("#BACK .PriceBox").length > 0) $("#BACK .PriceBox").removeClass("ac_loading");
		}
	});
}
function Calculate(container)
{
	var Rate = 0.0, Taxi = 0.0, Economy = 0.0;
	var step		= $("#next_step").val() - 1;
	
	// Container exists ?
	if ($("#" + container).length == 0)  container = "GO";

	if (step == 0)
	{
		Rate = RESULT.GO.rate;  Taxi = RESULT.GO.taxi;
		if ($("#is_round").is(":checked"))
		{
			Rate += RESULT.BACK.rate;  Taxi += RESULT.BACK.taxi;
		}
	}
	else
	{
		Rate = RESULT[container].rate;  Taxi = RESULT[container].taxi;
	}
	
	// Compute economy in € 
	if (Taxi > Rate)  Economy = Taxi - Rate;
	
	if (Economy)	$("#" + container + " .JQ_discount").show();
	else			$("#" + container + " .JQ_discount").hide();
	
	$("#" + container + " .JQ_rate").html( number_format(Rate, 2) );
	$("#" + container + " .JQ_taxi").html( number_format(Taxi, 2) );
	$("#" + container + " .JQ_economy").html( number_format(Economy,2) );
	
	$("#" + container + " .JQ_choose").hide();
	$("#" + container + " .JQ_detail").slideDown();
}

function Calculate_Total()
{
	var Total_People = 0, Total_Taxi_Nb = 0;
	var Total_Rate = 0.0, Total_Taxi = 0.0;
	var Total_Detail = "";
	
	Total_People += parseInt($("#nb_adults").val());
	Total_People += parseInt($("#nb_babies").val());
	Total_People += parseInt($("#nb_children").val());
	
	Total_Taxi_Nb	= Math.ceil(Total_People / 4); // 4 places in a Taxi
	Total_Rate		= RESULT.GO.rate;
	Total_Taxi		= RESULT.GO.taxi;
	Total_Detail	= "" + number_format(RESULT.GO.rate, 2) + " €";
	
	if ($("#is_round").is(":checked"))
	{
		Total_Rate += RESULT.BACK.rate;  Total_Taxi += RESULT.BACK.taxi;
		Total_Detail = "(" + Total_Detail + " + " + number_format(RESULT.BACK.rate, 2) + " €)";
	}
	
	Total_Rate = Total_Rate * Total_People;
	Total_Taxi = Total_Taxi * Total_Taxi_Nb;

	$("#JQ_Total_People").html(Total_People);
	$("#JQ_Total_Detail").html(Total_Detail);
	$("#JQ_Total_Rate").html(number_format(Total_Rate, 2));
	$("#JQ_Total_Taxi_Nb").html(Total_Taxi_Nb);
	$("#JQ_Total_Taxi").html(number_format(Total_Taxi, 2));
	
	// Compute economy in € 
	if (Total_Taxi > Total_Rate)
	{
		$("#JQ_Total_Economy").html(number_format(Total_Taxi - Total_Rate, 2));
		$("#JQ_Total_Discount").show();
	}
	else
		$("#JQ_Total_Discount").hide();

	// Animate
	$("#Total_Price").fadeTo('fast', 0, function() {
		$(this).fadeTo('fast', 1, function() {
			$(this).fadeTo('fast', 0, function() {
				$(this).fadeTo('fast', 1, function() {
					$(this).fadeTo('fast', 0, function() {
						$(this).fadeTo('fast', 1);
					});
				});
			});
		});
	});
}

// Plugin "Enable"
(function($)
 {
	$.fn.Enable = function(enable)
	{
		return this.each( function()
		{
			if (enable)
			{
				$(this).addClass("ac_OK");
				
				var activate = true;
				$("input.location").each( function ()
				{
					if ( ! $(this).hasClass("ac_OK"))  activate = false;
					return activate; // if return false, break "each" function
				});
				
				if (activate) $("#next_step_btn").removeClass("disabled");
			}
			else
			{
				$(this).removeClass("ac_OK");
				
				var trip		= $(this).attr("id");
				var container	= trip.substring(0, trip.indexOf("_")).toUpperCase();
				// Container exists ?
				if ($("#" + container).length == 0)  container = "GO";
				
				$("#" + container + " .JQ_detail").hide();
				$("#" + container + " .JQ_choose").slideDown();
				
				$("#next_step_btn").addClass("disabled");
			}	
		});
	};
})(jQuery)


// http://www.nyamsprod.com/blog/2009/comparaisons-dobjets-en-javascript
function isObjectsEquals(a, b)
{
	var isOK = true;
	for (var prop in a) {
		if (a.hasOwnProperty(prop)) {
			if (a[prop] !== b[prop]) {
				isOK = false;  break;
			}
		}
	}
	return isOK;
}
// http://kevin.vanzonneveld.net
function number_format (number, decimals, dec_point, thousands_sep)
{
	// Strip all characters but numerical ones.
	number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
	var n = !isFinite(+number) ? 0 : +number,
		prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		sep = (typeof thousands_sep === 'undefined') ? ' ' : thousands_sep,
		dec = (typeof dec_point === 'undefined') ? ',' : dec_point,
		s = '',
		toFixedFix = function (n, prec) {
			var k = Math.pow(10, prec);
			return '' + Math.round(n * k) / k;
		};
	// Fix for IE parseFloat(0.55).toFixed(0) = 0;
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

