// ************************************** //
// AJAX methods for the BHX flight boards //
// ************************************** //

// Enum type for direction
DirectionType = { Departures:0, Arrivals:1 }

// This function returns the selected timespan.
function TimeSpanGet() {
    if ($('#timespan .option input:checked').val() == "rdoEightHours") {
        return 8;
    }

    if ($('#timespan .option input:checked').val() == "rdoOneDay") {
        return 24;
    }
    
    return 48;
}

function FormatDateHeader(date) {
    var dayNames = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

    var today = new Date();
    var todayDay = today.getDay();
    var todayDate = today.getDate();
    var todayMonth = today.getMonth();
    var sup = '';

    if (todayDate == 1 || todayDate == 21 || todayDate == 31) {
        sup = 'st';
    } else if (todayDate == 2 || todayDate == 22) {
        sup = 'nd';
    } else if (todayDate == 3 || todayDate == 23) {
        sup = 'rd';
    } else {
        sup = 'th';
    }

    var todayString = dayNames[todayDay] + ' ' + todayDate + sup + ' ' + monthNames[todayMonth];

    if (todayString == date) {
        return '<strong>Today</strong> (' + date + ')';
    } else {
        return date;
    }
}

// This function formats a date and time in a format usuable by the AJAX updating script.
function FormatDateTime(date, time) {
    return '<span class="date">' + date + '</span>' + time;
}

// Function to handle flight board updates
function FlightBoardUpdate(directionType) {
    $('a#update').attr('style', 'background-image: url("/img/arrdep-lastupdated-loading.gif");');

    // Variables that contain param details.
    $timespan = "'timespan':'" + TimeSpanGet() + "'";
    $params = "{" + $timespan + "}";
    $flightNumber = $("#arrDepSearchForm input[type='text']");
    $airline = $("#arrDepSearchForm select[id$='AirlineList']");
    $location = $("#arrDepSearchForm select[id$='LocationList']");
    
    // Params added if filters need to be applied.
    if ($flightNumber.val() != '') {
        $params = "{" + $timespan + ",'filterBy':'FlightNumber', 'filterValue':'" + $flightNumber.val().replace("'", "\\'") + "'}";
    } else if ($airline.val() != '') {
        $params = "{" + $timespan + ",'filterBy':'Airline', 'filterValue':'" + $airline.val().replace("'", "\\'") + "'}";
    } else if ($location.val() != '') {
        $params = "{" + $timespan + ",'filterBy':'Location', 'filterValue':'" + $location.val().replace("'", "\\'") + "'}";
    }
    
    // AJAX methods according to direction
    if (directionType == DirectionType.Departures) {
        $url = "/services/AjaxWebServices.asmx/LatestDeparturesGet";
        $filteredUrl = "/services/AjaxWebServices.asmx/FilteredLatestDeparturesGet";
        $updateUrl = "/services/AjaxWebServices.asmx/DeparturesLastUpdate";
    } else {
        $url = "/services/AjaxWebServices.asmx/LatestArrivalsGet";
        $filteredUrl = "/services/AjaxWebServices.asmx/FilteredLatestArrivalsGet";
        $updateUrl = "/services/AjaxWebServices.asmx/ArrivalsLastUpdate";
    }
    
    // Clear any server-side error messages
    $('.serverMessage').remove();
    
    // Clear any client-side error messages
    $('.clientMessage').remove();
    
    if ($params == "{" + $timespan + "}") {
	    // No filters so return all flights.
	    $.ajax({
		    type: "POST",
		    contentType: "application/json; charset=utf-8",
		    url: $url,
		    data: $params,
		    dataType: "json",
		    success: function(results) {
			    AjaxSucceeded(results, directionType);
		    },
		    error: function(xhr, status, error) {
		        AjaxError();
		    }
	    });
	} else {
	    // Return flights for the filters applied.
	    $.ajax({
		    type: "POST",
		    contentType: "application/json; charset=utf-8",
		    url: $filteredUrl,
		    data: $params,
		    dataType: "json",
		    success: function(results) {
			    AjaxSucceeded(results, directionType);
		    },
		    error: function(xhr, status, error) {
		        AjaxError();
		    }
	    });
	}
	
	// Separate AJAX call to update the last updated time.
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: $updateUrl,
		data: "{}",
		dataType: "json",
		success: function(results) {
			LastUpdated(results);
	    },
	    error: function(xhr, status, error) {
	        AjaxLastUpdatedError();
	    }
	});
}

