function showCustomerNotification(msg, notifications) {
	var text = msg;
	text += "\n\n";
	for (k in notifications) {
		text += " - " + notifications[k] + "\n";
	}
	alert(text);
}

/**
 * Recarga la página con la información del producto hermano
 * seleccionado en el combo. Si no hay ningún producto seleccionado
 * entonces no se realiza ninguna acción.
 */
function showSelectedBrother(servletUrl) {
    var select = document.getElementById('brothersCombo');
    var brotherId = select.options[select.selectedIndex].value;
    if (brotherId != '') {
        document.location.href = servletUrl + '?productId=' + brotherId;
    }
}

/**
 * Valida los datos del formulario y, si son correctos, lo envía.
 */
function pay(msgWhenNotAccepted) {
    var ok = true;

    // Validamos que se han aceptado las condiciones.
    var acceptConditions = document.getElementById('acceptConditions');
    if (acceptConditions != null && !acceptConditions.checked) {
        alert(msgWhenNotAccepted);
        ok = false;
    }

    // Sólo continuamos si no ha habido errores.
    if (ok) {
        document.payForm.submit();
    }
}

/**
 * Cambia el input de selección de provincia, para que sea un combo o un
 * campo de texto, en función del pais seleccionado actualmente.
 */
function updateProvinceInput(currentCountry) {
    // Obtenemos el combo de selección de paises.
    var combo = document.getElementById('addressCountry');

    // Obtenemos el elemento seleccionado.
    var country = combo.options[combo.selectedIndex].value;

    if (country == currentCountry) {
        // La provincia se seleccionará mediante un combo.
        document.getElementById('addressProvinceField').disabled = true;
        document.getElementById('addressProvinceFieldDiv').style.display = 'none';

        document.getElementById('addressProvinceComboDiv').style.display = 'inline';
        document.getElementById('addressProvinceCombo').disabled = false;
    } else {
        // La provincia se introduce manualmente.
        document.getElementById('addressProvinceCombo').disabled = true;
        document.getElementById('addressProvinceComboDiv').style.display = 'none';

        document.getElementById('addressProvinceFieldDiv').style.display = 'inline';
        document.getElementById('addressProvinceField').disabled = false;
    }
}

function changePassword() {
	var password = document.getElementById('inner_password').value;
	document.getElementById('password').value = hex_md5(password);
	document.loginForm.submit();
}

/**
 * Valida si hay elementos en la cesta de la compra, y si los hay pide
 * confirmación para salir.
 */
function logout(cartSize, url, msgWhenCartIsNotEmpty) {
    var ok = true;
    if (cartSize > 0) {
        ok = confirm(msgWhenCartIsNotEmpty);
    }

    if (ok) {
        window.location.href = url;
        return true;
    } else {
        return false;
    }
}

/**
 * Valida el formulario de cambio de contraseña, y si los datos son
 * correctos envía el formulario.
 */
function validatePasswordUpdateForm(noOldPasswordMsg, noNewPasswordMsg, passwordCopyDifferentMsg) {
    // Obtenemos los campos.
    var oldPassword = document.getElementById('inner_oldPassword').value;
    var newPassword = document.getElementById('inner_newPassword').value;
    var newPasswordCopy = document.getElementById('inner_newPasswordCopy').value;

    // Comprobamos que se ha introducido la contraseña antigua.
    if (oldPassword == '') {
        alert(noOldPasswordMsg);
        return false;
    }
    
    // Comprobamos que se ha introducido la contraseña nueva.
    if (newPassword == '') {
        alert(noNewPasswordMsg);
        return false;
    }

    // Compromamos que la contraseña es igual a la copia.
    if (newPassword != newPasswordCopy) {
    	alert(passwordCopyDifferentMsg);
        return false;
    }

    // Todo está bien. rellenamos los inputs ocultos.
    document.getElementById('oldPassword').value = hex_md5(oldPassword);

    // Lanzamos el formulario.
    document.passwordUpdateForm.submit();

    return true;
}

/**
 * Valida el formulario de ingreso de dinero, y si los datos son
 * correctos envía el formulario.
 */
function validateIncomeForm(noConceptMsg, noAmountMsg) {
    // Obtenemos los campos.
    var concept = document.getElementById('concept').value;
    var amount = document.getElementById('amount').value;

    if (concept == '') {
    	alert(noConceptMsg);
    	return false;
    }
    if (amount == '') {
    	alert(noAmountMsg);
    	return false;
    }

    // Lanzamos el formulario.
    document.incomeForm.submit();

    return true;
}

/**
 * Envía el formulario en la modalidad indicada.
 */
