/* Nectar Gift Chooser application
 * Minify before deployment and make sure that all references to //console.log are commented
 */
 
//globals
var categoryList = '';
var topcategoryList = '';
var personalityList = '';
var productList = '';
var numPages = 0;
var imgWidth = '100';
var imgHeight = '100';
var apiPath = '/dynamic/shoppingPopup/shopping/search'; //path to API
var resultHolder = $('#resultsPanelCtr02'); //holds formatted results
var userMap = [];
var maxPages = 10; //limit size of resultset here
var urlPrefix = '/price-checker-results.eshops'; //set as empty string to generate relative links
var productCache = {};
var userShortList;
var page = 0;

//kickoff application
//document.observe('dom:loaded', init);
//$(window).load(initApp);
//console.log('running');

userMap[0] = '0-5>>Adventure seeker|Cheeky little monkey|Fashionista|Globetrotter|Gorgeously groomed|Nature lover';
userMap[1] = '6-10>>Adventure seeker|Cheeky little monkey|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Nature lover|Person who has everything|Sports bod|Workaholic';
userMap[2] = '11-15>>Adventure seeker|Bookworm|Cheeky little monkey|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|Music lover|Nature lover|Person who has everything|Sports bod|Telly addict|Workaholic|';
userMap[3] = '16-18>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Music lover|Nature lover|Party animal|Person who has everything|Sports bod|Telly addict|Workaholic';
userMap[4] = '19-24>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Movie buff|Music lover|Nature lover|Party animal|Person who has everything|Sports bod|Telly addict|Workaholic';
userMap[5] = '25-34>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Movie buff|Music lover|Nature lover|Party animal|Person who has everything|Sports bod|Telly addict|Workaholic';
userMap[6] = '35-39>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Movie buff|Music lover|Nature lover|Party animal|Person who has everything|Sports bod|Telly addict|Workaholic';
userMap[7] = '40-45>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Movie buff|Music lover|Nature lover|Party animal|Person who has everything|Sports bod|Telly addict|Workaholic';
userMap[8] = '46-54>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Movie buff|Music lover|Nature lover|Party animal|Person who has everything|Sports bod|Telly addict|Workaholic';
userMap[9] = '55+>>Adventure seeker|Bookworm|Fashionista|Foodie|Gizmo geek|Globetrotter|Gorgeously groomed|Happy hippy|House addict|Loves luxury|Movie buff|Music lover|Nature lover|Person who has everything|Sports bod|Telly addict|Workaholic';

//console.log(userMap[6].split('>>')[0]);

$(document).ready(function() {
    initApp();
    userShortList = new shortList();
    
    /* 
    $('#resultsPanelCtr02').append('<div id="snow-globe"></div>');

    $('#snow-globe').flash({
        swf: '/contents/flash/gift-finder/snow-globe.swf',
        width: 320,
        height: 260,
        wmode: 'transparent'
    });
    */
    
});


//init function- fires first
function initApp(){

    $('#submitButton').css('cursor','pointer');
    $('#submitButton').click(handleSubmit);
    $('#gender').hide();
    $('#formRecipient').val('female');

    $('#formAge').change(function(){
        $('#formInterest').html('');
        var _persList = '';
        var _regexAge = new RegExp($('#formAge').attr('value'));
        var i;
        for(i=0; i<userMap.length;i++){
            if(_regexAge.test(userMap[i])){
                _persList = userMap[i].split('>>')[1].split('|');
            }
        }

        $('#formInterest').append('<option value="null">Please select</option>');
        for (i = 0; i < _persList.length; i++){
            $('#formInterest').append('<option value="'+_persList[i]+'">'+_persList[i]+'</option>');
        }
    });
    
    $('#formInterest').change(function(){
        if(this.value == 'Fashionista' || this.value == 'Gorgeously groomed') {
            $('#formRecipient').val('null');
            $('#gender').show();
        } else {
            // for categories that return both sexes, hide the option but set a default
            $('#gender').hide();  
            $('#formRecipient').val('female');
        }
    });
    
    
}



