//Appends an element to the document
var appendHtml = function (element, html) {
var div = document.createElement('div');
div.innerHTML = html;
while (div.children.length > 0) {
element.appendChild(div.children[0]);
}
}
async function AddHeaderScripts() {
Log("Jquery Check");
if ('undefined' == typeof window.jQuery) {
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js');
document.head.appendChild(jQueryScript);
var count = 0;
//Check if Jquery is running yet?
while (!window.hasOwnProperty("jQuery")) {
Log("waiting for jQuery");
await new Promise(r => setTimeout(r, 250));
count++;
//Stop infinateloop maxtime 5s
if (count > 20) {
break;
}
}
}
AddScripts()
}
function AddScripts() {
if ('undefined' != typeof window.jQuery) {
Log("jQuery Installed");
$("head").append($("").attr("src","https://www.c-level.earth//scripts/autocomplete/autocomplete-combined.js"));
$("head").append($(""));
Log("All header scripts loaded");
} else {
Log("jQuery NOT Installed");
//Jquery didnt insert properly calculator wont run.
alert("Jquery could not be installed, please refresh and try again.");
}
}
//Global pramas
var quoteParmId = getParameterByName("oid");
var cancelParm = getParameterByName("c");
/* START Global Functions */
//Gets a query string parameter by name
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
//Hide all the steps in the calculator
function HideStep() {
$('.clevel-step').hide();
}
//Reloads the page
function ReloadPage() {
Log("Page reload");
window.location.reload();
}
//logging
function Log(message) {
if (balanceAPI.DeveloperMode) {
console.log(message)
}
}
//Get a property from an object by name
function GetProperty(item, name) {
if (item[name]) {
return item[name];
}
return "Key not found";
};
/* END Global Functions */
/* START API Functions */
async function FetchHtml(url){
var fetchedData = await fetch(url, {headers: {'apikey': balanceAPI.ApiKey},})
.then(response => response.text())
.then(responseBody => {
Log("FetchHtml:Complete " +url)
Log("FetchHtml:Text " +responseBody.toString())
return responseBody.toString();
})
.catch(error => {
console.error(error);
});
return fetchedData;
}
async function GetJSONFromAPI(url, result) {
var fetchedData = await fetch(url, {headers: {'apikey': balanceAPI.ApiKey, 'Content-Type': 'application/json'},})
.then(response => response.json())
.then(responseBody => {
Log("Fetch:Complete " +url)
Log("Fetch:JSON " +JSON.stringify(responseBody))
result = responseBody;
})
.catch(error => {
Log(error);
return null;
});
return result;
}
function GetJQueryAPICall(url){
var result = null;
$.ajax({
method: "GET",
url: url,
headers: {
'apikey': balanceAPI.ApiKey,
'Content-Type': 'application/json'
},
contentType: "application/json",
async: false,
error: function () {
alert("An error has occured please check entered data and try again!");
}
}).done(function (data) {
Log("GetJQueryAPICall" +data);
result = data;
});
return result;
}
function PostUpdate(url, postData) {
var _data = JSON.stringify(postData);
Log("PostUpdate" +_data);
$.ajax({
method: "POST",
url: balanceAPI.ApiUrl + url,
headers: {
'apikey': balanceAPI.ApiKey,
'Content-Type': 'application/json'
},
contentType: "application/json",
async: false,
data: _data,
error: function () {
alert("An error has occured please check entered data and try again!");
}
}).done(function (data) {
balanceAPI.UpdateResponse = data;
Log(data)
});
}
function PostCombine(postData) {
var _data = JSON.stringify(postData);
$.ajax({
method: "POST",
url: balanceAPI.ApiUrl + "/v1/quote/combine",
headers: {
'apikey': balanceAPI.ApiKey,
'Content-Type': 'application/json'
},
contentType: "application/json",
async: false,
data: _data,
error: function () {
alert("An error has occured please check entered data and try again!");
balanceAPI.QuoteDetails = null;
}
}).done(function (data) {
Log("PostCombine" +data)
balanceAPI.QuoteDetails = data;
});
}
function PostCalculation(url, postData) {
if(balanceAPI.Error) {
return;
}
var _data = JSON.stringify(postData);
$.ajax({
method: "POST",
url: balanceAPI.ApiUrl + url,
headers: {
'apikey': balanceAPI.ApiKey,
'Content-Type': 'application/json'
},
contentType: "application/json",
async: false,
data: _data,
error: function () {
alert("An error has occured please check entered data and try again!");
//balanceAPI.QuoteDetails = null; try not resetting just not updating.
return false;
}
}).done(function (data) {
Log("PostCalculation" +data)
//Do we already have a quote?
if(balanceAPI.QuoteDetails == null) {
balanceAPI.QuoteDetails = data;
return true;
}
Log("Combine needed");
currentQuoets = GetCombinedQuote(data.QuoteId);
Log("Quote Combine" +JSON.stringify(currentQuoets));
PostCombine(currentQuoets);
});
}
/* END API Functions */
/* START Object Functions */
function GetCombinedQuote(quoteId) {
var Quote = {QuoteIds:[]};
if(quoteId != null) {
Quote.QuoteIds.push(quoteId);
}
var push = true;
if(typeof balanceAPI.QuoteDetails !== undefined) {
balanceAPI.QuoteDetails?.Quotes?.forEach(function(item) {
Quote.QuoteIds.push(item.QuoteId);
push = false;
});
if(push) {
//We only have one quote, push
Quote.QuoteIds.push(balanceAPI.QuoteDetails.QuoteId);
}
}
return Quote;
}
function GetUpdateObject() {
var QuoteId = balanceAPI.QuoteDetails.QuoteId;
var Personalisation = "";
var CertificateSendEmail = "";
var perObj = $("input[name='clevel-cert-name']");
if (typeof perObj != 'undefined') {
Personalisation = $(perObj).val();
}
var emailObject = $("input[name='clevel-cert-email']");
if (typeof emailObject != 'undefined') {
CertificateSendEmail = $(emailObject).val();
}
var SendCertificate = balanceAPI.SendCertificate;
var Reference = balanceAPI.Referance;
var UrlReferer = window.location.href;
UrlReferer = UrlReferer.replace(/\#.*/, '');
UrlReferer = UrlReferer.replace(/\?.+/g, "$'");
return {
QuoteId,
CertificateSendEmail,
Personalisation,
SendCertificate,
Reference,
UrlReferer,
};
}
//Checks is the broswer is mobile width
function MobileCheck() {
var isMobile = window.matchMedia("only screen and (max-width: 559px)").matches;
if(isMobile) {
return true;
}
}
function ScrollToResolver(elem) {
// Check if elem is not null and is a DOM element
if (!elem || !(elem instanceof Element)) {
return;
}
var jump = parseInt(elem.getBoundingClientRect().top * .2);
document.body.scrollTop += jump;
document.documentElement.scrollTop += jump;
//lastjump detects anchor unreachable, also manual scrolling to cancel animation if scroll > jump
if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
elem.lastjump = Math.abs(jump);
setTimeout(function() {
ScrollToResolver(elem);
}, "100");
} else {
elem.lastjump = null;
}
}
function formatZeroPadding(dateString) {
return dateString < 10 ? '0' + dateString : dateString.toString();
}
function ClearFormForNextCalculation()
{
// Check if the elements exist and then set their values to an empty string
if ($("#clevel-from").length) {
$("#clevel-from").val("");
}
if ($("#clevel-to").length) {
$("#clevel-to").val("");
}
}
/* END Object Functions */
//Flight prams in queryString
var clevelFlightFrom = getParameterByName("clevelfrom");
var clevelFlightTo = getParameterByName("clevelto");
var clevelFlightClass = getParameterByName("clevelclass");
var clevelFlightPassangers = getParameterByName("clevelpass");
var flightHtmlDashSteps = "
";
//Set and changes the dashset settings
function DashStepSettings() {
}
//Sets and shows the correct step
function ShowStep() {
HideStep();
DashStepSettings();
$(balanceAPI.Step).show();
$(".clevel-step-dash>div").removeClass("select");
DashStepSettings();
//dash step name
var dashStep = balanceAPI.Step +"-dash";
$(dashStep).addClass("select");
//Show the correct buttons
$(".clevel-add-another").hide();
$(".clevel-offset").hide();
$(".clevel-calculate").show();
Log("ShowStep()");
Log("Show Step" +dashStep);
//Scroll to new step top.
var srcollElementId = balanceAPI.Step.replace('.', '');
Log("Call scroll with element " +srcollElementId);
var element = document.getElementById(srcollElementId);
ScrollToResolver(element);
}
var balanceAPI = {
ApiKey: "c374b2a8-4adf-4755-a7bc-ee6759211941",
ApiUrl: "https://api.c-level.earth",
Calculator:"Flight",
CalculatorHtmlUrl: "",
CalculationHtml: "",
CalculatorElement: "clevel-calculator",
CartHtml: "",
DeveloperMode: false,
Equivalence:null,
HtmlRoot: "https://www.c-level.earth",
Referance:"",
Error:false,
SandboxMode: false,
SendCertificate:true,
Step:".clevel-step-one",
NavigationHtml: "",
QuoteDetails:null,
Initialize: function () {
Initialize();
}
};
async function SetEquivilance(calHtml) {
var CO2Kg = parseInt(balanceAPI.QuoteDetails.Co2Total_Kg);
Log("CO2kg:" +CO2Kg);
var url = balanceAPI.ApiUrl +"/v1/equivalence/co2/" +CO2Kg
var _data = await GetJSONFromAPI(url, balanceAPI.Equivalence);
Log("EQUDATA" +_data);
balanceAPI.Equivalence = _data
Log("balanceAPI.Equivalence" +JSON.stringify(balanceAPI.Equivalence));
var cal = document.getElementById(balanceAPI.CalculatorElement);
if (cal) {
balanceAPI.Equivalence.forEach(item => {
var name = GetProperty(item, "Name")
if(name == "Black Coffee") {
calHtml = EquivilanceShow(calHtml, item, "ONE")
}
if(name == "Mobile") {
calHtml = EquivilanceShow(calHtml, item, "TWO")
}
if(name == "Allowance") {
calHtml = EquivilanceShow(calHtml, item, "THREE")
}
});
Log("Calculator Replaced HTML:" +calHtml)
}
return calHtml;
}
function EquivilanceShow(calHtml, item, EQUTEXT){
var iconName = "==EQU" +EQUTEXT +"ICON=="
var icon = GetProperty(item, "FontAwesomeIconCss")
var textName = "==EQU" +EQUTEXT +"TEXT=="
var textDescription = GetProperty(item, "Description")
var totalName = "==EQU" +EQUTEXT +"NUMBER=="
var total = GetProperty(item, "Total")
var unitName = "==EQU" +EQUTEXT +"UNIT=="
var unit = GetProperty(item, "Unit")
var totalFixed = 0;
if(total > 0)
{
totalFixed = total.toFixed(0)
}
calHtml = calHtml.toString().replaceAll(iconName,icon);
calHtml = calHtml.toString().replaceAll(textName, textDescription);
calHtml = calHtml.toString().replaceAll(totalName, totalFixed);
calHtml = calHtml.toString().replaceAll(unitName, unit);
Log("Calhtml equivilance replaced");
return calHtml;
}
function SetBloodHound() {
autocomplete = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 20,
sufficient: 20,
remote: {
url: balanceAPI.ApiUrl + '/v1/airport/autocomplete/',
prepare: function (query, settings) {
settings.url = settings.url + query,
settings.headers = {
'apikey': balanceAPI.ApiKey,
};
return settings;
},
filter: function (autocomplete) {
// Map the remote source JSON array to a JavaScript object array
return autocomplete.map(function (item) {
if (item) { // Check if the item is not null
return {
value: item.IataCode + '-' + item.AirportName,
text: item.AirportName
};
}
return null;
}).filter(function (item) { return item !== null; }); // This will remove any null values from the mapped array
}
}
});
autocomplete.initialize();
Log("SetBloodhound - complete")
}
function SetAutoComplete(htmlObject) {
Log("SetAutoComplete on:" +htmlObject.attr("id"))
// Instantiate the Typeahead UI
htmlObject.typeahead(null, {
displayKey: 'value',
limit: 19, // This controls the number of suggestions displayed
source: autocomplete.ttAdapter(),
templates: {
suggestion: Handlebars.compile("{{value}}
"),
footer: Handlebars.compile("Searched for '{{query}}'")
}
});
}
/* START CART FUNCTIONS */
async function BuildCart(){
var cartHtml = "";
var cartTemplateUrl = balanceAPI.HtmlRoot + "/Html/Cart";
var cartSingleLineHtml = await FetchHtml(cartTemplateUrl);
//No quote is Set
if (balanceAPI.QuoteDetails === undefined || balanceAPI.QuoteDetails === null) {
Log("No quotes")
balanceAPI.CartHtml = cartHtml;
} else {
cartHtml = "";
//Add heading to the cart.
cartHtml = 'Items Added:
'
//We have single quote
if(balanceAPI.QuoteDetails.Quotes === undefined || balanceAPI.QuoteDetails.Quotes === null){
cartHtml = cartHtml +CartOrderlineHtml(balanceAPI.QuoteDetails, cartSingleLineHtml);
} else {
//We have mulitple quotes
balanceAPI.QuoteDetails?.Quotes?.forEach(item => {
var result = CartOrderlineHtml(item, cartSingleLineHtml);
cartHtml = cartHtml +result;
});
}
}
balanceAPI.CartHtml = "" + cartHtml +"
";
//Are we replacing the current cart?
var cartElement = document.getElementsByName("clevel-cart-continer");
Log("Element found:" +cartElement)
if(cartElement) {
Log("CartHtml: replaced")
$(".clevel-cart-continer").replaceWith(balanceAPI.CartHtml);
}
//Set the cart functions
CartFunctions();
}
function CartOrderlineHtml(quoteDetails, cartSingleLineHtml) {
var newCartLine = cartSingleLineHtml;
var tonnesCO2 = GetProperty(quoteDetails, "Co2Total_Tonne");
var shortDescription = GetProperty(quoteDetails, "ShortDescription");
var metaDataHtml = CartMetaData(quoteDetails.MetaData);
var quoteId = GetProperty(quoteDetails, "QuoteId");
newCartLine = newCartLine.replaceAll("==QUOTEID==", quoteId);
newCartLine = newCartLine.replaceAll("==CO2TONNES==", tonnesCO2);
newCartLine = newCartLine.replaceAll("==SHORTDISCRIPTION==", shortDescription);
newCartLine = newCartLine.replaceAll("==METADATA==", metaDataHtml);
return newCartLine;
}
function CartMetaData(metaData) {
var str = "";
if (typeof metaData != 'undefined') {
metaData.forEach(item => {
var metaDataString = "==NAME==:==VALUE==";
var metaName = GetProperty(item, "Name");
var metaValue = GetProperty(item, "Value");
metaDataString = metaDataString.replace("==NAME==", metaName);
metaDataString = metaDataString.replace("==VALUE==", metaValue);
str = str + metaDataString;
});
}
return str;
}
function CartFunctions() {
$(".cart-view").click(function() {
Log("cart view toggle");
var showElement = $(this).nextAll(".cart-item");
Log("Element to toggle:" +showElement)
showElement.toggle();
});
$(".cart-delete").click(function() {
var quoteId = $(this).data("quoteid")
Log("Cart-Delete-Click: " +quoteId)
CartDelete(quoteId);
BuildCart();
});
}
function CartDelete(quoteId) {
var mainQuoteId = GetProperty(balanceAPI.QuoteDetails, "QuoteId");
if(mainQuoteId == quoteId) {
balanceAPI.QuoteDetails = null;//There was only one quote just blank it.
Log("Cart-item-cleared-removed:" +quoteId);
ReloadPage();
return;
}
//Do we have lots of quotes find index in array and remove.
balanceAPI.QuoteDetails?.Quotes?.forEach(function(item, index, object) {
var itemQuoyeId = GetProperty(item,"QuoteId")
if (itemQuoyeId === quoteId) {
object.splice(index, 1);
Log("Cart-item-removed:" +quoteId);
}
});
Log("Cart-item-count:" +balanceAPI.QuoteDetails?.Quotes?.length);
//Have we removed all the quotes?
if(balanceAPI.QuoteDetails?.Quotes?.length == 0) {
ReloadPage();
return;
}
//Replace the current calulation back to the replacment text
if(balanceAPI.Step == ".clevel-step-calculation") {
$(".clevel-step-calculation").replaceWith(balanceAPI.CalculationHtml);
currentQuoets = GetCombinedQuote();
Log("Quote Combine" +JSON.stringify(currentQuoets));
PostCombine(currentQuoets);
Calculate();
ShowCalculation();
}
}
async function Initialize() {
//First make sure all scripts are on the page
await AddHeaderScripts();
Log("balanceAPI.SandboxMode" +balanceAPI.SandboxMode);
if(balanceAPI.SandboxMode) {
Log("Model.ApiSandboxRootUrl:https://sandbox-api.c-level.earth");
balanceAPI.ApiUrl = "https://sandbox-api.c-level.earth";
balanceAPI.HtmlRoot = "https://sandbox.c-level.earth";
}
Log("balanceAPI.ApiUrl" +balanceAPI.ApiUrl);
Log("balanceAPI.HtmlRoot" +balanceAPI.HtmlRoot);
var bootstrapCss = ''
appendHtml(document.head, bootstrapCss);
var customCssUrl = ''
appendHtml(document.head, customCssUrl);
if (balanceAPI.Calculator == "Flight") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/flightcalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/flightcalculator"
}
if (balanceAPI.Calculator == "Accommodation") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/accommodationcalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/accommodationcalculator"
}
if (balanceAPI.Calculator == "Business") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/businesscalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/businesscalculator"
}
if (balanceAPI.Calculator == "Carbon") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/carboncalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/carboncalculator"
}
if (balanceAPI.Calculator == "Car") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/carcalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/carcalculator"
}
if(balanceAPI.Calculator == "Tree") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/treecalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/treecalculator"
}
if(balanceAPI.Calculator == "Gas") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/gascalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/gascalculator"
}
if(balanceAPI.Calculator == "Electric") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/electriccalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/electriccalculator"
}
if(balanceAPI.Calculator == "Percapita") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/percapitacalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/percapitacalculator"
}
if(balanceAPI.Calculator == "FilmProduction") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/filmproductioncalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/filmproductioncalculator"
}
if(balanceAPI.Calculator == "FilmLights") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/filmlightscalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/filmlightscalculator"
}
if(balanceAPI.Calculator == "FilmLocation") {
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/filmlocationcalculator"
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/filmlocationcalculator"
}
//Multistep cals
if(balanceAPI.Calculator == "Energy") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/energycalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/energycalculator"
}
if(balanceAPI.Calculator == "Film") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/filmcalculator";
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/filmcalculator";
}
if(balanceAPI.Calculator == "Travel") {
balanceAPI.NavigationHtml = balanceAPI.HtmlRoot + "/htmlnavigation/travelcalculator"
balanceAPI.CalculatorHtmlUrl = balanceAPI.HtmlRoot + "/html/travelcalculator"
}
BuildCart();
BuildHtml();
CartFunctions();
};
function Calculate() {
Log("Calculate() called");
balanceAPI.Error = false;
//Set the client referance if there is one for the quote
if($('#clevel-clientref').length) {
var _ref = $("#clevel-clientref").val();
if(_ref) {
balanceAPI.Referance = _ref;
Log("Referance set:" +balanceAPI.Referance);
}
}
//Call the correct Calculate function
if(balanceAPI.Calculator == "Flight" || balanceAPI.Step == ".clevel-step-flight") {
FlightCalculate();
}
if(balanceAPI.Calculator == "Accommodation" || balanceAPI.Step == ".clevel-step-accommodation") {
AccommodationCalculate();
}
if(balanceAPI.Calculator == "Business") {
BusinessCalculate();
}
if(balanceAPI.Calculator == "Carbon") {
CarbonCalculate();
}
if(balanceAPI.Calculator == "Car" || balanceAPI.Step == ".clevel-step-car") {
CarCalculate();
}
if(balanceAPI.Calculator == "Gas" || balanceAPI.Step == ".clevel-step-gas") {
GasCalculate();
}
if(balanceAPI.Calculator == "Electric" || balanceAPI.Step == ".clevel-step-electric") {
ElectricCalculate();
}
if(balanceAPI.Calculator == "FilmProduction" || balanceAPI.Step == ".clevel-step-filmproduction") {
FilmProductionCalculate();
}
if(balanceAPI.Calculator == "FilmLights" || balanceAPI.Step == ".clevel-step-filmlights") {
FilmLightsCalculate();
}
if(balanceAPI.Calculator == "FilmLocation" || balanceAPI.Step == ".clevel-step-filmlocation") {
FilmLocationCalculate();
}
if(balanceAPI.Calculator == "Tree") {
TreeCalculate();
}
if(balanceAPI.Calculator == "Percapita") {
PerCapitaCalculate();
}
//MultiStep start points
if(balanceAPI.Calculator == "Energy") {
if(balanceAPI.Step == ".clevel-step-one") {
GasCalculate();
}
}
if(balanceAPI.Calculator == "Business") {
if(balanceAPI.Step == ".clevel-step-one") {
BusinessCalculate();
}
}
if(balanceAPI.Calculator == "Film") {
if(balanceAPI.Step == ".clevel-step-one") {
FilmLocationCalculate();
}
}
if(balanceAPI.Calculator == "Travel") {
if(balanceAPI.Step == ".clevel-step-one") {
FlightCalculate();
}
}
};
async function SetNavigation() {
//Remove the selected tag from nav
$("a").removeClass("clevel-nav-selected");
Log("SetNavigation()");
var navSelector = balanceAPI.Step.replace('-dash','');
navSelector = navSelector.replace('step','next');
Log("Nav selector:" +navSelector);
if($(navSelector)) {
$(navSelector).addClass("clevel-nav-selected");
}
//Next Steps
$(".clevel-next-calculation").click(function() {
Log("clevel-net-calculation click()")
//Only show cal if there is a QuoteDetails
if(balanceAPI.QuoteDetails) {
ShowCalculation();
} else {
if(!balanceAPI.Error) {
alert("You cant see the results until you have made an offset");
}
balanceAPI.Error = true;
}
})
$(".clevel-next-flight").click(function() {
balanceAPI.Step = ".clevel-step-flight"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-filmlights").click(function() {
balanceAPI.Step = ".clevel-step-filmlights"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-filmlocation").click(function() {
balanceAPI.Step = ".clevel-step-filmlocation"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-filmproduction").click(function() {
balanceAPI.Step = ".clevel-step-filmproduction"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-car").click(function() {
balanceAPI.Step = ".clevel-step-car"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-accommodation").click(function() {
balanceAPI.Step = ".clevel-step-accommodation"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-gas").click(function() {
balanceAPI.Step = ".clevel-step-gas"
ShowStep();
SetNavigation();
Settings();
})
$(".clevel-next-electric").click(function() {
balanceAPI.Step = ".clevel-step-electric"
ShowStep();
SetNavigation();
Settings();
})
}
async function ButtonEvents() {
Log("ButtonEvents() called")
//Add item without moving.
$(".clevel-add").click(function() {
Log("clevel-add click()")
Calculate();
if(!balanceAPI.Error) {
BuildCart();
ShowAddAnother()
}
var srcollElementId = balanceAPI.Step.replace('.', '');
if(element == null || element.length === 0) {
//Cant find the correct element scroll to the top
srcollElementId = "clevel-calculator";
}
var element = document.getElementById(srcollElementId);
Log("Call scroll with element " +srcollElementId);
ScrollToResolver(element);
})
$('.clevel-add-another-button').click(function() {
$(".clevel-calculate").show();
$(".clevel-add-another").hide();
var srcollElementId = balanceAPI.Step.replace('.', '');
Log("Call scroll with element " +srcollElementId);
ScrollToResolver(document.getElementById(srcollElementId));
// Check if the elements exist and then set their values to an empty string
ClearFormForNextCalculation();
})
$("#clevel-show-price").click(function() {
Log("clevel-show-price click()")
ShowCalculation();
})
$("#clevel-calculate-price").click(function() {
Log("clevel-calculate-price click()")
Calculate();
ShowCalculation();
//Wait
setTimeout(function (){}, 500);
//Scroll to element
ScrollToResolver(document.getElementById("clevel-step-calculation"));
})
}
async function BuildProjectHtml(calHtml) {
var projectsHtml = await FetchHtml(balanceAPI.HtmlRoot + "/html/projects/" +balanceAPI.ApiKey);
calHtml = calHtml.toString().replaceAll("==PROJECTS==", projectsHtml);
return calHtml
}
async function BuildNavigationHtml(calculatorHtml) {
//Add the navigation
var navigationResultsHtml = "";
if(balanceAPI.NavigationHtml.length) {
var navigationResultsHtml = await FetchHtml(balanceAPI.NavigationHtml);
}
calculatorHtml = calculatorHtml.toString().replaceAll("==NAVIGATION==", navigationResultsHtml);
return calculatorHtml;
}
async function Settings() {
//Set the settings
if(balanceAPI.Calculator == "Flight") {
await FlightSettings()
}
//Apply settings
if(balanceAPI.Calculator == "Business") {
await BusinessSettings();
}
//Apply settings
if(balanceAPI.Calculator == "Carbon") {
await CarbonSettings();
}
if(balanceAPI.Calculator == "Car") {
await CarSettings();
}
if(balanceAPI.Calculator == "Gas") {
await GasSettings();
}
if(balanceAPI.Calculator == "Energy") {
await GasSettings();
}
if(balanceAPI.Calculator == "Film") {
await CarSettings();
await FlightSettings()
}
if(balanceAPI.Calculator == "Travel") {
await FlightSettings();
await CarSettings();
}
}
async function BuildHtml() {
var cal = document.getElementById(balanceAPI.CalculatorElement);
if (cal) {
//Build Caclulation results HTML template
var calulatorResultsHtml = await FetchHtml(balanceAPI.HtmlRoot + "/html/calculation");
calulatorResultsHtml = calulatorResultsHtml.toString().replaceAll('==CART==', balanceAPI.CartHtml);
balanceAPI.CalculationHtml = calulatorResultsHtml;
//Build full calculator HTML
var calculatorHtml = await FetchHtml(balanceAPI.CalculatorHtmlUrl);
calculatorHtml = calculatorHtml.toString().replaceAll("==CALCULATION==", calulatorResultsHtml);
calculatorHtml = calculatorHtml.toString().replaceAll('==CART==', balanceAPI.CartHtml);
calculatorHtml = await BuildProjectHtml(calculatorHtml);
calculatorHtml = await BuildNavigationHtml(calculatorHtml);
//Set the Calculator inner HTML
cal.innerHTML = calculatorHtml;
if (typeof c !== "undefined" && c != null) {
alert("Your transaction has been canceled")
window.location.replace(location.pathname);
}
if (typeof quoteParmId !== "undefined" && quoteParmId != null) {
Log("Quote id found");
OrderCompleted();
} else {
Settings();
//Set the default dsah steps
DashStepSettings();
SetNavigation();
ButtonEvents();
}
} else {
Log("element is missing from the page");
}
}
function InitFunctions() {
Log("InitFunctions");
$("#clevel-purchase").click(function() {
Log("Purchase click")
Purchase();
});
$("#clevel-balance-now").click(function() {
var element = document.getElementById("clevel-purchase");
Log("Scoll to clevel-purchase")
ScrollToResolver(element);
});
$('#clevel-balance-more').click(function() {
Log("Reload Page")
window.location.replace(location.pathname);
})
}
function Purchase() {
Log("Complete click");
var updateOffset = GetUpdateObject();
var url = "/v1/quote/update";
PostUpdate(url, updateOffset);
var url = balanceAPI.UpdateResponse.CheckOutUrl;
Log("CheckOutUrl" +url)
if (url == "invoice") {
var url = window.location.href.split(/[?#]/)[0];
url = url + "?oid=" + balanceAPI.QuoteDetails.QuoteId;
Log("redirect url:" + url);
window.location.replace(url);
}
Log("redirect url:" + url);
window.location.replace(url);
}
async function OrderCompleted() {
Log("Order complete");
var url = balanceAPI.ApiUrl + "/v1/quote/purchase/" +quoteParmId
var result = "";
result = await GetJSONFromAPI(url, result);
balanceAPI.QuoteDetails = result;
ShowComplete();
}
function ShowAddAnother() {
//Dont hid the calculator if we have an error.
if(balanceAPI.Error) {
balanceAPI.Error = false;//Reset error as it has been shown.
return;
}
$(".clevel-calculate").hide();
$(".clevel-offset").show();
$(".clevel-add-another").show();
if(balanceAPI.Step == ".clevel-step-calculation") {
return;
}
}
async function ShowCalculation() {
Log("ShowCalculation()");
balanceAPI.Error = false;
//Check we have item in
if(balanceAPI?.QuoteDetails == null) {
return;
}
balanceAPI.Step = ".clevel-step-calculation"
HideStep();
Log("BuildCart()");
await BuildCart();
await BuildCompleteCalculationHtml();
ShowStep();
ButtonEvents();
CartFunctions();
SetNavigation();
Settings();
//If we have a referance add it to the certificate name field
var referance = balanceAPI.Referance;
if(referance.length) {
document.getElementById('clevel-cert-name').value = referance;
}
}
async function ShowComplete() {
Log("ShowComplete()");
balanceAPI.Step = ".clevel-step-complete";
HideStep();
Log("BuildCart()");
await BuildCart();
await BuildCompleteCalculationHtml();
CartFunctions();
ShowStep();
$('.clevel-cart').hide();
$('.clevel-cart-complete').show();
}
async function BuildCompleteCalculationHtml() {
//Replace the calculation with a new blank one!
var calulatorResultsHtml = await FetchHtml(balanceAPI.HtmlRoot + "/html/calculation");
var newBlankCalculation = calulatorResultsHtml;
//Are we replacing the current cart?
var cartElement = document.getElementById("clevel-calculation-container");
Log("Calculator Element found:" +cartElement)
if(cartElement) {
$("#clevel-calculation-container").replaceWith(calulatorResultsHtml);
Log("Calculator Html: replaced")
}
//Replace all content
var cal = document.getElementById(balanceAPI.CalculatorElement);
var calHtml = "";
if (cal) {
var totalPrice = balanceAPI?.QuoteDetails?.TotalPrice;
if(balanceAPI?.QuoteDetails?.TotalPrice > 1)
{
totalPrice = totalPrice.toFixed(2)
}
calHtml = cal.innerHTML;
if(typeof balanceAPI.QuoteDetails.TotalTrees != "undefined" && balanceAPI.QuoteDetails.TotalTrees != 0) {
calHtml = calHtml.toString().replaceAll("==OFFSETH1==", "YOUR IMPACT");
calHtml = calHtml.toString().replaceAll("==OFFSETCTA==", "PLANT TREES");
calHtml = calHtml.toString().replaceAll("==OFFSETFINALCATH2==", "BALANCE MY IMPACT");
calHtml = calHtml.toString().replaceAll("==OFFSETTOTAL==", balanceAPI.QuoteDetails.TotalTrees);
calHtml = calHtml.toString().replaceAll("==OFFSETTOTALTEXT==", "TREE(S) PLANTED");
} else {
calHtml = calHtml.toString().replaceAll("==OFFSETH1==", "YOUR CARBON FOOTPRINT")
calHtml = calHtml.toString().replaceAll("==OFFSETCTA==", "BALANCE MY CARBON");
calHtml = calHtml.toString().replaceAll("==OFFSETFINALCATH2==", "BALANCE MY CARBON");
calHtml = calHtml.toString().replaceAll("==OFFSETTOTAL==", balanceAPI.QuoteDetails.Co2Total_Tonne);
calHtml = calHtml.toString().replaceAll("==OFFSETTOTALTEXT==", "TONNES CO2");
}
calHtml = calHtml.toString().replaceAll("==OFFSETTOTALCOST==", totalPrice);
var calHtmlWithEq = await SetEquivilance(calHtml);
Log("Calculator Replaced HTML");
var calWithProjects = await BuildProjectHtml(calHtmlWithEq);
var calWithNav = await BuildNavigationHtml(calWithProjects);
calWithNav = calWithNav.toString().replaceAll('==CART==', balanceAPI.CartHtml);
cal.innerHTML = calWithNav;
InitFunctions();
}
}
function CheckQuotePart(quoteType) {
if(balanceAPI?.QuoteDetails?.Quotes?.includes(quoteType)) {
return true;
}
return false;
}
function RequiredText(htmlElement) {
if(!balanceAPI.Error) {
htmlElement.removeClass("error");
}
var result = htmlElement.val();
if(result == null) {
balanceAPI.Error = true;
}
if (result.length === 0) {
balanceAPI.Error = true;
}
if(balanceAPI.Error) {
htmlElement.addClass("error");
htmlElement.focus();
return true;
}
return false;
}
function RequiredNumber(htmlElement) {
Log("RequiredNumber" +JSON.stringify(htmlElement));
if(!balanceAPI.Error) {
htmlElement.removeClass("error");
}
if(!RequiredText(htmlElement)) {
var result = htmlElement.val();
if ($.isNumeric(result)) {
return false;
}
balanceAPI.Error = true;
htmlElement.focus();
htmlElement.addClass("error");
return true;
}
return false;
}
/* START FilmLocations Cal */
function FilmLocationCalculate() {
var cal = {
Description: "Film Location Offset",
CountryCode: "GB",
CurrencyCode: "GBP",
Reference: balanceAPI.Referance
}
Log("Cal Referance Set:" +cal.Reference);
var _countryCode = $("#clevel-filmlocation-countrycode").val();
var _externalCrew = $("#clevel-filmlocation-externalcrew").val();
var _shootlocation = $("#clevel-filmlocation-location").val();
var _shootDuration = $("#clevel-filmlocation-duration").val();
var _localCrew = $("#clevel-filmlocation-localcrew").val();
cal.LocalCrew = Number(_localCrew);
cal.ExternalCrew = Number(_externalCrew);
cal.DurationDays = Number(_shootDuration);
cal.CountryCode = _countryCode;
cal.ShootCityLocation = _shootlocation;
//Validation
RequiredNumber($("#clevel-filmlocation-externalcrew"));
RequiredNumber($("#clevel-filmlocation-localcrew"));
RequiredNumber($("#clevel-filmlocation-duration"));
Log("filmlocation calculate complete");
PostCalculation("/v1/calculate/filmlocation", cal);
}
/* END FilmLocations Cal */
/* START FilmLights Cal */
function FilmLightsCalculate() {
var cal = {
CountryCode: "GB",
CurrencyCode: "GBP",
LightNumber: 1,
Reference: balanceAPI.Reference,
LightType: "Key",
DurationDays: 2
}
var _countryCode = $("#clevel-filmlights-countrycode").val();
var _lightingType = $("#clevel-filmlights-type").val();
var _shootlocation = $("#clevel-filmlights-shootlocation").val();
var _shootDuration = $("#clevel-filmlights-shootDuration").val();
var _totalLights = $("#clevel-filmlights-lights").val();
cal.LightNumber = Number(_totalLights);
cal.DurationDays = Number(_shootDuration);
Log("filmlights duration:" +cal.DurationDays);
cal.LightType = _lightingType;
Log("filmlights duration:" +cal.DurationDays);
cal.CountryCode = _countryCode;
cal.ShootLocation = _shootlocation;
//Validation
RequiredNumber($("#clevel-filmlights-shootDuration"));
RequiredNumber($("#clevel-filmlights-lights"));
Log("filmlights Calculate: complete");
PostCalculation("/v1/calculate/filmlights", cal);
}
/* END FilmLights Cal */
/* START FilmProduction Cal */
function FilmProductionCalculate() {
var cal = {
Description: "Film Production Offset",
CountryCode: "GB",
CurrencyCode: "GBP",
Reference: balanceAPI.Reference,
ProductionType: "Edit"
}
var _countryCode = $("#clevel-filmproduction-countrycode").val();
var _productionType = $("#clevel-accommodation-type").val();
var _officeLocation = $("#clevel-filmproduction-officelocation").val();
var _durationDays = $("#clevel-filmproduction-duration").val();
var _totalPeople = $("#clevel-filmproduction-staff").val();
cal.TotalPeople = Number(_totalPeople);
cal.DurationDays = Number(_durationDays);
cal.ProductionType = _productionType;
cal.CountryCode = _countryCode;
cal.OfficeLocation = _officeLocation;
//Validation
RequiredNumber($("#clevel-filmproduction-duration"));
RequiredNumber($("#clevel-filmproduction-staff"));
Log("filmproduction Calculate: complete");
PostCalculation("/v1/calculate/filmproduction", cal);
}
/* END FilmProduction */
/* START Electricity Cal */
function ElectricCalculate() {
var cal = {
Description: "Electricity Offset",
CountryCode: "GB",
Amount: 1000,
Reference: balanceAPI.Reference,
CurrencyCode: "GBP"
}
var _ammount = $("#clevel-electric-amount").val();
var _countryCode = $("#clevel-electric-countrycode").val();
cal.CountryCode = _countryCode;
cal.Amount = Number(_ammount);
//Check validation
RequiredNumber($("#clevel-electric-amount"));
Log("Electricity Calculate: complete");
PostCalculation("/v1/calculate/electricity", cal);
}
/* END Electric */
/* START Gas Cal */
function GasCalculate() {
var cal = {
Description: "Gas Offset",
CountryCode: "UK",
Unit: "kwh",
Amount: 1000,
Reference: balanceAPI.Reference,
CurrencyCode: "GBP"
}
var _amount = $("#clevel-gas-amount").val();
var _unitChecked = $("#btn-gas-m3").attr("checked");
if (_unitChecked === "checked") {
cal.Unit = "m3";
}
cal.Amount = Number(_amount);
Log("Gas Calculate: complete");
//Check validation
RequiredNumber($("#clevel-gas-amount"));
PostCalculation("/v1/calculate/gas", cal);
}
function GasSettings() {
$(".clevel-gas-unit").click(function () {
$(".clevel-gas-unit").removeClass('bg-colour-one');
$(".clevel-gas-unit").removeAttr("checked");
$(this).addClass('bg-colour-one');
$(this).attr('checked', 'checked');
})
}
/* END Gas */
/* START PerCapita Cal */
function PerCapitaCalculate() {
var cal ={
CountryCode: "GB",
TotalPeople: 1,
Reference: balanceAPI.Reference,
CurrencyCode: "GBP"
}
var _people = $("#clevel-percapita-people").val();
cal.TotalPeople = Number(_people);
var _countryCode = $("#clevel-percapita-country").val();
cal.CountryCode = _countryCode;
Log("PerCapita Calculate: complete");
//Check validation
RequiredNumber($("#clevel-percapita-people"));
PostCalculation("/v1/calculate/percapita", cal);
}
/* END PerCapita Cal */
/* START Tree Cal */
function TreeCalculate() {
var cal = {
Trees: 1,
Reference: "",
CurrencyCode: "GBP",
Reference: balanceAPI.Reference
}
var _treesToPlant = $("#clevel-tree-amount").val();
cal.Trees = Number(_treesToPlant);
//Check validation
RequiredNumber($("#clevel-tree-amount"));
//only post if no error
Log("Tree Calculate: complete");
PostCalculation("/v1/calculate/planttrees", cal);
}
/* END Tree Cal */
/* START Business Cal */
function BusinessCalculate() {
Log("Business Calculate: start");
var cal = {
FromDate:"2023/01/01",
ToDate:"2023/01/01",
CountryCode:"UK",
OrganisationSize:"",
HomeEmployee:1,
OfficeEmployee:1,
OfficeSizem2:200,
HomeWorkPercentage:50,
Reference:""
}
//Populate
var _fromMonth = $("#clevel-business-frommonth").val();
var _fromYear = $("#clevel-business-fromyear").val();
cal.ToDate = _fromYear + '-' + formatZeroPadding(_fromMonth) + '-01';
var _toMonth = $("#clevel-business-tomonth").val();
var _toYear = $("#clevel-business-toyear").val();
cal.ToDate = _toYear + '-' + formatZeroPadding(_toMonth) + '-01';
var _organisation = $("#clevel-business-org").val();
cal.OrganisationSize = _organisation;
//Check validation
Log("#clevel-clientref");
RequiredText($("#clevel-clientref"));
Log("#clevel-business-peoplehome");
RequiredNumber($("#clevel-business-peoplehome"));
Log("#clevel-business-homepercent");
RequiredNumber($("#clevel-business-homepercent"));
Log("#clevel-business-peopleoffice");
RequiredNumber($("#clevel-business-peopleoffice"));
Log("#clevel-business-officesizem2");
RequiredNumber($("#clevel-business-officesizem2"));
var _clientRef = $("#clevel-clientref").val();
cal.Reference = _clientRef;
var _peopleHome = $("#clevel-business-peoplehome").val();
cal.HomeEmployee = Number(_peopleHome);
var _peopleOffice = $("#clevel-business-peopleoffice").val();
cal.OfficeEmployee = Number(_peopleOffice);
var _officeSize_m2 = $("#clevel-business-officesizem2").val();
cal.OfficeSizem2 = Number(_officeSize_m2);
var _homePercent = $("#clevel-business-homepercent").val();
cal.HomeWorkPercentage = Number(_homePercent);
Log("Business Calculate: complete");
PostCalculation("/v1/calculate/business", cal);
}
function BusinessSettings() {
}
/* END Carbon */
/* START Car Cal */
function CarCalculate() {
var cal = {
Size: "Small",
Type: "Petrol",
Distance: 1,
Reference: balanceAPI.Reference,
DistanceMeasurement: "Km"
}
//Populate
var _carSize = $("#clevel-car-size").val();
var _carType = $("#clevel-car-type").val();
cal.Size = _carSize;
cal.Type = _carType;
var _unitChecked = $("#btn-miles").attr("checked");
if (_unitChecked === "checked") {
cal.DistanceMeasurement = "Miles";
}
var _Distance = $("#clevel-car-distance").val();
cal.Distance = Number(_Distance);
//Check validation
RequiredNumber($("#clevel-car-distance"));
Log("Car Calculate: complete");
PostCalculation("/v1/calculate/car", cal);
}
function CarSettings() {
$(".clevel-car-unit").click(function () {
$(".clevel-car-unit").removeClass('bg-colour-one');
$(".clevel-car-unit").removeAttr("checked");
$(this).addClass('bg-colour-one');
$(this).attr('checked', 'checked');
})
}
/* END Carbon */
/* START Carbon Cal */
function CarbonCalculate() {
var cal = {
Description: "Carbon offset",
Unit: "Kg",
Co2Amount: 1,
Reference: balanceAPI.Reference,
CurrencyCode: "GBP"
}
var _co2Ammount = $("#clevel-carbon-amount").val();
var _unitChecked = $("#btn-tonne").attr("checked");
if (_unitChecked === "checked") {
cal.Unit = "Tonne";
}
cal.Co2Amount = Number(_co2Ammount);
//Check validation
RequiredNumber($("#clevel-carbon-amount"));
Log("Carbon Calculate: complete");
PostCalculation("/v1/calculate/carbon", cal);
}
function CarbonSettings() {
$(".clevel-carbon-unit").click(function () {
$(".clevel-carbon-unit").removeClass('bg-colour-one');
$(".clevel-carbon-unit").removeAttr("checked");
$(this).addClass('bg-colour-one');
$(this).attr('checked', 'checked');
})
}
/* END Carbon */
//API Calls
/* START Accommodation */
function AccommodationCalculate() {
var cal = {
Guests: 1,
Nights: 1,
AccomodationType: "Hotel",
CountryCode:"UK",
Reference: balanceAPI.Reference,
CurrencyCode: "GBP"
}
//Populate
var _guests = $("#clevel-accommodation-guests").val();
var _countryCode = $("#clevel-accommodation-countrycode").val();
var _nights = $("#clevel-accommodation-nights").val();
var _accomodationType = $("#clevel-accommodation-type").val();
cal.Guests = Number(_guests)
cal.Nights = Number(_nights)
cal.CountryCode = _countryCode
cal.AccomodationType = _accomodationType
Log("AccommodationCalculate: complete");
//Check validation
RequiredNumber($("#clevel-accommodation-nights"));
RequiredNumber($("#clevel-accommodation-guests"));
PostCalculation("/v1/calculate/accommodation", cal);
}
/* END Accommodation */
/* START Flight Functions */
async function FlightSettings() {
if (balanceAPI.Calculator == "Flight" || balanceAPI.Calculator == "Travel" || balanceAPI.Calculator == "Film") {
SetBloodHound();
SetAutoComplete($('#clevel-from'));
SetAutoComplete($('#clevel-to'));
$(".clevel-flight-trip").click(function () {
$(".clevel-flight-trip").removeClass('bg-colour-two');
$(".clevel-flight-trip").removeAttr("checked");
$(this).addClass('bg-colour-two');
$(this).attr('checked', 'checked');
})
}
$("#clevel-from").focusout(function () {
var result = CheckIataCode($("#clevel-from"));
Log("clevel-to check:" +result);
});
$("#clevel-to").focusout(function () {
var result = CheckIataCode($("#clevel-to"));
Log("clevel-to check:" +result);
});
}
function FlightCalculate() {
var cal = {
IataCodes: [],
IsReturn: false,
Passengers: 1,
Class: "Economy",
Reference: balanceAPI.Reference,
CurrencyCode: "GBP"
}
//Populate
var _fromAirport = $("#clevel-from").val();
var _passangerNumber = $("#clevel-passengers").val();
var _toAirport = $("#clevel-to").val();
var _roundTrip = $("#btn-return").attr("checked");
var _flightClass = $("#clevel-flightclass").val();
var _fromIataCode = _fromAirport.substring(0, 3);
var _toIataCode = _toAirport.substring(0, 3);
if (!CheckIataCode($("#clevel-from"))) {
if(balanceAPI.QuoteDetails == null) {
alert("Error on FROM airport, Please use three letter airport code or autocomplete.");
$("#clevel-from").focus();
balanceAPI.Error = true;
return;
}
}
if (!CheckIataCode($("#clevel-to"))) {
if(balanceAPI.QuoteDetails == null) {
alert("Error on TO airport, Please use three letter airport code or autocomplete.");
$("#clevel-to").focus()
balanceAPI.Error = true;
return;
}
}
if (isNaN(_passangerNumber)) {
alert("Passanger number is not a number");
return;
}
if (_roundTrip === "checked") {
cal.IsReturn = true;
}
cal.IataCodes = [_fromIataCode, _toIataCode]
cal.Passengers = _passangerNumber;
cal.Class = _flightClass;
Log("FlightCalculate: complete");
Log("From IATSA Code:" +_fromIataCode)
PostCalculation("/v1/calculate/flight", cal);
//Clear the form
$("#clevel-from").val(null);
$("#clevel-passengers").val(1);
$("#clevel-to").val(null);
}
function CheckIataCode(htmlElement) {
htmlElement.removeClass("error");
var airport = htmlElement.val();
if ((airport.indexOf("-") === -1 && airport.indexOf("-") !== 4) && (airport.length !== 3)) {
var check = true;
//Check if IATA codes passed in query string.
if (typeof clevelFlightFrom !== "undefined" && clevelFlightFrom !== null) {
check = false;
}
if (typeof clevelFlightTo !== "undefined" && clevelFlightTo !== null) {
check = false;
}
if (check) {
htmlElement.addClass("error");
return false;
}
}
var iataCode = airport.substring(0, 3);
if (typeof (iataCode) !== 'undefined' || iataCode !== null || iataCode !== "") {
var url = balanceAPI.ApiUrl + "/v1/airport/details/" + iataCode
var result = GetJQueryAPICall(url);
Log("IATACode:" +JSON.stringify(result));
if(result == null) {
airportData = null;
htmlElement.addClass("error");
} else {
airportData = result;
htmlElement.addClass("success");
}
}
return true;
}
/* END Flight Functions */