/* 
 * RST Location calcul V3.0 (Jquery 1.5 version)
 * © 2008 > 2012 tix02.be
 */ 

var debugEnabled = 0;


function parseX(n) {
	if(n.slice(0,1) == '0') {
		return parseInt(n.slice(1));
	}
	else { 
		return parseInt(n);
	}
}

Date.prototype.difference = function(yy, mm, dd) { 
	var date1 = this;
	var date2 = yy == '' ? new Date() : new Date(yy, mm, dd);
	
	if(date1 >= date2) {
		var tmp = date1;
		date1 = date2;
		date2 = tmp;
	}

	var between = [
		date2.getFullYear() - date1.getFullYear(),
		date2.getMonth() - date1.getMonth(),
		date2.getDate() - date1.getDate()
	];
	

	var ynum = date2.getFullYear();
	var mlengths = [31, (ynum % 4 == 0 && ynum % 100 != 0 || ynum % 400 == 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	
	if(between[2] < 0) {
		between[1]--;
		var mnum = date1.getMonth();
		
		if(mnum < 0)
			mnum += 12;

		between[2] += mlengths[mnum]; // prendre la durée du mois 1, non du mois 2!!!
	}
		
	if(between[1] < 0) {
		between[0]--;
		between[1] += 12;
	}
	
	
	var isMonthComplete1 = (between[2] + 1) == mlengths[date1.getMonth()];
	var isMonthComplete2 = date1.getDate() == (date2.getDate() + 1);
	if(isMonthComplete1 && isMonthComplete2) {
		between[1]++;
		between[2] = 0;
	}
	
	return between;
}




var RST = {
	step: 1,
	steps: 6,
	date1: null,
	date2: null,
	dateDiff: null,
	ftype: null,
	fprice: null,
	vehicle: null,
	addedKMs: null,
	hour1:null,
	hour2:null,
	vehicle:null,
	
	price: 0,
	
	
	
	
	// initialize function
	// jQuery ready
	init: function() {		
		RST.step = 1;
		RST.setControls(false);
		
		for(var i = 1; i <= RST.steps; i++) {
			$('#rent-step'+ i +' h3').click(function(e) {
				var id = parseInt($(this).closest('div').attr('id').slice(-1));
				RST.toggle(id);
			});
		}
		

		$('#date1-ok').click(function(e) { RST.date.save(1); });
		$('#date2-ok').click(function(e) { RST.date.save(2); });
		$('#vehicle-ok').click(RST._vehicle.save);
		
		if($('#place-slt')) 
			$('#place-slt').change(function(e) {
				RST.place.sel2($('#place-slt').val());
			});
	
		$('#place-ok').click(RST.place.save);
		$('#omnium-ok').click(RST.Omnium.save);
		$('#kms-ok').click(RST._options.save);
			
		$('#nbr-km-supp').keyup(function(e) {
			var el = $('#nbr-km-supp');
			if(isNaN($(el).val().slice(-1)))
				$(el).val($(el).val().slice(0,-1));
			else {
				RST._options.add();
				RST.getPrice();
			}										
		});
		
		$('#nbr-km-supp').focus(function(e) {
			if($(this).val() == '0') { 
				$(this).val('');
			}									
		});
		
		$('#nbr-km-supp').blur(function(e) {
			if($(this).val() == '') { 
				$(this).val('0');
			}
		});	
		
		$('#omnium-cbx').click(RST.Omnium.select);

	},
	
	
	
	// enable or disable form's controls
	// jQuery ready
	setControls: function(set) {
		var op = set ? 1 : 0.3;
		$('#submit-step1').attr('disabled', !set);
		$('#form-controls').fadeTo('slow', op);
	},
	
	
	
	// go from a step to another
	// jQuery ready
	toggle: function(id) {
		//$('#rent-step'+ id +' p.error-box ').css('display', 'none');
		$('#rent-step'+ id +' p.error-box ').hide();
		
		if(RST.step > 3) { 
			RST.getPrice();
		}
			
		if(id == null) {
			$('#rent-step6 h3').removeClass('step-header');
			//$('#rent-step6').children('div:first').css('display','none');
			$('#rent-step6').children('div:first').hide();
			return;
		}

		
		if(RST.step >= id) {
			var div = $('#rent-step'+ id).children('div:first');
			var display = $(div).css('display') == 'none' ? 'block' : 'none';
			
			if(display == 'block') {
				for(var i = 0; i <= RST.steps; i++) {
					//$('#rent-step'+ i +' div.step-content').css('display', 'none');
					$('#rent-step'+ i +' div.step-content').hide();
					$('#rent-step'+ i +' h3').removeClass('step-header');
				}
				
				$('#rent-step'+ id +' h3').addClass('step-header');	
			} 
			else { 
				$('#rent-step'+ id +' h3').removeClass('step-header');
			}
			
			$(div).css('display',display);
		}
	},
	
	
	
	
	
	
	
	/*
	Store the dates into the system - 
	Ready to post
	if id == 1, update of the second calendar in order to make no possible to select a day before the first date
	if this is already a date selected for the second part, update it as the day after on morning (or 2 days if that day is sunday)
	*/
	// jQuery ready
	date: {
		save: function(id) {
			var da = id == 1 ? 'from' : 'to';
			var moment = RST.date.getTimeAsText(id);
			
			if(RST['date'+ id] == null || RST['hour'+ id] == null) {
				$('#rent-step'+ id +' p.error-box').css('display', 'block');
				return false;
			}
			
			var date = RST['date'+ id].split('-');
			var D = new Date(date[0], (date[1] - 1), date[2]);
			var print_date = _days[D.getDay()] +' '+ D.getDate() +' '+ _months[D.getMonth()] +' '+ D.getFullYear() +' '+ moment;
		
			$('#rent-step'+ id +' h3 span.fright').text(print_date);
			
			// bind the form
			$('#hi-cal-time'+ id).val(RST['hour'+ id]);

			
			if(id == 1) {
				RST.date.updateCal2();
			}
			else if(id == 2) {
				RST.date2 = $('#hi-cal-to-date').val();
				var d1 = RST.date1.split('-');
				var d2 = RST.date2.split('-');
				
				var date1_d = new Date(parseX(d1[0]), parseX(d1[1]) -1, parseX(d1[2]));
				RST.dateDiff = date1_d.difference(parseX(d2[0]), parseX(d2[1])-1, parseX(d2[2]));
				var date2_d = new Date(parseX(d2[0]), parseX(d2[1]) -1, parseX(d2[2]));
			}
			
			RST._options.add();
			
			if(RST.step < (id + 1)) {
				RST.step = id + 1;
			}
				
			RST.toggle(id + 1);
		},
	
		
		// Enable or disable availables moments when I select a day 
		// jQuery ready
		check: function(calID) {
			var id = (calID == 'cal-from') ? 1 : 2;
			RST['date'+ id] = $('#hi-'+ calID +'-date').val();
			
			var date = RST['date'+ id].split('-');
			date[2] = date[2].slice(0,1) == '0' ? parseInt(date[2].slice(-1)) : parseInt(date[2]);
			var d = new Date(parseInt(date[0]), RST.date.formatMonth(date[1]), date[2]);
			RST['day'+ id] = d.getDay();
			
			// if we are on saturday
			if(RST['day'+ id] == 6) {	
				$('#time'+ id +'-1').attr('disabled', false);
				$('#time'+ id +'-2').attr('disabled', true);
				$('#time'+ id +'-1').attr('checked', true);
				
			} 
			else {
				$('#time'+ id +'-1').attr('disabled', false);
				$('#time'+ id +'-2').attr('disabled', false);
			}
			
			// if we select the same date of first cal, disable unavailable moments and select the first after
			if(id == 2) {
				if(RST.date1 == RST.date2) {
					for(var j = 1; j <= parseInt(RST.hour1); j++) {
						$('#time2-'+ j).attr('disabled', true);
					}
					
					if(RST.hour1 > RST.hour2) { 
						$('#time2-'+ (parseInt(RST.hour1) + 1)).attr('checked', true);
					}
				}
			}
		
		},
		
		
		
		
		// jQuery ready
		updateCal2: function() {
			// I update the calendar 'to' with a new Ajax request
			// if next moment is not the same day
			var date = RST.date1.split('-');
			var D = new Date(date[0], (date[1] - 1), date[2]);
			
			var month_id = date[1].length == 1 ? '0'+ date[1] : date[1];
			var month = date[0] +'-'+ month_id;
			
			/*
			 * Since Jan 1st 2010, the minimum duration of a rent is 24h => the returns will be at least the next day  
			 */
			D.setTime(D.getTime() + 24 * 3600 * 1000); 
			if(D.getDay() == 0) {
				D.setTime(D.getTime() + 24 * 3600 * 1000); 
			}
			var day = D.getDate() < 10 ? '0'+ D.getDate() : D.getDate();
			month_id = (D.getMonth() + 1) < 10 ? '0'+ (D.getMonth() + 1) : (D.getMonth() + 1);
			disable_before = D.getFullYear() +'-'+ month_id +'-'+ day;	
			month = D.getFullYear() +'-'+ month_id;
			
		
			
			if(RST.date2 != null) {
				var d1 = parseInt(RST.date1.split('-').join(''));
				var d2 = parseInt(RST.date2.split('-').join(''));
				
				if(d1 >= d2) { 
					var moment = RST.date.getTimeAsText(2);
					Calendar.highlight('cal-to', disable_before);
					print_date = _days[D.getDay()] +' '+ D.getDate() +' '+ _months[D.getMonth()] +' '+ D.getFullYear() +' '+ moment;
					$('#rent-step2 h3 span.fright').text(print_date);
					
					// bind the form
					$('#hi-cal-time2').val(RST.hour2);
					if(RST.step > 3) { 
						RST.getPrice();
					}
				}
			}
			
			var selected = RST.date2 == null ? '' : RST.date2;
			$.get('addons/calendar/calendar.php', 
				{
					'cal_id': 'cal-to', 
					'month': month,
					'disable_before': disable_before, 
					'selected': selected
				}, 
				function(r) {
					$('#cal-to').parent().html(r);
				}
			);			
		},
	
	
	
		// Get the text label of the selected radio button
		// Return false if no one checked
		// jQuery ready
		getTimeAsText: function(id) { 
			var radios = $('#rent_step_1 input[name=time'+ id +']');
			var time = 0;
			
			$(radios).each(function(index) { 
				if($(this).attr('checked')) {
					time = $(this).val();
				}
			});
			
			if(time > 0) { 
				var time_text = $(radios).eq(time - 1).next('label').html();
			}
			if(time == 0) { 
				return false;
			}
			else {
				RST['hour'+ id] = time;
				return time_text;
			}
		},
		
		// jQuery ready
		formatMonth: function(month) {
			return month < 10 ? parseInt(month.slice(-1)) - 1 : parseInt(month) - 1;
		}
	},
	
	
	
	
	_vehicle: {
		// jQuery ready
		save: function() {
			if(RST.vehicle == null) {
				$('#rent-step3 p.error-box').css('display', 'block');
				return false;	
			}
			
			if(RST.step < 4) { 
				RST.step = 4;
			}
				
			RST.toggle(4);
		},
		
		// jQuery ready
		update: function() {
			RST.vehicle = $('#hi-vehicle').val();
			RST._options.add();	
			
			$.get(
				'rent_tool/ajax.php', 
				{
					'action': 'price-night',
					'vehicle': RST.vehicle
				},
				function(r) {
					$('#by-night').html(r);
				}
			);
		},
		
		// jQuery ready
		sel: function(id) {
			if($('#vehicle-'+ $('#hi-vehicle').val()).length > 0) { 
				$('#vehicle-'+ $('#hi-vehicle').val()).removeClass('selected');
			}
			$('#vehicle-'+ id).addClass('selected');
			$('#hi-vehicle').val(id);
			
			RST._vehicle.update();
			$('#rent-step3 h3 span.fright').text($('#vehicle-'+ id +' img:first').attr('alt'));
		}
	},
	
	
	
	
	
	place: {
		// jQuery ready
		save: function() {
			if($('#place').val() != '') {
				$('#rent-step4 h3 span.fright').text($('#depot-name-hidden').val());
				$('#hi-place').val($('#place').val());
				if(RST.step < 5) {
					RST.step = 5;
					RST.setControls(true);
				}
				RST.toggle(5);
			} 
			else { 
				$('#rent-step4 p.error-box').css('display', 'block');
			}
		},
		
		
		
		
		sel: function(location_id) {
			$('#place-slt option[value='+ location_id +']').attr('selected','selected');
			RST.place.makeSelection(location_id);	
		},
		
		
	
		sel2: function() {
			$('#rent-step4 p.error-box').hide();
			$('#place').val($('#place-slt').val());
			var _value = $('#place-slt option:selected').val();
			$('#depot-name-hidden').val(_value);
		},		
		
		
		// jQuery ready
		makeSelection: function(location_id) {
			$('#rent-step4 p.error-box').hide();
			$.get(
				'rent_tool/ajax.php',
				{
					'action': 'get-address',
					'place': location_id 
				},
				function(r) {
					var data = r.split('|');
					var _html = '<h2>'+ data[0] +'</h2>'+ data[2] +'<p><a href="'+ myLang.ISO +'/'+ myLang.url_places +'/'+ data[1] /+'" onclick="window.open(this.href); return false" style="font-size:8pt">'+ myLang.details +'</a></p>';
					$('#place').val(location_id);
					$('#depot-info').html(_html);
					$('#depot-info').css('display', 'block');
					$('#depot-name-hidden').val(data[0]);
				}
			);
		},
		
		// jQuery ready
		callBack: function() {
			RST.place.makeSelection($('#place-slt').val());
		}
	},
	
	
	
	
	
	Omnium: {
		total: 0,
		caution: 0,
		franchise_rc: 0,
		franchise_omnium: 0,
		
		// jQuery ready
		save: function() {
			RST.Omnium.update();
			if(RST.step < 6) {
				RST.step = 6;
			}
			RST.toggle(6);
		},
		
		// jQuery ready
		update: function() {
			if(RST.step > 4) {
				if(RST.Omnium.total == 0) {
					var print_text = myLang.unavailable;
					$('#hi-omnium').val(-2);
				}
				else {
					var print_text = $('#omnium-cbx').attr('checked') == true ? myLang.yes +' ('+ RST.Omnium.total +' €)' : myLang.no;
					var _value = $('#omnium-cbx').attr('checked') == true ? RST.Omnium.price : -1;
					$('#hi-omnium').val(_value);
				}
				$('#rent-step5 h3 span.fright').text(print_text);
			}
		},

		
		// jQuery ready
		setPrice: function(enabled) {
			if(enabled) {
				$('#omnium-cbx').val(RST.Omnium.total);
				$('#omnium-price').html(RST.Omnium.total);
				$('#omnium-price2').html(RST.Omnium.total);
				$('#warranty-caution').html(RST.Omnium.caution);
				$('#franchise-omnium').html(RST.Omnium.franchise_omnium);
				$('#franchise-classic').html(RST.Omnium.franchise_rc);
			}
			else {
			}
		},
		
		// jQuery ready
		select: function() {
			var price_total = $('#omnium-cbx').attr('checked') == true ? parseInt(RST.price) + parseInt(RST.Omnium.total) : RST.price;	
			$('#hi-total').val(price_total);
			$('#total-output').html(price_total);
		}
	},

	
	_options: {
		// jQuery ready
		save: function() {
			RST._options.update();
			/*
			if(RST.step < 7) 
				RST.step = 7;
			*/
			RST.toggle(null);
		},
		
		// jQuery ready
		update: function() {
			if(RST.step > 5) {
				var print_text = $('#kms-included').html() +' '+ myLang.inc_km +' - '+ $('#nbr-km-supp').val() +' '+ myLang.add_km +' (€ '+ $('#total-price-km').html() +')';
				// $('#rent-step6 h3 span.fright').text(print_text);
				$('#hi-kms-xt').val(RST.addedKMs);
				$('#hi-kms-xt-price').val($('#total-price-km').html());
			}
		},
		
		// jQuery ready
		add: function() {
			if(RST.vehicle != null) {
				$.get(
					'rent_tool/ajax.php',
					{
						'action': 'price-km',
						'vehicle': RST.vehicle
					},
					function(priceByKM) {
						$('#by-kms').html(priceByKM);
						RST.addedKMs = $('#nbr-km-supp').val();
						var number = priceByKM * RST.addedKMs;		
						$('#total-price-km').text(number.toFixed(2));
						RST._options.update();
					}
				);
			}
		}
	},



	
	// jQuery ready
	getPrice: function() {
		var dat1 = RST.date1.split('-');
		var dat2 = RST.date2.split('-');
		var day_from = RST.day1;
		var day_to = RST.day2;
		var days = RST.dateDiff[2];
		var months = (RST.dateDiff[0] * 12) + RST.dateDiff[1];
		
		var params = { 
			'vid': RST.vehicle, 
			'day1': day_from,
			'day2': day_to,
			'time1': RST.hour1,
			'time2': RST.hour2,
			'months': months,
			'days': days
		};
		
		// for debugging only
		debug('query: '+ $.param(params));
		//
		
		$.getJSON(
			'rent_tool/go.php', 
			params, 
			function(r) {
				debug(r);

				var price = r.total;
				var kms = r.km;
				var omnium = r.omnium;
				var warranty = r.warranty;
				RST.price = price; // price without franchise
				
				RST.Omnium.total = r.omnium;
				RST.Omnium.caution = r.warranty.caution;
				RST.Omnium.franchise_rc = r.warranty.f_rc;
				RST.Omnium.franchise_omnium = r.warranty.f_omnium;
				RST.Omnium.setPrice(RST.Omnium.total != 0);
				var price_total = $('#omnium-cbx').attr('checked') == true ? parseInt(price) + parseInt(RST.Omnium.total) : price;

				$('#hi-stotal').val(price);
				$('#hi-total').val(price_total);
				$('#hi-kms-inc').val(kms);
				$('#total-output').html(price_total);
				$('#response-wrap').show();
				$('#kms-included').html(kms);
				return true;
			}
		);
	}
}


function debug(str) {
	if(debugEnabled) {
		if(console) {
			console.log(str);
		}
	}
}








var Customer = {
	authentify: function() {
		$.post(
			'rent_tool/ajax.php?action=get_user_info', 
			{
				e: $('#customer-email').val(),
				p: $('#customer-password').val()
			},
			function(r) {
				if(r.firstChild.nodeName != 'client') {
					Customer.displayMessage('login-error');
				}
				else {
					//Customer.hideMessages();
					Customer.hideLogin();
					Customer.populateForm(r);
					Customer.displayMessage('hello-user', {'ID': Customer.findXmlValue(r, 'firstname') +' '+ Customer.findXmlValue(r, 'name')});
					Customer.showForm();
				}
			}
		);
	},
	
	
	populateForm: function(responseXML) {
		$('#ip-lastname').val(Customer.findXmlValue(responseXML, 'name'));
		$('#ip-firstname').val(Customer.findXmlValue(responseXML, 'firstname'));
		$('#ip-company').val(Customer.findXmlValue(responseXML, 'company'));
		$('#ip-tva').val(Customer.findXmlValue(responseXML, 'tva'));
		$('#ip-address1').val(Customer.findXmlValue(responseXML, 'address'));
		$('#ip-zip').val(Customer.findXmlValue(responseXML, 'zip'));
		$('#ip-city').val(Customer.findXmlValue(responseXML, 'city'));
		$('#ip-email').val(Customer.findXmlValue(responseXML, 'email'));
		$('#ip-phone').val(Customer.findXmlValue(responseXML, 'phone'));
		$('#ip-mobile').val(Customer.findXmlValue(responseXML, 'mobile'));
		$('#ip-bank-iban').val(Customer.findXmlValue(responseXML, 'bank_iban'));
		$('#ip-bank-bic').val(Customer.findXmlValue(responseXML, 'bank_bic'));
		$('#customer-id').val(Customer.findXmlValue(responseXML, 'id'));
		
		if($('#ip-company').val() == '') {
			$('#ip-company').closest('li').hide();
			$('#ip-tva').closest('li').hide();
		}
		else {
			$('#is-a-company').attr('checked', true);
			$('#ip-company').closest('li').show();
			$('#ip-tva').closest('li').show();
		}
		$('#ip-howuknow').closest('li').hide();
	},


	showForm: function() {
		$('#rent-coordinates').show();
	}, 

	hideLogin: function() {
		$('#rent-login').remove();
	},

	displayMessage: function(id, vars) {
		Customer.hideMessages();

		if(vars != undefined) {
			var _html = $('#'+ id).html();
			for(i in vars) {
				console.debug(i);
				_html = _html.replace('{'+ i +'}', vars[i]);
			}
			$('#'+ id).html(_html);
		}
		$('#'+ id).show();
	},
	
	
	hideMessages: function() {
		$('#message-wrapper p').hide();
	},
	

	
	lostPassword: function() {
		Customer.toggleLoginLostPasswd(2);
	},
	
	
	toggleLoginLostPasswd: function(s) {
		var values = ['block', 'none'];
		$('#rent-login').css('display', s == 2 ? values[1] : values[0]);
		$('#lostpasswd').css('display', s == 2 ? values[0] : values[1]);
	},
	
	
	retrievePassword: function() {
		var e = $('#lostpaswd-email').val();
		$.post('rent_tool/ajax.php?action=retrieve_password', { 'e': e }, 
					function(r) {
						Customer.goLogin();
						if(r == 'TRUE') {
							// display message ok
							Customer.displayMessage('password-sent');
						}
						else {
							// display message !ok
							Customer.displayMessage('user-not-found');
						}
					}
		);
	}, 
	
	goLogin: function() {
		Customer.toggleLoginLostPasswd(1);
	},
	
	
	/* Private use only */
	
	findXmlValue: function(xml, node) {
		//console.debug(node);
		if(xml.getElementsByTagName(node)[0].firstChild)
			return xml.getElementsByTagName(node)[0].firstChild.nodeValue;
		else return '';
	},
	
	
	C: function(session_id) {
		$.post('rent_tool/ajax.php?action=c_coordinates', { 'r': session_id }, 
					function(r) {
						if(r == 'TRUE') {
							// load step 2 then load in the infos
							document.location.reload();
						}
					}
		);
	}
};






function gotoStep(c,n) {
	$.post('rent_tool/ajax.php?action=set_session_step', { 's': n }, 
				function(r) {
					if(r == 'TRUE') {
						$('#rent_step_'+ c).submit();
					}
				}
	);
}




function checkRentStep2() {
	Validator.validate([
		{ field: '#ip-lastname', type: 'filled' },
		{ field: '#ip-firstname', type: 'filled' },
		{ field: '#ip-address1', type: 'filled' },
		{ field: '#ip-zip', type: 'number' },
		{ field: '#ip-city', type: 'filled' },
		{ field: '#ip-mobile', type: 'filled' },
		{ field: '#ip-email', type: 'mail' }
	]);
	
	if(Validator.valid) { 
		gotoStep(2,3);
	}
	else {  
		var l = Validator.eFields.length;
		var f;
		for(var i = 0; i < l; i++) {
			f = Validator.eFields[i];
			$(f).closest('li').addClass('error-field');
		}
	}
}




/* Document.ready() 
*/
$(function(evt) {
	RST.init();
	$('#is-a-company').click(function(e) {
		var _display = $(this).attr('checked') == true ? 'block' : 'none';
		$('#ip-company').closest('li').css('display', _display);
		$('#ip-tva').closest('li').css('display', _display);
		if(_display == 'none') {
			$('#ip-company').val('');
			$('#ip-tva').val('');
		}
	});
	$('#submit-step1').click(function(e) { gotoStep(1,2); });
	$('#submit-step2').click(function(e) { checkRentStep2(); });
	$('#submit-step3').click(function(e) { gotoStep(3,4); });
});
