﻿
/* Sky Shop */
var Sky_Shop = {
    Root: '/shop',
    Basket: {},
    Checkout: {},
    Product: {
        ID: 0,
        OptionsXSLT: ''
    },
    Error: function(msg){
        alert(msg);
    },
    RunAjax: function(el, settings){
        o = {
            type: "POST",
            cache: false,
            contentType: "application/json; charset=utf-8",
            beforeSend: function() {
                if (el != null) { el.addClass('processing'); }
            },
            dataType: 'html',
            /*dataFilter: function(data) {
                try {
                    var df = null;
                    if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
                        df = JSON.parse(data);
                    } else {
                        df = eval('(' + data + ')');
                    }
                    if (df.hasOwnProperty('d')) {
                        return df.d;
                    } else {
                        return df;
                    }
                }
                catch (ex) {
                    return data;
                }
            },*/
            complete: function() {
                if (el != null) { el.removeClass('processing'); }
            },
            error: function(a, b, c) {
                Sky_Shop.Error(a.responseText + "\n" + "If you continue to experience problems, please contact us");
                return false;
            }
        };
        o = jQuery.extend(true, o, settings);
                    
        jQuery.ajax(o);
    }
};

/* Init product page purchasing */
Sky_Shop.Product.Init = function()
{
    /* Initialize prettyLoader */
    jQuery.prettyLoader({
		bind_to_ajax: true,
		loader: '/assets/visual/prettyLoader/ajax-loader.gif'
    });
    
    /* Fancy select */
    //jQuery('select').fancySelect({ width: 180, ignoreFirst: true });
    
    /* Tabify any product descriptions */
    jQuery('#read-more').prepend('<div class="tabs"></div>')
        .removeClass('notTabbed').addClass('tabbed')
        .find('h2.read-more').appendTo(jQuery('#read-more .tabs'));
    jQuery(window).bind('hashchange', function(e){
        var url = jQuery.param.fragment();
        if (url != "")
        {
            jQuery('#read-more .tabs a[href$=#' + url + ']').closest('.read-more').addClass('open').siblings().removeClass('open');
            jQuery('#' + url).addClass('open').siblings('.read-section').removeClass('open');
        }
    }).trigger('hashchange');
    
    /* Stock product option change */
	jQuery('.productPurchase .stocked .optionSelect select').live('change', Sky_Shop.Product.StockedOptionSelected);
	
	/* Customisable product option change */
	jQuery('.productPurchase .customisable .optionSelect select').live('change', Sky_Shop.Product.CustomisableOptionChanged);
	jQuery('.productPurchase .customisable .optionSelect input[type=checkbox]').live('change', Sky_Shop.Product.CustomisableOptionChanged);
	
	/* Quantity change */
	jQuery('.productPurchase input.quantityRequired').live('keyup', Sky_Shop.Product.ShowTotal);
	jQuery('.productPurchase select.quantityRequired').live("change", Sky_Shop.Product.ShowTotal);
	
	/* Buy click */
	jQuery('.productPurchase .addToBasket').live('click', Sky_Shop.Product.AddToBasket);
};

/********************************************/
/* Stock Option drop down selection changed */
/********************************************/
Sky_Shop.Product.StockedOptionSelected = function()
{
    $el = jQuery(this);    
    
    /* Get current selected option */
    curr_selection = jQuery('option:selected', $el).val();
    options = { selected: [], nextType: 0 };
    if (curr_selection > 0)
    {
        /* Get currently selected options */
        $el.closest('.optionSelect').prevAll('.optionSelect').andSelf().find('select').each(function(i, el){
            options.selected.push(jQuery(this).val());
        });
        /* get next option type */
        $next_select = $el.closest('.optionSelect').next('.optionSelect');
        options.nextType = $next_select.find('select').data('type');
        if (options.nextType > 0)
        {
            /* get next type's options - send currently selected options */
            Sky_Shop.RunAjax(null, {
                beforeSend: function(){
                    $next_select.addClass('checking');
                },
                url: Sky_Shop.Root + "/stocked_product/get_options",
                data: JSON.stringify({ ProductID: Sky_Shop.Product.ID, OptionTypeID: options.nextType, OptionsSelected: options.selected, XSLT: Sky_Shop.Product.OptionsXSLT }),
                success: function(data, xhr)
                {
                    /* Add next type options in html and trigger it's change event if only one option */
                    $next_select.removeClass('checking');
                    $next_select = $next_select.find('select');
                    $next_select.html(data);
                    
                    /* Rebuild the next fancy select */
                    if ($next_select.hasClass('fancy')) {
                        $next_select.trigger('contentsChanged');
                    }
                    
                    /* remove quantity/buy section */
                    $el.closest('.productPurchase').find('.purchase .stock').remove();
                }
           });
        }
        else
        {    
            /* Get stock row info */
            Sky_Shop.RunAjax(null, {
                beforeSend: function(){
                    $el.closest('.optionSelect').addClass('checking');
                },
                url: Sky_Shop.Root + "/stocked_product/get_cost",
                data: JSON.stringify({ ProductID: Sky_Shop.Product.ID, OptionsSelected: options.selected, XSLT: Sky_Shop.Product.OptionsXSLT }),
                success: function(data, xhr)
                {
                    $el.closest('.optionSelect').removeClass('checking');
                    $el.closest('.productPurchase').find('.purchase').html(data);
                }
            });
        }
    }  
};

