Subversion Repositories SmartDukaan

Rev

Rev 18226 | Rev 18290 | 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(){
18226 naman 336
		if (typeof(Storage) !== "undefined") {
337
			localStorage.removeItem("productdetail");
338
			localStorage.setItem("productdetail", $(this).closest(".card").html());
339
		}
18220 naman 340
		$('#loadingModal').modal();
18226 naman 341
 
18220 naman 342
		var url = $(this).data('url');
18226 naman 343
 
18220 naman 344
		window.location = url;
345
	});
346
 
15767 anikendra 347
	$(document).on('click','.viewproduct',function(e){		
14386 anikendra 348
		if(typeof livePriceCalls != undefined) {
349
	    	for(var i in livePriceCalls){
350
	    		livePriceCalls[i].abort();
351
	    	}
352
	    }
13686 anikendra 353
		$('#loadingModal').modal();
14952 anikendra 354
		if($(this).data('source')==2){
355
			//in case of flipkart, close popup after 5 seconds
15311 anikendra 356
			setTimeout(function(){ $('#loadingModal').modal('hide');$('#customMessageModal').modal('hide'); }, 1000*10);			
14952 anikendra 357
		}
15159 anikendra 358
		var store = $(this).data('source');
14345 anikendra 359
		var url = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
13579 anikendra 360
		$.ajax({
361
			url: url,
362
			// The name of the callback parameter, as specified by the YQL service
363
			jsonp: "callback",
364
			// Tell jQuery we're expecting JSONP
365
			dataType: "jsonp",
366
			// Tell YQL what we want and that we want JSON
367
			data: {
368
				format: "json"
369
			},
370
			// Work with the response
371
			success: function( response ) {
372
				if(response.success && response.type=='redirect'){
18119 amit.gupta 373
					//console.log(store);
15920 anikendra 374
					if(store == 5) {
375
						//check if shopclues is active or not
376
						active = getCookie('shopcluesActive',1);
16679 anikendra 377
						response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
378
						if(active && active == 'true'){							
15920 anikendra 379
							document.location = response.url;	
380
							pma.send('apk','shopclues','active',me,null);
381
						}else{
382
							pma.send('apk','shopclues','inactive',me,null);
383
							$('#loadingModal').modal('hide');
384
							showShopcluesPopup(response.url);
385
						}
17026 naman 386
				  	} else if(store == 6 ) {
16485 anikendra 387
				  		//display paytm help
18261 naman 388
//				  		if(needToDisplayPaytmPopup(me)){
389
//				  			showPaytmHelpPopup();
390
//					  		$('#oktatabyebye').on('click',function(){
391
//					  			redirectToPaytm(response.url);	
392
//					  		});	
393
//				  		}else{
16495 anikendra 394
				  			redirectToPaytm(response.url);	
18261 naman 395
//				  		}
17006 naman 396
 
18220 naman 397
                    } 
398
                      //for homeshop 18
399
                      else if(store == 7)
400
                      {
401
                            redirectTohomeShop18(response.url); 
402
 
403
                      }
404
                      else if (store == 3 || store == 2) {
405
                        if (store == 2){
406
                            response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
407
                        }
408
                        if (store == 3){
409
                            response.url = '/r.html?'+Base64.encode(response.url);
410
                        }
411
                        if(response.showmessage == 1) {
412
                            $('#loadingModal').modal('hide');
413
                            $('#customMessage').html(response.message);
414
                            $('#customMessageModal').modal('show');                         
415
                            setTimeout(function(){ document.location = response.url;}, 1000*3);         
416
                        } else{
417
                            document.location = response.url;   
418
                        }
419
                    } else {
420
                        response.url = '/r.html?'+Base64.encode(response.url);
421
                        document.location = response.url;
422
                    }                                       
423
                }
424
            },
425
            error: function() {
426
                document.location = url;
427
            }
428
        });
429
        ga('send', 'event', 'product', 'click', $(this).data('url'));
430
        var properties = {};
431
        properties.sku = String($(this).data('id'));
432
        properties.source = String($(this).data('source'));
433
        properties.url = encodeURIComponent($(this).data('url'));
434
        properties.price = String($(this).data('price'));
435
        pma.send('products','url','click',me,properties);
436
    });
437
    $(document).on('click','.likeit',function(e){   
438
        var that = $(this);
439
        if($(that).find('span.likedeal').hasClass('active')){
440
            //User has already liked it,so remove like
441
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";   
442
        }else{
443
            var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
444
        }
445
        $.ajax({
446
            url: url,
447
            // The name of the callback parameter, as specified by the YQL service
448
            jsonp: "callback",
449
            // Tell jQuery we're expecting JSONP
450
            dataType: "jsonp",
451
            // Tell YQL what we want and that we want JSON
452
            data: {
453
                format: "json"
454
            },
455
            // Work with the response
456
            success: function( response ) {
457
                if(response.success){
458
                    that.find('span.likedeal').toggleClass('active');
459
                    $(".img-overlay div[name='dislikediv_"+that.data('id')+"']").find('span.dislikedeal').removeClass('active');
460
                }
461
            }
462
        });
463
        ga('send', 'event', 'product', 'like', $(this).data('id'));
464
        var properties = {};
465
        properties.sku = String($(this).data('id'));
466
        pma.send('products','favourites','like',me,properties);
467
    });
