/**
* @package   Gridbox
* @author    Balbooa http://www.balbooa.com/
* @copyright Copyright @ Balbooa
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

app.setEndPoint = function(){
    $g('.notification-placeholder').hide();
    $g('.notification-backdrop').addClass('visible-notification-backdrop');
    window.parent.document.body.classList.add('ba-set-end-point');
    document.body.classList.add('ba-set-end-point-iframe');
}

function returnPointItem(event)
{
    const pageY = event.clientY
    const pageX = event.clientX;
    const str = '.ba-wrapper:not(.ba-lightbox):not(.ba-overlay-section):not(.tabs-content-wrapper) > .ba-section';
    const row = ' > .ba-section-items > .ba-row-wrapper > .ba-row';
    const nested = ' > .column-wrapper > .ba-grid-column-wrapper > .ba-grid-column > .ba-row-wrapper > .ba-row';
    let section = document.querySelectorAll(str + row + nested);
    let item = getPointItem(section, pageX, pageY)
    if (!item) {
        section = document.querySelectorAll(str + row);
        item = getPointItem(section, pageX, pageY)
    }
    if (!item) {
        section = document.querySelectorAll(str);
        item = getPointItem(section, pageX, pageY)
    }

    return item;
}

function getPointItem(section, pageX, pageY)
{
    let item = null;
    for (let i = 0; i < section.length; i++) {
        let rect = section[i].getBoundingClientRect()
        if (rect.top < pageY && rect.bottom > pageY
            && rect.left < pageX && rect.right > pageX) {
            item = section[i];
            break;
        }
    }

    return item;
}

$g('.notification-backdrop').on('mousedown', function(event){
    event.stopPropagation();
}).on('click', function(event){
    const item = returnPointItem(event);
    if (item) {
        if (window.parent.app.edit.init) {
            window.parent.app.edit.init.target = item.id;
            app['init'+window.parent.app.edit.type](window.parent.app.edit, app.edit);
        }
        window.parent.fontBtn.value = item.id;
        top.$g(window.parent.fontBtn).trigger('change');
        window.parent.app.addHistory();
    }
    window.parent.document.body.classList.remove('ba-set-end-point');
    document.body.classList.remove('ba-set-end-point-iframe');
    $g(this).removeClass('visible-notification-backdrop');
}).on('mousemove', function(event){
    const item = returnPointItem(event);
    if (item) {
        const rect = item.getBoundingClientRect();
        const css = $g.extend(true, {}, rect);
        css.width = css.width - 10;
        delete(css.height);
        delete(css.toJSON);
        $g('.notification-placeholder').show().css(css);
    } else {
        $g('.notification-placeholder').hide();
    }
});

app.setEndPoint();