/*
 * How to use:
    ri = new RecommendedItems('recommended_items', store_id, gift_registry_id); // instantiate the new object
    ri.fetchItems();	// update container with the recommended items

    optional methods:
    ri.setMaxResults(3);	// set maximum number of items to retrieve
    ri.setImageTemplate(new Template());	// override image src (for instance, if image is dynamic based on product/sku data)
    ri.setImageSize({ width: 50, height: 50 });	// set image dimensions
    ri.setTemplate(new Template());	// replace the default item row formatting with a custom template
    ri.setProduct(145542, 3231);	// set the catalogue product id and cateogry from which to retrieve recommended items
*/
var RecommendedItems = Class.create({
    initialize: function(container, store_id, gift_registry_id) {
        this.setTemplate(new Template(
                '<form id="#{container}_#{id}_form" action="#{cart_page}" method="POST">' +
                '<input type="hidden" name="store_id" value="#{store_id}" />' +
                '<input type="hidden" name="gift_registry_id" value="#{gift_registry_id}" />' +
                '<input type="hidden" name="redir" value="#{redir}" />' +
                '<input type="hidden" name="quantity" value="1" />' +
                '<div class="#{container}_img"><a href="#{link}"><img src="#{image}" /></a></div>' +
                '<div class="#{container}_name"><a href="#{link}">#{name}</a></div>' +
                '<div class="#{container}_description">#{description}</div>' +
                '<div id="#{container}_#{id}_buy" class="#{container}_buy"></div>' +
                '</form>'
        ));
        this.setButtonHTML('<input type="submit" value="Add To Cart" />');

	this.complete=false;
        this.setContainer(container);
        this.setStoreId(store_id);
        this.setGiftRegistryId(gift_registry_id);
        this.setProduct(-1, -1);
        this.setMaxResults(-1);
        this.setLabel('Recommended Items');
        this.setPriceLeader('Price: ');
        this.setPriceTrailer('');
        this.setDebug(false);
        this.setBaseURL('/qs/');
        this.setImageTemplate(null);
        this.setBreakAfterPrice(true);
    },
    parseResults: function(transport) {
        var json = transport.responseText.evalJSON();
        if (this._debug) alert('displaying '+json.count+' items\n'+Object.toJSON(json.items));
        if (json.count < 1) {
            return;
        }

        $(this._container).update(new Element('div', {
            id: this._container + '_label',
            style: 'display:none'
        }).update(this._label));
        new Effect.Appear(this._container + '_label');

        var detail_container = this._container + '_detail';
        $(this._container).insert(new Element('div', { id: detail_container }));

        $H(json.items).values().each(function(s) {
            s['container'] = this._container;
            s['link'] = this._baseurl + 'product/' + s.store_id + '/' + s.category_id + '/' + s.id + '/0/0';
            s['redir'] = this._product_id > 0 ? 1 : 0;

            s.image = (this._image_template) ? this._image_template.evaluate(s) : s.image;
            if (s.image == '') {
                s['image_style'] = 'display:none;';
            } else {
                s['image_style'] = '';
            }

            var new_item_id = this._container + '_' + s.id;
            var new_item = new Element('div', {
                    id: new_item_id,
                    style: 'display:none'
            }).addClassName(this._container + '_item');
            new_item.insert(this._template.evaluate(s));
            $(detail_container).insert(new_item);
            new Effect.Appear(new_item_id);

            var inventory_items = $H(s.inventory_items).values();
            if (inventory_items.size() > 1) {
                $(new_item_id+'_buy').insert({ 'top': '<select id="'+ new_item_id +'_inventory_id' +'" name="inventory_id"></select>'});
                var property_str = '';
                inventory_items.each(function(t) {
                    $(new_item_id+'_inventory_id').insert(
                        '<option value="' + t.id + '">' + $H(t.properties).values().join(', ') + ' ($'+ t.price +')</option>'
                    );
                }.bind(this));

            } else {
                $(new_item_id+'_buy').insert('<input type="hidden" name="inventory_id" value="'+ inventory_items[0].id +'" />');
                $(new_item_id+'_buy').insert({top: this._price_leader + '$' + inventory_items[0].price.toFixed(2) + this._price_trailer});
            }
            if (this._break_after_price) {
                $(new_item_id+'_buy').insert('<br />');
            }
            if (inventory_items[0].id > '-1') {
                $(new_item_id+'_buy').insert(this._button_html);
            }
            if (s.redir == 1) {
                $(new_item_id+'_buy').insert('<input type="hidden" name="product_id" value="'+ this._product_id +'" />');
                $(new_item_id+'_buy').insert('<input type="hidden" name="category_id" value="'+ this._category_id +'" />');
            }
        }.bind(this));
	this.complete=true;
    },
    fetchItems: function() {
        new Ajax.Request(this._baseurl + 'recommended_items.php', {
            method: 'get',
            parameters: {
                store_id: this._store_id,
                gift_registry_id: this._gift_registry_id,
                product_id: this._product_id,
                category_id: this._category_id,
                max_results: this._results,
                request_type: 'json'
            },
            onSuccess: this.parseResults.bindAsEventListener(this)
        });
    },
    setContainer: function(container) { this._container = container; },
    setStoreId: function(store_id) { this._store_id = store_id; },
    setGiftRegistryId: function(gift_registry_id) { this._gift_registry_id = gift_registry_id; },
    setMaxResults: function (max_results) { this._results = max_results; },
    setTemplate: function(template) { this._template = template; },
    getTemplate: function() { return this._template; },
    setProduct: function(id, category) {
        this._product_id = id;
        this._category_id = category;
    },
    setLabel: function(label) { this._label = label; },
    setBaseURL: function(url) { this._baseurl = url; },
    setImageTemplate: function(tmpl) { this._image_template = tmpl; },
    setButtonHTML: function(html) { this._button_html = html; },
    setBreakAfterPrice: function(add_break) { this._break_after_price = (add_break) ? true : false; },
    setPriceLeader: function(leader) { this._price_leader = leader; },
    setPriceTrailer: function(trailer) { this._price_trailer = trailer; },
    setDebug: function(debug) { this._debug = debug; }
});