/********************************************/
/*       Customisable Option changed        */
/********************************************/
Sky_Shop.Product.CustomisableOptionChanged = function(e)
{    
    $el = jQuery(this);
    $cost_value_DOM = null;
    if (jQuery('.productPurchase .productPrice .sale.price .value'))
    {
        $cost_value_DOM = jQuery('.productPurchase .productPrice .sale.price .value');
    } else {
        $cost_value_DOM  = jQuery('.productPurchase .productPrice .normal.price .value');
    }
    $product_running_total = parseFloat($cost_value_DOM.text().substr(1));
    $cost = 0;
    if ($el.is('select')){
        $cost = parseFloat($el.find('option:selected').data('cost'));
    } else if ($el.is('input[type=checkbox]')){
        $cost = parseFloat($el.data('cost'));
    }
    
    $activeCost = parseFloat($el.data('activeCost'));
    if (isNaN($activeCost)){
        $activeCost = 0;
    }
    if (isNaN($cost)){
        $cost = 0;
    }
    /* check to see what type of element it is */
    if ($el.is('select')){
        if ($activeCost > 0){
            /* remove active cost from total and add new cost */
            $cost_value_DOM.html('£' + ($product_running_total - $activeCost + $cost).toFixed(2));
        } else {
            /* add new cost */
            $cost_value_DOM.html('£' + ($product_running_total + $cost).toFixed(2));
        }
    } else if ($el.is('input[type=checkbox]')){
        if ($el.is(':checked')){
            /* add cost */
            $cost_value_DOM.html('£' + ($product_running_total + $cost).toFixed(2));
        } else {
            /* remove cost */
            $cost_value_DOM.html('£' + ($product_running_total - $cost).toFixed(2));
        }
    }
    $el.data('activeCost', $cost);
};

/********************************************/
/*         Refresh total on the page        */
/********************************************/
Sky_Shop.Product.ShowTotal = function()
{
    $cost = parseFloat(jQuery('#sku_cost').val());
    $qty = parseInt(jQuery('.productPurchase .quantityRequired').val());
    if (isNaN($qty)){
        $qty = 1;
    }
    $total = parseFloat($cost * $qty);
    if (jQuery('.productPurchase .productPrice .sale.price .value'))
    {
        jQuery('.productPurchase .productPrice .sale.price .value').html('£'+$total.toFixed(2));
    } else {
        jQuery('.productPurchase .productPrice .normal.price .value').html('£'+$total.toFixed(2));
    }
};


/**********************************************/
/* Add selected product and options to basket */
/**********************************************/
Sky_Shop.Product.AddToBasket = function(e)
{
    e.preventDefault();
    $btn = jQuery(this);
    
    if (!$btn.hasClass('clicked'))
    {    
        data_opts = {};
        $sku = jQuery('#sku').val();
        $qty = parseInt(jQuery('.productPurchase .quantityRequired').val());
        
        if (!($qty > 0))
        {
            alert("Please select a quantity required");
            return;
        }
        else
        {
            $sku_options = [];
            try
            {
                if ($btn.closest('.purchase').hasClass('customisable')){
                    /* get sku options */
                    jQuery('.productPurchase .customisable.options .optionSelect select').each(function(){
                        if (parseInt(jQuery(this).val()) > 0) {
                            $sku_options.push(jQuery(this).val());
                        } else {
                            throw jQuery(this).attr('title');
                        }
                    });
                    jQuery('.productPurchase .customisable.options .optionSelect input:checked').each(function(){ $sku_options.push(jQuery(this).val()); });
                }
            }
            catch (err){
                alert(err);
                return;
            }
            
            $btn.addClass('clicked');
        
            /* Add product to basket */
            Sky_Shop.RunAjax(null, {
                url: Sky_Shop.Root + "/basket/add_item",
                data: JSON.stringify({ 
                    SKU_Code: $sku,
                    Quantity: $qty, 
                    SKU_Options: $sku_options,
                    ExtraInfo: ''
                }),
                success: function(data, xhr){
                    $btn.removeClass('clicked');
                    $btn.after('<a href="/assets/visual/basket/addedtobasket.html?ajax=true&width=260&height=160" rel="prettyPhoto[ajax]" style="display: none;"></a>');
                    $btn.next().prettyPhoto({ 
                        overlay_gallery: false,
                        changepicturecallback: function(){ 
                            jQuery('.pp_content #product').html(jQuery('.productInfo h1.name').text());
                        }
                    }).trigger('click');
                    $btn.next().remove();
                },
                error: function(err, b, c){
                    $btn.removeClass('clicked');
                    jQuery.prettyLoader.hide();
                    alert(err.responseText);
                }
            });
        }
    }
};

