Subversion Repositories SmartDukaan

Rev

Rev 18708 | Rev 18758 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

var livePriceCalls = [];
var outOfStockCount = 0;
function getcashbackstring(type,value) {
    if(value==0){
        return '';
    }
    if(type==2){
        return ' +'+value+' Cashback';
    }else if(type==1){
        return ' +'+value+'% Cashback';
    }else{
        return '';
    }
};
function showShopcluesPopup(url){
    $('#shopcluesUrl').prop('href',url);
    $('#shopcluesModal').modal('show');
    return;
};
function showPaytmPopup(url){
    $('#paytmUrl').prop('href',url);
    $('#paytmModal').modal('show');
    return;
};
function showPaytmHelpPopup() {
    $('#loadingModal').modal('hide');
    $('#paytmHelpModal').modal('show');
}
function redirectToPaytm(url){
    url = 'http://mobilehotindia.com/r.html?'+Base64.encode(url);
    $('#paytmHelpModal').modal('hide');
    //check if paytm is active or not
    var paytmactive = getCookie('paytmActive',1);
    if(paytmactive && paytmactive == 'true'){       
        document.location = url;    
        pma.send('apk','paytm','active',me,null);
    }else{
        pma.send('apk','paytm','inactive',me,null);
        $('#loadingModal').modal('hide');
        showPaytmPopup(url);
    }
}

function redirectTohomeShop18(url){
    url = 'http://mobilehotindia.com/r.html?'+Base64.encode(url);
    //check if paytm is active or not
    var homeShop18active = getCookie('homeshop18',1);
    if(homeShop18active && homeShop18active == 'true'){     
        document.location = url;    
        pma.send('apk','homeShop18','active',me,null);
    }else{  
        pma.send('apk','homeShop18','inactive',me,null);
        $('#loadingModal').modal('hide');
        showhomeShop18Popup(url);
    }
}

function showhomeShop18Popup(url){
    $('#homeShop18Url').prop('href',url);
    $('#homeShop18Modal').modal('show');
    return;
};