// Generic AJAX Error Handler
function AjaxError() {
    $error = '<div class="message warning clientMessage"><h3>Sorry, there was a problem&hellip;</h3><p>It wasn\'t possible to update the flight information. Please try again later, thank you.</p></div>';
    $('#arrDepSearch').after($error);
    $('.arrivalsDeparturesBoard').remove();
    $('a#update').removeAttr('style');
}

// Last updated AJAX Error Handler
function AjaxLastUpdatedError() {
    $('p.lastUpdated > em').text('Last updated: not available');
}

// Updates the last updated element with the result from 
// the AJAX call.
function LastUpdated(results) {
	$('p.lastUpdated > em').text(results.d);
}

// Function that applies the correct CSS classes to each
// row according to the order and comment.
function FlightBoardItemCssClassUpdate(row, comment) {
	if (comment.indexOf('Arrived') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light landed');
		} else {
			row.attr('class', 'dark landed');
		}
	} else if (comment.indexOf('Expected') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light expected');
		} else {
			row.attr('class', 'dark expected');
		}
	} else if (comment.indexOf('Departed') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light departed');
		} else {
			row.attr('class', 'dark departed');
		}
	} else if (comment.indexOf('Final Call') != -1 || comment.indexOf('Boarding') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light finalcall');
		} else {
			row.attr('class', 'dark finalcall');
		}
	} else if (comment.indexOf('Cancelled') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light cancelled');
		} else {
			row.attr('class', 'dark cancelled');
		}
	} else if (comment.indexOf('Delayed') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light delayed');
		} else {
			row.attr('class', 'dark delayed');
		}
	} else if (comment.indexOf('Check In') != -1 || comment.indexOf('Gate Closed') != -1) {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light checkin');
		} else {
			row.attr('class', 'dark checkin');
		}
	} else {
		if (row.attr('class').indexOf('light') != -1) {
			row.attr('class', 'light');
		} else {
			row.attr('class', 'dark');
		}
	}
}

