﻿$(document).ready(function () {
    $("#results_body table tr:even").css("background-color", "#d8eaed");
    $("table.data tr:even").css("background-color", "#d8eaed");
    $('#results_body table tr:first').before('<tr><td><strong>From</strong></td><td><strong>To</strong></td><td><strong>Aircraft</strong></td><td><strong>From Date</strong></td><td><strong>To Date</strong></td><td><strong>Seats</strong></td><td><strong>Enquire</strong></td></tr>');
    $('ul#fade').cycle({
        fx: 'fade',
        timeout: 6000,
        random: 1
    });
});

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function displayImage(imageId) {
    $.blockUI({
        message: "<br /><img onclick='closeBlockUI();' src='DisplayDBImage.aspx?id=" + imageId + "&table=VehicleImage&MaxX=480&MaintainHorzAspect=true' /><p class='smallP' onclick='closeBlockUI();'>click image to close</p><br />",
        css: {
            top: ($(window).height() - 500) / 2 + 'px',
            left: ($(window).width() - 500) / 2 + 'px',
            width: '500px',
            cursor: 'pointer'
        },
        showOverlay: false
    });
}
function closeBlockUI() {
    $.unblockUI({ fadeOut: 200 });
}  

// Define this control's client-side functionality in a closure so it won't affect anything else on the page
	function ShowAirportSelector(title, $textValueControl, $idAndPosValueControl, $idOnlyValueControl)
	{
		///	<summary>
		///		1: ShowAirportSelector($textValueControl, $idAndPosValueControl) - shows the airport picker popup
		///	</summary>
		///	<param name="$textValueControl" type="jQuery">
		///		1: $textValueControl - jQuery object containing the element in which to display the name of the selected airport
		///	</param>
		///	<param name="$idAndPosValueControl" type="jQuery">
		///		1: $idAndPosValueControl - jQuery object containing the object in which to store the id etc of the selected airport
		///	</param>
		var SelectAirport = function SelectAirport($textValueControl, $idAndPosValueControl)
		{
			var _selectAirport = this;
			_selectAirport.$ddlCountry = $('.ddlCountry');
			_selectAirport.$ddlCity = $('.ddlCity');
			_selectAirport.$ddlAirport = $('.ddlAirport');
			_selectAirport.$acceptButton = $('.imgSelectAirport');
			
			var SelectedAirport = function ()
			{
				var _selectedAirport = this;
				var Location = function ()
				{
					var _location = this;
					this.Id = 0;
					this.Latitude = 0;
					this.Longitude = 0;
					this.Name = '';
					this.Parse = function (compoundId)
					{
						var temp = compoundId.split('|');
						if (temp.length === 3)
						{
							_location.Id = temp[0];
							_location.Latitude = temp[1];
							_location.Longitude = temp[2];
						}
					};
					this.CompoundId = function()
					{
						return _location.Id + '|' + _location.Latitude + '|' + _location.Longitude;
					};
				};
				_selectedAirport.Country = new Location();
				_selectedAirport.City = new Location();
				_selectedAirport.Airport = new Location();
				_selectedAirport.Name = function()
				{
					return _selectedAirport.Airport.Name + ', ' + _selectedAirport.City.Name + ', ' + _selectedAirport.Country.Name;
				}
			}
			
			$('.imgSelectAirport').click(function()
			{
				var selectedValue = _selectAirport.$ddlAirport.val();
				if (selectedValue === null || selectedValue === '-1')
					alert('No airport has been selected');
				else
				{
					
					var selectedAirport = new SelectedAirport();
					selectedAirport.Country.Parse(_selectAirport.$ddlCountry.val());
					selectedAirport.City.Parse(_selectAirport.$ddlCity.val());
					selectedAirport.Airport.Parse(selectedValue);
					selectedAirport.Country.Name = _selectAirport.$ddlCountry.find('option:selected').text();
					selectedAirport.City.Name = _selectAirport.$ddlCity.find('option:selected').text();
					selectedAirport.Airport.Name = _selectAirport.$ddlAirport.find('option:selected').text();
					
					var jsonSelectedAirport = JSON.stringify(selectedAirport);
					
					var airportName = selectedAirport.Name();
					$textValueControl.val(airportName);
					$idAndPosValueControl.val(jsonSelectedAirport);
					$idOnlyValueControl.val(selectedAirport.Airport.Id);
					$(this).unbind('click');
					tb_remove();
				}
			});
			
			var _mapCityZoomLevel = 8;
			var _mapCountryZoomLevel = 6;
			var _mapAirportZoomLevel = 13;
			var _mapDefaultLatitude = 51.511307;
			var _mapDefaultLongitude = -0.098877;
			
			// set up a default map point - this is where the map will pan to before a country/city/airport is selected
			var LondonLatLon = new GLatLng(_mapDefaultLatitude, _mapDefaultLongitude);
			
			// initialise the googlemap
			_selectAirport.mapAirports = new GMap2($('.airportMap')[0]);
			_selectAirport.mapAirports.setMapType(G_HYBRID_MAP);
			_selectAirport.mapAirports.enableDragging();
			_selectAirport.mapAirports.setCenter(LondonLatLon);
			_selectAirport.mapAirports.setZoom(5);
			_selectAirport.mapAirports.checkResize();

			
			var makeAjaxRequest = function (url, data, successFunction, errorFunction)
			{
				$.ajax(
				{
					type: "POST",
					contentType: "application/json; charset=utf-8",
					url: url,
					data: data,
					dataType: "json",
					success: successFunction,
					error: errorFunction
				});
			};

			var displayAjaxError = function (data, textStatus, errorThrown)
			{
				alert(textStatus + ' - ' + errorThrown);
			};

			_selectAirport.AirportChanged = function () 
			{
				var ids = _selectAirport.$ddlAirport.val().split("|");

				_selectAirport.mapAirports.setZoom(_mapAirportZoomLevel);
				if (ids[1] == null || ids[2] == null)
					{
					    // no airport selected - go back to city zoom
					    var idsCity = _selectAirport.$ddlCity.val().split("|");
					   _selectAirport.mapAirports.setZoom(_mapCityZoomLevel);
					    if (idsCity[1] == null || idsCity[2] == null)
						    _selectAirport.mapAirports.panTo(LondonLatLon); // default catch - should always have a country selected
					    else
						    _selectAirport.mapAirports.panTo(new GLatLng(idsCity[1], idsCity[2]));
					
					}
				else
					_selectAirport.mapAirports.panTo(new GLatLng(ids[1], ids[2]));
			};

			_selectAirport.CountryChanged = function (selectedCityId, selectedAirportId) 
			{
				var ids = _selectAirport.$ddlCountry.val().split("|");

				_selectAirport.ResetCityDropdown();

				
				if (!argmentsAllDefinedAndNonNull(selectedCityId, selectedAirportId))
				{
					_selectAirport.mapAirports.setZoom(_mapCountryZoomLevel);
					if (ids[1] == null || ids[2] == null)
						_selectAirport.mapAirports.panTo(LondonLatLon); // default
					else
						_selectAirport.mapAirports.panTo(new GLatLng(ids[1], ids[2]));
				}
				_selectAirport.$ddlCity.next('span').html('<img src="images/ajaxLoader.gif" alt="Loading cities" />');
				
				var PopulateCitiesWrapper = function(data)
				{
					
					if (argmentsAllDefinedAndNonNull(selectedCityId, selectedAirportId))
					{
						_selectAirport.PopulateCitiesDDL(data, selectedCityId, selectedAirportId);
					}
					else
						_selectAirport.PopulateCitiesDDL(data);
				}
				
				makeAjaxRequest('/services/JQueryService.asmx/GetCitiesByCountry', "{'iCountryID' : '" + ids[0] + "'}", PopulateCitiesWrapper, displayAjaxError);
			};
			
			_selectAirport.CityChanged = function (e, selectedAirportId) 
			{
				var ids = _selectAirport.$ddlCity.val().split("|");
				
				_selectAirport.ResetAirportDropdown();

				
				if (!argmentsAllDefinedAndNonNull(selectedAirportId))
				{
					if (ids[1] == null || ids[2] == null)
					{
					    // no city selected - go back to country zoom
					    var idsCountry = _selectAirport.$ddlCountry.val().split("|");
						_selectAirport.mapAirports.setZoom(_mapCountryZoomLevel);
					    if (idsCountry[1] == null || idsCountry[2] == null)
						    _selectAirport.mapAirports.panTo(LondonLatLon); // default catch - should always have a country selected
					    else
						    _selectAirport.mapAirports.panTo(new GLatLng(idsCountry[1], idsCountry[2]));
					}
					else
					{
					    _selectAirport.mapAirports.setZoom(_mapCityZoomLevel);
						_selectAirport.mapAirports.panTo(new GLatLng(ids[1], ids[2]));
					}
				}
				
				_selectAirport.$ddlAirport.next('span').html('<img src="images/ajaxLoader.gif" alt="Loading airports" />');
				
				var PopulateAirportsWrapper = function(data)
				{
					
					if (argmentsAllDefinedAndNonNull(selectedAirportId))
					{
						_selectAirport.PopulateAirportsDDL(data, selectedAirportId);
					}
					else
						_selectAirport.PopulateAirportsDDL(data);
				}
				
				makeAjaxRequest('/services/JQueryService.asmx/GetAirportsByCity', "{'iCityID' : '" + ids[0] + "'}", PopulateAirportsWrapper, displayAjaxError);
			};

			
			var argmentsAllDefinedAndNonNull = function()
			{
				var allDefinedAndNonNull = true;
				for (var i = 0; i < arguments.length; i++)
				{
					allDefinedAndNonNull = allDefinedAndNonNull && (arguments[i] !== null && arguments[i] !== undefined);
				}
				return allDefinedAndNonNull;
			};
			
			_selectAirport.PopulateCitiesDDL = function (data, selectedCityId, selectedAirportId) 
			{
				
				if (argmentsAllDefinedAndNonNull(selectedCityId, selectedAirportId))
				{
					PopulateIdLatLonNameDDL(_selectAirport.$ddlCity, data, _selectAirport.ResetCityDropdown, selectedCityId);
					_selectAirport.CityChanged(null, selectedAirportId);
				}
				else
				{
					// The dropdowns don't need setting up, they need to be emptied
					PopulateIdLatLonNameDDL(_selectAirport.$ddlCity, data, _selectAirport.ResetCityDropdown);
				}
			};

			_selectAirport.PopulateAirportsDDL = function (data, selectedAirportId) 
			{
				if (argmentsAllDefinedAndNonNull(selectedAirport))
				{
					PopulateIdLatLonNameDDL(_selectAirport.$ddlAirport, data, _selectAirport.ResetAirportDropdown, selectedAirportId);
					_selectAirport.AirportChanged();
				}
				else
					PopulateIdLatLonNameDDL(_selectAirport.$ddlAirport, data, _selectAirport.ResetAirportDropdown);
			};
			
			function PopulateIdLatLonNameDDL($ddl, data, noDataFunction, selected) 
			{
				var arrData = eval('(' + data.d + ')');
				var $msgSpan = $ddl.next('span');
				if (arrData.length > 0)
				{
					$ddl.empty();
					var html = '<option value="-1">Please Select...</option>';
					for (var i = 0; i < arrData.length; i++) 
					{
						html = html + '<option value="' + arrData[i].IdWithLatLon + '"';
						if ((argmentsAllDefinedAndNonNull(selected) && selected === arrData[i].IdWithLatLon) || arrData.length == 1)
							html = html + ' selected="selected"';
						html = html + '>' + arrData[i].Name + '</option>';
					}
					$ddl.html(html);
					$msgSpan.html('');
					$ddl.show();
					if (arrData.length == 1)
						$ddl.trigger('change');
				}
				else
					noDataFunction();
			};
			
			_selectAirport.ResetCityDropdown = function ()
			{
				_selectAirport.$ddlCity.empty();
				_selectAirport.$ddlCity.hide();
				_selectAirport.$ddlCity.next('span').html('Please select a country');
				_selectAirport.ResetAirportDropdown();
			};

			_selectAirport.ResetAirportDropdown = function ()
			{
				_selectAirport.$ddlAirport.empty();
				_selectAirport.$ddlAirport.hide();
				_selectAirport.$ddlAirport.next('span').html('Please select a city');
			};
			
			_selectAirport.PrePopulateAirportSelector = function (selectedAirport) 
			{
				var selectedCountryId = selectedAirport.Country.Id + '|' + selectedAirport.Country.Latitude + '|' + selectedAirport.Country.Longitude;
				var selectedCityId = selectedAirport.City.Id + '|' + selectedAirport.City.Latitude + '|' + selectedAirport.City.Longitude;
				var selectedAirportId = selectedAirport.Airport.Id + '|' + selectedAirport.Airport.Latitude + '|' + selectedAirport.Airport.Longitude;
				// Select the country
				_selectAirport.$ddlCountry.val(selectedCountryId);
				_selectAirport.CountryChanged(selectedCityId, selectedAirportId);
			};

			var currentValue = $idAndPosValueControl.val();
			if (currentValue.length > 0) 
			{
				var selectedAirport = eval('(' + currentValue + ')');// = currentValue.split('|');
				_selectAirport.PrePopulateAirportSelector(selectedAirport);
			}
			else 
			{
				_selectAirport.$ddlCountry.val('-1');
				_selectAirport.ResetCityDropdown();
			}
			// attach events to the drop down menus
			_selectAirport.$ddlCountry.change(_selectAirport.CountryChanged);
			_selectAirport.$ddlCity.change(_selectAirport.CityChanged);
			_selectAirport.$ddlAirport.change(_selectAirport.AirportChanged);
		}
				
		var selectAirport = new SelectAirport($textValueControl, $idAndPosValueControl);
		tb_show(title, "#TB_inline?height=300&width=600&inlineId=divAirport", false);
		selectAirport.mapAirports.checkResize();
		return false;
}

