/*
*   Copyright (c) 2009 Ade Olonoh - http://www.adeolonoh.com
*
*   This code is freely distributable for all uses under the BSD license:
*   http://www.mileagecalc.com/bsd.txt
*/

window.onload = init;

function init() {
    
    // Make sure the start/end fields are on the page
    if ($('end') && $('start')) {
    
        // Set the default end date to today
        var end = new Date();
        $('end').value = (end.getMonth() + 1) + '/' + end.getDate() + '/' + end.getFullYear().toString().substr(2);
        
        // Set the default start date to the beginning of the month
        var start = new Date(end.getFullYear(), end.getMonth(), 1);
        $('start').value = (start.getMonth() + 1) + '/' + start.getDate() + '/' + start.getFullYear().toString().substr(2);
    }
}

function getEvents() {

    // Make sure a starting address was supplied
    if ($F('addr') == '') {
        alert('Please enter your default starting address');
        return;
    }
    
    // If a calendar URL wasn't supplied, skip the Ajax call to fetch events
    if ($F('url') == '') {
        noEvents();
        return;
    }
    
    // Show the progress indicator and disable the submit button
    Element.show('indicator1');
    $('button1').disabled = true;
    
    // Make an Ajax request to get calendar events
    new Ajax.Request(
        'mileage.php',
        {
            parameters: 'a=getEvents&' + Form.serialize('form1') + noCacheParam(),
            onSuccess: getEventsSuccess,
            onFailure: ajaxFailure
        }
    );
}

function getEventsSuccess(request) {
    
    // Hide the progress indicator and show the submit button
    Element.hide('indicator1');
    $('button1').disabled = false;
    
    // Parse the JSON response
    var res = jsonParse(request);
    if (!res) return;
    
    // Build the event table with the retreived events
    if (res.length) {
        buildEventTable(res);
    }
    else {
        noEvents();
    }
}

function noEvents() {
    
    // Build an event table with one empty row
    buildEventTable([{ title: '', start: '', end: '', where: '' }]);
}

function buildEventTable(events) {
    
    // Clear the event table
    clearEventTable();
    
    // Don't do anything if there weren't any events
    if (!events.length) return;

    // Iterate over each event
    var i = 1;
    events.each( function(event) {
        
        // Add an event to the table
        addEvent(event, i);
        i++;
    });
    
    // Update the count of events in the table
    $('numevents').value = i;
    
    // Show the event table
    Element.show('step2');
    Element.scrollTo('step2');
}

function addEvent(event, i) {
    
    // Create a new row in the event table
    var table = $('events');
    var row = table.insertRow(table.rows.length - 1);
    row.id = 'event' + i;
    
    // Create each cell in the row -- looks messy, but it's fast
    var cell = row.insertCell(0);
    cell.innerHTML = '<input type="text" size="10" name="title' + i +'" id="title' + i + '" value="' + event.title + '" style="width: 85px;" />';
    
    cell = row.insertCell(1);
    cell.innerHTML = '<input type="text" size="10" name="time' + i +'" id="time' + i + '" value="' + (event.start == '' && event.end == '' ? '' : event.start + ' to ' + event.end) + '" style="width: 100px;" />';
   
    cell = row.insertCell(2);
    cell.innerHTML = '<input type="text" size="20" name="from' + i +'" id="from' + i + '" value="' + $F('addr') + '" style="width: 135px;" />';
    
    cell = row.insertCell(3);
    cell.innerHTML = '<input type="text" size="20" name="to' + i +'" id="to' + i + '" value="' + event.where + '" style="width: 135px;" />';
    
    cell = row.insertCell(4);
    cell.innerHTML = '<input type="text" size="5" name="mileage' + i +'" id="mileage' + i + '" style="width: 30px;" />';
    
    cell = row.insertCell(5);
    cell.innerHTML = '<a href="#" onclick="showMap(' + i  + '); return false;"><img src="map.png" alt="Map" title="Map" /></a> <a href="#" onclick="deleteRow(' + i  + '); return false;"><img src="cross.png" alt="Delete" title="Delete" /></a>';
}

function clearEventTable() {
    
    // Get all rows in the event table
    var table = $('events');
    var rows = table.getElementsByTagName('tr');
    
    // Iterate over each row
    $A(rows).each( function(row) {
        
        // Make sure the row id matches that of an event
        if (row.id != '' && row.id.match(/^event\d/)) {
            
            // Remove the row
            row.parentNode.removeChild(row);
        }
    });
    
    // Update the event count and mileage total
    $('numevents').value = 0;
    $('total').value = 0;
}

function addRow() {
    
    // Add a row to the event table
    var i = parseInt($('numevents').value);
    addEvent({ title: '', start: '', end: '', where: '' }, i);
    $('numevents').value = i + 1;
}

function deleteRow(i) {
    
    // Delete a row from the event table
    var row = $('event' + i);
    row.parentNode.removeChild(row);
    
    // Do not decrement numevents -- is used to determine max id, not absolute count
}

function getMileage() {
    
    // Show the progress indicator and disable the submit button
    Element.show('indicator2');
    $('button2').disabled = true;
    
    // Set the form action
    $('action').value = 'getMileage';
    
    // Make an Ajax request to get travel mileage
    new Ajax.Request(
        'mileage.php',
        {
            parameters: Form.serialize('form2') + noCacheParam(),
            onSuccess: getMileageSuccess,
            onFailure: ajaxFailure
        }
    );
}

function getMileageSuccess(request) {
    
    // Hide the progress indicator and show the submit button
    Element.hide('indicator2');
    $('button2').disabled = false;
    
    // Parse the JSON response
    var res = jsonParse(request);
    if (!res) return;
    
    // Iterate over each event
    var total = 0;
    var error = 0;
    for (var i = 1; i < parseInt($F('numevents')); i++) {
        
        // Make sure the row exists
        var input = $('mileage' + i);
        if (input) {
            
            // Update the input field with the mileage value
            input.value = res[i];
            
            // Highlight the mileage field if the value was 0
            if (res[i] == 0) {
                input.style.backgroundColor = '#fcc';
                error++;
            }
            else {
                input.style.backgroundColor = '#fff';
            }
            
            // Increment the total
            total += parseFloat(res[i]);
        }
    }
    
    // If there was an error show the error message
    if (error) {
        Element.show('mileageError');
    }
    else {
        Element.hide('mileageError');
    }
    
    // Update the total field
    $('total').value = total;
}

function download() {
    
    // Update the form action and submit to initiate CSV download
    $('action').value = 'download';
    $('form2').submit();
}

function showMap(i) {
    window.open('http://maps.google.com/maps?saddr=' + escape($F('from' + i)) + '&daddr=' + escape($F('to' + i)));
}

function noCacheParam() {
    
    // Hack to make sure the requests aren't cached (IE6)
    var now = new Date();
    return '&r=' + now.getTime();
}

function ajaxFailure(request) {
    
    // Show the error message
    alert('An error was encountered: ' + request.responseText);
    
    // Hide all the indicators
    var indicators = document.getElementsByClassName('indicator');
    indicators.each( function(indicator) {
        Element.hide(indicator);
    });
    
    // Enable all the submit buttons
    var buttons = document.getElementsByClassName('button');
    buttons.each( function(button) {
        button.disabled = false;
    });
}

function jsonParse(request) {
    
    // Parse the JSON response
    var res = JSON.parse(request.responseText);
    if (!res) {
        
        // Display an error if it couldn't be parsed
        ajaxFailure(request);
        return false;
    }
    
    return res;
}
