/**
 * @see dynamic.js.php
 */
var REGEX = typeof _REGEX !== 'undefined' ? _REGEX : {};

function isValidRegex(input, regex) {
	input = input + "";
	return input.match(new RegExp(regex)) != null;
}

function isReservNumberValid(numberId) {
	return isValidRegex($('#' + numberId).val(), REGEX['valid_reservnum']);
}

function isTimeValid(timeId) {
	return isValidRegex($('#' + timeId).val(), REGEX['valid_time']);
}
function isFlightValid(flightId) {
	return isValidRegex($('#' + flightId).val(), REGEX['valid_flightnum']);
}
function isAgeValid(ageId) {
	return isValidRegex($('#' + ageId).val(), REGEX['valid_age']);
}

function isNameValid(nameId) {
	return isValidRegex($('#' + nameId).val(), REGEX['valid_name']);
}

function isEmailValid(emailId) {
	return isValidRegex($('#' + emailId).val(), REGEX['valid_email']);
}

function isPhoneValid(phoneId) {
	return isValidRegex($('#' + phoneId).val(), REGEX['valid_phone']);
}

function isAddressValid(addressId) {
	return isValidRegex($('#' + addressId).val(), REGEX['valid_address']);
}

function isCountryValid(countryId) {
	return isValidRegex($('#' + countryId).val(), REGEX['valid_country']);
}

function isCityValid(cityId) {
	return isValidRegex($('#' + cityId).val(), REGEX['valid_city']);
}

function isZipValid(zipId) {
	return isValidRegex($('#' + zipId).val(), REGEX['valid_zip']);
}

function isDateValid(dateId) {
    var day = isValidRegex($('#' + dateId + '_day').val(), REGEX['valid_day']),
        month = isValidRegex($('#' + dateId + '_month').val(), REGEX['valid_month']),
        year = isValidRegex($('#' + dateId + '_year').val(), REGEX['valid_year']);

	return day && month && year;
}

function isCreditCardNumberValid(numberId) {
	var number = $('#' + numberId).val();
	if(number.length == 0) {
		return false;
	}
	var length = number.length;
	var idx = length - 2;
	var sum = 0;
	var digit = 0;
	var result = 0;

	for (var i = length - 1;i >= 0; i--) {
		digit = parseInt(number.substring(i, i+1), 10);
		if (i == idx) {
			idx -= 2;
			result = digit * 2;
			if (result >= 10) {
				sum += (result - 9);
			} else {
				sum += result;
			}
		} else {
			sum += digit;
		}
	}
	return sum % 10 == 0;
}

function isCvv2Valid(id) {
	return isValidRegex($('#' + id).val(), REGEX['valid_cvv2']);
}

function isExpiryDateValid(dateId) {
	if (!isDateValid(dateId)) {
		return false;
	}
	var today = new Date(),
	    expiry = new Date($('#' + dateId + '_year').val(), $('#' + dateId + '_month').val() - 1);

    today = (new Date(today.getFullYear(), today.getMonth(), 1));

    return today.getTime() <= expiry.getTime();
}