468
    $('#myModal').on('click','#unlikebtn',function(e){
469
        e.preventDefault();
470
        var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
471
        $.ajax({
472
            url: url,
473
            // The name of the callback parameter, as specified by the YQL service
474
            jsonp: "callback",
475
            // Tell jQuery we're expecting JSONP
476
            dataType: "jsonp",
477
            // Tell YQL what we want and that we want JSON
478
            data: {
479
                format: "json"
480
            },
481
            // Work with the response
482
            success: function( response ) {
483
            }
484
        });
485
        $('#myModal').modal('hide');
486
        ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
487
        pma.send('brands','hide',$('#myModal').find('#productToHide',0).val(),me);
488
    })
18066 naman 489
    $(document).on('click','.dislikeit',function(e){            
18220 naman 490
        var that = $(this);
491
        if($(that).find('span.dislikedeal').hasClass('active')){
492
            //User has already liked it,so remove like
493
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";    
494
        }else{
495
            $('#myModal').find('#productToHide',0).val($(this).data('id'));
496
            var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
497
        }
498
        $.ajax({
499
            url: url,
500
            // The name of the callback parameter, as specified by the YQL service
501
            jsonp: "callback",
502
            // Tell jQuery we're expecting JSONP
503
            dataType: "jsonp",
504
            // Tell YQL what we want and that we want JSON
505
            data: {
506
                format: "json"
507
            },
508
            // Work with the response
509
            success: function( response ) {
510
                if(response.success){
511
                    that.find('span.dislikedeal').toggleClass('active');
512
                    $(".img-overlay div[name='likediv_"+that.data('id')+"']").find('span.likedeal').removeClass('active');
513
                }
514
            }
515
        });
516
        ga('send', 'event', 'product', 'dislike', $(this).data('id'));
517
        var properties = {};
518
        properties.sku = String($(this).data('id'));
519
        pma.send('products','favourites','dislike',me,properties);
520
    });
521
    $('.deletefav').on('click',function(){
522
        var that = $(this);
523
        $('#loadingModal').modal();
524
        var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');         
525
        $.ajax({
526
            url: url,
527
            // The name of the callback parameter, as specified by the YQL service
528
            jsonp: "callback",
529
            // Tell jQuery we're expecting JSONP
530
            dataType: "jsonp",
531
            // Tell YQL what we want and that we want JSON
532
            data: {
533
                format: "json"
534
            },
535
            // Work with the response
536
            success: function( response ) {
537
                $('#loadingModal').modal('hide');
538
                if(response.success){           
539
                    $('#fav-'+$(that).data('id')).hide('slow');
540
                }
541
            }
542
        });
543
        ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
544
        var properties = {};
545
        properties.sku = String($(this).data('id'));
546
        pma.send('products','favourites','remove',me,properties);
547
    });
548
    $('.clearfavs').on('click',function(){
549
        var that = $(this);
550
        $('#loadingModal').modal();
551
        var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');           
552
        $.ajax({
553
            url: url,
554
            // The name of the callback parameter, as specified by the YQL service
555
            jsonp: "callback",
556
            // Tell jQuery we're expecting JSONP
557
            dataType: "jsonp",
558
            // Tell YQL what we want and that we want JSON
559
            data: {
560
                format: "json"
561
            },
562
            // Work with the response
563
            success: function( response ) {
564
                $('#loadingModal').modal('hide');
565
                if(response.success){           
566
                    $('.deletefav').each(function(){
567
                        $('#fav-'+$(this).data('id')).hide('slow');
568
                    })                  
569
                }
570
                $(that).hide();
571
            }
572
        });
573
        ga('send', 'event', 'favourites', 'removeall', me);
574
        pma.send('products','favourites','removeall',me);
575
    });
576
    $('.revealbrands').on('click',function(){
577
        $(this).parent().find('.notfeatured').toggleClass('hidden');
578
        if($(this).html()=='Others'){
579
            $(this).html('Hide');
580
        }else{
581
            $(this).html('Others');
582
        }
583
    });
584
    $(document).on('click','.showtips',function(){
585
        $('.apptips').toggleClass('hidden');
586
    });
587
    $(document).on('click','.creditedcashbacks',function(){
588
        if($(this).find('.glyphicon-plus',0).length>0){
589
            $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
590
        }else{
591
            $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
592
        }
593
        $(this).next().toggleClass('hidden');
594
    });
595
    $(document).on('click','.panel-heading a',function(){
596
        if($(this).find('.glyphicon-plus',0).length>0){
597
            $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
598
        }else{
599
            $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
600
        }
601
    });
602
    $(document).on('click','.prefcatselect',function(){
603
        $('.prefcatselect').removeClass('active')
604
        $(this).addClass('active');
605
        $('.categorypreferences').addClass('hidden');
606
        $('#cat-'+$(this).data('id')).toggleClass('hidden');
607
    });
608
    $(document).on('click','.refresh',function(){
609
        document.location.reload();
610
    });
611
    $(document).on('click','.hasmoretext',function(){
612
        $('#fulltext').html($(this).data('fulltext'));
613
        $('#fullTextModal').modal();
614
    });
