// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
// behaviours - Product comparison;
// depends: 	jQuery library;
// author:		nr;
// --------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
if (typeof Barclaycard !== 'object') var Barclaycard={};

Barclaycard.productComparison = (function(){

    var $comparisonTable = $("#comparisonTable table");
    var productArray;
    var visibleProducts = [];
    var productCount = 0;
    var $emptyTable;
    var firstEmptyColumnIndex = 0;
    var $comparisonDiv = $("#comparisonTable");
    var representativeRemark;

    /* Method name: prepareTable
	 * Method description:
	 * 		(a) Empty the table and add four empty columns, storing the table contents in an array
	 * OR	(b) Show products identified on queryString (or elsewhere, cookie perhaps?)
	 */
    var prepareTable = function() {
        productArray = MultiDimensionalArray($comparisonTable.find("tr").length, $comparisonTable.find("tbody > tr:eq(0) > td").length);

        // Iterate over every table header/cell except first column and dump into array.
        $comparisonTable.find("tr").each(function(x) {
            $(this).find("td,th").each(function(y) {
                if (y > 0) {
                    // Input value is used in flash popup credit card rating window.
                    $comparisonDiv.append($("input",this));

                    productArray[x][y] = $(this).html();
                    $(this).remove();
                    // Add product to visible product list if it has class of 'compareMe'
                    if (x === 0 && $(this).hasClass("compareMe")) {
                        visibleProducts[visibleProducts.length++] = y;
                    }
                }
            });
        });

        // Save empty table for later
        $emptyTable = $comparisonTable.clone(false);

        // If there are any products to make visible, show them in the table
        if (visibleProducts.length > 0) {
            $("#comparisonTable table").replaceWith(buildNewComparisonTable());
        }
        else {
            // Add four empty columns
            $comparisonTable.find("tr").each(function(x){
                if (x < 1) {
                    $("<th class='empty'><span>Select a card above to compare it</span></th><th class='empty'><span>Select a card above to compare it</span></th><th class='empty'><span>Select a card above to compare it</span></th><th class='empty'><span>Select a card above to compare it</span></th>").appendTo($(this));
                }
                else {
                    $("<td></td><td></td><td></td><td></td>").appendTo($(this));
                }
            });
        }

        $("#comparisonTable").click(function(e) {
            var $target = $(e.target);
            if (!$target.is("a") || !$target.hasClass("close")) {
                return true;
            }
            var id = $target.attr("id");
            var columnIndexToRemove = parseInt(id.charAt(id.length - 1), 10);
            getFlashObject("loader").deselectCards([(columnIndexToRemove - 1)]);
            return false;

        });
    };
    var stripeTable = function() {
        $("#comparisonTable table tbody tr:even").addClass("stripe");
    };

    var MultiDimensionalArray = function (iRows,iCols) {
        var a = new Array(iRows);
        for (var i=0; i < iRows; i++) {
            a[i] = new Array(iCols);
            for (var j=0; j < iCols; j++) {
                a[i][j] = "";
            }
        }
        return(a);
    };


    var addTableColumn = function(columnIndex) {
        columnIndex = parseInt(columnIndex, 10);

        // Don't add new column if there's 4 or more products,
        // OR if the product has already been added
        if (isProductIndexInInList(columnIndex)) {
            return true;
        }

        // return false so that Flash can display an error message
        if (visibleProducts.length >= 4) {
            return false;
        }


        // Add column index to list of product indexes to show
        visibleProducts[visibleProducts.length++] = columnIndex;

        $("#comparisonTable table").replaceWith(buildNewComparisonTable());

        return true;
    };


    var removeTableColumn = function(columnIndex) {
        columnIndex = parseInt(columnIndex, 10);

        // Exit function if there's no visible products
        if (visibleProducts.length < 1) {
            return false;
        }

        // Remove column index from list of product indexes showing
        var elementIndexToRemoveFromArray = -1;
        for (var i = 0; i < visibleProducts.length; i++) {
            if (visibleProducts[i] === columnIndex) {
                elementIndexToRemoveFromArray = i;
            }
        }

        if (elementIndexToRemoveFromArray > -1) {
            visibleProducts.splice(elementIndexToRemoveFromArray, 1);
        }

        $("#comparisonTable table").replaceWith(buildNewComparisonTable());

        return true;
    };

    var buildNewComparisonTable = function() {
        // Clone the empty table
        var $newComparisonTable = $emptyTable.clone(false);

        $newComparisonTable.find("tr").each(function(x) {
            for (var y = 0; y < 4; y++) {
                if (y < visibleProducts.length ) {
                    if (x < 1) {
                        $("<th scope='col'><div>" +
                            productArray[x][visibleProducts[y]] +
                            " <a href='#' class='close' id='close" + visibleProducts[y] + "' >&nbsp;</a></div></th>").appendTo($(this));
                    }
                    else {
                        $("<td>" + productArray[x][visibleProducts[y]] + "</td>").appendTo($(this));
                    }
                }
                // Add empty table cell
                else {
                    if (x < 1) {
                        $("<th class='empty'><span>Select a card above to compare it</span></th>").appendTo($(this));
                    }
                    else {
                        $("<td></td>").appendTo($(this));
                    }
                }
            }
        });

        return $newComparisonTable;
    };




    var isProductIndexInInList = function(columnIndex) {
        for (var i = 0; i < visibleProducts.length; i++) {
            if (visibleProducts[i] === columnIndex) {
                return true;
            }
        }

        return false;
    };

    var getFlashObject = function(objName) {
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        return (isIE) ? window[objName] : document[objName];
    };

    /**
     * Add the rate text if there's 1 or more products.
     */
    var addRepresentativeDetail = function() {
        if (visibleProducts.length > 0) {
            var tr_apr_el = $("#comparisonTable table tr.apr");

            if ($("#comparisonTable table").find("tr.representativeRemark").length <= 0) {
                if (tr_apr_el.hasClass('stripe')) {
                    tr_apr_el.after("<tr class='stripe representativeRemark'><th scope='row'><div></div></th><td colSpan=4>" + representativeRemark +"</td></tr>");
                } else {
                    tr_apr_el.after("<tr class='representativeRemark'><th scope='row'><div></div></th><td colSpan=4>" + representativeRemark +"</td></tr>");
                }
            }
        }

    };

    var initRepresentativeRemark = function() {
        representativeRemark = $comparisonTable.find('.representativeRemark td').html();
        $('.representativeRemark').remove();
    }

    return {

        init : function() {
            initRepresentativeRemark();
            prepareTable();
            stripeTable();
            addRepresentativeDetail();
        },

        addTableColumn : function(colIndex) {
            if (addTableColumn(colIndex)) {
                // only if no representative example text, stripe the table
                if ($("#comparisonTable table").find("tr.representativeRemark").length <= 0) {
                    stripeTable();
                }
                addRepresentativeDetail();
            }
        },

        removeTableColumn : function(colIndex) {
            removeTableColumn(colIndex);
            stripeTable();
            addRepresentativeDetail();
        },

        updateFlash : function() {
            var flashVisibleProducts = new Array(visibleProducts.length);
            for(var i = 0; i < visibleProducts.length; i++) {
                flashVisibleProducts[i] = visibleProducts[i] -1;
            }
            getFlashObject("loader").selectCards(flashVisibleProducts);
        }
    };

}());
$().ready(function() {
    if ($("body").hasClass("hasFlash")) {
        Barclaycard.productComparison.init();
    }
});

// --------------------------------------------------------------------------------------------------------------------------------
// --- end of file ---
// -------------------------------------------------------------------------------------------------------------------------------