/**********************************************/
/* Add multi products to basket */
/**********************************************/
Sky_Shop.Product.MultiAddToBasket = function(e)
{
    e.preventDefault();
    $btn = jQuery(this);
    
    if (!$btn.hasClass('clicked'))
    {    
        data_opts = {};

        $sku = [];
        $qty = [];

        $btn.siblings('.items').find('.product').each(function(el, i){
            $sku.push(parseInt(jQuery('.qty input[type=hidden]', this).val()))
            $qty.push(parseInt(jQuery('.qty input[type=text]', this).val()));
        });

        $btn.addClass('clicked');
        
        /* Add products to basket */
        Sky_Shop.RunAjax(null, {
            url: Sky_Shop.Root + "/basket/add_items",
            data: JSON.stringify({ 
                SKUs: $sku,
                Quantities: $qty
            }),
            success: function(data, xhr){
                $btn.removeClass('clicked');
                $btn.after('<a href="/assets/visual/basket/addedtobasket.html?ajax=true&width=260&height=160" rel="prettyPhoto[ajax]" style="display: none;"></a>');
                $btn.next().prettyPhoto({ 
                    overlay_gallery: false,
                    changepicturecallback: function(){ 
                        jQuery('.pp_content #product').html('Your selection');
                    }
                }).trigger('click');
                $btn.next().remove();

                /* remove items */
                $btn.siblings('.items').find('.product').fadeOut(250, function(){ jQuery(this).remove(); });
            },
            error: function(err, b, c){
                $btn.removeClass('clicked');
                jQuery.prettyLoader.hide();
                alert(err.responseText);
            }
        });
    }
};

/**********************************************/
/* Quick add product to basket */
/**********************************************/
Sky_Shop.Product.QuickAddToBasket = function(e)
{
    e.preventDefault();

    $el = jQuery(this);
    if ($el.val() == '') return;
    if (parseInt($el.val()) <= 0)
    {
        $el.val(1);
        return;
    }
    $sku = $el.closest('.qty').find('input[type=hidden]').val();
    $qty = $el.val();

    if ($el.hasClass('inBasket'))
    {
        /* Update product in basket */
        Sky_Shop.RunAjax(null, {
            url: Sky_Shop.Root + "/basket/update_stock_item",
            data: JSON.stringify({
                SKU: $sku,
                Quantity: $qty
            }),
            success: function(data, xhr)
            {
                $rnd = (Math.random()*9999).toString().replace(/[.]/gi, '');
                $el.closest('.qty').append('<span class="green addedToBasket" id="a'+$rnd+'">Quantity updated</span>');
                setTimeout('jQuery("#a'+$rnd+'").fadeOut(250, function(){ jQuery(this).remove(); });', 2500);

                Sky_Shop.Basket.RefreshQuickLook();
            },
            error: function(err, b, c){
                alert(err.responseText);
            }
        });
    }
    else
    {
        /* Add product to basket */
        Sky_Shop.RunAjax(null, {
            url: Sky_Shop.Root + "/basket/add_items",
            data: JSON.stringify({
                SKUs: [$sku],
                Quantities: [$qty]
            }),
            success: function(data, xhr)
            {
                $el.addClass('inBasket');
                $el.before('<span class="modify down" title="Remove one">-</span>').after('<span class="modify up" title="Add another">+</span>');
                $rnd = (Math.random()*9999).toString().replace(/[.]/gi, '');
                $el.closest('.qty').append('<span class="green addedToBasket" id="a'+$rnd+'">Added to basket</span>');
                setTimeout('jQuery("#a'+$rnd+'").fadeOut(250, function(){ jQuery(this).remove(); });', 2500);

                Sky_Shop.Basket.RefreshQuickLook();
            },
            error: function(err, b, c){
                alert(err.responseText);
            }
        });
    }
};

/* refrsh quick look basket */
Sky_Shop.Basket.RefreshQuickLook = function()
{
    Sky_Shop.RunAjax(null, {
        url: Sky_Shop.Root + "/basket/refresh",
        data: JSON.stringify({ ImageSize: "thumb" }),
        success: function(data, xhr)
        {
            jQuery('#top .quickBasket').html(data);
        },
        error: function(err, b, c){
            alert(err.responseText);
        }
    });
};

Sky_Shop.Basket.Delivery = {}
/*********************************************/
/*          Delivery Country Changed         */
/*********************************************/
Sky_Shop.Basket.Delivery.CountryChanged = function(e){
    e.preventDefault();
    var el = jQuery(this);
    var CountryCode = el.val();
    var CountryName = jQuery('option:selected', el).text();
    if (CountryCode != "")
    {
        /* Change basket delivery country */
        Sky_Shop.RunAjax(el.closest('.delivery'), {
            url: Sky_Shop.Root + "/basket/delivery_country_changed",
            data: JSON.stringify({ CountryCode: CountryCode, CountryName: CountryName, ResetCurrent: e.type == "AutoChange" ? false : true }),
            success: function(data, status, xhr){
                el.next('.availableTariffs').remove().end().after(data);
                if (e.type != "AutoChange" && el.next('.availableTariffs').find('.tariff').size() == 1)
                {
                    /* Update the totals */
                    Sky_Shop.Basket.UpdateTotals(true, false);
                }
                
                deliveryHeader = xhr.getResponseHeader('DeliveryError');
                if (deliveryHeader != null)
                {
                    deliveryHeader = deliveryHeader.replace(/&lt;/g, "<");
                    deliveryHeader = deliveryHeader.replace(/&gt;/g, ">");
                    jQuery('.basketContents .totals .delivery').hide();
                    jQuery('.basketContents .right .checkoutButton').css({ visibility: 'hidden' });
                }                 
            }
        });
    }
};
/*********************************************/
/*          Delivery Tariff Changed          */
/*********************************************/
Sky_Shop.Basket.Delivery.TariffChanged = function(e){
    //e.preventDefault();
    var el = jQuery(this);
    el.blur();
    var tariffID = parseInt(el.val());
    if (tariffID > 0)
    {
        /* Change basket delivery tariff */
        Sky_Shop.RunAjax(el.closest('.tariff'), {
            url: Sky_Shop.Root + "/basket/change_delivery_tariff",
            data: JSON.stringify({ DeliveryTariff: tariffID }),
            success: function(data, xhr){                
                /* Update totals */
                el.closest('.tariff').addClass('selected').siblings().removeClass('selected');
                Sky_Shop.Basket.UpdateTotals();
            },
            error: function(xhr, statusText){
                el.removeAttr('checked');
                alert(xhr.responseText);
            }
        });
    }
};