$(function(){   
        if($('.scrollselector > .card').length>0) {
                setTimeout(function(){ document.location.reload(); }, 1000*15*60);
                if(typeof noscrolling == 'undefined') {
                        $('.scrollselector').jscroll({
                                loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
                            autoTriggerUntil: 3,
                            padding: 20,
                            callback:loadCartDetails
                        });
                }
        }
        if($('.storeminprice').length>0) {
                var globalminprice = 9999999;
                var globalminsku;
                var globalmincashback = '';             
                var globalminoffer = '';                
                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 getCouponText(coupon){
                return "<span class='red'>"+coupon+"</span>";
        };
        function getGrossPriceText(gross_price,available_price){
                if(gross_price == available_price)
                        return "";
                return "Paytm cashback - "+(gross_price-available_price)+"<br>Net Price = <span class='red text-bigger'>"+available_price+"</span>"
        }
        function fetchLivePrice(obj){           
                ga('send', 'event', 'liveprice', 'fetch',$('#bestpriceproductname').html());
                var properties = {};
                properties.bundle_id = String($(obj).data('bundle_id'));
                properties.product_name = String($('#bestpriceproductname').html());
                pma.send('products','livesprice','fetch',me,properties);
                var that = obj; 
                var inStock = false;            
                var priceToCompare = 0;
                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 ) {
                                if(response.success){
                                        var i = 0;      
                                        var minpriceindex = 0;          
                                        if(response.products[i].in_stock == 1) {
                                                inStock = true;
                                                var minprice = 9999999;//Math.round(response.products[i]['available_price']);
                                                var minpriceurl = response.products[i]['marketPlaceUrl'];
                                        }
                                        if(response.products.length>0){
                                                //More than one products in store
                                                var variants = [];
                                                var j = 0;
                                                for(var i in response.products){                                                                
                                                        if(response.products[i].in_stock == 1){
                                                                if(response.products[i].gross_price && response.products[i].gross_price > response.products[i].available_price) {
                                                                        priceToCompare = response.products[i].gross_price;
                                                                }else{
                                                                        priceToCompare = response.products[i].available_price;
                                                                }
                                                                inStock = true;                                                         
                                                                if(priceToCompare && priceToCompare <= globalminprice) {
                                                                        if (typeof globalminsource != "undefined" && globalminsource==4 && priceToCompare==globalminprice){
                                                                        } else {
                                                                                globalminprice = Math.round(priceToCompare);
                                                                                globalminsku = response.products[i]._id;
                                                                                globalminsource = response.products[i].source_id;
                                                                                globalminurl = response.products[i].marketPlaceUrl;
                                                                                globalminoffer = response.products[i].offer;
                                                                                globalmincashback = getcashbackstring(response.products[i].cash_back_type,response.products[i].cash_back);
                                                                        }
                                                                }
                                                                if(typeof minprice == 'undefined' || priceToCompare < minprice) {
                                                                        minprice = Math.round(priceToCompare);
                                                                        minpriceindex = j;
                                                                }                                                               
                                                                if(response.products[i].tagline && response.products[i].tagline.length>0 && $('#productoneliner').html().length==0) { 
                                                                        $('#productoneliner').html(response.products[i].tagline).removeClass('hidden').show();                                                                  
                                                                }                                                               
                                                                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,'coupon': response.products[i].coupon,'codAvailable' : response.products[i].codAvailable,'offer' : response.products[i].offer,'gross_price' : response.products[i].gross_price});
                                                        }                                       
                                                        j++;
                                                }
                                                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');
                                                
                                                if($(that).parent().data('storename') == "Saholic")
                                                {
                                                        var url = minpriceurl;
                                                        var value = url.substring(url.lastIndexOf('-') + 1);
                                                        $(that).parent().attr('data-identifier', value);
                                                        $(that).parent().attr('data-proid', response.products[minpriceindex]['_id']);
                                                }

                                                $('#name-'+$(that).data('id')).html(response.products[minpriceindex]['source_product_name']);
                                                if(response.products[minpriceindex]['coupon'] && response.products[minpriceindex]['coupon'].length>0){
                                                        $('#couponcode-'+$(that).data('id')).show().find('span.red',0).html(getCouponText(response.products[minpriceindex]['coupon']));
                                                }                       
                                                if(!response.products[minpriceindex]['codAvailable']){
                                                        $('#codstatus-'+$(that).data('id')).show().removeClass('codstatus');
                                                }
                                                if(response.products[minpriceindex]['gross_price'] && response.products[minpriceindex]['gross_price'] > 0){
                                                        $('#gross_price-'+$(that).data('id')).show().removeClass('gross_price').html(getGrossPriceText(response.products[minpriceindex]['gross_price'],response.products[minpriceindex]['available_price']));
                                                }
                                                if(response.products[minpriceindex]['offer'].length>0){
                                                        $('#itemoffer-'+$(that).data('id')).show().html(response.products[minpriceindex]['offer']);
                                                }
                                                $('#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');
                                                if(globalminprice != 9999999) {
                                                        $('#bestprice').html(globalminprice).siblings('.cashbackamount').html(globalmincashback).siblings('.productoffer').html(globalminoffer);
                                                        $('#beststorelink').data('id',globalminsku).data('source',globalminsource).data('price',globalminprice).data('url',globalminurl).removeClass('hidden');
                                                        $('#bestpricecontainer').removeClass('hidden');
                                                        if(typeof globalminsource!= "undefined") {
                                                                if (globalminsource==4){
                                                                        var value = globalminurl.substring(globalminurl.lastIndexOf('-') + 1);
                                                                        $('#beststorelink').attr('data-identifier', value);
                                                                        $('#beststorelink').attr('data-proid', globalminsku);
                                                                } else {
                                                                        $('#beststorelink').removeAttr('data-identifier');
                                                                        $('#beststorelink').removeAttr('data-proid');
                                                                }                                               
                                                        }
                                                } 
                                        } else{
                                                ga('send', 'event', 'liveprice', 'outofstock', $('#bestpriceproductname').html());
                                                var properties = {};
                                                properties.sku = String(response.products[0]._id);
                                                properties.source = String(response.products[0].source_id);
                                                properties.product_name = String($('#bestpriceproductname').html());
                                                pma.send('products','liveprice','outofstock',me,properties);
                                                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);
                                                // console.log('failed for '+ response);
                                                // properties = {};
                                                // properties.sku = String(response.products[0]._id); 
                                                // pma.send('products','liveprice','failed',me,properties);
                                        }                                       
                                } 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);
                                        properties = {};
                                        properties.sku = String(response.products[0]._id); 
                                        pma.send('products','liveprice','failure',me,properties);
                                }
                                checkForOutStocks(outOfStockCount);
                        },
                        error: function(request, status, err) {                 
                        var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                $(that).html(btn);
                                try{
                                        if(response){
                                                ga('send', 'event', 'liveprice', 'error', response.products[0]._id);
                                                var properties = {};
                                                properties.sku = String(response.products[0]._id);
                                                pma.send('products','livescore','error',me,properties);
                                        }                                               
                                } catch(e){}
                        }
                });
                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');
                $('#variantscount').html(variants.length);
                for(var i in variants){
                        if(variants[i].gross_price && variants[i].gross_price > variants[i].available_price) {
                                var priceToDisplay = variants[i].gross_price;
                        }else{
                                var priceToDisplay = variants[i].available_price;
                        }
                        if(minprice == priceToDisplay) {
                                var html = '<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="'+priceToDisplay+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span class="storeminprice">'+priceToDisplay+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span>';
                        } else {
                                var html = '<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="'+priceToDisplay+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span class="text-small">'+priceToDisplay+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span>';
                        }
                        if(variants[i].gross_price && variants[i].gross_price>0){
                                html += '<p class="text-small">'+getGrossPriceText(variants[i].gross_price,variants[i].available_price)+'</p>';
                        }       
                        if(variants[i].offer.length>0){
                                html += '<p class="text-small">'+variants[i].offer+'</p>';
                        }       
                        if(variants[i].coupon && variants[i].coupon.length>0){
                                html += '<p class="text-small">Use Coupon <span class="red">'+variants[i].coupon+'</span></p>';
                        }
                        if(!variants[i].codAvailable){
                                html += '<p class="text-small">COD not available</p>';
                        }                       
                        html += '</div></div>';
                        var row = $(html);                      
                        $(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');
                        }
                });
                $('.subcategoryselector').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');
                                }
                        }
                });
                active = getCookie('shopcluesActive',1);
                if(active && active == 'true'){
                        $('.firsttimemsg').removeClass('hidden').show();
                }               
                ga('send', 'event', 'preferences', 'update', me);
                properties = pma.formDataToObject($('#categorypreference-'+$(this).data('id')).serializeArray());
                pma.send('preferences', 'update', 'set', me, properties);
        });
        
        
        $(document).on('click','.accsproduct',function(){
                if (typeof(Storage) !== "undefined") {
                        localStorage.removeItem("productdetail");
                        localStorage.setItem("productdetail", $(this).closest(".card").html());
                }
                $('#loadingModal').modal();
                var redirect_url = $(this).data('url');
                var call = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
                $.ajax({
                        url: call,
                        // 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);
                                window.location = redirect_url;
                        },
                        error: function() {
                                window.location = redirect_url;
            }
                        });
        });
        
        $(document).on('click','.viewproduct',function(e){

                var proid = $(this).data("proid");
                var identifier = $(this).data("identifier");
                
                if(typeof livePriceCalls != undefined) {
                for(var i in livePriceCalls){
                        livePriceCalls[i].abort();
                }
            }
                $('#loadingModal').modal();
                if($(this).data('source')==2){
                        //in case of flipkart, close popup after 5 seconds
                        setTimeout(function(){ $('#loadingModal').modal('hide');$('#customMessageModal').modal('hide'); }, 1000*10);                    
                }
                var store = $(this).data('source');
                var url = apihost+"clicks/add/"+me+"/"+$(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'){
                                        //console.log(store);
                                        if(store == 5) {
                                                //check if shopclues is active or not
                                                active = getCookie('shopcluesActive',1);
                                                response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
                                                if(active && active == 'true'){                                                 
                                                        document.location = response.url;       
                                                        pma.send('apk','shopclues','active',me,null);
                                                }else{
                                                        pma.send('apk','shopclues','inactive',me,null);
                                                        $('#loadingModal').modal('hide');
                                                        showShopcluesPopup(response.url);
                                                }
                                        } else if(store == 6 ) {
                                                //display paytm help
//                                              if(needToDisplayPaytmPopup(me)){
//                                                      showPaytmHelpPopup();
//                                                      $('#oktatabyebye').on('click',function(){
//                                                              redirectToPaytm(response.url);  
//                                                      });     
//                                              }else{
                                                        redirectToPaytm(response.url);  
//                                              }

                    } 
                      //for homeshop 18
                      else if(store == 7)
                      {
                            redirectTohomeShop18(response.url); 
                        
                      }
                      else if (store == 3 || store == 2) {
                        if (store == 2){
                            response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
                        }
                        if (store == 3){
                            response.url = '/r.html?'+Base64.encode(response.url);
                        }
                        if(response.showmessage == 1) {
                            $('#loadingModal').modal('hide');
                            $('#customMessage').html(response.message);
                            $('#customMessageModal').modal('show');                         
                            setTimeout(function(){ document.location = response.url;}, 1000*3);         
                        } else{
                            document.location = response.url;   
                        }
                    } else if (store == 4) {
                        var urll = apihost+"categories/saholicdeal/"+proid;
                        $.ajax({
                            method: "GET",
                            url:  urll,
                        },'json')
                        .done(function(msg){
                                if (typeof(Storage) !== "undefined") {
                                        localStorage.removeItem("productdetail");
                                                localStorage.setItem("productdetail",msg);
                                                document.location = apihost+"categories/dealdetail/"+identifier;
                                }
                        });
                        
//                        response.url = '/r.html?'+Base64.encode(response.url);

//                        document.location = response.url;
                    } 
                                        
                                        else{
                                                response.url = '/r.html?'+Base64.encode(response.url);

                      document.location = response.url;
                                        }
                }
            },
            error: function() {
                document.location = url;
            }
        });
        ga('send', 'event', 'product', 'click', $(this).data('url'));
        var properties = {};
        properties.sku = String($(this).data('id'));
        properties.source = String($(this).data('source'));
        properties.url = encodeURIComponent($(this).data('url'));
        properties.price = String($(this).data('price'));
        pma.send('products','url','click',me,properties);
    });
    $(document).on('click','.likeit',function(e){   
        var that = $(this);
        if($(that).find('span.likedeal').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.find('span.likedeal').toggleClass('active');
                    $(".img-overlay div[name='dislikediv_"+that.data('id')+"']").find('span.dislikedeal').removeClass('active');
                }
            }
        });
        ga('send', 'event', 'product', 'like', $(this).data('id'));
        var properties = {};
        properties.sku = String($(this).data('id'));
        pma.send('products','favourites','like',me,properties);
    });
    $('#myModal').on('click','#unlikebtn',function(e){
        e.preventDefault();
        var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
        $.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 ) {
            }
        });
        $('#myModal').modal('hide');
        ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
        pma.send('brands','hide',$('#myModal').find('#productToHide',0).val(),me);
    })
    $(document).on('click','.dislikeit',function(e){            
        var that = $(this);
        if($(that).find('span.dislikedeal').hasClass('active')){
            //User has already liked it,so remove like
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";    
        }else{
            $('#myModal').find('#productToHide',0).val($(this).data('id'));
            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.find('span.dislikedeal').toggleClass('active');
                    $(".img-overlay div[name='likediv_"+that.data('id')+"']").find('span.likedeal').removeClass('active');
                }
            }
        });
        ga('send', 'event', 'product', 'dislike', $(this).data('id'));
        var properties = {};
        properties.sku = String($(this).data('id'));
        pma.send('products','favourites','dislike',me,properties);
    });
    $('.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'));
        var properties = {};
        properties.sku = String($(this).data('id'));
        pma.send('products','favourites','remove',me,properties);
    });
    $('.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);
        pma.send('products','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','.showtips',function(){
        $('.apptips').toggleClass('hidden');
    });
    $(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 a',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());
        pma.send('notifications','click',$(this).html(),me);
    });
    $(document).on('click','.banner',function(){        
        ga('send', 'event', 'banners', 'click', $(this).data('name'));
        pma.send('banners','click',$(this).data('name'),me);
    });
});
function setCookie(cname, cvalue, days, forceCookie) {
    if(typeof(Storage) !== "undefined" && !forceCookie) {
        localStorage.setItem(cname, cvalue);
    } else{
        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,forceCookie) {
    if(typeof(Storage) !== "undefined" && !forceCookie) {
        return localStorage.getItem(cname);
    } else {       
        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 needToDisplayPaytmPopup(me){
    var id = 'tip'
    var cname = 'paytm-help-count-'+me+'-'+id;
    var cookieval = getCookie(cname,1);
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
        incrementPopupCount(id,0,'paytm-help-count-');
        return true;
    } else if(cookieval < 5) {
        incrementPopupCount(id,cookieval,'paytm-help-count-');
        return true;
    } else{
        return false;
    }
};

function showpopup(id,count,interval){
    var cname = 'notif-count-'+me+'-'+id;
    var cookieval = getCookie(cname,1);
    var cname = 'notif-lastshown-'+me+'-'+id;
    var lastshown = getCookie(cname,1);
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
        incrementPopupCount(id,0,'notif-count-');
        setLastShown(id,'notif-lastshown-');
        return true;
    } else{
        var d = new Date();
        var t = d.getTime();
        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, 1);
}
function incrementPopupCount(id,currentCount,cookiename) {
    var cname = cookiename+me+'-'+id;
    setCookie(cname, parseInt(currentCount)+1, 365, 1);
}
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-'+$(this).parent().data('id'), 'ok', me);
    var properties = {};
    properties.id = String($(this).parent().data('id'));
    pma.send('popupnotification','click','ok',me,properties);
    document.location = $(this).parent().prop('href');
});
$(document).on('click','.clearfilter',function(){   
    $('.filterbrand').each(function(){
        $(this).prop('checked',false);
    }); 
    ga('send', 'event', 'filter', 'brand', 'reset');
    pma.send('filters','brands','reset',me);
});

