﻿
$(document).ready(function() {
    $(window).bind('addToOrderSucceeded', function() {
        reloadBasket();
    });
    reloadSkus();
    $('#MatrixValues select').change(reloadSkus);
    $('#ListValues select').change(reloadSkus);
});

function reloadBasket() {
    var basketSelector = '.Basket';

    basketUrl = $.addToQueryString(basketUrl, 'time', new Date().getTime());

    $(basketSelector).load(basketUrl, null, function() {
        $(basketSelector).stop();
        $(basketSelector).css('backgroundColor', '#ffff00');
        $(basketSelector).animate({ backgroundColor: '#ffffff' }, 3000);

        var basketPostition = $(basketSelector).offset().top;

        var windowPosition = $(window).scrollTop();
        if (windowPosition > basketPostition)
            $(window).scrollTop(basketPostition);
    });
}

function reloadSkus() {

    var url = '';

    if ($('#MatrixValues select').length > 0) {

        var productContainer = $.locateContainer($('#SkusAjax'), 'Aspidistra.Ecommerce.Catalogue.Product');

        var productId = $(productContainer).data('ItemId');
        var axisValues = new Array();

        $('#MatrixValues select').each(function() {
            if ($.isGuid($(this).val()))
                axisValues.push($(this).val());
        });

        url = skusUrl + '?prod_id=' + productId;

        if (axisValues.length > 0)
            url += '&matrixValues=' + axisValues.join(',');

    }
    else if ($('#ListValues select').length > 0) {
        var skuId = '';

        $('#ListValues select').each(function() {
            if ($.isGuid($(this).val()))
                skuId = $(this).val();
        });

        url = skusUrl + '?prod_id=' + skuId;
    }
    else {
        var productContainer = $.locateContainer($('#SkusAjax'), 'Aspidistra.Ecommerce.Catalogue.Product');
        var productId = $(productContainer).data('ItemId');
        url = skusUrl + '?prod_id=' + productId;
    }
    reloadPanel(url);
}

function reloadPanel(url) {

    // $('#SkusAjax').css('display', 'none');
    $('#SkusAjax').progressIndicator({ func: 'start', text: 'Checking stock...' });

    $('.Axis').hide();


    // Add time to URL to avoid browser caching
    url = $.addToQueryString(url, 'time', new Date().getTime());
    //url = $.addToQueryString(url, 'account', accountId);

    $('#SkusAjax').load(url, null, activateLinks);
}

function activateLinks() {

    $('#SkusAjax').progressIndicator({ func: 'stop' });
    $('.Axis').show();

//    $('#SkusAjax a').click(function(event) {
//        reloadPanel($(this).attr('href'));
//        event.preventDefault();
//    });

    //                $('#SkusAjax input').click(function(event) {
    //                    $(this).addToOrder();
    //                    event.preventDefault();
    //                });
}            
           
           