function validacion() {

valor = document.getElementById("nombre").value;

  if ( valor == null || valor.length == 0 || /^\s+$/.test(valor) ) {
    // Si no se cumple la condicion...
    alert('[ERROR] Debe indicar su Nombre');
    return false;
  }
  
valor2 = document.getElementById("apellidos").value; 
 
  else if ( valor2 == null || valor2.length == 0 || /^\s+$/.test(valor2) ) {
    // Si no se cumple la condicion...
    alert('[ERROR] Debe indicar sus Apellidos ');
    return false;
  }
 

 
  // Si el script ha llegado a este punto, todas las condiciones
  // se han cumplido, por lo que se devuelve el valor true
  return true;
}


function stepOne()
{
    showDiv('form');
    showDiv('footer');

    document.getElementById('flight').disabled = true;
    document.getElementById('insurance').disabled = true;
    document.getElementById('destinations').disabled = true;
    document.getElementById('startDates').disabled = true;
    document.getElementById('departure').disabled = true;

    document.getElementById('stepOneButton').style.display = 'none';
    document.getElementById('goBackButton').style.display = '';
}

// **************************************************************************************************************                

function getDates()
{
    //set price to 0 and hides the 2nd part of the form
    cleanForm();

    //unchecks and disables on every first load
    document.getElementById('insurance').checked = true;
    insuranceEnabled(false);

    grabFile('getData.asp?event=getDates', getDatesCallBack);
}

function getDatesCallBack(req)
{
    fillDropdown('startDates', req.responseText, function(items) { return items[1]; },
                function(items) { var dateArray = items[0].split('/'); return dateArray[2] + dateArray[1] + dateArray[0]; }, ';');
}

// **************************************************************************************************************

function getDestinations()
{

    //set price to 0 and hides the 2nd part of the form
    cleanForm();

    var startDates = document.getElementById('startDates').value;

    if ((startDates != "-1") && (startDates != "0"))
    {
        //a date is selected
        grabFile('getData.asp?event=getDestinations&startDate=' + startDates, getDestinationsCallBack);
    } else
    {
        destinationEnabled(false);
        flightEnabled(false);
        insuranceEnabled(false);
        departureEnabled(false);
    }
}

function getDestinationsCallBack(req) {
    var responseData = stripOmnitureError(req.responseText);    
    
    //check if there are still courses
    if (isEmpty(responseData))
    {
        //set price to 0 and hides the 2nd part of the form
        cleanForm();

        // no more availability for that choice. Disables the dropdowns.
        destinationEnabled(false);
        flightEnabled(false);
        insuranceEnabled(false);
        departureEnabled(false);

        //starts over dates to refreshes available dates.
        getDates();
    }
    else
    {
        fillDropdown('destinations', responseData, function(items) { return items[1]; },
                    function(items) { return items[0] + '|' + items[2]; });

        flightEnabled(false);
        departureEnabled(false);
        insuranceEnabled(false);
    }
}

// **************************************************************************************************************

function getFlight()
{
    //set price to 0 and hides the 2nd part of the form
    cleanForm();

    var destinations = document.getElementById('destinations').value;
    var startDates = document.getElementById('startDates').value;

    if (destinations == undefined)
        destinationsCode = "0";

    //nothing is selected
    if (destinations != "-1")
    {
        //set the values in hidden boxes
        var destinationCode = destinations.split("|")[0];
        document.getElementById('destinationCode').value = destinationCode;
        var accomCode = destinations.split("|")[1];
        document.getElementById('accomCode').value = accomCode;

        grabFile('getData.asp?event=getFlight&accomCode=' + accomCode + '&destinationCode=' + destinationCode + '&startDates=' + startDates, getFlightCallBack);
    }
    else
    {
        flightEnabled(false);
        departureEnabled(false);
        insuranceEnabled(false);
    }
}

function getFlightCallBack(req) {

    var responseData = stripOmnitureError(req.responseText);

    if (isEmpty(responseData))
    {        
        //set price to 0 and hides the 2nd part of the form
        cleanForm();

        //disables flight dropdown when no more availability for that destination
        flightEnabled(false);
        departureEnabled(false);
        insuranceEnabled(false);

        //starts over destinations
        getDestinations();
    }
    else
    {
        var dropdown = fillDropdown('flight', responseData,
                    function(items) { return items[1]; },
                    function(items)
                    {
                        var value = items[0] + '|' + //1 flight code
                                    items[2] + '|' + //2 availability_id
                                    items[3] + '|' + //3 course price
                                    items[4] + '|' + //4 residence price
                                    items[5] + '|' + //5 flight price
                                    items[6] + '|' + //6 transfer price
                                    items[7]; //7 insurance price
                        return value;
                    });
                    
        insuranceEnabled(false);

        if (g_AutoSelectEnabled && dropdown.options.length == 2)
            onFlightSelected(); // if there is no choice trigger the selected event
    }
}

