Subversion Repositories SmartDukaan

Rev

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