Subversion Repositories SmartDukaan

Rev

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