﻿window.addEvent('domready', function() { Products.setup(); });

var Products = {
    ReqId: 0,
    CurrentThumb: 0,
    setup: function() {
        if ($('priceSummary') != null) {
            Products.GetPrice();
            $$('.option,#variant').addEvent('change', Products.GetPrice);
        }
        
        new QuickBox();
        
        var p = Products.ThumbList = $$('#thumbinner img');
        $('thumbinner').setStyle('width', (84 * p.length) + 'px');

        $$('#prevthumbpage').addEvent('click', function(y) { Products.MoveThumb(y, -1); });
        $$('#nextthumbpage').addEvent('click', function(y) { Products.MoveThumb(y, 1); });
    },
    MoveThumb: function(y, direction) {
        y.stop();
        Products.CurrentThumb += direction;

        if (Products.CurrentThumb < 0)
            Products.CurrentThumb = 0;

        if (Products.CurrentThumb > Math.floor(Products.ThumbList.length / 5))
            Products.CurrentThumb = Math.floor(Products.ThumbList.length / 5);

        var firstPage = Products.CurrentThumb * 5;

        var left = -Products.ThumbList[firstPage].getPosition('thumbinner').x;

        $('thumbinner').tween('left', left + 'px');

    },
    GetPrice: function() {

        Products.ReqId++;
        $('priceSummary').addClass('hidden');
        var nv = $('numvars').value * 1;

        var variants = new Array();

        for (var i = 1; i <= nv; i++) {
            var row = $$('#addShop tbody tr')[i - 1];
            var opts = row.getElements('.option');
            var options = new Array();
            opts.each(function(y) {
                options.include({ 'ID': y.get('rel'), 'Value': y.get('type') == 'checkbox' ? y.checked : y.value });
            });
            variants.include({ 'ID': row.getElement('.var').value, 'Val': i, 'Options': options });
        }
        var post = { 'ID': Products.ReqId, 'Variants': variants };

        var req = new Request.JSON({ url: 'price', onSuccess: Products.PriceDone, onFailure: function() { } });
        req.send("json=" + JSON.encode(post));
    },
    PriceDone: function(r) {
        if (r.OK && r.ID == Products.ReqId) {
            r.Variants.each(function(y) {
                var row = $$('#addShop tbody tr')[y.Val - 1];

                if (y.InStock) {
                    row.getElement('.priceInfo').set('text', '£' + y.Price);
                }
                else {
                    row.getElement('.priceInfo').set('text', 'Out of Stock');
                }

            });

            $('priceSummary').removeClass('hidden');

            if (r.OK) {
                $('addbasket').removeClass('hidden');
            }
            else {
                $('addbasket').addClass('hidden');
            }
        }
    }
}