$(document).on('click','.clearfiltersubcategory',function(){    
    $('.filtersubcategory').each(function(){
        $(this).prop('checked',false);
    }); 
    ga('send', 'event', 'filter', 'subcategory', 'reset');
    pma.send('filters','subcategory','reset',me);
});

function getJsonFromUrl() {
          var query = location.search.substr(1);
          var result = {};
          query.split("&").forEach(function(part) {
            var item = part.split("=");
            result[item[0]] = decodeURIComponent(item[1]);
          });
          return result;
        }

$(document).on('click','.applyfilter',function(){
        var str = window.location.search;
    var urlplus = '';
    var urldet = getJsonFromUrl();
    
    $(this).prop('disabled',true);
    $('#loadingModal').modal();
    var brands = [];
    var brandnames = [];
    var subcategories = [];
    var subcatnames = [];
    $('.filterbrand').each(function(){
        if($(this).prop('checked')){
            brands.push($(this).val());
            brandnames.push($(this).parent().siblings('.brandname').html());
        }       
    });
    
    $('.filtersubcategory').each(function(){
        if($(this).prop('checked')){
            subcategories.push($(this).val());
            subcatnames.push($(this).parent().siblings('.subcategoryname').html());
        }
    });
    
    if($("#brandselecter").length == 0 && urldet['brands'] != undefined && urldet['brands'] != ''){
        brands = urldet['brands'];
    }
    if($("#subcategoryselecter").length == 0 && urldet['subcategories'] != undefined && urldet['subcategories'] != ''){
        subcategories = urldet['subcategories'];
    }
    

        if(brands.length==0 && subcategories.length==0){
                $('#loadingModal').modal('hide');
//              $('clearfilters').click();
//              setCookie('brandschosen', '', -1, true);
//            setCookie('subcategorieschosen','',-1, true);     
                var url = '';
                if($('#brandselecter').prop('action') !== undefined )
                {
                        url = $('#brandselecter').prop('action'); 
                }
                if($('#subcategoryselecter').prop('action') !== undefined )
                {
                        url = $('#subcategoryselecter').prop('action'); 
                }
                document.location = url; 
            
//            $('#message').html('Please choose a few brands/subcategories first').removeClass('hidden');
//            setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
//            $(this).prop('disabled',false);
//            return false;
        }else if(brands.length==0 && subcategories.length>0 ){
//            setCookie('subcategorieschosen', subcategories, 0.25, true);
            var url = $('#subcategoryselecter').prop('action');
            ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
            properties = {};
            for(var i in subcatnames){
                properties['subcategories_'+i] = subcatnames[i];
            }
            pma.send('filters','subcategories','addfilter',me,properties);
            var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
            $.post( "/user_filters/add", postdata, function( data ) {
                $('#loadingModal').modal('hide');
                $(this).prop('disabled',false);
                document.location = url+'&subcategories='+subcategories.join('^');
            }); 
        }else if(brands.length>0 && subcategories.length==0 ){
//            setCookie('brandschosen', brands, 0.25, true);
            var url = $('#brandselecter').prop('action');
            ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
            properties = {};
            for(var i in brandnames){
                properties['brand_'+i] = brandnames[i];
            }
            pma.send('filters','brands','addfilter',me,properties);
            var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
            $.post( "/user_filters/add", postdata, function( data ) {
                $('#loadingModal').modal('hide');
                $(this).prop('disabled',false);
                document.location = url+'&brands='+brands.join('^');
            });     
        }else if(brands.length>0 && subcategories.length>0 ){
            setCookie('brandschosen', brands, 0.25, true);
            setCookie('subcategorieschosen', subcategories, 0.25, true);
            var url = $('#brandselecter').prop('action');
            ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
            ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
            properties = {};
            for(var i in brandnames){
                properties['brand_'+i] = brandnames[i];
            }
            for(var i in subcatnames){
                properties['subcategory_'+i] = subcatnames[i];
            }
            pma.send('filters','brandsnsubcategories','addfilter',me,properties);
            var dataStr = brandnames.join('|');
            dataStr = dataStr + subcatnames.join('|');
            var postdata = {'user_id':me,'type':'brandnsubcategory','filters':dataStr};
            $.post( "/user_filters/add", postdata, function( data ) {
                $('#loadingModal').modal('hide');
                $(this).prop('disabled',false);
                if($("#brandselecter").length == 0 && urldet['brands'] != undefined && urldet['brands'] != ''){
                        url = $("#subcategoryselecter").prop('action');
                        brands = urldet['brands'];
                        document.location = url.split('?')[0]+'?brands='+brands+"&subcategories="+subcategories.join("^");
                }
                else if($("#subcategoryselecter").length == 0 && urldet['subcategories'] != undefined && urldet['subcategories'] != ''){
                        url = $('#brandselecter').prop('action');
                        subcategories = urldet['subcategories'];
                        document.location = url.split('?')[0]+'?brands='+brands.join('^')+"&subcategories="+subcategories;
                }
//                document.location = url+'&brands='+brands.join('^')+"&subcategories="+subcategories.join("^");
            });
        }
//    }


    /*if(brands.length==0){
        $('#loadingModal').modal('hide');
        $('#message').html('Please choose a few brands first').removeClass('hidden');
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
        $(this).prop('disabled',false);
        return false;
    }else{
        setCookie('brandschosen', brands, 0.25, true);
        var url = $('#brandselecter').prop('action');
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
        properties = {};
        for(var i in brandnames){
            properties['brand_'+i] = brandnames[i];
        }
        pma.send('filters','brands','addfilter',me,properties);
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
        $.post( "/user_filters/add", postdata, function( data ) {
            $('#loadingModal').modal('hide');
            $(this).prop('disabled',false);
            document.location = url+'&brands='+brands.join('^');
        });     
    }

    if(subcategories.length==0){
        $('#loadingModal').modal('hide');
        $('#message').html('Please choose a few Sub-categories first').removeClass('hidden');
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
        $(this).prop('disabled',false);
        return false;
    }else{
        setCookie('subcategorieschosen', subcategories, 0.25, true);
        var url = $('#subcategoryselecter').prop('action');
        ga('send', 'event', 'filter', 'subcategory', brandnames.join('|'));
        properties = {};
        for(var i in brandnames){
            properties['brand_'+i] = brandnames[i];
        }
        pma.send('filters','subcategories','addfilter',me,properties);
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
        $.post( "/user_filters/add", postdata, function( data ) {
            $('#loadingModal').modal('hide');
            $(this).prop('disabled',false);
            document.location = url+'&brands='+brands.join('^');
        });     
    }*/ 
});


