/**
 * Handles functionality for the public-facing LEED offset calculator.
 */

var ajax_url = '/flight-ajax.html?';

var storedCookie;
var storedFlights;
var flights = [];
var lastIndex = -1;

/**
 * Setup autocomplete fields and event handlers once the html has loaded
 */
$(document).ready(function() {
    storedCookie = jQuery.cookie('FlightCalculator');
    storedFlights = (storedCookie) ? window.JSON.parse(storedCookie) : [];

    var form_origin = $('#form_origin');
    var form_destination = $('#form_destination');

    var airport_match = /^([^\(]+) \(([A-Z]{3,4}) \- (.+)\)$/;

    form_origin.click(function(event) {
        $(this).select();
    });

    form_origin.autocomplete(ajax_url + jQuery.param({action: 'search'}), {
        autoFill: true,
        dataType: 'json',
        parse: function(data) {
            var parsed = [];
            jQuery.each(data, function(index, item) {
                var matches = item.match(airport_match);
                var city = matches[1];
                var iata = matches[2];
                var airport = matches[3];

                parsed.push({
                    data: [item, city, iata, airport],
                    value: item,
                    //result: city,
                    result: item
                });
            });
            return parsed;
        },
        highlight: function(value, term) {
            return value.replace(new RegExp('(?![^&;]+;)(?!<[^<>]*)(' + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, '\\$1') + ')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<span class="ac_highlight">$1</span>');
        },
        max: 20,
        minChars: 1,
        multiple: false,
        mustMatch: false,
        scroll: true,
        selectFirst: true
    });

    form_origin.result(function(event, data, formatted) {
        if (data && data[2]) {
            var hidden = $(this).parent().find(">:input").next();
            hidden.val(data[2]);
        } else {
            $(this).val('');
        }
    });

    form_destination.click(function(event) {
        $(this).select();
    });

    form_destination.autocomplete(ajax_url + jQuery.param({action: 'search'}), {
        autoFill: true,
        dataType: 'json',
        parse: function(data) {
            var parsed = [];
            jQuery.each(data, function(index, item) {
                var matches = item.match(airport_match);
                var city = matches[1];
                var iata = matches[2];
                var airport = matches[3];

                parsed.push({
                    data: [item, city, iata, airport],
                    value: item,
                    //result: city,
                    result: item
                });
            });
            return parsed;
        },
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class=\"ac_highlight\">$1</span>");
        },
        max: 20,
        minChars: 1,
        multiple: false,
        mustMatch: false,
        scroll: true,
        selectFirst: true
    });

    form_destination.result(function(event, data, formatted) {
        if (data && data[2]) {
            var hidden = $(this).parent().find(">:input").next();
            hidden.val(data[2]);
        } else {
            $(this).val('');
        }
    });

    // Add any saved flights (cookie) to the itinerary
    populateFlights();

    $('#button_add_flight').click(addFlight);
    $('.button_checkout').each(function(index, el) {
        $(el).click(foxyCheckout);
    });
    $('#button_clear_flights').click(clearFlights);
});

/**
 * Load stored flights into the table
 */
var populateFlights = function() {
    jQuery.each(storedFlights, function(index, flight) {
        addFlight(flight.origin, flight.destination, flight.tickets, flight.roundtrip);
    });
}

/**
 * Update the flight totals
 */
var updateTotal = function() {
    var distance = 0;
    var emissions = 0;
    var price = 0;
    jQuery.each(flights, function(index, flight) {
        if (flight) {
            distance += (parseFloat(flight.distance) * parseInt(flight.tickets));
            emissions += (parseFloat(flight.emissions) * parseInt(flight.tickets));
            price += (parseFloat(flight.price) * parseInt(flight.tickets));
        }
    });

    //if (price < 5 && price > 0) {
    //    price = '5.00 (Minimum $5 purchases)';
    //} else {
        price = (Math.round(price*100)/100) + '';
        price += (price.charAt(price.length-2) == '.') ? '0' : '';
    //}

    $('#total_miles').html(addCommas(distance));
    $('#total_lbs').html(addCommas(emissions));
    $('#total_price').html(addCommas(price));
}

/**
 * Delete a flight from the list of flights
 */
var deleteFlight = function(flight) {
    // Ensure the flight exists in the table
    if ($('#flight-' + flight).length > 0) {
        // Remove flight from table
        $('#flight-' + flight).remove();

        // Update index for delete link on subsequent flights
        for (i = flight+1; i < flights.length; i++) {
            $('#flight-' + i + ' a.calculator-delete').attr('href', 'javascript:deleteFlight(' + (i-1) + ')');
            $('#flight-' + i).attr('id', 'flight-' + (i-1));
        }

        // Update internal arrays of flights
        flights.splice(flight, 1);
        lastIndex--;
        saveFlights();
        updateTotal();
    }
}

/**
 * Lookup and attempt to add a flight
 */