function onFlightSelected()
{
    var flight = document.getElementById('flight').value;

    if (flight != '-1')
    {
        var flightParam = flight.split("|");

        if (flightParam[0] == '1')
        {
            cleanForm();
            getDeparturePoints(flightParam[1]);
        }
        else
        {
            $("div#departureOption").hide();
            setValues(flightParam);
        }
    }
    else
    {        
        cleanForm();
    }
}

// **************************************************************************************************************

function getDeparturePoints(availabilityId)
{
    var url = 'getData.asp?event=getDeparturePoints&availability_id=' + availabilityId.toString();    
    grabFile(url, getDeparturePointsCallBack);
}

function getDeparturePointsCallBack(req) {

    var responseData = stripOmnitureError(req.responseText);

    var dropdown = fillDropdown('departure', responseData,
        function(items) { return items[2]; }, 
        function(items) { return items[1] + '|' + items[3]; }, ';');                   

    if (dropdown.options.length > 0)
    {
        $("div#departureOption").show();
        if (g_AutoSelectEnabled && dropdown.options.length == 2)
            setValues();
    }
}

function getDDPPrice()
{    
    if (document.getElementById("flight").value.split('|')[0] == '1')
    {
        var departure = document.getElementById("departure").value;

        if (departure != '-1')
            return parseInt(departure.split('|')[1]);
    }

    return 0;
}

function getDDPCode()
{
    if (document.getElementById("flight").value.split('|')[0] == '1')
    {
        var departure = document.getElementById("departure").value;

        if (departure != '-1')
            return departure.split('|')[0];
    }

    return '';
}

// **************************************************************************************************************
//enables or disables destination dropdown
function destinationEnabled(val)
{
    if (!val) disableDropdown("destinations");
}

//enables or disables flight dropdown
function flightEnabled(val)
{
    if (!val) disableDropdown("flight");
}

function departureEnabled(val)
{
    if (!val) disableDropdown("departure");
}

// **************************************************************************************************************

//cleans the price and hides the 2nd part of the form
function cleanForm()
{  
    document.getElementById('totalPrice').innerHTML = 0;
    $("div#departureOption").hide();
    $('#priceTable').hide();
    $('#stepOneButton').hide();
}

// **************************************************************************************************************

//enables or disables insurance checkbox
function insuranceEnabled(val)
{
    if (val)
    {
        document.getElementById("insuranceDiv").style.color = "#000";
    }
    else
    {
        document.getElementById("insuranceDiv").style.color = "#ccc";
        cleanForm();
    }

    document.getElementById("insurance").disabled = !val;
}

// **************************************************************************************************************

//set the prices values in hidden boxes
function setValues()
{
    var flight = document.getElementById('flight').value;

    if (flight == "-1" || flight == undefined)
    {       
        //enables insurance checkbox
        insuranceEnabled(false);
    }
    else
    {   
        //enables insurance checkbox
        insuranceEnabled(true);

        var flightParam = flight.split("|");        

        document.getElementById('availability_id').value = flightParam[1]; //availability_id
        document.getElementById('startDate').value = document.getElementById('startDates').value; // save it to a hidden field
        document.getElementById('coursePrice').value = flightParam[2]; //course price

        document.getElementById('weekPrice').value = (parseInt(flightParam[2]) + parseInt(flightParam[3])) / 3; //week price
        document.getElementById('residencePrice').value = flightParam[3]; //residence price

        document.getElementById('flightPrice').value = flightParam[4]; //flight price
        var ddpCode = getDDPCode();
        document.getElementById('ddpPrice').value = getDDPPrice();
        document.getElementById('ddpCode').value = ddpCode;
        
        document.getElementById('flightChoice').value = flightParam[0]; //flight choice at the dropdown
        document.getElementById('transferPrice').value = flightParam[5]; //transfer price

        document.getElementById('insurancePrice').value = flightParam[6]; //insurance price
        document.getElementById('insuranceChoice').value = document.getElementById('insurance').checked; //insurance checkbox        
        
        // These fields are used by the agent's confirmation.asp page
        var ddl = document.getElementById('destinations');
        document.getElementById('txtDestination').value = ddl[ddl.selectedIndex].text;
        
        ddl = document.getElementById('startDates');
        document.getElementById('txtStartDates').value = ddl[ddl.selectedIndex].text;

        ddl = document.getElementById('departure');
        document.getElementById('txtDeparture').value = (isEmpty(ddpCode) ? '' : ddl[ddl.selectedIndex].text);        

        //calculates the total price
        checkPrice();
    }
}

// **************************************************************************************************************