function AirportChanged() {
    var ids = $('.ddlCities').val().split("|");

    mapAirports.setZoom(13);
    if (ids[1] == null || ids[2] == null)
        mapAirports.panTo(defaultLatLon);
    else
        mapAirports.panTo(new GLatLng(ids[1], ids[2]));

}

function CountryChanged() {
    var ids = $('.ddlCountries').val().split("|");

    $('.ddlCities').empty();
    $(".ddlAirports").empty();

    mapAirports.setZoom(6);
    if (ids[1] == null || ids[2] == null)
        mapAirports.panTo(LondonLatLon);
    else
        mapAirports.panTo(new GLatLng(ids[1], ids[2]));

    $('#cityLoading').html("<img src='images/ajaxLoader.gif' alt='Loading cities'>");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/JQueryService.asmx/GetCitiesByCountry",
        data: "{'iCountryID' : '" + ids[0] + "'}",
        dataType: "json",
        success: PopulateCitiesDDL,
        error: function (data, textStatus, errorThrown) {
            //debugger;
            alert(textStatus);
            alert(errorThrown);
        }
    });
}

function CityChanged() {
    var ids = $('.ddlCities').val().split("|");

    mapAirports.setZoom(8);
    if (ids[1] == null || ids[2] == null)
        mapAirports.panTo(LondonLatLon);
    else
        mapAirports.panTo(new GLatLng(ids[1], ids[2]));

    $('#airportLoading').html("<img src='images/ajaxLoader.gif' alt='Loading airports'>");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/JQueryService.asmx/GetAirportsByCity",
        data: "{'iCityID' : '" + ids[0] + "'}",
        dataType: "json",
        success: PopulateAirportsDDL,
        error: function (data, textStatus, errorThrown) {
            //debugger;
            alert(textStatus);
            alert(errorThrown);
        }
    });
}