var addFlight = function(origin_iata, destination_iata, tickets_value, roundtrip_value) {
    var table = $('#flights-table');

    // Get the current values from the input form if necessary
    if (roundtrip_value == null) {
        roundtrip_value = ($('#form_roundtrip').attr('checked')) ? 1 : 0;
    }
    if (tickets_value == null) {
        tickets_value = $('#form_tickets').val() || 1;
    }
    if (origin_iata == null || destination_iata == null) {
        origin_iata = $('#form_origin_iata').val();
        destination_iata = $('#form_destination_iata').val();

        // Run tests to ensure airport input was valid
        if (origin_iata == '' || destination_iata == '') {
            alert('Please enter a valid origin and destination airport.');
            return;
        } else if (origin_iata == destination_iata) {
            alert('The origin and destination airports cannot be the same!');
            return;
        }
        clearInputs();
    }

    // Add a new table row to the flights display
    var flightIndex = ++lastIndex;
    var row = document.createElement('tr');
    row.setAttribute('id', 'flight-' + flightIndex);
    table.find('tbody').append(row);

    // Lookup selected airports using AJAX
    var request = jQuery.ajax({
        //type: 'POST',
        //data: data,
        //success: success,
        type: 'GET',
        url: ajax_url + jQuery.param({action: 'flight', origin: origin_iata, destination: destination_iata, tickets: tickets_value, roundtrip: roundtrip_value}),
        dataType: 'json',
        complete: function(response) {
            var flight = jQuery.parseJSON(response.responseText);

            if (flight.found == 1) {
                // Create ticket column
                var ticketCell = document.createElement('td');
                ticketCell.appendChild(document.createTextNode(addCommas(flight.tickets) + ' x '));
                row.appendChild(ticketCell);

                // Create flight column
                var flightCell = document.createElement('td');
                var flightField = document.createElement('input');
                flightField.setAttribute('type', 'hidden');
                flightField.setAttribute('name', 'flights[]');
                flightField.setAttribute('value', flight.origin + '|' + flight.destination + '|' + flight.roundtrip);
                flightCell.appendChild(flightField);
                flightCell.appendChild(document.createTextNode(flight.description));
                row.appendChild(flightCell);

                // Create distance column
                var distanceCell = document.createElement('td');
                distanceCell.setAttribute('class', 'strong');
                distanceCell.appendChild(document.createTextNode(addCommas(flight.distance) + ' miles'));
                row.appendChild(distanceCell);

                // Create co2e column
                var co2eCell = document.createElement('td');
                co2eCell.setAttribute('class', 'strong');
                co2eCell.appendChild(document.createTextNode(addCommas(flight.emissions) + ' lbs CO2e'));
                row.appendChild(co2eCell);

                // Create price column
                var priceCell = document.createElement('td');
                priceCell.setAttribute('class', 'strong');
                priceCell.appendChild(document.createTextNode('$' + addCommas(flight.price)));
                row.appendChild(priceCell);

                // Create delete column
                var deleteCell = document.createElement('td');
                var deleteButton = document.createElement('a');
                deleteButton.setAttribute('href', 'javascript:deleteFlight(' + flightIndex + ')');
                deleteButton.setAttribute('title', 'Click to delete this flight');
                deleteButton.appendChild(document.createTextNode('Del'));
                deleteButton.setAttribute('class', 'calculator-delete');
                deleteCell.appendChild(deleteButton);
                row.appendChild(deleteCell);

                // Add the flight to the internal storage object and save
                flights[flightIndex] = {
                    origin: origin_iata,
                    destination: destination_iata,
                    tickets: flight.tickets,
                    roundtrip: flight.roundtrip,
                    description: flight.description,
                    distance: flight.distance,
                    emissions: flight.emissions,
                    price: flight.price
                };
                saveFlights();
                updateTotal();
            } else {
                lastIndex--;
                $('flight-' + flightIndex).remove();
                alert('The flight could not be added because one or more of the entered airports were not found.');
            }
        }
    });
}

/**
 * Store the current list of flights as a cookie
 */
var saveFlights = function() {
    storedFlights = [];
    jQuery.each(flights, function(index, flight) {
        if (flight) {
            storedFlights.push({
                origin: flight.origin,
                destination: flight.destination,
                tickets: flight.tickets,
                roundtrip: flight.roundtrip
            });
        }
    });

    // Set the cookie
    var cookieData = window.JSON.stringify(storedFlights);
    if (cookieData > 4096) {
        // Maximum cookie size reached
        alert('The maximum number of flight legs has been reached, please add your current itinerary to the cart and clear the list before adding additional flights.');
    } else {
        var expiresOn = new Date();
        expiresOn.setTime(expiresOn.getTime() + (365 * 24 * 60 * 60 * 1000));
        jQuery.cookie('FlightCalculator', cookieData, {expires: expiresOn});
    }
}

/**
 * Clear any entered flights
 */