615
    $(document).on('click','.favswitch',function(){
616
        $('.favswitch').removeClass('active')
617
        $(this).addClass('active');
618
        $('.clearfavs').addClass('hidden');
619
        $('.card').addClass('hidden');
620
        $('.'+$(this).data('type')).removeClass('hidden');
621
    });
622
    $(document).on('click','.brandpreferences .brands',function(){
623
        $(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
624
    });
625
    $(document).on('click','.tryagainforliveprice',function(){      
626
        fetchLivePrice($(this).parent());
627
        $(this).parent().html('Getting Live Prices');
628
    });
629
    $(document).on('click','.alert > a',function(){     
630
        ga('send', 'event', 'notifications', 'click', $(this).html());
631
        pma.send('notifications','click',$(this).html(),me);
632
    });
633
    $(document).on('click','.banner',function(){        
634
        ga('send', 'event', 'banners', 'click', $(this).data('name'));
635
        pma.send('banners','click',$(this).data('name'),me);
636
    });
13992 anikendra 637
});
15310 anikendra 638
function setCookie(cname, cvalue, days, forceCookie) {
18220 naman 639
    if(typeof(Storage) !== "undefined" && !forceCookie) {
640
        localStorage.setItem(cname, cvalue);
641
    } else{
642
        var d = new Date();
643
        d.setTime(d.getTime() + (days*24*60*60*1000));
644
        var expires = "expires="+d.toUTCString();
645
        document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
646
    }    
14849 anikendra 647
}
648
 
15310 anikendra 649
function getCookie(cname,forceCookie) {
18220 naman 650
    if(typeof(Storage) !== "undefined" && !forceCookie) {
651
        return localStorage.getItem(cname);
652
    } else {       
653
        var name = cname + "=";
654
        var ca = document.cookie.split(';');
655
        for(var i=0; i<ca.length; i++) {
656
            var c = ca[i];
657
            while (c.charAt(0)==' ') c = c.substring(1);
658
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
659
        }
660
        return "";
661
    }
14849 anikendra 662
}
15310 anikendra 663
 
16495 anikendra 664
function needToDisplayPaytmPopup(me){
18220 naman 665
    var id = 'tip'
666
    var cname = 'paytm-help-count-'+me+'-'+id;
667
    var cookieval = getCookie(cname,1);
668
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
669
        incrementPopupCount(id,0,'paytm-help-count-');
670
        return true;
671
    } else if(cookieval < 5) {
672
        incrementPopupCount(id,cookieval,'paytm-help-count-');
673
        return true;
674
    } else{
675
        return false;
676
    }
16495 anikendra 677
};
678
 
14849 anikendra 679
function showpopup(id,count,interval){
18220 naman 680
    var cname = 'notif-count-'+me+'-'+id;
681
    var cookieval = getCookie(cname,1);
682
    var cname = 'notif-lastshown-'+me+'-'+id;
683
    var lastshown = getCookie(cname,1);
684
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
685
        incrementPopupCount(id,0,'notif-count-');
686
        setLastShown(id,'notif-lastshown-');
687
        return true;
688
    } else{
689
        var d = new Date();
690
        var t = d.getTime();
691
        if(t-lastshown>interval*60*1000){
692
            if(cookieval>=count){
693
                return false;
694
            }else{
695
                setLastShown(id,'notif-lastshown-');
696
                incrementPopupCount(id,cookieval,'notif-count-');
697
                return true;    
698
            }
699
        }
700
    }
14849 anikendra 701
}
15077 anikendra 702
function setLastShown(id,cookiename){
18220 naman 703
    var cname = cookiename+me+'-'+id;
704
    var d = new Date();
705
    setCookie(cname, d.getTime(), 365, 1);
14849 anikendra 706
}
15077 anikendra 707
function incrementPopupCount(id,currentCount,cookiename) {
18220 naman 708
    var cname = cookiename+me+'-'+id;
709
    setCookie(cname, parseInt(currentCount)+1, 365, 1);
14858 anikendra 710
}
711
var hidden, visibilityChange; 
712
function handleVisibilityChange() {
713
  if (document[hidden]) {
18220 naman 714
    // pagetitle = document.title;
14858 anikendra 715
  } else {
18220 naman 716
    // document.title = pagetitle;
14858 anikendra 717
  }
718
}
719
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
720
  hidden = "hidden";
721
  visibilityChange = "visibilitychange";
722
} else if (typeof document.mozHidden !== "undefined") {
723
  hidden = "mozHidden";
724
  visibilityChange = "mozvisibilitychange";
725
} else if (typeof document.msHidden !== "undefined") {
726
  hidden = "msHidden";
727
  visibilityChange = "msvisibilitychange";
728
} else if (typeof document.webkitHidden !== "undefined") {
729
  hidden = "webkitHidden";
730
  visibilityChange = "webkitvisibilitychange";
731
}
732
if (typeof document.addEventListener === "undefined" || 
733
  typeof document[hidden] === "undefined") {
18119 amit.gupta 734
  //console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
14858 anikendra 735
} else {
736
  // Handle page visibility change   
737
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
738
}    
14936 anikendra 739
$('.notificationok').on('click',function(e){
18220 naman 740
    e.preventDefault();
741
    $('.notificationmodal').modal('hide');
742
    // setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
743
    ga('send', 'event', 'popupnotification-'+$(this).parent().data('id'), 'ok', me);
744
    var properties = {};
745
    properties.id = String($(this).parent().data('id'));
746
    pma.send('popupnotification','click','ok',me,properties);
747
    document.location = $(this).parent().prop('href');
15015 anikendra 748
});
18220 naman 749
$(document).on('click','.clearfilter',function(){   
750
    $('.filterbrand').each(function(){
751
        $(this).prop('checked',false);
752
    }); 
753
    ga('send', 'event', 'filter', 'brand', 'reset');
754
    pma.send('filters','brands','reset',me);
15015 anikendra 755
});
17691 naman 756
 
