(function($) {

    $.productDetail = function(options, productId) {
        return $.productDetail.impl.init(options, productId);
    };

    $.fn.productDetail = function(options) {
        return $.productDetail.impl.init(this, options);
    };

    /*
    * default options
    */
    $.productDetail.defaults = {
        res: {/* translations go here */
    }
};

$.productDetail.impl = {

    /*
    * options
    */
    opts: null,

    /*
    * helper
    */
    helper: {},
    
    /*
    * swfAddressInit
    */
    swfAddressInit: false,

    /*
    * product id
    */
    productId: null,

    /*
    * Initializes the page
    */
    init: function(options, productId) {
        
        var self = this;

        this.opts = $.extend({}, $.productDetail.defaults, options);

        // set product ID
        self.productId = productId;

        // helper objects
        self.helper.container = $('div.page-productdetail');
        self.helper.optionList = self.helper.container.find('ul.option-collection');
        self.helper.crossSells = self.helper.container.find('ul.crosssellitem-collection');
        self.helper.variantSelectors = self.helper.container.find('ul.variantselector-collection');
        self.helper.addProduct = self.helper.container.find('a.add-product');
        self.helper.productAdded = self.helper.container.find('ul.product-added');
        self.helper.price = self.helper.container.find('.product-price');

        // initialize the select boxes
        self.initSelects();

        // initialize the cross sells
        self.initCrossSells();
        
        if (SWFAddress.getParameter('id') != '')
        {
            var $bc = $('.breadcrumb div:last-child a');
            var bcHref = $bc.attr('href');
            
            $bc
                .attr('href', bcHref + '#/?id=' + SWFAddress.getParameter("id"))
                ;
        }
        
        // show the imagery
        var text;
        
        if (self.opts.variant != '' && self.opts.variant != null)
        {
            var text = self.helper.variantSelectors.find('a[href="#' + self.opts.variant + '"]').attr('title');
        }
        else
        {
            self.opts.variant = $(self.helper.variantSelectors.find('a')[0]).attr('href').replace('#', '');
            var text = self.helper.variantSelectors.find('a[href="#' + self.opts.variant + '"]').attr('title');
        }
        
        self.helper.container.find('.fixer')
            .css({
                display: 'none',
                position: 'static',
                left: 'auto'
            })
//            .fadeIn(500, function(){
//                
//                if (text != null)
//                    self.changeVariant(text, self.opts.variant);
//                
//            })
            .css({
                display: 'block'
            })
            ;
        
        if (text != null)
            self.changeVariant(text, self.opts.variant);
        
        // bind the events
        self.bindEvents();

        return self;
    },

    /*
    * Binds the events
    */
    bindEvents: function() {

        var self = this;

        // variant click
        self.helper.variantSelectors.find('a').click(function(e) {
            e.preventDefault();

            var v = $(this).attr('href').split('#')[1];

            if ($(this).parent().hasClass('variantselector-selected'))
                return;

            self.changeVariant($(this).attr('title'), v);

        });

        // click addProduct
        self.bindAddProductClick();

        return;
    },

    /*
    * addProduct callback
    */
    addProductCallback: function(data) {

        var self = $.productDetail.impl;
        var count = (data > 0) ? data : 0;

        // re-bind the addproduct click
        self.bindAddProductClick();

        if (data < 0)
        {
            if (data == -2)
                alert(self.opts.res.quantityUnavailable);
            else
                alert(self.opts.res.anErrorHasOccurred);

            return;
        }

        // show the checkout button
        self.helper.productAdded
            .fadeIn(500)
            ;

        // update the shoppingbag count in header
        $('ul#nav-ecommerce .shoppingbag-count')
            .text(count)
            ;

        return;
    },

    /*
    * Binds the add product click
    */
    bindAddProductClick: function() {

        var self = this;

        self.helper.addProduct
            .removeClass('disabled')
            .click(function(e) {
                e.preventDefault();

                $(this)
                    .addClass('disabled')
                    .unbind()
                    ;

                self.helper.productAdded
                    .css({
                        display: 'none'
                    })
                    ;

                var sizeCode = self.helper.optionList.find('.option-size a.select-selected').attr('value');
                var variantCode = self.helper.optionList.find('.option-color a.select-selected').attr('value');
                var quantity = self.helper.optionList.find('.option-quantity a.select-selected').attr('value');

                if (sizeCode == '' || sizeCode == 'null') {
                    alert(self.opts.res.pleaseSelectSize);

                    // re-bind the addproduct click
                    self.bindAddProductClick();

                    return;
                }

                $.shoppingBag.impl.addProduct(self.productId, sizeCode, variantCode, quantity, self.opts.folderCrumb, $.productDetail.impl.addProductCallback);

            })
            ;

        return;
    },

    /*
    * Changes the variant
    */
    changeVariant: function(text, value) {
        
        var self = this;
        var $og = self.helper.container.find('ul.option-collection li.option-color select');
        var $sSelected = self.helper.container.find('ul.option-collection li.option-color .select-selected');
        var $selectors = $('ul.variantselector-collection');
        
        $sSelected
            .attr('value', value)
            .html('<span>' + self.opts.res.color + ': </span><span class="select-selected-value">' + text + '</span>')
            ;

        $og.setSelected(value);

        // handle the case where user selects "color:" from dropdown
        var $v = $selectors.find('.variantselector-' + value);
        
        // user selects variant w/ images
        if ($v.length > 0 && !$v.hasClass('variantselector-selected')) {
            if (value == '-1')
                $v = $($selectors.find('.variantselector')[0]);

            $selectors.find('.variantselector')
                .removeClass('variantselector-selected')
                ;

            $v
                .addClass('variantselector-selected')
                ;

            var variantName = $v.find('a').attr('href').split('#')[1];
            
            $.imagery.impl.variant(variantName);
        }
        
        CreateThe.Com.Web.CodeBase.WebServices.ProductService.GetSizes(self.productId, self.opts.folderId, self.opts.folderCrumb, self.opts.root, self.opts.lang, self.opts.region, self.opts.priceCode, value, $.productDetail.impl.getSizesSuccess, $.productDetail.impl.getFailure);
        
//        SWFAddress.onInit = function() {
//            self.swfAddressInit = true;
//            SWFAddress.setValue('/?v=' + value);
//        }
        
        // set the deep linked value
        if (self.swfAddressInit)
            SWFAddress.setValue('/?v=' + value);
        
        // block sizes until get sizes call is complete
        try
        {
            // blocker was erroring out occasinoally. Added try statement.
            self.helper.container.find('ul.option-collection li.option-size .select-container')
	            .unblock()
	            .block({
	                message: null,
	                overlayCSS: {
	                    backgroundColor: '#000',
	                    opacity: '0.60'
	                }
	            })
                ;
        }
        catch(err)
        {
            
        }
        
        return;
    },

    /*
    * Initializes the select boxes
    */
    initSelects: function() {

        var self = this;
        var selectedVariant = $(self.helper.variantSelectors.find('a')[0]).attr('href').split('#')[1];

        self.helper.optionList.find('select').each(function(i, item) {

            var $og = $(item).hide();
            var ogId = $og.attr('id');
            var ogClass = $og.attr('class');
            var selectedIndex = $og.children("option[selected='selected']").prevAll().length;
            var values = [];
            var texts = [];

            $og.children().each(function(j) {

                values[j] = $(this).attr('value');
                texts[j] = $(this).text();

            });

            var optionName;
            switch (i) {
                case 0:
                    optionName = self.opts.res.color;
                    selectedIndex = $og.find('[value="' + selectedVariant + '"]').prevAll().length;
                    break;
                case 1:
                    optionName = self.opts.res.size;
                    break;
                case 2:
                    optionName = self.opts.res.quantity;
                    break;
            }

            var $sContainer = $('<div class="select-container"></div>').insertAfter($og);
            var $sSelected = $('<a href="#" class="select-selected" value="' + values[selectedIndex] + '"><span>' + optionName + ': </span><span class="select-selected-value">' + texts[selectedIndex] + '</span></a>').appendTo($sContainer);
            var $sOptions = $('<ul class="select-option-collection"></ul>').appendTo($sContainer);

            $.each(values, function(j) {

                var $o = $('<li class="select-option"><a href="#" value="' + values[j] + '">' + texts[j] + '</a></li>');

                $sOptions.append($o);

            });

            // selected click (i.e. open/close)
            $sSelected.click(function(e) {
                e.preventDefault();

                if (!$sContainer.hasClass('select-container-show')) {
                    $sContainer
		                    .addClass('select-container-show')
		                    ;

                    $sContainer.find('a').blur(function() {
                        $sContainer
		                        .removeClass('select-container-show')
		                        ;
                    });
                }
                else {
                    $sContainer
		                    .removeClass('select-container-show')
		                    ;
                }
            });

            // option click
            $sOptions.find('a').click(function(e) {
                e.preventDefault();

                if ($(this).parent().hasClass('select-option-disabled'))
                    return;

                if ($sSelected.text() != $(this).text()) {
                    $sSelected.find('.select-selected-value').text($(this).text());
                    $sSelected.attr('value', $(this).attr('value'));
                }

                $sContainer
                        .removeClass('select-container-show')
                        ;
            });

            // link hover
            $sContainer.find('a').hover(
		            function() {
		                $sContainer.find('a').unbind('blur');
		            },
		            function() {
		                $sContainer.find('a').blur(function() {
		                    $sContainer
		                        .removeClass('select-container-show')
		                        ;
		                });
		            }
		        );
        });

        // define helpers
        self.helper.variantList = self.helper.optionList.find('.option-color .select-option-collection');
        self.helper.sizeList = self.helper.optionList.find('.option-size .select-option-collection');
        self.helper.quantityList = self.helper.optionList.find('.option-quantity .select-option-collection');

        // change variant click
        self.helper.variantList.find('a').click(function(e) {
            e.preventDefault();

            if (self.helper.variantList.find('a.select-selected').text() != $(this).text())
                self.changeVariant($(this).text(), $(this).attr('value'));
        });

        return;
    },

    /*
    * Initializes the cross sells
    */
    initCrossSells: function() {

        var self = this;
        var count = self.helper.crossSells.length;
        var visible = 2;

        if (count == 1)
            visible = 3;

        // loop through collections
        self.helper.crossSells.each(function(i, list) {

            var length = $(list).children().length;
            var pages = Math.ceil(length / visible);
            var index = 0;

            // initialize the carousel
            if (length > visible)
            {
                $(list)
	                .addClass('crosssellitem-collection-' + visible)
	                ;

                var $prev = $('<a class="prev-item" href="#">' + self.opts.res.previous + '</a>').prependTo($(list).parent());
                var $next = $('<a class="next-item" href="#">' + self.opts.res.next + '</a>').insertAfter($(list));

                $next
	                .css({
	                    top: parseInt($(list).css('height')) + 16 + 'px'
	                })
	                ;

                function page(index) {

                    if (index == 0)
                    {
                        $prev
	                        .addClass('disabled')
	                        ;
                    }
                    else
                    {
                        $prev
	                        .removeClass('disabled')
	                        ;
                    }

                    if (index + 1 == pages)
                    {
                        $next
	                        .addClass('disabled')
	                        ;
                    }
                    else
                    {
                        $next
	                        .removeClass('disabled')
	                        ;
                    }


                    $(list).children()
	                    .css({
	                        display: 'none'
	                    })
	                    ;

                    for (var j = index * visible; j < (index + 1) * visible; j++)
                    {
                        if ($(list).children()[j])
                        {
                            $($(list).children()[j])
	                            .css({
	                                opacity: '0.00',
	                                display: 'block'
	                            })
	                            .fadeTo(1000, '1.00')
	                            ;
                        }
                    }
                }

                // init
                page(index);

                // prev click
                $prev.click(function(e) {
                    e.preventDefault();

                    if (index - 1 >= 0) {
                        index--;
                        page(index);
                    }
                });

                // next click
                $next.click(function(e) {
                    e.preventDefault();

                    if (index + 1 < pages) {
                        index++;
                        page(index);
                    }
                });
            }
        });

        return;
    },

    /*
    * GetSizes success
    */
    getSizesSuccess: function(data) {
        
        var self = $.productDetail.impl;
        var v = eval(data);
        var sizes = v.AvailableSizes;
        var price = v.Price;
        
        // update the price
        var $price = $('<div class="product-price"></div>');

        if (price.GrossPrice > 0)
        {
            if (price.MarkDownPrice > 0)
            {
                $price
	                .addClass('product-price-markdown')
	                .html('<span class="original">' + currency.format(price.GrossPrice, self.opts.currency) + '</span><span class="markdown product-price-animate">' + currency.format(price.MarkDownPrice, self.opts.currency) + '</span>')
	                ;
            }
            else
            {
                $price
	                .addClass('product-price-gross product-price-animate')
	                .html(currency.format(price.GrossPrice, self.opts.currency))
	                ;
            }

            self.helper.price
	            .replaceWith($price)
	            ;

            self.helper.price = $price;
        }

        // walk the sizes
        self.helper.sizeList.find('li.select-option').each(function(i, item) {

            var sizeCodeVal = $(item).find('a').attr('value');

            if (sizeCodeVal == '' || sizeCodeVal == 'null') {
                self.helper.optionList.find('.option-size a.select-selected')
	                .attr('value', 'null')
	                .html('<span>' + self.opts.res.size + ': </span><span class="select-selected-value"></span>')
	                ;

                return;
            }

            if (sizes.length < 1)
                $(item).addClass('select-option-disabled');

            // walk the result
            $.each(sizes, function(i, size) {

                if (sizeCodeVal == size.Key) {
                    $(item).removeClass('select-option-disabled');
                    return false;
                }
                else {
                    $(item).addClass('select-option-disabled');
                }

            });

        });

        // unblock
        self.helper.container.find('ul.option-collection li.option-size .select-container')
	        .unblock()
            ;
        
        return;
    },

    /*
    * Get Failure
    */
    getFailure: function() {

        

    }

};

$.fn.setSelected = function(value, clear) {

    var v = value;
    var vT = typeof (value);
    var c = clear || false;

    // has to be a string or regular expression (object in IE, function in Firefox)
    if (vT != "string" && vT != "function" && vT != "object") return this;

    this.children().each(function(i, o) {
        if (v.constructor == RegExp) {
            if (o.value.match(v)) {
                o.selected = true;
            }
            else if (c) {
                o.selected = false;
            }
        }
        else {
            if (o.value == v) {
                o.selected = true;
            }
            else if (c) {
                o.selected = false;
            }
        }
    });

    return this;
};

})(jQuery);