$(document).on('click','#showallbrands',function(){ 
    $('.brand').removeClass('hidden');
    $('.subcategory').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('input','#subcatfilter',function(){  
    $('.subcategory').addClass('hidden');
    $('#showallbrands').hide();
    var that = $(this);
    $('li.subcategory').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();
    // 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','.filtersubcategory',function(){
    var clicked = $(this).parent().parent();
    // 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, true);
//    setCookie('subcategorieschosen','',-1, true);
    ga('send', 'event', 'filter', 'brand', 'clearfilters');
    ga('send', 'event', 'filter', 'subcategory', 'clearfilters');
    pma.send('filters','brands','clearfilters',me);
    pma.send('filters','subcategory','clearfilters',me);
    var postdata = {'user_id':me,'type':'clear'};
    $('#loadingModal').modal('show');
    $.post("/user_filters/add", postdata, function( data ) {        
        // document.location.reload();
        window.location.replace(window.location.href.split('?')[0]);
    }); 
});
function selectChosenBrands(){

    var urldet = getJsonFromUrl();

    if (urldet['brands'] !=undefined && urldet['brands'] !="") {
        var brands = urldet['brands'].split('^');
                for(var i in brands){
                        $('[data-brandid="'+brands[i]+'"]').removeClass('hidden').find('.filterbrand',0).trigger( "click" );
                }
        }
    
    if (urldet['subcategories'] != undefined && urldet['subcategories'] != "") {
        var subcategories = urldet['subcategories'].split('^');
        for(var i in subcategories){
                    $('.subcategory').filter(function() { 
                        return $(this).data("brandid") == subcategories[i];
                    }).removeClass('hidden').find('.filtersubcategory',0).trigger( "click" );
                }
        }
    
}

function clearFilters(){
        setCookie('brandschosen', '', -1, true);
        setCookie('subcategorieschosen','',-1, true);
}
function showPosition(position) {
    setCookie('latitude',position.coords.latitude,1,true); 
    setCookie('longitude',position.coords.longitude,1,true);    
}
$(function () {
        $("#popovertrigger5").popover('hide').remove();
        $('.data-up:first').append('<a id="popovertrigger5"  data-container="body" data-toggle="popover" data-placement="left" data-content="Quick buy multiple items together"></a>');
        setPopOver("popovertrigger5", ".plusqtybutton", 'click', 3000);
        callBackFunction = function(){
                return document.location.pathname=="/category/6";               
        };
        setPopOver("popovertrigger4", callBackFunction,undefined,3000);
        //$('[data-toggle="popover"]#'+id).popover('show');
        if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } 
});

function setPopOver(poid, callBack1, eventString, fadeAfter){
        var cname = 'popover-count-'+me+'-'+poid;
        var cookieval = getCookie(cname,1);
        if(typeof callBack1=="function"){
                if (callBack1()){
                        var cname = 'popover-count-'+me+'-'+poid;
                        var cookieval = getCookie(cname,1);
                        $('#' + poid).popover('hide');
                        if(!cookieval || cookieval == 'NaN' || cookieval == ''){
                                incrementPopupCount(poid,0,'popover-count-');
                        } else if(cookieval > 0) {
                                incrementPopupCount(poid, cookieval, 'popover-count-');
                        }
                        setLastShown(poid,'popover-lastshown-');
                }
        } else {
                $('div.content').on(eventString, callBack1, function(){
                        var cname = 'popover-count-'+me+'-'+poid;
                        var cookieval = getCookie(cname,1);
                        $('#' + poid).popover('hide');
                        if(!cookieval || cookieval == 'NaN' || cookieval == ''){
                                incrementPopupCount(poid,0,'popover-count-');
                        } else if(cookieval > 0) {
                                incrementPopupCount(poid, cookieval, 'popover-count-');
                        }
                        setLastShown(poid,'popover-lastshown-');
                }); 
        }
        
        if(typeof fadeAfter!="undefined"){
                var s = setInterval(function(){
                        if($('#' + poid +':in-viewport').length>0) {
                                setTimeout(function(){
                                        $('#' + poid).popover('hide');
                                }, fadeAfter);
                                clearInterval(s);
                        }
                }, 2000);
        }
        
        var cname = 'popover-lastshown-'+me+'-'+poid;
        var lastshown = getCookie(cname,1);
        if(cookieval=='' || cookieval == 'NaN' || !cookieval){                          
                showpopover(poid);
        } 
        //Donot show popover anymore as long as we don't find a suitable solution
        else{
                var d = new Date();
                var t = d.getTime();
                if(t-lastshown>18*3600*1000){
                        if(cookieval>=2){
                                return false;
                        }else{
                                showpopover(poid);                              
                        }
                }
        }
        ga('send', 'event', 'popover', me, cookieval);
}
$('.getapp').on('click',function(){
    /*var that = $(this);
    var req = $.ajax({
        url: 'http://104.200.25.40:8057/appAffiliates/generateRedirectUrl/'+me+'/'+$(that).data('id'),
        // Tell jQuery we're expecting JSONP
        dataType: "jsonp",
        // Tell YQL what we want and that we want JSON          
        method: 'get',
        // timeout: 30000,
        // Work with the response
        success: function( response ) {
            console.log(response);
        }
    });*/
    $('#loadingModal').modal('show');
    document.location = '/abouts/apphint';
});
function showpopover(id){
    try {
        $('[data-toggle="popover"]#'+id).popover({html:true,viewport:{container:'body'}, trigger:'manual'});
        $('[data-toggle="popover"]#'+id).popover('show');       
    }catch(err){
        //
    }
}
$(document).on('click','.nodeals',function(){
    document.location = $(this).data('href');
});
$(document).on('click','.selectbrand',function(e){
    e.preventDefault();
    var brands = $(this).data('id');
    var brandname = $(this).html();
    //console.log(brandname);

//    setCookie('brandschosen', brands, 1, true);
    var url = $(this).data('href');
    ga('send', 'event', 'selectbrand', 'brand', brandname);
    properties = {};
    properties['brand'] = brandname;
    pma.send('filters','brands','selectbrand',me,properties);
    var postdata = {'user_id':me,'type':'brand','filters':brandname};
    $.post( "/user_filters/add", postdata, function( data ) {
        $('#loadingModal').modal('hide');
        $(this).addClass('activebrand');
//        document.location = url+'&brands='+brands;
        document.location = url;
    });
});



$(document).on('click','.shownexttip',function(e){
    $(this).addClass('hidden').remove();
    $('#firsttip').addClass('hidden').remove();
    $('#secondtip').removeClass('hidden');
    $('.gotit').removeClass('hidden');
});
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;
    }
}