18220 naman 757
$(document).on('click','.clearfiltersubcategory',function(){    
758
    $('.filtersubcategory').each(function(){
759
        $(this).prop('checked',false);
760
    }); 
761
    ga('send', 'event', 'filter', 'subcategory', 'reset');
762
    pma.send('filters','subcategory','reset',me);
17691 naman 763
});
18220 naman 764
$(document).on('click','.applyfilter',function(){   
765
    $(this).prop('disabled',true);
766
    $('#loadingModal').modal();
767
    var brands = [];
768
    var brandnames = [];
769
    var subcategories = [];
770
    var subcatnames = [];
771
    $('.filterbrand').each(function(){
772
        if($(this).prop('checked')){
773
            brands.push($(this).val());
774
            brandnames.push($(this).parent().siblings('.brandname').html());
775
        }       
776
    });
777
 
778
    $('.filtersubcategory').each(function(){
779
        if($(this).prop('checked')){
780
            subcategories.push($(this).val());
781
            subcatnames.push($(this).parent().siblings('.subcategoryname').html());
782
        }
783
    });
17691 naman 784
 
18220 naman 785
    if(brands.length==0 && subcategories.length==0){
786
        $('#loadingModal').modal('hide');
787
        $('#message').html('Please choose a few brands/subcategories first').removeClass('hidden');
788
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
789
        $(this).prop('disabled',false);
790
        return false;
791
    }else if(brands.length==0 && subcategories.length>0 ){
792
        setCookie('subcategorieschosen', subcategories, 0.25, true);
793
        var url = $('#subcategoryselecter').prop('action');
794
        ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
795
        properties = {};
796
        for(var i in subcatnames){
797
            properties['subcategories_'+i] = subcatnames[i];
798
        }
799
        pma.send('filters','subcategories','addfilter',me,properties);
800
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
801
        $.post( "/user_filters/add", postdata, function( data ) {
802
            $('#loadingModal').modal('hide');
803
            $(this).prop('disabled',false);
804
            document.location = url+'&subcategories='+subcategories.join('^');
805
        }); 
806
    }else if(brands.length>0 && subcategories.length==0 ){
807
        setCookie('brandschosen', brands, 0.25, true);
808
        var url = $('#brandselecter').prop('action');
809
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
810
        properties = {};
811
        for(var i in brandnames){
812
            properties['brand_'+i] = brandnames[i];
813
        }
814
        pma.send('filters','brands','addfilter',me,properties);
815
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
816
        $.post( "/user_filters/add", postdata, function( data ) {
817
            $('#loadingModal').modal('hide');
818
            $(this).prop('disabled',false);
819
            document.location = url+'&brands='+brands.join('^');
820
        });     
821
    }else if(brands.length>0 && subcategories.length>0 ){
822
        setCookie('brandschosen', brands, 0.25, true);
823
        setCookie('subcategorieschosen', subcategories, 0.25, true);
824
        var url = $('#brandselecter').prop('action');
825
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
826
        ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
827
        properties = {};
828
        for(var i in brandnames){
829
            properties['brand_'+i] = brandnames[i];
830
        }
831
        for(var i in subcatnames){
832
            properties['subcategory_'+i] = subcatnames[i];
833
        }
834
        pma.send('filters','brandsnsubcategories','addfilter',me,properties);
835
        var dataStr = brandnames.join('|');
836
        dataStr = dataStr + subcatnames.join('|');
837
        var postdata = {'user_id':me,'type':'brandnsubcategory','filters':dataStr};
838
        $.post( "/user_filters/add", postdata, function( data ) {
839
            $('#loadingModal').modal('hide');
840
            $(this).prop('disabled',false);
841
            document.location = url+'&brands='+brands.join('^')+"&subcategories="+subcategories.join("^");
842
        });
843
    }
17691 naman 844
 
18220 naman 845
    /*if(brands.length==0){
846
        $('#loadingModal').modal('hide');
847
        $('#message').html('Please choose a few brands first').removeClass('hidden');
848
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
849
        $(this).prop('disabled',false);
850
        return false;
851
    }else{
852
        setCookie('brandschosen', brands, 0.25, true);
853
        var url = $('#brandselecter').prop('action');
854
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
855
        properties = {};
856
        for(var i in brandnames){
857
            properties['brand_'+i] = brandnames[i];
858
        }
859
        pma.send('filters','brands','addfilter',me,properties);
860
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
861
        $.post( "/user_filters/add", postdata, function( data ) {
862
            $('#loadingModal').modal('hide');
863
            $(this).prop('disabled',false);
864
            document.location = url+'&brands='+brands.join('^');
865
        });     
866
    }
17691 naman 867
 
18220 naman 868
    if(subcategories.length==0){
869
        $('#loadingModal').modal('hide');
870
        $('#message').html('Please choose a few Sub-categories first').removeClass('hidden');
871
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
872
        $(this).prop('disabled',false);
873
        return false;
874
    }else{
875
        setCookie('subcategorieschosen', subcategories, 0.25, true);
876
        var url = $('#subcategoryselecter').prop('action');
877
        ga('send', 'event', 'filter', 'subcategory', brandnames.join('|'));
878
        properties = {};
879
        for(var i in brandnames){
880
            properties['brand_'+i] = brandnames[i];
881
        }
882
        pma.send('filters','subcategories','addfilter',me,properties);
883
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
884
        $.post( "/user_filters/add", postdata, function( data ) {
885
            $('#loadingModal').modal('hide');
886
            $(this).prop('disabled',false);
887
            document.location = url+'&brands='+brands.join('^');
888
        });     
889
    }*/ 
15015 anikendra 890
});
18066 naman 891
 
