Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

var livePriceCalls = [];
var outOfStockCount = 0;
function getcashbackstring(type,value) {
        // console.log(type+' '+value);
        if(value==0){
                return '';
        }
        if(type==2){
                return ' +'+value+' Cashback';
        }else if(type==1){
                return ' +'+value+'% Cashback';
        }else{
                return '';
        }
}

$(function(){   
        if($('.scroll > .card').length>0) {
                setTimeout(function(){ document.location.reload(); }, 1000*15*60);
                $('.scroll').jscroll({
                        loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
                    autoTriggerUntil: 3,
                    padding: 20,
                });
        }
        /*
        if($('.storeminprice').length>0) {
                var globalminprice = 9999999;
                var globalminsku;
                var globalmincashback = '';             
                var calls = [];
                $('.storeminprice').each(function(){
                        var temp = {'sort':$(this).data('searchorder'),'val':$(this)};
                        calls.push(temp);
                });
                calls = sortByKey(calls,'sort');                
                for(var i in calls){
                        fetchLivePrice(calls[i]['val'])
                }                               
        };*/
        function sortByKey(array, key) {
            return array.sort(function(a, b) {
                var x = a[key]; var y = b[key];
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            });
        };
        function fetchLivePrice(obj){           
                ga('send', 'event', 'liveprice', 'fetch', $(obj).data('bundle_id'));
                var that = obj; 
                var inStock = false;            
                var req = $.ajax({
                        url: '/store_products/getliveprice/'+$(that).data('bundle_id')+'/'+$(that).data('id'),
                        // Tell jQuery we're expecting JSONP
                        dataType: "json",
                        // Tell YQL what we want and that we want JSON                  
                        method: 'get',
                        // timeout: 30000,
                        // Work with the response
                        success: function( response ) {
                                // console.log(response);
                                if(response.success){
                                        var i = 0;      
                                        var minpriceindex = 0;                          
                                        if(response.products[i].in_stock == 1) {inStock = true;}
                                        if(response.products[i].in_stock == 1) {
                                                var minprice = Math.round(response.products[i]['available_price']);
                                                var minpriceurl = response.products[i]['marketPlaceUrl'];
                                                console.log(minprice);
                                        }
                                        if(response.products.length>0){
                                                //More than one products in store
                                                var variants = [];
                                                // var i = 0;
                                                for(var i in response.products){        
                                                        if(response.products[i].in_stock == 1){
                                                                inStock = true;
                                                                // console.log(response.products[i]);
                                                                if(response.products[i].available_price && response.products[i].available_price < globalminprice) {
                                                                        globalminprice = Math.round(response.products[i].available_price);
                                                                        globalminsku = response.products[i]._id;
                                                                        var globalminsource = response.products[i].source_id;
                                                                        var globalminurl = response.products[i].marketPlaceUrl;
                                                                        var globalmincashback = getcashbackstring(response.products[i].cash_back_type,response.products[i].cash_back);
                                                                }
                                                                if(typeof minprice == 'undefined' || response.products[i].available_price <= minprice) {
                                                                        minprice = Math.round(response.products[i].available_price);
                                                                        minpriceindex = i;
                                                                }
                                                                variants.push({'name' : response.products[i].source_product_name, 'source_id' : response.products[i].source_id, 'available_price' : Math.round(response.products[i].available_price), 'url' : response.products[i].marketPlaceUrl,'source_product_name' : response.products[i].source_product_name,'id' : response.products[i]._id,'cash_back_type' : response.products[i].cash_back_type,'cash_back' : response.products[i].cash_back});
                                                        }                                               
                                                }
                                                if(variants.length>1){
                                                        variants.splice(minpriceindex,1);
                                                        var variantslink = $('<span class="variants"> '+(variants.length+1)+' Options</span>');
                                                        $(that).parent().parent().find('.pull-left',0).append(variantslink);                                                    
                                                        $(variantslink).data('variants',variants).data('minprice',minprice);
                                                }
                                        }
                                        if(inStock){
                                                $(that).html(minprice).siblings('.cashbackamount').html(getcashbackstring(response.products[minpriceindex].cash_back_type,response.products[minpriceindex].cash_back)).parent().addClass('viewproduct');
                                                $('#name-'+$(that).data('id')).html(response.products[minpriceindex]['source_product_name']);
                                                // console.log(response.products[minpriceindex]);
                                                $('#sku-'+$(that).data('id')).data('id',response.products[minpriceindex]['_id']).data('source',response.products[minpriceindex]['source_id']).data('price',response.products[minpriceindex]['available_price']).data('url',response.products[minpriceindex]['marketPlaceUrl']).removeClass('hidden');
                                                // console.log(globalminprice+' '+globalminsku);
                                                if(globalminprice != 9999999) {
                                                        $('#bestprice').html(globalminprice).siblings('.cashbackamount').html(globalmincashback);
                                                        $('#beststorelink').data('id',globalminsku).data('source',globalminsource).data('price',globalminprice).data('url',globalminurl).removeClass('hidden');
                                                        $('#bestpricecontainer').removeClass('hidden');
                                                } 
                                        } else{
                                                ga('send', 'event', 'liveprice', 'outofstock', response.products[0]._id);
                                                outOfStockCount++;
                                                $(that).parent().parent().remove();     
                                        }
                                        if(!response.products[0].available_price){
                                                // outOfStockCount++;
                                                // $(that).parent().parent().remove();  
                                                var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                                $(that).html(btn);
                                                ga('send', 'event', 'liveprice', 'failed', response.products[0]._id);
                                        }                                       
                                } else{
                                        // outOfStockCount++;
                                        // $(that).parent().parent().remove();
                                        var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                        $(that).html(btn);
                                        ga('send', 'event', 'liveprice', 'failure', response.products[0]._id);
                                }
                                checkForOutStocks(outOfStockCount);
                        },
                        error: function(request, status, err) {
                                //console.log(status+' '+err+' '+request);
                // if (status == "timeout") {
                        var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                        $(that).html(btn);
                                        ga('send', 'event', 'liveprice', 'error', response.products[0]._id);
                                // } else {
                                        // $(that).parent().parent().remove();
                                // }
                        }
                });
                livePriceCalls.push(req);
        };
        function checkForOutStocks(count){
                if(count>=livePriceCalls.length){
                        $('#bestpricecontainer').html('<h4>Out of stock</h4>').removeClass('hidden');   
                }               
        };
        $(document).on('click','.showless',function(){
                $(this).addClass('hidden').siblings('.varnts').hide();
                $(this).parent().find('.variants',0).removeClass('hidden').addClass('justshow');
        });
        $(document).on('click','.variants',function(){
                $('.storeproductinfo').empty();
                var variants = $(this).data('variants');
                var minprice = $(this).data('minprice');
                // console.log(variants);
                $('#variantscount').html(variants.length);
                for(var i in variants){
                        // console.log(variants[i]);
                        // var row = $('<div class="row storeproductinfo"><div class="col-xs-7">'+variants[i].source_product_name+'</div><div class="col-xs-3">'+variants[i].available_price+'</div><div class="col-xs-2"><button class="btn btn-primary btn-xs viewproduct" type="button" data-id="'+variants[i].id+'">Buy</button></div></div>');
                        // $('#storeproducts').parent().append(row);
                        // var row = $('<div class="clearfix varnts"></div><div class="col-xs-6 varnts text-small">'+variants[i].name+'</div><div class="col-xs-4 varnts"><span class="cashbackrupee"></span> <span>'+variants[i].available_price+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span></div><div class="col-xs-2 viewproduct varnts text-right" data-source="'+variants[i].source_id+'" data-price="'+variants[i].available_price+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><button type="button" class="btn-xs btn btn-success">BUY</button></div>');
                        if(minprice == variants[i].available_price) {
                                var row = $('<div class="clearfix varnts"></div><div class="col-xs-6 varnts text-small">'+variants[i].name+'</div><div class="col-xs-6 varnts viewproduct" data-source="'+variants[i].source_id+'" data-price="'+variants[i].available_price+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span class="storeminprice">'+variants[i].available_price+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span></div></div>');
                        } else {
                                var row = $('<div class="clearfix varnts"></div><div class="col-xs-6 varnts text-small">'+variants[i].name+'</div><div class="col-xs-6 varnts viewproduct" data-source="'+variants[i].source_id+'" data-price="'+variants[i].available_price+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span>'+variants[i].available_price+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span></div></div>');
                        }                       
                        $(this).parent().parent().append(row);                  
                }
                var showless = $('<div class="showless col-xs-9 text-right">Less <i class="glyphicon glyphicon-chevron-up"></i></span>');
                $(this).parent().parent().append(showless);
                $(this).addClass('hidden');
        });
        $('.categorytab').on('click','.categorytabcontrol.active',function(){
                $(this).toggleClass('active');
                $('#preferences-'+$(this).data('id')).addClass('hidden');
                $(this).parent().parent().children().find('.savecategorypreferences',0).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
        });
        $('.categorytab').on('click','.categorytabcontrol:not(.active)',function(){
                $(this).parent().parent().find('.btn',0).click();
        });
        $('.categorytab').on('click','.editcategorypreferences',function(e){
                var that = $(this);
                $(that).removeClass('editcategorypreferences').addClass('savecategorypreferences').html('Done').addClass('btn-success');
                $('#togglepreferences-'+$(that).data('id')).toggleClass('active');
                $('#preferences-'+$(that).data('id')).removeClass('hidden');
                $('.brandselector').each(function(){
                        if($(this).data('catid')==$(that).data('id')){
                                $(this).addClass('active');
                        }
                });
        });
        $('.categorytab').on('click','.savecategorypreferences',function(e){
                var that = $(this);
                $(that).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
                $('#togglepreferences-'+$(that).data('id')).toggleClass('active');
                $.ajax({
                        url: $('#categorypreference-'+$(that).data('id')).attr('action'),
                        data: $('#categorypreference-'+$(that).data('id')).serialize(),
                        // Tell jQuery we're expecting JSONP
                        dataType: "json",
                        // Tell YQL what we want and that we want JSON                  
                        method: 'post',
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        $('#preferences-'+$(that).data('id')).addClass('hidden');
                                }
                        }
                });
                ga('send', 'event', 'preferences', 'update', me);
        });
        // $('.row').on('click','.viewproduct',function(e){
        $(document).on('click','.viewproduct',function(e){
                if(typeof livePriceCalls != undefined) {
                for(var i in livePriceCalls){
                        // console.log('killing ajax call '+i);
                        livePriceCalls[i].abort();
                }
            }
                $('#loadingModal').modal();
                /*
                if($(this).data('source')==2){
                        //in case of flipkart, close popup after 5 seconds
                        setTimeout(function(){ $('#loadingModal').modal('hide'); }, 1000*5);                    
                }*/
                // console.log($(this).data('id'));
                var url = apihost+"clicks/add/0/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                if(response.success && response.type=='redirect'){
                                        document.location = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);

                                }
                        }
                });
                ga('send', 'event', 'product', 'click', $(this).data('url'));
        });
        $('.jscroll-inner').on('click','.likedeal',function(e){ 
                var that = $(this);
                if($(that).hasClass('active')){
                        //User has already liked it,so remove like
                        var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";       
                }else{
                        var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
                }
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        $(that).toggleClass('active');
                                        $(that).parent().find('li.dislikedeal',0).removeClass('active');
                                }
                        }
                });
                ga('send', 'event', 'product', 'like', $(this).data('id'));
        });
        $('#myModal').on('click','#unlikebtn',function(e){
                e.preventDefault();
                var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
                // console.log(url);
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                // console.log(response);                                               
                        }
                });
                $('#myModal').modal('hide');
                ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
        })
        $('.jscroll-inner').on('click','.dislikedeal',function(e){                      
                var that = $(this);
                if($(that).hasClass('active')){
                        //User has already liked it,so remove like
                        var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";    
                }else{
                        // console.log('show modal');
                        $('#myModal').find('#productToHide',0).val($(this).data('id'));
                        //$('#myModal').modal();
                        var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
                }
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        $(that).toggleClass('active');
                                        $(that).parent().find('li.likedeal',0).removeClass('active');
                                }
                        }
                });
                ga('send', 'event', 'product', 'dislike', $(this).data('id'));
        });
        $('.deletefav').on('click',function(){
                var that = $(this);
                $('#loadingModal').modal();
                var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');                 
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                $('#loadingModal').modal('hide');
                                if(response.success){                   
                                        $('#fav-'+$(that).data('id')).hide('slow');
                                }
                        }
                });
                ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
        });
        $('.clearfavs').on('click',function(){
                var that = $(this);
                $('#loadingModal').modal();
                var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');                   
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                $('#loadingModal').modal('hide');
                                if(response.success){                   
                                        $('.deletefav').each(function(){
                                                $('#fav-'+$(this).data('id')).hide('slow');
                                        })                                      
                                }
                                $(that).hide();
                        }
                });
                ga('send', 'event', 'favourites', 'removeall', me);
        });
        $('.revealbrands').on('click',function(){
                $(this).parent().find('.notfeatured').toggleClass('hidden');
                if($(this).html()=='Others'){
                        $(this).html('Hide');
                }else{
                        $(this).html('Others');
                }
        });
        $(document).on('click','.creditedcashbacks',function(){
                if($(this).find('.glyphicon-plus',0).length>0){
                        $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
                }else{
                        $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
                }
                $(this).next().toggleClass('hidden');
        });
        $(document).on('click','.panel-heading',function(){
                if($(this).find('.glyphicon-plus',0).length>0){
                        $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
                }else{
                        $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
                }
        });
        $(document).on('click','.prefcatselect',function(){
                $('.prefcatselect').removeClass('active')
                $(this).addClass('active');
                $('.categorypreferences').addClass('hidden');
                $('#cat-'+$(this).data('id')).toggleClass('hidden');
        });
        $(document).on('click','.refresh',function(){
                document.location.reload();
        });
        $(document).on('click','.hasmoretext',function(){
                $('#fulltext').html($(this).data('fulltext'));
                $('#fullTextModal').modal();
        });
        $(document).on('click','.favswitch',function(){
                $('.favswitch').removeClass('active')
                $(this).addClass('active');
                $('.clearfavs').addClass('hidden');
                $('.card').addClass('hidden');
                $('.'+$(this).data('type')).removeClass('hidden');
        });
        $(document).on('click','.brandpreferences .brands',function(){
                $(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
        });
        
        $(document).on('click','.tryagainforliveprice',function(){              
                fetchLivePrice($(this).parent());
                $(this).parent().html('Getting Live Prices');
        });
        $(document).on('click','.alert > a',function(){         
                ga('send', 'event', 'notifications', 'click', $(this).html());
        });
        $(document).on('click','.banner',function(){            
                ga('send', 'event', 'banners', 'click', $(this).data('name'));
        });
});
function setCookie(cname, cvalue, days) {
    var d = new Date();
    d.setTime(d.getTime() + (days*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}
function showpopup(id,count,interval){
        var cname = 'notif-count-'+me+'-'+id;
        var cookieval = getCookie(cname);
        var cname = 'notif-lastshown-'+me+'-'+id;
        var lastshown = getCookie(cname);
        if(cookieval==''){              
                incrementPopupCount(id,0,'notif-count-');
                setLastShown(id,'notif-lastshown-');
                return true;
        } else{
                var d = new Date();
                var t = d.getTime();
                console.log(t-lastshown);
                console.log(interval*60*1000);
                if(t-lastshown>interval*60*1000){
                        if(cookieval>=count){
                                return false;
                        }else{
                                setLastShown(id,'notif-lastshown-');
                                incrementPopupCount(id,cookieval,'notif-count-');
                                return true;    
                        }
                }
        }
}
function setLastShown(id,cookiename){
        var cname = cookiename+me+'-'+id;
        var d = new Date();
        setCookie(cname, d.getTime(), 365);
}
function incrementPopupCount(id,currentCount,cookiename) {
        var cname = cookiename+me+'-'+id;
        setCookie(cname, parseInt(currentCount)+1, 365);
}
var hidden, visibilityChange; 
function handleVisibilityChange() {
  if (document[hidden]) {
        // pagetitle = document.title;
  } else {
        // document.title = pagetitle;
  }
}
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
  hidden = "hidden";
  visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
  hidden = "mozHidden";
  visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
}
if (typeof document.addEventListener === "undefined" || 
  typeof document[hidden] === "undefined") {
  console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
  // Handle page visibility change   
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
}    
$('.notificationok').on('click',function(e){
        e.preventDefault();
        $('.notificationmodal').modal('hide');
        setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
        ga('send', 'event', 'popupnotification', 'ok', me);
        document.location = $(this).parent().prop('href');
});
$(document).on('click','.clearfilter',function(){       
        $('.filterbrand').each(function(){
                $(this).prop('checked',false);
        });     
        ga('send', 'event', 'filter', 'brand', 'clearfilter');
});
$(document).on('click','.applyfilter',function(){       
        var brands = [];
        var brandnames = [];
        $('.filterbrand').each(function(){
                if($(this).prop('checked')){
                        // console.log($(this).parent().siblings('.brandname').html());
                        brands.push($(this).val());
                        brandnames.push($(this).parent().siblings('.brandname').html());
                }               
        });
        if(brands.length==0){
                $('#message').html('Please choose a few brands first').removeClass('hidden');
                setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
                return false;
        }else{
                setCookie('brandschosen', brands, 1);
                var url = $('#brandselecter').prop('action');
                ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
                var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
                $.post( "/user_filters/add", postdata, function( data ) {
                  document.location = url+'&brands='+brands.join('^');
                });             
        }       
});
$(document).on('click','#showallbrands',function(){     
        $('.hidden').removeClass('hidden');
        $(this).hide();
});
$(document).on('input','#brandfilter',function(){       
        $('.brand').addClass('hidden');
        $('#showallbrands').hide();
        var that = $(this);
        $('li.brand').filter(function() { 
          return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
        }).removeClass('hidden','slow');
});
$(document).on('click','.filterbrand',function(){
        var clicked = $(this).parent().parent();
        console.log(clicked.prop('class'));
        // clicked.find('.filterbrand',0).prop('checked',true);
        // all the LIs above the clicked one
        var previousAll = clicked.prevAll();

        // only proceed if it's not already on top (no previous siblings)
        if(previousAll.length > 0) {
        // top LI
        var top = $(previousAll[previousAll.length - 1]);

        // immediately previous LI
        var previous = $(previousAll[0]);

        // how far up do we need to move the clicked LI?
        var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');

        // how far down do we need to move the previous siblings?
        var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());

        // let's move stuff
        clicked.css('position', 'relative');
        previousAll.css('position', 'relative');
        clicked.animate({'top': -moveUp});
        previousAll.animate({'top': moveDown}, {complete: function() {
          // rearrange the DOM and restore positioning when we're done moving
          clicked.parent().prepend(clicked);
          clicked.css({'position': 'static', 'top': 0});
          previousAll.css({'position': 'static', 'top': 0}); 
        }});
        }
})
$(document).on('click','.clearfilters',function(){
        setCookie('brandschosen', '', -1);
        ga('send', 'event', 'filter', 'brand', 'clearfilters');
        var postdata = {'user_id':me,'type':'clear'};
        $.post("/user_filters/add", postdata, function( data ) {
          document.location.reload();
        });     
});
function selectChosenBrands(){
        var brandschosen = getCookie('brandschosen');
        if(brandschosen && brandschosen.length>0){
                var brands = brandschosen.split(',');
                for(var i in brands){
                        $('.brand').filter(function() { 
                                return $(this).data("brandid") == brands[i];
                        }).removeClass('hidden').find('.filterbrand',0).trigger( "click" );
                }
        }
}
$(function () {
        var poid = 'popovertrigger';
        /*
  var popovershown = getCookie('popovershown');
  if(!popovershown){
        popovershown = 0;
  }
  if(popovershown < 2){
        $('[data-toggle="popover"]').popover({'html':true});
        $('[data-toggle="popover"]').trigger('click');
  }  
  */
  $('#dropdownMenu1').on('click',function(){
        $('#popovertrigger').popover('hide');
        incrementPopupCount(poid,0,'popover-count-');
        setLastShown(poid,'popover-lastshown-');
  })
   
        var cname = 'popover-count-'+me+'-'+poid;
        var cookieval = getCookie(cname);
        var cname = 'popover-lastshown-'+me+'-'+poid;
        var lastshown = getCookie(cname);
        if(cookieval==''){                              
                showpopover(poid);
        } else{
                var d = new Date();
                var t = d.getTime();
                console.log('time elapsed '+(t-lastshown));
                if(t-lastshown>18*3600*1000){
                        if(cookieval>2){
                                return false;
                        }else{
                                showpopover(poid);
                                incrementPopupCount(poid,cookieval,'popover-count-');
                                setLastShown(poid,'popover-lastshown-');
                        }
                }
        }
});
function showpopover(id){
        $('[data-toggle="popover"]#'+id).popover({'html':true});
        $('[data-toggle="popover"]#'+id).trigger('click');              
}
$(document).on('click','.nodeals',function(){
        document.location = $(this).data('href');
})
var Base64 = {


    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",


    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },


    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}