function handleSubmit(){

    // Form validation. Iterate over the form elements and if a value is "null" stop submission
    var _count = 0;
    var nullList = [];
    
    $('#resultsPanel').css('background', '#fff');

    jQuery.each($('#giftForm select'), function(){

        // alert("Parent: " + this.parent);

        if(this.value == 'null'){
            _count++;

            this.style.borderColor = 'red';
            this.style.borderWidth = '1px';
            this.style.borderStyle = 'solid';

            $('#'+ this.id + '_err').addClass('highlight');

        }
        else {
            this.style.borderColor = 'red';
            this.style.borderWidth = '0px';
            this.style.borderStyle = 'solid';

            $('#'+ this.id + '_err').removeClass('highlight');

        }

    });

    jQuery.each($('#giftForm input[type="text"]'), function(){
        
        if ($(this).attr('id') == 'priceFrom'){
            return true;        //skip priceFrom field
        }
        
        if(this.value.match(/[^0-9]/gi) || this.value == ''){
            _count++;
        
            this.style.borderColor = 'red';
            this.style.borderWidth = '1px';
            this.style.borderStyle = 'solid';
            
            $('#'+ this.id + '_err').addClass('highlight');
        }
        else {
            this.style.borderColor = 'red';
            this.style.borderWidth = '0px';
            this.style.borderStyle = 'solid';

            $('#'+ this.id + '_err').removeClass('highlight');
        }
    });

    if(_count < 1){
        checkMatrix();
    }
    else {
        //error message here?
    }
}


//scan through matrix and return matches
function checkMatrix(){

    //START process: show loading animation and change button

    $('#resultsPanel').fadeIn(300);

    var _width = $('#resultsPanelCtr02').width();
    var _pos = (_width/2)-159;

    resultHolder.html('<img src="/contents/images/content/eshops/redirecting-animation.gif" style="position: relative; left:'+_pos+'px; top:10px;" />');

    //$('#submitButton').removeClass();
    //$('#submitButton').addClass('waitButton');
    $('#submitButton').css('cursor','arrow');

    var _regexPers = new RegExp($('#formInterest').attr('value'));
    var _regexAge = new RegExp('age'+$('#formAge').attr('value'));
    var _regexRec = new RegExp('rec'+$('#formRecipient').attr('value'));
    var i;
    //console.log(_regexPers+'-'+_regexRec+'-'+_regexAge);

    categoryList = [];
    topcategoryList = [];

    for(i=0; i<matrix.length; i++){

            if(_regexPers.test(matrix[i].personalities) && _regexRec.test(matrix[i].recipient) && _regexAge.test(matrix[i].agerange)){

                categoryList.push(matrix[i].category);

                var topCategories = matrix[i].category.split("|")[0] + "|" + matrix[i].category.split("|")[1];
                
                //check if level 3 category exists
                if (matrix[i].category.split("|")[2] !== undefined){
                    topCategories += "|" + matrix[i].category.split("|")[2];
                }

                topcategoryList.push(topCategories);
                //console.log("Top Cat List: " + topcategoryList);
            }
            else{
                // console.log("No Match");
            }

    }

    //dedupe top level categories and then fire off query to API
    topcategoryList = topcategoryList.unique();
    topcategoryList = topcategoryList.shuffle();

    //belt and braces. Is there any chance we have 0 categories? This may fail at the server, so let''s capture it as an error instead.
    if(categoryList.length > 0){
        doQuery();
        $('.shortlist').show();
    }
    else{
        handleError('no_results');
    }

}


//last item list constructor
function LastItem(cat){
    this.category = cat;
}

