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();
    });
});

// Remove yellow from rc-slider-mark-text when moved
$(document).ready(function () {
    $(document).on('click','.rc-slider' , function () {
		const handle = document.getElementsByClassName('rc-slider-handle')[0];
		const text = document.getElementsByClassName('rc-slider-mark-text')[0];
		if (handle.style.left == '100%'){
			text.style.color = '#999';
		}else{
			text.style.color = '#F1B545';
		}
	})
})
		

// 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);
		}
	});
});

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

// 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];
		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() {
		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);
	});
    });
});

function waitForElm(selector) {
    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));
		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');
		    };
		}
	    }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true,
	    attributes: true, 
	    attributeFilter: ['class', 'text'],
	    attributeOldValue: true, 
	    characterData: true, 
	    characterDataOldValue: true

        });
    });
}
// 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 INITIAL CARETS TO STATS TABLES
$(document).ready(function () {
    $(document).on('click', "#scores-apply, #evaluation-tab", function () {
	var areas = "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast')";
	waitForElm('.column-0').then(() => {
	    $(areas).addClass('table_caret_down');
	});
    })
})

//GET CURRENT DIRECTI0N OF CARET OF TABLE REGION ELEMENTS AND RETURN A LIST 
function getClasses(elements) {
    len = $(elements).length
    results = [] 
    for( var i = 0; i < len; i++) {
	var temp = $(elements)[i];
	if(temp.classList.contains('table_caret_up') == true){
	    var caret = 'table_caret_up';
	}else {
	    var caret = 'table_caret_down';
	}
	results.push(caret);
    };
    return results
}

// ADD THE CARETS BACK AFTER THE TABLE HAS BEEN CLEARED
function addClasses(areas, results){
    for (var i = 0; i < results.length; i++) {
	var element = $(areas).eq(i);
	element.addClass(results[i]);
    }
}

//CHANGE CARET DIRECTIONS ACCORDING TO CLICKS
$(document).ready(function () {
    var areas = "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast')";
    $(document).on('click', areas, function resetStyles () {
	elements = getClasses(areas);
	$(".table_caret_down").removeClass('table_caret_down');
	$(".table_caret_up").removeClass(".table_caret_up");
	var origLength = $('tr').length;
	setTimeout(() => {
	    var newLength = $('tr').length;
	    if (origLength < newLength) {
		addClasses(areas, elements);
		$(this).removeClass('table_caret_down');
		$(this).addClass('table_caret_up');
	    }else if (newLength < origLength) {
		addClasses(areas, results);
		$(this).removeClass('table_caret_up');
		$(this).addClass('table_caret_down');
	    };
	}, 300);	
    })
})


// //CHANGE CARET DIRECTIONS ACCORDING TO CLICKS
// $(document).ready(function () {
//     var areas = "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast')";
//     $(document).on('click', areas, function resetStyles () {
// 	elements = getClasses(areas);
// 	$(".table_caret_down").removeClass('table_caret_down');
// 	$(".table_caret_up").removeClass(".table_caret_up");
// 	var origLength = $('tr').length;
// 	setTimeout(() => {
// 	    var newLength = $('tr').length;
// 	    if (origLength < newLength) {
// 		addClasses(areas, elements);
// 		$(this).removeClass('table_caret_down');
// 		$(this).addClass('table_caret_up');
// 	    }else if (newLength < origLength) {
// 		addClasses(areas, results);
// 		$(this).removeClass('table_caret_up');
// 		$(this).addClass('table_caret_down');
// 	    };
// 	}, 300);	
//     })
// })
//
//
