// Load localization from ejs
var iphy_locTimeString = "";
var iphy_protection_plan_skin_risk = "";
var iphy_protection_plan_skin_risk_2 = "";
// Here are a few tips and facts to prepare you for your day and keep your skin healthy
var iphySkinRiskCopy = "";
var iphy_dateArray = [];
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var iphyProtectionPlanSubHeader = "";
var iphySkinRiskCopy = "";
var iphy_weather_dict= {};
var temperatureArray = [];
var pollutionArray = [];
var humidityArray = [];
var chosenLanguage = "";
var iphy_protection_temp_copy = "";
var iphyChatCopy = "";
var sliderMovements = {
forward: true,
backward: true
}
var skinToneType = 'fair';
var uvIndexStr;
var slideCounter = 0;
var breezometerResp;
var latLngPayload = {
latitude: null,
longitude: null,
};
var locationInfo;
var latLng;
let prodDataByCountry;
var skinToneDict = {
'11': {
'0.1': '12',
'0.2': '12',
'0.3': '15',
'0.4': '15',
'0.5': '15',
'0.6': '21',
'0.7': '21',
'0.8': '21',
'0.9': '21',
'1.0': '27',
},
'8': {
'0.1': '15',
'0.2': '15',
'0.3': '19',
'0.4': '19',
'0.5': '19',
'0.6': '19',
'0.7': '26',
'0.8': '26',
'0.9': '26',
'1.0': '33',
},
'6': {
'0.1': '22',
'0.2': '22',
'0.3': '28',
'0.4': '28',
'0.5': '28',
'0.6': '39',
'0.7': '39',
'0.8': '39',
'0.9': '39',
'1.0': '50',
},
'3': {
'0.1': '27',
'0.2': '27',
'0.3': '33',
'0.4': '33',
'0.5': '33',
'0.6': '47',
'0.7': '47',
'0.8': '47',
'0.9': '47',
'1.0': '60',
},
'1': {
'0.1': '60+',
'0.2': '60+',
'0.3': '60+',
'0.4': '60+',
'0.5': '60+',
'0.6': '60+',
'0.7': '60+',
'0.8': '60+',
'0.9': '60+',
'1.0': '60+',
},
}
var iphySelectedSkinTone = {
r: 189,
g: 142,
b: 104
};
var iphySkinToneRelMark = 0.5;
// var skinToneDict = {
// '11': {
// 'very fair': '12',
// 'fair': '15',
// 'medium': '15',
// 'olive': '21',
// 'brown': '21',
// 'dark brown': '27',
// },
// '10': {
// 'very fair': '15',
// 'fair': '19',
// 'medium': '19',
// 'olive': '26',
// 'brown': '26',
// 'dark brown': '33',
// },
// '9': {
// 'very fair': '15',
// 'fair': '19',
// 'medium': '19',
// 'olive': '26',
// 'brown': '26',
// 'dark brown': '33',
// },
// '8': {
// 'very fair': '15',
// 'fair': '19',
// 'medium': '19',
// 'olive': '26',
// 'brown': '26',
// 'dark brown': '33',
// },
// '7': {
// 'very fair': '22',
// 'fair': '28',
// 'medium': '28',
// 'olive': '39',
// 'brown': '39',
// 'dark brown': '50',
// },
// '6': {
// 'very fair': '22',
// 'fair': '28',
// 'medium': '28',
// 'olive': '39',
// 'brown': '39',
// 'dark brown': '50',
// },
// '5': {
// 'very fair': '27',
// 'fair': '33',
// 'medium': '33',
// 'olive': '47',
// 'brown': '47',
// 'dark brown': '60',
// },
// '4': {
// 'very fair': '27',
// 'fair': '33',
// 'medium': '33',
// 'olive': '47',
// 'brown': '47',
// 'dark brown': '60',
// },
// '3': {
// 'very fair': '27',
// 'fair': '33',
// 'medium': '33',
// 'olive': '47',
// 'brown': '47',
// 'dark brown': '60',
// },
// '2': {
// 'very fair': '60+',
// 'fair': '60+',
// 'medium': '60+',
// 'olive': '60+',
// 'brown': '60+',
// 'dark brown': '60+',
// },
// '1': {
// 'very fair': '60+',
// 'fair': '60+',
// 'medium': '60+',
// 'olive': '60+',
// 'brown': '60+',
// 'dark brown': '60+',
// },
// }
var productLinkJson = {
US: {
iphy: "https://www.dermalogica.com/dynamic-skin-recovery-spf50/60,default,pd.html",
dsr: "https://www.dermalogica.com/dynamic-skin-recovery-spf50/60,default,pd.html"
}
}
var iphy_protection_outdoors_copy_1 = "You can spend";
var iphy_protection_outdoors_copy_2 = "minutes";
var iphy_protection_outdoors_copy_3 ="outside before burning. This is based on your skin tone and the UV index in your area.";
var is = "is";
let iphyUserLanguageCode;
function getAvailableLanguages(path = "/availableLanguages"){
return new Promise((resolve,reject)=>{
function requestFrontendForAvailLang(callback){
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://spf-widget-production.herokuapp.com" + path );
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function(){
if(this.readyState == 4){
try{
callback(JSON.parse(this.responseText));
}catch(err){
//console.log("could not parse json response - ",err);
callback(this.responseText);
}
}
}
xhr.send();
}
let intervalCounter = 0;
let foundLanguageCodes = false;
let getLangInterval = setInterval(()=>{
if (intervalCounter < 3){
requestFrontendForAvailLang((res)=>{
logOnLocalHostFrontEnd("response from available languages: ", res)
if (res.status == "success" && !foundLanguageCodes){
clearInterval(getLangInterval);
foundLanguageCodes = true;
resolve(res.language_codes);
}
if (res.status != "success" && intervalCounter > 2 && !foundLanguageCodes){
resolve(["en"]);
}
})
}else{
clearInterval(getLangInterval);
}
intervalCounter++;
},200);
})
}
function getTextForLanguage(callback){
let languageCode;
if (window.iphy_forcedLanguageCode != ""){
languageCode = window.iphy_forcedLanguageCode;
}else{
languageCode = iphyReadCookie("iphy_languageCode");
languageCode = languageCode == "" ? navigator.language : languageCode;
if (languageCode.substring(0,2) == "nn" || languageCode.substring(0,2) == "no"){
languageCode = languageCode.replace("no","nb").replace("nn","nb");
}
if (languageCode.substring(0,2) == "zh"){
if (languageCode.toLowerCase() == "zh-hant" || languageCode.toLowerCase() == "zh_hant" || languageCode.toLowerCase() == "zh-tw" || languageCode.toLowerCase() == "zh_tw" || languageCode.toLowerCase() == "zh-hk" || languageCode.toLowerCase() == "zh_hk"){
languageCode = "zh-hant";
}else{
languageCode = "zh-hans";
}
}
}
let langPath;
/*
if ("https://imb-backend.herokuapp.com" == "https://imb-staging.herokuapp.com"){
reqPath = "/availableLanguagesStaging";
}else{
reqPath = "/availableLanguages";
}
*/
getAvailableLanguages("/availableLanguages")
.then((res)=>{
getLanguageFileFromAvailable(languageCode, res, (res)=>{
callback(res);
})
})
.catch((err)=>{
//console.log("error in getting languagecode list - using English - ",err);
languageCode = "en";
})
}
function getLanguageFileFromAvailable(langCode, langCodeList, callback){
let languageCode = langCode;
// languageCode = 'pl';
stylingPL(languageCode);
logOnLocalHostFrontEnd("looking for language Code: ", languageCode);
if (!langCodeList.includes(languageCode)){
languageCode = languageCode.split("-")[0];
logOnLocalHostFrontEnd("language Code not found, new language code to look up: ", languageCode);
if (!langCodeList.includes(languageCode)){
languageCode = "en";
}
}
logOnLocalHostFrontEnd("language Code used: ", languageCode);
iphyUsedLanguageCode = languageCode;
let languageFile = languageCode+".json";
//languageFile = "xx.json";
//getLanguageFile("xx.json", (defaultObj)=>{
let tillCounter = 1;
function getAtLeastEnglishFile(){
getLanguageFile("en-US.json", (defaultObj)=>{
if (defaultObj.status == "200"){
if (languageFile == "en.json"){
callback(JSON.parse(defaultObj.data));
}else{
render_jsonTextObject(JSON.parse(defaultObj.data));
getLanguageFile(languageFile, (responseObj)=>{
if (responseObj.status == "200"){
callback(JSON.parse(responseObj.data));
}else{
if (languageCode.length > 3){
getLanguageFile(languageCode.split("-")[0]+".json", (fallbackObj)=>{
if (fallbackObj.status == "200"){
callback(JSON.parse(fallbackObj.data));
}else{
reportError({
"title": "WARNING - languageCode "+languageCode.split("-")[0],
"value": "FALLBACK Language File for "+languageCode.split("-")[0]+" not retreived from Front end server.\nStatusCode: "+fallbackObj.status,
"targetChannel": "missing-languages",
"color": "warning"
});
callback(JSON.parse(defaultObj.data));
}
});
}else{
reportError({
"title": "WARNING - languageCode "+languageCode,
"value": "FALLBACK Language File for "+languageCode+" not retreived from Front end server.\nStatusCode: "+responseObj.status,
"targetChannel": "missing-languages",
"color": "warning"
});
callback(JSON.parse(defaultObj.data));
}
}
})
}
}else{
reportError({
"title": "ERROR in getting file en.json",
"value": "Language File en.json not retreived from Front end server.\nStatusCode: "+defaultObj.status + "\nTrying again\nTry Counter: " + tillCounter
});
tillCounter++
setTimeout(()=>{
if (tillCounter <= 20){
getAtLeastEnglishFile();
}
},100)
}
});
}
getAtLeastEnglishFile();
}
function getLanguageFile(fileName,callback){
let xhr = new XMLHttpRequest();
/*
if ( "https://spf-widget-production.herokuapp.com" == "https://iphy.herokuapp.com" || "https://spf-widget-production.herokuapp.com" == "https://www.bioluminceye.com"){
xhr.open("GET", "https://spf-widget-production.herokuapp.com/lang/"+fileName+"?"+iphySessionTimeString );
}else{
xhr.open("GET", "https://spf-widget-production.herokuapp.com/lang_staging/"+fileName+"?"+iphySessionTimeString );
}
*/
xhr.open("GET", "https://spf-widget-production.herokuapp.com/lang/"+fileName+"?"+iphySessionTimeString );
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onreadystatechange = function(){
if(this.readyState == 4){
callback({status: this.status, data:this.responseText});
}
}
xhr.send();
}
// RENDER START
function languageToUserSettings(languageElementObj, callback){
render_jsonTextObject(languageElementObj);
callback();
}
function render_jsonTextObject(textObj){
Object.keys(textObj).forEach((item,index)=>{
if ( item == "!variables!"){
updateJsVariables(textObj["!variables!"]);
}else if ( item == "!attributes!"){
updateAttributes(textObj["!attributes!"]);
}else{
if (typeof textObj[item] == "object"){
render_jsonTextObject(textObj[item]);
}else{
try{
if (document.getElementById(item) != null){
document.querySelectorAll("#"+item).forEach((htmlEl,index)=>{
htmlEl.innerHTML = textObj[item];
})
}
}catch(err){
console.log('INFO - Element with id '+item+' not found - err: ',err);
}
}
}
})
}
function updateJsVariables(variablesObj){
Object.keys(variablesObj).forEach((item,index)=>{
try{
this[item] = variablesObj[item];
}catch(err){
console.log('Variable '+ item +' not found - err: ',err);
}
});
}
function updateAttributes(attributeObj){
Object.keys(attributeObj).forEach((item, index) => {
let attrName = Object.keys(attributeObj[item]);
let attrValue = attributeObj[item][attrName];
if (document.getElementById(item) != null){
try{
document.getElementById(item).setAttribute(attrName,attrValue);
}catch(err){
logOnLocalHostFrontEnd("error in setting attributes: ",err);
}
}
});
}
// RENDER END
// let getDioxideCountryData = (dioxCountryCode, callback)=>{
// let xhr = new XMLHttpRequest();
// xhr.open("GET", "https://dioxide.herokuapp.com/product/country_json/"+dioxCountryCode, true);
// xhr.setRequestHeader('Content-Type', 'application/json')
// xhr.timeout = 48000;
// xhr.onreadystatechange = function(){
// if(this.readyState == 4 && this.responseText != ""){
// let response;
// if (typeof this.responseText == "string"){
// response = JSON.parse(this.responseText);
// }else{
// response = this.responseText;
// }
// callback(response);
// }
// }
// xhr.onerror =(err)=>{
// let parsedError;
// try{
// parsedError = JSON.parse(err)
// }catch(catcherror){
// parsedError = err
// }
// logOnLocalHostFrontEnd("ERROR: ",parsedError);
// }
// xhr.ontimeout = ()=>{
// }
// xhr.send();
// }
let getProductDataFromCountry = (countryCode) => {
return new Promise( (resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://dioxide.herokuapp.com/product/country_json/"+countryCode, true);
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.timeout = 48000;
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.responseText != ""){
let response;
if (typeof this.responseText == "string"){
response = JSON.parse(this.responseText);
//console.log(response)
} else {
response = this.responseText;
}
resolve(response);
}
}
xhr.onerror =(err)=>{
reject(err)
logOnLocalHostFrontEnd("ERROR: ",parsedError);
}
xhr.ontimeout = ()=>{
}
xhr.send();
});
}
async function iphyGetAndApplyProductData(){
const dsrPimcoreId = 9178;
const iphyPimcoreId = 11350;
let res = await handleProdDataCountryCall();
const IPHY_DEFAULT_URL = "https://www.dermalogica.com/invisible-physical-defense-spf30/260,default,pd.html";
const DSR_DEFAULT_URL = "https://www.dermalogica.com/dynamic-skin-recovery-spf50/60,default,pd.html";
// let dsrObj = res.filter(product => dsrPimcoreId == product.pimcore_id);
// let iphyObj = res.filter(product => iphyPimcoreId === product.pimcore_id);
logOnLocalHostFrontEnd(prodReccomendationArr)
prodReccomendationArr.push("protection 50 sport spf50");
console.log(prodReccomendationArr)
let prodDioxide = [];
prodReccomendationArr.forEach((prodName)=>{
const prodDataFromDioxide = res.filter((prod) => prod.name == prodName);
if (prodDataFromDioxide.length > 0){
prodDioxide.push(prodDataFromDioxide[0])
}else{
console.warn(`missing product for ${iphyUserCountry} - ${prodName}`);
}
})
let iphyCards = Array.from(document.querySelectorAll(".iphy_product"));
populateProductCards(prodDioxide, iphyCards)
//console.log('dioxide data: ' + prodDioxide)
// containers for each product are predefined in HTML
// simply need to toggle display none or block if the product
// is in the prodReccomendationArr
//console.log(iphyCards)
let iphyBodySize = document.querySelector("#iphy_body");
let protectionPlanSize = document.querySelector(".iphy_slider_container_four");
if (iphyBodySize.classList.contains("iphy_992")) {
if (prodReccomendationArr.length === 1) {
protectionPlanSize.style.height = "1400px";
} else if (prodReccomendationArr.length === 2 || prodReccomendationArr.length === 3) {
protectionPlanSize.style.height = "1800px";
} else {
protectionPlanSize.style.height = "2200px";
}
} else if (iphyBodySize.classList.contains("iphy_600")) {
//console.log("in 600")
if (prodReccomendationArr.length === 2) {
protectionPlanSize.style.height = "2000px";
} else if (prodReccomendationArr.length == 3) {
protectionPlanSize.style.height = "2600px";
} else if (prodReccomendationArr.length == 4) {
protectionPlanSize.style.height = "3100px";
} else if (prodReccomendationArr.length === 5) {
protectionPlanSize.style.height = "3600px";
} else {
protectionPlanSize.style.height = "3600px";
}
} else if(iphyBodySize.classList.contains("iphy_1200")) {
if (prodReccomendationArr.length === 1) {
protectionPlanSize.style.height = "1400px";
} else if (prodReccomendationArr.length === 2 || prodReccomendationArr.length === 3) {
protectionPlanSize.style.height = "1800px";
} else {
protectionPlanSize.style.height = "2200px";
}
}
else {
if (prodReccomendationArr.length === 2 || prodReccomendationArr.length === 3) {
protectionPlanSize.style.height = "1400px";
} else {
protectionPlanSize.style.height = "1800px";
}
}
}
// call getProductDataFromCountry and handle response
async function handleProdDataCountryCall() {
let res;
try{
res = await getProductDataFromCountry(iphyUserCountry);
if (res.length == 0) {
res = await getProductDataFromCountry('US');
}
}catch(err){
res = await getProductDataFromCountry('US');
}
return res;
}
function populateProductCards(prodDioxide, iphyCards) {
for (let prod of prodDioxide) {
//console.log(prod)
if (prod.name === "porescreen spf40") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_ps_plug")) {
card.style.display = "block";
document.querySelector(".ps_link").href = prod.productUrl;
}
}
}
if (prod.name === "dynamic skin recovery spf50") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_dsr_plug")) {
card.style.display = "block";
document.querySelector(".dsr_link").href = prod.productUrl;
}
}
}
if (prod.name === "skinperfect primer spf30") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_spp_plug")) {
card.style.display = "block";
document.querySelector(".spp_link").href = prod.productUrl;
}
}
}
if (prod.name === "powerbright moisturizer spf50") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_pm_plug")) {
card.style.display = "block";
document.querySelector(".pm_link").href = prod.productUrl;
}
}
}
if (prod.name === "invisible physical defense spf30") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_invisibile_plug")) {
card.style.display = "block";
document.querySelector(".iphy_link").href = prod.productUrl;
}
}
}
if (prod.name === "prisma protect spf30") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_pp_plug")) {
card.style.display = "block";
document.querySelector(".pp_link").href = prod.productUrl;
}
}
}
if (prod.name === "protection 50 sport spf50") {
for (let card of iphyCards) {
if (card.classList.contains("iphy_sp_plug")) {
document.querySelector(".sp_link").href = prod.productUrl;
}
}
}
}
}
function populateProductCarousel(prodDataByCountryArr) {
let allSpfProductsArr = [
'dynamic skin recovery spf50',
'prisma protect spf30',
'porescreen spf40',
'skinperfect primer spf30',
'powerbright moisturizer spf50',
'invisible physical defense spf30',
'protection 50 sport spf50'
];
// check if product name is in arr of dioxide prods & call configureCarouselCard to display
allSpfProductsArr.forEach((spfProduct, index) => {
let indexOfProductMatch = prodDataByCountryArr.findIndex((productObj) => productObj.name === spfProduct);
let productObj = prodDataByCountryArr[indexOfProductMatch]
if (indexOfProductMatch > -1) {
switch (productObj.name.toLowerCase()) {
case "porescreen spf40":
configureCarouselCard("iphy_ps_carousel_card", productObj.productUrl);
break;
case "skinperfect primer spf30":
configureCarouselCard("iphy_spp_carousel_card", productObj.productUrl);
break;
case "dynamic skin recovery spf50":
configureCarouselCard("iphy_dsr_carousel_card", productObj.productUrl);
break;
case "powerbright moisturizer spf50":
configureCarouselCard("iphy_pm_carousel_card", productObj.productUrl);
break;
case "prisma protect spf30":
configureCarouselCard("iphy_pp_carousel_card", productObj.productUrl);
break;
case "invisible physical defense spf30":
configureCarouselCard("iphy_ip_carousel_card", productObj.productUrl);
break;
case "protection 50 sport spf50":
configureCarouselCard("iphy_sp_carousel_card", productObj.productUrl);
break;
default:
break;
}
}
});
}
function configureCarouselCard(className, link) {
let carouselCard = document.querySelector(`.${className}`);
//console.log(className)
carouselCard.style.display = "flex";
carouselCard.querySelector('.iphy_carousel_shop_link').href = link;
}
async function iphyPage(pageId){
let pages = document.querySelectorAll(".iphy_page");
sliderLoading();
pages.forEach((page)=>{
page.style.display = "none";
if (page.getAttribute("id")==pageId){
page.style.display = "block";
}
})
if (pageId === 'iphy_parallax_page') {
prodDataByCountry = await handleProdDataCountryCall();
populateProductCarousel(prodDataByCountry)
}
}
var locationAccess;
function iphyGetLocation() {
//console.log(document.querySelector('.iphy_search_input'));
iphyGeolocation()
.then((res)=>{
let long = res.data.coords.longitude;
let lat = res.data.coords.latitude;
let latlng = lat+","+long;
//iphyUpdateLocationResults({latitude: lat, longitude: long})
iphyGetUvIndex({latitude: lat, longitude: long}).then((uvRes)=>{
iphyApplyBreezometerResponse(latlng,uvRes)
})
})
.catch((res)=>{
console.log("error in getting geolocation - ", res);
})
}
function iphyApplyBreezometerResponse(latlng,uvRes){
logOnLocalHostFrontEnd("UV response after lat lng call: ", uvRes)
logOnLocalHostFrontEnd("latlng value: ", latlng)
let dataObj = {...uvRes};
iphyGetCityFromLatLng(latlng, iphyUserLanguageCode, (res)=>{
logOnLocalHostFrontEnd("response from iphyGetCityFromLatLng call: ", res)
let addressArr = res.address.split(',');
const city = addressArr[0];
let state = "";
if (addressArr.length >= 2){
state = addressArr[1].trim();
}
let country = "";
if (addressArr.length >= 3){
country = addressArr[2].trim();
}
dataObj.city = city;
dataObj.state = state;
dataObj.country_code = country;
let now = new Date();
let hours = now.getHours();
let suffix;
if (hours >= 12){
suffix = " pm";
} else {
suffix = " am";
}
if (hours > 12){
hours -= 12;
}
let minutes = ("0" + now.getMinutes()).slice(-2)
let time = hours + ":" + minutes + suffix;
iphy_locTimeString = res.address + " - " + time;
let skinRisk = "";
if ( temperatureArray[2] >= 90) {
skinRisk = iphy_weather_dict['very high'];
} else if ( temperatureArray[2] < 90 && temperatureArray[2] >= 75) {
skinRisk = iphy_weather_dict['high'];
} else if ( temperatureArray[2] < 75 && temperatureArray[2] >= 50) {
skinRisk = iphy_weather_dict['moderate'];
} else if ( temperatureArray[2] < 50) {
skinRisk = iphy_weather_dict['low'];
}
//document.querySelector('.iphy_skin_risk').style.display = 'block';
//document.querySelector('.iphy_skin_risk').innerHTML = iphySkinRiskCopy + " " + is + " " + skinRisk + " " + res.address + " " + time;
getLastThreeDates(now)
.then((res)=>{
// logOnLocalHostFrontEnd("last 3 dates obj: ", res)
iphy_dateArray = [];
iphy_dateArray.push(res.twoDaysAgo);
iphy_dateArray.push(res.yesterday);
iphy_dateArray.push(res.today);
iphy_generateData(dataObj)
})
.catch((err)=>{
console.log("error in getting the last 3 dates - ", err);
//iphyGetBreezometerResults();
})
document.getElementById("searchTextField").style.display = "block";
});
}
function iphyGeolocation(){
return new Promise((resolve,reject)=>{
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition((response) => {
resolve({status:"success",data:response})
}, (error) => {
if (error.code == error.PERMISSION_DENIED)
console.log("you denied me :-(");
// change to next slide if user doesnt accept location
// for slide 2
setTimeout(()=> {
document.getElementById("iphy_step_3_button_slide_two").click();
}, 1000)
document.querySelector("#iphy_protection_plan_card").style.display = "none";
try {
iphyGetBreezometerResults();
} catch (err) {
console.log('error on breez results');
}
}
);
} else {
reject({status:"failure",message:"Geolocation is not supported by this browser."});
}
})
}
function iphyGetCityFromLatLng(latlngString, languageCode,callback){
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://invisiblephysical.com/getCity?latlng=" + latlngString + "&language=" + languageCode);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onreadystatechange = function(){
if(this.readyState == 4){
let jsonData = JSON.parse(this.responseText);
if (jsonData.results == []) {
callback({latitude: "", "longitude": "", address:"" });
} else {
let keepLooking = true;
jsonData.results.forEach((item,index)=>{
if (item.types.indexOf("locality") > -1 && item.types.indexOf("political") >-1 && keepLooking){
keepLooking = false;
latLng = {
lat: item.geometry.location.lat,
long: item.geometry.location.lng,
lng: item.geometry.location.lng
}
callback({latitude: item.geometry.location.lat, "longitude": item.geometry.location.lng, address: item.formatted_address })
}
});
}
}
}
xhr.send();
}
function iphyGetLatLngFromPlaces(res) {
document.querySelector('.iphy_skin_risk').style.display = 'none';
document.getElementById("searchTextField").style.display = "none";
let addressArr = res.split(',');
const city = addressArr[0];
let state = "";
if (addressArr.length >= 2){
state = addressArr[1].trim();
}
let country = "";
if (addressArr.length >= 3){
country = addressArr[2].trim();
}
document.getElementById('searchTextField').value = '';
removePlacesSelectionWrapper();
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://invisiblephysical.com/getLatLng?city= "+ city + "&state=" + state +"&countryCode=" + country);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
let res = JSON.parse(this.responseText);
latLng = res.results[0].geometry.location;
const { location } = res.results[0].geometry;
logOnLocalHostFrontEnd('location:', location)
//iphyUpdateLocationResults(location)
iphyGetUvIndex(location).then((uvRes)=>{
iphyApplyBreezometerResponse(`${location.lat},${location.lng}`,uvRes)
})
}
}
xhr.send();
}
function iphyGetUvIndex(latLng) {
if (latLng.latitude != undefined){
latLng.lat = latLng.latitude;
}
if (latLng.longitude != undefined){
latLng.lng = latLng.longitude;
}
const payload = {
latitude: latLng.lat,
longitude: latLng.lng
}
//console.log("PAYLOAD: ", payload)
const URL = window.iphy_backendToUse + '/iphy/get-breezometer-lat-lon/';
//const URL = window.iphy_backendToUse + '/myskinclock/get-breezometer-lat-lon/';
//const URL = 'https://imb-backend.herokuapp.com/iphy/get-breezometer-lat-lon/';
let response;
return new Promise( (resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response = JSON.parse(this.responseText);
logOnLocalHostFrontEnd("UVB RESPONSES : ", response)
fillUVMeter(response,response.today.temperature_farenheight)
resolve(response);
}
}
xhr.send(JSON.stringify(payload));
});
}
function uvIndexThreshold(uvIndexNum) {
uvIndexNum = parseInt(uvIndexNum);
uvIndexNum = (uvIndexNum / 100) * 10;
logOnLocalHostFrontEnd(uvIndexNum)
if ( uvIndexNum >= 10) {
return iphy_weather_dict['very high'];
} else if ( uvIndexNum < 10 && uvIndexNum >= 6) {
return iphy_weather_dict['high'];
} else if ( uvIndexNum < 6 && uvIndexNum >= 3) {
return iphy_weather_dict['moderate'];
} else {
return iphy_weather_dict['low'];
}
}
function fillUVMeter(uvIndex, temperature = 50) {
//console.log("UV CALL ", uvIndex, temperature)
let uv_index = Math.floor(Math.random() * 5)*5 + 40;
if (uvIndex.today.uv_index != undefined){
uv_index = uvIndex.today.uv_index;
}
//console.log("USING UV INDEX: ",uv_index)
let uvMeter = document.querySelector('.iphy_uv_meter_inner_container');
let uvIndexPercentage;
if ( uv_index >= 100) {
uvIndexPercentage = 100;
} else {
uvIndexPercentage = (uv_index / 100) * 100;
uvIndexPercentage = uvIndexPercentage.toFixed(1);
}
uvMeter.style.width = uvIndexPercentage + '% ';
//UPDATE label above bar:
addCopyToProtectionPlanCard(uv_index, temperature)
}
function updateDateAndDiagram(res) {
return new Promise((resolve,reject)=>{
let { address } = res;
let splitAdress = address.split(',');
let locationInfo = {};
try{
locationInfo.city = splitAdress[0].trim();
}catch(e){
locationInfo.city = ""
}
try{
locationInfo.state = splitAdress[1].trim();
}catch(e){
locationInfo.state = ""
}
try{
locationInfo.country_code = splitAdress[2].trim();
}catch(e){
locationInfo.country_code = ""
}
let now = new Date();
let hours = now.getHours();
let suffix;
createProtectionPlanSubHeader(now, res.address);
if (hours >= 12) {
suffix = " pm";
} else {
suffix = " am";
}
if (hours > 12){
hours -= 12;
}
let minutes = ("0"+now.getMinutes()).slice(-2)
let time = hours + ":" + minutes + suffix;
iphy_locTimeString = res.address + " - "+time;
document.querySelector('.iphy_skin_risk').style.opacity = '1';
document.querySelector('.iphy_skin_risk').innerHTML = iphySkinRiskCopy + " " + is + " " + getTempDict(temperatureArray[2]) + " " + locationInfo.city + ', ' + locationInfo.state + ', ' + locationInfo.country_code + " " + time;
getLastThreeDates(now)
.then((res)=>{
iphy_dateArray = [];
iphy_dateArray.push(res.twoDaysAgo);
iphy_dateArray.push(res.yesterday);
iphy_dateArray.push(res.today);
resolve("date and location update done")
})
})
}
function createProtectionPlanSubHeader(dateObj, address) {
let year = dateObj.getFullYear();
let month = monthNames[dateObj.getMonth()];
let todaysDate = dateObj.getDate();
iphyProtectionPlanSubHeader = todaysDate + " " + month + " " + year + " " + "-" + " " + address;
}
function getLastThreeDates(nowDateObj){
return new Promise((resolve,reject)=>{
let today = {
day: nowDateObj.getDate(),
month: nowDateObj.getMonth() + 1
}
nowDateObj.setDate(nowDateObj.getDate()-1)
let yesterday= {
day: nowDateObj.getDate() ,
month: nowDateObj.getMonth() + 1
}
nowDateObj.setDate(nowDateObj.getDate()-1)
let twoDaysAgo = {
day: nowDateObj.getDate() ,
month: nowDateObj.getMonth() + 1
}
resolve({today: today.month + "." + today.day, yesterday: yesterday.month + "." + yesterday.day, twoDaysAgo: twoDaysAgo.month + "." + twoDaysAgo.day})
});
}
let zenDeskCounter = 0;
function setUpZendesk(){
//console.log("setting up ZenDesk");
deactivateChatComponents();
let allowChat = false;
let zenDeskKeyId = ""
if (iphyUsedLanguageCode == "de" && /dermalogica.de($|:)/g.test(window.location.hostname)){
allowChat = true;
zenDeskKeyId = "de"
}
if (iphyUsedLanguageCode == "en" ){
if (/dermalogica.com($|:)/g.test(window.location.hostname)){
allowChat = true;
zenDeskKeyId = "en"
}
if (/dermalogica.co.uk($|:)/g.test(window.location.hostname) || /dermalogica.ie($|:)/g.test(window.location.hostname)){
allowChat = true;
zenDeskKeyId = "gb_and_ie"
}
if (/dermalogica.co.nz($|:)/g.test(window.location.hostname)){
allowChat = true;
zenDeskKeyId = "derm_nz"
}
}
if (allowChat){
//console.log("setup ZenDesk for language: ", iphyUsedLanguageCode);
stripFormerZopimTags().then((stripResponse)=>{
//console.log(stripResponse)
let zenDeskKeys = {
"en" : "6f0e2fa4-9cd5-4967-9bb9-2238c7817942",
"de" : "1169476d-c034-4bd4-973f-9c034d308605",
"derm_nz" : "1egZcjJ3wq2f6oXMNWdb3UL4eHQ3zB7H",
"gb_and_ie" : "d505e8bc-134c-4364-bdcf-9c91f21fe249"
}
let curZenDeskKey;
let curZenDeskLang;
curZenDeskKey = zenDeskKeys[zenDeskKeyId]
curZenDeskLang = iphyUsedLanguageCode;
logOnLocalHostFrontEnd("user language at Zenddesk setup: ", iphyUsedLanguageCode)
dmliphy_getScript_withAttributes("https://static.zdassets.com/ekr/snippet.js?key=" + curZenDeskKey, {"id":"ze-snippet"}, ()=>{
//console.log("zendesk script for iphy loaded");
let chatOptions = { suppress:false , tags: ["facemapping"]};
window.zESettings = {
webWidget: {
chat: chatOptions
}
}
zE('webWidget', 'setLocale', curZenDeskLang);
zE('webWidget:on', 'chat:status', (status) => {
//console.log("chat status: ", status)
if(status=="online"){
iphySendGA("chat events","chat is online");
window.iphyChatStatus = "online";
activateChatComponents();
}else{
iphySendGA("chat events","chat is offline");
deactivateChatComponents();
window.iphyChatStatus = "offline";
}
})
zE('webWidget', 'hide');
zE('webWidget:on', 'open', function() {
logOnLocalHostFrontEnd("The widget has been opened!");
iphySendGA("chat events","widget has been opened");
});
zE('webWidget:on', 'chat:end', function() {
logOnLocalHostFrontEnd("The chat has been closed!");
iphySendGA("chat events","chat has ended");
zE('webWidget', 'hide');
});
zE('webWidget:on', 'close', function() {
logOnLocalHostFrontEnd("The widget has been closed!");
iphySendGA("chat events","widget is closed");
zE('webWidget', 'hide');
});
})
})
}else{
//console.log("language not matching for ZenDesk");
}
}
let stripFormerZopimTags = ()=>{
let stripZopimPromise = new Promise((res,rej)=>{
if (window.location.href.indexOf("dermalogica.co.nz") > -1 || window.location.href.indexOf("dermalogica.com.au") || window.location.href.indexOf("dermalogica.co.za")> -1){
let pageScripts = document.querySelectorAll("script");
let zdassetsScriptsNum = 0;
[].forEach.call(pageScripts, (scrpt) => {
if (scrpt.src.indexOf("zdassets") > -1 || scrpt.innerHTML.indexOf(".zopim")>-1 || scrpt.src.indexOf(".zopim")>-1){
zdassetsScriptsNum++;
scrpt.parentNode.removeChild(scrpt);
}
})
let pageIframes = document.querySelectorAll("iframe");
let zdassetsIframesNum = 0;
[].forEach.call(pageIframes, (ifrm) => {
if (ifrm.classList.value.indexOf("zEWidget")>-1 || ifrm.getAttribute("data-product") == "web_widget"){
zdassetsIframesNum++;
ifrm.parentNode.removeChild(ifrm);
}
})
window.$zopim = null;
window.zE = null;
window.zChat = null;
window.zESettings = null;
window.zEACLoaded = null;
res("removed "+zdassetsScriptsNum+" zdassets scripts and " + zdassetsIframesNum + " iframes");
}else{
res("nothing to remove");
}
});
return stripZopimPromise;
}
let mobileClickedOnceAlready = false;
let mobileClickedOnceTimeout;
let openChat = ()=>{
let currentlyChatting = zE('webWidget:get', 'chat:isChatting');
logOnLocalHostFrontEnd("currently Chatting: ", currentlyChatting)
if (document.getElementById("iphy_body").offsetWidth > 768 || mobileClickedOnceAlready){
iphySendGA("chat events","user used chat button");
if (document.getElementById("iphy_body").offsetWidth <= 768){
reduceChatBannerOnMobile();
}
window.zE('webWidget','show');
window.$zopim.livechat.window.show();
window.zE('webWidget','open');
zE('webWidget:on', 'chat:connected', function() {
//console.log('successfully connected to Zendesk Chat!');
});
zE('webWidget', 'chat:send', iphyChatCopy);
}else{
mobileClickedOnceAlready = true;
clearTimeout(mobileClickedOnceTimeout);
document.getElementById("iphy_fixed_chat_button").style.width = "260px";
document.getElementById("iphy_fixed_chat_button").style.borderColor = "rgba(0,0,0,0)";
setTimeout(()=>{
document.getElementById("iphy_body").addEventListener("click",reduceChatBannerOnMobile);
},10)
mobileClickedOnceTimeout = setTimeout(()=>{
reduceChatBannerOnMobile();
},3000)
}
}
let deactivateChatComponents = () => {
try{
document.getElementById("iphy_fixed_chat_button").style.display = "none";
}catch(err){
//console.log("cannot deactivate chat components - ",err);
}
}
let activateChatComponents = ()=>{
try{
document.getElementById("iphy_fixed_chat_button").style.display = "block";
document.getElementById("iphy_fixed_chat_button").onmouseover = ()=>{
document.getElementById("iphy_fixed_chat_button").style.width = document.getElementById("iphy_fixed_chat_button_text").offsetWidth+ 70 + "px";
}
document.getElementById("iphy_fixed_chat_button").onmouseleave = ()=>{
document.getElementById("iphy_fixed_chat_button").style.width = "62px";
}
}catch(err){
//console.log("cannot activate chat compontents - ",err)
}
}
let reduceChatBannerOnMobile = ()=>{
document.getElementById("iphy_body").removeEventListener("click",reduceChatBannerOnMobile);
logOnLocalHostFrontEnd("reduce mobile chat badge");
mobileClickedOnceAlready = false;
document.getElementById("iphy_fixed_chat_button").style.width = "62px";
document.getElementById("iphy_fixed_chat_button").style.borderColor = "#848683";
}
let animationTimeStep = 30;
function iphyUpdateDiagram(svgId){
let svg = document.getElementById(svgId);
logOnLocalHostFrontEnd("update diagram - date Array: ",iphy_dateArray)
svg.getElementById("iphy_date_label_1").innerHTML = iphy_dateArray[0];
svg.getElementById("iphy_date_label_2").innerHTML = iphy_dateArray[1];
svg.getElementById("iphy_date_label_3").innerHTML = iphy_dateArray[2];
svg.getElementById("iphy_location_and_time").innerHTML = iphy_locTimeString;
let temperature = temperatureArray[2] + '° F';
let aqi = pollutionArray[2] + ' / 300';
let relativeHumidity = humidityArray[2] + ' / 100';
let highYToday = temperatureArray[2];
let highYYesterday = temperatureArray[1];
let highYTwoDaysAgo = temperatureArray[0];
svg.getElementById("iphy_diagram_temp_desc_word").innerHTML = temperature;
svg.getElementById("iphy_diagram_pollution_desc_word").innerHTML = aqi;
svg.getElementById("iphy_diagram_humidity_desc_word").innerHTML = relativeHumidity;
document.querySelector(".lds_roller_container").style.display="none";
document.querySelector("#iphy_diagram_svg_2").style.display="block";
function updateCurve(dotIdPrefix, lineIdPrefix, dataArray){
for (let ii = 0; ii < 3; ii++){
let curDotId = dotIdPrefix+(ii+1);
let curLineId = lineIdPrefix+(ii+1);
let dotElement = svg.getElementById(curDotId);
let dotTargetY = Number(140-dataArray[ii]) ;
iphy_animate_dot(dotElement,dotTargetY,500);
let targetY1;
let targetY2;
let lineElement = svg.getElementById(curLineId);
if (ii==0){
targetY1 = 140;
}else{
targetY1 = 140-dataArray[ii-1];
}
targetY2 = 140-dataArray[ii];
iphy_animate_line(lineElement,targetY1,targetY2,500);
if (ii == 0){
highYTwoDaysAgo = Math.min(highYTwoDaysAgo, targetY2 - 10)
}else if (ii == 1){
highYYesterday = Math.min(highYYesterday, targetY2 - 10)
}else{
highYToday = Math.min(highYToday, targetY2 - 10)
}
}
}
updateCurve("tempDot_","tempLine_", temperatureArray);
updateCurve("pollutionDot_","pollutionLine_", pollutionArray);
updateCurve("humidityDot_","humidityLine_", humidityArray);
iphy_animate_text(svg.getElementById("iphy_date_label_1"), highYTwoDaysAgo,500);
iphy_animate_text(svg.getElementById("iphy_date_label_2"), highYYesterday,500);
iphy_animate_text(svg.getElementById("iphy_date_label_3"), highYToday,500);
let tempLabelY = 140 - temperatureArray[2];
let pollutionLabelY = 140 - pollutionArray[2];
let humidityLabelY = 140 - humidityArray[2];
// logic for seperating labels START
var listY = [tempLabelY, pollutionLabelY, humidityLabelY];
var mapped = listY.map(function(el, i) {
return { index: i, value: el };
})
let sortedConditions = mapped.sort(function(a, b) {
if (a.value > b.value) {
return 1;
}
if (a.value < b.value) {
return -1;
}
return 0;
});
if (listY[sortedConditions[1].index] - listY[sortedConditions[0].index] < 15){
listY[sortedConditions[0].index] -= 15;
}
if (listY[sortedConditions[2].index] - listY[sortedConditions[1].index] < 15){
listY[sortedConditions[2].index] += 15;
}
// logic for seperating labels END
iphy_animate_group(svg.getElementById("iphy_tempLabel_group"), listY[0], 500);
iphy_animate_group(svg.getElementById("iphy_pollutionLabel_group"), listY[1], 500);
iphy_animate_group(svg.getElementById("iphy_humidityLabel_group"), listY[2], 500);
}
function iphy_score_conditions(conditionValue) {
let dictKey;
if (conditionValue > 75){
dictKey = "very high";
} else if (conditionValue > 50){
dictKey = "high";
} else if (conditionValue > 25){
dictKey = "moderate";
} else{
dictKey = "low";
}
//console.log("Condition Value:" + conditionValue)
return dictKey;
}
function iphy_animate_line(lineElement, targetY1,targetY2,time){
let timeStep = animationTimeStep;
let curTime = 50;
let startY1 = Number(lineElement.getAttribute("y1"));
let startY2 = Number(lineElement.getAttribute("y2"));
let animInterval = setInterval(()=>{
if (curTime < time){
let animationFraction = curTime/time;
lineElement.setAttribute("y1",startY1 + animationFraction*(targetY1-startY1));
lineElement.setAttribute("y2",startY2 + animationFraction*(targetY2-startY2));
}else{
lineElement.setAttribute("y1",targetY1);
lineElement.setAttribute("y2",targetY2);
clearInterval(animInterval);
}
curTime += timeStep;
},timeStep);
}
function iphy_animate_dot(dotElement, targetY,time){
let timeStep = animationTimeStep;
let curTime = 50;
let startY = Number(dotElement.getAttribute("cy"));
let animInterval = setInterval(()=>{
if (curTime < time){
let animationFraction = curTime/time;
dotElement.setAttribute("cy", startY + animationFraction * (targetY - startY) );
} else {
dotElement.setAttribute("cy",targetY);
clearInterval(animInterval);
}
curTime += timeStep;
}, timeStep);
}
function iphy_animate_text(textElement,targetY,time){
let timeStep = animationTimeStep;
let curTime = 50;
let startY = Number(textElement.getAttribute("y"));
let animInterval = setInterval(()=>{
if (curTime < time){
let animationFraction = curTime/time;
textElement.setAttribute("y", startY + animationFraction * (targetY - startY ));
} else {
textElement.setAttribute("y",targetY);
clearInterval(animInterval);
}
curTime += timeStep;
}, timeStep);
}
function iphy_animate_group(groupElement, targetY, time){
let timeStep = animationTimeStep;
let curTime = 50;
let translateString = groupElement.getAttribute("transform");
let translateXPart =translateString.split(",")[0];
let startY = Number(translateString.split(",")[1].replace(")",""));
let animInterval = setInterval(()=>{
if (curTime < time){
let animationFraction = curTime/time;
let currentY = startY + animationFraction*(targetY-startY);
groupElement.setAttribute("transform",translateXPart + "," + currentY + ")");
} else {
groupElement.setAttribute("transform",translateXPart + "," + targetY + ")");
clearInterval(animInterval);
}
curTime += timeStep;
}, timeStep);
}
function iphy_generateData(resp) {
logOnLocalHostFrontEnd("generate Data call",resp)
temperatureArray = [];
pollutionArray = [];
humidityArray = [];
let locationInfo = {};
if ( resp.city) {
locationInfo = { ...resp };
}
Object.keys(resp).forEach(key => {
if (key === "today" || key === 'yesterday' || key === 'twoDaysBack') {
Object.keys(resp[key]).forEach( innerKey => {
if ( innerKey === 'temperature_farenheight') {
temperatureArray.push(resp[key][innerKey].toFixed(0));
} else if ( innerKey === 'aqi') {
pollutionArray.push(resp[key][innerKey]);
} else if ( innerKey === 'relative_humidity') {
humidityArray.push(resp[key][innerKey])
}
});
}
});
let address = locationInfo.city + ',' + locationInfo.state;
let now = new Date();
let hours = now.getHours();
let suffix;
if (hours >= 12){
suffix = " pm";
} else {
suffix = " am";
}
if (hours > 12) {
hours -= 12;
}
createProtectionPlanSubHeader(now, address);
let minutes = ("0" + now.getMinutes()).slice(-2);
let time = hours + ":" + minutes + suffix;
if ( !iphy_locTimeString) {
iphy_locTimeString = resp.city;
if (resp.state != ""){
iphy_locTimeString += ", " + resp.state;
}
if (resp.country_code != ""){
iphy_locTimeString += ", " + resp.country_code;
}
iphy_locTimeString += " " + time;
};
temperatureArray = temperatureArray.reverse();
pollutionArray = pollutionArray.reverse();
humidityArray = humidityArray.reverse();
getLastThreeDates(now).then( res => {
iphy_dateArray = [];
iphy_dateArray.push(res.twoDaysAgo);
iphy_dateArray.push(res.yesterday);
iphy_dateArray.push(res.today);
iphyUpdateDiagram('iphy_diagram_svg_2');
});
document.querySelector('.iphy_skin_risk').style.display = 'block';
document.querySelector('.iphy_skin_risk').innerHTML = iphySkinRiskCopy + " " + is + " " + getTempDict(temperatureArray[2]) + " " + resp.city + ', ' + resp.state + ', ' + resp.country_code + " " + time;
}
function getTempDict(temperature) {
if ( temperature >= 90) {
return iphy_weather_dict['very high'];
} else if ( temperature < 90 && temperature >= 75) {
return iphy_weather_dict['high'];
} else if ( temperature < 75 && temperature >= 50) {
return iphy_weather_dict['moderate'];
} else if ( temperature < 50) {
return iphy_weather_dict['low'];
}
}
function getCity() {
const URL = window.iphy_backendToUse + '/iphy/get-breezometer/';
return new Promise( (resolve, reject) => {
let xhr = new XMLHttpRequest();
let resp;
xhr.open("GET", URL);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if(this.readyState == 4){
try {
resp = JSON.parse(this.responseText);
resolve(resp);
} catch(err) {
//console.log("could not parse json response - ",err);
}
// updateGdprAndEndPoints(response,true);
}
}
xhr.send();
});
}
function iphyGetBreezometerResults() {
return new Promise( (resolve, reject) => {
const URL = window.iphy_backendToUse + '/iphy/get-breezometer/';
let xhr = new XMLHttpRequest();
let breezometerResp;
xhr.open("GET", URL);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if(this.readyState == 4){
try {
breezometerResp = JSON.parse(this.responseText);
//iphy_generateData(breezometerResp);
//resolve(iphyUpdateDiagram('iphy_diagram_svg_2'));
fillUVMeter( { "today" : { "tmp" : 0 } })
resolve(breezometerResp);
} catch(err) {
//console.log("could not parse json response - ",err);
}
}
}
xhr.send();
});
}
function iphyUpdateLocationResults(latLngPayload) {
let latLng;
if (latLngPayload.latitude) {
latLng = latLngPayload.latitude + ',' + latLngPayload.longitude;
} else {
latLng = latLngPayload.lat + ',' + latLngPayload.lng;
latLngPayload = {
'latitude': latLngPayload.lat,
'longitude':latLngPayload.lng
}
}
const URL = window.iphy_backendToUse + '/iphy/get-breezometer-lat-lon/';
//const URL = window.iphy_backendToUse + '/myskinclock/get-breezometer-lat-lon/';
//const URL = 'https://imb-staging.herokuapp.com/myskinclock/get-breezometer-lat-lon/';
let response;
return new Promise( (resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector('.iphy_skin_risk').style.opacity = '0';
response = JSON.parse(this.responseText);
//console.log("RESPONSE: ",response)
iphyGetCityFromLatLng(latLng, iphyUserLanguageCode, (res) => {
//console.log("RESPONSE !!!!!: ",res)
response.address = res.address;
try {
iphy_generateData(response);
//updateDateAndDiagram(res, resolve)
}
catch( err) {
//console.log("error in getting the last 3 dates - ",err);
}
})
}
}
xhr.send(JSON.stringify(latLngPayload));
});
}
function toggleDropdown(evt,dropdownNumber){
let btnEl = evt.target;
if (btnEl.getAttribute("allowclick")=="true"){
btnEl.setAttribute("allowclick","false");
setTimeout(()=>{
btnEl.setAttribute("allowclick","true");
},500)
let arrowEl = document.querySelector(".iphy_arrow_logo.iphy_cta_dropdown_"+dropdownNumber);
arrowEl.classList.toggle("cta_opened");
let dropDownEl = document.querySelector(".element_iphy_cta_dropdown_"+dropdownNumber);
//dropDownEl.classList.toggle("cta_opened");
if (dropDownEl.offsetHeight > 0){
dropDownEl.style.maxHeight = 0;
}else{
let maxHeight = 0;
dropDownEl.querySelectorAll(".iphy_cta_dropdown_el_wrapper > div").forEach((child)=>{
maxHeight = Math.max(maxHeight, child.offsetHeight);
});
dropDownEl.style.maxHeight = maxHeight + "px";
}
}
}
function addEventListenerOnCTA() {
let iphyDropDownOpen = false;
document.querySelectorAll('.iphy_cta_btn').forEach(btn => btn.addEventListener('click', function() {
iphyOpenCtaDropDown(this);
}));
document.querySelectorAll('.iphy_arrow_logo').forEach(arrow => arrow.addEventListener('click', function() {
iphyOpenCtaDropDown(this);
}));
function iphyOpenCtaDropDown(elem) {
let arrowImg;
if ( elem.classList.contains('iphy_arrow_logo')) {
arrowImg = elem;
} else {
arrowImg = elem.nextSibling.nextSibling;
}
let iphyDropdownElement;
elem.classList.forEach( (className) => {
let regex = new RegExp("[0-9]+");
if ( regex.test(className)) {
iphyDropdownElement = className;
}
});
let dropdownElem = document.querySelector('.element_'+iphyDropdownElement);
if ( !iphyDropDownOpen) {
dropdownElem.style.maxHeight = '1200px';
arrowImg.style.transform = 'rotate(180deg)';
iphyDropDownOpen = true
} else if (iphyDropDownOpen) {
dropdownElem.style.maxHeight = '0px';
arrowImg.style.transform = 'rotate(0deg)';
iphyDropDownOpen = false;
}
}
}
function positionCircles() {
const circles = document.querySelectorAll('.circle div');
for (var i = 0, l = circles.length; i < circles.length; i++) {
circles[i].style.left = (50 - 35*Math.cos(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
circles[i].style.top = (50 + 35*Math.sin(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
}
}
function activeSegments(event, segmentNum, segmentClassName) {
const circles = document.querySelectorAll('.circle div');
let segments = document.querySelectorAll(segmentClassName);
let iphyNavLinks = document.querySelectorAll('.iphy_nav_link');
let segmentIcon;
//(event.currentTarget);
if ( event.currentTarget.classList.contains('circle_div')) {
circles.forEach(circle => circle.style.backgroundColor = '#fedf41');
event.currentTarget.style.backgroundColor = '#f2bc00';
}
segments.forEach( (segment, index) => {
let segmentAttrNum = segment.getAttribute('data-segment-number');
if (segmentClassName === '.iphy_bluelight_segment') {
iphyNavLinks[index].classList.remove('active_link');
document.querySelector('.iphy_question_mark_active').style.display = 'none';
document.querySelector('.iphy_skin_active').style.display = 'none';
document.querySelector('.iphy_shield_active').style.display = 'none';
document.querySelector('.iphy_question_mark_inactive').style.display = 'inline-block';
document.querySelector('.iphy_shield_inactive').style.display = 'inline-block';
document.querySelector('.iphy_skin_inactive').style.display = 'inline-block';
}
if (parseInt(segmentAttrNum) === segmentNum) {
segment.style.display = 'block';
} else {
segment.style.display = 'none';
}
});
if (segmentClassName === '.iphy_bluelight_segment') {
segmentIcon = event.currentTarget.getAttribute('data-segment-icon');
document.querySelector('.iphy_' + segmentIcon + '_active').style.display = 'inline-block';
document.querySelector('.iphy_' + segmentIcon + '_inactive').style.display = 'none';
event.currentTarget.classList.add('active_link');
}
}
function mobileActiveSegments(event, segmentNumber) {
const questionMarkIconEl = document.querySelector('.iphy_question_mobile');
const skinIconEl = document.querySelector('.iphy_skin_mobile');
const shieldIconEl = document.querySelector('.iphy_shield_mobile');
let icon = event.currentTarget.getAttribute('data-icon');
if ( icon === 'questionMarkIcon') {
event.currentTarget.classList.add('iphy_question_mark_active');
event.currentTarget.classList.remove('iphy_question_mark_mobile_inactive');
// remove active bg
skinIconEl.classList.remove('iphy_skin_mobile_active');
shieldIconEl.classList.remove('iphy_shield_active');
// add inactive bg
skinIconEl.classList.add('iphy_skin_mobile_inactive')
shieldIconEl.classList.add('iphy_shield_mobile_inactive');
} else if ( icon === 'skinIcon') {
event.currentTarget.classList.add('iphy_skin_active');
event.currentTarget.classList.remove('iphy_skin_mobile_inactive');
// remove active bg
questionMarkIconEl.classList.remove('iphy_question_mark_active')
shieldIconEl.classList.remove('iphy_shield_active');
// add inactive bg
questionMarkIconEl.classList.add('iphy_question_mark_mobile_inactive');
shieldIconEl.classList.add('iphy_shield_mobile_inactive');
} else {
event.currentTarget.classList.add('iphy_shield_active')
event.currentTarget.classList.remove('iphy_shield_mobile_inactive');
// remove active bg
questionMarkIconEl.classList.remove('iphy_question_mark_active');
skinIconEl.classList.remove('iphy_skin_active')
// add inactive bg
questionMarkIconEl.classList.add('iphy_question_mark_mobile_inactive')
skinIconEl.classList.add('iphy_skin_mobile_inactive');
}
activeSegmentHelperFn('.iphy_bluelight_segment_container_mobile', segmentNumber);
}
function mobileCtaOneDropdown(event, segmentNumber) {
const circles = document.querySelectorAll('.mobile_circle_div');
if ( event.currentTarget.classList.contains('mobile_circle_div')) {
circles.forEach(circle => circle.style.backgroundColor = '#fedf41');
event.currentTarget.style.backgroundColor = '#f2bc00';
}
activeSegmentHelperFn('.iphy_cta_1_copy_container', segmentNumber);
}
function activeSegmentHelperFn(segmentClass, segmentNumber) {
const segments = document.querySelectorAll(segmentClass);
segments.forEach(segment => {
let segmentAtrr = segment.getAttribute('data-segment-number');
if ( parseInt(segmentAtrr) === segmentNumber) {
segment.style.display = 'block';
} else {
segment.style.display = 'none';
}
});
}
let prodReccomendationArr = [];
let finalCategory = "";
function addEventListenerToSlideBtns(element, cb) {
document.querySelectorAll(element).forEach( elem => {
elem.addEventListener('click', cb);
});
}
function sliderLoading() {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve(positionContentSliders());
}, 500)
});
}
function getElementWidth(element) {
return document.querySelector(element).offsetWidth;
}
function repositionContentSliders() {
const sliderContainerWidth = getElementWidth('.iphy_slider_container');
const contentSliders = document.querySelectorAll('.iphy_slide');
//console.log('current slide:', currentSlide);
currentSlide = 0;
if ( !currentSlide) {
for ( let i = currentSlide; i < contentSliders.length; i++) {
if ( i === currentSlide) {
contentSliders[i].style.left = '0px';j
} else {
contentSliders[i].style.left = sliderContainerWidth * i + 'px';
}
}
}
}
function positionContentSliders() {
const elementWidth = getElementWidth('.iphy_slider_container');
const sliders = document.querySelectorAll('.iphy_slide');
slideCounter = 0;
sliders.forEach( (elem, index) => {
if ( !index) {
elem.style.left = '0px';
} else {
elem.style.left = elementWidth * index + 'px';
}
});
resetBtnOpacity();
}
let currentSlide = 0;
function moveSliderForward(e) {
const currentTarget = e.currentTarget;
const parentContainerWidth = getElementWidth('.iphy_slider_container');
const sliders = document.querySelectorAll('.iphy_slide');
//console.log(e)
setTimeout( () => {
if ( sliderMovements.forward) {
sliderMovements.forward = false;
slideCounter++;
currentSlide++;
sliders.forEach( (element, index) => {
const elementLeftPosition = element.offsetLeft;
element.style.left = elementLeftPosition - parentContainerWidth + 'px';
});
if ( slideCounter === 5) {
document.querySelector('.iphy_content_slider_one').style.display = 'none';
document.querySelector('.iphy_content_slider_two').style.display = 'block';
}
}
}, 200)
if ( slideCounter === 3) {
setWidthUVMeters();
}
setTimeout( () => {
sliderMovements.forward = true;
}, 1000)
if ( slideCounter === 4 ) {
//console.log("slide 4 now") //do something here
iphyGetAndApplyProductData()
}
}
function moveSliderBackwards(e) {
const parentContainerWidth = getElementWidth('.iphy_slider_container');
const sliders = document.querySelectorAll('.iphy_slide');
const nextBtns = document.querySelectorAll('.iphy_next_btn');
if ( sliders[0].style.left === '0px') {
return;
}
if ( sliderMovements.backward) {
slideCounter--;
currentSlide--;
sliderMovements.backward = false;
sliders.forEach( element => {
const elementLeftPosition = element.offsetLeft;
element.style.left = elementLeftPosition + parentContainerWidth + 'px';
});
};
setTimeout( () => {
sliderMovements.backward = true;
}, 800);
if ( slideCounter === 2) {
setTimeout( () => {
nextBtns[1].style.opacity = '1';
}, 800)
} else if ( slideCounter === 1) {
setTimeout( () => {
nextBtns[0].style.opacity = '1';
}, 800)
} else {
resetBtnOpacity();
}
}
function resetBtnOpacity() {
document.querySelectorAll('.iphy_next_btn').forEach(btn => {
if ( btn.classList.contains('iphy_step_two_btn')) {
btn.style.opacity = '.5';
} else {
btn.style.opacity = '1';
}
});
}
function highLightSkinTone(e) {
let parentClassName = e.currentTarget.classList[1];
removeHighlightHelperFn('.iphy_skin_type', 'iphy_bold_text');
removeHighlightHelperFn('.iphy_skin_description', 'iphy_bold_text');
removeHighlightHelperFn('.iphy_skin_color', 'iphy_highlight');
document.querySelector('.'+parentClassName + ' .iphy_skin_type').classList.add('iphy_bold_text');
document.querySelector('.'+parentClassName + ' .iphy_skin_color').classList.add('iphy_highlight');
e.currentTarget.childNodes.forEach( child => {
if ( child.nodeType === 1) {
if ( child.classList.contains('iphy_skin_description')) {
child.classList.add('iphy_bold_text');
}
}
});
}
function removeHighlightHelperFn(elements, className,) {
const selectedElem = document.querySelectorAll(elements);
selectedElem.forEach( elem => {
elem.classList.remove(className);
});
}
function setWidthUVMeters() {
setTimeout( () => {
const uvMeterContainerWidth = getElementWidth('.iphy_uv_meter_container');
document.querySelector('.iphy_uv_meter').style.width = uvMeterContainerWidth - 13 + 'px';
document.querySelector('.iphy_uv_meter_foreground').style.width = uvMeterContainerWidth - 13 + 'px';
document.querySelector('.iphy_uv_meter_foreground').style.visibility = 'visible';
}, 1000)
}
function resizeIphyElements() {
const iphyBodyEl = document.querySelector('#iphy_body');
const iphyBodyWidth = document.querySelector('#iphy_body').offsetWidth;
if ( iphyBodyWidth <= 600 && iphyBodyWidth) {
iphyBodyEl.classList.add('iphy_600');
iphyBodyEl.classList.remove('iphy_768');
iphyBodyEl.classList.remove('iphy_992');
iphyBodyEl.classList.remove('iphy_1200');
} else if ( iphyBodyWidth <= 768) {
iphyBodyEl.classList.add('iphy_768');
iphyBodyEl.classList.remove('iphy_600');
iphyBodyEl.classList.remove('iphy_992');
iphyBodyEl.classList.remove('iphy_1200');
} else if ( iphyBodyWidth <= 992) {
iphyBodyEl.classList.add('iphy_992');
iphyBodyEl.classList.remove('iphy_600');
iphyBodyEl.classList.remove('iphy_768');
iphyBodyEl.classList.remove('iphy_1200');
} else if ( iphyBodyWidth <= 1200) {
iphyBodyEl.classList.add('iphy_1200');
iphyBodyEl.classList.remove('iphy_600');
iphyBodyEl.classList.remove('iphy_768');
iphyBodyEl.classList.remove('iphy_992');
} else {
iphyBodyEl.classList.remove('iphy_600');
iphyBodyEl.classList.remove('iphy_768');
iphyBodyEl.classList.remove('iphy_992');
iphyBodyEl.classList.remove('iphy_1200');
}
}
function subscribeEmail() {
let email = document.querySelector('.iphy_text_input').value;
//console.log(email)
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/\S+@\S+\.\S+/
);
};
console.log("subscribeEmail Called")
if (validateEmail(email) !== null) {
email = validateEmail(email)[0];
const payload = {};
let xhr = new XMLHttpRequest();
payload.email = email;
payload.api_key = '9DWV9qJCxpyQTYTr4SA0';
xhr.open('POST', `https://imb-backend-eu.herokuapp.com/fmc/subscribe_klaviyo_api`, true);
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(payload));
document.querySelector("#iphy_valid_email").style.display = 'none';
} else {
document.querySelector("#iphy_valid_email").style.display = 'block';
return;
}
document.querySelector("#iphy_submit").style.display = 'none';
document.querySelector('.iphy_text_input').style.display = 'none';
document.querySelector('.iphy_submit_confirm').style.display = 'flex';
}
function resizeProductPlugs() {
let iphyBodyWidth = document.querySelector('#iphy_body').offsetWidth;
let dsrPlugEl = document.querySelector('.iphy_dsr_plug');
let iphyInvisPhysPlugEl = document.querySelector('.iphy_invisibile_plug');
let scaleFactor = Math.min(1, 600 / iphyBodyWidth);
if ( iphyBodyWidth <= 600) {
dsrPlugEl.style.transform = "scale("+scaleFactor+")";
iphyInvisPhysPlugEl.style.transform = "scale("+scaleFactor+")";
}
}
function addCopyToProtectionPlanCard(uv_index, temperature = 50) {
// debugger;
let uvIndexStr = Number(uv_index);
//let temperatureCopy = getTempDict(temperatureArray[2]);
let temperatureCopy = getTempDict(Number(temperature));
let iphySkinRiskEl = document.querySelector('.iphy_skin_risk_copy');
let iphySkinRiskEl2 = document.createElement('span');
let iphyTempEl = document.createElement('span');
let iphyUvIndexEl = document.querySelector('.iphy_uv_index_num');
let iphyMinsOutdoorsEl = document.querySelector('.iphy_sunburn_risk_copy');
let slideFourSubHeaderEl = document.querySelector('.iphy_slide_four_sub_header');
let minsOutdoors = "";
//uvIndexStr = 50;
uvIndexStr = (parseInt(uvIndexStr) / 100) * 100;
uvIndexStr = uvIndexStr.toFixed(0);
//console.log(`UV Index: ${uvIndexStr}`);
if ( uvIndexStr >= 10) {
minsOutdoors = skinToneDict['11'][iphySkinToneRelMark.toFixed(1)]
} else if ( uvIndexStr < 10 && uvIndexStr >= 8) {
minsOutdoors = skinToneDict['8'][iphySkinToneRelMark.toFixed(1)];
} else if ( uvIndexStr < 8 && uvIndexStr >= 6) {
minsOutdoors = skinToneDict['6'][iphySkinToneRelMark.toFixed(1)];
} else if ( uvIndexStr < 6 && uvIndexStr >= 3) {
minsOutdoors = skinToneDict['3'][iphySkinToneRelMark.toFixed(1)];
} else {
minsOutdoors = skinToneDict['1'][iphySkinToneRelMark.toFixed(1)];
//console.log(`Mins: ${minsOutdoors}`)
}
iphyTempEl.classList.add('iphy_temp_copy', 'iphy_inline');
iphySkinRiskEl2.classList.add('iphy_inline', 'iphy_protection_cta');
iphyTempEl.innerHTML = temperatureCopy;
iphySkinRiskEl2.innerHTML = ". " + iphy_protection_plan_skin_risk_2;
iphySkinRiskEl.innerHTML = iphy_protection_plan_skin_risk + " ";
iphySkinRiskEl.appendChild(iphyTempEl);
iphySkinRiskEl.appendChild(iphySkinRiskEl2);
iphyUvIndexEl.innerHTML = uvIndexStr + "(" + uvIndexThreshold(uvIndexStr) + ")";
try{
iphyMinsOutdoorsEl.innerHTML = iphy_protection_outdoors_copy_1 + "" + " " + minsOutdoors + " " + iphy_protection_outdoors_copy_2 + "" + " " + iphy_protection_outdoors_copy_3;
}catch(err){
console.log("error in setting copy - ",err);
}
slideFourSubHeaderEl.innerHTML = iphyProtectionPlanSubHeader;
}
let startSliderPos;
let sliderMarker = document.getElementById("iphy_options_slider_marker");
sliderMarker.ontouchstart = iphyStartSlider;
sliderMarker.onmousedown = iphyStartSlider;
let sliderCont = sliderMarker.parentElement;
let leftBorder;
let rightBorder;
let sliderWidth;
function iphyStartSlider(evt){
let clientRectCont = sliderCont.getBoundingClientRect();
leftBorder = clientRectCont.left;
sliderWidth = clientRectCont.width;
rightBorder = leftBorder + sliderWidth;
document.ontouchmove = iphyDocumentCursorMove;
document.onmousemove = iphyDocumentCursorMove;
document.ontouchend = iphyEndSlider;
document.onmouseup = iphyEndSlider;
sliderMarker.ontouchend = iphyEndSlider;
sliderMarker.onmouseup = iphyEndSlider;
}
function iphyDocumentCursorMove(evt){
let cursorPos ;
if (evt.type == "mousemove"){
cursorPos = evt.clientX;
}
if (evt.type == "touchmove"){
cursorPos = evt.touches[0].clientX;
}
cursorPos = Math.max(leftBorder, cursorPos);
cursorPos = Math.min(rightBorder, cursorPos);
sliderPos = cursorPos - leftBorder - 30; // left padding and half circle needs to be substracted;
sliderMarker.style.left = sliderPos + "px";
iphySliderColor(cursorPos);
}
function iphyEndSlider(evt){
document.ontouchmove = null;
document.onmousemove = null;
document.ontouchend = null;
document.onmouseup = null;
sliderMarker.ontouchend = null;
sliderMarker.onmouseup = null;
}
iphy_skintone_colors={
veryfair: {
"hex":"#f7e3d2",
"r":247,
"g":227,
"b":210
},
fair: {
"hex":"#e6cba6",
"r":230,
"g":203,
"b":166
},
medium: {
"hex":"#cda17a",
"r":205,
"g":161,
"b":122
},
olive: {
"hex":"#a7724f",
"r":167,
"g":114,
"b":79
},
brown: {
"hex":"#774d35",
"r":119,
"g":77,
"b":53
},
darkbrown: {
"hex":"#2b1712",
"r":43,
"g":23,
"b":18
}
}
function iphySliderColor(sliderPos){
let colorMark = (sliderPos - leftBorder) / sliderWidth;
iphySkinToneRelMark = colorMark;
function mixGradColor(colorLeft, colorRight, relPos){
return {
r: Math.round(colorLeft.r * (1 - relPos) + colorRight.r * relPos),
g: Math.round(colorLeft.g * (1 - relPos) + colorRight.g * relPos),
b: Math.round(colorLeft.b * (1 - relPos) + colorRight.b * relPos)
};
}
let curColor;
if (document.getElementById("iphy_body").classList.contains("iphy_768") || document.getElementById("iphy_body").classList.contains("iphy_600") ){
document.querySelectorAll("#iphy_options_text_container .iphy_skin_tone").forEach((element)=>{
element.style.display = "none";
})
if (colorMark < 0.1){
document.querySelector("#iphy_options_text_container .iphy_skin_tone_1").style.display = "block";
}else if (colorMark < 0.3){
document.querySelector("#iphy_options_text_container .iphy_skin_tone_2").style.display = "block";
}else if (colorMark < 0.5){
document.querySelector("#iphy_options_text_container .iphy_skin_tone_3").style.display = "block";
}else if (colorMark < 0.7){
document.querySelector("#iphy_options_text_container .iphy_skin_tone_4").style.display = "block";
}else if (colorMark < 0.9){
document.querySelector("#iphy_options_text_container .iphy_skin_tone_5").style.display = "block";
}else{
document.querySelector("#iphy_options_text_container .iphy_skin_tone_6").style.display = "block";
}
}
if (colorMark < 0.2){
curColor = mixGradColor(iphy_skintone_colors.veryfair, iphy_skintone_colors.fair, colorMark * 5);
}else if (colorMark < 0.4){
curColor = mixGradColor(iphy_skintone_colors.fair, iphy_skintone_colors.medium, (colorMark - 0.2) * 5);
}else if (colorMark < 0.6){
curColor = mixGradColor(iphy_skintone_colors.medium, iphy_skintone_colors.olive, (colorMark - 0.4) * 5);
}else if (colorMark < 0.8){
curColor = mixGradColor(iphy_skintone_colors.olive, iphy_skintone_colors.brown, (colorMark - 0.6) * 5);
}else{
curColor = mixGradColor(iphy_skintone_colors.brown, iphy_skintone_colors.darkbrown, (colorMark - 0.8) * 5);
}
iphyUpdateAllSkinColorElements(curColor);
sliderMarker.style.backgroundColor = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ")";
}
function iphyUpdateAllSkinColorElements(curColor){
iphySelectedSkinTone = curColor;
document.querySelectorAll(".iphy_skin_tone_background_color").forEach((element)=>{
element.style.backgroundColor = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ")";
})
}
function placeProductPlug() {
const iphyBodyWidth = document.querySelector('#iphy_body').offsetWidth;
const dsrPlugEl = document.querySelector('.iphy_dsr_plug').offsetHeight;
let iphyPlug3 = document.querySelector('.iphy_plug_3');
if ( iphyBodyWidth <= 600) {
let topPos = 0.575 * dsrPlugEl;
iphyPlug3.style.top = 0.575 * dsrPlugEl + 'px';
}
}
var iphyGMPlacesSessionToken = uuidv4();
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function initAutocompleteNew(autocompleteFieldID) {
inputFieldElement = document.getElementById(autocompleteFieldID);
inputFieldElement.addEventListener("keyup", changedPlacesInputHandler);
}
function changedPlacesInputHandler(e){
let inputFieldWidth = e.target.offsetWidth;
const parentIphyResultEl = document.querySelector('.iphy_text_field');
let userInput = e.target.value;
let latLngString = "";
if (latLng != undefined){
if (latLng.lat != undefined && latLng.long != undefined){
//logOnLocalHostFrontEnd("latLng defined, using latLng: ", latLng)
latLngString = "&lat=" + latLng.lat + "&long="+latLng.long;
}else{
latLngString = "&lat=40.7&long=74.0";
//logOnLocalHostFrontEnd("latLng.lat and/or latLng.long not defined, using default New York - latLng: ", latLng)
}
}else{
//logOnLocalHostFrontEnd("latLng not defined, using default New York - latLng: ", latLng)
latLngString = "&lat=40.7&long=74.0";
}
if (userInput.length > 0){
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://invisiblephysical.com/getPlacesAutocomplete?input="+userInput+"&language="+"en"+"&session="+ iphyGMPlacesSessionToken + latLngString);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
let placesObj = JSON.parse(this.responseText);
try {
document.getElementById("iphy_search_results_container").remove();
} catch (e) {
console.log("e:", e);
}
let iphySearchResultsContainer = document.createElement('div');
iphySearchResultsContainer.classList.add('iphy_search_results_container');
iphySearchResultsContainer.id = 'iphy_search_results_container';
iphySearchResultsContainer.style.width = inputFieldWidth + 'px';
parentIphyResultEl.append(iphySearchResultsContainer);
placesObj.predictions.forEach( (place, index) => {
if ( index === placesObj.predictions.length -1) {
return;
}
const iphyResultEl = document.createElement('span');
iphyResultEl.classList.add('iphy_result');
iphyResultEl.innerHTML = place.description;
iphyResultEl.addEventListener('click', () => {
document.getElementById("iphy_location_and_time").innerHTML = place.description;
iphyGetLatLngFromPlaces(place.description)
});
iphySearchResultsContainer.append(iphyResultEl);
});
}
}
xhr.send();
}
}
function removePlacesSelectionWrapper(e){
setTimeout(()=>{
document.getElementById("iphy_search_results_container").remove();
}, 500);
}
function calculateProductRecQuizOne() {
let optionArr = Array.from(document.querySelectorAll(".iphy_option"));
let exposureObj = {
indoor: 0,
outdoor: 0,
partial: 0
}
let skinConcernObj = {
oily: 0,
aging: 0,
hyperpigmented: 0,
dehydrated: 0,
sensitive: 0
}
let final;
optionArr.map((index) => {
if (index.classList.contains("indoor")) {
index.addEventListener("click", () => {
if (index.classList.contains("selected")) {
exposureObj.indoor -= 1;
} else {
exposureObj.indoor += 1;
}
finalResult(exposureObj, skinConcernObj);
})
}
if (index.classList.contains("outdoor")) {
index.addEventListener("click", () => {
if (index.classList.contains("selected")) {
exposureObj.outdoor -= 1;
} else {
exposureObj.outdoor += 1;
}
finalResult(exposureObj, skinConcernObj);
})
}
if (index.classList.contains("partial")) {
index.addEventListener("click", () => {
if (index.classList.contains("selected")) {
exposureObj.partial -= 1;
} else {
exposureObj. partial += 1;
}
finalResult(exposureObj, skinConcernObj);
})
}
if (index.classList.contains("oily")) {
index.addEventListener("click", () => {
if (index.classList.contains("selectedSlideFour")) {
skinConcernObj.oily -= 1;
} else {
skinConcernObj.oily += 1;
}
finalResult(exposureObj, skinConcernObj)
})
}
if (index.classList.contains("aging")) {
index.addEventListener("click", () => {
if (index.classList.contains("selectedSlideFour")) {
skinConcernObj.aging -= 1;
} else {
skinConcernObj.aging += 1;
}
finalResult(exposureObj, skinConcernObj)
})
}
if (index.classList.contains("hyperpigmented")) {
index.addEventListener("click", () => {
if (index.classList.contains("selectedSlideFour")) {
skinConcernObj.hyperpigmented -= 1;
} else {
skinConcernObj.hyperpigmented += 1;
}
finalResult(exposureObj, skinConcernObj)
})
}
if (index.classList.contains("dehydrated")) {
index.addEventListener("click", () => {
if (index.classList.contains("selectedSlideFour")) {
skinConcernObj.dehydrated -= 1;
} else {
skinConcernObj.dehydrated += 1;
}
finalResult(exposureObj, skinConcernObj)
})
}
if (index.classList.contains("sensitive")) {
index.addEventListener("click", () => {
if (index.classList.contains("selectedSlideFour")) {
skinConcernObj.sensitive -= 1;
} else {
skinConcernObj.sensitive += 1;
}
finalResult(exposureObj, skinConcernObj)
})
}
})
}
function finalResult (exposureObj, skinConcernObj) {
let final;
let {indoor, outdoor, partial} = exposureObj;
if (indoor > 0 && outdoor > 0 && partial <= 0) {
final = "partial";
partialProduct(final, skinConcernObj);
//console.log(final);
} else if (indoor > 0 && partial > 0 && outdoor <= 0) {
final = "indoor";
indoorProduct(final, skinConcernObj);
//console.log(final);
} else if (outdoor > 0 && partial > 0 && indoor <= 0) {
final = "outdoor"
outdoorProduct(final, skinConcernObj);
//console.log(final);
} else if (indoor > 0 && partial <= 0 && outdoor <= 0) {
final = "indoor";
indoorProduct(final, skinConcernObj);
//console.log(final);
} else if (outdoor > 0 && indoor <= 0 && partial <= 0) {
final = "outdoor";
outdoorProduct(final, skinConcernObj);
//console.log(final);
} else if (partial > 0 && indoor <= 0 && outdoor <= 0) {
final = "partial";
partialProduct(final, skinConcernObj);
//console.log(final);
} else if (partial > 0 && indoor > 0 && outdoor > 0) {
final = "partial";
partialProduct(final, skinConcernObj);
//console.log(final);
}
}
function indoorProduct (final, skinConcernObj) {
let prodArr = [];
let {oily, aging, hyperpigmented, dehydrated, sensitive} = skinConcernObj;
const skinToneSliderMarker = document.querySelector("#iphy_options_slider_marker");
//let indoorObj = {
// oily: "clearing defense spf30",
// agingOptionOne: "skinperfect primer spf30",
// agingOptionTwo: "dynamic skin recovery spf50",
// hyperpigmented: "powerbright moisturizer spf50",
// dehydrated: "prisma protect spf30",
// sensitive: "invisible physical defense spf30"
//}
let indoorObj = {
oily: "porescreen spf40",
aging: "skinperfect primer spf30",
hyperpigmented: "powerbright moisturizer spf50",
dehydrated: "prisma protect spf30",
sensitive: "porescreen spf40"
}
let sliderPosition = parseInt(getComputedStyle(skinToneSliderMarker).left.slice(0, getComputedStyle(skinToneSliderMarker).left.indexOf("px")));
//console.log("slider position: " + sliderPosition);
if(oily > 0) {
prodArr.push(indoorObj.oily)
//console.log(prodArr)
}
//if(aging > 0 && sliderPosition <= 390) {
// prodArr.push(indoorObj.agingOptionOne)
//console.log(prodArr)
//}
//if(aging > 0 && sliderPosition >= 390) {
// prodArr.push(indoorObj.agingOptionTwo)
//console.log(prodArr)
//}
if(hyperpigmented > 0) {
prodArr.push(indoorObj.hyperpigmented)
//console.log(prodArr)
}
if(dehydrated > 0) {
prodArr.push(indoorObj.dehydrated)
//console.log(prodArr)
}
if(sensitive > 0) {
prodArr.push(indoorObj.sensitive)
//console.log(prodArr)
}
prodReccomendationArr = prodArr.concat();
finalCategory = final;
}
function outdoorProduct (final, skinConcernObj) {
let prodArr = [];
let {oily, aging, hyperpigmented, dehydrated, sensitive} = skinConcernObj;
let outdoorObj = {
oily: "prisma protect spf 30",
aging: "dynamic skin recovery spf50",
hyperpigmented: "powerbright moisturizer spf50",
dehydrated: "dynamic skin recovery spf50",
sensitive: "invisible physical defense spf30"
}
if(oily > 0) {
prodArr.push(outdoorObj.oily)
//console.log(prodArr)
}
if(aging > 0) {
prodArr.push(outdoorObj.aging)
//console.log(prodArr)
}
if(hyperpigmented > 0) {
prodArr.push(outdoorObj.hyperpigmented)
//if(!prodArr.includes("solar defense booster spf50")) {
// prodArr.push(outdoorObj.hyperpigmented)
//}
//console.log(prodArr)
}
if(dehydrated > 0) {
prodArr.push(outdoorObj.dehydrated)
//if(!prodArr.includes("solar defense booster spf50")) {
// prodArr.push(outdoorObj.dehydrated)
//}
//console.log(prodArr)
}
if(sensitive > 0) {
prodArr.push(outdoorObj.sensitive)
// console.log(prodArr)
}
prodReccomendationArr = prodArr.concat();
//console.log(prodArr)
finalCategory = final;
}
function partialProduct (final, skinConcernObj) {
let prodArr = [];
let {oily, aging, hyperpigmented, dehydrated, sensitive} = skinConcernObj;
let partialObj = {
oily: "porescreen spf40",
aging: "dynamic skin recovery spf50",
hyperpigmented: "powerbright moisturizer spf50",
dehydrated: "prisma protect spf30",
sensitive: "porescreen spf40"
}
if(oily > 0) {
prodArr.push(partialObj.oily)
//console.log(prodArr)
}
if(aging > 0) {
prodArr.push(partialObj.aging)
//console.log(prodArr)
}
if(hyperpigmented > 0) {
prodArr.push(partialObj.hyperpigmented)
//console.log(prodArr)
}
if(dehydrated > 0) {
if(!prodArr.includes("invisible physical defense spf30")) {
prodArr.push(partialObj.dehydrated)
}
//console.log(prodArr)
}
if(sensitive > 0) {
if(!prodArr.includes("invisible physical defense spf30")) {
prodArr.push(partialObj.sensitive)
}
//console.log(prodArr)
}
prodReccomendationArr = prodArr.concat();
finalCategory = final;
}
async function updateGdprAndEndPoints(locObj, showGdpr=false, productArr) {
const { country_code } = locObj;
if (typeof locObj.country_code == "string"){
if (locObj.country_code != ""){
window.iphyUserCountry = locObj.country_code;
}else{
window.iphyUserCountry = "US"
}
}else{
window.iphyUserCountry = "US"
}
logOnLocalHostFrontEnd("gdrpData: ", locObj);
if (locObj.region == "EU"){
if ("https://imb-backend.herokuapp.com" == "https://imb-backend.herokuapp.com"){
window.iphy_backendToUse = "https://imb-backend-eu.herokuapp.com";
}
}
if (locObj.country_code=="CA"){
if ("https://imb-backend.herokuapp.com" == "https://imb-backend.herokuapp.com" ){
window.iphy_backendToUse = "https://imb-backend-ca.herokuapp.com";
}
}
//console.log(locObj);
iphySendGA("main flow","backend used - " + window.iphy_backendToUse);
// console.log("setting up ZenDesk");
setUpZendesk();
/*
iphyGetBreezometerResults().then((res)=>{
logOnLocalHostFrontEnd("breezometer response: ",res)
iphy_generateData(res);
}).catch((err)=>{
console.log("error in getting breezometer results - ", err)
})
*/
window.iphy_pendingBackendUpdate = false;
}
function addEventListenerOnOptions(element) {
// console.log(element);
const iphyRows = document.querySelectorAll(element);
let stepTwoBtn = document.querySelector('.iphy_step_two_btn');
let stepFiveBtn = document.querySelector('.iphy_step_five_btn');
stepTwoBtn.disabled = true;
stepTwoBtn.style.opacity = '.5';
stepFiveBtn.disabled = true;
stepFiveBtn.style.opacity = '.5';
iphyRows.forEach(row => row.addEventListener('click', highlightOptions));
function highlightOptions(e) {
let selectedBtns = [];
let selectedBtnsSlideFour = [];
if ( !e.target.classList.contains('selected') && e.target.parentElement.id !== "iphy_row_slide_4") {
e.target.classList.add('selected');
selectedBtns = document.querySelectorAll('.selected');
} else if(!e.target.classList.contains('selectedSlideFour') && e.target.parentElement.id === "iphy_row_slide_4"){
e.target.classList.add('selectedSlideFour');
selectedBtnsSlideFour = document.querySelectorAll('.selectedSlideFour');
} else if (e.target.classList.contains('selectedSlideFour') && e.target.parentElement.id === "iphy_row_slide_4") {
e.target.classList.remove('selectedSlideFour');
selectedBtnsSlideFour = document.querySelectorAll('.selectedSlideFour')
} else if (e.target.classList.contains('selected') && e.target.parentElement.id !== "iphy_row_slide_4") {
e.target.classList.remove('selected');
selectedBtns = document.querySelectorAll('.selected');
stepTwoBtn.style.opacity = '.5';
}
if (selectedBtns.length > 0) {
stepTwoBtn.disabled = false;
stepTwoBtn.style.opacity = '1';
} else {
stepTwoBtn.disabled = true;
stepTwoBtn.style.opacity = '.5';
}
if (selectedBtnsSlideFour.length > 0) {
stepFiveBtn.disabled = false;
stepFiveBtn.style.opacity = '1';
} else {
stepFiveBtn.disabled = true;
stepFiveBtn.style.opacity = '.5';
}
}
}
addEventListenerOnOptions('.iphy_row');
addEventListenerOnOptions('.iphy_double_option_row');
addEventListenerOnOptions('.iphy_single_option_row');
function stylingPL(lang) {
console.log('LANGUAGE:', lang);
if (lang === "pl") {
//console.log(window.innerWidth);
document.querySelector('.iphy_plug_1').style.width = '80px';
document.querySelector('.iphy_plug_2').style.right = "4%";
document.querySelector('.iphy_plug_2').style.width = "90px";
document.querySelector('.iphy_plug_3').style.left = '-8px';
document.querySelector('.iphy_plug_3').style.width = '90px';
document.querySelector('.iphy_plug_4').style.width = '90px';
}
}
let currSlideIndex = 0;
function handleProductCarousel(direction) {
// select carousel container and get its width
const iphyCarouselContainer = document.querySelector("#iphy_product_carousel_slide_container");
const carouselWidth = iphyCarouselContainer.clientWidth;
// select carousel cards and get width of 1 card
const carouselCardsArr = document.querySelectorAll('.iphy_product_carousel_card');
const carouselCardWidth = carouselCardsArr[0].clientWidth;
if (direction === 'right') {
currSlideIndex++;
} else {
currSlideIndex--;
}
// scroll carousel
iphyCarouselContainer.scrollLeft = (carouselCardWidth + 25) * currSlideIndex;
// hide / show arrows
const leftArrow = document.querySelector('#iphy_carousel_arrow_left');
const rightArrow = document.querySelector('#iphy_carousel_arrow_right');
if (currSlideIndex === 0) {
leftArrow.style.display = 'none';
} else if (currSlideIndex === carouselCardsArr.length - 1) {
rightArrow.style.display = 'none';
} else if (currSlideIndex === 1) {
leftArrow.style.display = 'block';
} else if(currSlideIndex === carouselCardsArr.length - 2) {
rightArrow.style.display = 'block';
}
}
function handleProductCarouselResize() {
// select carousel container and get its width
const iphyCarouselContainer = document.querySelector("#iphy_product_carousel_slide_container");
const carouselWidth = iphyCarouselContainer.clientWidth;
// select carousel cards and get width of 1 card
const carouselCardsArr = document.querySelectorAll('.iphy_product_carousel_card');
const carouselCardWidth = carouselCardsArr[0].clientWidth;
// scroll carousel
iphyCarouselContainer.scrollLeft = (carouselCardWidth + 25) * currSlideIndex;
}
window.addEventListener('resize', handleProductCarouselResize);
calculateProductRecQuizOne()
let iphyUsedLanguageCode;
let iphySessionTimeString = (new Date()).getTime();
window.iphy_backendToUse = "https://imb-backend.herokuapp.com";
window.iphyChatStatus = "offline";
let reportError = (messageObj) => {
var xhr = new XMLHttpRequest()
messageObj.value += "\nuuid: "+ iphyCustomUID;
messageObj.value += "\nFrontend: https://spf-widget-production.herokuapp.com";
messageObj.value += "\nBackend: "+window.iphy_backendToUse;
let connectionInfoString = "";
try {
let connectionInfo = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
connectionInfoString += "\nConnection downlink: " + connectionInfo.downlink;
connectionInfoString += "\nConnection effType: " + connectionInfo.effectiveType;
connectionInfoString += "\nConnection rtt: " + connectionInfo.rtt;
connectionInfoString += "\nConnection saveData: " + connectionInfo.saveData;
} catch(err){
}
messageObj.value += connectionInfoString;
xhr.open('POST', 'https://spf-widget-production.herokuapp.com' + "/report-error" )
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function(){
if (this.readyState == 4){
if (this.status != "200"){
}
}
}
xhr.send(JSON.stringify(messageObj));
}
let getSpecs = ()=>{
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://spf-widget-production.herokuapp.com/getSpecs" );
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onreadystatechange = function(){
if(this.readyState == 4){
let agentData = JSON.parse(this.responseText);
//logOnLocalHostFrontEnd("userAgent data: ",agentData);
iphyBrowser = agentData.family + " " + agentData.major;
iphyOS = agentData.os.family + " " + agentData.os.major;
}
}
xhr.send();
}
getSpecs();
let updateClassesDueWidth = () =>{
document.getElementById("iphy_body").className = "";
//console.log(document.getElementById("iphy_body").offsetWidth)
if ( document.getElementById("iphy_body").offsetWidth <= 600) {
document.getElementById("iphy_body").classList.add("iphy_600");
if (document.getElementById("iphy_body").offsetWidth <= 420){
document.getElementById("iphy_body").classList.add("iphy_420");
}
if (document.getElementById("iphy_body").offsetWidth <= 350){
document.getElementById("iphy_body").classList.add("iphy_350");
}
} else if (document.getElementById("iphy_body").offsetWidth <= 768) {
document.getElementById("iphy_body").classList.add("iphy_768");
} else if ( document.getElementById("iphy_body").offsetWidth <= 992) {
document.getElementById("iphy_body").classList.add("iphy_992");
} else if ( document.getElementById("iphy_body").offsetWidth <= 1200) {
document.getElementById("iphy_body").classList.add("iphy_1200");
}
}
// ------------------------------------------
// START OF APP
// ------------------------------------------
getTextForLanguage((languageData)=>{
logOnLocalHostFrontEnd('LANGUAGE DATA: ', languageData);
let xhr = new XMLHttpRequest();
xhr.open("GET","https://gdpr.facemapping.me/get_country_gdpr/?lang_code="+iphyUsedLanguageCode)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function(){
if(this.readyState == 4){
let response;
try {
response = JSON.parse(this.responseText);
} catch(err) {
console.log("could not parse json response - ",err);
response = this.responseText;
}
updateGdprAndEndPoints(response,true);
}
}
xhr.send();
languageToUserSettings(languageData, ()=>{
});
iphyPage('iphy_landing_page');
// switch pages here
if ( window.iphy_onlyQuiz ) {
let parallax = document.querySelector("#iphy_parallax_page");
parallax.classList.add('spf_quiz_only');
iphyPage('iphy_parallax_page');
//console.log("done")
}
// extract "spf" text and make it bold
const carouselProductTitles = document.querySelectorAll('.iphy_carousel_card_product_title');
carouselProductTitles.forEach(title => {
const text = title.textContent;
if (text.includes('spf')) {
const spfNumber = text.slice(-2)
const newText = text.replace(/(spf \d+)/g, `spf ${spfNumber}`);
title.innerHTML = newText;
}
});
});
let iphyResizeTimer;
let iphyContentResizeTimer;
updateClassesDueWidth();
positionCircles();
document.querySelectorAll('.iphy_skin_tone').forEach(elem => {
elem.addEventListener('click', highLightSkinTone);
});
addEventListenerToSlideBtns('.iphy_next_btn', moveSliderForward);
addEventListenerToSlideBtns('.iphy_back_btn', moveSliderBackwards);
//document.querySelector('.iphy_btm_banner_btn').addEventListener('click', moveSliderForward);
document.querySelectorAll('.iphy_btm_banner_btn').forEach(elem => {
elem.addEventListener('click', moveSliderForward);
});
initAutocompleteNew('searchTextField');
window.addEventListener('load', function() {
if (document.getElementById("iphy_body").offsetWidth > 800){
//let phoneCont = document.querySelector(".element_iphy_cta_dropdown_2 .iphy_iphone");
//phoneCont.style.height = Math.round(phoneCont.offsetWidth /586 * 297 ) + "px";
//console.log(phoneCont.offsetWidth /586 * 297)
}else{
//let phoneCont = document.querySelector(".element_iphy_cta_dropdown_2 .iphy_iphone_mobile");
//console.log(phoneCont, phoneCont.offsetWidth);
//phoneCont.style.height = Math.round(phoneCont.offsetWidth /900 * 1784 ) + "px";
}
});
window.addEventListener('resize', function() {
document.querySelector('.iphy_uv_meter_foreground').style.visibility = 'hidden'
updateClassesDueWidth();
resizeProductPlugs();
//if (document.getElementById("iphy_body").offsetWidth > 800){
// let phoneCont = document.querySelector(".element_iphy_cta_dropdown_2 .iphy_iphone");
// phoneCont.style.height = Math.round(phoneCont.offsetWidth /586 * 297 ) + "px";
//}else{
// let phoneCont = document.querySelector(".element_iphy_cta_dropdown_2 .iphy_iphone_mobile");
// console.log(phoneCont, phoneCont.offsetWidth);
// phoneCont.style.height = Math.round(phoneCont.offsetWidth /900 * 1784 ) + "px";
//}
clearTimeout(iphyResizeTimer);
iphyResizeTimer = setTimeout(() => {
setWidthUVMeters();
}, 500);
let iphyBodySize = document.querySelector("#iphy_body");
let protectionPlanSize = document.querySelector(".iphy_slider_container_four");
if (iphyBodySize.classList.contains("iphy_992")) {
if (prodReccomendationArr.length === 1) {
protectionPlanSize.style.height = "1400px";
} else if (prodReccomendationArr.length === 2 || prodReccomendationArr.length === 3) {
protectionPlanSize.style.height = "1800px";
} else {
protectionPlanSize.style.height = "2200px";
}
} else if (iphyBodySize.classList.contains("iphy_600")) {
console.log("in 600")
if (prodReccomendationArr.length === 2) {
protectionPlanSize.style.height = "2000px";
} else if (prodReccomendationArr.length == 3) {
protectionPlanSize.style.height = "2600px";
} else if (prodReccomendationArr.length == 4) {
protectionPlanSize.style.height = "3200px";
} else if (prodReccomendationArr.length === 5) {
protectionPlanSize.style.height = "3600px";
} else {
protectionPlanSize.style.height = "4100px";
}
} else if(iphyBodySize.classList.contains("iphy_1200")) {
if (prodReccomendationArr.length === 1) {
protectionPlanSize.style.height = "1400px";
} else if (prodReccomendationArr.length === 2 || prodReccomendationArr.length === 3) {
protectionPlanSize.style.height = "1800px";
} else {
protectionPlanSize.style.height = "2200px";
}
} else {
if (prodReccomendationArr.length === 2) {
protectionPlanSize.style.height = "1400px";
} else {
protectionPlanSize.style.height = "1800px";
}
}
});
sliderLoading();