Array.prototype.unique = function( b ) {var a = [], i, l = this.length;for( i=0; i<l; i++ ) {if( a.indexOf( this[i], 0, b ) < 0 ) {a.push( this[i] );}}return a;};

// Create the ProductDetail namespace
Jabba.ProductDetail = {};


// Create the product detail observer namespace
Jabba.ProductDetail.Observer = {};

/**
 * Product Detail Page General Control
 *
 */
Jabba.ProductDetail.Page = function(options) {
    var that = {};
    var loaded = false;
    if (typeof(options) == 'undefined') options = {};

    /**
     * Initialize Object
     */
    that.init = function() {        
        that.productForm = options.productForm || '#product_form';
        that.addToCartButton = options.addToCartButton || '#btn_cart_add';
        that.checkoutButton = options.checkoutButton || '#btn_cart_checkout';
        that.returnToFinderButton = options.returnToFinderButton || '#return_to_finder';
        that.linkToProductButton = options.linkToProductButton || '#link_to_product';
        that.pageBodySelector = options.pageBodySelector || '#product-detail';
        that.itemType = options.itemType || '';
        that.baseUrl = options.baseUrl || '';

        that.productForm = jQuery(that.productForm);
        that.addToCartButton = jQuery(that.addToCartButton);        
        that.checkoutButton = jQuery(that.checkoutButton);
        that.returnToFinderButton = jQuery(that.returnToFinderButton);
        that.linkToProductButton = jQuery(that.linkToProductButton);
        that.pageBody = jQuery(that.pageBodySelector);

        // start review comment controls
        Jabba.Review().initComments();

        // Bind events
        that.addToCartButton.unbind();
        that.addToCartButton.click(function(){
            disabled = jQuery(this).attr('disabled');
            if (typeof('disabled') != 'undefined' && disabled) {
                return false;
            }
            that.addToCart();
            return false;
        });
        that.checkoutButton.click(function(){
            that.checkout();
            return false;
        });
        that.returnToFinderButton.click(function(){
           that.returnToFinder();
           return false;
        });
        
//        jQuery('.notify-customer').click(function() {
//            var requestedSize = jQuery('#converted-size .superselect-selected').html();
//            requestedSize = requestedSize.replace(/<.*>/, '');
//            Jabba.Product.Inventory.showNotifyWindow(requestedSize);
//            return false;
//        });
//        jQuery('.view-variance').click(function() {
//            var requestedSize = jQuery('#converted-size .superselect-selected').html();
//            requestedSize = requestedSize.replace(/<.*>/, '');
//            Jabba.Product.Inventory.showVarianceWindow(requestedSize);
//            return false;
//        });
        
        // Bind alternate colors event listener
        jQuery('#product-detail #alternate-colors').live('change', function(event, value){
            value = value.split('|');
            if (typeof(value[1]) != 'undefined') {
                top.location = value[1];
            }
        });
        
        /**
         * Check if a size is selected
         * 
         * @return bool
         */
        that.hasSizeSelected = function() {
            var input = jQuery('input[name=product]');
            if (typeof(input) != 'undefined' && input) {
                if (input.val() == '') {
                    return false;
                }
            }
            return true;
        }

        that.initStarRatings();

        jQuery('#product-thumbnails a').click(function(){
            jQuery('#product-thumbnails a').closest('div').removeClass('selected');
            jQuery(this).closest('div').addClass('selected');
            
            // remove jQZoom so we can reload new image/dimensions
            jQuery(".jqZoomWindow").remove();
            jQuery(".jqZoomPup").remove();
            jQuery(".jqzoom").remove();

            var largeImage = jQuery(this).attr('href');
            var mediumImage = jQuery(this).attr('rel');
            jQuery('.view-larger-images').remove();
            jQuery('#product-image').append('<a href="' + largeImage + '" class="view-larger-images"><img src="' + mediumImage + '" rel="v:photo" class="default-image" /></a>');

            jQuery('.view-larger-images').ready(function(){
                jQuery('.view-larger-images').jqzoom({
                    zoomType: 'standard',
                    lens: true,
                    preloadImages: true,
                    alwaysOn: false,
                    xOffset:50,
                    yOffset:0,
                    zoomWidth: 455,
                    zoomHeight: 470,
                    position:'right',
                    title: false
                 });
            });
            
            return false;
        });

        jQuery('#product-detail .brand-history .read-more').click(function() {
            jQuery('#product-detail .brand-history .info').removeClass('short');
            jQuery('#product-detail .brand-history .read-more').hide();

            return false;
        })
        jQuery(document).ready(function() {
            if (jQuery('#product-detail .brand-history .info').height() > 315) {
                jQuery('#product-detail .brand-history .info').addClass('short');
                jQuery('#product-detail .brand-history .read-more').show();
            }
        });
    }

    that.showQuantityAlert = function(id) {
        jQuery('#low-inventory-message').hide();
        if (jQuery.inArray(id, outOfStock) == -1) {
            that.ajax = jQuery.ajax({
                url: '/catalog/product/quantityAlert/',
                dataType: 'html',
                type: 'get',
                data: {
                    id: id
                },
                success: function(response) {
                    var qty = parseInt(response);
                    if (qty > 2) {
                        jQuery('.availability').show();
                    } else if (qty > 0) {
                        var text = 'is only 1 pair';
                        if (qty > 1) {
                            text = 'are only ' + qty + ' pairs';
                        }
                        jQuery('.availability').hide();
                        jQuery('#low-inventory-message .qty').text(text);
                        jQuery('#low-inventory-message').show();
                    }
                }
            });
        }
    }

    /**
     * Add the current product to shopping cart
     *
     * @return boolean
     */
    that.addToCart = function() {
        if (!that.hasSizeSelected()) {
            Boxy.alert('<p style="padding:20px">Please choose a product size.</p>');
            return false;
        }        
        
        if (jQuery('#view-mode') && jQuery('#view-mode').val() == 'quickview') {
            jQuery('#btn_cart_add span')
                .text('Adding to Cart...');
            jQuery('#btn_cart_add').attr('disabled', 'disabled');
            Jabba.Quickview().addToCart();
        } else {
            that.productForm.submit();
        }
    }

    /**
     * Redirect to checkout page
     */
    that.checkout = function() {
        document.location.href = that.baseUrl + 'checkout/onepage';
        return false;
    }

    /**
     * Return to finder results
     */
    that.returnToFinder = function() {
        var val = Jabba.Cookie.read('finder');
        if (val) {
            window.location.href = val;
        } else if (document.referrer.indexOf(that.baseUrl) > -1) {
            history.go(-1);
        } else {
            window.location.href = that.baseUrl + 'finder/type/' + that.itemType;
        }
        return false;
    }

    /**
     * Bind click handlers to all products on the page
     */
    that.bindProductClicks = function() {
        jQuery('.product-result').live('click', function(e){
            if (typeof(e.button) != 'undefined') {
                // If it's a middle click, allow page to open normally in new tab
                // If it's a right click, don't do anything
                if (e.button == 1 || e.button == 2) {
                    return true;
                }
            }
            
            that.loadProduct(jQuery(this));
            return false;
        });
    }

    /**
     * Initialize jQuery star-rating plugin
     */
    that.initStarRatings = function() {
        // re-initialize all rating controllers
        jQuery('.rating-controller').each(function(){            
            Jabba.Ratings('.rate', jQuery(this).attr('rel')).init(false);
        });
    }

    /**
     * Process product click, set up ajax page load
     *
     * @param object element The page element that was clicked
     */
    that.loadProduct = function(element)
    {        
        if (!element.hasClass('empty')) {
            var url = element.find('a').attr('href');
            if (url) {
                if (element.parents(".ajax-products").hasClass("hide-carousel")) {
                    jQuery('.carousel').fadeOut(); // Hide the carousel, since the results likely no longer apply
                    jQuery('.status').fadeOut();
                }
                jQuery.historyLoad(url);                
            }
        }
    }

    /**
     * Ajax-load page
     *
     * @param string url
     */
    that.loadPage = function(url) {
        if (typeof(url) == 'undefined') url = '';
        if (!url) {
            if (top.location) {
                url = top.location.toString();
                url = '/' + url.replace(that.baseUrl, '');
            } else {
                return;
            }
        }
        that.pageBody.showLoader();
        jQuery.get(url, null, function(response){
            var responseBody = jQuery('<div>' + response + '</div>').find(that.pageBodySelector);
            if (responseBody.length) {
                that.pageBody.replaceWith(responseBody);
                jQuery(document).trigger('pageUpdated'); // trigger custom 'pageUpdated' event
            }
        });           
    }

    // Loads facebook want button
    that.loadWantButton = function() {
        var button = jQuery('<a></a>')
            .attr({href: 'http://wanttt.com/want/initial_popup/'})
            .attr({'data-merchant_name' : 'Shoebacca'})
            .attr({'data-title' : gigyaParams.title})
            .attr({'data-price' : gigyaParams.price})
            .attr({'data-image_url' : gigyaParams.wantItImage})
            .attr({'data-count' : 'true'})
            .attr({'data-style' : 'wbfb2'})
            .attr({'data-page_source' : 'PRODUCT'})
            .attr({'class' : 'wantButton'});

            jQuery('#want-wrapper').append(button);
    }

    // Call init method on page load
    jQuery(that.init);

    // Re-initialize after ajax page change
    jQuery(document).bind('pageUpdated', that.init);

    return that;
}