function PopulateIdLatLonNameDDL(ddl, data) {
    var arrData = Sys.Serialization.JavaScriptSerializer.deserialize(data.d);
    if (arrData.length === 0)
        return;
    ddl.empty();

    var optionPS = document.createElement("option");
    optionPS.value = "-1";
    optionPS.text = "Please Select";
    ddl[0].options.add(optionPS);

    for (var i = 0; i < arrData.length; i++) {
        var option = document.createElement("option");
        option.value = arrData[i].IdWithLatLon;
        option.text = arrData[i].Name;
        ddl[0].options.add(option);
    }

}

function PopulateCitiesDDL(data) {
    $(".ddlAirports").empty();
    PopulateIdLatLonNameDDL($(".ddlCities"), data);
    $('#cityLoading').html("");
}

function PopulateAirportsDDL(data) {
    PopulateIdLatLonNameDDL($(".ddlAirports"), data);
    $('#airportLoading').html("");
}

function ShowSourceAirportSelector(e, legID) {
    e.preventDefault();

    $('#txtAirportLegType').val("source");
    $('#txtAirportLegNumber').val(legID);

    if ($('#txtSourceAirportId_Leg' + legID).val() != "") {
        var arrIDs = $('#txtSourceAirportId_Leg' + legID).val().split('|');
        PrePopulateAirportSelector(arrIDs);
    }
    else {
        $('.ddlCountries').val("-1");
        CountryChanged();
    }

    tb_show("Select Airport", "#TB_inline?height=300&width=600&inlineId=divAirport", false);
    //this.blur();
    mapAirports.checkResize();
    return false;
}