892
 
18220 naman 893
$(document).on('click','#showallbrands',function(){ 
894
    $('.brand').removeClass('hidden');
18066 naman 895
    $('.subcategory').removeClass('hidden');
18220 naman 896
    $(this).hide();
15019 anikendra 897
});
18220 naman 898
$(document).on('input','#brandfilter',function(){   
899
    $('.brand').addClass('hidden');
900
    $('#showallbrands').hide();
901
    var that = $(this);
902
    $('li.brand').filter(function() { 
903
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
904
    }).removeClass('hidden','slow');
15042 anikendra 905
});
17707 naman 906
 
18220 naman 907
$(document).on('input','#subcatfilter',function(){  
908
    $('.subcategory').addClass('hidden');
909
    $('#showallbrands').hide();
910
    var that = $(this);
911
    $('li.subcategory').filter(function() { 
912
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
913
    }).removeClass('hidden','slow');
17707 naman 914
});
915
 
916
 
15077 anikendra 917
$(document).on('click','.filterbrand',function(){
18220 naman 918
    var clicked = $(this).parent().parent();
919
    // all the LIs above the clicked one
920
    var previousAll = clicked.prevAll();
15042 anikendra 921
 
18220 naman 922
    // only proceed if it's not already on top (no previous siblings)
923
    if(previousAll.length > 0) {
924
    // top LI
925
    var top = $(previousAll[previousAll.length - 1]);
15042 anikendra 926
 
18220 naman 927
    // immediately previous LI
928
    var previous = $(previousAll[0]);
15042 anikendra 929
 
18220 naman 930
    // how far up do we need to move the clicked LI?
931
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
15042 anikendra 932
 
18220 naman 933
    // how far down do we need to move the previous siblings?
934
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
15042 anikendra 935
 
18220 naman 936
    // let's move stuff
937
    clicked.css('position', 'relative');
938
    previousAll.css('position', 'relative');
939
    clicked.animate({'top': -moveUp});
940
    previousAll.animate({'top': moveDown}, {complete: function() {
941
      // rearrange the DOM and restore positioning when we're done moving
942
      clicked.parent().prepend(clicked);
943
      clicked.css({'position': 'static', 'top': 0});
944
      previousAll.css({'position': 'static', 'top': 0}); 
945
    }});
946
    }
15042 anikendra 947
})
17691 naman 948
$(document).on('click','.filtersubcategory',function(){
18220 naman 949
    var clicked = $(this).parent().parent();
950
    // all the LIs above the clicked one
951
    var previousAll = clicked.prevAll();
17691 naman 952
 
18220 naman 953
    // only proceed if it's not already on top (no previous siblings)
954
    if(previousAll.length > 0) {
955
    // top LI
956
    var top = $(previousAll[previousAll.length - 1]);
17691 naman 957
 
18220 naman 958
    // immediately previous LI
959
    var previous = $(previousAll[0]);
17691 naman 960
 
18220 naman 961
    // how far up do we need to move the clicked LI?
962
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
17691 naman 963
 
18220 naman 964
    // how far down do we need to move the previous siblings?
965
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
17691 naman 966
 
18220 naman 967
    // let's move stuff
968
    clicked.css('position', 'relative');
969
    previousAll.css('position', 'relative');
970
    clicked.animate({'top': -moveUp});
971
    previousAll.animate({'top': moveDown}, {complete: function() {
972
      // rearrange the DOM and restore positioning when we're done moving
973
      clicked.parent().prepend(clicked);
974
      clicked.css({'position': 'static', 'top': 0});
975
      previousAll.css({'position': 'static', 'top': 0}); 
976
    }});
977
    }
17691 naman 978
})
15042 anikendra 979
$(document).on('click','.clearfilters',function(){
18220 naman 980
    setCookie('brandschosen', '', -1, true);
981
    setCookie('subcategorieschosen','',-1, true);
982
    ga('send', 'event', 'filter', 'brand', 'clearfilters');
983
    ga('send', 'event', 'filter', 'subcategory', 'clearfilters');
984
    pma.send('filters','brands','clearfilters',me);
985
    pma.send('filters','subcategory','clearfilters',me);
986
    var postdata = {'user_id':me,'type':'clear'};
987
    $('#loadingModal').modal('show');
988
    $.post("/user_filters/add", postdata, function( data ) {        
989
        // document.location.reload();
990
        window.location.replace(window.location.href.split('?')[0]);
991
    }); 
15042 anikendra 992
});
993
function selectChosenBrands(){
18220 naman 994
    var brandschosen = decodeURIComponent(getCookie('brandschosen',true));
995
    var subcategorieschosen = decodeURIComponent(getCookie('subcategorieschosen',true));
996
    if(brandschosen && brandschosen.length>0){
997
        var brands = brandschosen.split(',');
998
        for(var i in brands){
999
            $('.brand').filter(function() { 
1000
                return $(this).data("brandid") == brands[i];
1001
            }).removeClass('hidden').find('.filterbrand',0).trigger( "click" );
1002
        }
1003
    }
1004
    if(subcategorieschosen && subcategorieschosen.length>0){
1005
        var subcategories = subcategorieschosen.split(',');
1006
        for(var i in subcategories){
1007
            $('.subcategory').filter(function() { 
1008
                return $(this).data("brandid") == subcategories[i];
1009
            }).removeClass('hidden').find('.filtersubcategory',0).trigger( "click" );
1010
        }
1011
    }
15065 anikendra 1012
}
18190 amit.gupta 1013
 
