Subversion Repositories SmartDukaan

Rev

Rev 19171 | Rev 19244 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14386 anikendra 1
var livePriceCalls = [];
14432 anikendra 2
var outOfStockCount = 0;
14773 anikendra 3
function getcashbackstring(type,value) {
18220 naman 4
    if(value==0){
5
        return '';
6
    }
7
    if(type==2){
8
        return ' +'+value+' Cashback';
9
    }else if(type==1){
10
        return ' +'+value+'% Cashback';
11
    }else{
12
        return '';
13
    }
15926 anikendra 14
};
15
function showShopcluesPopup(url){
18220 naman 16
    $('#shopcluesUrl').prop('href',url);
17
    $('#shopcluesModal').modal('show');
18
    return;
15926 anikendra 19
};
16397 anikendra 20
function showPaytmPopup(url){
18220 naman 21
    $('#paytmUrl').prop('href',url);
22
    $('#paytmModal').modal('show');
23
    return;
16397 anikendra 24
};
16485 anikendra 25
function showPaytmHelpPopup() {
18220 naman 26
    $('#loadingModal').modal('hide');
27
    $('#paytmHelpModal').modal('show');
16485 anikendra 28
}
29
function redirectToPaytm(url){
18220 naman 30
    url = 'http://mobilehotindia.com/r.html?'+Base64.encode(url);
31
    $('#paytmHelpModal').modal('hide');
32
    //check if paytm is active or not
33
    var paytmactive = getCookie('paytmActive',1);
34
    if(paytmactive && paytmactive == 'true'){       
35
        document.location = url;    
36
        pma.send('apk','paytm','active',me,null);
37
    }else{
38
        pma.send('apk','paytm','inactive',me,null);
39
        $('#loadingModal').modal('hide');
40
        showPaytmPopup(url);
41
    }
16485 anikendra 42
}
17006 naman 43
 
44
function redirectTohomeShop18(url){
18220 naman 45
    url = 'http://mobilehotindia.com/r.html?'+Base64.encode(url);
46
    //check if paytm is active or not
47
    var homeShop18active = getCookie('homeshop18',1);
48
    if(homeShop18active && homeShop18active == 'true'){     
49
        document.location = url;    
50
        pma.send('apk','homeShop18','active',me,null);
51
    }else{  
52
        pma.send('apk','homeShop18','inactive',me,null);
53
        $('#loadingModal').modal('hide');
54
        showhomeShop18Popup(url);
55
    }
17006 naman 56
}
57
 
58
function showhomeShop18Popup(url){
18220 naman 59
    $('#homeShop18Url').prop('href',url);
60
    $('#homeShop18Modal').modal('show');
61
    return;
17006 naman 62
};
63
 