function ShowDestinationAirportSelector(e, legID) {
    e.preventDefault();


    $('#txtAirportLegType').val("dest");
    $('#txtAirportLegNumber').val(legID);



    if ($('#txtDestAirportId_Leg' + legID).val() != "") {
        var arrIDs = $('#txtDestAirportId_Leg' + legID).val().split('|');
        PrePopulateAirportSelector(arrIDs);
    }
    else {
        $('.ddlCountries').val("-1");
        CountryChanged();
    }

    tb_show("Select Airport", "#TB_inline?height=300&width=600&inlineId=divAirport", false);
    //this.blur();
    mapAirports.checkResize();
    return false;
}

function PrePopulateAirportSelector(arrIDs) {

    var airportID = arrIDs[0] + "|" + arrIDs[1] + "|" + arrIDs[2]
    var countryID = arrIDs[3] + "|" + arrIDs[4] + "|" + arrIDs[5]
    var cityID = arrIDs[6] + "|" + arrIDs[7] + "|" + arrIDs[8]

    // select the country
    $('.ddlCountries').val(countryID);

    // build the city ddl
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/JQueryService.asmx/GetCitiesByCountry",
        data: "{'iCountryID' : '" + arrIDs[3] + "'}",
        dataType: "json",
        success: PopulateCitiesDDL,
        error: function (data, textStatus, errorThrown) {
            //debugger;
            alert(textStatus);
            alert(errorThrown);
        }
    });

    // select the country
    $('.ddlCities').val(cityID);

    // build the airports
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/JQueryService.asmx/GetAirportsByCity",
        data: "{'iCityID' : '" + arrIDs[6] + "'}",
        dataType: "json",
        success: PopulateAirportsDDL,
        error: function (data, textStatus, errorThrown) {
            //debugger;
            alert(textStatus);
            alert(errorThrown);
        }
    });

    // select the airport
    $('.ddlAirports').val(airportID);
    AirportChanged();
}
