Subversion Repositories SmartDukaan

Rev

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