18759 naman 64
$(function(){   
65
    if($('.scrollselector > .card').length>0) {
66
        setTimeout(function(){ document.location.reload(); }, 1000*15*60);
67
        if(typeof noscrolling == 'undefined') {
68
            $('.scrollselector').jscroll({
69
                loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
70
                autoTriggerUntil: 3,
71
                padding: 20,
72
                callback:loadCartDetails
73
            });
74
        }
75
    }
76
    if($('.storeminprice').length>0) {
77
        var globalminprice = 9999999;
78
        var globalminsku;
79
        var globalmincashback = '';     
80
        var globalminoffer = '';        
81
        var calls = [];
18763 naman 82
        var priceRange = "";
19163 naman 83
        var saholic_cash = "";
84
        var globalminpriceshow;
18759 naman 85
        $('.storeminprice').each(function(){
86
            var temp = {'sort':$(this).data('searchorder'),'val':$(this)};
87
            calls.push(temp);
88
        });
89
        calls = sortByKey(calls,'sort');        
90
        for(var i in calls){
91
            fetchLivePrice(calls[i]['val'])
92
        }               
93
    };
94
    function sortByKey(array, key) {
95
        return array.sort(function(a, b) {
96
            var x = a[key]; var y = b[key];
97
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
98
        });
99
    };      
100
    function getCouponText(coupon){
101
        return "<span class='red'>"+coupon+"</span>";
102
    };
103
    function getGrossPriceText(gross_price,available_price){
104
        if(gross_price == available_price)
105
            return "";
106
        return "Paytm cashback - "+(gross_price-available_price)+"<br>Net Price = <span class='red text-bigger'>"+available_price+"</span>"
107
    }
108
    function fetchLivePrice(obj){       
109
        ga('send', 'event', 'liveprice', 'fetch',$('#bestpriceproductname').html());
110
        var properties = {};
111
        properties.bundle_id = String($(obj).data('bundle_id'));
112
        properties.product_name = String($('#bestpriceproductname').html());
113
        pma.send('products','livesprice','fetch',me,properties);
114
        var that = obj; 
115
        var inStock = false;        
116
        var priceToCompare = 0;
19163 naman 117
        var priceToShow = 0;
18759 naman 118
        var req = $.ajax({
119
            url: '/store_products/getliveprice/'+$(that).data('bundle_id')+'/'+$(that).data('id'),
120
            // Tell jQuery we're expecting JSONP
121
            dataType: "json",
122
            // Tell YQL what we want and that we want JSON          
123
            method: 'get',
124
            // timeout: 30000,
125
            // Work with the response
126
            success: function( response ) {
127
                if(response.success){
128
                    var i = 0;  
129
                    var minpriceindex = 0;      
130
                    if(response.products[i].in_stock == 1) {
131
                        inStock = true;
132
                        var minprice = 9999999;//Math.round(response.products[i]['available_price']);
133
                        var minpriceurl = response.products[i]['marketPlaceUrl'];
134
                    }
135
                    if(response.products.length>0){
136
                        //More than one products in store
137
                        var variants = [];
138
                        var j = 0;
139
                        for(var i in response.products){                                
140
                            if(response.products[i].in_stock == 1){
141
                                if(response.products[i].gross_price && response.products[i].gross_price > response.products[i].available_price) {
19163 naman 142
//                                    priceToCompare = response.products[i].gross_price;
143
                                	priceToCompare = response.products[i].netPriceAfterCashBack;
144
                                    priceToShow = response.products[i].gross_price;
18759 naman 145
                                }else{
146
                                    if (response.products[i].source_id == 4 && response.products[i].cheapestBulkPrice != 0) {
147
                                                priceToCompare = response.products[i].cheapestBulkPrice;
148
                                                if(response.products[i].packQuantity>1){
149
                                                    priceRange =(Math.round((response.products[i].cheapestBulkPrice/response.products[i].packQuantity) * 100) / 100)    + " - "
19175 naman 150
                                                    + (Math.round((response.products[i].available_price/response.products[i].packQuantity) * 100) / 100) + " /- per unit";
18759 naman 151
                                                }
152
                                                else{
153
                                                    priceRange = response.products[i].cheapestBulkPrice
154
                                                    + " - "
19175 naman 155
                                                    + Math.round(response.products[i].available_price);
18759 naman 156
                                                }
157
 
18290 naman 158
 
18759 naman 159
                                    } else {
19163 naman 160
                                        priceToCompare = response.products[i].netPriceAfterCashBack;
161
                                        priceToShow = response.products[i].available_price;
162
                                        if(response.products[i].source_id == 4 && response.products[i].showNetPrice == 1 && response.products[i].cash_back >0 && response.products[i].cash_back_type > 0){
163
                                        	priceToShow = response.products[i].netPriceAfterCashBack;
19167 naman 164
                                        	saholic_cash = '<span style="font-size:10px;color:#555;">(</span><span style="font-size:10px;color:red;">&#8377; '+response.products[i].available_price+'</span> <span style="font-size:10px;color:#555;">less </span>';
19163 naman 165
                                        	if(response.products[i].cash_back_type == 2){
19167 naman 166
                                        		saholic_cash =  saholic_cash+'<span style="font-size:10px;color:green">&#8377; '+response.products[i].cash_back+' Cashback</span><span style="font-size:10px;color:#555;">)</span>';
19163 naman 167
                                        	}
168
                                        	if(response.products[i].cash_back_type == 1){
19167 naman 169
                                        		saholic_cash =  saholic_cash+'<span style="font-size:10px;color:green">'+response.products[i].cash_back+'% Cashback</span><span style="font-size:10px;color:#555;">)</span>';
19163 naman 170
                                        	}
171
                                        }
18759 naman 172
                                    }
173
                                }
174
                                inStock = true;                             
175
                                if(priceToCompare && priceToCompare <= globalminprice) {
176
                                    if (typeof globalminsource != "undefined" && globalminsource==4 && priceToCompare==globalminprice){
177
                                    } else {
178
                                        globalminprice = Math.round(priceToCompare);
19168 naman 179
                                        globalminpriceshow = Math.round(priceToShow);
18759 naman 180
                                        globalminsku = response.products[i]._id;
181
                                        globalminsource = response.products[i].source_id;
182
                                        globalminurl = response.products[i].marketPlaceUrl;
183
                                        globalminoffer = response.products[i].offer;
19163 naman 184
                                        if(globalminsource == 4 && saholic_cash !=""){
185
                                        	globalmincashback = saholic_cash;
186
                                        }else{
187
                                        	globalmincashback = getcashbackstring(response.products[i].cash_back_type,response.products[i].cash_back);
188
                                        }
189
 
18759 naman 190
                                    }
191
                                }
192
                                if(typeof minprice == 'undefined' || priceToCompare < minprice) {
19163 naman 193
//                                    minprice = Math.round(priceToCompare);
194
                                	minprice = Math.round(priceToShow);
18759 naman 195
                                    minpriceindex = j;
196
                                }                               
197
                                if(response.products[i].tagline && response.products[i].tagline.length>0 && $('#productoneliner').html().length==0) { 
198
                                    $('#productoneliner').html(response.products[i].tagline).removeClass('hidden').show();                                  
199
                                }                               
200
                                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});
201
                            }                   
202
                            j++;
203
                        }
204
                        if(variants.length>1){
205
                            variants.splice(minpriceindex,1);                           
206
                            var variantslink = $('<span class="variants"> '+(variants.length+1)+' Options</span>');
207
                            $(that).parent().parent().find('.pull-left',0).append(variantslink);                            
208
                            $(variantslink).data('variants',variants).data('minprice',minprice);
209
                        }
210
                    }
211
                    if(inStock){
212
                        $(that).html(minprice).siblings('.cashbackamount').html(getcashbackstring(response.products[minpriceindex].cash_back_type,response.products[minpriceindex].cash_back)).parent().addClass('viewproduct');
213
 
214
                        if($(that).parent().data('storename') == "Saholic")
215
                        {
19163 naman 216
                        	if(saholic_cash !=""){
19167 naman 217
                        		$(that).html(minprice).siblings('.cashbackamount').html("<div>"+saholic_cash+"</div>");
19163 naman 218
                        	} 
18759 naman 219
                            if (priceRange != "") {
220
                                        $(that).html(priceRange);
221
                            }
222
                            var url = minpriceurl;
223
                            var value = url.substring(url.lastIndexOf('-') + 1);
224
                            $(that).parent().attr('data-identifier', value);
225
                            $(that).parent().attr('data-proid', response.products[minpriceindex]['_id']);
226
                        }
227
 
228
                        $('#name-'+$(that).data('id')).html(response.products[minpriceindex]['source_product_name']);
229
                        if(response.products[minpriceindex]['coupon'] && response.products[minpriceindex]['coupon'].length>0){
230
                            $('#couponcode-'+$(that).data('id')).show().find('span.red',0).html(getCouponText(response.products[minpriceindex]['coupon']));
231
                        }           
232
                        if(!response.products[minpriceindex]['codAvailable']){
233
                            $('#codstatus-'+$(that).data('id')).show().removeClass('codstatus');
234
                        }
235
                        if(response.products[minpriceindex]['gross_price'] && response.products[minpriceindex]['gross_price'] > 0){
236
                            $('#gross_price-'+$(that).data('id')).show().removeClass('gross_price').html(getGrossPriceText(response.products[minpriceindex]['gross_price'],response.products[minpriceindex]['available_price']));
237
                        }
238
                        if(response.products[minpriceindex]['offer'].length>0){
239
                            $('#itemoffer-'+$(that).data('id')).show().html(response.products[minpriceindex]['offer']);
240
                        }
241
                        $('#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');
242
                        if(globalminprice != 9999999) {
19163 naman 243
                            $('#bestprice').html(globalminpriceshow).siblings('.cashbackamount').html(globalmincashback).siblings('.productoffer').html(globalminoffer);
244
                            $('#beststorelink').data('id',globalminsku).data('source',globalminsource).data('price',globalminpriceshow).data('url',globalminurl).removeClass('hidden');
18759 naman 245
                            $('#bestpricecontainer').removeClass('hidden');
18763 naman 246
 
18759 naman 247
                            if(typeof globalminsource!= "undefined") {
248
                                if (globalminsource==4){
19163 naman 249
//                                	$('#bestprice').html(globalminprice);
18759 naman 250
                                    if (priceRange != "") {
251
                                                $('#bestprice').html(priceRange);
252
                                    }
253
                                    var value = globalminurl.substring(globalminurl.lastIndexOf('-') + 1);
254
                                    $('#beststorelink').attr('data-identifier', value);
255
                                    $('#beststorelink').attr('data-proid', globalminsku);
256
                                } else {
257
                                    $('#beststorelink').removeAttr('data-identifier');
258
                                    $('#beststorelink').removeAttr('data-proid');
259
                                }                       
260
                            }
261
                        } 
262
                    } else{
263
                        ga('send', 'event', 'liveprice', 'outofstock', $('#bestpriceproductname').html());
264
                        var properties = {};
265
                        properties.sku = String(response.products[0]._id);
266
                        properties.source = String(response.products[0].source_id);
267
                        properties.product_name = String($('#bestpriceproductname').html());
268
                        pma.send('products','liveprice','outofstock',me,properties);
269
                        outOfStockCount++;
270
                        $(that).parent().parent().remove(); 
271
                    }
19163 naman 272
                    if(!response.products[minpriceindex].available_price){
18759 naman 273
                        // outOfStockCount++;
274
                        // $(that).parent().parent().remove();  
275
                        var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
276
                        $(that).html(btn);
277
                        // ga('send', 'event', 'liveprice', 'failed', response.products[0]._id);
278
                        // console.log('failed for '+ response);
279
                        // properties = {};
280
                        // properties.sku = String(response.products[0]._id); 
281
                        // pma.send('products','liveprice','failed',me,properties);
282
                    }                   
283
                } else{
284
                    // outOfStockCount++;
285
                    // $(that).parent().parent().remove();
286
                    var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
287
                    $(that).html(btn);
288
                    ga('send', 'event', 'liveprice', 'failure', response.products[0]._id);
289
                    properties = {};
290
                    properties.sku = String(response.products[0]._id); 
291
                    pma.send('products','liveprice','failure',me,properties);
292
                }
293
                checkForOutStocks(outOfStockCount);
294
            },
295
            error: function(request, status, err) {             
296
                var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
297
                $(that).html(btn);
298
                try{
299
                    if(response){
300
                        ga('send', 'event', 'liveprice', 'error', response.products[0]._id);
301
                        var properties = {};
302
                        properties.sku = String(response.products[0]._id);
303
                        pma.send('products','livescore','error',me,properties);
304
                    }                       
305
                } catch(e){}
18710 naman 306
            }
18759 naman 307
        });
308
        livePriceCalls.push(req);
309
    };
310
    function checkForOutStocks(count){
311
        if(count>=livePriceCalls.length){
312
            $('#bestpricecontainer').html('<h4>Out of stock</h4>').removeClass('hidden');   
313
        }       
314
    };
315
    $(document).on('click','.showless',function(){
316
        $(this).addClass('hidden').siblings('.varnts').hide();
317
        $(this).parent().find('.variants',0).removeClass('hidden').addClass('justshow');
318
    });