var pma = new function() {
    this.apiurl = "http://45.33.50.227:8081/";
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};

    this.send = function (category,action,label,user_id,properties) {
        if(!properties){
            properties = {};
        }
        properties.location = window.location.href;
        // properties.appCodeName = navigator.appCodeName;
        // properties.appName = navigator.appName;
        // properties.appVersion = navigator.appVersion;
        properties.cookieEnabled = String(navigator.cookieEnabled);
        properties.platform = navigator.platform;
        properties.userAgent = navigator.userAgent;
        properties.ip = ip;
        if (navigator.geolocation) {
            if(getCookie('latitude',true)){
                properties.latitude = getCookie('latitude');
            }           
            if(getCookie('longitude',true)){
                properties.longitude = getCookie('longitude');
            }
        }
        properties.screenHeight = String(screen.height);
        properties.screenWidth = String(screen.width);
        // console.log(properties);
        $.ajax({
            url: this.apiurl + this.endpoints.track,
            data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
            // 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 ) {
                //Well, well, well :)
            }
        });       
    };

    this.formDataToObject = function(formdata){
        var properties = {};
        var keys = [];
        var formdata = JSON.parse(JSON.stringify(formdata));
        for (var i in formdata) {
            var key = formdata[i].name;
            if(index = keys.indexOf(key)==-1){
                properties[key] = formdata[i].value;
            }else{
                properties[key+'_'+i] = formdata[i].value;
            }
            keys.push(key);
        };
        return properties;
    }
}
//App page
$.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        val = Math.round(val * 2) / 2;
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}
$(function() {
    $('span.stars').stars();    
});

function sendCartChangeEvent(){
    var cart_details_old = localStorage.getItem('cart_details_old');
    var cart_details = localStorage.getItem('cart_details');
    if (cart_details_old == cart_details){
        return;
    } else if(cart_details!=null){
        JSON.parse(cart_details);
        
    }
}

//setInterval(30000, )