var defaultStock = {text: '', classNames: ''},
    settings,
    url;

function identifyAssociatedProduct() {
    var $container = $$('.product-stock')[0],
        $stockIcon = $container.childElements().grep(new Selector('.icon'))[0],
        $stockText = $container.childElements().grep(new Selector('.text'))[0],
        $stockQty = $container.childElements().grep(new Selector('.qty'))[0],
        selectedAttributes = 0;

    settings.each(function(element){
        if (element.selectedIndex != 0) {
            selectedAttributes++;
        }
    });

    if (selectedAttributes == settings.length) {
        $container.addClassName('associated-product-loading');

        new Ajax.Request(url, {
            method: 'get',
            parameters: $('product_addtocart_form').serialize(true),
            onSuccess: function (transport) {
                var classes = ['green', 'red', 'yellow'],
                    i = 0,
                    stockQty = parseInt(transport.responseText, 10),
                    stockStatus = (stockQty > 0)
                    s = classes.length;

                $container.removeClassName('associated-product-loading');

                if ($container.hasClassName('init')) {
                    defaultStock.classNames += $stockIcon.classNames();
                    defaultStock.text += $stockText.innerHTML;

                    $container.removeClassName('init');
                }

                for (; i < s; i += 1) {
                    $stockIcon.removeClassName(classes[i]);
                }

                $stockIcon.addClassName((stockStatus) ? 'green' : 'red');
                $stockText.innerHTML = (stockStatus) ? 'I lager' : 'Ej i lager';

                if (stockStatus) {
                    $stockQty.innerHTML = '(' + stockQty.toString() + ')';
                } else {
                    $stockQty.innerHTML = '';
                }
            }
        });
    } else {
        if (defaultStock.classNames.length) {
            $stockIcon.className = defaultStock.classNames;
            $stockText.innerHTML = defaultStock.text;
        }
    }
}

document.observe("dom:loaded", function() {
    settings = $$('.super-attribute-select');
    url = '/ctlg/product_configurable/identifyassociatedproduct/';

    settings.each(function(element){
        Event.observe(element, 'change', function() {
            identifyAssociatedProduct();
        });
    });
});