Sky_Shop.Basket.Init = function()
{
    /* Item qty change */
    jQuery('#main .basketContents .alterQuantity').click(Sky_Shop.Basket.Item.QuantityClick);
    jQuery('#main .basketContents .item .qty .input_Quantity').keyup(function(e){
        if (e.which >= 49 && e.which <= 57 || e.which == 96)
        {
            $el = jQuery(this);
            setTimeout(function(){
                Sky_Shop.Basket.Item.UpdateQuantity_Do($el);
            }, 500);
        }
    });
    jQuery('#main .basketContents .remove').click(Sky_Shop.Basket.Item.Remove);
            
    /* Promo code button clicked */
    jQuery('#applyPromoCode').click(Sky_Shop.Basket.PromoCode.Apply);
    
    /* Promo code input keyup */
    jQuery('#input_PromoCode').keyup(function(){
        if (jQuery(this).val().length > 0){
            jQuery(this).next().css('visibility','visible');
        } else {
            jQuery(this).next().css('visibility','hidden');
        }
    });
    
    /* Delivery tariff changed */
    jQuery('.availableTariffs .tariffSelector').live('change', Sky_Shop.Basket.Delivery.TariffChanged);
    
    /* Delivery country change */
    jQuery('#main .delivery select').change(Sky_Shop.Basket.Delivery.CountryChanged);
        
    /* Initialize prettyLoader */
    jQuery.prettyLoader({
		bind_to_ajax: true,
		loader: '/assets/visual/prettyLoader/ajax-loader.gif'
    });
};
Sky_Shop.Basket.Item = {};
Sky_Shop.Basket.Item.Timer = null;
Sky_Shop.Basket.Item.QtyEl = null;
/*********************************************/
/*        Basket Item Quantity Click         */
/*********************************************/
Sky_Shop.Basket.Item.QuantityClick = function(e)
{
    e.preventDefault();
    if (jQuery(this).hasClass('up'))
    {
        Sky_Shop.Basket.Item.UpdateQuantity(jQuery(this).prev('input.input_Quantity'), 1);
    }
    else if (jQuery(this).hasClass('down'))
    {
        Sky_Shop.Basket.Item.UpdateQuantity(jQuery(this).next('input.input_Quantity'), -1);
    }
};
/*********************************************/
/*        Change basket item quantity        */
/*********************************************/
Sky_Shop.Basket.Item.UpdateQuantity = function(input_el, direction, pass_through)
{
    /* Current qty */
    currQty = parseInt(input_el.val());    
    newQty = currQty;
    
    /* Check for any max quantities */
    maxQty = parseInt(input_el.siblings('input.max').val());
    
    /* If there is a max qty allowed and it's going to exceed it, return */
    if (direction > 0 && (!isNaN(maxQty) && (currQty == maxQty))) { return; }
    
    /* If valid change - set */
    if ( (currQty > 1 && direction < 0) || (currQty >= 1 && direction > 0) )
    {
        newQty = currQty + direction;
    }
    else { return; }
    
    /* set input qty */
    input_el.val(newQty);
    
    /* If we have have clicked on a qty-change a el already and it's not the one we are on */
    if (Sky_Shop.Basket.Item.QtyEl != null && (Sky_Shop.Basket.Item.QtyEl.attr("id") != input_el.attr("id")))
    {
        Sky_Shop.Basket.Item.UpdateQuantity_Do(Sky_Shop.Basket.Item.QtyEl);
    }
    /* Set "active" item */
    Sky_Shop.Basket.Item.QtyEl = input_el;
    
    /* Clear timeout - so it doesn't fire multiple times */
    clearTimeout(Sky_Shop.Basket.Item.Timer);
    
    /* Set timeout */
    Sky_Shop.Basket.Item.Timer = setTimeout(function(){
        /* Update basket item */
        Sky_Shop.Basket.Item.UpdateQuantity_Do(Sky_Shop.Basket.Item.QtyEl);
        clearTimeout(Sky_Shop.Basket.Item.Timer);
    },500);
};
/*********************************************/
/*        Update basket item quantity        */
/*********************************************/
Sky_Shop.Basket.Item.UpdateQuantity_Do = function(el){
    itemID = jQuery(el).siblings('input.itemid').val();
    qty = parseInt(jQuery(el).val());
    
    /* Update basket item */
    Sky_Shop.RunAjax(el, {
        url: Sky_Shop.Root + "/basket/update_item",
        data: JSON.stringify({ ItemID: itemID, Quantity: qty }),
        success: function(data, xhr){
            /* Update line total */
            price_el = jQuery(el).closest('.item').find('.price');
            var price = price_el.html().replace(',','');
            price = parseFloat(price.substring(1, price.length));
            var linetotal = (price * qty).toFixed(2);
            jQuery(el).closest('.item').find('.line-total').html(price_el.html().substring(0,1) + linetotal);
            
            /* Update totals */
            Sky_Shop.Basket.UpdateTotals();
        }
    });
};


