(function($) {

    $.quickBuy = function(options) {
        return $.quickBuy.impl.init(options);
    };

    $.fn.quickBuy = function(options) {
        return $.quickBuy.impl.init(this, options);
    };

    /*
    * default options
    */
    $.quickBuy.defaults = {
        res: {}
    };

    $.quickBuy.impl = {

        /*
        * options
        */
        opts: null,

        /*
        * helper
        */
        helper: {},

        /*
        * product id
        */
        productId: null,

        /*
        * Initialize the page
        */
        init: function(modal, options) {

            var self = this;

            this.opts = $.extend({}, $.quickBuy.defaults, options);

            // helpers
            self.helper.modal = modal;
            self.helper.overlay = $('<div class="overlay"></div>').insertBefore(self.helper.modal);
            self.helper.close = $('<a class="close-quickbuy" href="#">' + self.opts.res.close + '</a>').prependTo(self.helper.modal);
            self.helper.productImagery = self.helper.modal.find('.product-imagery');
            self.helper.productInfo = self.helper.modal.find('.product-info');
            self.helper.variantSelectors = self.helper.modal.find('ul.variantselector-collection');
            self.helper.options = self.helper.modal.find('ul.option-collection');
            self.helper.optionVariant = self.helper.options.find('.option-color');
            self.helper.optionSize = self.helper.options.find('.option-size');
            self.helper.optionQuantity = self.helper.options.find('.option-quantity');
            self.helper.addProduct = self.helper.modal.find('a.add-product');

            // set the position
            self.position();

            // bind the events
            self.events();

            // init quantity select box
            self.initSelect(self.helper.optionQuantity.find('select'));

            return self;
        },

        /*
        * Position
        */
        position: function() {

            var self = this;
            var $content = $('div#content');

            self.helper.modal
                .css({
                    left: '50%',
                    top: '50%',
                    marginLeft: -self.helper.modal.outerWidth() / 2 + 'px',
                    marginTop: -self.helper.modal.outerHeight() / 2 + 'px'
                })
                ;

            return;
        },

        /*
        * Events
        */
        events: function() {

            var self = this;

            // open
            $('a.open-quickbuy').click(function(e) {
                e.preventDefault();

                var productId = $(this).attr('href').split('#')[1];

                self.show(productId);
            });

            // close
            self.helper.close.click(function(e) {
                e.preventDefault();
                self.hide();
            });

            // overlay
            self.helper.overlay.click(function(e) {
                e.preventDefault();
                self.hide();
            });

            return;
        },

        /*
        * Show
        */
        show: function(productId) {

            var self = this;

            // set the product Id
            self.productId = productId;

            // reset the modal
            self.reset();

            CreateThe.Com.Web.CodeBase.WebServices.ProductService.GetProduct(productId, self.opts.folderId, self.opts.root, self.opts.lang, self.opts.region, self.opts.priceCode, $.quickBuy.impl.getProductSuccess, $.quickBuy.impl.getFailure);

            self.helper.modal
		        .fadeIn(1000)
		        ;

            self.helper.overlay
		        .css({
		            opacity: '0.00',
		            display: 'block'
		        })
		        .fadeTo(1000, '0.60')
		        ;

            return;
        },

        /*
        * Resets the modal
        */
        reset: function() {

            var self = this;

            self.helper.productImagery
		        .empty()
		        ;

            self.helper.productInfo
		        .css({
		            display: 'none'
		        })
		        ;

            self.helper.variantSelectors
		        .empty()
		        ;

            // reset the variant select box
            self.helper.optionVariant.find('.select-container')
		        .remove()
		        ;
            self.helper.optionVariant.find('select')
		        .empty()
		        ;

            // reset the size select box
            self.helper.optionSize.find('.select-container')
		        .remove()
		        ;
            self.helper.optionSize.find('select')
		        .empty()
		        .append($('<option value="null">' + self.opts.res.size + ':</option>'))
		        ;

            return;
        },

        /*
        * Hide
        */
        hide: function() {

            var self = this;

            self.helper.modal
		        .fadeOut(1000)
		        ;

            self.helper.overlay
		        .fadeOut(1000)
		        ;

            return;
        },

        /*
        * getProduct succes
        */
        getProductSuccess: function(data) {

            var self = $.quickBuy.impl;
            var product = eval(data);
            var link = product.FolderBreadCrumb + product.ProductId;

            self.helper.productImagery
		        .attr('href', link)
		        ;

            // load the image
            $(new Image).load(function() {

                $(this)
		            .css({
		                display: 'none'
		            })
		            ;

                self.helper.productImagery
		            .append($(this))
		            ;

                $(this)
		            .fadeIn(500)
		            ;

            }).attr('src', json.ctsImageServerUrl + '/products/187/219/' + product.SystemFileName);

            self.helper.modal.find('.product-brand')
		        .html(product.ProductName)
		        ;

            self.helper.modal.find('.product-collectionname')
		        .html(product.Collection)
		        ;

//            self.helper.modal.find('.product-title')
//		        .html(product.ProductName)
//		        ;

            self.helper.modal.find('.product-price')
		        .html(currency.format(product.Price, self.opts.currency))
		        ;

            self.helper.modal.find('.product-description')
		        .html(product.Description)
		        ;

            self.helper.modal.find('.product-link a')
		        .attr('href', link)
		        ;

            var variantSkus = [];
            var sizeSkus = [];

            // walk the skus
            $.each(product.Skus, function(i, sku) {

                var variantSkuAdded = false;
                var sizeSkuAdded = false;

                $.each(variantSkus, function(j, variantSku) {

                    if (variantSku.VariantName == sku.VariantName)
                        variantSkuAdded = true;

                });

                $.each(sizeSkus, function(j, sizeSku) {

                    if (sizeSku.SizeCode == sku.SizeCode)
                        sizeSkuAdded = true;

                });

                var $option;

                if (!variantSkuAdded) {
                    variantSkus.push(sku);

                    var $variant = $('<li class="variantselector"><span><img src="' + json.ctsImageServerUrl + '/products/19/19/' + sku.SwatchImage + '" /></span></li>');
                    $option = $('<option value="' + sku.VariantName + '">' + sku.VariantName + '</option>');

                    self.helper.variantSelectors
		                .append($variant)
		                ;

                    self.helper.optionVariant.find('select')
		                .append($option)
		                ;
                }

                if (!sizeSkuAdded) {
                    sizeSkus.push(sku);

                    $option = $('<option value="' + sku.SizeCode + '">' + sku.SizeCode + '</option>');

                    self.helper.optionSize.find('select')
		                .append($option)
		                ;
                }
            });

            // initialize the select boxes
            self.initSelect(self.helper.optionVariant.find('select'));
            self.initSelect(self.helper.optionSize.find('select'));

            // get the sizes
            CreateThe.Com.Web.CodeBase.WebServices.ProductService.GetSizes(self.productId, self.opts.folderId, self.opts.root, self.opts.lang, self.opts.region, self.opts.priceCode, self.helper.optionVariant.find('select').val(), $.quickBuy.impl.getSizesSuccess, $.quickBuy.impl.getFailure);

            return;
        },

        /*
        * GetSizes success
        */
        getSizesSuccess: function(data) {

            var self = $.quickBuy.impl;
            var sizes = eval(data)

            // walk the sizes
            self.helper.optionSize.find('li.select-option').each(function(i, item) {

                var sizeCodeVal = $(item).find('a').attr('value');

                if (sizeCodeVal == '' || sizeCodeVal == 'null') {
                    self.helper.optionSize.find('a.select-selected')
		                .attr('value', 'null')
		                .text($(item).text())
		                ;

                    return false;
                }

                // walk the result
                $.each(sizes, function(i, size) {

                    if (sizeCodeVal == size.Key) {
                        $(item).removeClass('select-option-disabled');
                        return false;
                    }
                    else {
                        if ($(item).prevAll().length > 0)
                            $(item).addClass('select-option-disabled');
                    }

                });

            });
            
            // bind add product click
            self.helper.addProduct
		        .unbind()
		        .click(function(e) {
		            e.preventDefault();

		            var sizeCode = self.helper.optionSize.find('a.select-selected').attr('value');
		            var variantCode = self.helper.optionVariant.find('a.select-selected').attr('value');
		            var quantity = self.helper.optionQuantity.find('a.select-selected').attr('value');

		            if (sizeCode == '' || sizeCode == 'null') {
		                alert(self.opts.res.pleaseSelectSize)
		                return;
		            }

		            $.shoppingBag.impl.addProduct(self.productId, sizeCode, variantCode, quantity, $.quickBuy.impl.addProductCallback);

		        })
		        ;
            
            // show the info after everything is rendered
            self.helper.productInfo
		        .fadeIn(500)
		        ;

            return;
        },

        /*
        * addProduct callback
        */
        addProductCallback: function(data) {

            var self = $.quickBuy.impl;
            var count = (data > 0) ? data : 0;

            if (data < 0) {
                alert(self.opts.res.anErrorHasOccurred);

                return;
            }

            // hide
            self.hide();

            return;
        },

        /*
        * Initializes the select box
        */
        initSelect: function(item) {

            var self = this;
            var $og = $(item).hide();
            var ogId = $og.attr('id');
            var ogClass = $og.attr('class');
            var selectedIndex = $og.children("option:selected").prevAll().length;
            var values = [];
            var texts = [];

            $og.children().each(function(j) {

                values[j] = $(this).attr('value');
                texts[j] = $(this).text();

            });

            var $sContainer = $('<div class="select-container"></div>').insertAfter($og);
            var $sSelected = $('<a href="#" class="select-selected" value="' + values[selectedIndex] + '">' + texts[selectedIndex] + '</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.text($(this).text());
                    $sSelected.attr('value', $(this).attr('value'));
                }

                $sContainer
                    .removeClass('select-container-show')
                    ;

                // update the size ddl when variant is changed
                if ($(this).parent().parent().parent().parent().hasClass('option-color')) {
                    self.variantCode = $(this).attr('value');

                    CreateThe.Com.Web.CodeBase.WebServices.ProductService.GetSizes(self.productId, self.opts.folderId, self.opts.root, self.opts.lang, self.opts.region, self.opts.priceCode, self.variantCode, $.quickBuy.impl.getSizesSuccess, $.quickBuy.impl.getFailure);
                }

            });

            // link hover
            $sContainer.find('a').hover(
	            function() {
	                $sContainer.find('a').unbind('blur');
	            },
	            function() {
	                $sContainer.find('a').blur(function() {
	                    $sContainer
	                        .removeClass('select-container-show')
	                        ;
	                });
	            }
	        );

            return;
        },

        /*
        * get Failure
        */
        getFailure: function() {

            alert('failure');

        }

    };
})(jQuery);
