﻿/// <reference path="jquery/jquery.intellisense.js" />
function setupGridLayout(containerClassName, elementMinWidth, elementMaxWidth) {

    $('.' + containerClassName).each(function() {

        var containerMinWidth = 200
        var hotDealBoxMinWidth = elementMinWidth;
        var hotDealBoxMarginWidth = 10;
        var numberOfBoxes = $(this).children('div.midcolfl').length;

        var containerWidth = parseInt($(this).width());

        // a safety check to make sure we don't have a smaller centre panel than we expect
        if (containerWidth < containerMinWidth) {
            $(this).width(containerMinWidth)
            containerWidth = containerMinWidth;
        }

        // Work out how many promo boxes we can fit on each row
        var hotDealBoxesPerRow = parseInt(containerWidth / hotDealBoxMinWidth);
        var hotDealMinBoxesPerRow = parseInt(containerWidth / elementMaxWidth);
        if (hotDealBoxesPerRow > hotDealMinBoxesPerRow + 2) {
            //logic that tries to limit the number of boxes per row by
            hotDealBoxesPerRow = hotDealMinBoxesPerRow + 2;
        }


        if (hotDealBoxesPerRow > numberOfBoxes) {
            hotDealBoxesPerRow = numberOfBoxes;
        }

        // figure out how wide each promo box should be
        var hotDealBoxNewWidth = parseInt((containerWidth - ((hotDealBoxesPerRow - 1) * hotDealBoxMarginWidth)) / hotDealBoxesPerRow);
        if (elementMaxWidth > 0 && hotDealBoxNewWidth > elementMaxWidth) {
            hotDealBoxNewWidth = elementMaxWidth;
        }

        $(this).children('.midcolflclr.clr.midcolflclrmaxwidth').remove();

        // iterate through the promo boxes applying width and margin to each
        var itemCount = $(this).children('div.midcolfl').length;
        for (var i = 0; i <= itemCount - 1; i++) {

            var currentItem = $(this).children('div.midcolfl:eq(' + [i] + ')');

            // the end box of each row should be handled differently (ie; 0 margin)
            if (((i + 1) / hotDealBoxesPerRow).toString().indexOf(".") == -1) {
                $(currentItem).css('margin-right', 0);
                $('<div class="midcolflclr clr midcolflclrmaxwidth" />').insertAfter(currentItem);
            } else {
                $(currentItem).css('margin-right', hotDealBoxMarginWidth + "px");
            }

            if (itemCount == 1) {
                //only one item in grid, so don't set it's width to the calculated value or it will take up the whole width
                $(currentItem).width(elementMinWidth + 'px');
            } else {
                $(currentItem).width(hotDealBoxNewWidth + 'px');
            }
        }

    });

}