function arrangeGrids() {
    let $ = require('jquery');
    let grids = $(".grid3");
    for (let i = 0, l = grids.length; i < l; i++) {
        let grid = grids[i];
        arrangeGrid(grid, 3);
    }
}

function arrangeGrid(grid: HTMLElement, width: number) {
    let children = grid.children;
    for (let i = 0, l = children.length; i < l; i++) {
        if (0 === i) {
            placeZero(children[i] as HTMLElement);
            continue;
        }
        let sibling = children[i - 1];
        let child = children[i];

        if (0 === (i % width)) {
            let rowBegin = children[i - width];
            placeUnder(rowBegin as HTMLElement, child as HTMLElement, 15);
        } else {
            placeRight(sibling as HTMLElement, child as HTMLElement, 15);
        }
    }
}

function placeZero(anchor: HTMLElement) {
    let posX = anchor.offsetLeft;
    let posY = anchor.offsetTop;
    anchor.style.left = `${posX}px`
    anchor.style.top = `${posY}px`;
}

function placeRight(anchor: HTMLElement, satellite: HTMLElement, spacing: number) {
    let posX = anchor.offsetLeft;
    let posY = anchor.offsetTop;
    let finalX = posX + anchor.clientWidth + spacing;
    let finalY = posY;

    satellite.style.left = `${finalX}px`
    satellite.style.top = `${finalY}px`;

    let childX = finalX + satellite.clientWidth - satellite.parentElement.offsetLeft;
    if (childX > satellite.parentElement.clientWidth) {
        console.log(`setting parent width to ${childX}`)
        satellite.parentElement.style.width = `${childX}px`;
    }
}

function placeUnder(anchor: HTMLElement, satellite: HTMLElement, spacing: number) {
    let posX = anchor.offsetLeft;
    let posY = anchor.offsetTop;

    let finalX = posX;
    let finalY = posY + anchor.clientHeight + spacing;

    satellite.style.left = `${finalX}px`
    satellite.style.top = `${finalY}px`;

    let childY = finalY + satellite.clientHeight - satellite.parentElement.offsetTop;
    if (childY > satellite.parentElement.clientHeight) {
        console.log(`setting parent height to ${childY}`)
        satellite.parentElement.style.height = `${childY}px`;
    }
}


arrangeGrids();