1014
function clearFilters(){
1015
	setCookie('brandschosen', '', -1, true);
1016
	setCookie('subcategorieschosen','',-1, true);
1017
}
15585 anikendra 1018
function showPosition(position) {
15586 anikendra 1019
    setCookie('latitude',position.coords.latitude,1,true); 
18220 naman 1020
    setCookie('longitude',position.coords.longitude,1,true);    
15585 anikendra 1021
}
15065 anikendra 1022
$(function () {
18115 amit.gupta 1023
	$("#popovertrigger5").popover('hide').remove();
18033 amit.gupta 1024
	$('.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 1025
	setPopOver("popovertrigger5", ".plusqtybutton", 'click', 3000);
18023 amit.gupta 1026
	callBackFunction = function(){
1027
		return document.location.pathname=="/category/6";		
1028
	};
18191 amit.gupta 1029
	setPopOver("popovertrigger4", callBackFunction,undefined,3000);
18115 amit.gupta 1030
	//$('[data-toggle="popover"]#'+id).popover('show');
18023 amit.gupta 1031
	if (navigator.geolocation) {
1032
        navigator.geolocation.getCurrentPosition(showPosition);
1033
    } 
1034
});
1035
 
18176 amit.gupta 1036
function setPopOver(poid, callBack1, eventString, fadeAfter){
15310 anikendra 1037
	var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 1038
	var cookieval = getCookie(cname,1);
18023 amit.gupta 1039
	if(typeof callBack1=="function"){
1040
		if (callBack1()){
1041
			var cname = 'popover-count-'+me+'-'+poid;
1042
			var cookieval = getCookie(cname,1);
1043
			$('#' + poid).popover('hide');
1044
			if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1045
				incrementPopupCount(poid,0,'popover-count-');
1046
			} else if(cookieval > 0) {
1047
				incrementPopupCount(poid, cookieval, 'popover-count-');
1048
			}
1049
			setLastShown(poid,'popover-lastshown-');
15310 anikendra 1050
		}
18023 amit.gupta 1051
	} else {
1052
		$('div.content').on(eventString, callBack1, function(){
1053
			var cname = 'popover-count-'+me+'-'+poid;
1054
			var cookieval = getCookie(cname,1);
1055
			$('#' + poid).popover('hide');
1056
			if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1057
				incrementPopupCount(poid,0,'popover-count-');
1058
			} else if(cookieval > 0) {
1059
				incrementPopupCount(poid, cookieval, 'popover-count-');
1060
			}
1061
			setLastShown(poid,'popover-lastshown-');
1062
		}); 
18008 amit.gupta 1063
	}
18176 amit.gupta 1064
 
1065
	if(typeof fadeAfter!="undefined"){
18181 amit.gupta 1066
		var s = setInterval(function(){
1067
			if($('#' + poid +':in-viewport').length>0) {
1068
				setTimeout(function(){
1069
					$('#' + poid).popover('hide');
1070
				}, fadeAfter);
1071
				clearInterval(s);
1072
			}
1073
		}, 2000);
18176 amit.gupta 1074
	}
15310 anikendra 1075
 
15077 anikendra 1076
	var cname = 'popover-lastshown-'+me+'-'+poid;
15721 anikendra 1077
	var lastshown = getCookie(cname,1);
15310 anikendra 1078
	if(cookieval=='' || cookieval == 'NaN' || !cookieval){				
15077 anikendra 1079
		showpopover(poid);
15521 anikendra 1080
	} 
1081
	//Donot show popover anymore as long as we don't find a suitable solution
15721 anikendra 1082
	else{
15077 anikendra 1083
		var d = new Date();
1084
		var t = d.getTime();
15085 anikendra 1085
		if(t-lastshown>18*3600*1000){
15310 anikendra 1086
			if(cookieval>=2){
15077 anikendra 1087
				return false;
1088
			}else{
15310 anikendra 1089
				showpopover(poid);				
15077 anikendra 1090
			}
1091
		}
15721 anikendra 1092
	}
15583 anikendra 1093
	ga('send', 'event', 'popover', me, cookieval);