319
    $(document).on('click','.variants',function(){
320
        $('.storeproductinfo').empty();
321
        var variants = $(this).data('variants');        
322
        var minprice = $(this).data('minprice');
323
        $('#variantscount').html(variants.length);
324
        for(var i in variants){
325
            if(variants[i].gross_price && variants[i].gross_price > variants[i].available_price) {
326
                var priceToDisplay = variants[i].gross_price;
327
            }else{
328
                var priceToDisplay = variants[i].available_price;
329
            }
330
            if(minprice == priceToDisplay) {
331
                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>';
332
            } else {
333
                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>';
334
            }
335
            if(variants[i].gross_price && variants[i].gross_price>0){
336
                html += '<p class="text-small">'+getGrossPriceText(variants[i].gross_price,variants[i].available_price)+'</p>';
337
            }   
338
            if(variants[i].offer.length>0){
339
                html += '<p class="text-small">'+variants[i].offer+'</p>';
340
            }   
341
            if(variants[i].coupon && variants[i].coupon.length>0){
342
                html += '<p class="text-small">Use Coupon <span class="red">'+variants[i].coupon+'</span></p>';
343
            }
344
            if(!variants[i].codAvailable){
345
                html += '<p class="text-small">COD not available</p>';
346
            }           
347
            html += '</div></div>';
348
            var row = $(html);          
349
            $(this).parent().parent().append(row);          
350
        }
351
        var showless = $('<div class="showless col-xs-9 text-right">Less <i class="glyphicon glyphicon-chevron-up"></i></span>');
352
        $(this).parent().parent().append(showless);
353
        $(this).addClass('hidden');
354
    });
355
    $('.categorytab').on('click','.categorytabcontrol.active',function(){
356
        $(this).toggleClass('active');
357
        $('#preferences-'+$(this).data('id')).addClass('hidden');
358
        $(this).parent().parent().children().find('.savecategorypreferences',0).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
359
    });
360
    $('.categorytab').on('click','.categorytabcontrol:not(.active)',function(){
361
        $(this).parent().parent().find('.btn',0).click();
362
    });
363
    $('.categorytab').on('click','.editcategorypreferences',function(e){
364
        var that = $(this);
365
        $(that).removeClass('editcategorypreferences').addClass('savecategorypreferences').html('Done').addClass('btn-success');
366
        $('#togglepreferences-'+$(that).data('id')).toggleClass('active');
367
        $('#preferences-'+$(that).data('id')).removeClass('hidden');
368
        $('.brandselector').each(function(){
369
            if($(this).data('catid')==$(that).data('id')){
370
                $(this).addClass('active');
371
            }
372
        });
373
        $('.subcategoryselector').each(function(){
374
            if($(this).data('catid')==$(that).data('id')){
375
                $(this).addClass('active');
376
            }
377
        });     
378
    });
379
    $('.categorytab').on('click','.savecategorypreferences',function(e){
380
        var that = $(this);
381
        $(that).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
382
        $('#togglepreferences-'+$(that).data('id')).toggleClass('active');
383
        $.ajax({
384
            url: $('#categorypreference-'+$(that).data('id')).attr('action'),
385
            data: $('#categorypreference-'+$(that).data('id')).serialize(),
386
            // Tell jQuery we're expecting JSONP
387
            dataType: "json",
388
            // Tell YQL what we want and that we want JSON          
389
            method: 'post',
390
            // Work with the response
391
            success: function( response ) {
392
                if(response.success){
393
                    $('#preferences-'+$(that).data('id')).addClass('hidden');
394
                }
395
            }
396
        });
397
        active = getCookie('shopcluesActive',1);
398
        if(active && active == 'true'){
399
            $('.firsttimemsg').removeClass('hidden').show();
400
        }       
401
        ga('send', 'event', 'preferences', 'update', me);
402
        properties = pma.formDataToObject($('#categorypreference-'+$(this).data('id')).serializeArray());
403
        pma.send('preferences', 'update', 'set', me, properties);
404
    });
405
 
406
 
407
    $(document).on('click','.accsproduct',function(){
408
        if (typeof(Storage) !== "undefined") {
409
            localStorage.removeItem("productdetail");
410
            localStorage.setItem("productdetail", $(this).closest(".card").html());
411
        }
412
        $('#loadingModal').modal();
413
        var redirect_url = $(this).data('url');
414
        var properties = {};
415
        properties.sku = String($(this).data('id'));
416
        properties.source = String($(this).data('source'));
417
        properties.url = encodeURIComponent($(this).data('url'));
418
        properties.price = String($(this).data('price'));
419
        pma.send('products','url','click',me,properties);
420
        var call = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
421
        $.ajax({
422
            url: call,
423
            // The name of the callback parameter, as specified by the YQL service
424
            jsonp: "callback",
425
            // Tell jQuery we're expecting JSONP
426
            dataType: "jsonp",
427
            // Tell YQL what we want and that we want JSON
428
            data: {
429
                format: "json"
430
            },
431
            // Work with the response
432
            success: function( response ) {
433
//              console.log(response);
434
                window.location = redirect_url;
435
            },
436
            error: function() {
437
                window.location = redirect_url;
438
            }
439
            });
440
    });
441
 
442
    $(document).on('click','.viewproduct',function(e){
18290 naman 443
 
18759 naman 444
        var proid = $(this).data("proid");
445
        var identifier = $(this).data("identifier");
446
 
447
        if(typeof livePriceCalls != undefined) {
448
            for(var i in livePriceCalls){
449
                livePriceCalls[i].abort();
450
            }
451
        }
452
        $('#loadingModal').modal();
453
        if($(this).data('source')==2){
454
            //in case of flipkart, close popup after 5 seconds
455
            setTimeout(function(){ $('#loadingModal').modal('hide');$('#customMessageModal').modal('hide'); }, 1000*10);            
456
        }
457
        var store = $(this).data('source');
458
        var url = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
459
        $.ajax({
460
            url: url,
461
            // The name of the callback parameter, as specified by the YQL service
462
            jsonp: "callback",
463
            // Tell jQuery we're expecting JSONP
464
            dataType: "jsonp",
465
            // Tell YQL what we want and that we want JSON
466
            data: {
467
                format: "json"
468
            },
469
            // Work with the response
470
            success: function( response ) {
471
                if(response.success && response.type=='redirect'){
472
                    //console.log(store);
473
                    if(store == 5) {
474
                        //check if shopclues is active or not
475
                        active = getCookie('shopcluesActive',1);
476
                        response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
477
                        if(active && active == 'true'){                         
478
                            document.location = response.url;   
479
                            pma.send('apk','shopclues','active',me,null);
480
                        }else{
481
                            pma.send('apk','shopclues','inactive',me,null);
482
                            $('#loadingModal').modal('hide');
483
                            showShopcluesPopup(response.url);
484
                        }
485
                    } else if(store == 6 ) {
486
                        //display paytm help
487
//                      if(needToDisplayPaytmPopup(me)){
488
//                          showPaytmHelpPopup();
489
//                          $('#oktatabyebye').on('click',function(){
490
//                              redirectToPaytm(response.url);  
491
//                          }); 
492
//                      }else{
493
                            redirectToPaytm(response.url);  
494
//                      }
17006 naman 495
 
18220 naman 496
                    } 
497
                      //for homeshop 18
498
                      else if(store == 7)
499
                      {
500
                            redirectTohomeShop18(response.url); 
501
 
502
                      }
503
                      else if (store == 3 || store == 2) {
504
                        if (store == 2){
505
                            response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
506
                        }
507
                        if (store == 3){
508
                            response.url = '/r.html?'+Base64.encode(response.url);
509
                        }
510
                        if(response.showmessage == 1) {
511
                            $('#loadingModal').modal('hide');
512
                            $('#customMessage').html(response.message);
513
                            $('#customMessageModal').modal('show');                         
514
                            setTimeout(function(){ document.location = response.url;}, 1000*3);         
515
                        } else{
516
                            document.location = response.url;   
517
                        }
18290 naman 518
                    } else if (store == 4) {
18759 naman 519
                        var urll = apihost+"categories/saholicdeal/"+proid;
520
                        $.ajax({
18290 naman 521
                            method: "GET",
522
                            url:  urll,
523
                        },'json')
524
                        .done(function(msg){
18759 naman 525
                            if (typeof(Storage) !== "undefined") {
526
                                localStorage.removeItem("productdetail");
527
                                localStorage.setItem("productdetail",msg);
528
                                document.location = apihost+"categories/dealdetail/"+identifier;
529
                            }
18290 naman 530
                        });
18759 naman 531
 
18290 naman 532
//                        response.url = '/r.html?'+Base64.encode(response.url);
533
 
534
//                        document.location = response.url;
535
                    } 
18759 naman 536
 
537
                    else{
538
                        response.url = '/r.html?'+Base64.encode(response.url);
18290 naman 539
 
540
                      document.location = response.url;
18759 naman 541
                    }
18220 naman 542
                }
543
            },
544
            error: function() {
545
                document.location = url;
546
            }
547
        });
548
        ga('send', 'event', 'product', 'click', $(this).data('url'));
549
        var properties = {};
550
        properties.sku = String($(this).data('id'));
551
        properties.source = String($(this).data('source'));
552
        properties.url = encodeURIComponent($(this).data('url'));
553
        properties.price = String($(this).data('price'));
554
        pma.send('products','url','click',me,properties);
555
    });
