// ORDER FORM

function InRange(val,min,max)
{
	return ((val<=max)&&(val>=min));
}

	var errorsEn = {
		 'invalidForm':  "The form is invalid!"
		,'noName':       "Please insert your name!"
		,'noPhone':      "Please insert your phone number!"
		,'noEmail':      "Please insert your email address!"
		,'noValidEmail': "Please insert a valid email address!"
		,'noDelivDate':  "Please select the car's delivery date!"
		,'noDelivHour':  "Please select the car's delivery hour!"
		,'noDelivLoc':   "Please select the car's delivery location!"
		,'noDropOffLoc': "Please select the car's drop off location!"
		,'noRentDur':    "Please select the car's rental duration!"
	};
	var errorsRo = {
		 'invalidForm':   "Forumularul este invalid!"
		,'noName':        "Va rugam sa va introduceti numele!"
		,'noPhone':       "Va rugam sa introduceti un numar de telefon!"
		,'noEmail':       "Va rugam sa introduceti o adresa de email!"
		,'noValidEmail':  "Va rugam sa introduceti o adresa de email valida!"
		,'noDelivDate':   "Va rugam sa selectati data livrarii masinii!"
		,'noDelivHour':   "Va rugam sa selectati ora livrarii masinii!"
		,'noDelivLoc':    "Va rugam sa selectati locatia livrarii masinii!"
		,'noDropOffLoc':  "Va rugam sa selectati locatia de predare a masinii!"
		,'noRentDur':     "Va rugam sa selectati durata inchirierii masinii!"
	};




	var lang = window.__lang;
	var errLang = {};
	if (lang=='' || lang=='ro')
	{
		lang = 'ro';
		errLang = errorsRo;
	}
	else if (lang=='en')
	{
		lang = 'en';
		errLang = errorsEn;
	}



