Subversion Repositories SmartDukaan

Rev

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