556
    $(document).on('click','.likeit',function(e){   
557
        var that = $(this);
558
        if($(that).find('span.likedeal').hasClass('active')){
559
            //User has already liked it,so remove like
560
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";   
561
        }else{
562
            var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
563
        }
564
        $.ajax({
565
            url: url,
566
            // The name of the callback parameter, as specified by the YQL service
567
            jsonp: "callback",
568
            // Tell jQuery we're expecting JSONP
569
            dataType: "jsonp",
570
            // Tell YQL what we want and that we want JSON
571
            data: {
572
                format: "json"
573
            },
574
            // Work with the response
575
            success: function( response ) {
576
                if(response.success){
577
                    that.find('span.likedeal').toggleClass('active');
578
                    $(".img-overlay div[name='dislikediv_"+that.data('id')+"']").find('span.dislikedeal').removeClass('active');
579
                }
580
            }
581
        });
582
        ga('send', 'event', 'product', 'like', $(this).data('id'));
583
        var properties = {};
584
        properties.sku = String($(this).data('id'));
585
        pma.send('products','favourites','like',me,properties);
586
    });
587
    $('#myModal').on('click','#unlikebtn',function(e){
588
        e.preventDefault();
589
        var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
590
        $.ajax({
591
            url: url,
592
            // The name of the callback parameter, as specified by the YQL service
593
            jsonp: "callback",
594
            // Tell jQuery we're expecting JSONP
595
            dataType: "jsonp",
596
            // Tell YQL what we want and that we want JSON
597
            data: {
598
                format: "json"
599
            },
600
            // Work with the response
601
            success: function( response ) {
602
            }
603
        });
604
        $('#myModal').modal('hide');
605
        ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
606
        pma.send('brands','hide',$('#myModal').find('#productToHide',0).val(),me);
607
    })
18066 naman 608
    $(document).on('click','.dislikeit',function(e){            
18220 naman 609
        var that = $(this);
610
        if($(that).find('span.dislikedeal').hasClass('active')){
611
            //User has already liked it,so remove like
612
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";    
613
        }else{
614
            $('#myModal').find('#productToHide',0).val($(this).data('id'));
615
            var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
616
        }
617
        $.ajax({
618
            url: url,
619
            // The name of the callback parameter, as specified by the YQL service
620
            jsonp: "callback",
621
            // Tell jQuery we're expecting JSONP
622
            dataType: "jsonp",
623
            // Tell YQL what we want and that we want JSON
624
            data: {
625
                format: "json"
626
            },
627
            // Work with the response
628
            success: function( response ) {
629
                if(response.success){
630
                    that.find('span.dislikedeal').toggleClass('active');
631
                    $(".img-overlay div[name='likediv_"+that.data('id')+"']").find('span.likedeal').removeClass('active');
632
                }
633
            }
634
        });
635
        ga('send', 'event', 'product', 'dislike', $(this).data('id'));
636
        var properties = {};
637
        properties.sku = String($(this).data('id'));
638
        pma.send('products','favourites','dislike',me,properties);
639
    });
640
    $('.deletefav').on('click',function(){
641
        var that = $(this);
642
        $('#loadingModal').modal();
643
        var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');         
644
        $.ajax({
645
            url: url,
646
            // The name of the callback parameter, as specified by the YQL service
647
            jsonp: "callback",
648
            // Tell jQuery we're expecting JSONP
649
            dataType: "jsonp",
650
            // Tell YQL what we want and that we want JSON
651
            data: {
652
                format: "json"
653
            },
654
            // Work with the response
655
            success: function( response ) {
656
                $('#loadingModal').modal('hide');
657
                if(response.success){           
658
                    $('#fav-'+$(that).data('id')).hide('slow');
659
                }
660
            }
661
        });
662
        ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
663
        var properties = {};
664
        properties.sku = String($(this).data('id'));
665
        pma.send('products','favourites','remove',me,properties);
666
    });
667
    $('.clearfavs').on('click',function(){
668
        var that = $(this);
669
        $('#loadingModal').modal();
670
        var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');           
671
        $.ajax({
672
            url: url,
673
            // The name of the callback parameter, as specified by the YQL service
674
            jsonp: "callback",
675
            // Tell jQuery we're expecting JSONP
676
            dataType: "jsonp",
677
            // Tell YQL what we want and that we want JSON
678
            data: {
679
                format: "json"
680
            },
681
            // Work with the response
682
            success: function( response ) {
683
                $('#loadingModal').modal('hide');
684
                if(response.success){           
685
                    $('.deletefav').each(function(){
686
                        $('#fav-'+$(this).data('id')).hide('slow');
687
                    })                  
688
                }
689
                $(that).hide();
690
            }
691
        });
692
        ga('send', 'event', 'favourites', 'removeall', me);
693
        pma.send('products','favourites','removeall',me);
694
    });
695
    $('.revealbrands').on('click',function(){
696
        $(this).parent().find('.notfeatured').toggleClass('hidden');
697
        if($(this).html()=='Others'){
698
            $(this).html('Hide');
699
        }else{
700
            $(this).html('Others');
701
        }
702
    });
703
    $(document).on('click','.showtips',function(){
704
        $('.apptips').toggleClass('hidden');
705
    });
706
    $(document).on('click','.creditedcashbacks',function(){
707
        if($(this).find('.glyphicon-plus',0).length>0){
708
            $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
709
        }else{
710
            $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
711
        }
712
        $(this).next().toggleClass('hidden');
713
    });
714
    $(document).on('click','.panel-heading a',function(){
715
        if($(this).find('.glyphicon-plus',0).length>0){
716
            $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
717
        }else{
718
            $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
719
        }
720
    });
721
    $(document).on('click','.prefcatselect',function(){
722
        $('.prefcatselect').removeClass('active')
723
        $(this).addClass('active');
724
        $('.categorypreferences').addClass('hidden');
725
        $('#cat-'+$(this).data('id')).toggleClass('hidden');
726
    });
727
    $(document).on('click','.refresh',function(){
728
        document.location.reload();
729
    });
730
    $(document).on('click','.hasmoretext',function(){
731
        $('#fulltext').html($(this).data('fulltext'));
732
        $('#fullTextModal').modal();
733
    });
734
    $(document).on('click','.favswitch',function(){
735
        $('.favswitch').removeClass('active')
736
        $(this).addClass('active');
737
        $('.clearfavs').addClass('hidden');
738
        $('.card').addClass('hidden');
739
        $('.'+$(this).data('type')).removeClass('hidden');
740
    });
741
    $(document).on('click','.brandpreferences .brands',function(){
742
        $(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
743
    });
19163 naman 744
    $(document).on('click','.tryagainforliveprice',function(e){   
745
    	e.stopPropagation();
18220 naman 746
        fetchLivePrice($(this).parent());
747
        $(this).parent().html('Getting Live Prices');
748
    });
749
    $(document).on('click','.alert > a',function(){     
750
        ga('send', 'event', 'notifications', 'click', $(this).html());
751
        pma.send('notifications','click',$(this).html(),me);
752
    });
753
    $(document).on('click','.banner',function(){        
754
        ga('send', 'event', 'banners', 'click', $(this).data('name'));
755
        pma.send('banners','click',$(this).data('name'),me);
756
    });
13992 anikendra 757
});
15310 anikendra 758
function setCookie(cname, cvalue, days, forceCookie) {
18220 naman 759
    if(typeof(Storage) !== "undefined" && !forceCookie) {
760
        localStorage.setItem(cname, cvalue);
761
    } else{
762
        var d = new Date();
763
        d.setTime(d.getTime() + (days*24*60*60*1000));
764
        var expires = "expires="+d.toUTCString();
765
        document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
766
    }    
14849 anikendra 767
}
768
 
