/**
 * Universal Wish List support for WebStore by Amazon.
 * Requires jQuery 1.3 or above.
 * Must be manually uploaded and added to script tags for the "product" page.
 * See https://w.amazon.com/index.php/Gifting/Sprint/Sprint20/Starbury#Test_Site
 */

// don't pollute the global namespace!
$(function() {

    /*
     * @return true if all boxes were selected (or there are no boxes).
     */
    function allSelected(variationBoxes) {
        var foundUnselected = false;
        $.each(variationBoxes, function(i, v) {
            if ($("#" + v + " option:selected").attr('value') === "") {
                // no value for this option
                foundUnselected = true;
                return false; // end "each" early
            }
        });
        return !foundUnselected;
    }

    /**
     * Revises title, price, and image.
     */
    function updateButtonForCurrentVariant(product, variationBoxes) {
        if (variationBoxes) {
            var titleSuffix = $.map(variationBoxes, function(v) {
                return '|' + $('select#' + v + ' option:selected').val();
            }).join('');
            $('div#AUWLBkTitle').text(product.title + titleSuffix);

            // this product may not have variation images
            if (window.variationImages && variationImages[titleSuffix]) {
                $('div#AUWLBkImage').text(variationImages[titleSuffix]);
            }

            // asins and variationInfo seem to be present on every page
            if (window.asins && asins[titleSuffix]) {
                var variantAsin = asins[titleSuffix];
                if (window.variationInfo && variationInfo[variantAsin] && variationInfo[variantAsin].price) {
                    $('div#AUWLBkPrice').text(variationInfo[variantAsin].price);
                }
            }
        }
    }

    /**
     * Enables/disables/updates button
     */
    function updateButton(product, variationBoxes) {
        var anchor = $("#AUWLHook a");
        var img = $("#AUWLHook img");
        if (img.length === 0) {
            // button hasn't yet been rendered
            setTimeout(function() { updateButton(product, variationBoxes); }, 1);
            return;
        }
        // stretch image to "correct" size. Ugly.
        img.attr('height', $('input.wba_add_to_cart_btn').height());
        // store the original url
        if (!anchor.data('original_href')) {
            anchor.data('original_href', anchor.attr('href'));
        }
        // enable/disable
        if (allSelected(variationBoxes)) {
            // enable button
            img.css('cursor', 'pointer');
            anchor.attr('href', anchor.data('original_href'));
            anchor.attr('alt', 'Add to your Universal Wish List');
            anchor.attr('title', 'Add to your Universal Wish List');
        } else {
            // disable button
            anchor.removeAttr('href');
            anchor.attr('alt', 'To add to your Universal Wish List, please choose from options above');
            anchor.attr('title', 'To add to Wish List, please choose from options above');
            $("#AUWLHook img").css('cursor', 'not-allowed');
        }
        updateButtonForCurrentVariant(product, variationBoxes);
    }

    /**
     * Adds UWL button into page.
     * Should probably be replaced with template edits.
     */
    function addAUWLForProduct(product, elem, doc, variationBoxes) {
        $(elem).after('&nbsp;&nbsp;&nbsp;<span id="AUWLHook"><div style="display: none;" id="AUWLBkURL">' +
                    location.protocol + '//' + location.hostname + product.productDetailUrl + '</div>' +
            '<div style="display: none;" id="AUWLBkPrice">' + (product.salePrice || product.regularPrice) + '</div>' +
            '<div style="display: none;" id="AUWLBkTitle">' + product.title + '</div>' +
            '<div style="display: none;" id="AUWLBkImage">' + product.smallImageUrl + '</div></span>');

        // adding script tag directly in the "after" doesn't work, using DOM api directly
        var scr = doc.createElement('script');
        scr.setAttribute('src', 'http://www.amazon.com/wishlist/bookmarklet/getbutton.js?image=2');
        scr.setAttribute('id', 'AddToAUWLButton');
        doc.getElementById('AUWLHook').appendChild(scr);
        if (variationBoxes && variationBoxes.length > 0) {
            $.each(variationBoxes, function(i, v) {
                $('#' + v).click(function() {
                    updateButton(product, variationBoxes);
                    return true;
                });
            });
        }
        setTimeout(function() { updateButton(product, variationBoxes); }, 1);
    }


    // main block - instrument AUWL into page.
    $("input.wba_add_to_cart_btn").each(function() {
        // simulate wba_product, since JS variables haven't been tunrned on for Starbury.
        addAUWLForProduct(wba_product, this, document, variationSelectBoxNames);
    });

    // force the popover to navigate to Wish List in a new Window
    $('table#AUWLPopover a').live('click', function() {
       $('table#AUWLPopover a[href^="http"]').each(function() {
           $(this).attr('target', '_blank');
           $(this).click(function() {
               AUWLBook.hidePopover();
            });
       });
       return true;
    });
});

