Subversion Repositories SmartDukaan

Rev

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