var timeoutClear
var cropperElement

$(".js-pixabay-trigger").on("click", function() {
	cropperElement = $(this).closest(".image-cropper")
	$("#modal-pixabay").modal("show")
})

$(".js-pixabay-search-input").bind("input propertychange", function() {
	
	var keyword = $(this).val()
	clearTimeout(timeoutClear)
  timeoutClear = setTimeout(function () {

    if (keyword) {	
			$(".js-pixabay-search-input").closest('.form-group').waitMe({effect : 'win8_linear'})
			fetchPixabay(encodeURI(keyword))
    }
  }, 1000);
})



function fetchPixabay(q) {
	axios.get("https://pixabay.com/api/?key=5548477-1513108f42ec243456e0fad6f&response_group=high_resolution&q=" + q + "&orientation=horizontal&safesearch=true&image_type=photo")
		.then(response => {
			var hits = response.data.hits
			$(".js-pixabay-result").empty()
			for(hit of hits) {
				$(".js-pixabay-result").append(`<img style='height: ${hit.previewHeight}px; width: ${hit.previewWidth}px;' class='pixabay-image' alt='Bootstrap Image Preview' src='${hit.previewURL}' data-url='${hit.fullHDURL}'/>`)
			}
			if ($(".js-pixabay-result").masonry().length > -1) {
				$(".js-pixabay-result").masonry('destroy')
			}
			
			$(".js-pixabay-result").masonry({
        itemSelector: '.pixabay-image',
        isFitWidth: true,
        gutter: 0
      });
			$(".js-pixabay-search-input").closest('.form-group').waitMe('hide')
		})
		.catch(error => {
			console.log(error)
		})
}

$(document).on("click", ".pixabay-image", function() {
	var url = $(this).attr("data-url")
	cropperElement.cropit('imageSrc', url)
	$("#modal-pixabay").modal("hide")
})

$('.js-modal-pixabay').on('shown.bs.modal', function() {
	$('body').addClass('modal-open')
})

$('.js-modal-pixabay').on('hidden.bs.modal', function() {
	$('body').removeClass('modal-open')
})