﻿/// <reference path="jquery/jquery.intellisense.js" />

$(document).ready(function() {
    setupHotDealsLayout();
    $(window).resize(function() { setupHotDealsLayout(); });
});


function setupHotDealsLayout() {

    $('.hot-deals-grid').each(function() {

        var containerMinWidth = 200
        var hotDealBoxMinWidth = 270;
        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);
        if (hotDealBoxesPerRow > 4) {
            hotDealBoxesPerRow = 4;
        }
        if (hotDealBoxesPerRow > numberOfBoxes) {
            hotDealBoxesPerRow = numberOfBoxes;
        }

        // if we calculate 3 boxes per row, but end up with one box orphaned, revert to 2 boxes per row - looks neater
        if (((numberOfBoxes % hotDealBoxesPerRow) == 1) && hotDealBoxesPerRow == 3) {
            hotDealBoxesPerRow = 2
        }
        // if we calculate 4 boxes per row, but end up with 2 boxes orphaned, revert to 3 boxes per row - looks neater
        if (((numberOfBoxes % hotDealBoxesPerRow) == 2) && hotDealBoxesPerRow == 4) {
            hotDealBoxesPerRow = 3
        }

        // figure out how wide each promo box should be
        var hotDealBoxNewWidth = parseInt((containerWidth - ((hotDealBoxesPerRow - 1) * hotDealBoxMarginWidth)) / hotDealBoxesPerRow);

        // hack for FF rendering issue when there are only 2 boxes available and they both appear on one line
        //if((numberOfBoxes == 2) && (hotDealBoxesPerRow == 2) && (is_fx)){hotDealBoxNewWidth -= 8}

        $(this).children('.midcolflclr.clr.midcolflclrmaxwidth').remove();

        // iterate through the promo boxes applying width and margin to each
        for (var i = 0; i <= $(this).children('div.midcolfl').length - 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");
            }
            $(currentItem).width(hotDealBoxNewWidth + 'px');
        }

    });

}