18023 amit.gupta 1094
}
16656 anikendra 1095
$('.getapp').on('click',function(){
18220 naman 1096
    /*var that = $(this);
1097
    var req = $.ajax({
1098
        url: 'http://104.200.25.40:8057/appAffiliates/generateRedirectUrl/'+me+'/'+$(that).data('id'),
1099
        // Tell jQuery we're expecting JSONP
1100
        dataType: "jsonp",
1101
        // Tell YQL what we want and that we want JSON          
1102
        method: 'get',
1103
        // timeout: 30000,
1104
        // Work with the response
1105
        success: function( response ) {
1106
            console.log(response);
1107
        }
1108
    });*/
1109
    $('#loadingModal').modal('show');
1110
    document.location = '/abouts/apphint';
16656 anikendra 1111
});
15077 anikendra 1112
function showpopover(id){
18220 naman 1113
    try {
1114
        $('[data-toggle="popover"]#'+id).popover({html:true,viewport:{container:'body'}, trigger:'manual'});
1115
        $('[data-toggle="popover"]#'+id).popover('show');       
1116
    }catch(err){
1117
        //
1118
    }
15085 anikendra 1119
}
1120
$(document).on('click','.nodeals',function(){
18220 naman 1121
    document.location = $(this).data('href');
16018 anikendra 1122
});
1123
$(document).on('click','.selectbrand',function(e){
18220 naman 1124
    e.preventDefault();
1125
    var brands = $(this).data('id');
1126
    var brandname = $(this).html();
1127
    //console.log(brandname);
17703 naman 1128
 
18220 naman 1129
    setCookie('brandschosen', brands, 1, true);
1130
    var url = $(this).data('href');
1131
    ga('send', 'event', 'selectbrand', 'brand', brandname);
1132
    properties = {};
1133
    properties['brand'] = brandname;
1134
    pma.send('filters','brands','selectbrand',me,properties);
1135
    var postdata = {'user_id':me,'type':'brand','filters':brandname};
1136
    $.post( "/user_filters/add", postdata, function( data ) {
1137
        $('#loadingModal').modal('hide');
1138
        $(this).addClass('activebrand');
1139
        document.location = url+'&brands='+brands;
1140
    });
16018 anikendra 1141
});
17703 naman 1142
 
1143
$(document).on('click','.selectsubcat',function(e){
18220 naman 1144
    e.preventDefault();
1145
    $('.clearfilters').click();
1146
    var brands = $(this).data('id');
1147
    var brandname = $(this).html();
1148
    //console.log(brandname);
1149
 
1150
    setCookie('subcategorieschosen', brands, 1, true);
1151
    var url = $(this).data('href');
1152
    // alert(url);
1153
    // ga('send', 'event', 'subcategorieschosen', 'brand', brandname);
1154
    document.location = url;
1155
    // properties = {};
1156
    // properties['brand'] = brandname;
1157
    // pma.send('filters','brands','selectbrand',me,properties);
1158
    // // var postdata = {'user_id':me,'type':'brand','filters':brandname};
1159
    // $.post( "/user_filters/add", postdata, function( data ) {
1160
    //  $('#loadingModal').modal('hide');
1161
    //  $(this).addClass('activebrand');
1162
 //         document.location = url+'&brands='+brands;
1163
    // });
17703 naman 1164
});
1165
 
16495 anikendra 1166
$(document).on('click','.shownexttip',function(e){
18220 naman 1167
    $(this).addClass('hidden').remove();
1168
    $('#firsttip').addClass('hidden').remove();
1169
    $('#secondtip').removeClass('hidden');
1170
    $('.gotit').removeClass('hidden');
16495 anikendra 1171
});
15128 anikendra 1172
var Base64 = {
1173
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
1174
    encode: function(input) {
1175
        var output = "";
1176
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
1177
        var i = 0;
1178
        input = Base64._utf8_encode(input);
1179
        while (i < input.length) {
1180
            chr1 = input.charCodeAt(i++);
1181
            chr2 = input.charCodeAt(i++);
1182
            chr3 = input.charCodeAt(i++);
1183
 
1184
            enc1 = chr1 >> 2;
1185
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
1186
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
1187
            enc4 = chr3 & 63;
1188
            if (isNaN(chr2)) {
1189
                enc3 = enc4 = 64;
1190
            } else if (isNaN(chr3)) {
1191
                enc4 = 64;
1192
            }
1193
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
1194
        }
1195
        return output;
1196
    },
1197
 
1198
 
1199
    decode: function(input) {
1200
        var output = "";
1201
        var chr1, chr2, chr3;
1202
        var enc1, enc2, enc3, enc4;
1203
        var i = 0;
1204
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
1205
        while (i < input.length) {
1206
            enc1 = this._keyStr.indexOf(input.charAt(i++));
1207
            enc2 = this._keyStr.indexOf(input.charAt(i++));
1208
            enc3 = this._keyStr.indexOf(input.charAt(i++));
1209
            enc4 = this._keyStr.indexOf(input.charAt(i++));
1210
            chr1 = (enc1 << 2) | (enc2 >> 4);
1211
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
1212
            chr3 = ((enc3 & 3) << 6) | enc4;
1213
            output = output + String.fromCharCode(chr1);
1214
            if (enc3 != 64) {
1215
                output = output + String.fromCharCode(chr2);
1216
            }
1217
            if (enc4 != 64) {
1218
                output = output + String.fromCharCode(chr3);
1219
            }
1220
        }
1221
        output = Base64._utf8_decode(output);
1222
        return output;
1223
    },
1224
 
1225
    _utf8_encode: function(string) {
1226
        string = string.replace(/\r\n/g, "\n");
1227
        var utftext = "";
1228
        for (var n = 0; n < string.length; n++) {
1229
            var c = string.charCodeAt(n);
1230
            if (c < 128) {
1231
                utftext += String.fromCharCode(c);
1232
            }
1233
            else if ((c > 127) && (c < 2048)) {
1234
                utftext += String.fromCharCode((c >> 6) | 192);
1235
                utftext += String.fromCharCode((c & 63) | 128);
1236
            }
1237
            else {
1238
                utftext += String.fromCharCode((c >> 12) | 224);
1239
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
1240
                utftext += String.fromCharCode((c & 63) | 128);
1241
            }
1242
        }
1243
        return utftext;
1244
    },
1245
 
1246
    _utf8_decode: function(utftext) {
1247
        var string = "";
1248
        var i = 0;
1249
        var c = c1 = c2 = 0;
1250
        while (i < utftext.length) {
1251
            c = utftext.charCodeAt(i);
1252
            if (c < 128) {
1253
                string += String.fromCharCode(c);
1254
                i++;
1255
            }
1256
            else if ((c > 191) && (c < 224)) {
1257
                c2 = utftext.charCodeAt(i + 1);
1258
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
1259
                i += 2;
1260
            }
1261
            else {
1262
                c2 = utftext.charCodeAt(i + 1);
1263
                c3 = utftext.charCodeAt(i + 2);
1264
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
1265
                i += 3;
1266
            }
1267
        }
1268
        return string;
1269
    }
15550 anikendra 1270
}
1271
 