var clearFlights = function() {
    // Clear table rows
    var table = $('#flights-table');
    table.find('tr').remove();

    // Clear internal data structures
    lastIndex = -1;
    flights = [];
    saveFlights();
    updateTotal();
}

/**
 * Clear button confirmation dialog
 */
var confirmClear = function() {
    return confirm('Are you sure you want to clear all flights in the itinerary?');
}

/**
 * Clear the origin and destination inputs
 */
var clearInputs = function() {
    $('#form_origin').val('');
    $('#form_origin_iata').val('');
    $('#form_destination').val('');
    $('#form_destination_iata').val('');
}

/**
 * Make sure there is something in a user's flight
 * list before they can checkout
 */
var foxyCheckout = function(event) {
    if (flights.length <= 0) {
        event = new Event(event).stop();
        alert('Please add at least one flight before purchasing.');
    }

    var flight_checkout_fields = $('#flight_checkout_fields');
    var flight_checkout_fields_gift = $('#flight_checkout_fields_gift');

    // Build Foxycart form fields for each flight offset product
    var numFlights = 0;
    var price = 0;
    var formFieldset = document.createElement('fieldset');
    jQuery.each(flights, function(index, flight) {
        if (flight) {
            var namePrefix = (index+1) + ':';

            var nameField = document.createElement('input');
            nameField.setAttribute('type', 'hidden');
            nameField.setAttribute('name', namePrefix + 'name');
            nameField.setAttribute('value', 'Custom Flight Offset');
            formFieldset.appendChild(nameField);

            var flight_pathField = document.createElement('input');
            flight_pathField.setAttribute('type', 'hidden');
            flight_pathField.setAttribute('name', namePrefix + 'flight_path');
            flight_pathField.setAttribute('value', flight.description.replace('<', '&lt;').replace('>', '&gt;'));
            formFieldset.appendChild(flight_pathField);

            var priceField = document.createElement('input');
            priceField.setAttribute('type', 'hidden');
            priceField.setAttribute('name', namePrefix + 'price');
            priceField.setAttribute('value', parseFloat(flight.price));
            formFieldset.appendChild(priceField);

            var quantityField = document.createElement('input');
            quantityField.setAttribute('type', 'hidden');
            quantityField.setAttribute('name', namePrefix + 'quantity');
            quantityField.setAttribute('value', parseFloat(flight.tickets));
            formFieldset.appendChild(quantityField);

            var co2eField = document.createElement('input');
            co2eField.setAttribute('type', 'hidden');
            co2eField.setAttribute('name', namePrefix + 'co2e');
            co2eField.setAttribute('value', parseFloat(flight.emissions));
            formFieldset.appendChild(co2eField);

            var milesField = document.createElement('input');
            milesField.setAttribute('type', 'hidden');
            milesField.setAttribute('name', namePrefix + 'miles');
            milesField.setAttribute('value', parseFloat(flight.distance));
            formFieldset.appendChild(milesField);

            price += parseFloat(flight.price);
            numFlights++;
        }
    });

    //if (price < 5) {
    //    event = new Event(event).stop();
    //    alert('The minimum offset purchase is $5.');
    //}

    // Add fields for standard purchase
    flight_checkout_fields.empty();
    flight_checkout_fields.append(formFieldset.cloneNode(true));
    for (var i = 1; i <= numFlights; i++) {
        var categoryField = document.createElement('input');
        categoryField.setAttribute('type', 'hidden');
        categoryField.setAttribute('name', i + ':category');
        categoryField.setAttribute('value', $('#flight_offset_category').val());
        flight_checkout_fields.append(categoryField);

        var codeField = document.createElement('input');
        codeField.setAttribute('type', 'hidden');
        codeField.setAttribute('name', i + ':code');
        codeField.setAttribute('value', $('#flight_offset_code').val());
        flight_checkout_fields.append(codeField);
    }

    // Add fields for gift purchase
    flight_checkout_fields_gift.empty();
    flight_checkout_fields_gift.append(formFieldset.cloneNode(true));
    for (var i = 1; i <= numFlights; i++) {
        var categoryField = document.createElement('input');
        categoryField.setAttribute('type', 'hidden');
        categoryField.setAttribute('name', i + ':category');
        categoryField.setAttribute('value', $('#flight_offset_gift_category').val());
        flight_checkout_fields_gift.append(categoryField);

        var codeField = document.createElement('input');
        codeField.setAttribute('type', 'hidden');
        codeField.setAttribute('name', i + ':code');
        codeField.setAttribute('value', $('#flight_offset_gift_code').val());
        flight_checkout_fields_gift.append(codeField);

        var recipientField = document.createElement('input');
        recipientField.setAttribute('type', 'hidden');
        recipientField.setAttribute('name', i + ':recipient');
        recipientField.setAttribute('value', $('#f37_recipient').val());
        flight_checkout_fields_gift.append(recipientField);
    }
}

/**
 * Add commas to a number
 */
var addCommas = function(num) {
    num += '';
    return num.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