/*********************************************/
/*            Remove basket item             */
/*********************************************/
Sky_Shop.Basket.Item.Remove = function(e)
{
    e.preventDefault();
    item_el = jQuery(this);
    
    /* Get item id */
    itemID = item_el.attr('rel');

    /* Remove basket item */
    Sky_Shop.RunAjax(item_el, {
        url: Sky_Shop.Root + "/basket/update_item",
        data: JSON.stringify({ ItemID: itemID, Quantity: 0 }),
        success: function(data, xhr){
            item_el.closest('.item').fadeOut(250, function(){ jQuery(this).remove(); });            
            /* Update totals */
            Sky_Shop.Basket.UpdateTotals();
        }
    });
};

/*********************************************/
/*            Update basket totals           */
/*********************************************/
Sky_Shop.Basket.UpdateTotals = function()
{
    /* Get basket totals */
    Sky_Shop.RunAjax(null, {
        url: Sky_Shop.Root + "/basket/get_totals",
        success: function(data, status, xhr)
        {                
            /* Update totals */
            jQuery('.basketContents .right .totals').replaceWith(data);            
            
            /* Check any promotional code response headers */
            promoHeader = xhr.getResponseHeader('PromoError');
            if (promoHeader != null && promoHeader != "")
            {
                promoHeader = promoHeader.replace(/&lt;/g, "<");
                promoHeader = promoHeader.replace(/&gt;/g, ">");
                jQuery('.basketContents .promocode').find('.action-message').remove().end().append('<div class="action-message error">'+promoHeader+'</div>');
            } 
            else 
            {
                jQuery('.basketContents .promocode div.action-message').remove();
            }
            
            continueHeader = xhr.getResponseHeader('AllowContinue');
            if (continueHeader != null && continueHeader == 'true')
            {
                jQuery('.basketContents .checkoutButton').css({ visibility: 'visible' })
            } else {
                jQuery('.basketContents .checkoutButton').css({ visibility: 'hidden' })
            }

            Sky_Shop.Basket.RefreshQuickLook();
        }
    });
};


Sky_Shop.Basket.PromoCode = {}
/*********************************************/
/*            Promo code entered             */
/*********************************************/
Sky_Shop.Basket.PromoCode.Apply = function(e){
    e.preventDefault();
    $btn = jQuery(this);
    $PromoCode = $btn.siblings('input#input_PromoCode').val();
    if ($PromoCode.length > 0)
    {
        /* Apply promo code */
        Sky_Shop.RunAjax($btn.closest('div.promocode'), {
            url: Sky_Shop.Root + "/basket/apply_promocode",
            data: JSON.stringify({ PromoCode: $PromoCode }),
            success: function(data, xhr)
            {
                /* Update totals */
                Sky_Shop.Basket.UpdateTotals();
            },
            error: function(xhr, status){
                $btn.closest('.promocode').find('.action-message').remove().end().append('<div class="action-message error">'+xhr.responseText+'</div>');
            }
        });
    }
};

var $timeout;
Sky_Shop.ProductPaging = {
    el: null,
    LimitPP: 12,
    SortMethod: 0
};
/***************************** Paging *****************************/
Sky_Shop.ProductPaging.Build = function(el, Count, LimitPP)
{
    /* look for a sorting dropdown on the page with the class 'sortProductsBy' */
    Sky_Shop.ProductPaging.SortMethod = jQuery('.sortProductsBy select option:selected').val();
    if (!isNaN(Sky_Shop.ProductPaging.SortMethod)){
        /* set sort event handler */
        jQuery('.sortProductsBy select').change(function(e){
            Sky_Shop.ProductPaging.SortMethod = parseInt(jQuery(this).val());
            Sky_Shop.Filtering.GotoPage(1);
        });
    } else {
        Sky_Shop.ProductPaging.SortMethod = 0;
    }
    
    $el = jQuery(el);
    html = '<div class="productPaging"> \
			    <span class="resultCount"></span> \
			    <span class="pages"></span> \
                <a href="#" rel="no-follow" class="viewAll">view all</a> \
		    </div>';

    /* add paging structure to el */
    $el.append(html);
    Sky_Shop.ProductPaging.el = $el.find('> .productPaging');
    Sky_Shop.ProductPaging.LimitPP = LimitPP;
    
    /* view all click */
    jQuery('.productPaging .viewAll').live('click', function(e)
    {
        e.preventDefault();
        Sky_Shop.Filtering.GotoPage(0);
    });
    
    Sky_Shop.ProductPaging.Draw(Count, LimitPP, 1);
};
Sky_Shop.ProductPaging.Draw = function(Count, LimitPP, CurrentPage)
{    
    Sky_Shop.ProductPaging.LimitPP = LimitPP;    
    Sky_Shop.ProductPaging.el.find('> .resultCount').html(Count + " item" + (Count>1 ? "s" : "") + " found");
    if (Count > 0){
        Sky_Shop.ProductPaging.el.find('.viewAll').hide();
    }

    if (Count <= LimitPP){
        Sky_Shop.ProductPaging.el.find('.pages, .prevNext_, .viewAll').hide();
        return;
    } else {
        Sky_Shop.ProductPaging.el.find('.pages, .prevNext_, .viewAll').show();
    }
    
    /* Create pagination element */
    Sky_Shop.ProductPaging.el.find('.pages').pagination(Count, {
        current_page: CurrentPage-1,
        num_edge_entries: 6,
        num_display_entries: 6,
        callback: function(indx, container){
            clearTimeout($timeout);
            $timeout = setTimeout(function()
            {
                clearTimeout($timeout);
            
                /* get products */
                Sky_Shop.Filtering.GotoPage(indx+1);
            
            }, 500);
        },
        items_per_page: LimitPP
    });
};
Sky_Shop.ProductPaging.HighlightPage = function(PageNum)
{
    Sky_Shop.ProductPaging.el.find('.pages').trigger('setPage', PageNum-1);
};