15310 anikendra 769
function getCookie(cname,forceCookie) {
18220 naman 770
    if(typeof(Storage) !== "undefined" && !forceCookie) {
771
        return localStorage.getItem(cname);
772
    } else {       
773
        var name = cname + "=";
774
        var ca = document.cookie.split(';');
775
        for(var i=0; i<ca.length; i++) {
776
            var c = ca[i];
777
            while (c.charAt(0)==' ') c = c.substring(1);
778
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
779
        }
780
        return "";
781
    }
14849 anikendra 782
}
15310 anikendra 783
 
16495 anikendra 784
function needToDisplayPaytmPopup(me){
18220 naman 785
    var id = 'tip'
786
    var cname = 'paytm-help-count-'+me+'-'+id;
787
    var cookieval = getCookie(cname,1);
788
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
789
        incrementPopupCount(id,0,'paytm-help-count-');
790
        return true;
791
    } else if(cookieval < 5) {
792
        incrementPopupCount(id,cookieval,'paytm-help-count-');
793
        return true;
794
    } else{
795
        return false;
796
    }
16495 anikendra 797
};
798
 
14849 anikendra 799
function showpopup(id,count,interval){
18220 naman 800
    var cname = 'notif-count-'+me+'-'+id;
801
    var cookieval = getCookie(cname,1);
802
    var cname = 'notif-lastshown-'+me+'-'+id;
803
    var lastshown = getCookie(cname,1);
804
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
805
        incrementPopupCount(id,0,'notif-count-');
806
        setLastShown(id,'notif-lastshown-');
807
        return true;
808
    } else{
809
        var d = new Date();
810
        var t = d.getTime();
811
        if(t-lastshown>interval*60*1000){
812
            if(cookieval>=count){
813
                return false;
814
            }else{
815
                setLastShown(id,'notif-lastshown-');
816
                incrementPopupCount(id,cookieval,'notif-count-');
817
                return true;    
818
            }
819
        }
820
    }
14849 anikendra 821
}
15077 anikendra 822
function setLastShown(id,cookiename){
18220 naman 823
    var cname = cookiename+me+'-'+id;
824
    var d = new Date();
825
    setCookie(cname, d.getTime(), 365, 1);
14849 anikendra 826
}
15077 anikendra 827
function incrementPopupCount(id,currentCount,cookiename) {
18220 naman 828
    var cname = cookiename+me+'-'+id;
829
    setCookie(cname, parseInt(currentCount)+1, 365, 1);
14858 anikendra 830
}
831
var hidden, visibilityChange; 
832
function handleVisibilityChange() {
833
  if (document[hidden]) {
18220 naman 834
    // pagetitle = document.title;
14858 anikendra 835
  } else {
18220 naman 836
    // document.title = pagetitle;
14858 anikendra 837
  }
838
}
839
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
840
  hidden = "hidden";
841
  visibilityChange = "visibilitychange";
842
} else if (typeof document.mozHidden !== "undefined") {
843
  hidden = "mozHidden";
844
  visibilityChange = "mozvisibilitychange";
845
} else if (typeof document.msHidden !== "undefined") {
846
  hidden = "msHidden";
847
  visibilityChange = "msvisibilitychange";
848
} else if (typeof document.webkitHidden !== "undefined") {
849
  hidden = "webkitHidden";
850
  visibilityChange = "webkitvisibilitychange";
851
}
852
if (typeof document.addEventListener === "undefined" || 
853
  typeof document[hidden] === "undefined") {
18119 amit.gupta 854
  //console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
14858 anikendra 855
} else {
856
  // Handle page visibility change   
857
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
858
}    
14936 anikendra 859
$('.notificationok').on('click',function(e){
18220 naman 860
    e.preventDefault();
861
    $('.notificationmodal').modal('hide');
862
    // setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
863
    ga('send', 'event', 'popupnotification-'+$(this).parent().data('id'), 'ok', me);
864
    var properties = {};
865
    properties.id = String($(this).parent().data('id'));
866
    pma.send('popupnotification','click','ok',me,properties);
867
    document.location = $(this).parent().prop('href');
15015 anikendra 868
});
18220 naman 869
$(document).on('click','.clearfilter',function(){   
870
    $('.filterbrand').each(function(){
871
        $(this).prop('checked',false);
872
    }); 
873
    ga('send', 'event', 'filter', 'brand', 'reset');
874
    pma.send('filters','brands','reset',me);
15015 anikendra 875
});
17691 naman 876
 
18220 naman 877
$(document).on('click','.clearfiltersubcategory',function(){    
878
    $('.filtersubcategory').each(function(){
879
        $(this).prop('checked',false);
880
    }); 
881
    ga('send', 'event', 'filter', 'subcategory', 'reset');
882
    pma.send('filters','subcategory','reset',me);
17691 naman 883
});
18391 naman 884
 
885
function getJsonFromUrl() {
18759 naman 886
      var query = location.search.substr(1);
887
      var result = {};
888
      query.split("&").forEach(function(part) {
889
        var item = part.split("=");
890
        result[item[0]] = decodeURIComponent(item[1]);
891
      });
892
      return result;
893
    }
18391 naman 894
 