// Main AJAX call processing function.
function AjaxSucceeded(results, directionType) {
    $table = $('table.arrivalsDeparturesBoard');
    $departuresHeader = '<tr class="head"><th class="location">Flying to</th><th class="airline">Airline</th><th class="flight">Flight no.</th><th class="scheduled">Scheduled</th><th class="details">Details</th></tr>';
    $arrivalsHeader = '<tr class="head"><th class="location">Arriving from</th><th class="airline">Airline</th><th class="flight">Flight no.</th><th class="scheduled">Scheduled</th><th class="details">Details</th></tr>';
    
    // Check flight information table exists
    if ($table.length <= 0) {
        // Create base table markup
        if (directionType == DirectionType.Departures) {
            $table = '<table class="arrivalsDeparturesBoard" summary="Live flight information at Birmingham Airport"><tr id="newblank" class="light"><td class="location"><div></div></td><td class="airline"><div></div></td><td class="flight"><div></div></td><td class="scheduled"><div></div></td><td class="details"><div></div></td></tr></table>';
        } else {
            $table = '<table class="arrivalsDeparturesBoard" summary="Live flight information at Birmingham Airport"><tr id="newblank" class="light"><td class="location"><div></div></td><td class="airline"><div></div></td><td class="flight"><div></div></td><td class="scheduled"><div></div></td><td class="details"><div></div></td></tr></table>';
        }
        
        $('#content > .formWrapper').after($table);
    }
    
    // Remove all rows
    $('table.arrivalsDeparturesBoard tr').remove();
    
	// Load JSON data into a variable.
	$data = results.d;
	
	// Add blank rows
	if ($data.length > 0) {
	    for (k=0;k<$data.length;k++) {
		    $cssClass = 'dark';

		    if (($data.length % 2) != 0) {
		        if (($data.length + k) % 2 != 0) {
			        $cssClass = 'light';
		        }
		    } else if (($data.length + k + 1) % 2 != 0) {
			    $cssClass = 'light';
		    }
			
		    // Creates the markup for a new row.
		    $newrow = '<tr id="new' + k + '" class="' + $cssClass + '"><td class="location"><div></div></td><td class="airline"><div></div></td><td class="flight"><div></div></td><td class="scheduled"><div></div></td><td class="details"><div></div></td></tr>';
            $('table.arrivalsDeparturesBoard').append($newrow);
	    }
		
	    // Reload rows collection with the new rows added.
	    $rows = $('table.arrivalsDeparturesBoard tr[class!=head]');
    	
	    // Update row content according to data    
	    for (i=0;i<$rows.length;i++) {
	        displayHeader = false;
	        
		    // Get the row specific values into local variables
		    $row = $rows.eq(i);
		    $rowId = $row.attr('id');
    		
		    $location = $('tr#' + $rowId + ' > td.location > div').eq(0);
		    $airline = $('tr#' + $rowId + ' > td.airline > div').eq(0);
		    $flight = $('tr#' + $rowId + ' > td.flight > div').eq(0);
		    $scheduled = $('tr#' + $rowId + ' > td.scheduled > div').eq(0);
		    $comment = $('tr#' + $rowId + ' > td.details > div').eq(0);

		    $rowDivs = $('tr#' + $rowId + ' div').eq(0);
			
		    // Update row specific values
		    $rowId = $data[i].FlightId;
		    $row.attr('id', $rowId);
			
		    if (directionType == DirectionType.Departures) {
		        $location.text($data[i].FlightTo);
		    } else {
		        $location.text($data[i].FlightFrom);
		    }
		    $airline.text($data[i].Airline);
		    $flight.text($data[i].FlightNumber);
		    $scheduled.html(FormatDateTime($data[i].FlightDateString, $data[i].FlightTimeString));
		    $comment.html($data[i].Comment);
			
		    FlightBoardItemCssClassUpdate($row, $data[i].Comment);

			$currentDate = $('tr#' + $rowId + ' > td.scheduled > div > span.date').eq(0);

			if (i == 0) {
			    displayHeader = true;
			} else {
			    $previousRow = $rows.eq(i - 1);
			    $previousRowId = $previousRow.attr('id');
			    $previousDate = $('tr#' + $previousRowId + ' > td.scheduled > div > span.date').eq(0);

			    if ($currentDate.text() != $previousDate.text()) {
			        displayHeader = true;
			    }
			}

			if (displayHeader) {
			    if (i == 0) {
			        $header = '<tr class="head date first">';
			    }
			    else {
			        $header = '<tr class="head date">';
			    }

			    $header += '<th colspan="5">' + FormatDateHeader($currentDate.text()) + '</th></tr>';

			    $row.hide();
                
			    $row.before($header);
			    
			    if (directionType == DirectionType.Departures) {
			        $row.before($departuresHeader);
			    } else {
			        $row.before($arrivalsHeader);
			    }
			    
			    $row.show();
			}                    
	    } 
	} else {
	    $noResults = '<div class="message warning clientMessage"><h3>Sorry, there wasn\'t a match</h3><p>No flights have been found for the location or flight number entered. Please try again.</p></div>';
        $('#arrDepSearch').after($noResults);
        $('.arrivalsDeparturesBoard').remove();
	}
	
	$('a#update').removeAttr('style');
}

// This method shows and hides destination specific related
// information and tries to load a destination summary if one is
// available via AJAX.
function ShowRelatedDetails() {
    $location = $("#arrDepSearchForm select[id$='LocationList']").val();

    if ($location != '') {
        $('.destinationsRelated').removeClass('offscreen');
        $('.destinationDetail').show();

        $params = "{'destination':'" + $location.replace("'", "\\'") + "'}";
        $url = "/services/AjaxWebServices.asmx/DestinationSummaryGet";

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: $url,
            data: $params,
            dataType: "json",
            success: function(results) {
                DestinationSummarySet(results);
            },
            error: function(xhr, status, error) {
                $('.destinationDetail').hide();
            }
        });
    }
    else {
        $('.destinationsRelated').addClass('offscreen');
    }
};

// Loads the provided summary into the div if it isn't empty.
function DestinationSummarySet(results) {
    $div = $('#destinationDetailInner');

    // Load JSON data and current rows into variables.
    $data = results.d;

    if ($data.length > 0) {
        $div.html($data);
    }
    else {
        $('.destinationDetail').hide();
    }
}

function HighlightTimespan() {
    $('#timespan .option').removeClass('selected');

    $selectedRadioButton = $('#timespan .option input:checked');
    $selectedRadioButton.parent().addClass('selected');
}

// By default destination specific related information is hidden.
// This must be offscreen not actually hidden or the ADT booking 
// form will not load correctly.
$(document).ready(function() {
    $location = $("#arrDepSearchForm select[id$='LocationList']").val();

    if ($location == '') {
        $('.destinationsRelated').addClass('offscreen');
    }

    HighlightTimespan();
});
