(function($) {

    $.brandProductList = function(options) {
        return $.brandProductList.impl.init(options);
    };

    $.fn.brandProductList = function(options) {
        return $.brandProductList.impl.init(this, options);
    };

    /*
    * default options
    */
    $.brandProductList.defaults = {
        pageSize: 5,
        pageIndex: 0,
        collection: null,
        res: {},
        products: new Array(),
        sCnt: 1
    };

    $.brandProductList.impl = {

        /*
        * options
        */
        opts: null,

        /*
        * helper
        */
        helper: {},

        /*
        * Init
        */
        init: function(options) {

            var self = this;
            this.opts = $.extend({}, $.brandProductList.defaults, options);

            self.helper.container = $('div.page-brandproductlist');
            self.helper.list = self.helper.container.find('ul.rtwitem-collection');
            self.helper.data = self.helper.list.clone();
            self.helper.nav = self.helper.container.find('div.nav-container');
            //self.helper.container.find('.brand-logo img').pngFix()

            var src = self.helper.container.find('.brand-logo img').attr('src');

            // load the images
            $(new Image()).load(function() {

                self.helper.container.find('.brand-logo img').pngFix();

            }).attr('src', src);
            
            
                    
            self.initNav();
            self.carousel(self.opts.collection);

            return self;
        },

        /*
        * Initializes the nav
        */
        initNav: function() {

            var self = this;
            var $list = self.helper.nav.find('ul#nav-brandproductlist');

            if (self.opts.collection != '' && self.opts.collection != null)
                $list.find('li.col-' + self.opts.collection)
		            .addClass('li-1-active')
		            ;
            else
                $($list.children()[0])
		            .addClass('li-1-active')
		            ;

            $list.siblings('.collection-info')
                .html($list.find('.li-1-active .collection-info').html())
                ;

            var $selected = $('<a class="category-selected" href="#">' + $list.find('.li-1-active .a-1').text() + '</a>').insertBefore($list);

            $selected
                .click(function(e) {
                    e.preventDefault();

                    if (!$list.hasClass('ul-1-open')) {
                        $list
		                    .addClass('ul-1-open')
		                    ;

                        $selected
		                    .text($list.find('.li-1-active .a-1').text())
		                    ;

                        // blur
                        self.helper.nav.find('a')
		                    .blur(function() {
		                        $list
	                                .removeClass('ul-1-open')
	                                ;
		                    })
	                        ;

                        // click
                        $list.find('a')
	                        .click(function() {

	                            $(this).parent()
	                                .addClass('li-1-active')
	                                .siblings()
	                                    .removeClass('li-1-active')
	                                    ;

	                            $selected
		                            .text($(this).text())
		                            ;

	                            $list
	                                .removeClass('ul-1-open')
	                                ;
	                        })
	                        ;

                        // hover
                        self.helper.nav.find('a')
		                    .hover(
		                        function() {
		                            self.helper.nav.find('a').unbind('blur');
		                        },
		                        function() {
		                            self.helper.nav.find('a').blur(function() {
		                                $list
	                                        .removeClass('ul-1-open')
	                                        ;
		                            });
		                        }
		                    )
		                    ;
                    }
                    else {
                        $list
		                    .removeClass('ul-1-open')
		                    ;

                        $selected
		                    .text($list.find('.li-1-active .a-1').text())
		                    ;
                    }
                })
                ;

            $list.find('a.a-1').click(function(e) {
                e.preventDefault();

                $list
	                .removeClass('ul-1-open')
	                ;

                if ($(this).parent().hasClass('li-1-active'))
                    return;

                $(this).parent()
		            .addClass('li-1-active')
		            .siblings()
		            .removeClass('li-1-active')
		            ;

                $selected
	                .text($(this).text())
	                ;

                var c = $(this).attr('href').split('#')[1];

                $list.siblings('.collection-info')
	                .html($(this).siblings('.collection-info').html())
	                ;

                self.carousel(c);

            });

            self.helper.nav
		        .fadeIn(1000)
		        ;

            return;
        },

        /*
        * Initializes the carousel
        */
        carousel: function(collection) {

            var self = this;
            var $container = $('<div class="rtw-container"></div>');

            self.helper.list = $('<ul class="rtwitem-collection"></ul>');
            self.helper.pages = $('<ul class="page-collection"></ul>');

            self.helper.container.find('div.rtw-container')
		        .before($container)
		        .removeClass('rtw-container')
		        .css({
		            position: 'absolute',
		            left: '-999em'
		        })
		        ;

            // apply filter
            if (collection != null && collection != '') {
                self.helper.list
		            .append(self.helper.data.find('li.col-' + collection).clone())
		            ;
            }
            else {
                self.helper.list
		            .append(self.helper.data.children().clone())
		            ;
            }

            self.helper.list
		        .appendTo($container)
		        ;

            self.opts.pageIndex = 0;
            self.opts.length = self.helper.list.children().length;

            while (self.opts.length % self.opts.pageSize != 0) {
                var $dummy = $('<li class="rtwitem"></li>');

                self.helper.list.append($dummy);
                self.opts.length++
            }

            // bind the events
            self.bind();

            // initialize the carousel
            self.helper.list.jcarousel({
                scroll: self.opts.pageSize,
                animation: 0,
                buttonPrevHTML: '<div></div>',
                buttonNextHTML: '<div></div>',
                initCallback: self.carouselInit,
                itemLastInCallback: self.carouselIndexChanged
            });

            return;
        },

        /*
        * Binds the events
        */
        bind: function() {

            var self = $.brandProductList.impl;

            self.helper.list.find('a.rtwitem-link')
                .hover(function() {

                    var $item = $(this).parent();

                    $item.siblings().find('img')
	                    .queue('fx', [])
                        .fadeTo(300, '0.40')
                        ;

                    self.getBrandProds($item);

                }, function() {

                    $(this).parent().siblings().find('img')
	                    .queue('fx', [])
                        .fadeTo(300, '1.00')
                        ;

                })
                ;

            return;
        },

        /*
        * Carousel init callback
        */
        carouselInit: function(carousel, state) {

            var self = $.brandProductList.impl;
            var pageCount = Math.ceil(self.opts.length / self.opts.pageSize);

            if (pageCount < 2)
                self.helper.pages
                    .css({
                        display: 'none'
                    })
                    ;

            for (var i = 0; i < pageCount; i++) {
                var $li = $('<li class="page"><a class="page-' + i + '" href="#">' + (i + 1) + '</a></li>');

                if (i == self.opts.pageIndex)
                    $li.addClass('page-active');

                self.helper.pages.append($li);
            }

            self.helper.pages.find('a').click(function(e) {
                e.preventDefault();

                var p = $(this).attr('class').split('-')[1];

                if (p == self.opts.pageIndex)
                    return;

                self.page(p, carousel);

            });

            carousel.container.parent().append(self.helper.pages);

            self.helper.pages
		        .css({
		            marginLeft: -self.helper.pages.width() / 2 + 'px',
		            left: '50%'
		        })
		        ;

            // bind the tooltip
            carousel.list.find('a.rtwitem-link').tooltip({
                id: 'rtwitem-tooltip',
                track: true,
                showURL: false,
                delay: 0,
                bodyHandler: function() {
                    return $(this).siblings('.rtwitem-info').clone();
                }
            });

            // bind next hover
            carousel.buttonNext
		        .hover(
		            function() { $(this).addClass('jcarousel-next-hover') },
		            function() { $(this).removeClass('jcarousel-next-hover') }
		        )
		        .appendTo(self.helper.container.find('div.rtw-container'))
		        ;

            // bind prev hover
            carousel.buttonPrev
		        .hover(
		            function() { $(this).addClass('jcarousel-prev-hover') },
		            function() { $(this).removeClass('jcarousel-prev-hover') }
		        )
		        .appendTo(self.helper.container.find('div.rtw-container'))
		        ;

            return;
        },

        /*
        * Carousel index changed callback
        */
        carouselIndexChanged: function(carousel, item, i, action) {

            var self = $.brandProductList.impl;

            self.opts.pageIndex = i / self.opts.pageSize - 1;

            if (action == 'prev') {
                self.helper.pages.find('a.page-' + self.opts.pageIndex).parent()
                    .addClass('page-active')
                    .siblings()
                    .removeClass('page-active')
                    ;
            }
            else if (action == 'next') {
                self.helper.pages.find('a.page-' + self.opts.pageIndex).parent()
                    .addClass('page-active')
                    .siblings()
                    .removeClass('page-active')
                    ;
            }

            return;
        },

        /*
        * Updates the current page
        */
        page: function(p, carousel) {

            var self = this;

            self.opts.pageIndex = parseInt(p);

            var scroll = self.opts.pageIndex * self.opts.pageSize + 1;

            carousel.scroll(jQuery.jcarousel.intval(scroll));

            return;
        },

        /*
        * Get Brand Products or not
        */
        getBrandProds: function($item) {

            var self = $.brandProductList.impl;

            if ($item.data('isLoading') || $item.data('isLoaded'))
                return;

            $item
                .data('isLoading', true)
                ;

            var productIds = $item.find('img.rtwitem-image').attr('rel');

            CreateThe.Com.Web.CodeBase.WebServices.ProductService.GetBrandProducts(productIds, self.opts.folderId, self.opts.root, self.opts.lang, self.opts.region, self.opts.priceCode, $.brandProductList.impl.getBrandProductsSuccess, $.brandProductList.impl.getBrandProductsFailure, $item);

            return;
        },

        /*
        * Get Brand Products Success
        */
        getBrandProductsSuccess: function(data, $item) {

            var self = $.brandProductList.impl;
            var result = eval(data);

            if (result.Count < 1)
                return;

            $item
                .data('isLoading', false)
                .data('isLoaded', true)
                ;

            var products = result.Products;
            var $products = $('<ul>');

            $.each(products, function(i, product) {

                var $product = $('<li>');
                var $title = $('<div>');
                var $price = $('<div>');

                $title
                    .addClass('product-title')
                    .html(product.SafeProductName)
                    ;

                $price
                    .addClass('product-price')
                    ;

                $product
                    .addClass('product')
                    .append($title)
                    ;

                var skus = [];
                var $variants = $('<ul class="variantselector-collection"></ul>');

                $.each(product.Skus, function(j, sku) {

                    if (self.opts.isCountryShoppable && j == 0) {
                        var d0 = new Date();
                        var d1 = new Date(sku.EffectiveFrom);
                        var d2 = new Date(sku.EffectiveTo);
                        var isMarkdown = (d0 > d1 && d0 < d2 && sku.MarkdownPrice > 0);

                        $price
                            .append('<div class="price-retail">' + currency.format(sku.Price, self.opts.currency) + '</div>')
                            ;

                        if (isMarkdown)
                            $price
                                .addClass('price-ismarkdown')
                                .append('<div class="price-markdown">' + currency.format(sku.MarkdownPrice, self.opts.currency) + '</div>')
                                ;

                        if (self.opts.isVatIncluded)
                            $price
                                .append('<div class="price-vatincluded">(' + self.opts.res.vatIncluded + ')</div>')
                                ;

                        $price
                            .append('<div class="clear"></div>')
                            ;

                        $product
                            .append($price)
                            .append('<div class="clear"></div>')
                            ;
                    }

                    if (!skus[sku.VariantName] && !isNullOrEmpty(sku.SwatchImage)) {
                        var swatchUrl = self.getImagePath(self.opts.ctsImageUrlRaw);

                        $variants
                            .append('<li class="variantselector"><a href="#"><img src="' + swatchUrl + "/swatches/19/19/" + sku.SwatchImage + '" /></a></li>')
                            ;

                        skus[sku.VariantName] = true;
                    }

                });

                $product
                    .append($variants)
                    .append('<div class="clear"></div>')
                    .appendTo($products)
                    ;

            });

            var $tooltip = $('div#rtwitem-tooltip');

            //            $tooltip
            //                .css({
            //                    height: $tooltip.height() + 'px',
            //                    overflow: 'hidden'
            //                })
            //                ;

            // append the products to the tooltip
            $tooltip.find('.product-collection')
                .remove()
                ;

            $products.clone()
                .addClass('product-collection')
            //                .css({
            //                    opacity: '0.00'
            //                })
                .appendTo($tooltip.find('.rtwitem-info'))
            //.fadeTo(500, '1.00')
                ;

            //            $tooltip
            //                .animate({
            //                    height: tooltip.height() + $products.height() + 'px'
            //                }, 500, 'easeOutCubic')
            //                ;

            // append the products to the look
            $item.find('.rtwitem-info')
                .append($products)
                ;

            return;
        },

        /*
        *  Get image path
        */
        getImagePath: function(url) {

            var self = $.brandProductList.impl;

            if (url.indexOf('{0}') === -1) {
                return url;
            }
            else {
                var ran_unrounded = Math.random() * self.opts.imgSrvrCount;
                var ran_number = Math.floor(ran_unrounded) + 1;
                var path = url.replace('{0}', ran_number);

                return path;
            }
        },

        /*
        *  Get Brand Products Failure
        */
        getBrandProductsFailure: function(data) {

            var self = $.brandProductList.impl;

            // do nothing

            return;
        }

        /*
        * Fix IE
        */
        /* fixIE: function(item) {

            if (!$.browser.msie || ($.browser.version >= 7))
                return;

            var self = this;
            var $logo = $(item).find('img.brand-logo');

            $logo
		        .pngFix()
                ;

            return;
        }*/
    };

})(jQuery);