895
$(document).on('click','.applyfilter',function(){
18759 naman 896
    var str = window.location.search;
18391 naman 897
    var urlplus = '';
898
    var urldet = getJsonFromUrl();
899
 
18220 naman 900
    $(this).prop('disabled',true);
901
    $('#loadingModal').modal();
902
    var brands = [];
903
    var brandnames = [];
904
    var subcategories = [];
905
    var subcatnames = [];
906
    $('.filterbrand').each(function(){
907
        if($(this).prop('checked')){
908
            brands.push($(this).val());
909
            brandnames.push($(this).parent().siblings('.brandname').html());
910
        }       
911
    });
912
 
913
    $('.filtersubcategory').each(function(){
914
        if($(this).prop('checked')){
915
            subcategories.push($(this).val());
916
            subcatnames.push($(this).parent().siblings('.subcategoryname').html());
917
        }
918
    });
18391 naman 919
 
920
    if($("#brandselecter").length == 0 && urldet['brands'] != undefined && urldet['brands'] != ''){
18759 naman 921
        brands = urldet['brands'];
18391 naman 922
    }
923
    if($("#subcategoryselecter").length == 0 && urldet['subcategories'] != undefined && urldet['subcategories'] != ''){
18759 naman 924
        subcategories = urldet['subcategories'];
18391 naman 925
    }
926
 
17691 naman 927
 
18391 naman 928
        if(brands.length==0 && subcategories.length==0){
18759 naman 929
            $('#loadingModal').modal('hide');
930
//          $('clearfilters').click();
931
//          setCookie('brandschosen', '', -1, true);
932
//            setCookie('subcategorieschosen','',-1, true); 
933
            var url = '';
934
            if($('#brandselecter').prop('action') !== undefined )
935
            {
936
                url = $('#brandselecter').prop('action'); 
937
            }
938
            if($('#subcategoryselecter').prop('action') !== undefined )
939
            {
940
                url = $('#subcategoryselecter').prop('action'); 
941
            }
942
            document.location = url; 
18391 naman 943
 
944
//            $('#message').html('Please choose a few brands/subcategories first').removeClass('hidden');
945
//            setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
946
//            $(this).prop('disabled',false);
947
//            return false;
948
        }else if(brands.length==0 && subcategories.length>0 ){
949
//            setCookie('subcategorieschosen', subcategories, 0.25, true);
950
            var url = $('#subcategoryselecter').prop('action');
951
            ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
952
            properties = {};
953
            for(var i in subcatnames){
954
                properties['subcategories_'+i] = subcatnames[i];
955
            }
956
            pma.send('filters','subcategories','addfilter',me,properties);
957
            var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
958
            $.post( "/user_filters/add", postdata, function( data ) {
959
                $('#loadingModal').modal('hide');
960
                $(this).prop('disabled',false);
961
                document.location = url+'&subcategories='+subcategories.join('^');
962
            }); 
963
        }else if(brands.length>0 && subcategories.length==0 ){
964
//            setCookie('brandschosen', brands, 0.25, true);
965
            var url = $('#brandselecter').prop('action');
966
            ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
967
            properties = {};
968
            for(var i in brandnames){
969
                properties['brand_'+i] = brandnames[i];
970
            }
971
            pma.send('filters','brands','addfilter',me,properties);
972
            var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
973
            $.post( "/user_filters/add", postdata, function( data ) {
974
                $('#loadingModal').modal('hide');
975
                $(this).prop('disabled',false);
976
                document.location = url+'&brands='+brands.join('^');
977
            });     
978
        }else if(brands.length>0 && subcategories.length>0 ){
979
            setCookie('brandschosen', brands, 0.25, true);
980
            setCookie('subcategorieschosen', subcategories, 0.25, true);
981
            var url = $('#brandselecter').prop('action');
982
            ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
983
            ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
984
            properties = {};
985
            for(var i in brandnames){
986
                properties['brand_'+i] = brandnames[i];
987
            }
988
            for(var i in subcatnames){
989
                properties['subcategory_'+i] = subcatnames[i];
990
            }
991
            pma.send('filters','brandsnsubcategories','addfilter',me,properties);
992
            var dataStr = brandnames.join('|');
993
            dataStr = dataStr + subcatnames.join('|');
994
            var postdata = {'user_id':me,'type':'brandnsubcategory','filters':dataStr};
995
            $.post( "/user_filters/add", postdata, function( data ) {
996
                $('#loadingModal').modal('hide');
997
                $(this).prop('disabled',false);
998
                if($("#brandselecter").length == 0 && urldet['brands'] != undefined && urldet['brands'] != ''){
18759 naman 999
                    url = $("#subcategoryselecter").prop('action');
1000
                    brands = urldet['brands'];
1001
                    document.location = url.split('?')[0]+'?brands='+brands+"&subcategories="+subcategories.join("^");
18391 naman 1002
                }
1003
                else if($("#subcategoryselecter").length == 0 && urldet['subcategories'] != undefined && urldet['subcategories'] != ''){
18759 naman 1004
                    url = $('#brandselecter').prop('action');
1005
                    subcategories = urldet['subcategories'];
1006
                    document.location = url.split('?')[0]+'?brands='+brands.join('^')+"&subcategories="+subcategories;
18391 naman 1007
                }
1008
//                document.location = url+'&brands='+brands.join('^')+"&subcategories="+subcategories.join("^");
1009
            });
18220 naman 1010
        }
18391 naman 1011
//    }
17691 naman 1012
 
18391 naman 1013
 
18220 naman 1014
    /*if(brands.length==0){
1015
        $('#loadingModal').modal('hide');
1016
        $('#message').html('Please choose a few brands first').removeClass('hidden');
1017
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
1018
        $(this).prop('disabled',false);
1019
        return false;
1020
    }else{
1021
        setCookie('brandschosen', brands, 0.25, true);
1022
        var url = $('#brandselecter').prop('action');
1023
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
1024
        properties = {};
1025
        for(var i in brandnames){
1026
            properties['brand_'+i] = brandnames[i];
1027
        }
1028
        pma.send('filters','brands','addfilter',me,properties);
1029
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
1030
        $.post( "/user_filters/add", postdata, function( data ) {
1031
            $('#loadingModal').modal('hide');
1032
            $(this).prop('disabled',false);
1033
            document.location = url+'&brands='+brands.join('^');
1034
        });     
1035
    }
17691 naman 1036
 
18220 naman 1037
    if(subcategories.length==0){
1038
        $('#loadingModal').modal('hide');
1039
        $('#message').html('Please choose a few Sub-categories first').removeClass('hidden');
1040
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
1041
        $(this).prop('disabled',false);
1042
        return false;
1043
    }else{
1044
        setCookie('subcategorieschosen', subcategories, 0.25, true);
1045
        var url = $('#subcategoryselecter').prop('action');
1046
        ga('send', 'event', 'filter', 'subcategory', brandnames.join('|'));
1047
        properties = {};
1048
        for(var i in brandnames){
1049
            properties['brand_'+i] = brandnames[i];
1050
        }
1051
        pma.send('filters','subcategories','addfilter',me,properties);
1052
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
1053
        $.post( "/user_filters/add", postdata, function( data ) {
1054
            $('#loadingModal').modal('hide');
1055
            $(this).prop('disabled',false);
1056
            document.location = url+'&brands='+brands.join('^');
1057
        });     
1058
    }*/ 
15015 anikendra 1059
});
18066 naman 1060
 
1061
 
18220 naman 1062
$(document).on('click','#showallbrands',function(){ 
1063
    $('.brand').removeClass('hidden');
18066 naman 1064
    $('.subcategory').removeClass('hidden');
18220 naman 1065
    $(this).hide();
15019 anikendra 1066
});
18220 naman 1067
$(document).on('input','#brandfilter',function(){   
1068
    $('.brand').addClass('hidden');
1069
    $('#showallbrands').hide();
1070
    var that = $(this);
1071
    $('li.brand').filter(function() { 
1072
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
1073
    }).removeClass('hidden','slow');
15042 anikendra 1074
});
17707 naman 1075
 
18220 naman 1076
$(document).on('input','#subcatfilter',function(){  
1077
    $('.subcategory').addClass('hidden');
1078
    $('#showallbrands').hide();
1079
    var that = $(this);
1080
    $('li.subcategory').filter(function() { 
1081
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
1082
    }).removeClass('hidden','slow');
17707 naman 1083
});
1084
 
1085
 