1272
 
1273
var pma = new function() {
15584 anikendra 1274
    this.apiurl = "http://45.33.50.227:8081/";
15550 anikendra 1275
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};
1276
 
1277
    this.send = function (category,action,label,user_id,properties) {
18220 naman 1278
        if(!properties){
1279
            properties = {};
1280
        }
1281
        properties.location = window.location.href;
1282
        // properties.appCodeName = navigator.appCodeName;
1283
        // properties.appName = navigator.appName;
1284
        // properties.appVersion = navigator.appVersion;
1285
        properties.cookieEnabled = String(navigator.cookieEnabled);
1286
        properties.platform = navigator.platform;
1287
        properties.userAgent = navigator.userAgent;
1288
        properties.ip = ip;
1289
        if (navigator.geolocation) {
1290
            if(getCookie('latitude',true)){
1291
                properties.latitude = getCookie('latitude');
1292
            }           
1293
            if(getCookie('longitude',true)){
1294
                properties.longitude = getCookie('longitude');
1295
            }
1296
        }
1297
        properties.screenHeight = String(screen.height);
1298
        properties.screenWidth = String(screen.width);
1299
        // console.log(properties);
1300
        $.ajax({
1301
            url: this.apiurl + this.endpoints.track,
1302
            data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
1303
            // Tell jQuery we're expecting JSONP
1304
            dataType: "json",
1305
            // Tell YQL what we want and that we want JSON          
1306
            method: 'post',
1307
            // Work with the response
1308
            success: function( response ) {
1309
                //Well, well, well :)
1310
            }
1311
        });       
15550 anikendra 1312
    };
1313
 
1314
    this.formDataToObject = function(formdata){
18220 naman 1315
        var properties = {};
1316
        var keys = [];
1317
        var formdata = JSON.parse(JSON.stringify(formdata));
1318
        for (var i in formdata) {
1319
            var key = formdata[i].name;
1320
            if(index = keys.indexOf(key)==-1){
1321
                properties[key] = formdata[i].value;
1322
            }else{
1323
                properties[key+'_'+i] = formdata[i].value;
1324
            }
1325
            keys.push(key);
1326
        };
1327
        return properties;
1328
    }
16704 anikendra 1329
}
1330
//App page
1331
$.fn.stars = function() {
1332
    return $(this).each(function() {
1333
        // Get the value
1334
        var val = parseFloat($(this).html());
1335
        // Make sure that the value is in 0 - 5 range, multiply to get width
1336
        val = Math.round(val * 2) / 2;
1337
        var size = Math.max(0, (Math.min(5, val))) * 16;
1338
        // Create stars holder
1339
        var $span = $('<span />').width(size);
1340
        // Replace the numerical value with stars
1341
        $(this).html($span);
1342
    });
1343
}
1344
$(function() {
18220 naman 1345
    $('span.stars').stars();    
18023 amit.gupta 1346
});
1347
 
1348
function sendCartChangeEvent(){
18220 naman 1349
    var cart_details_old = localStorage.getItem('cart_details_old');
1350
    var cart_details = localStorage.getItem('cart_details');
1351
    if (cart_details_old == cart_details){
1352
        return;
1353
    } else if(cart_details!=null){
1354
        JSON.parse(cart_details);
1355
 
1356
    }
18023 amit.gupta 1357
}
1358
 
1359
//setInterval(30000, )