﻿/****** REGION: Constants ******/
var xmlDataDocMotorCycle = "";
var xmlAirportDataDoc = "";
var xmlCarDataDoc = "";
var xmlDataDocIndRail = "";
/****** END REGION: Constants ******/

function loadHolidayData() {
    loadXmlAirportDataDoc();
    loadCarXmlDataDoc();
    loadMotorcycleXmlDataDoc();
    loadRailXmlDataDoc();
}

/****** REGION: flight data ******/
function loadXmlAirportDataDoc()
{
    feed_id = 0;
    feed_total = 0;
    feed_file = individualFlightXML;
    
    if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
        xmlAirportDataDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlAirportDataDoc.async = "true";
        xmlAirportDataDoc.onreadystatechange = verifyXmlAirportDataLoaded;
        xmlAirportDataDoc.load(airportXML);
    } else if (window.XMLHttpRequest) {
        xmlAirportDataDoc = new XMLHttpRequest();
        xmlAirportDataDoc.onreadystatechange = verifyXmlAirportDataLoaded;
        xmlAirportDataDoc.open("GET", airportXML, true);
        xmlAirportDataDoc.send(null);
    }
    return true;
}
function verifyXmlAirportDataLoaded()
{
    if (xmlAirportDataDoc.readyState == 4)
    {
        loadOption1DptrApt();
        loadOption1DstApt();
    };
}

/****** REGION: car data ******/
function loadCarXmlDataDoc()
{
    feed_id = 0;
    feed_total = 0;
    feed_file = individualCarXML;
    
    if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
        xmlCarDataDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlCarDataDoc.async = "true";
        xmlCarDataDoc.onreadystatechange = verifyCarXmlDataLoaded;
        xmlCarDataDoc.load(individualCarXML);
    } else if (window.XMLHttpRequest) {
        xmlCarDataDoc = new XMLHttpRequest();
        xmlCarDataDoc.onreadystatechange = verifyCarXmlDataLoaded;
        xmlCarDataDoc.open("GET", individualCarXML, true);
        xmlCarDataDoc.send(null);
    }
    return true;
}
function verifyCarXmlDataLoaded()
{
    //alert('xmlDoc readyState: ' + xmlDataDoc.readyState);
    if (xmlCarDataDoc.readyState == 4)
    {
        loadOption1FuelTypes();
        //loadOption1CityDriving();
    };
}

/****** REGION: Motorcycle data ******/
function loadMotorcycleXmlDataDoc()
{
    feed_id = 0;
    feed_total = 0;
    feed_file = individualMotorcycleXML;
    
    if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
        xmlDataDocMotorCycle = new ActiveXObject("Microsoft.XMLDOM");
        xmlDataDocMotorCycle.async = "true";
        xmlDataDocMotorCycle.onreadystatechange = verifyMotorcycleXmlDataLoaded;
        xmlDataDocMotorCycle.load(individualMotorcycleXML);
    } else if (window.XMLHttpRequest) {
        xmlDataDocMotorCycle = new XMLHttpRequest();
        xmlDataDocMotorCycle.onreadystatechange = verifyMotorcycleXmlDataLoaded;
        xmlDataDocMotorCycle.open("GET", individualMotorcycleXML, true);
        xmlDataDocMotorCycle.send(null);
    }
    return true;
}
function verifyMotorcycleXmlDataLoaded()
{
    //alert('xmlDoc readyState: ' + xmlDataDocMotorCycle.readyState);
    if (xmlDataDocMotorCycle.readyState == 4)
    {
        //loadOption1MotorcycleCityDriving();
        loadOption1MotorCycleEngineSizes();
    };
}

/****** REGION: Rail data ******/
function loadRailXmlDataDoc()
{
    feed_id = 0;
    feed_total = 0;
    feed_file = individualFlightXML;
    
    if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
        xmlDataDocIndRail = new ActiveXObject("Microsoft.XMLDOM");
        xmlDataDocIndRail.async = "true";
        xmlDataDocIndRail.onreadystatechange = verifyRailXmlDataLoaded;
        xmlDataDocIndRail.load(individualRailXML);
    } else if (window.XMLHttpRequest) {
        xmlDataDocIndRail = new XMLHttpRequest();
        xmlDataDocIndRail.onreadystatechange = verifyRailXmlDataLoaded;
        xmlDataDocIndRail.open("GET", individualRailXML, true);
        xmlDataDocIndRail.send(null);
    }
    return true;
}
function verifyRailXmlDataLoaded()
{
    if (xmlDataDocIndRail.readyState == 4)
    {
        loadOpt1RailTravelMethod();
    };
}