15077 anikendra 1086
$(document).on('click','.filterbrand',function(){
18220 naman 1087
    var clicked = $(this).parent().parent();
1088
    // all the LIs above the clicked one
1089
    var previousAll = clicked.prevAll();
15042 anikendra 1090
 
18220 naman 1091
    // only proceed if it's not already on top (no previous siblings)
1092
    if(previousAll.length > 0) {
1093
    // top LI
1094
    var top = $(previousAll[previousAll.length - 1]);
15042 anikendra 1095
 
18220 naman 1096
    // immediately previous LI
1097
    var previous = $(previousAll[0]);
15042 anikendra 1098
 
18220 naman 1099
    // how far up do we need to move the clicked LI?
1100
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
15042 anikendra 1101
 
18220 naman 1102
    // how far down do we need to move the previous siblings?
1103
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
15042 anikendra 1104
 
18220 naman 1105
    // let's move stuff
1106
    clicked.css('position', 'relative');
1107
    previousAll.css('position', 'relative');
1108
    clicked.animate({'top': -moveUp});
1109
    previousAll.animate({'top': moveDown}, {complete: function() {
1110
      // rearrange the DOM and restore positioning when we're done moving
1111
      clicked.parent().prepend(clicked);
1112
      clicked.css({'position': 'static', 'top': 0});
1113
      previousAll.css({'position': 'static', 'top': 0}); 
1114
    }});
1115
    }
15042 anikendra 1116
})
17691 naman 1117
$(document).on('click','.filtersubcategory',function(){
18220 naman 1118
    var clicked = $(this).parent().parent();
1119
    // all the LIs above the clicked one
1120
    var previousAll = clicked.prevAll();
17691 naman 1121
 
18220 naman 1122
    // only proceed if it's not already on top (no previous siblings)
1123
    if(previousAll.length > 0) {
1124
    // top LI
1125
    var top = $(previousAll[previousAll.length - 1]);
17691 naman 1126
 
18220 naman 1127
    // immediately previous LI
1128
    var previous = $(previousAll[0]);
17691 naman 1129
 
18220 naman 1130
    // how far up do we need to move the clicked LI?
1131
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
17691 naman 1132
 
18220 naman 1133
    // how far down do we need to move the previous siblings?
1134
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
17691 naman 1135
 
18220 naman 1136
    // let's move stuff
1137
    clicked.css('position', 'relative');
1138
    previousAll.css('position', 'relative');
1139
    clicked.animate({'top': -moveUp});
1140
    previousAll.animate({'top': moveDown}, {complete: function() {
1141
      // rearrange the DOM and restore positioning when we're done moving
1142
      clicked.parent().prepend(clicked);
1143
      clicked.css({'position': 'static', 'top': 0});
1144
      previousAll.css({'position': 'static', 'top': 0}); 
1145
    }});
1146
    }
17691 naman 1147
})
15042 anikendra 1148
$(document).on('click','.clearfilters',function(){
18391 naman 1149
//    setCookie('brandschosen', '', -1, true);
1150
//    setCookie('subcategorieschosen','',-1, true);
18220 naman 1151
    ga('send', 'event', 'filter', 'brand', 'clearfilters');
1152
    ga('send', 'event', 'filter', 'subcategory', 'clearfilters');
1153
    pma.send('filters','brands','clearfilters',me);
1154
    pma.send('filters','subcategory','clearfilters',me);
1155
    var postdata = {'user_id':me,'type':'clear'};
1156
    $('#loadingModal').modal('show');
1157
    $.post("/user_filters/add", postdata, function( data ) {        
1158
        // document.location.reload();
1159
        window.location.replace(window.location.href.split('?')[0]);
1160
    }); 
15042 anikendra 1161
});
1162
function selectChosenBrands(){
18391 naman 1163
 
1164
    var urldet = getJsonFromUrl();
1165
 
1166
    if (urldet['brands'] !=undefined && urldet['brands'] !="") {
18759 naman 1167
        var brands = urldet['brands'].split('^');
1168
            for(var i in brands){
1169
                $('[data-brandid="'+brands[i]+'"]').removeClass('hidden').find('.filterbrand',0).trigger( "click" );
1170
            }
1171
        }
18391 naman 1172
 
1173
    if (urldet['subcategories'] != undefined && urldet['subcategories'] != "") {
18759 naman 1174
        var subcategories = urldet['subcategories'].split('^');
1175
        for(var i in subcategories){
1176
                $('.subcategory').filter(function() { 
1177
                    return $(this).data("brandid") == subcategories[i];
1178
                }).removeClass('hidden').find('.filtersubcategory',0).trigger( "click" );
1179
            }
1180
        }
18391 naman 1181
 
15065 anikendra 1182
}
18190 amit.gupta 1183
 
1184
function clearFilters(){
18759 naman 1185
    setCookie('brandschosen', '', -1, true);
1186
    setCookie('subcategorieschosen','',-1, true);
18190 amit.gupta 1187
}
15585 anikendra 1188
function showPosition(position) {
15586 anikendra 1189
    setCookie('latitude',position.coords.latitude,1,true); 
18220 naman 1190
    setCookie('longitude',position.coords.longitude,1,true);    
15585 anikendra 1191
}
15065 anikendra 1192
$(function () {
19030 amit.gupta 1193
	$('div.see_more_link:first').append('<a id="popovertrigger7"  data-container="body" data-toggle="popover" data-placement="right" data-content="Click to view">&nbsp;</a>');
18759 naman 1194
    $("#popovertrigger5").popover('hide').remove();
1195
    $('.data-up:first').append('<a id="popovertrigger5"  data-container="body" data-toggle="popover" data-placement="left" data-content="Quick buy multiple items together"></a>');
19023 amit.gupta 1196
    setPopOver("popovertrigger5", ".plusqtybutton", 'click', 300);
19027 amit.gupta 1197
    setPopOver("popovertrigger7", "div.see_more_link:first a", 'click', 400);
19023 amit.gupta 1198
    setPopOver("popovertrigger", ".dropdown", 'click', 300);
18759 naman 1199
    callBackFunction = function(){
1200
        return document.location.pathname=="/category/6";       
1201
    };
1202
    setPopOver("popovertrigger4", callBackFunction,undefined,3000);
1203
    //$('[data-toggle="popover"]#'+id).popover('show');
1204
    if (navigator.geolocation) {
18023 amit.gupta 1205
        navigator.geolocation.getCurrentPosition(showPosition);
1206
    } 
1207
});
1208
 
18176 amit.gupta 1209
function setPopOver(poid, callBack1, eventString, fadeAfter){
18759 naman 1210
    var cname = 'popover-count-'+me+'-'+poid;
1211
    var cookieval = getCookie(cname,1);
1212
    if(typeof callBack1=="function"){
1213
        if (callBack1()){
1214
            var cname = 'popover-count-'+me+'-'+poid;
1215
            var cookieval = getCookie(cname,1);
1216
            $('#' + poid).popover('hide');
1217
            if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1218
                incrementPopupCount(poid,0,'popover-count-');
1219
            } else if(cookieval > 0) {
1220
                incrementPopupCount(poid, cookieval, 'popover-count-');
1221
            }
1222
            setLastShown(poid,'popover-lastshown-');
1223
        }
1224
    } else {
19023 amit.gupta 1225
        $('div.container').on(eventString, callBack1, function(){
18759 naman 1226
            var cname = 'popover-count-'+me+'-'+poid;
1227
            var cookieval = getCookie(cname,1);
1228
            $('#' + poid).popover('hide');
1229
            if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1230
                incrementPopupCount(poid,0,'popover-count-');
1231
            } else if(cookieval > 0) {
1232
                incrementPopupCount(poid, cookieval, 'popover-count-');
1233
            }
1234
            setLastShown(poid,'popover-lastshown-');
1235
        }); 
1236
    }
1237
 
1238
    if(typeof fadeAfter!="undefined"){
1239
        var s = setInterval(function(){
1240
            if($('#' + poid +':in-viewport').length>0) {
1241
                setTimeout(function(){
1242
                    $('#' + poid).popover('hide');
1243
                }, fadeAfter);
1244
                clearInterval(s);
1245
            }
1246
        }, 2000);
1247
    }
1248
 
1249
    var cname = 'popover-lastshown-'+me+'-'+poid;
1250
    var lastshown = getCookie(cname,1);
1251
    if(cookieval=='' || cookieval == 'NaN' || !cookieval){              
1252
        showpopover(poid);
1253
    } 
1254
    //Donot show popover anymore as long as we don't find a suitable solution
1255
    else{
1256
        var d = new Date();
1257
        var t = d.getTime();
1258
        if(t-lastshown>18*3600*1000){
1259
            if(cookieval>=2){
1260
                return false;
1261
            }else{
1262
                showpopover(poid);              
1263
            }
1264
        }
1265
    }
1266
    ga('send', 'event', 'popover', me, cookieval);
18023 amit.gupta 1267
}
16656 anikendra 1268
$('.getapp').on('click',function(){
18220 naman 1269
    /*var that = $(this);
1270
    var req = $.ajax({
1271
        url: 'http://104.200.25.40:8057/appAffiliates/generateRedirectUrl/'+me+'/'+$(that).data('id'),
1272
        // Tell jQuery we're expecting JSONP
1273
        dataType: "jsonp",
1274
        // Tell YQL what we want and that we want JSON          
1275
        method: 'get',
1276
        // timeout: 30000,
1277
        // Work with the response
1278
        success: function( response ) {
1279
            console.log(response);
1280
        }
1281
    });*/
1282
    $('#loadingModal').modal('show');
1283
    document.location = '/abouts/apphint';
16656 anikendra 1284
});
15077 anikendra 1285
function showpopover(id){
18220 naman 1286
    try {
1287
        $('[data-toggle="popover"]#'+id).popover({html:true,viewport:{container:'body'}, trigger:'manual'});
1288
        $('[data-toggle="popover"]#'+id).popover('show');       
1289
    }catch(err){
1290
        //
1291
    }
15085 anikendra 1292
}
1293
$(document).on('click','.nodeals',function(){
18220 naman 1294
    document.location = $(this).data('href');
16018 anikendra 1295
});
1296
$(document).on('click','.selectbrand',function(e){
18220 naman 1297
    e.preventDefault();
1298
    var brands = $(this).data('id');
1299
    var brandname = $(this).html();
1300
    //console.log(brandname);
17703 naman 1301
 
18391 naman 1302
//    setCookie('brandschosen', brands, 1, true);
18220 naman 1303
    var url = $(this).data('href');
1304
    ga('send', 'event', 'selectbrand', 'brand', brandname);
1305
    properties = {};
1306
    properties['brand'] = brandname;
1307
    pma.send('filters','brands','selectbrand',me,properties);
1308
    var postdata = {'user_id':me,'type':'brand','filters':brandname};
1309
    $.post( "/user_filters/add", postdata, function( data ) {
1310
        $('#loadingModal').modal('hide');
1311
        $(this).addClass('activebrand');
18391 naman 1312
//        document.location = url+'&brands='+brands;
1313
        document.location = url;
18220 naman 1314
    });
16018 anikendra 1315
});
17703 naman 1316
 