Sky_Shop.Filtering = {
    Timout: null,
    LastSelection: {
        GroupID: 0,
        FilterID : 0
    },
    ProductList: '.productsList',
    SearchTerms: ''
};
/***************************** Filtering *****************************/
Sky_Shop.Filtering.Init = function(SearchTerms)
{
    Sky_Shop.Filtering.SearchTerms = SearchTerms;
    jQuery('#filtering input[type=checkbox]').change(function(e)
    {
        if (jQuery(this).is(':checked')){
            jQuery(this).addClass('checked');
        } else {
            jQuery(this).removeClass('checked');
        }
        Sky_Shop.Filtering.LastSelection.GroupID = jQuery(this).closest('.filterSelect').find('> input[name=group_id]').val();
        Sky_Shop.Filtering.LastSelection.FilterID = jQuery(this).val();
        Sky_Shop.Filtering.Timout = setTimeout(function(){
            clearTimeout(Sky_Shop.Filtering.Timout);
            Sky_Shop.Filtering.GotoPage(1);
        }, 500);
    });
    
    jQuery('#filtering .clear').click(function(e){
        e.preventDefault();
        jQuery(this).addClass('hide').closest('.filterSelect').find('input[type=checkbox]').removeAttr('disabled').removeAttr('checked').removeClass('checked');
        Sky_Shop.Filtering.GotoPage(1);
    });

    jQuery('#productListBottom').live('inview', function(event, isInView, visiblePartX, visiblePartY){
        if (isInView){
            jQuery('.categoryMainPanel .productPaging.clone').remove();
            jQuery('.categoryMainPanel').append(jQuery('.productPaging').clone(true).addClass('clone'));            
        }
    });

    /* check to auto set filters */
    $categoryID = parseInt(jQuery('#filtering input[name=category_id]').val()) || 0;    
    if ($categoryID > 0)
    {
        Sky_Shop.RunAjax(null, {
            url: "/products/refresh_list",
            cache: false,
            data: JSON.stringify({ CategoryID: $categoryID }),
            dataType: 'json',
            beforeSend: function(){
                jQuery('.disableDuringAjax').addClass('running').append('<div class="ajaxDisable" />');
            },
            success: function(data, xhr)
            {
                jQuery('.disableDuringAjax').removeClass('running').find('> .ajaxDisable').fadeOut(450, function(){ jQuery(this).remove(); });
                if (data.d != "")
                {
                    $checkedFilters = "";
                    for($i = 0; $i < data.d.Filters.length; $i++)
                    {
                        for($x = 0; $x < data.d.Filters[$i].Selections.length; $x++)
                        {
                            $checkedFilters += "input#filter_g_" + data.d.Filters[$i].GroupID + "_f_" + data.d.Filters[$i].Selections[$x] + ",";
                        }
                    }
                    jQuery($checkedFilters, jQuery('#filtering')).attr('checked', 'checked').addClass('checked');
                    
                    /* Jump to last viewed page */
                    Sky_Shop.Filtering.GotoPage(data.d.PageState.GotoPage, true);
                }
                else
                {
                    if (jQuery(Sky_Shop.Filtering.ProductList).find('li').size() == 0)
                    {
                        Sky_Shop.Filtering.GotoPage(1);
                    }
                }
            },
            error: function(xhr, status){
                jQuery('.disableDuringAjax').removeClass('running').find('> .ajaxDisable').fadeOut(450, function(){ jQuery(this).remove(); });
            }
        });
    }
};
Sky_Shop.Filtering.GotoPage = function(PageNum, AutoRefresh)
{
    $categoryID = parseInt(jQuery('#filtering input[name=category_id]').val()) || 0;
    $selected_filters = [];
    $filter_count = 0;
    /* get selected filters and their groups */
    jQuery('#filtering .filterSelect').each(function(i, el){
        $filter = {
            GroupID: parseInt(jQuery('> input[name=group_id]',  el).val()),
            Selections: []
        };
        jQuery('input[type=checkbox]:checked',  el).each(function(){
            $filter_count++;
            $filter.Selections.push(parseInt(jQuery(this).val()));
        });
        if ($filter.Selections.length > 0){
            jQuery('> .clear', this).removeClass('hide');
        } else {
            jQuery('> .clear', this).addClass('hide');
        }
        $selected_filters.push($filter);
    });
    $page_state = {
        CurrentPage: PageNum,
        GotoPage: PageNum,
        PageSize: Sky_Shop.ProductPaging.LimitPP,
        SortMethod: Sky_Shop.ProductPaging.SortMethod
    };
    
    /* Refine results */
    Sky_Shop.RunAjax(null, {
        url: "/products/refine_list",
        data: JSON.stringify({ 
            Refine: { 
                CategoryID: $categoryID, 
                Filters: $selected_filters, 
                PageState : $page_state,
                Keywords: Sky_Shop.Filtering.SearchTerms,
                ImageSize: jQuery(Sky_Shop.Filtering.ProductList).hasClass('list') ? "list" : "thumb"
            } 
        }),
        dataType: 'json',
        beforeSend: function(){
            jQuery('.disableDuringAjax').addClass('running').append('<div class="ajaxDisable" />');
        },
        complete: function(){
            jQuery('.disableDuringAjax').removeClass('running').find('> .ajaxDisable').fadeOut(450, function(){ jQuery(this).remove(); });
        },
        success: function(data, xhr)
        {
            if (data.d != "")
            {
                /* draw paging */
                Sky_Shop.ProductPaging.Draw(data.d.PageState.TotalItems, data.d.PageState.PageSize, data.d.PageState.CurrentPage);

                /* enabled/disable filters (if page 1) */
                if (data.d.PageState.CurrentPage == 1 || !AutoRefresh)
                {
                    jQuery('#filtering input[type=checkbox]').attr('disabled','disabled');
                    if (!AutoRefresh)
                    {
                        jQuery('#filtering input[name=group_id][value='+Sky_Shop.Filtering.LastSelection.GroupID+']').parent('.filterSelect').find('input[type=checkbox]').removeAttr('disabled');
                    }
                    $enabledFilters = "";
                    $enabled_filter_count = 0
                    for($i = 0; $i < data.d.EnabledFilters.length; $i++)
                    {
                        $enabled_filter_count += data.d.EnabledFilters[$i].Filters.length;
                        for($x = 0; $x < data.d.EnabledFilters[$i].Filters.length; $x++)
                        {
                            $enabledFilters += "input#filter_g_" + data.d.EnabledFilters[$i].GroupID + "_f_" + data.d.EnabledFilters[$i].Filters[$x] + ",";
                        }
                    }
                    jQuery($enabledFilters, jQuery('#filtering')).removeAttr('disabled');//.removeClass('checked');
                    if ($enabled_filter_count == 0)
                    {
                        /* no filters selected, unlock all */
                        jQuery('#filtering input[type=checkbox]').removeAttr('disabled');
                    }
                }
            
                /* template products */
                jQuery.ajax({
                    type: 'GET',
                    url: '/assets/visual/product/product_list-tmpl.txt',
                    cache: true,
                    success: function(template){
                        $list = jQuery(Sky_Shop.Filtering.ProductList).empty();
                        jQuery.tmpl(template, data.d.Products).appendTo($list);
                    }
                });
            }
        },
        error: function(xhr, status){
            //alert(JSON.parse(xhr.responseText).Message);
            //console.log(xhr);
        }
    });
};