/****** REGION: Option 1 Methods ******/
function loadOption1DptrApt()
{
    var selectID = 'ddlOpt1FlightDpt';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the data
        if (xmlAirportDataDoc.responseXML) 
        {
            xmlAirportDataDoc = xmlAirportDataDoc.responseXML;
        }
        if (xmlAirportDataDoc.getElementsByTagName('airport').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select departure airport...', '');            
            
            var airports = xmlAirportDataDoc.getElementsByTagName('airport');
            for (var i = 0; i < airports.length; i++)
            {
                var airportName = airports.item(i).getAttribute('city') + " - " + airports.item(i).childNodes[0].nodeValue;
                var airportLat = convertLatToMetric(airports.item(i).getAttribute('latDeg'), airports.item(i).getAttribute('latMin'), 
                    airports.item(i).getAttribute('latSec'), airports.item(i).getAttribute('latDirection'));
                var airportLong = convertLongToMetric(airports.item(i).getAttribute('longDeg'), airports.item(i).getAttribute('longMin'), 
                    airports.item(i).getAttribute('longSec'), airports.item(i).getAttribute('longDirection'));
                var airportLatLon = airportLat + "," + airportLong;
                AddListOption(selectID, airportName, airportLatLon);
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}
function loadOption1DstApt()
{
    var selectID = 'ddlOpt1FlightDst';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the data
        if (xmlAirportDataDoc.responseXML) 
        {
            xmlAirportDataDoc = xmlAirportDataDoc.responseXML;
        }
        if (xmlAirportDataDoc.getElementsByTagName('airport').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select destination airport...', '');            
            
            var airports = xmlAirportDataDoc.getElementsByTagName('airport');
            for (var i = 0; i < airports.length; i++)
            {
                var airportName = airports.item(i).getAttribute('city') + " - " + airports.item(i).childNodes[0].nodeValue;
                var airportLat = convertLatToMetric(airports.item(i).getAttribute('latDeg'), airports.item(i).getAttribute('latMin'), 
                    airports.item(i).getAttribute('latSec'), airports.item(i).getAttribute('latDirection'));
                var airportLong = convertLongToMetric(airports.item(i).getAttribute('longDeg'),airports.item(i).getAttribute('longMin'), 
                    airports.item(i).getAttribute('longSec'), airports.item(i).getAttribute('longDirection'));
                var airportLatLon = airportLat + "," + airportLong;
                AddListOption(selectID, airportName, airportLatLon);
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}function loadOption1FuelTypes()
{
    var selectID = 'ddlOpt1CarFuelType';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the data
        if (xmlCarDataDoc.responseXML) 
        {
            xmlCarDataDoc = xmlCarDataDoc.responseXML;
        }
        if (xmlCarDataDoc.getElementsByTagName('Option').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select fuel type...', '');            
            
            var options = xmlCarDataDoc.getElementsByTagName('Option');
            for (var i = 0; i < options.length; i++)
            {
                // check the "Name" attribute of the data item
                var optionName = options.item(i).getAttribute('Name');
                if (optionName == 'Mileage Per Annum')
                { // this is the data item we want
                    var fuelTypes = options.item(i).getElementsByTagName('FuelType');
                    // add the data items to the list
                    for (var iFt = 0; iFt < fuelTypes.length; iFt++)
                    {
                        AddListOption(selectID, fuelTypes.item(iFt).getAttribute('Name'), 
                            fuelTypes.item(iFt).getAttribute('Name'));
                    }
                }
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}
function loadOption1CityDriving()
{
    debugger;
    var selectID = 'ddlOpt1CarCityDriving';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the data
        if (xmlCarDataDoc.responseXML) 
        {
            xmlCarDataDoc = xmlCarDataDoc.responseXML;
        }
        if (xmlCarDataDoc.getElementsByTagName('Option').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select how much city driving...', '');            
            
            var options = xmlCarDataDoc.getElementsByTagName('Option');
            for (var i = 0; i < options.length; i++)
            {
                // check the "Name" attribute of the data item
                var optionName = options.item(i).getAttribute('Name');
                if (optionName == 'Mileage Per Annum')
                { // this is the data item we want
                    var fuelTypes = options.item(i).getElementsByTagName('CityDrivingOption');
                    // add the data items to the list
                    for (var iFt = 0; iFt < fuelTypes.length; iFt++)
                    {
                        AddListOption(selectID, fuelTypes.item(iFt).firstChild.nodeValue, 
                            fuelTypes.item(iFt).getAttribute('MultiplicationFactor'));
                    }
                }
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}
function loadOption1EngineSizes(selectFuelType)
{
    // set selectID of engine <select>
    var selectID = 'ddlOpt1CarEngineSize';

    // get the selected value from the calling select
    var selectedValue = selectFuelType.options[selectFuelType.selectedIndex].value;
    
    // populate the target select with data
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the country's airports
        if (xmlCarDataDoc.getElementsByTagName('Option').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select engine size...', '');            
            
            var options = xmlCarDataDoc.getElementsByTagName('Option');
            for (var i = 0; i < options.length; i++)
            {
                // check the "Name" attribute of the data item
                var optionName = options.item(i).getAttribute('Name');
                if (optionName == 'Mileage Per Annum')
                { // this is the data item we want
                    var fuelTypes = options.item(i).getElementsByTagName('FuelType');
                    
                    // find the matching FuelType to selectedValue
                    for (var iFt = 0; iFt < fuelTypes.length; iFt++)
                    {
                        if (fuelTypes.item(iFt).getAttribute('Name') == selectedValue)
                        {
                            // this is the matching fuel type, get the EngineSizes and bind them to the select control
                            var engineSizes = fuelTypes.item(iFt).getElementsByTagName('EngineSize');
                            for (var iEs = 0; iEs < engineSizes.length; iEs++)
                            {
                                 AddListOption(selectID, engineSizes.item(iEs).firstChild.nodeValue, 
                                    engineSizes.item(iEs).getAttribute('EmissionFactor'));
                            }
                        }
                    }
                }
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}
function loadOption1MotorCycleEngineSizes()
{
    var selectID = 'ddlOp1MotorcycleEngineSize';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the data
        if (xmlDataDocMotorCycle.responseXML) 
        {
            xmlDataDocMotorCycle = xmlDataDocMotorCycle.responseXML;
        }
        if (xmlDataDocMotorCycle.getElementsByTagName('Option').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select...', '');            
            
            var options = xmlDataDocMotorCycle.getElementsByTagName('Option');
            for (var i = 0; i < options.length; i++)
            {
                // check the "Name" attribute of the data item
                var optionName = options.item(i).getAttribute('Name');
                if (optionName == 'Mileage Per Annum')
                { // this is the data item we want
                    var fuelTypes = options.item(i).getElementsByTagName('EngineSize');
                    // add the data items to the list
                    for (var iFt = 0; iFt < fuelTypes.length; iFt++)
                    {
                        AddListOption(selectID, fuelTypes.item(iFt).firstChild.nodeValue, 
                            fuelTypes.item(iFt).getAttribute('EmissionFactor'));
                    }
                }
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}
function loadOption1MotorcycleCityDriving()
{
    debugger;
    var selectID = 'ddlOpt1MotorcycleCityDriving';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting the data
        if (xmlDataDocMotorCycle.responseXML) 
        {
            xmlDataDocMotorCycle = xmlDataDocMotorCycle.responseXML;
        }
        if (xmlDataDocMotorCycle.getElementsByTagName('Option').length > 0) {
            // add a default "Select" option
            AddListOption(selectID, 'Select...', '');            
            
            var options = xmlDataDocMotorCycle.getElementsByTagName('Option');
            for (var i = 0; i < options.length; i++)
            {
                // check the "Name" attribute of the data item
                var optionName = options.item(i).getAttribute('Name');
                if (optionName == 'Mileage Per Annum')
                { // this is the data item we want
                    var fuelTypes = options.item(i).getElementsByTagName('CityDrivingOption');
                    // add the data items to the list
                    for (var iFt = 0; iFt < fuelTypes.length; iFt++)
                    {
                        AddListOption(selectID, fuelTypes.item(iFt).firstChild.nodeValue, 
                            fuelTypes.item(iFt).getAttribute('MultiplicationFactor'));
                    }
                }
            };
        }
        else {
            AddListOption(selectID, 'Error loading data', '');
        };
    };
}
function loadOpt1RailTravelMethod()
{
    var selectID = 'ddlOpt1RailMethod';
    if (document.getElementById(selectID))
    {
        // clear previous values out first.
        RemoveListOptions(selectID);
        
        // iterate through the xml document getting data
        if (xmlDataDocIndRail.responseXML) {
            xmlDataDocIndRail = xmlDataDocIndRail.responseXML;
        }
        if (xmlDataDocIndRail.getElementsByTagName('Option').length > 0) {
            // add a default "Select..." option
            AddListOption(selectID, 'Select...', '');
            
            var options = xmlDataDocIndRail.getElementsByTagName('Option');
            for (var i = 0; i < options.length; i++)
            {
                // check the "Name" attribute of the data item
                var optionName = options.item(i).getAttribute('Name');
                if (optionName == 'Non-Regular Commuter')
                { // this is the data item we want
                    var listItems = options.item(i).getElementsByTagName('TravelMethod');
                    // add the data items to the list
                    for (var iLi = 0; iLi < listItems.length; iLi++)
                    {
                        AddListOption(selectID, listItems.item(iLi).firstChild.nodeValue, 
                            listItems.item(iLi).getAttribute('EmissionFactor'));
                    }
                }
            };
        }
    }
}
function calculateOption1()
{
    if (document.getElementById)
    {
     
    	var ddlOpt1NumPpl = document.getElementById('ddlOpt1NumPpl');
    	var txtOpt1Days = document.getElementById('txtOpt1Days');
        //var ddlOpt1Flight = document.getElementById('ddlOpt1Flight');
        var ddlOpt1Flight = document.forms[0].optFlight;
        var ddlOpt1FlightDpt = document.getElementById('ddlOpt1FlightDpt');
        var ddlOpt1FlightDst = document.getElementById('ddlOpt1FlightDst');
    	//var ddlOpt1Car = document.getElementById('ddlOpt1Car');
    	var ddlOpt1Car = document.forms[0].optDrive;
        var ddlOpt1CarFuelType = document.getElementById('ddlOpt1CarFuelType');
        var ddlOpt1CarEngineSize = document.getElementById('ddlOpt1CarEngineSize');
        var txtOpt1CarMiles = document.getElementById('txtOpt1CarMiles');
        var blnUseCarKilometres = false;
        if((txtOpt1CarMiles.value == '') || (parseInt(txtOpt1CarMiles.value) == 0))
        {
            blnUseCarKilometres = true;
            txtOpt1CarMiles = document.getElementById('txtOpt1CarKilometres');
        }
        //var ddlOpt1CarCityDriving = document.getElementById('ddlOpt1CarCityDriving');
    	//var ddlOpt1Rail = document.getElementById('ddlOpt1Rail');
    	var ddlOpt1Rail = document.forms[0].optRail;
        var txtOpt1RailMiles = document.getElementById('txtOpt1RailMiles');
        var blnUseRailKilometres = false;
        if ((txtOpt1RailMiles.value == '') || (parseInt(txtOpt1RailMiles.value) == 0))
        {
            blnUseRailKilometres = true;
            txtOpt1RailMiles = document.getElementById('txtOpt1RailKilometres');
        }
        var ddlOpt1RailMethod = document.getElementById('ddlOpt1RailMethod');
    	//var ddlOpt1Coach = document.getElementById('ddlOpt1Coach');
    	var ddlOpt1Coach = document.forms[0].optCoach;
        var txtOpt1CoachMiles = document.getElementById('txtOpt1CoachMiles');
        var blnUseCoachKilometres = false;
        if ((txtOpt1CoachMiles.value == '')||(parseInt(txtOpt1CoachMiles.value) == 0))
        {
            blnUseCoachKilometres = true;
            txtOpt1CoachMiles = document.getElementById('txtOpt1CoachKilometres');
        }        
    	//var ddlOpt1Motorcycle = document.getElementById('ddlOpt1Motorcycle');
    	var ddlOpt1Motorcycle = document.forms[0].optMotorcycle;
        var ddlOp1MotorcycleEngineSize = document.getElementById('ddlOp1MotorcycleEngineSize');
        var txtOpt1MotorcycleMiles = document.getElementById('txtOpt1MotorcycleMiles');
        var blnUseMotorcycleKilometres = false;
        if((txtOpt1MotorcycleMiles.value == '')||(parseInt(txtOpt1MotorcycleMiles.value) == 0))
        {
            blnUseMotorcycleKilometres = true;
            txtOpt1MotorcycleMiles = document.getElementById('txtOpt1MotorcycleKilometres');
        }   
        //var ddlOpt1MotorcycleCityDriving = document.getElementById('ddlOpt1MotorcycleCityDriving');
        var ddlOpt1PrivateTrans = document.getElementById('ddlOpt1PrivateTrans');
        var ddlOpt1PublicTrans = document.getElementById('ddlOpt1PublicTrans');
        
        var result = 0;
        // calculate the transport to and from the destination
        if (ddlOpt1Flight[0].checked) {
            var airportFrom = ddlOpt1FlightDpt.value.split(',');
            var airportTo = ddlOpt1FlightDst.value.split(',');
            var flightKgs = calculateLatLongDistance(airportFrom[0], airportFrom[1], airportTo[0], airportTo[1]);
            flightKgs = flightKgs * ddlOpt1NumPpl.value * nonRegularFlightKgCo2PerKmPerPassenger * 2;
            result = parseFloat(result) + parseFloat(flightKgs);
        }
        if (ddlOpt1Car[0].checked) {
            var carKgs = ddlOpt1CarEngineSize.value * (txtOpt1CarMiles.value * (blnUseCarKilometres ? 1 : KilometresToMilesConversionFactor)) * CarNeverCityDriving;
            result = parseFloat(result) + parseFloat(carKgs);
        }
        if (ddlOpt1Rail[0].checked) {
            var railKgs = (txtOpt1RailMiles.value * (blnUseRailKilometres ? 1 : KilometresToMilesConversionFactor)) * 3 * ddlOpt1RailMethod.value * ddlOpt1NumPpl.value;
            result = parseFloat(result) + parseFloat(railKgs);
        }
        if (ddlOpt1Coach[0].checked) {
            var coachKgs = (txtOpt1CoachMiles.value * (blnUseCoachKilometres ? 1 : KilometresToMilesConversionFactor)) * 0.09 * ddlOpt1NumPpl.value;
            result = parseFloat(result) + parseFloat(coachKgs);
        }
        if (ddlOpt1Motorcycle[0].checked) {
            var motocycleKgs = ddlOp1MotorcycleEngineSize.value * (txtOpt1MotorcycleMiles.value * (blnUseMotorcycleKilometres ? 1 : KilometresToMilesConversionFactor)) * 
                MotorCycleNeverCityDriving;
            result = parseFloat(result) + parseFloat(motocycleKgs);
        }
        
        // calculate accomodation, food and local services emissions
        var accomKgs = ddlOpt1NumPpl.value * txtOpt1Days.value * 200;
        result = parseFloat(accomKgs) + parseFloat(result);
        
        // calculate local private transport emissions
        if (ddlOpt1PrivateTrans.value == "yes") {
            var privateTransKgs = txtOpt1Days.value * 500;
            result = parseFloat(result) + parseFloat(privateTransKgs);
        }
        
        // calculate local public transport emissions
        if (ddlOpt1PublicTrans.value == "yes") {
            var publicTransKgs = ddlOpt1NumPpl.value * txtOpt1Days.value * 80;
            result = parseFloat(result) + parseFloat(publicTransKgs);
        }
        
        // convert from kilo's to tonnes
        result = result / 1000;
                
        // round to two decimal places
        var roundedResult = Math.round(result*100)/100;
        // show the cost of this offset
        var roundedCost = (Math.round((roundedResult * costPerTonne)*100)/100).toFixed(2);
        document.getElementById('ctl00_cphPrimary_hfOpt1Result').value = roundedResult;
        
        if(document.all)
        {
            document.getElementById('divOpt1Result').innerHTML = roundedResult.toString();
            document.getElementById('divOpt1Cost').innerText = roundedCost;
        }
        else
        {
            document.getElementById('divOpt1Result').textContent = roundedResult.toString();
            document.getElementById('divOpt1Cost').textContent  = roundedCost;
        }
    }
}

function calculateLatLongDistance(lat1, long1, lat2, long2)
{
    var R = 6371; // km
    var dLat = (lat2-lat1) * Math.PI / 180;
    var dLon = (long2-long1) * Math.PI / 180; 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
            Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;
    return d;
}
function convertLatToMetric(degree, minutes, seconds, compassDirection)
{
    degree = parseFloat(degree);
    minutes = parseFloat(minutes / 60);
    seconds = parseFloat(seconds / 3600);
    var newLat = parseFloat(degree + minutes + seconds);
    if (compassDirection.toLowerCase() == "s") newLat = "-" + newLat;    
    return newLat;
}
function convertLongToMetric(degree, minutes, seconds, compassDirection)
{
    degree = parseFloat(degree);
    minutes = parseFloat(minutes / 60);
    seconds = parseFloat(seconds / 3600);
    var newLon = parseFloat(degree + minutes + seconds);
    if (compassDirection.toLowerCase() == "w") newLon = "-" + newLon;
    return newLon;
}
/****** END REGION: Option 1 Methods ******/