1317
 
18391 naman 1318
 
16495 anikendra 1319
$(document).on('click','.shownexttip',function(e){
18220 naman 1320
    $(this).addClass('hidden').remove();
1321
    $('#firsttip').addClass('hidden').remove();
1322
    $('#secondtip').removeClass('hidden');
1323
    $('.gotit').removeClass('hidden');
16495 anikendra 1324
});
15128 anikendra 1325
var Base64 = {
1326
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
1327
    encode: function(input) {
1328
        var output = "";
1329
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
1330
        var i = 0;
1331
        input = Base64._utf8_encode(input);
1332
        while (i < input.length) {
1333
            chr1 = input.charCodeAt(i++);
1334
            chr2 = input.charCodeAt(i++);
1335
            chr3 = input.charCodeAt(i++);
1336
 
1337
            enc1 = chr1 >> 2;
1338
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
1339
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
1340
            enc4 = chr3 & 63;
1341
            if (isNaN(chr2)) {
1342
                enc3 = enc4 = 64;
1343
            } else if (isNaN(chr3)) {
1344
                enc4 = 64;
1345
            }
1346
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
1347
        }
1348
        return output;
1349
    },
1350
 
1351
 
1352
    decode: function(input) {
1353
        var output = "";
1354
        var chr1, chr2, chr3;
1355
        var enc1, enc2, enc3, enc4;
1356
        var i = 0;
1357
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
1358
        while (i < input.length) {
1359
            enc1 = this._keyStr.indexOf(input.charAt(i++));
1360
            enc2 = this._keyStr.indexOf(input.charAt(i++));
1361
            enc3 = this._keyStr.indexOf(input.charAt(i++));
1362
            enc4 = this._keyStr.indexOf(input.charAt(i++));
1363
            chr1 = (enc1 << 2) | (enc2 >> 4);
1364
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
1365
            chr3 = ((enc3 & 3) << 6) | enc4;
1366
            output = output + String.fromCharCode(chr1);
1367
            if (enc3 != 64) {
1368
                output = output + String.fromCharCode(chr2);
1369
            }
1370
            if (enc4 != 64) {
1371
                output = output + String.fromCharCode(chr3);
1372
            }
1373
        }
1374
        output = Base64._utf8_decode(output);
1375
        return output;
1376
    },
1377
 
1378
    _utf8_encode: function(string) {
1379
        string = string.replace(/\r\n/g, "\n");
1380
        var utftext = "";
1381
        for (var n = 0; n < string.length; n++) {
1382
            var c = string.charCodeAt(n);
1383
            if (c < 128) {
1384
                utftext += String.fromCharCode(c);
1385
            }
1386
            else if ((c > 127) && (c < 2048)) {
1387
                utftext += String.fromCharCode((c >> 6) | 192);
1388
                utftext += String.fromCharCode((c & 63) | 128);
1389
            }
1390
            else {
1391
                utftext += String.fromCharCode((c >> 12) | 224);
1392
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
1393
                utftext += String.fromCharCode((c & 63) | 128);
1394
            }
1395
        }
1396
        return utftext;
1397
    },
1398
 
1399
    _utf8_decode: function(utftext) {
1400
        var string = "";
1401
        var i = 0;
1402
        var c = c1 = c2 = 0;
1403
        while (i < utftext.length) {
1404
            c = utftext.charCodeAt(i);
1405
            if (c < 128) {
1406
                string += String.fromCharCode(c);
1407
                i++;
1408
            }
1409
            else if ((c > 191) && (c < 224)) {
1410
                c2 = utftext.charCodeAt(i + 1);
1411
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
1412
                i += 2;
1413
            }
1414
            else {
1415
                c2 = utftext.charCodeAt(i + 1);
1416
                c3 = utftext.charCodeAt(i + 2);
1417
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
1418
                i += 3;
1419
            }
1420
        }
1421
        return string;
1422
    }
15550 anikendra 1423
}
1424
 
1425
 
1426
var pma = new function() {
15584 anikendra 1427
    this.apiurl = "http://45.33.50.227:8081/";
15550 anikendra 1428
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};
1429
 
1430
    this.send = function (category,action,label,user_id,properties) {
18220 naman 1431
        if(!properties){
1432
            properties = {};
1433
        }
1434
        properties.location = window.location.href;
1435
        // properties.appCodeName = navigator.appCodeName;
1436
        // properties.appName = navigator.appName;
1437
        // properties.appVersion = navigator.appVersion;
1438
        properties.cookieEnabled = String(navigator.cookieEnabled);
1439
        properties.platform = navigator.platform;
1440
        properties.userAgent = navigator.userAgent;
1441
        properties.ip = ip;
1442
        if (navigator.geolocation) {
1443
            if(getCookie('latitude',true)){
1444
                properties.latitude = getCookie('latitude');
1445
            }           
1446
            if(getCookie('longitude',true)){
1447
                properties.longitude = getCookie('longitude');
1448
            }
1449
        }
1450
        properties.screenHeight = String(screen.height);
1451
        properties.screenWidth = String(screen.width);
1452
        // console.log(properties);
1453
        $.ajax({
1454
            url: this.apiurl + this.endpoints.track,
1455
            data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
1456
            // Tell jQuery we're expecting JSONP
1457
            dataType: "json",
1458
            // Tell YQL what we want and that we want JSON          
1459
            method: 'post',
1460
            // Work with the response
1461
            success: function( response ) {
1462
                //Well, well, well :)
1463
            }
1464
        });       
15550 anikendra 1465
    };
1466
 
1467
    this.formDataToObject = function(formdata){
18220 naman 1468
        var properties = {};
1469
        var keys = [];
1470
        var formdata = JSON.parse(JSON.stringify(formdata));
1471
        for (var i in formdata) {
1472
            var key = formdata[i].name;
1473
            if(index = keys.indexOf(key)==-1){
1474
                properties[key] = formdata[i].value;
1475
            }else{
1476
                properties[key+'_'+i] = formdata[i].value;
1477
            }
1478
            keys.push(key);
1479
        };
1480
        return properties;
1481
    }
16704 anikendra 1482
}
1483
//App page
1484
$.fn.stars = function() {
1485
    return $(this).each(function() {
1486
        // Get the value
1487
        var val = parseFloat($(this).html());
1488
        // Make sure that the value is in 0 - 5 range, multiply to get width
1489
        val = Math.round(val * 2) / 2;
1490
        var size = Math.max(0, (Math.min(5, val))) * 16;
1491
        // Create stars holder
1492
        var $span = $('<span />').width(size);
1493
        // Replace the numerical value with stars
1494
        $(this).html($span);
1495
    });
1496
}
1497
$(function() {
18220 naman 1498
    $('span.stars').stars();    
18023 amit.gupta 1499
});
1500
 
1501
function sendCartChangeEvent(){
18220 naman 1502
    var cart_details_old = localStorage.getItem('cart_details_old');
1503
    var cart_details = localStorage.getItem('cart_details');
1504
    if (cart_details_old == cart_details){
1505
        return;
1506
    } else if(cart_details!=null){
1507
        JSON.parse(cart_details);
1508
 
1509
    }
18023 amit.gupta 1510
}
1511
 
1512
//setInterval(30000, )