var popup_backdrop;

function popup_wrap_window(element)
{
	if (element.hasClass('popup_processed'))
		return;

	element.addClass('popup_processed');

	var item_head;
	if (item_head = jQuery('.header', element))
	{
		// adding 'close' button
		popup_set_header(element, item_head.html());
		item_head.prepend();

		element.addClass("ui-widget-content");
		element.draggable({handle: '.header'});
	}
}

// Set window header for popup
// Returns false if popup doesn't have header div or already has a close button
function popup_set_header(element, header_text)
{
	if (typeof close === 'undefined')
		close = true;

	var item_head = jQuery('.header', element);
	if (!item_head) {
		return false;
	}

	item_head.html('<h5 class="modal-title popup-js-header">' + header_text + '</h5>');

	if(item_head.parent().find('.close').length === 0) {
		item_head.after('<div><a class="close" href="#" onclick="popup_hide(jQuery(this).parents(\'.popup_window\')); return false" style=""><ion-icon name="close-outline"></ion-icon></a></div>');
	}

	return true;
}

function popup_show_centered(element)
{
	popup_wrap_window(element);
	element.trigger('show');

	element.css('position', 'fixed');
	element.removeClass('d-none');

    if(jQuery(window).width() < 575) {
        element.css("width", jQuery(window).width() - 20 + "px");
    } else {
        element.css("left", (jQuery(window).width() - element.width())/2 + jQuery(window).scrollLeft() + "px");
    }
	element.trigger('shown');
}

function popup_hide(element)
{
	element = jQuery(element);
	element.trigger('hide').addClass('d-none');
	jQuery('body').removeClass('modal-open');
	if (element.hasClass('popup_window_modal'))
	{
		element.removeClass('popup_window_modal');
		if (popup_backdrop)
			popup_backdrop.remove();
		popup_backdrop = null;
		popup_modal_current = null;
	}
	popup_escape_key(element);
	element.trigger('hidden')
}

function popup_show_modal(element)
{
	if (popup_modal_current)
		popup_hide(popup_modal_current);
	popup_modal_current = element;
	popup_backdrop = jQuery('<div class="modal-backdrop fade show" style="z-index: 1100" />').appendTo(document.body);
	popup_backdrop.click(function () { popup_hide(popup_modal_current); });
	jQuery('body').addClass('modal-open');

	popup_show_centered(element);
	element.addClass('popup_window_modal');
	popup_escape_key(element);
}

function popup_escape_key(element)
{
	if (!element.hasClass('d-none'))
	{
		jQuery(document).bind('keyup.popup_window', function ( e ) {
			if ( e.which == 27 ) {
				popup_hide(popup_modal_current);
			}
		});
	} else {
		jQuery(document).unbind('keyup.popup_window')
	}
}

jQuery(function(){
	popup_modal_current = null;
	popup_backdrop = null;

	jQuery('.popup_window').each(function() {
		popup_wrap_window(jQuery(this));
	});

	jQuery('body').delegate('[data-controls-popup]', 'click', function (e) {
		e.preventDefault();
		popup_show_modal(jq_$(jQuery(this).attr('data-controls-popup')));
	});
});