/*
 * jQuery Templates Plugin 1.0.0pre
 * http://github.com/jquery/jquery-tmpl
 * Requires jQuery 1.4.2
 *
 * Copyright Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */
(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);

/* in view - https://github.com/protonet/jquery.inview */
(function(c){function p(){var d,a={height:h.innerHeight,width:h.innerWidth};if(!a.height&&((d=i.compatMode)||!c.support.boxModel))d=d==="CSS1Compat"?k:i.body,a={height:d.clientHeight,width:d.clientWidth};return a}var m={},e,a,i=document,h=window,k=i.documentElement,j=c.expando;c.event.special.inview={add:function(a){m[a.guid+"-"+this[j]]={data:a,$element:c(this)}},remove:function(a){try{delete m[a.guid+"-"+this[j]]}catch(c){}}};c(h).bind("scroll resize",function(){e=a=null});setInterval(function(){var d=
c(),j,l=0;c.each(m,function(a,b){var c=b.data.selector,e=b.$element;d=d.add(c?e.find(c):e)});if(j=d.length){e=e||p();for(a=a||{top:h.pageYOffset||k.scrollTop||i.body.scrollTop,left:h.pageXOffset||k.scrollLeft||i.body.scrollLeft};l<j;l++)if(c.contains(k,d[l])){var g=c(d[l]),f={height:g.height(),width:g.width()},b=g.offset(),n=g.data("inview"),o;if(!a||!e)break;b.top+f.height>a.top&&b.top<a.top+e.height&&b.left+f.width>a.left&&b.left<a.left+e.width?(o=a.left>b.left?"right":a.left+e.width<b.left+f.width?
"left":"both",f=a.top>b.top?"bottom":a.top+e.height<b.top+f.height?"top":"both",b=o+"-"+f,(!n||n!==b)&&g.data("inview",b).trigger("inview",[!0,o,f])):n&&g.data("inview",!1).trigger("inview",[!1])}}},250)})(jQuery);

/**
 * This jQuery plugin displays pagination links inside the selected elements.
 */