//JSON request handler
function doQuery(){

    //var _qString = 'priceRange='+$('#formSpend').attr('value');
    //uncomment below to set upper and lower prices
    /*
    var _qString = 'partner_wl_path=/VENDA/nectar/cse/giftchooser/search&priceFrom='+$('#formSpend').attr('value').split('-')[0];
    _qString += '&priceTo='+$('#formSpend').attr('value').split('-')[1];
    _qString += '&priceRange='+$('#formSpend').attr('value');
    */
    
    
    var priceFrom = $('#priceFrom').val();
    
    if (priceFrom == '' || priceFrom.match(/[^0-9]/)){
        priceFrom = 0;
    }
    
    var _qString = 'partner_wl_path=/VENDA/nectar/cse/giftchooser/search&priceFrom='+priceFrom+'&priceTo='+$('#priceTo').val();
    _qString += '&priceRange='+priceFrom+'-'+$('#priceTo').val();

    //build parameters for query string
    for (var i = 0; i < categoryList.length; i++){
        _qString+='&category='+escape(categoryList[i]);
    }

    _qString += '&imgWidth='+imgWidth+'&imgHeight='+imgHeight;

    //this one is for testing only.
    _qString += '&result=1&live=1';
    //console.log(_qString);

    //and then send the request off to the API
     $.ajax({
        type: "POST",
        dataType:'json',
        timeout: 30000,
        url: apiPath,
        data: _qString,
        success: function(response){

            try {
                pageTracker._trackEvent('Collect Nectar', 'Gift Finder', 'M1 - Search results shown');
                ntptAddPair('GFAge', $('#formAge').val() );
                ntptAddPair('GFPersonality', $('#formInterest').val() );
                ntptAddPair('GFHimHer', $('#formRecipient').val() );
                ntptAddPair('GFBudget', priceFrom + '-' + $('#priceTo').val() );
                ntptEventTag('ev=GF&pv=0');
            } catch (e){
                        
            }

            
            //first - parse JSON to array - parsing is automatic with JSON type in jQuery
            productList = response;

            //let''s display the results
            if (productList.products.length > 0) {

                // console.log(productList.products.length)

                if (productList.products.length < 30 )    {

                    //add the last item (look elsewhere categories)
                    productList.products[productList.products.length] = new LastItem(topcategoryList.join('@@'));

                }
                else {

                    //add the last item (look elsewhere categories)
                    productList.products[productList.products.length-1] = new LastItem(topcategoryList.join('@@'));

                }

                //then get number of pages required for display
                numPages = (productList.products.length - productList.products.length%3)/3 + 1;

                //set a MAX number of pages (10)
                if(numPages > maxPages){
                    numPages = maxPages;
                }
                
                //FINISH - remove loading animation    and reset button
                resultHolder.html('<ul id="resultList"></ul>');
                //$('#submitButton').removeClass();
                //$('#submitButton').addClass('tryAgainButton');
                $('#submitButton').css('cursor','pointer');
            
                
                productCache = {};                      // Empty product cache
                page = 0;
                showPage(page);
                buildPagination();
                buildCategoryLinks();
            }
            else {
                //empty resultset
                productList.products[productList.products.length] = new LastItem(topcategoryList.join('@@'));
                handleError('no_results');
            }

        },
        error:function(response){
            //failed response - generic error:
            //console.log(response);
            handleError('app_down');
        }
    });


}

function handleError(errType){

    resultHolder.html('');
    //$('#submitButton').removeClass();
    //$('#submitButton').addClass('tryAgainButton');
    $('#submitButton').css('cursor','pointer');

    switch (errType) {
        case 'app_down': resultHolder.append("<h1>Sorry.  We seem to be having some technical difficulties, please try again later.</h1>"); break;
        case 'no_results': resultHolder.append("<h1>Sorry.  We couldn't find anything we thought you'd like. Please try another search.</h1>"); break;
    }

}

