window.forecastTab = Object.assign({}, window.forecastTab, {  
    forecastMaps: {  
        styleHandle: function(feature, context){
            // get props from hideout
	    const {bounds, colorscale, style, colorProp} = context.props.hideout;
            // get value the determines the color
            const value = feature.properties[colorProp];
	    for (let i = 0; i < bounds.length; ++i) {
		if (value > bounds[i]) {
	            // set the fill color according to the class
		    style.fillColor = colorscale[i];
		}
	    }
            return style;
        },
	pointToLayer: function(feature, latlng, context){
            const {min, max, colorscale, circleOptions, colorProp} = context.props.hideout;
            // set color based on color prop.
            circleOptions.fillColor = feature.properties[colorProp];
            // sender a simple circle marker.
            return L.circleMarker(latlng, circleOptions);
        },
	bindTooltip: function(feature, layer, context) {
            const props = feature.properties;
            // delete props.cluster;
            layer.bindTooltip(JSON.stringify(props.value), { opacity: 1.0 })
        }
    },
    wasMaps: {
        styleHandle: function(feature, context){
            // get props from hideout
	    const {bounds, colorscale, style, colorProp} = context.props.hideout;
            // get value the determines the color
            const value = feature.properties[colorProp];
	    style.fillColor = colorscale[value];
            return style;
        },
    }
});

window.evaluationTab = Object.assign({}, window.evaluationTab, {  
    evaluationMaps: {  
	pointToLayer: function(feature, latlng, context){
            const {circleOptions} = context.props.hideout;
            // sender a simple circle marker.
            return L.circleMarker(latlng, circleOptions);
        },
    }
});

window.observationsTab = Object.assign({}, window.observationsTab, {  
    observationsMaps: {  
	pointToLayer: function(feature, latlng, context){
            const {colorscale, circleOptions, colorProp} = context.props.hideout;
            const value = feature.properties[colorProp];
            circleOptions.fillColor = colorscale[value];
            // sender a simple circle marker.
            return L.circleMarker(latlng, circleOptions);
        },
    }
});

$(document).ready(function () {
    $(document).on('click', ".leaflet-popup-close-button", function () {
	elements = document.getElementsByClassName("leaflet-popup-close-button");
	
	for (let i = 0; i < elements.length; i++) {
	    var elem = elements[i];
	    // elem.replaceWith(elem.clone());
	    alert(elem.innerHTML);
	}

	alert('Closing!');
        elements[0].close();
    });
});

// Add logos for the animated gifs
$(document).ready(function () {
	$(document).on('click', "#slider-graph", function () {
		const logos = document.getElementById('logos');
		if(!logos) {
			var img = new Image();
			img.src = './assets/images/logoline.png';
			img.style.position = 'absolute';
			img.style.width = '40rem';
			img.style.height = '5rem';
			img.style.top = '0';
			img.style.left = '23rem';
			img.style.zIndex = '999';
			img.setAttribute('id','logos');
			img.style.display = 'none';

			// Get the element to overlay the image on
			var div = document.querySelectorAll('.leaflet-map-pane')[0];

			// Append the image to the element
			div.appendChild(img);
		}
	});
});

// MAKE FULLSCREEN ICON SMALLER WHEN APP IS FULLSCREEN
function changeFullscreenIcon() {
       const isFullscreen = window.innerWidth === screen.width && window.innerHeight === screen.height;
       const button = document.getElementById('fullscreen-tab'); 
       if (isFullscreen) {
           button.classList.remove('small');
       } else {
           button.classList.add('small');
       }
}

// SEND FULLSCREEN REQUEST TO PARENT WINDOW
$(document).ready(function () {
    $(document).on('click', "#fullscreen-tab", function () {
	parent.postMessage('fullscreen', '*');
	changeFullscreenIcon();
	})	
});

// DETECT IFRAME AND REMOVE FULLSCREEN BUTTON
$(window).on('load', function removeFullscreen () {
    const tab = document.getElementById('fullscreen-tab');
    if (tab != null) {
	if (window.self === window.top){
	    tab.style.visibility = "hidden";
	}
    } else {
	setTimeout(removeFullscreen, 5); 
    }
});

// Move datepicker above the time series area
$(document).ready(function () {
	$(document).on('click', ".SingleDatePickerInput_clearDate, .SingleDatePicker", function moveDatePicker () {
		const element = document.getElementsByClassName('DayPicker')[0];
		//we still want the menu to go below on eval/vis for modis
		const evalVis = document.getElementById('eval-date');
		if (evalVis != null) {
		    return
		}else if (element != null) {
		    element.style.position = 'absolute';
		    element.style.bottom = '78px';
		}else {
		    setTimeout(moveDatePicker, 20);
		};
	});
});

// COLLAPSE NAVBAR HAMBURGER RESIZE LARGER
$(window).on('resize', function () {
  if (window.innerWidth > 1045) $('.navbar-collapse').removeClass('show')
})