function isArray(testObject) {
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function colorize (labelId, inputId, callbacks) {
	var color = validate(inputId, callbacks) ? "#00FF00" : "#FF0000";
	$('#' + labelId).css('background-color', color);
}

function equalValues(id, id2) {
	return $('#' + id).val() == $('#' + id2).val();
}

function isEmpty(id) {
	return $('#' + id).val() == '';
}

function isNonZero(id) {
	return $('#' + id).val() != '0';
}
function isChecked(id) {
	return $('#' + id + ':checked').length;
}


/* return true, if any callback returns true */
function validate(inputId, callback) {
	if (isArray(callback)) {
		for (var i=0; i<callback.length; i++) {
			if (callback[i](inputId)) return true;
		}
		return false;
	} else {
		return callback(inputId);
	}
}

function userMessage(message) {
	alert(message);
}

function validateFunction(labelId, callback) {
	if (!callback) {
		$('#' + labelId).css('color', 'red');
	} else {
		$('#' + labelId).css('color', 'black');
	}
}

function checkSearchboxForm() {
	var message = "";
	var ok = true;

	function report(errMessage) {
		message += errMessage + "\n";
		ok = false;
	}
	if (!$('#driver-age-ok').attr('checked')) {
		if(!validate('driver_age', isAgeValid)) report(_t('driver_age_not_valid'));
	}

    var search = $('#pick_up_search');
    if (search.val() == '' || search.val() == search.data('default')) {
        report(_t('insert_pickup_location_error'));
    } else {
        if ($('#data_loaded').val() == '1') {
            if ($('#pickup_country').val() == "0" || $('#pickup_city').val() == "0" || $('#pickup_location').val() == "0") {
                report(_t('pickup_info_not_valid'));
            }

            if (!$('#same_as_pickup').attr('checked')) {
                if ($('#dropoff_country').val() == "0" || $('#dropoff_city').val() == "0" || $('#dropoff_location').val() == "0") {
                    report(_t('dropoff_info_not_valid'));
                }
            } else {
                if ($('#dropoff_country').val() == "0") report(_t('dropoff_country_not_valid'));
                if ($('#dropoff_city').val() == "0") report(_t('dropoff_city_not_valid'));
                if ($('#dropoff_location').val() == "0") report(_t('dropoff_location_not_valid'));
            }
        } else {
            report(_t('location_not_selected_or_loading'));
        }
    }

    if ($('#pickup_calendar_alt').val() == '0') report(_t('date_not_valid_pickup'));
	if ($('#dropoff_calendar_alt').val() == '0') report(_t('date_not_valid_dropoff'));

    if ($('#pickup_time').val() == '-1') report(_t('time_not_valid_pickup'));
	if ($('#dropoff_time').val() == '-1') report(_t('time_not_valid_dropoff'));

	var inputs = ['pickup_country', 'pickup_city', 'pickup_location', 'dropoff_country', 'dropoff_city', 'dropoff_location'];
	for (var i=0; i<inputs.length; i++) $('#' + inputs[i]).keyup();
	if (!ok) {
		userMessage(message);
	}
	return ok;
}

function checkSelfServiceForm() {
	var message = "";
	var ok = true;

	function report(errMessage) {
		message += errMessage + "\n";
		ok = false;
	}
	
	if($('#self_reserv').val() == "0" || !validate('self_reserv', isReservNumberValid)) report(_t('reservnumber_not_valid'));
	if ($('#self_email').val() == "0" || !validate('self_email', isEmailValid)) report(_t('email_not_valid'));
	if (!ok) {
		//		userMessage(message);
	}
	return ok;
}

function checkStep3Form(type) {
	var message = "";
	var ok = true;

	function report(errMessage) {
		message += errMessage + "\n";
		ok = false;
	}

	if (!validate('firstname_input', isNameValid)) report(_t('firstname_not_valid'));
	if (!validate('lastname_input', isNameValid)) report(_t('lastname_not_valid'));
	if (!validate('phone_input', isPhoneValid)) report (_t('phone_not_valid'));
	if (!validate('email_input', isEmailValid)) report (_t('email_not_valid'));
	//if (!validate('birth', isDateValid)) report (_t('birth_date_not_valid'));
	if (type == 'book') {
		if (!document.getElementById('terms').checked) report(_t('agreement_needed_with_terms'));
		if (!validate('flight_number', isFlightValid)) report(_t('flight_number_not_valid'));
		if (!validate('address_input', isAddressValid)) report(_t('address_not_valid'));
		if (!validate('city_input', isCityValid)) report(_t('city_not_valid'));
		if (!validate('country_select', isCountryValid)) report(_t('country_not_valid'));
		if (!validate('zip_input', isZipValid)) report(_t('zip_not_valid'));
		if (!validate('cc_holder', isNameValid)) report(_t('cc_holder_not_valid'));
		if (!validate('cc_number_input', isCreditCardNumberValid)) report(_t('cc_number_not_valid'));
		if (!validate('cc_cvv2', isCvv2Valid)) report(_t('cc_cvv2_not_valid'));
		if (!validate('cc_expire', isExpiryDateValid)) report(_t('cc_expire_date_not_valid'));
	}
	
	refreshStep3Form(type);
	
	if (!ok) {
		//		userMessage(message);
	}
	return ok;
}

function refreshStep3Form(type) {
	$('#firstname_input').keyup();
	$('#lastname_input').keyup();
	$('#address_input').keyup();
	$('#city_input').keyup();
	$('#country_select').change();
	$('#zip_input').keyup();
	$('#phone_input').keyup();
	$('#email_input').keyup();
	$('#birth_day').change();
	$('#terms').change();
	if (type == 'book') {
		$('#cc_holder').keyup();
		$('#cc_number_input').keyup();
		$('#cc_cvv2').keyup();
		$('#cc_expire_month').change();
	}
}