//builds and outputs html based on the current item number
function showPage(pageNum){
    
    var pageNum = pageNum || page;
    
    var _resultList = $('#resultList');
    //resultHolder.append(_resultList);

    //build resultset
    for (var i = pageNum; i < pageNum + 3; i++) {

        // Hide if no more products
        if (i == productList.products.length-1) {
            //this is the last item - categories are stored here not products
            $('#pagNext').hide();
            return false;
            break;
        }
       
        /////////////////////////
        // GENERATE PRODUCT HTML
        /////////////////////////
                
        //replace default image if necessary
        var _imgPath = '';

        if(productList.products[i].product.imageUrl == null){
            _imgPath = '/contents/images/landing-pages/gift-detective/no_image.jpg';
        }
        else {
            _imgPath = productList.products[i].product.imageUrl;
        }
        
        
        //save product incase user adds to shortlist
        var sku = productList.products[i].product.sku;
        var info = productList.products[i].product;
        productCache[sku] = info;
        
        
        //create a result element and build html content for it
        var _result = $('<li></li>');
        var _productHtml = '<img src="' + _imgPath + '" />';
        _productHtml += '<h4>' + productList.products[i].product.title + '</h4>';
        _productHtml += '<p class="price_and_points">FROM <span class="amount">&pound;' + productList.products[i].product.priceFrom + '</span> <span class="points">Collect up to ' + productList.products[i].product.pointsMax + ' points</span></p>';
        _productHtml += '<p class="description">' + productList.products[i].product.description.replace(/<[^>]+>/g, ' ') + '</p>';
        //__productHtml += '<div class="quicklinks"><a href="#" onclick="userShortList.addProduct(this, ' + productList.products[i].product.sku + '); return false; ">ADD TO SHORTLIST</a><a href="'+urlPrefix+productList.products[i].product.productURL + '?from=gc_quickview" onclick="getProductDetails(this, ' + productList.products[i].product.sku + '); return false;" target="_blank">QUICKVIEW</a></div>';
        _productHtml += '<div class="quick-links"></div>';
        //_productHtml += '<p class="full-info"><a href="' + urlPrefix+productList.products[i].product.productURL + '?from=gc" target="_blank" onclick="try{ntptEventTag(\"ev=GFFullDetails&pv=0&productid=' + sku +'\");}catch(e){}">Full details</a></p>';
		_productHtml += '<p class="full-info"><a href="' + urlPrefix + '#!&from=gc&product=' + productList.products[i].product.sku + '" target="_blank" onclick="try{ntptEventTag(&quot;ev=GFFullDetails&pv=0&productid=' + sku + '&quot;)}catch(e){}">Full details</a></p>';
        _productHtml += '<div class="clear"></div>';
        _result.html(_productHtml);
        
        //$(_resultList).append(_result);

        // Build 'add to shortlist' button - click handler always needs binding, even if product is already in shortlist (otherwise removing, then re-adding a product won't work)
        
        var _shortListToggle = $('<a class="short-list" href="#">ADD TO SHORTLIST</a>').click(
            function(sku){
                return function(){
                    // alert("adding: " + productSku);
                    userShortList.addProduct(sku);
                    userShortList.bindToggleElement(sku, _shortListToggle);
                    return false; // prevent default click action
                };
            }(sku)
        );
        
        
        productCache[sku].shortListToggle = _shortListToggle;
        
        if (userShortList.hasProduct(sku)){
           userShortList.bindToggleElement(sku, _shortListToggle);
        }
        
        
        // Build 'quickview' button
        var _quickViewLink = $('<a class="quick-view" href="' + urlPrefix + '#!&from=gc_quickview&product="' + productList.products[i].product.sku + '">QUICKVIEW</a>').click(
            function(productSku){
                return function(){
                    //alert(productSku);
                    var detailsTable = $(this).parent().parent().next('table.product_details');
                    
                    try {
                        ntptAddPair('productid', productSku);
                        ntptEventTag('ev=GFQuickView&pv=0');
                    } catch (e){
                        
                    }
                    
                    if (detailsTable.length == 0){
                        //call IS needed, as getProductsDetails is a function, so 'this' will get set to window
                        getProductDetails(productSku, this);
                        return false;
                    }
                        
                    if (detailsTable.css('display') == 'none'){
                        detailsTable.show();
                    }
                    else {
                        detailsTable.hide();
                    }
                    
                    return false; // prevent default click action
                };
            }(sku)
        );

        // Add 'quick view' and 'add to shortlist' buttons to result
        _result.find('.quick-links').eq(0).append(_quickViewLink);
        _result.find('.quick-links').eq(0).append(_shortListToggle);
        
        // Insert result into list
        _resultList.append(_result);
        
    }
    
    page += 3;
   
    NECTAR.trunc($('p.description'), 7);

    return false;

}

