(function($) {
    
    $.productList = function(options, keyword) {
        return $.productList.impl.init(options, keyword);
    };
    
    $.fn.productList = function(options) {
        return $.productList.impl.init(this, options);
    };
    
    /*
    * default options
    */
    $.productList.defaults = {
        folderBreadCrumb: null,
        lang: null,
        region: null,
        root: null,
        priceCode: null,
        sizeCode: {},
        styleCode: {},
        variantFamily: {},
        sortRule: 'relevance',
        enableFacets: true,
        itemsPerPage: 10,
        itemsCount: 0,
        pageIndex: 0,
        pageCount: 0,
        res: {
    }
};

$.productList.impl = {
    
    /*
    * options
    */
    opts: null,
    
    /*
    * helper
    */
    helper: {},
    
    /*
    * facets
    */
    facets: [{
        'Id': 'f-size',
        'Focis': []
    },{
        'Id': 'f-style',
        'Focis': []
    },{
        'Id': 'f-variant',
        'Focis': []
    }],
    
    /*
    * keyword
    */
    keyword: '',
    
    /*
    * category
    */
    category: '',
    
    /*
    * loader
    */
    loader: null,
    
    /*
    * content height
    */
    contentHeight: 666,
    
    /*
    * sort
    */
    sort: '',
    
    /*
    * count
    */
    count: 0,
    
    /*
    * page
    */
    page: 1,
    
    /*
    * page count
    */
    pageCount: 0,
    
    /*
    * Initializes the page
    */
    init: function(options, keyword) {
        
        var self = this;
        
        this.opts = $.extend({}, $.productList.defaults, options);
        
        
        
        self.keyword = !isNullOrEmpty(keyword) ? keyword: self.keyword;
        
        // helper objects
        self.helper.container = $('div.page-productlist');
        self.helper.facets = self.helper.container.find('ul.facet-collection');
        self.helper.products = self.helper.container.find('ul.product-collection');
        self.helper.sorters = self.helper.container.find('ul.sorter-collection');
        self.helper.selectees = self.helper.container.find('ul.selectee-collection');
        self.helper.loader = $('<div class="loader"></div>').appendTo(self.helper.container);
        self.helper.pages = $('<ul class="page-collection"></ul>').prependTo(self.helper.container.find('div.product-container'));
        self.helper.prev = $('<a class="page-control prev-page page-control-disabled" href="#">' + self.opts.res.previous + '</a>').appendTo(self.helper.container);
        self.helper.next = $('<a class="page-control next-page page-control-disabled" href="#">' + self.opts.res.next + '</a>').insertAfter(self.helper.container.find('div.product-container'));
        self.helper.clear = self.helper.container.find('a.clear-selectees');
        self.helper.nav = self.helper.container.find('div.category-container');
        self.helper.resultInfo = self.helper.container.find('div.resultinfo-container');
        self.helper.facetNote = self.helper.container.find('div.facet-note');
        
        // temporarily disable loading animation
//        self.loader = self.helper.container.loader({
//            onShow: function(){
//                self.initProductList();
//            }
//        });
        
        self.initProductList();
        
        self.contentHeight = $('#content').height();
        
        return self;
    },
    
    /*
    * Initializes the ProductList page
    */
    initProductList: function() {
        
        var self = this;
        
        // initialize the nav
        self.initNav();
        
        // check for no items
        if (self.opts.count < 1)
        {
            self.helper.sorters.parent()
                .css({
                    display: 'none'
                })
                ;
            
            self.helper.next
                .css({
                    display: 'none'
                })
                ;
            
            self.helper.prev
                .css({
                    display: 'none'
                })
                ;
            
            return;
        }
        
        // init the deep linking
        var p = SWFAddress.getParameter("p");
        var s = SWFAddress.getParameter("s");
        var z = SWFAddress.getParameter("f-size");
        var y = SWFAddress.getParameter("f-style");
        var v = SWFAddress.getParameter("f-variant");
        
        self.page = !isNullOrEmpty(p) ? parseInt(p) : self.page;
        self.sort = !isNullOrEmpty(s) ? s : self.sort;
        
        var params = 'f-size=' + z + '&f-style=' + y + '&f-variant=' + v + '&p=' + self.page + '&s=' + self.sort;
        
        SWFAddress.onInit = function() {
            SWFAddress.setValue('/?' + params);
        }
        
        $.each(self.facets, function(i, facet) {
            if (facet.Id == 'f-size' && !isNullOrEmpty(z))
                facet.Focis.push(z);
            else if (facet.Id == 'f-style' && !isNullOrEmpty(y))
                facet.Focis.push(y);
            else if (facet.Id == 'f-variant' && !isNullOrEmpty(v))
                facet.Focis.push(v);
        });
        
        // get the Result and initialize
        CreateThe.Com.Web.CodeBase.WebServices.SearchService.GetResult(self.opts.lang, self.opts.region, self.opts.root, self.opts.priceCode, self.opts.folderBreadCrumb, v, z, y, '', self.keyword, self.category, self.sort, self.page, $.productList.impl.initResultSuccess, $.productList.impl.getFailure);
        
        // bind the controls
        self.bindControls();
        
        return;
    },
    
    /*
    * Binds the controls
    */
    bindControls: function() {
        
        var self = this;
        
        // prev click
        self.helper.prev
	        .unbind()
	        .click(function(e) {
	            e.preventDefault();
	            if ($(this).hasClass('page-control-disabled'))
	                return;
	            self.page--;
	            self.updateResult();
	        })
	        ;
	    
        // next click
        self.helper.next
	        .unbind()
	        .click(function(e) {
	            e.preventDefault();
	            if ($(this).hasClass('page-control-disabled'))
	                return;
	            self.page++;
	            self.updateResult();
	        })
	        ;
        
        // clear click
        self.helper.clear
	        .click(function(e) {
	            e.preventDefault();
	            self.clearSelectees();
	        })
	        ;
        
        // sort click
        self.helper.sorters.find('a')
	        .click(function(e) {
	            e.preventDefault();
	            
	            if ($(this).parent().hasClass('sorter-active'))
	            {
	                $(this).parent()
	                    .removeClass('sorter-active')
	                    ;
	                
	                self.sort = '';
	            }
	            else
	            {
	                $(this).parent()
	                    .addClass('sorter-active')
	                    .siblings()
	                        .removeClass('sorter-active')
	                        ;
	                
	                self.sort = $(this).attr('href').split('#')[1];
	            }
	            
	            self.updateResult();
	        })
	        ;
        
        return;
    },

    /*
    * Initializes the nav
    */
    initNav: function() {
        
        var self = this;
        var $list = self.helper.container.find('ul#nav-productlist');
        var $selected = $('<a class="category-selected" href="#">' + $list.find('.li-1-active').text() + '</a>').insertBefore($list);
        
        $selected.click(function(e) {
            e.preventDefault();
            
            if (!$list.hasClass('ul-1-open'))
            {
                $list
	                .addClass('ul-1-open')
	                ;
                
                $selected
	                .text(self.opts.res.pleaseSelect)
	                ;
                
                // 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').text())
	                ;
            }
        });
        
        return;
    },
    
    /*
    * Init Result success
    */
    initResultSuccess: function(data) {
        
        var self = $.productList.impl;
        var result = eval(data);
        
        self.count = result.Count;
        self.page = result.Page;
        self.pageCount = result.PageCount;
        
        if (self.count > 0)
        {
            // hide the loader
            //self.loader.stop();
            
            // init the Products
            self.updateProducts(result.Products);
            
            // init the Facets
            if (self.opts.enableFacets && isNullOrEmpty(self.keyword))
                self.initFacets(result.Facets);
            
            // show keyword
            if (!isNullOrEmpty(self.keyword))
            {
                self.helper.resultInfo.find('.resultinfo-count')
	                .text(self.count)
	                ;
	            
                self.helper.resultInfo.find('.resultinfo-keyword')
	                .text(self.keyword)
	                ;
            }
        }
        
        return;
    },
    
    /*
    * Inits the Facets
    */
    initFacets: function(facets) {
        
        var self = this;
        
        self.helper.facets
            .css({
                display: 'none'
            })
	        .empty()
	        ;
        
        self.helper.selectees
	        .empty()
	        ;
        
        // walk facets
        $.each(facets, function(i, facet) {
            
            if (facet.Focis.length < 1)
                return;
            
            var $facet = $('<li id="' + facet.Id + '" class="facet"><div class="facet-title">' + facet.Name + '</div></li>');
            
            if (facet.MutuallyExclusive)
                $facet
	                .addClass('facet-exclusive')
	                ;
            
            var $focis = $('<ul class="foci-collection"></ul>').appendTo($facet);
            
            // walk focis
            $.each(facet.Focis, function(j, foci) {
                
                var $foci = $('<li id="' + foci.Id + '" class="foci"><a href="#">' + foci.Name + '</a></li>');
                
                $.each(self.facets, function(i, f) {
                    if (f.Id == facet.Id)
                    {
                        if (f.Focis.contains(foci.Id))
                        {
                            $foci
	                            .addClass('foci-selected')
	                            ;
	                    }
                    }
                });
                
                if (!foci.Enabled) {
                    $foci
	                    .addClass('foci-disabled')
	                    ;
                }
                
                $foci
	                .appendTo($focis)
	                ;
                
            });
            
            $facet
	            .appendTo(self.helper.facets)
	            ;
            
            // bind the events
            self.bindFacets();
            
        });
        
        self.helper.facets
            .css({
                display: 'block'
            })
            //.fadeIn(500, callback)
            ;
    },
    
    /*
    * Update Result success
    */
    updateResultSuccess: function(data) {
        
        var self = $.productList.impl;
        var result = eval(data);
        
        self.count = result.Count;
        self.page = result.Page;
        self.pageCount = result.PageCount;
        
        // init the Facets
        self.updateFacets(result.Facets);
        
        // init the Products
        self.updateProducts(result.Products);
        
        // hide the preloader
        //self.loader.stop();
        
        // hide the loader
        self.helper.loader
            .css({
                display: 'none'
            })
            ;
        
        return;
    },
    
    /*
    * Updates the Facets
    */
    updateFacets: function(facets) {
        
        var self = this;
        
        // walk facets
        $.each(facets, function(i, facet) {
            
            if (facet.Focis.length < 1)
                return;
            
            var $facet = self.helper.facets.find('#' + facet.Id);
            var $focis = $facet.find('ul.foci-collection');
            
            $focis
	            .empty()
	            ;
            
            // walk focis
            $.each(facet.Focis, function(j, foci) {
                
                var $foci = $('<li id="' + foci.Id + '" class="foci"><a href="#">' + foci.Name + '</a></li>');
                
                $.each(self.facets, function(i, f) {
                    if (f.Id == facet.Id) {
                        if (f.Focis.contains(foci.Id))
                            $foci
	                            .addClass('foci-selected')
	                            ;
                    }
                });
                
                if (!foci.Enabled) {
                    $foci
	                    .addClass('foci-disabled')
	                    ;
                }
                
                $focis
	                .append($foci)
	                ;
                
            });

        });
        
        // re-bind the facets
        self.bindFacets();
        
        return;
    },
    
    /*
    * Updates the Products
    */
    updateProducts: function(products) {
        
        var self = this;
        
        self.helper.products
            .empty()
            .css({
                display: 'none'
            })
            ;
        
        self.helper.pages
            .empty()
            ;
        
        self.helper.prev
            .css({
                display: 'block'
            })
            ;
        
        self.helper.next
            .css({
                display: 'block'
            })
            ;
        
        // handle view all
        if (self.page == 0)
        {
            $('div#content')
                .css({
                    backgroundColor: '#000',
                    height: 'auto'
                })
                ;
            
            self.helper.prev
                .css({
                    display: 'none'
                })
                ;
            
            self.helper.next
                .css({
                    display: 'none'
                })
                ;
        }
        else {
            
            $('div#content')
                .css({
                    backgroundColor: '#675a56',
                    height: self.contentHeight + 'px'
                })
                ;
        }
        
        // walk the Products
        if (!isNullOrEmpty(products))
        {
            $.each(products, function(i, product) {
                
                var $p = self.buildProduct(product);
                
                $p
                    .css({
                        display: 'block'
                    })
                    .appendTo(self.helper.products)
                    ;
                
            });
        }
        
        // prev
        if (self.page == 1)
        {
            self.helper.prev
                .addClass('page-control-disabled')
                ;
        }
        else
        {
            self.helper.prev
                .removeClass('page-control-disabled')
                ;
        }
        
        // next
        if (self.page == self.pageCount)
        {
            self.helper.next
                .addClass('page-control-disabled')
                ;
        }
        else
        {
            self.helper.next
                .removeClass('page-control-disabled')
                ;
        }
        
        // pagination
        if (self.pageCount > 1)
        {
            // view all
            var $va = $('<li class="page"><a href="#">' + self.opts.res.viewAll + '</a></li>');
            
            if (self.page == 0)
            {
                $va
                    .addClass('page-active')
                    ;
            }
            
            $va
	            .data('page', 0)
	            .appendTo(self.helper.pages)
	            .click(function(e) {
	                e.preventDefault();
                    
	                if (!$(this).hasClass('page-active'))
	                {
	                    $(this)
                            .addClass('page-active')
                            .siblings()
                            .removeClass('page-active')
                            ;
                        
	                    self.page = 0;
	                }
	                else
	                {
	                    $(this)
                            .removeClass('page-active')
                            ;
                        
	                    self.page = 1;
	                    
	                    
	                    $('div#content')
                            .css({
                                height: self.contentHeight + 'px'
                            })
                            ;
	                }
	                
	                self.updateResult();
	            })
	            ;
            
            // walk pages
            for (var i = 1; i <= self.pageCount; i++)
            {
                var $li = $('<li class="page"><a href="#">' + i + '</a></li>');
                
                $li
	                .data('page', i)
	                .appendTo(self.helper.pages)
	                ;
	            
                $li.find('a')
	                .click(function(e) {
	                    e.preventDefault();
	                    self.page = parseInt($(this).parent().data('page'));
	                    self.updateResult();
	                })
	                ;
                
                if (self.page == i)
                {
                    $li
	                    .addClass('page-active')
	                    ;
	            }
            }
        }
        
        // product count
        var $pc = $('<li class="page"><span class="page-count">' + self.count + ' ' + self.opts.res.products + '</span></li>');
        $pc
	        .appendTo(self.helper.pages)
	        ;
	    
	    // hide the loader
//        self.loader.stop(function(){
//            
//            self.helper.products
//                .fadeIn(500)
//                ;
//            
//        });
        
        self.helper.products
            .css({
                display: 'block'
            })
            //.fadeIn(500)
            ;
        
        return;
    },

    /*
    * Updates the Categories
    */
    updateCategories: function(categories) {

        var self = this;

        self.helper.categories = $('<ul id="nav-productlist" class="ul-1"></ul>');

        self.helper.categories
		        .append($('<li class="li-1 li-1-active"><a class="a-1" href="#">' + self.opts.res.viewAll + '</a></li>'))
		        ;

        $.each(categories, function(i, category) {

            var $li = $('<li class="li-1"><a class="a-1" href="#' + category.Key + '">' + category.Value + '</a></li>');

            self.helper.categories
		            .append($li)
		            ;
        });

        self.helper.container.find('.category-container')
		        .append(self.helper.categories)
		        ;

        self.initSearchNav();

        return;
    },

    /*
    * Builds the product
    */
    buildProduct: function(product) {

        var self = this;
        var $product = $('<li id="' + product.ProductId + '" class="product"></li>');
        var $pBrand = $('<div class="product-brand">' + product.ProductName + '</div>');
        var $pCollectionName = $('<div class="product-collectionname">' + product.Collection + '</div>');
        var $pName = $('<div class="product-name">' + product.ProductName + '</div>');
        var $pVariants = $('<ul class="product-variant-collection"></ul>');
        var $pLink = $('<a class="product-url" title="' + product.ProductName + '">' + product.ProductName + '</a>');
        var $pPrice = $('<div class="product-price"></div>');
        
        // hide price if not shoppable
        if (self.opts.isCountryShoppable) {

            var price;

            if (product.MarkdownPrice > 0)
                price = '<span class="price-original">' + currency.format(product.Price, self.opts.currency) + "</span>&nbsp;&nbsp;" + currency.format(product.MarkdownPrice, self.opts.currency);
            else
                price = (product.Price > 0) ? currency.format(product.Price, self.opts.currency) : currency.format(product.LowPrice, self.opts.currency) + '&#8212;' + currency.format(product.HighPrice, self.opts.currency);
            
            $pPrice
                .append(price)
                ;
        }

        // construct the URL based on selection
        var url = (self.opts.folderBreadCrumb != '') ? product.ProductId : product.FolderBreadCrumb + '/' + product.ProductId;
        var thumbImage = null;
        
        url += '?e=' + product.ExceptionId;
        
        $.each(self.facets, function(i, facet) {

            var s = '&';

            s += facet.Id + '=';

            if (facet.Focis.length > 0) {
                $.each(facet.Focis, function(j, foci) {
                    
                    if (j > 0)
                        s += '+';
                    
                    s += foci;
                    
                });
            }

            url += s;
        });

        url += '&s=' + self.opts.sortRule;
        url += (self.keyword != '') ? '&keyword=' + self.keyword + '&resultCount=' + self.opts.itemsCount : '';

        $pLink
	        .attr('href', url.toLowerCase())
	        ;

        $product
            .css({
                display: 'block'
            })
            .append($('<img class="product-image" src="' + ((thumbImage == null) ? product.Image : thumbImage) + '" alt="' + product.ProductName + '" />'))
            .append($pName)
            .append($pCollectionName)
            .append($pPrice)
            .append($pLink)
            ;

        // create the variants
        $.each(product.SwatchImages, function(i, item) {

            var $li = $('<li class="product-variant"><img src="' + item + '" alt="Swatch" /></li>');

            $pVariants
                    .append($li)
                    ;

        });
        
        // bind product hover
        var $tt = $('<div></div>');

        $tt
	        .append($pBrand.clone())
            .append($pCollectionName.clone())
            .append($pPrice.clone())
            .append($pVariants.clone())
	        ;

        $pLink
	        .hover(
	            function(){
	                $product
	                    .addClass('hover')
	                    ;
	            },
	            function(){
	                $product
	                    .removeClass('hover')
	                    ;
	            }
	        )
	        .tooltip({
	            id: 'product-tooltip',
	            track: true,
	            showURL: false,
	            delay: 0,
	            bodyHandler: function() {
	                return $tt;
	            }
	        })
	        .click(function(e){
	            //e.preventDefault();
	            
	            var href = $(this).attr('href');
	            
//	            $(this)
//                  .attr('href', href + '&p=' + self.page)
	        })
	        ;

        return $product;
    },

    /*
    * Binds the Facets
    */
    bindFacets: function() {
        
        var self = this;

        self.helper.facets.children()
            .each(function(i, facet){
                
                // unbind
                $(facet).find('a')
                    .unbind()
                    ;
                
                if ($(facet).hasClass('facet-exclusive'))
                {
                    // bind mutually exclusive facets
                    $(facet).find('li.foci a')
	                    .click(function(e) {
	                        e.preventDefault();
                            
	                        self.page = 1;

	                        var $li = $(this).parent();
	                        var facetId = $li.parent().parent().attr('id');
	                        var fociId = $li.attr('id');
	                        var fociName = $li.text();
                            
	                        if ($li.hasClass('foci-disabled'))
	                            return;

	                        if (!$li.hasClass('foci-selected'))
	                        {
	                            // append the classes
	                            $li
	                                .addClass('foci-selected')
	                                .siblings()
	                                    .addClass('foci-disabled')
	                                    ;
    	                        
	                            // add the foci
	                            self.addFoci(facetId, fociId);
    	                        
	                            // add the selectee
	                            self.addSelectee(facetId, fociId, fociName);
	                        }
	                        else
	                        {
	                            $li
	                                .removeClass('foci-selected')
	                                .siblings()
	                                    .removeClass('foci-disabled')
	                                    ;
                                
	                            // remove the foci
	                            self.removeFoci(facetId, fociId);
                                
	                            // remove the selectee
	                            self.removeSelectee(facetId, fociId);
	                        }
	                    })
	                    ;
                }
                else
                {
                    // bind inclusive facets
                    $(facet).find('li.foci a')
	                    .click(function(e) {
	                        e.preventDefault();
                            
                            self.page = 1;
                            
	                        var $li = $(this).parent();
	                        var facetId = $li.parent().parent().attr('id');
	                        var fociId = $li.attr('id');
	                        var fociName = $li.text();
                            
	                        if ($li.hasClass('foci-disabled'))
	                            return;
                            
	                        if (!$li.hasClass('foci-selected'))
	                        {
	                            // append the classes
	                            $li
	                                .addClass('foci-selected')
	                                ;
                                
	                            // add the foci
	                            self.addFoci(facetId, fociId);
                                
	                            // add the selectee
	                            self.addSelectee(facetId, fociId, fociName);
	                        }
	                        else
	                        {
	                            $li
	                                .removeClass('foci-selected')
	                                ;
                                
	                            // remove the foci
	                            self.removeFoci(facetId, fociId);
                                
	                            // remove the selectee
	                            self.removeSelectee(facetId, fociId);
	                        }
	                    })
	                    ;
                }
            })
            ;
        
        return;
    },

    /*
    * Adds the Foci
    */
    addFoci: function(facetId, fociId) {
        
        var self = this;
        
        $.each(self.facets, function(i, facet){
            if (facet.Id == facetId)
                facet.Focis.push(fociId);
        });
        
        // update the facets
        self.updateResult();
        
        return;
    },
    
    /*
    * Removes the Foci
    */
    removeFoci: function(facetId, fociId) {
        
        var self = this;
        
        self.helper.facets.find('#' + fociId)
	        .removeClass('foci-selected')
	        ;
	    
        $.each(self.facets, function(i, facet){
            if (facet.Id == facetId)
                facet.Focis.remove(fociId);
        });
        
        // update the facets
        self.updateResult();
        
        return;
    },
    
    /*
    * Updates the Facets
    */
    updateResult: function() {
        
        var self = this;
        
        // show the loader
        self.helper.loader
            .css({
                display: 'block',
                opacity: '0.00'
            })
            ;
        
        self.helper.products
            .empty()
            ;
        
//        self.loader = self.helper.container.loader({
//            onShow: function(){
//                
//            }
//        });
        
        var z = '';
        var y = '';
        var v = '';
        
        $.each(self.facets, function(i, facet) {
            $.each(facet.Focis, function(j, foci) {
                if (facet.Id == 'f-size')
                    z += foci + ' ';
                else if (facet.Id == 'f-style')
                    y += foci + ' ';
                else if (facet.Id == 'f-variant')
                    v += foci + ' ';
            });
        });
        
        var params = 'f-size=' + z.trim() + '&f-style=' + y.trim() + '&f-variant=' + v.trim() + '&p=' + self.page + '&s=' + self.sort;
        
        SWFAddress.setValue('/?' + params);
        
        CreateThe.Com.Web.CodeBase.WebServices.SearchService.GetResult(self.opts.lang, self.opts.region, self.opts.root, self.opts.priceCode, self.opts.folderBreadCrumb, v, z, y, '', self.keyword, self.category, self.sort, self.page, $.productList.impl.updateResultSuccess, $.productList.impl.getFailure);
        
        return;
    },
    
    /*
    * Adds the selectee
    */
    addSelectee: function(facetId, fociId, fociName) {
        
        var self = this;
        var $selectee = $('<li id="s-' + fociId + '" class="selectee"><a href="#">' + fociName + '</a></li>');

        $selectee
	        .prependTo(self.helper.selectees)
	        ;

        // assign facet and foci data to selectee
        $.data($selectee.get(0), 'facetId', facetId);
        $.data($selectee.get(0), 'fociId', fociId);

        // bind the selectees
        self.bindSelectees();

        if (self.helper.selectees.children().length > 0)
            self.helper.clear
	            .css({
	                display: 'block'
	            })
	            ;
        else
            self.helper.clear
		            .css({
		                display: 'none'
		            })
		            ;

        return;
    },

    /*
    * Removes the selectee
    */
    removeSelectee: function(facetId, fociId) {
        
        var self = this;
        
        self.helper.selectees.find('#s-' + fociId)
	        .remove()
	        ;

        if (self.helper.selectees.children().length > 0)
            self.helper.clear
	            .css({
	                display: 'block'
	            })
	            ;
        else
            self.helper.clear
	            .css({
	                display: 'none'
	            })
	            ;

        return;
    },

    /*
    * Clears the selectees
    */
    clearSelectees: function() {
        
        var self = this;
        
        self.helper.selectees.find('li.selectee a')
	        .each(function(i, item) {
                
	            var $li = $(this).parent();
	            var facetId = $.data($li.get(0), 'facetId');
	            var fociId = $.data($li.get(0), 'fociId');
                
	            self.helper.facets.find('#' + fociId)
	                .removeClass('foci-selected')
	                ;
                
	            $.each(self.facets, function(i, facet){
	                if (facet.Id == facetId)
	                    facet.Focis.remove(fociId);
	            });
                
	            // remove the selectee
	            self.removeSelectee(facetId, fociId);
                
	        })
	        ;
        
        // update the facets
        self.updateResult();
        
        return;
    },
    
    /*
    * Bind the selectees
    */
    bindSelectees: function() {
        
        var self = this;
        
        self.helper.selectees.find('li.selectee a')
	        .unbind()
	        .click(function(e) {
	            e.preventDefault();
                
	            var $li = $(this).parent();
	            var facetId = $.data($li.get(0), 'facetId');
	            var fociId = $.data($li.get(0), 'fociId');
                
	            // remove the foci
	            self.removeFoci(facetId, fociId);
                
	            // remove the selectee
	            self.removeSelectee(facetId, fociId);
                
	        })
	        ;
        
        return;
    },

    /*
    * Get Failure
    */
    getFailure: function() {

        // nothing happens

    }

};
})(jQuery);

Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) 
    {
        if (this[i] == element) 
        {
            return true;
        }
    }
    return false;
};

Array.prototype.remove = function(s) {
    var i = 0;  this.indexOf(s);
    if (i != -1) this.splice(i, 1);
};

// indexOf support for IE
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    };
};

// isNullOrEmpty support
window.isNullOrEmpty = function(obj) {
    return (obj === '' || obj === null || obj === undefined)
};

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};