(function($){
	$.PaginationCalculator = function(maxentries, opts) {
		this.maxentries = maxentries;
		this.opts = opts;
	}	
	$.extend($.PaginationCalculator.prototype, {
		numPages:function() {
			return Math.ceil(this.maxentries/this.opts.items_per_page);
		},
		getInterval:function(current_page)  {
			var ne_half = Math.ceil(this.opts.num_display_entries/2);
			var np = this.numPages();
			var upper_limit = np - this.opts.num_display_entries;
			var start = current_page > ne_half ? Math.max( Math.min(current_page - ne_half, upper_limit), 0 ) : 0;
			var end = current_page > ne_half?Math.min(current_page+ne_half, np):Math.min(this.opts.num_display_entries, np);
			return {start:start, end:end};
		}
	});
	
	$.PaginationRenderers = {}

	$.PaginationRenderers.defaultRenderer = function(maxentries, opts) {
		this.maxentries = maxentries;
		this.opts = opts;
		this.pc = new $.PaginationCalculator(maxentries, opts);
	}
	$.extend($.PaginationRenderers.defaultRenderer.prototype, {

		createLink:function(page_id, current_page, appendopts){
			var lnk, np = this.pc.numPages();
			page_id = page_id<0?0:(page_id<np?page_id:np-1); 
			appendopts = $.extend({text:page_id+1, classes:""}, appendopts||{});
			if(page_id == current_page){
				lnk = $("<span class='current'>" + appendopts.text + "</span>");
			}
			else
			{
				lnk = $("<a>" + appendopts.text + "</a>")
					.attr('href', this.opts.link_to.replace(/__id__/,page_id));
			}
			if(appendopts.classes){ lnk.addClass(appendopts.classes); }
			lnk.data('page_id', page_id);
			return lnk;
		},
		appendRange:function(container, current_page, start, end) {
			var i;
			for(i=start; i<end; i++) {
				this.createLink(i, current_page).appendTo(container);
			}
		},
		getLinks:function(current_page, eventHandler) {
			var begin, end,
				interval = this.pc.getInterval(current_page),
				np = this.pc.numPages(),
				fragment = $("<div class='pagination'></div>");
			
			if(this.opts.prev_text && (current_page > 0 || this.opts.prev_show_always)){
				fragment.append(this.createLink(current_page-1, current_page, {text:this.opts.prev_text, classes:"prev"}));
			}
			if (interval.start > 0 && this.opts.num_edge_entries > 0)
			{
				end = Math.min(this.opts.num_edge_entries, interval.start);
				this.appendRange(fragment, current_page, 0, end);
				if(this.opts.num_edge_entries < interval.start && this.opts.ellipse_text)
				{
					jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment);
				}
			}
			
			this.appendRange(fragment, current_page, interval.start, interval.end);			
			if (interval.end < np && this.opts.num_edge_entries > 0)
			{
				if(np-this.opts.num_edge_entries > interval.end && this.opts.ellipse_text)
				{
					jQuery("<span>"+this.opts.ellipse_text+"</span>").appendTo(fragment);
				}
				begin = Math.max(np-this.opts.num_edge_entries, interval.end);
				this.appendRange(fragment, current_page, begin, np);				
			}
			if(this.opts.next_text && (current_page < np-1 || this.opts.next_show_always)){
				fragment.append(this.createLink(current_page+1, current_page, {text:this.opts.next_text, classes:"next"}));
			}
			$('a', fragment).click(eventHandler);
			return fragment;
		}
	});
	
	$.fn.pagination = function(maxentries, opts){
		
	    opts = jQuery.extend({
		    items_per_page:10,
		    num_display_entries:10,
		    current_page:0,
		    num_edge_entries:0,
		    link_to:"#",
		    prev_text:"Prev",
		    next_text:"Next",
		    ellipse_text:"&hellip;",
		    prev_show_always:true,
		    next_show_always:true,
		    renderer:"defaultRenderer",
		    callback:function(){return false;}
	    },opts||{});
    	
	    if (maxentries < opts.items_per_page)
	        return;
    	
	    var containers = this, renderer, links, current_page;

		function pageSelected(evt){
			var links, current_page = $(evt.target).data('page_id');
			containers.data('current_page', current_page);
			links = renderer.getLinks(current_page, pageSelected);
			containers.empty();
			links.appendTo(containers);
			var continuePropagation = opts.callback(current_page, containers);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}
		
		current_page = opts.current_page;
		containers.data('current_page', current_page);
		
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
		
		if(!$.PaginationRenderers[opts.renderer])
		{
			throw new ReferenceError("Pagination renderer '" + opts.renderer + "' was not found in jQuery.PaginationRenderers object.");
		}
		renderer = new $.PaginationRenderers[opts.renderer](maxentries, opts);
		
		containers.each(function() {
		    this.selectPage = function(page_id){ pageSelected(page_id);}
		    this.prevPage = function(){
			    var current_page = containers.data('current_page');
			    if (current_page > 0) {
				    pageSelected(current_page - 1);
				    return true;
			    }
			    else {
				    return false;
			    }
		    }
		    this.nextPage = function(){
			    var current_page = containers.data('current_page');
			    if(current_page < numPages()-1) {
				    pageSelected(current_page+1);
				    return true;
			    }
			    else {
				    return false;
			    }
		    }
		});
		links = renderer.getLinks(current_page, pageSelected);
		containers.empty();
		links.appendTo(containers);
    }

})(jQuery);

/* Case insensitive jQuery :contains */
jQuery.expr[':'].iContains = function(a,i,m){
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