function buildCategoryLinks(){
    // Category links
    resultHolder.append('<div class="more_categories"><p>Looking for more gift ideas? Try these:</p><ul id="category_listing"></ul></div>');
    var _categoryList = $('#category_listing');
    //_categoryList.html('');

    // categories are held in the last element
    //_cats = productList.products[i].category.split('@@', 3);
    _cats = productList.products[productList.products.length-1].category.split('@@', 3);

    for (var e = 0; e < _cats.length; e++){

        var _link = "";
        var _title = "";

        //_subCats = _cats[e].toLowerCase().split("|");
        _subCats = _cats[e].split("|");                        //lowercasing is stopping the links working now


        /////////////////////////////////////////////////////////////////
        //
        // GENERATE SINGLE LEVEL CATEGORY LINKS
        //
        // _link = _cats[e].toLowerCase().replace(/[.,?!,]/g, " ");

        //////////////////////////////////////////////////////////////////////////
        // some cat pages are not equvilant to their full title, i.e. Health and Beauty = heatlh.points
        // so use only the first word, which maintains consitancy...... Thanks Lorraine .. Whoop!!
        // _link = _link.split(" ")[0];

        // _link = _link.replace(/\s/g, '-');
        // _link = _link.replace(/--/g, '-');
        // _categoryList.innerHTML += '<a href="http://www.nectar.com/collect-online/categories/'+_link+'.points" target="_blank">Try '+_cats[e].toLowerCase()+'</a><br />';
        ///////////////////////////////////////////////////////////////////////////////

        if (_subCats[0] == "fashion accessories and luggage")    {
            _subCats[0] = "fashion and accessories and luggage";
        }
        else if (_subCats[0] == "computing")    {
            _subCats[0] = "computing and electronics";
        }
        else if (_subCats[1] == "womens fragrances")    {
            _subCats[1] = "women's fragrances";
        }
        else if (_subCats[1] == "mobile phones pay as you go")    {
            _subCats[1] = "Mobile Phones Pay-as-you-go";
        }
        else if (_subCats[1] == "gps")    {
            _subCats[0] = "computing and electronics";
            _subCats[1] = "gps";
        }

        //just the first category
        if (_subCats[0] == "DVDs" || _subCats[0] == "CDs" || _subCats[0] == "Music" || _subCats[0] == "Books and Magazines") {
               // _link = _subCats[0].replace(/\s/g, '%252520');
                _link = _subCats[0];
                _subCats[1] = "";
                _title = _subCats[0];
        }
        else {
            // replace the space with the following escape sequence - %252520
            _link = _subCats[0] + "|" + _subCats[1];
            _title = _subCats[0] + " > " + _subCats[1];
        }

        if (_subCats[2] !== undefined){
            _link += "|" + _subCats[2];
            _title += " > " + _subCats[2];
        }

        //_categoryList.innerHTML += '<a href="http://www.nectar.com/collect-online/compare-prices-results.points?partner_wl_path=/VENDA/nectar/cse/categories/' + _link + '" target="_blank">Try ' + _subCats[0] + " > " + _subCats[1] + '</a><br />'
        _categoryList.append('<li><a href="price-checker-results.eshops#!&category=' + _link + '&from=gc" target="_blank">' + _title + '</a></li>');

    }
}


function buildPagination(){
    
    resultHolder.append('<div id="resultsPanelPag" style="text-align: center"></div>');
    var _pagination = document.getElementById('resultsPanelPag');
    
    /*
    if(pageNum > 0){
        _pagination.innerHTML += '<a href="#" onclick="showPage('+(pageNum-3)+');return false;" id="pagPrev">Prev</a> ';
    }
    */

    var count = 0;

    /* 
    for (i = 0; i < numPages; i++){

        if (((pageNum/3)+1) == i+1)    {
            // we are displaying the current page
            _pagination.innerHTML += '<span id="pageSelected">'+(i+1)+'</span> ';
        }
        else if (count < productList.products.length)    {
            _pagination.innerHTML += '<a href="#" onclick="showPage('+count+');return false;">'+(i+1)+'</a> ';
        }

        count = count+3;
    }
    */

    // if(pageNum < productList.products.length-(productList.products.length%3)-3 || (pageNum == 0 && numPages > 1)){
        _pagination.innerHTML += '<a href="#" onclick="showPage();return false;" id="pagNext">More &hellip;</a> ';
    // }
    
}