//calculates the total price
function checkPrice()
{
    var withFlight = document.getElementById("flight").value.split('|')[0];
    if (withFlight == '1' && document.getElementById('departure').value == '-1')
    {        
        $('#priceTable').hide();
        $('#stepOneButton').hide();
    }
    else
    {   
        var insurance = document.getElementById('insurance').checked;
        var coursePrice = parseInt(document.getElementById('coursePrice').value);  //course price
        var residencePrice = parseInt(document.getElementById('residencePrice').value); //residence price
        var flightPrice = parseInt(document.getElementById('flightPrice').value); //flight price
        var ddpPrice = parseInt(document.getElementById('ddpPrice').value); //additional ddp flight cost
        var transferPrice = parseInt(document.getElementById('transferPrice').value); //transfer price

        var insurancePrice;
        if (insurance)
            insurancePrice = parseInt(document.getElementById('insurancePrice').value); //insurance price
        else
            insurancePrice = 0;

        document.getElementById('insuranceChoice').value = insurance; //insurance checkbox

        var totalPrice = coursePrice + residencePrice + flightPrice + transferPrice + ddpPrice;
        totalPrice = Math.round(totalPrice);

        // to show the price summary again, just enable this part
        setPrice('coursePrice', coursePrice, false);
        setPrice('residencePrice', residencePrice, false);
        setPrice('flightPrice', flightPrice, false);
        setPrice('transferPrice', transferPrice, false);
        setPrice('insurancePrice', insurancePrice, false);
        setPrice('ddpPrice', ddpPrice, false);

        if (insurance)
            totalPrice += insurancePrice;

        document.getElementById('totalPrice').innerHTML = '&euro;&nbsp;' + totalPrice.toString();
        
        $('#priceTable').show();
        $('#stepOneButton').show();        
    }
}

function setPrice(name, value, forceShow)
{
    if (value < 0 || value > 0 || forceShow) // NOTE (value < 0 || value > 0) != (value != 0) as value can be NULL
        $('#' + name + "Name").show();
    else
        $('#' + name + "Name").hide();
}

// **************************************************************************************************************

function fncClose()
{
    var form = document.getElementById("calculationForm")
    form.action = 'login.asp?ctr=es';
    form.submit();
}

// **************************************************************************************************************

function CheckForDuplicateBookings() {
    var email = document.getElementById('email').value;

    if (email != null && email.trim().length > 0) {
        grabFile('getData.asp?event=getDuplicateBookings&email=' + email.trim(), OnCheckedForDuplicateBookings);
    }
    else {
        alert("Please enter an email address first.");
    }
}

function OnCheckedForDuplicateBookings(req) {
    var json = stripOmnitureError(req.responseText);
    var duplicates = eval(json);

    if (duplicates.length > 0) {

        var duplicateStr = '';
        var count = 0;
        
        for (var i = 0; i < duplicates.length; ++i) {
            var html = AppendDuplicateBooking(duplicates[i]);

            if (!isEmpty(html)) {
                count++;
//                if (i > 0 && !isEmpty(duplicateStr) && !isEmpty(html)) {
//                    duplicateStr += '<br/>';
//                }

                duplicateStr += "<h3>Booking " + count + "</h3>";
                duplicateStr += html;
            }
        }

        $("div#overlay").html("<div class=\"bookingOverview\"><h2>Se encontraron " + count + " reservas con el mismo email</h2>" + duplicateStr + "</div>");
        $("#overlayTrigger").trigger("click");
    }
    else{
        alert("No previous bookings found.");
    }
}

function AppendDuplicateBooking(booking) {

    var html = "<table class=\"booking\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" +
                "<tr><td class=\"label\">WebBookingKey</td><td>" + booking.WebBookingKey + "</td></tr>" +
                "<tr><td class=\"label\">Booking date</td><td>" + booking.InsertDate + "</td></tr>" +
    	        "<tr><td class=\"label\">Nombre</td><td>" + booking.FirstName + "</td></tr>" +
                "<tr><td class=\"label\">Apellidos</td><td>" + booking.LastName + "</td></tr>" +
                "<tr><td class=\"label\">Fecha de nacimiento</td><td>" + booking.DateOfBirth + "</td></tr>" +
                "<tr><td class=\"label\">E-mail</td><td>" + booking.Email + "</td></tr>" +

		        "<tr><td class=\"label\">Fechas</td><td>" + booking.StartDate + "</td></tr>" +
                "<tr><td class=\"label\">Destino</td><td>" + booking.Destination + "</td></tr>" +
                "<tr><td class=\"label\">Con vuelo</td><td>" + (booking.Flight == 'true' ? 'Si' : 'No') + "</td></tr>" +
                "<tr><td class=\"label\">Salida desde</td><td>" + (isEmpty(booking.DeparturePoint) ? 'Madrid' : booking.DeparturePoint) + "</td></tr>" +
            "</table>";

    return html;
}