$(function()
{
	var linkSubmit = $("#link_submit");
	if (linkSubmit.length == 0) { throw new Error("Invalid form!"); }


	var form = $("#formComanda");
	if (form.length == 0) { throw new Error("Invalid form!"); }

	var validation = $("#validationWrapper");

	//[[ hide submit button if js active
	$('#nojs_submit').css('display','none');
	linkSubmit.css('visibility','visible');


	//(( FIELDS OF INTEREST
	var
		 task = $('#task')
		,masina = $('#masina')
		,nume = $('#nume')
		,telefon = $('#telefon')
		,email = $('#email')
		,data_livrarii =  $('#data_livrarii')//select
		,ora_livrarii = $('#ora_livrarii')
		,livrare_in = $('#livrare_in')
		,durata = $('#durata')
		,predare_in = $('#predare_in')
		,chkOptiuni = $('.optiuni input[type=checkbox]') // checkboxes
		// hidden fields
		,total = $('#totala')
		,formOrderTotal = $('#total') // update value so the validation page will retrieve the order's total
	;

	//[[ convenient function to show error messages
var _e = function( error )
	{
		validation . attr('class','validation') . html('<p>'+error+'</p>');
	},
	//[[ validate task
	_validateTask = function()
	{
		if ((task.val() == '')||(task.val() != 'validare')) { _e(errLang['invalidForm']); return false; }
		return true;
	},
	//[[ validate masina
	_validateMasina = function()
	{
		if (masina.val() == '') { _e(errLang['invalidForm']); return false; }
		return true;
	},
	//[[ validate nume
	_validateNume = function()
	{
		if ((nume.val() == '')) { _e(errLang['noName']); return false; }
		return true;
	},
	//[[ validate telefon
	_validateTelefon = function()
	{
		if (telefon.val() == '') { _e(errLang['noPhone']); return false; }
		return true;
	},
	//[[ validate email
	_validateEmail = function()
	{
		if ((email.val() == '')) { _e(errLang['noEmail']); return false; }
		else
		{
			var reg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;
			if (reg.test(email.val())) { return true; }
			else { _e(errLang['noValidEmail']); return false; }
		}
		return false;
	},
	//[[ validate data livrarii
	_validateDataLivrare = function()
	{
		if ((data_livrarii.val() == '')) { _e(errLang['noDelivDate']); return false; }
		return true;
	},
	//[[ validate ora livrarii
	_validateOraLivrare = function()
	{
		if ((ora_livrarii.val() == '')) { _e(errLang['noDelivHour']); return false; }
		return true;
	},
	//[[ validate locatia livrarii
	_validateLocatieLivrare = function()
	{
		if ((livrare_in.val() == '')) { _e(errLang['noDelivLoc']); return false; }
		return true;
	},
	//[[ validate durata inchirierii
	_validateDurata = function()
	{
		if ((durata.val() == '')) { _e(errLang['noRentDur']); return false; }
		return true;
	},
	//[[ validate locatia predarii
	_validateLocatiePredare = function()
	{
		if ((predare_in.val() == '')) { _e(errLang['noDropOffLoc']); return false; }
		return true;
	}
;




//[[ PRETURI PER DURATA INCHIRIERE
var  durata_1_3_zile = parseInt($('#h_1_3').val(),10)
    ,durata_4_7_zile = parseInt($('#h_4_7').val(),10)
	,durata_8_14_zile = parseInt($('#h_8_14').val(),10)
	,durata_zi_plus = parseInt($('#h_ad').val(),10)
	,garantie = 0 //parseInt($('#h_gar').val(),10)
	,taxa_aeroport = parseInt($('#h_taxa_aeroport').val(),10)
;

//[[ Convenient function to update the customer's order
var _updateComanda = function( valoare, operator )
{
	var _total = parseInt(total.html(),10); // existent order total
	if (operator == '-') {
		_total = parseInt(_total - valoare, 10);
	}
	else if (operator == '+') {
		_total = parseInt(_total+valoare, 10);
	}
	else { alert('function: _updateComanda: invalid operator!'); return; }

	_total = Math.floor(_total);
	total.html(_total);
	formOrderTotal.val(_total);
};

//[[ Convenient function to set the order's total
var internalUpdateOrderTotal = function( value )
{
	value = Math.floor(parseInt(value + taxa_aeroport,10));
	total.html(value);
	formOrderTotal.val(value);
	return;
	if (value > 0)
	{
		total.html(value);
		formOrderTotal.val(value);
	}
	else {
		var v = parseInt(total.html(),10);
		formOrderTotal.val(v);
	}
};

//[[ Convenient function to cancel current order
var _anuleazaComanda = function()
{
	total.html(0);
	formOrderTotal.val(0);
}

//[[ Convenient function to retrieve the current order's total
var _getTotalHtml = function()
{
	var t = total.html();
	t = Math.floor(parseInt(t,10));
	return t;
};

//[[ convenient function to add the Airport tax to order's total
var _updateWithAirportTax = function()
{
	internalUpdateOrderTotal(0);
};

//[[ ACTIVEAZA/DEZACTIVEAZA LIVRARE IN, PREDARE IN SI OPTIUNILE CAND NU ESTE SELECTATA PERIOADA DE INCHIRIERE
//var _manageExtra = function()
//{
//	if ((durata.val() != '') && (durata.val() > 0))
//	{
//		livrare_in.attr('disabled', false);
//		predare_in.attr('disabled', false);
//		$.each(chkOptiuni, function()
//		{
//			$(this).attr('disabled', false);
//		});
//	}
//	else
//	{
//		livrare_in.attr('disabled', true);
//		predare_in.attr('disabled', true);
//		$.each(chkOptiuni, function()
//		{
//			$(this).attr('disabled', true);
//		});
//	}
//};

//_manageExtra();


//[[ convenient function to highlight the price range when an order is being made
var _highlightPrice = function( perioada )
{
	var  _13_days_row = $('#_13_days_row')
		,_47_days_row = $('#_47_days_row')
		,_814_days_row = $('#_814_days_row')
		,zileAditionale_row = $('#zileAditionale_row')
	;
	switch(perioada)
	{
		case '1_3' :
		{
			_13_days_row.css('background','#ffc');
			_47_days_row.css('background','');
			_814_days_row.css('background','');
			zileAditionale_row.css('background','');
			break;
		}
		case '4_7' :
		{
			_47_days_row.css('background','#ffc');
			_13_days_row.css('background','');
			_814_days_row.css('background','');
			zileAditionale_row.css('background','');
			break;
		}
		case '8_14' :
		{
			_814_days_row.css('background','#ffc');
			_47_days_row.css('background','');
			_13_days_row.css('background','');
			zileAditionale_row.css('background','');
			break;
		}
		case 'more' :
		{
			zileAditionale_row.css('background','#ffc');
			_814_days_row.css('background','');
			_47_days_row.css('background','');
			_13_days_row.css('background','');
			break;
		}
	}
};





//[[ UPDATE TOTAL :: DURATA
var _totalSubstract = 0; // pretul per/ perioada; substrage din total
durata.bind('change',function()
{
	var  _total = _getTotalHtml() // existent order total
		,days = parseInt($(this).val(),10) // selected value
	;

//	_manageExtra();

	if ((days != '') && (days > 0))
	{

		// GET INTERVAL
		if (InRange(days,1,3))
		{
			// substract previous period if there's any
			if (_totalSubstract>0)
			{
				_updateComanda(_totalSubstract,'-');
			}
			_resetSelectedOptions();
			// 1- 3 days interval | price per day: durata_1_3_zile + garantie
			_highlightPrice('1_3');
			var price = (days * durata_1_3_zile) + garantie;
			_totalSubstract = price;
			internalUpdateOrderTotal(price);
		}
		else if (InRange(days,4,7))
		{
			// substract previous period if there's any
			if (_totalSubstract>0)
			{
				_updateComanda(_totalSubstract,'-');
			}
			_resetSelectedOptions();
			// 4- 7 days interval | price per day: durata_4_7_zile + garantie
			_highlightPrice('4_7');
			var price = (days * durata_4_7_zile) + garantie;
			_totalSubstract = price;
			internalUpdateOrderTotal(price);
		}
		else if (InRange(days,8,14))
		{
			// substract previous period if there's any
			if (_totalSubstract>0)
			{
				_updateComanda(_totalSubstract,'-');
			}
			_resetSelectedOptions();
			// 8- 14 days interval | price per day: durata_8_14_zile + garantie
			_highlightPrice('8_14');
			var price = (days * durata_8_14_zile) + garantie;
			_totalSubstract = price;
			internalUpdateOrderTotal(price);
		}
		else
		{
			// substract previous period if there's any
			if (_totalSubstract>0)
			{
				_updateComanda(_totalSubstract,'-');
			}
			_resetSelectedOptions();
			// more than 14 days interval | price per day: durata_zi_plus + garantie
			_highlightPrice('more');
			var price = (days * durata_zi_plus) + garantie;
			_totalSubstract = price;
			internalUpdateOrderTotal(price);
		}

		// Audauga taxa de aeroport la total
		//_updateWithAirportTax();
	}
	else
	{
		_resetSelectedOptions();
		_anuleazaComanda();
	}
});

//[[ UPDATE comanda: Livrare In -- check/uncheck taxa aeroport !! todo
//var  __taxaAeroport_LivrareIn = 0
//	,__livrareInAeroportSelectat = false
//;
//livrare_in.bind('change',function()
//{
//	var  _total = parseInt(total.html(),10) // existent order total
//		,where = $(this).val() // selected value
//		,whereReg = /baneasa|otopeni/gi
//	;
//
//	if (whereReg.test(where))
//	{
//		//[[ adauga taxa de aeroport doar daca nu a fost adaugata deja
//		if (__taxaAeroport_LivrareIn >0){ return;}
//		else {
//			__taxaAeroport_LivrareIn = taxa_aeroport;
//			_updateComanda(__taxaAeroport_LivrareIn,'+');
//			__livrareInAeroportSelectat = true;
////			_updateWithAirportTax();
//		}
//	}
//	else
//	{
//		//[[ scade taxa de aeroport doar daca a fost adaugata deja
//		if (__taxaAeroport_LivrareIn >0)
//		{
//			_updateComanda(__taxaAeroport_LivrareIn,'-');
//			__taxaAeroport_LivrareIn = 0;
//		}
//		__livrareInAeroportSelectat = false;
////		_updateWithAirportTax();
//	}
//});
//
////[[ UPDATE comanda: Predare In -- check/uncheck taxa aeroport !! todo
//var  __taxaAeroport_PredareIn = 0
//	,__predareInAeroportSelectat = false;
//predare_in.bind('change',function()
//{
//	var  _total = parseInt(total.html(),10) // existent order total
//		,where = $(this).val() // selected value
//		,whereReg = /airport|aeroport/i
//	;
//
//	if (whereReg.test(where))
//	{
//		//[[ adauga taxa de aeroport doar daca nu a fost adaugata deja
//		if (__taxaAeroport_PredareIn >0){ return;}
//		else {
//			__taxaAeroport_PredareIn = taxa_aeroport;
//			_updateComanda(__taxaAeroport_PredareIn,'+');
//			__predareInAeroportSelectat = true;
////			_updateWithAirportTax();
//		}
//	}
//	else
//	{
//		//[[ scade taxa de aeroport doar daca a fost adaugata deja
//		if (__taxaAeroport_PredareIn >0)
//		{
//			_updateComanda(__taxaAeroport_PredareIn,'-');
//			__taxaAeroport_PredareIn = 0;
//		}
//		__predareInAeroportSelectat = false;
////		_updateWithAirportTax();
//	}
//});

//[[ UPDATE TOTAL :: OPTIUNI
var  _optVal = 0 // valoarea optiuni selectate
	,valoareGps = 0
	,valoareSofer = 0
	,_perioada_selectata = 0 // valoare perioada
;
$.each(chkOptiuni, function()
{
	var regGps = /g.p.s.$/i // test for gps match
		,regSoferi = /sofer|driver/i
	;

	$(this).click(function()
	{
		_perioada_selectata = durata.val();
		var  thisVal = parseInt($(this).attr('title'),10) // valoare optiune
			,chkTitle = $(this).val().toLowerCase() // so we can search for gps && soferi
			,val = _getTotalHtml() // existent order total
		;

		if ($(this).is(':checked'))
		{
			//check
			$(this).checked = true;

			// whether or not gps selected :: if not, add value
			if (regGps.test(chkTitle))
			{
				if (_perioada_selectata > 0) {
					valoareGps = _perioada_selectata * thisVal;
				}
				else { valoareGps = thisVal; }
	
				_updateComanda(valoareGps,'+');
			}
	
			// whether or not a driver option has been checked -- if not, add :: update total
			else if (regSoferi.test(chkTitle))
			{
				if (_perioada_selectata > 0) {
					valoareSofer = (parseInt(_perioada_selectata/7)) * thisVal;
				}
				else { valoareSofer = thisVal; }
	
				_updateComanda(valoareSofer,'+');
			}
	
			// default :: other options
			else
			{
				_updateComanda(thisVal,'+');
			}
			
		}
		else
		{
			//uncheck
			$(this).checked = false;

			// check if gps selected :: if so, substract value
			if (regGps.test(chkTitle))
			{
				if (valoareGps == 0) { valoareGps = thisVal; }
	
				_updateComanda(valoareGps,'-');
				valoareGps = 0;
			}
	
			// whether or not a driver option has been checked -- if not, add :: update total
			else if (regSoferi.test(chkTitle))
			{
				if (valoareSofer == 0) { valoareSofer = thisVal; }
	
				_updateComanda(valoareSofer,'-');
				valoareSofer = 0;
			}
	
			// default :: other options
			else
			{
				_updateComanda(thisVal,'-');
			}
		}
	});
	/*[ end click ]*/	
});


//[[ Reset options
//[[ Aceasta functie este apelata atunci cand se schimba perioada de inchiriere
var _resetSelectedOptions = function()
{
	$.each(chkOptiuni,function()
	{
		if ($(this).attr('checked') == true) {
			$(this).attr('checked',false);
		}
	});

//	predare_in.val('');
//	livrare_in.val('');

	internalUpdateOrderTotal(taxa_aeroport);
};


	//[[ validate form
	var ValidateForm = function()
	{
		if ( ! _validateTask()) { return false; }
		if ( ! _validateMasina()) { return false; }
		if ( ! _validateNume()) { return false; }
		if ( ! _validateTelefon()) { return false; }
		if ( ! _validateEmail()) { return false; }
		if ( ! _validateDataLivrare()) { return false; }
		if ( ! _validateOraLivrare()) { return false; }
		if ( ! _validateLocatieLivrare()) { return false; }
		if ( ! _validateDurata()) { return false; }
		if ( ! _validateLocatiePredare()) { return false; }

		else return true;
	};

	//[[ submit form
	linkSubmit.click(function()
	{
		form.submit();
		return false;
	});

	//[[ register the event listener
	form.bind('submit', function(){ return ValidateForm(); });
});