function getProductDetails(product, clickedElement){
    
    var _queryData = {
        partner_wl_path : "/VENDA/nectar/cse/giftchooser/view/" + product + "/retailers?from=gc_quickview",
        from : "gc_quickview"
    };
    
    $(clickedElement).parent().parent().append('<p class="loading">Loading...</p>');
    
    $.ajax({
        type: "POST",
        dataType:'json',
        timeout: 30000,
        url: apiPath,
        data: _queryData,
        success: function(response){
            var retailers   = response.retailers,
                len         = retailers.length,
                detailsHtml = '<table class="product_details" cellpadding="0" cellspacing="0"><tr><th>Retailer</th><th>Price</th><th>Points collected</th><th></th></tr>';
            
            for (i = 0; i < len; i++){
                detailsHtml += '<tr><td><img src="' + retailers[i].imageUrl + '" alt="' + retailers[i].image + '"></td>';
                detailsHtml += '<td class="price">&pound;' + retailers[i].price + '</td>';
                detailsHtml += '<td class="price">' + retailers[i].points + '</td>';
                detailsHtml += '<td class="shop-now"><a href="' + retailers[i].buyURL.replace(/\s|'/g, '') + '" class="btn-shop-now shopnow">Buy now</a></td></tr>';
            }
            
            detailsHtml += '</table>';
            
            $('p.loading').remove();
            $(clickedElement).parent().parent().after(detailsHtml);
                
        },
        error: function(response){
            //failed response - generic error:
            //console.log(response);
            handleError('app_down');
        }
    });
    
}


/********************/
/*     Shortlist    */
/********************/
var shortList = function(){
    
    var pub = {},
        _items = {};
    
    
    function save(){
        var str = '';
        for (key in _items){
            if (_items.hasOwnProperty(key)){
                str += key + '|';
            }
        }
        document.cookie = 'shortlist=' + str;
    }
    
    pub.addProduct = function(itemSku){
        
        // Do nothing if this product is already on the shortlist
        if (typeof _items[itemSku] != 'undefined'){
            return false;
        }
        
        // Check if we've cached this product info already. If not, go and get it.
        if (typeof productCache[itemSku] === 'undefined'){
            var _query = 'partner_wl_path=/VENDA/nectar/cse/giftchooser/view/' + itemSku;
            $.ajax({
                type: 'POST',
                dataType:'json',
                timeout: 30000,
                url: apiPath,
                data: _query,
                success: function(response){
                    productCache[itemSku] = response;
                    pub.addProduct(itemSku);
                }
            });
            
            return false;
        }
        
        // Add product to shortlist from cache
        var chosenProduct = productCache[itemSku]; 
        _items[itemSku] = chosenProduct;

        var _listItem = $('<li><a href="' + urlPrefix + '#!&from=gc_shortlist&product=' + itemSku + '" target="_blank">' + chosenProduct.title + '</a> </li>');
        var removeLink = $('<a href="#" class="remove">(X)</a>').click(
            function(){
                return function(s){
                    userShortList.removeProduct(s);
                    try {
                        ntptAddPair('productid', s );
                        ntptEventTag('ev=GFRemove&pv=0');
                    } catch (e){
                        
                    }
                    return false;
                }(itemSku);
            }
        );
        
        _listItem.append(removeLink);
            
        _items[itemSku].listItem = _listItem;
        
        // if (toggleElement !== undefined){
        //    _items[itemSku].shortListToggle = $(toggleElement).text('(IN SHORTLIST)').addClass('in_shortlist');
        //}
        
        $('.shortlist ul').append(_listItem.hide().fadeIn());
        
        try {
            ntptAddPair('productid', itemSku );
            ntptEventTag('ev=GFShortList&pv=0');
        } catch (e){
            
        }

        save();
        
    };
    
    pub.bindToggleElement = function(itemSku, domElement){
        if (_items[itemSku].shortListToggle === undefined){
            _items[itemSku].shortListToggle = $(domElement);
        }
        _items[itemSku].shortListToggle.text('(IN SHORTLIST)').addClass('in_shortlist').removeClass('short-list');
       
    };
    
    pub.removeProduct = function(itemSku){
        if (_items[itemSku].shortListToggle !== undefined){
            _items[itemSku].shortListToggle.text('ADD TO SHORTLIST').addClass('short-list').removeClass('in_shortlist');
        }
        
        _items[itemSku].listItem.fadeOut('400', function(){
            $(this).remove();
        });
        
        delete _items[itemSku];
        save();
    };
    
    pub.hasProduct = function(itemSku){
        if (typeof _items[itemSku] != 'undefined'){
            return true;
        } else {
            return false;
        }
    };
    
    pub.listProducts = function(){
        return _items;
    };
    
    pub.countProducts = function() {
        var _size = 0, key;
        for (key in _items) {
            if (_items.hasOwnProperty(key)) {
                _size++;
            }
        }
        return _size;
    };
    
    // Load in any saved items  
    var match = document.cookie.match(/shortlist=([^;]+)/);
    if (match){
        var savedItems = match[1].split("|");
    
        for (var i = 0; i < savedItems.length; i++) {
            pub.addProduct(savedItems[i]);
        }
        
    }
    
    return pub;
    
};