function sendCart(option, notDivisibleMsg) {
    var ok = true;

    // Validamos las unidades, según la acción seleccionada.
    if (ok && (option == 'updateUnits' || option == 'save')) {
    	ok = validateUnits(notDivisibleMsg);
    }

    // Sólo continuamos si no ha habido errores.
    if (ok) {
        document.getElementById('option').value = option;
        document.cartForm.submit();
    }
}

/**
 * Función que se encarga de enviar el fomulario cuand se pulsa ENTER en
 * alguno de los campos de unidades de los productos.
 */
function submitEnter(myfield, e, notDivisibleMsg) {
    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    } else if (e) {
        keycode = e.which;
    } else {
        return true;
    }

    if (keycode == 13) {
        sendCart('updateUnits', notDivisibleMsg);
        return false;
    } else {
        return true;
    }
}

/**
 * Valida que las unidades no contienen decimales cuando el producto no
 * es divisible.
 */
function validateUnits(notDivisibleMsg) {
	var inputs = document.getElementsByTagName('input');
	for (k in inputs) {
		var input = inputs[k];
		if (input.name != undefined && input.name.indexOf('units_false') == 0) {
			var units = input.value + '';
			if (units.indexOf('.') > -1 || units.indexOf(',') > -1) {
				alert(notDivisibleMsg);
	            return false;
			}
		}
	}
	return true;
}

/**
 * Cambia el estado de visibilidad de la información del transportista
 * externho en función de la selección del usuario.
 */
function setExternalTransportInfoVisibility() {
    var externalInput = document.getElementById('externalTA');
    var externalInfo = document.getElementById('externalTransportInfo');
    var transportWarning = document.getElementById('transportWarning');
    var carryRow = document.getElementById('carryRow');
    if (externalInput.checked) {
        externalInfo.style.display = '';
        if (transportWarning != null) transportWarning.style.display = 'none';
        if (carryRow != null) carryRow.style.display = 'none';
    } else {
    	externalInfo.style.display = 'none';
        if (transportWarning != null) transportWarning.style.display = '';
        if (carryRow != null) carryRow.style.display = '';
    }
}

/**
 * Actualiza la selección del tipo de cliente en el combo a un tipo
 * dado. Además, indica si se debe forzar este cambio de modo que ya no
 * se pueda modificar por el usuario.
 */
function updateCustomerType(type, force, nifText) {
    if (type == 'pro') {
    	document.getElementById('customerTypeSelector').options[1].selected = true;
    } else {
    	document.getElementById('customerTypeSelector').options[0].selected = true;
    }

    document.getElementById('customerTypeSelector').disabled = force;
    customerTypeChanged(nifText);
}

/**
 * Cambia los datos del formulario en función de tipo de usuario
 * seleccionado.
 */
function customerTypeChanged(nifText) {
    // Obtenemos el tipo de cliente seleccionado.
    var selector = document.getElementById('customerTypeSelector');
    var option = selector.options[selector.selectedIndex].value;
    if (option == 'pro') {
        // Es un usuario profesional.
        document.getElementById('proObservations').style.display = '';
        document.getElementById('companyGeneralInfo1').style.display = '';
        document.getElementById('companyGeneralInfo2').style.display = '';
        document.getElementById('companyGeneralInfo3').style.display = '';
        document.getElementById('nif').style.fontWeight = 'bolder';
        document.getElementById('nif').innerHTML = '*' + nifText;
    } else {
        // Por defecto se trata de un usuario normal.
        document.getElementById('proObservations').style.display = 'none';
    	document.getElementById('companyGeneralInfo1').style.display = 'none';
    	document.getElementById('companyGeneralInfo2').style.display = 'none';
    	document.getElementById('companyGeneralInfo3').style.display = 'none';
    	document.getElementById('nif').style.fontWeight = 'normal';
    	document.getElementById('nif').innerHTML = nifText;
    }

    // Actualizamos también el estado del recargo de equivalencia.
    updateSurchageTaxInfo();
}

/**
 * Actualiza la visibilidad del campo de recargo de equivalencia según
 * los datos actuales.
 */
function updateSurchageTaxInfo() {
    // Obtenemos el tipo de cliente seleccionado.
	var selector = document.getElementById('customerTypeSelector');
    var customerType = selector.options[selector.selectedIndex].value;

    // Obtenemos el estado de selección de la exención de impuestos.
    var taxExempt = document.getElementById('taxExempt').checked;

    // El campo de recargo de equivalencia se muestra tan sólo cuando el
    // usuario es profesional y no está exento de impuestos.
    if (customerType == 'pro' && !taxExempt) {
    	document.getElementById('surchageTaxInfo1').style.display = '';
    	document.getElementById('surchageTaxInfo2').style.display = '';
    } else {
    	document.getElementById('surchageTaxInfo1').style.display = 'none';
    	document.getElementById('surchageTaxInfo2').style.display = 'none';
    }
}