$(document).ready(function () {
    $(document).on('click', ".SingleDatePickerInput_clearDate", function() {
	var date = document.getElementById('date');
	//ADD SPACES AT APPROPRIATE AREAS FOR DATE SELECTOR
	date.addEventListener('input', function(e) {
	    this.type = 'text';
	    var input = this.value;

	    //CREATE FUNCTION TO ALLOW DELETION OF SPACES
	    date.onkeydown = function(event) {
		var key = event.keyCode || event.charCode;
		inputText = String(input);
		if(key == 8 && (input.length==2 || input.length==6)){
		    this.value = inputText.substring(0, inputText.length);
		    return
		}
	    };

	    //ESCAPE FUNCTION IF FINAL CHARACTER IS ENTERED
	    if(input.length == 11) return;
	    var values = input.split(' ');
	    // ADD FUNCTION TO ADD SPACES
	    var output = values.map(function(v, i) {
		// ADD SPACE AFTER FIRST TWO CHARACTERS 
		if (v.length == 2 && i < 1){
		    return v =  v + ' ';
		    // ADD SPACE AFTER SECOND THREE CHARACTERS 
		}else if (v.length == 3 && i < 2){
		    return v = v + ' ';
		} else {
		    return v
		}
	    });
	    this.value = output.join('').substr(0, 11);
	});
    });
});


//================== Stats table carets ===============================================
// The aeronet stats table changes the position/index of the regions when they
// are clicked, so we cannot easily assign a class to the regions that will maintain on click,
// so we must remove the carets on click, and then add them back after the table has finished

// changing it's state

// ADD FUNCTION TO WAIT FOR TABLE TO FINISH CHANGING
function waitForMutation(selector, func) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        };
        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
		// console.log(mutations);
		func(mutations);
	    }
        });
        observer.observe(document.body, {
            childList: true,
            subtree: true,
	    attributeOldValue: true, 
	    characterDataOldValue: true
        });
    });
}

//FIND THE REGIONS TO REMOVE THE CARETS BEFORE FLIPPING THEM
function targetRegions(mutations) {
    //Carets will populate in the wrong rows after click, so we must remove them
    for (const element of mutations) {
	if (['Mediterranean','NAfrica', 'MiddleEast'].includes(element.oldValue)) {
	    //GET ELEMENTS PARENT NODE 2 ABOVE AS IT CONTAINS THE TARGET CLASS
	    const target = element.target.parentNode.parentNode;
	    target.classList.remove('table_caret_up');
	    target.classList.remove('table_caret_down');
	};
    }
    // Now add the carets back in where appropriate
    flipCarets();
}

//CREATE FUNCTION TO FIND REGIONS AND FLIP CARETS AS NEEDED
function flipCarets() {
    var areas = "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast')";
    $(areas).addClass('table_caret_down');
    //Each table has the four regions. Split the returned areas into tables, and then address caret flips
    for(var i = 0; i < ($(areas).length/4); i++){
	var medIndex = parseInt($("td:contains('Mediterranean')").eq(i).attr('data-dash-row'));
	var nafricaIndex = parseInt($("td:contains('NAfrica')").eq(i).attr('data-dash-row'));
	var middleEastIndex = parseInt($("td:contains('MiddleEast')").eq(i).attr('data-dash-row'));
	var totalIndex = parseInt($("td:contains('Total')").eq(i).attr('data-dash-row'));
	//for each table, check if the caret should be flipped
	//if the next region is not at the next index, the dropdown is open 
	//trigger the caret to be flipped
	if (medIndex !== 1) {
	    $("td:contains('Europe')").eq(i).addClass('table_caret_up');
	};
	if ((medIndex + 1) !== middleEastIndex) {
	    $("td:contains('Mediterranean')").eq(i).addClass('table_caret_up');
	};
	if ((middleEastIndex + 1) !== nafricaIndex) {
	    $("td:contains('MiddleEast')").eq(i).addClass('table_caret_up');
	};
	if ((nafricaIndex + 1) !== totalIndex) {
	    $("td:contains('NAfrica')").eq(i).addClass('table_caret_up');
	};
    };
};

//ADD FUNCTION TO WAIT FOR CLICKS ON AREAS THAT SHOULD TRIGGER CARET FLIPS
$(document).ready(function () {
    $(document).on('click', "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast'), #scores-apply, #evaluation-tab", function () {
	waitForMutation('td.dash-cell.column-0', targetRegions);
    })
})
//================== Stats table carets END ===============================================


//==================Functions to resize colorbar ======================

function setWidthForColorbars(nothing) {
    const colorbars = document.querySelectorAll('.leaflet-control-colorbar');
    colorbars.forEach(colorbar => {
	const info = document.querySelector('.info').offsetWidth;
	colorbar.style.maxWidth = info.toString() + 'px';
    });
}

$(document).ready(function () {
    $(document).on('click', "#models-apply, .DayPicker, .SingleDatePickerInput_clearDate", function () {
	setTimeout(tiltValues, 500);
	setTimeout(setWidthForColorbars, 500);
    })
})

$(document).ready(function () {
    setTimeout(setWidthForColorbars, 1500);
});
//==================END Funcfions to resize colorbar ==================

// //================= Function to clear datepicker without resetting =================================
$(document).ready(function () {
    $(document).on('click', "#clear_button", function () {
	const date = document.getElementById('date');
	date.focus();
	date.click();
	date.value = '';
    })
})

