Subversion Repositories SmartDukaan

Rev

Rev 16308 | Rev 16395 | 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) {
4
	if(value==0){
5
		return '';
6
	}
7
	if(type==2){
14789 anikendra 8
		return ' +'+value+' Cashback';
14773 anikendra 9
	}else if(type==1){
14789 anikendra 10
		return ' +'+value+'% Cashback';
14773 anikendra 11
	}else{
12
		return '';
13
	}
15926 anikendra 14
};
15
function showShopcluesPopup(url){
16
	$('#shopcluesUrl').prop('href',url);
17
	$('#shopcluesModal').modal('show');
18
	return;
19
};
13984 anikendra 20
$(function(){	
21
	if($('.scroll > .card').length>0) {
14969 anikendra 22
		setTimeout(function(){ document.location.reload(); }, 1000*15*60);
16368 anikendra 23
		if(typeof noscrolling === undefined) {
24
			$('.scroll').jscroll({
25
				loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
26
			    autoTriggerUntil: 3,
27
			    padding: 20,
28
			});
29
		}
13820 anikendra 30
	}
13901 anikendra 31
	if($('.storeminprice').length>0) {
32
		var globalminprice = 9999999;
14773 anikendra 33
		var globalminsku;
34
		var globalmincashback = '';		
16124 anikendra 35
		var globalminoffer = '';		
14345 anikendra 36
		var calls = [];
13901 anikendra 37
		$('.storeminprice').each(function(){
14345 anikendra 38
			var temp = {'sort':$(this).data('searchorder'),'val':$(this)};
39
			calls.push(temp);
40
		});
41
		calls = sortByKey(calls,'sort');		
42
		for(var i in calls){
43
			fetchLivePrice(calls[i]['val'])
14969 anikendra 44
		}				
14345 anikendra 45
	};
46
	function sortByKey(array, key) {
47
	    return array.sort(function(a, b) {
48
	        var x = a[key]; var y = b[key];
49
	        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
50
	    });
15926 anikendra 51
	};		
15923 anikendra 52
	function getCouponText(coupon){
53
		return "<span class='red'>"+coupon+"</span>";
15926 anikendra 54
	};
14432 anikendra 55
	function fetchLivePrice(obj){		
15607 anikendra 56
		ga('send', 'event', 'liveprice', 'fetch',$('#bestpriceproductname').html());
15550 anikendra 57
		var properties = {};
58
		properties.bundle_id = String($(obj).data('bundle_id'));
15607 anikendra 59
		properties.product_name = String($('#bestpriceproductname').html());
15585 anikendra 60
		pma.send('products','livesprice','fetch',me,properties);
14432 anikendra 61
		var that = obj;	
62
		var inStock = false;		
14386 anikendra 63
		var req = $.ajax({
14345 anikendra 64
			url: '/store_products/getliveprice/'+$(that).data('bundle_id')+'/'+$(that).data('id'),
65
			// Tell jQuery we're expecting JSONP
66
			dataType: "json",
67
			// Tell YQL what we want and that we want JSON			
68
			method: 'get',
14430 anikendra 69
			// timeout: 30000,
14345 anikendra 70
			// Work with the response
71
			success: function( response ) {
72
				if(response.success){
73
					var i = 0;	
16219 anikendra 74
					var minpriceindex = 0;									
14797 anikendra 75
					if(response.products[i].in_stock == 1) {
16219 anikendra 76
						inStock = true;
14797 anikendra 77
						var minprice = Math.round(response.products[i]['available_price']);
78
						var minpriceurl = response.products[i]['marketPlaceUrl'];
79
					}
14345 anikendra 80
					if(response.products.length>0){
81
						//More than one products in store
82
						var variants = [];
16124 anikendra 83
						var j = 0;
84
						for(var i in response.products){								
14685 anikendra 85
							if(response.products[i].in_stock == 1){
15923 anikendra 86
								inStock = true;								
14685 anikendra 87
								if(response.products[i].available_price && response.products[i].available_price < globalminprice) {
88
									globalminprice = Math.round(response.products[i].available_price);
89
									globalminsku = response.products[i]._id;
90
									var globalminsource = response.products[i].source_id;
14773 anikendra 91
									var globalminurl = response.products[i].marketPlaceUrl;
16124 anikendra 92
									var globalminoffer = response.products[i].offer;
14773 anikendra 93
									var globalmincashback = getcashbackstring(response.products[i].cash_back_type,response.products[i].cash_back);
14685 anikendra 94
								}
16219 anikendra 95
								if(typeof minprice == 'undefined' || response.products[i].available_price < minprice) {
14685 anikendra 96
									minprice = Math.round(response.products[i].available_price);
16219 anikendra 97
									minpriceindex = j;
16124 anikendra 98
								}								
16234 anikendra 99
								if(response.products[i].tagline && response.products[i].tagline.length>0 && $('#productoneliner').html().length==0) { 
16124 anikendra 100
									$('#productoneliner').html(response.products[i].tagline).removeClass('hidden').show();									
101
								}								
102
								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});
103
							}					
16219 anikendra 104
							j++;
13901 anikendra 105
						}
16219 anikendra 106
						if(variants.length>1){
16124 anikendra 107
							variants.splice(minpriceindex,1);							
14713 anikendra 108
							var variantslink = $('<span class="variants"> '+(variants.length+1)+' Options</span>');
109
							$(that).parent().parent().find('.pull-left',0).append(variantslink);							
14799 anikendra 110
							$(variantslink).data('variants',variants).data('minprice',minprice);
13948 anikendra 111
						}
14345 anikendra 112
					}
113
					if(inStock){
14797 anikendra 114
						$(that).html(minprice).siblings('.cashbackamount').html(getcashbackstring(response.products[minpriceindex].cash_back_type,response.products[minpriceindex].cash_back)).parent().addClass('viewproduct');
14689 anikendra 115
						$('#name-'+$(that).data('id')).html(response.products[minpriceindex]['source_product_name']);
16039 anikendra 116
						if(response.products[minpriceindex]['coupon'] && response.products[minpriceindex]['coupon'].length>0){
15923 anikendra 117
							$('#couponcode-'+$(that).data('id')).show().find('span.red',0).html(getCouponText(response.products[minpriceindex]['coupon']));
16013 anikendra 118
						}			
119
						if(!response.products[minpriceindex]['codAvailable']){
16124 anikendra 120
							$('#codstatus-'+$(that).data('id')).show().removeClass('codstatus');
15923 anikendra 121
						}
16124 anikendra 122
						if(response.products[minpriceindex]['offer'].length>0){
123
							$('#itemoffer-'+$(that).data('id')).show().html(response.products[minpriceindex]['offer']);
124
						}
14685 anikendra 125
						$('#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 126
						if(globalminprice != 9999999) {
16124 anikendra 127
							$('#bestprice').html(globalminprice).siblings('.cashbackamount').html(globalmincashback).siblings('.productoffer').html(globalminoffer);
14685 anikendra 128
							$('#beststorelink').data('id',globalminsku).data('source',globalminsource).data('price',globalminprice).data('url',globalminurl).removeClass('hidden');
14345 anikendra 129
							$('#bestpricecontainer').removeClass('hidden');
14432 anikendra 130
						} 
14386 anikendra 131
					} else{
15607 anikendra 132
						ga('send', 'event', 'liveprice', 'outofstock', $('#bestpriceproductname').html());
15550 anikendra 133
						var properties = {};
134
						properties.sku = String(response.products[0]._id);
15607 anikendra 135
						properties.source = String(response.products[0].source_id);
136
						properties.product_name = String($('#bestpriceproductname').html());
15767 anikendra 137
						pma.send('products','liveprice','outofstock',me,properties);
14432 anikendra 138
						outOfStockCount++;
14345 anikendra 139
						$(that).parent().parent().remove();	
13901 anikendra 140
					}
14345 anikendra 141
					if(!response.products[0].available_price){
14434 anikendra 142
						// outOfStockCount++;
143
						// $(that).parent().parent().remove();	
144
						var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
145
						$(that).html(btn);
15585 anikendra 146
						// ga('send', 'event', 'liveprice', 'failed', response.products[0]._id);
147
						// console.log('failed for '+ response);
148
						// properties = {};
149
						// properties.sku = String(response.products[0]._id); 
150
						// pma.send('products','liveprice','failed',me,properties);
14969 anikendra 151
					}					
14386 anikendra 152
				} else{
14434 anikendra 153
					// outOfStockCount++;
154
					// $(that).parent().parent().remove();
155
					var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
156
					$(that).html(btn);
14969 anikendra 157
					ga('send', 'event', 'liveprice', 'failure', response.products[0]._id);
15550 anikendra 158
					properties = {};
159
					properties.sku = String(response.products[0]._id); 
160
					pma.send('products','liveprice','failure',me,properties);
13901 anikendra 161
				}
14432 anikendra 162
				checkForOutStocks(outOfStockCount);
14345 anikendra 163
			},
15310 anikendra 164
			error: function(request, status, err) {            	
165
        		var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
166
				$(that).html(btn);
167
				try{
168
					if(response){
169
						ga('send', 'event', 'liveprice', 'error', response.products[0]._id);
15550 anikendra 170
						var properties = {};
171
						properties.sku = String(response.products[0]._id);
172
						pma.send('products','livescore','error',me,properties);
15310 anikendra 173
					}						
174
				} catch(e){}
14345 anikendra 175
			}
13901 anikendra 176
		});
14386 anikendra 177
		livePriceCalls.push(req);
14357 anikendra 178
	};
14432 anikendra 179
	function checkForOutStocks(count){
180
		if(count>=livePriceCalls.length){
181
			$('#bestpricecontainer').html('<h4>Out of stock</h4>').removeClass('hidden');	
14969 anikendra 182
		}		
14432 anikendra 183
	};
14687 anikendra 184
	$(document).on('click','.showless',function(){
185
		$(this).addClass('hidden').siblings('.varnts').hide();
186
		$(this).parent().find('.variants',0).removeClass('hidden').addClass('justshow');
187
	});
13901 anikendra 188
	$(document).on('click','.variants',function(){
189
		$('.storeproductinfo').empty();
16219 anikendra 190
		var variants = $(this).data('variants');		
14799 anikendra 191
		var minprice = $(this).data('minprice');
14026 anikendra 192
		$('#variantscount').html(variants.length);
13901 anikendra 193
		for(var i in variants){
14849 anikendra 194
			if(minprice == variants[i].available_price) {
16013 anikendra 195
				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="'+variants[i].available_price+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span class="storeminprice">'+variants[i].available_price+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span>';			
14849 anikendra 196
			} else {
16013 anikendra 197
				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="'+variants[i].available_price+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span>'+variants[i].available_price+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span>';
16124 anikendra 198
			}
199
			if(variants[i].offer.length>0){
200
				html += '<p class="text-small">'+variants[i].offer+'</p>';
16013 anikendra 201
			}	
16039 anikendra 202
			if(variants[i].coupon && variants[i].coupon.length>0){
16013 anikendra 203
				html += '<p class="text-small">Use Coupon <span class="red">'+variants[i].coupon+'</span></p>';
204
			}
205
			if(!variants[i].codAvailable){
16124 anikendra 206
				html += '<p class="text-small">COD not available</p>';
207
			}			
16013 anikendra 208
			html += '</div></div>';
209
			var row = $(html);			
14687 anikendra 210
			$(this).parent().parent().append(row);			
13901 anikendra 211
		}
14713 anikendra 212
		var showless = $('<div class="showless col-xs-9 text-right">Less <i class="glyphicon glyphicon-chevron-up"></i></span>');
14687 anikendra 213
		$(this).parent().parent().append(showless);
214
		$(this).addClass('hidden');
13901 anikendra 215
	});
13695 anikendra 216
	$('.categorytab').on('click','.categorytabcontrol.active',function(){
217
		$(this).toggleClass('active');
218
		$('#preferences-'+$(this).data('id')).addClass('hidden');
219
		$(this).parent().parent().children().find('.savecategorypreferences',0).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
220
	});
13759 anikendra 221
	$('.categorytab').on('click','.categorytabcontrol:not(.active)',function(){
222
		$(this).parent().parent().find('.btn',0).click();
223
	});
13695 anikendra 224
	$('.categorytab').on('click','.editcategorypreferences',function(e){
225
		var that = $(this);
226
		$(that).removeClass('editcategorypreferences').addClass('savecategorypreferences').html('Done').addClass('btn-success');
227
		$('#togglepreferences-'+$(that).data('id')).toggleClass('active');
228
		$('#preferences-'+$(that).data('id')).removeClass('hidden');
229
		$('.brandselector').each(function(){
230
			if($(this).data('catid')==$(that).data('id')){
231
				$(this).addClass('active');
232
			}
16066 anikendra 233
		});		
13695 anikendra 234
	});
235
	$('.categorytab').on('click','.savecategorypreferences',function(e){
236
		var that = $(this);
237
		$(that).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
238
		$('#togglepreferences-'+$(that).data('id')).toggleClass('active');
239
		$.ajax({
240
			url: $('#categorypreference-'+$(that).data('id')).attr('action'),
241
			data: $('#categorypreference-'+$(that).data('id')).serialize(),
242
			// Tell jQuery we're expecting JSONP
243
			dataType: "json",
244
			// Tell YQL what we want and that we want JSON			
245
			method: 'post',
246
			// Work with the response
247
			success: function( response ) {
248
				if(response.success){
249
					$('#preferences-'+$(that).data('id')).addClass('hidden');
250
				}
251
			}
252
		});
16066 anikendra 253
		active = getCookie('shopcluesActive',1);
16068 anikendra 254
		if(active && active == 'true'){
16066 anikendra 255
			$('.firsttimemsg').removeClass('hidden').show();
256
		}		
13695 anikendra 257
		ga('send', 'event', 'preferences', 'update', me);
15550 anikendra 258
		properties = pma.formDataToObject($('#categorypreference-'+$(this).data('id')).serializeArray());
259
		pma.send('preferences', 'update', 'set', me, properties);
13695 anikendra 260
	});
15767 anikendra 261
	$(document).on('click','.viewproduct',function(e){		
14386 anikendra 262
		if(typeof livePriceCalls != undefined) {
263
	    	for(var i in livePriceCalls){
264
	    		livePriceCalls[i].abort();
265
	    	}
266
	    }
13686 anikendra 267
		$('#loadingModal').modal();
14952 anikendra 268
		if($(this).data('source')==2){
269
			//in case of flipkart, close popup after 5 seconds
15311 anikendra 270
			setTimeout(function(){ $('#loadingModal').modal('hide');$('#customMessageModal').modal('hide'); }, 1000*10);			
14952 anikendra 271
		}
15159 anikendra 272
		var store = $(this).data('source');
14345 anikendra 273
		var url = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
13579 anikendra 274
		$.ajax({
275
			url: url,
276
			// The name of the callback parameter, as specified by the YQL service
277
			jsonp: "callback",
278
			// Tell jQuery we're expecting JSONP
279
			dataType: "jsonp",
280
			// Tell YQL what we want and that we want JSON
281
			data: {
282
				format: "json"
283
			},
284
			// Work with the response
285
			success: function( response ) {
286
				if(response.success && response.type=='redirect'){
15920 anikendra 287
					if(store == 5) {
288
						//check if shopclues is active or not
289
						active = getCookie('shopcluesActive',1);
15925 anikendra 290
						if(active && active == 'true'){
16308 anikendra 291
							response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
15920 anikendra 292
							document.location = response.url;	
293
							pma.send('apk','shopclues','active',me,null);
294
						}else{
295
							pma.send('apk','shopclues','inactive',me,null);
296
							$('#loadingModal').modal('hide');
297
							showShopcluesPopup(response.url);
298
							// return;
299
						}
16271 anikendra 300
				  	} 
301
				  	/*else if(store == 1 ) {
302
					 	url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
303
					 	document.location = url;
304
					} */
305
					else if (store == 3 || store == 2) {
15310 anikendra 306
						if (store == 2){
307
							response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
308
						}
15188 anikendra 309
						if(response.showmessage == 1) {
310
							$('#loadingModal').modal('hide');
311
							$('#customMessage').html(response.message);
15310 anikendra 312
							$('#customMessageModal').modal('show');							
15311 anikendra 313
							setTimeout(function(){ document.location = response.url;}, 1000*3);			
15310 anikendra 314
						} else{
15206 anikendra 315
							document.location = response.url;	
15188 anikendra 316
						}
15203 anikendra 317
					} else {
15128 anikendra 318
						document.location = response.url;
319
					}										
13579 anikendra 320
				}
15310 anikendra 321
			},
322
			error: function() {
323
				document.location = url;
13579 anikendra 324
			}
325
		});
14432 anikendra 326
		ga('send', 'event', 'product', 'click', $(this).data('url'));
15550 anikendra 327
		var properties = {};
328
		properties.sku = String($(this).data('id'));
329
		properties.source = String($(this).data('source'));
330
		properties.url = encodeURIComponent($(this).data('url'));
331
		properties.price = String($(this).data('price'));
332
		pma.send('products','url','click',me,properties);
13583 anikendra 333
	});
13719 anikendra 334
	$('.jscroll-inner').on('click','.likedeal',function(e){	
13583 anikendra 335
		var that = $(this);
13682 anikendra 336
		if($(that).hasClass('active')){
13583 anikendra 337
			//User has already liked it,so remove like
338
			var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";	
339
		}else{
340
			var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
341
		}
342
		$.ajax({
343
			url: url,
344
			// The name of the callback parameter, as specified by the YQL service
345
			jsonp: "callback",
346
			// Tell jQuery we're expecting JSONP
347
			dataType: "jsonp",
348
			// Tell YQL what we want and that we want JSON
349
			data: {
350
				format: "json"
351
			},
352
			// Work with the response
353
			success: function( response ) {
354
				if(response.success){
13672 anikendra 355
					$(that).toggleClass('active');
356
					$(that).parent().find('li.dislikedeal',0).removeClass('active');
13583 anikendra 357
				}
358
			}
359
		});
13686 anikendra 360
		ga('send', 'event', 'product', 'like', $(this).data('id'));
15550 anikendra 361
		var properties = {};
362
		properties.sku = String($(this).data('id'));
363
		pma.send('products','favourites','like',me,properties);
13583 anikendra 364
	});
13688 anikendra 365
	$('#myModal').on('click','#unlikebtn',function(e){
13682 anikendra 366
		e.preventDefault();
367
		var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
368
		$.ajax({
369
			url: url,
370
			// The name of the callback parameter, as specified by the YQL service
371
			jsonp: "callback",
372
			// Tell jQuery we're expecting JSONP
373
			dataType: "jsonp",
374
			// Tell YQL what we want and that we want JSON
375
			data: {
376
				format: "json"
377
			},
378
			// Work with the response
379
			success: function( response ) {
380
			}
381
		});
382
		$('#myModal').modal('hide');
13686 anikendra 383
		ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
15550 anikendra 384
		pma.send('brands','hide',$('#myModal').find('#productToHide',0).val(),me);
13682 anikendra 385
	})
13719 anikendra 386
	$('.jscroll-inner').on('click','.dislikedeal',function(e){			
13583 anikendra 387
		var that = $(this);
13682 anikendra 388
		if($(that).hasClass('active')){
13583 anikendra 389
			//User has already liked it,so remove like
390
			var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";	
391
		}else{
13682 anikendra 392
			$('#myModal').find('#productToHide',0).val($(this).data('id'));
13583 anikendra 393
			var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
394
		}
395
		$.ajax({
396
			url: url,
397
			// The name of the callback parameter, as specified by the YQL service
398
			jsonp: "callback",
399
			// Tell jQuery we're expecting JSONP
400
			dataType: "jsonp",
401
			// Tell YQL what we want and that we want JSON
402
			data: {
403
				format: "json"
404
			},
405
			// Work with the response
406
			success: function( response ) {
407
				if(response.success){
13672 anikendra 408
					$(that).toggleClass('active');
409
					$(that).parent().find('li.likedeal',0).removeClass('active');
13583 anikendra 410
				}
411
			}
412
		});
13686 anikendra 413
		ga('send', 'event', 'product', 'dislike', $(this).data('id'));
15550 anikendra 414
		var properties = {};
415
		properties.sku = String($(this).data('id'));
416
		pma.send('products','favourites','dislike',me,properties);
13583 anikendra 417
	});
13731 anikendra 418
	$('.deletefav').on('click',function(){
419
		var that = $(this);
420
		$('#loadingModal').modal();
421
		var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');			
422
		$.ajax({
423
			url: url,
424
			// The name of the callback parameter, as specified by the YQL service
425
			jsonp: "callback",
426
			// Tell jQuery we're expecting JSONP
427
			dataType: "jsonp",
428
			// Tell YQL what we want and that we want JSON
429
			data: {
430
				format: "json"
431
			},
432
			// Work with the response
433
			success: function( response ) {
434
				$('#loadingModal').modal('hide');
435
				if(response.success){			
436
					$('#fav-'+$(that).data('id')).hide('slow');
437
				}
438
			}
439
		});
440
		ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
15550 anikendra 441
		var properties = {};
442
		properties.sku = String($(this).data('id'));
443
		pma.send('products','favourites','remove',me,properties);
13731 anikendra 444
	});
445
	$('.clearfavs').on('click',function(){
446
		var that = $(this);
447
		$('#loadingModal').modal();
14300 anikendra 448
		var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');			
13731 anikendra 449
		$.ajax({
450
			url: url,
451
			// The name of the callback parameter, as specified by the YQL service
452
			jsonp: "callback",
453
			// Tell jQuery we're expecting JSONP
454
			dataType: "jsonp",
455
			// Tell YQL what we want and that we want JSON
456
			data: {
457
				format: "json"
458
			},
459
			// Work with the response
460
			success: function( response ) {
461
				$('#loadingModal').modal('hide');
462
				if(response.success){			
463
					$('.deletefav').each(function(){
464
						$('#fav-'+$(this).data('id')).hide('slow');
465
					})					
466
				}
467
				$(that).hide();
468
			}
469
		});
470
		ga('send', 'event', 'favourites', 'removeall', me);
15550 anikendra 471
		pma.send('products','favourites','removeall',me);
13731 anikendra 472
	});
13759 anikendra 473
	$('.revealbrands').on('click',function(){
474
		$(this).parent().find('.notfeatured').toggleClass('hidden');
475
		if($(this).html()=='Others'){
476
			$(this).html('Hide');
477
		}else{
478
			$(this).html('Others');
479
		}
480
	});
14068 anikendra 481
	$(document).on('click','.creditedcashbacks',function(){
482
		if($(this).find('.glyphicon-plus',0).length>0){
483
			$(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
484
		}else{
485
			$(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
486
		}
487
		$(this).next().toggleClass('hidden');
488
	});
489
	$(document).on('click','.panel-heading',function(){
490
		if($(this).find('.glyphicon-plus',0).length>0){
491
			$(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
492
		}else{
493
			$(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
494
		}
495
	});
14135 anikendra 496
	$(document).on('click','.prefcatselect',function(){
497
		$('.prefcatselect').removeClass('active')
498
		$(this).addClass('active');
499
		$('.categorypreferences').addClass('hidden');
500
		$('#cat-'+$(this).data('id')).toggleClass('hidden');
14150 anikendra 501
	});
502
	$(document).on('click','.refresh',function(){
503
		document.location.reload();
504
	});
14215 anikendra 505
	$(document).on('click','.hasmoretext',function(){
506
		$('#fulltext').html($(this).data('fulltext'));
507
		$('#fullTextModal').modal();
508
	});
14300 anikendra 509
	$(document).on('click','.favswitch',function(){
510
		$('.favswitch').removeClass('active')
511
		$(this).addClass('active');
512
		$('.clearfavs').addClass('hidden');
513
		$('.card').addClass('hidden');
514
		$('.'+$(this).data('type')).removeClass('hidden');
515
	});
14386 anikendra 516
	$(document).on('click','.brandpreferences .brands',function(){
517
		$(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
518
	});
519
	$(document).on('click','.tryagainforliveprice',function(){		
520
		fetchLivePrice($(this).parent());
521
		$(this).parent().html('Getting Live Prices');
522
	});
14579 anikendra 523
	$(document).on('click','.alert > a',function(){		
524
		ga('send', 'event', 'notifications', 'click', $(this).html());
15550 anikendra 525
		pma.send('notifications','click',$(this).html(),me);
14579 anikendra 526
	});
527
	$(document).on('click','.banner',function(){		
528
		ga('send', 'event', 'banners', 'click', $(this).data('name'));
15550 anikendra 529
		pma.send('banners','click',$(this).data('name'),me);
14579 anikendra 530
	});
13992 anikendra 531
});
15310 anikendra 532
function setCookie(cname, cvalue, days, forceCookie) {
533
	if(typeof(Storage) !== "undefined" && !forceCookie) {
534
		localStorage.setItem(cname, cvalue);
535
	} else{
536
		var d = new Date();
537
	    d.setTime(d.getTime() + (days*24*60*60*1000));
538
	    var expires = "expires="+d.toUTCString();
539
	    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
540
	}    
14849 anikendra 541
}
542
 
15310 anikendra 543
function getCookie(cname,forceCookie) {
544
	if(typeof(Storage) !== "undefined" && !forceCookie) {
545
	    return localStorage.getItem(cname);
546
	} else {	   
547
	    var name = cname + "=";
548
	    var ca = document.cookie.split(';');
549
	    for(var i=0; i<ca.length; i++) {
550
	        var c = ca[i];
551
	        while (c.charAt(0)==' ') c = c.substring(1);
552
	        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
553
	    }
554
	    return "";
555
	}
14849 anikendra 556
}
15310 anikendra 557
 
14849 anikendra 558
function showpopup(id,count,interval){
14851 anikendra 559
	var cname = 'notif-count-'+me+'-'+id;
15797 anikendra 560
	var cookieval = getCookie(cname,1);
14851 anikendra 561
	var cname = 'notif-lastshown-'+me+'-'+id;
15797 anikendra 562
	var lastshown = getCookie(cname,1);
15310 anikendra 563
	if(!cookieval || cookieval == 'NaN' || cookieval==''){		
15077 anikendra 564
		incrementPopupCount(id,0,'notif-count-');
565
		setLastShown(id,'notif-lastshown-');
14849 anikendra 566
		return true;
567
	} else{
568
		var d = new Date();
569
		var t = d.getTime();
570
		if(t-lastshown>interval*60*1000){
571
			if(cookieval>=count){
572
				return false;
573
			}else{
15077 anikendra 574
				setLastShown(id,'notif-lastshown-');
575
				incrementPopupCount(id,cookieval,'notif-count-');
14849 anikendra 576
				return true;	
577
			}
578
		}
579
	}
580
}
15077 anikendra 581
function setLastShown(id,cookiename){
582
	var cname = cookiename+me+'-'+id;
14849 anikendra 583
	var d = new Date();
15721 anikendra 584
	setCookie(cname, d.getTime(), 365, 1);
14849 anikendra 585
}
15077 anikendra 586
function incrementPopupCount(id,currentCount,cookiename) {
587
	var cname = cookiename+me+'-'+id;
15721 anikendra 588
	setCookie(cname, parseInt(currentCount)+1, 365, 1);
14858 anikendra 589
}
590
var hidden, visibilityChange; 
591
function handleVisibilityChange() {
592
  if (document[hidden]) {
15058 anikendra 593
  	// pagetitle = document.title;
14858 anikendra 594
  } else {
15058 anikendra 595
  	// document.title = pagetitle;
14858 anikendra 596
  }
597
}
598
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
599
  hidden = "hidden";
600
  visibilityChange = "visibilitychange";
601
} else if (typeof document.mozHidden !== "undefined") {
602
  hidden = "mozHidden";
603
  visibilityChange = "mozvisibilitychange";
604
} else if (typeof document.msHidden !== "undefined") {
605
  hidden = "msHidden";
606
  visibilityChange = "msvisibilitychange";
607
} else if (typeof document.webkitHidden !== "undefined") {
608
  hidden = "webkitHidden";
609
  visibilityChange = "webkitvisibilitychange";
610
}
611
if (typeof document.addEventListener === "undefined" || 
612
  typeof document[hidden] === "undefined") {
15077 anikendra 613
  console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
14858 anikendra 614
} else {
615
  // Handle page visibility change   
616
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
617
}    
14936 anikendra 618
$('.notificationok').on('click',function(e){
14932 anikendra 619
	e.preventDefault();
14931 anikendra 620
	$('.notificationmodal').modal('hide');
15159 anikendra 621
	// setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
16133 anikendra 622
	ga('send', 'event', 'popupnotification-'+$(this).parent().data('id'), 'ok', me);
623
	var properties = {};
624
	properties.id = String($(this).parent().data('id'));
625
	pma.send('popupnotification','click','ok',me,properties);
14932 anikendra 626
	document.location = $(this).parent().prop('href');
15015 anikendra 627
});
628
$(document).on('click','.clearfilter',function(){	
629
	$('.filterbrand').each(function(){
630
		$(this).prop('checked',false);
631
	});	
15550 anikendra 632
	ga('send', 'event', 'filter', 'brand', 'reset');
633
	pma.send('filters','brands','reset',me);
15015 anikendra 634
});
635
$(document).on('click','.applyfilter',function(){	
15584 anikendra 636
	$(this).prop('disabled',true);
637
	$('#loadingModal').modal();
15015 anikendra 638
	var brands = [];
15026 anikendra 639
	var brandnames = [];
15015 anikendra 640
	$('.filterbrand').each(function(){
641
		if($(this).prop('checked')){
642
			brands.push($(this).val());
15026 anikendra 643
			brandnames.push($(this).parent().siblings('.brandname').html());
15015 anikendra 644
		}		
645
	});
646
	if(brands.length==0){
15721 anikendra 647
		$('#loadingModal').modal('hide');
15015 anikendra 648
		$('#message').html('Please choose a few brands first').removeClass('hidden');
649
		setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
15722 anikendra 650
		$(this).prop('disabled',false);
15015 anikendra 651
		return false;
652
	}else{
16240 anikendra 653
		setCookie('brandschosen', brands, 0.25, true);
15015 anikendra 654
		var url = $('#brandselecter').prop('action');
15026 anikendra 655
		ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
15550 anikendra 656
		properties = {};
657
		for(var i in brandnames){
658
			properties['brand_'+i] = brandnames[i];
659
		}
660
		pma.send('filters','brands','addfilter',me,properties);
15085 anikendra 661
		var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
662
		$.post( "/user_filters/add", postdata, function( data ) {
15584 anikendra 663
			$('#loadingModal').modal('hide');
15722 anikendra 664
			$(this).prop('disabled',false);
15584 anikendra 665
	  		document.location = url+'&brands='+brands.join('^');
15085 anikendra 666
		});		
15015 anikendra 667
	}	
668
});
669
$(document).on('click','#showallbrands',function(){	
670
	$('.hidden').removeClass('hidden');
671
	$(this).hide();
15019 anikendra 672
});
673
$(document).on('input','#brandfilter',function(){	
674
	$('.brand').addClass('hidden');
675
	$('#showallbrands').hide();
676
	var that = $(this);
677
	$('li.brand').filter(function() { 
678
	  return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
679
	}).removeClass('hidden','slow');
15042 anikendra 680
});
15077 anikendra 681
$(document).on('click','.filterbrand',function(){
682
	var clicked = $(this).parent().parent();
15042 anikendra 683
	// all the LIs above the clicked one
684
	var previousAll = clicked.prevAll();
685
 
686
	// only proceed if it's not already on top (no previous siblings)
687
	if(previousAll.length > 0) {
688
	// top LI
689
	var top = $(previousAll[previousAll.length - 1]);
690
 
691
	// immediately previous LI
692
	var previous = $(previousAll[0]);
693
 
694
	// how far up do we need to move the clicked LI?
695
	var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
696
 
697
	// how far down do we need to move the previous siblings?
698
	var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
699
 
700
	// let's move stuff
701
	clicked.css('position', 'relative');
702
	previousAll.css('position', 'relative');
703
	clicked.animate({'top': -moveUp});
704
	previousAll.animate({'top': moveDown}, {complete: function() {
705
	  // rearrange the DOM and restore positioning when we're done moving
706
	  clicked.parent().prepend(clicked);
707
	  clicked.css({'position': 'static', 'top': 0});
708
	  previousAll.css({'position': 'static', 'top': 0}); 
709
	}});
710
	}
711
})
712
$(document).on('click','.clearfilters',function(){
15310 anikendra 713
	setCookie('brandschosen', '', -1, true);
15058 anikendra 714
	ga('send', 'event', 'filter', 'brand', 'clearfilters');
15550 anikendra 715
	pma.send('filters','brands','clearfilters',me);
15085 anikendra 716
	var postdata = {'user_id':me,'type':'clear'};
16240 anikendra 717
	$('#loadingModal').modal('show');
718
	$.post("/user_filters/add", postdata, function( data ) {		
719
	  	document.location.reload();
15085 anikendra 720
	});	
15042 anikendra 721
});
722
function selectChosenBrands(){
16261 anikendra 723
	var brandschosen = decodeURIComponent(getCookie('brandschosen',true));
15042 anikendra 724
	if(brandschosen && brandschosen.length>0){
725
		var brands = brandschosen.split(',');
726
		for(var i in brands){
727
			$('.brand').filter(function() { 
728
			  	return $(this).data("brandid") == brands[i];
15077 anikendra 729
			}).removeClass('hidden').find('.filterbrand',0).trigger( "click" );
15042 anikendra 730
		}
731
	}
15065 anikendra 732
}
15585 anikendra 733
function showPosition(position) {
15586 anikendra 734
    setCookie('latitude',position.coords.latitude,1,true); 
735
    setCookie('longitude',position.coords.longitude,1,true);	
15585 anikendra 736
}
15065 anikendra 737
$(function () {
15077 anikendra 738
	var poid = 'popovertrigger';
15310 anikendra 739
	var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 740
	var cookieval = getCookie(cname,1);
15310 anikendra 741
	$('#dropdownMenu1').on('click',function(){
742
		var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 743
		var cookieval = getCookie(cname,1);
15310 anikendra 744
		$('#popovertrigger').popover('hide');
745
		if(!cookieval || cookieval == 'NaN' || cookieval == ''){
746
			incrementPopupCount(poid,0,'popover-count-');
15526 anikendra 747
		} else if(cookieval > 0) {
15310 anikendra 748
			incrementPopupCount(poid, cookieval, 'popover-count-');
749
		}
750
		setLastShown(poid,'popover-lastshown-');
751
	})
752
 
15077 anikendra 753
	var cname = 'popover-lastshown-'+me+'-'+poid;
15721 anikendra 754
	var lastshown = getCookie(cname,1);
15310 anikendra 755
	if(cookieval=='' || cookieval == 'NaN' || !cookieval){				
15077 anikendra 756
		showpopover(poid);
15521 anikendra 757
	} 
758
	//Donot show popover anymore as long as we don't find a suitable solution
15721 anikendra 759
	else{
15077 anikendra 760
		var d = new Date();
761
		var t = d.getTime();
15085 anikendra 762
		if(t-lastshown>18*3600*1000){
15310 anikendra 763
			if(cookieval>=2){
15077 anikendra 764
				return false;
765
			}else{
15310 anikendra 766
				showpopover(poid);				
15077 anikendra 767
			}
768
		}
15721 anikendra 769
	}
15583 anikendra 770
	ga('send', 'event', 'popover', me, cookieval);
15585 anikendra 771
	if (navigator.geolocation) {
772
        navigator.geolocation.getCurrentPosition(showPosition);
773
    } 
15077 anikendra 774
});
775
function showpopover(id){
776
	$('[data-toggle="popover"]#'+id).popover({'html':true});
777
	$('[data-toggle="popover"]#'+id).trigger('click');		
15085 anikendra 778
}
779
$(document).on('click','.nodeals',function(){
780
	document.location = $(this).data('href');
16018 anikendra 781
});
782
$(document).on('click','.selectbrand',function(e){
783
	e.preventDefault();
784
	var brands = $(this).data('id');
785
	var brandname = $(this).html();
786
	console.log(brandname);
787
	setCookie('brandschosen', brands, 1, true);
788
	var url = $(this).data('href');
789
	ga('send', 'event', 'selectbrand', 'brand', brandname);
790
	properties = {};
791
	properties['brand'] = brandname;
792
	pma.send('filters','brands','selectbrand',me,properties);
793
	var postdata = {'user_id':me,'type':'brand','filters':brandname};
794
	$.post( "/user_filters/add", postdata, function( data ) {
795
		$('#loadingModal').modal('hide');
796
		$(this).addClass('activebrand');
797
  		document.location = url+'&brands='+brands;
798
	});
799
});
15128 anikendra 800
var Base64 = {
801
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
802
    encode: function(input) {
803
        var output = "";
804
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
805
        var i = 0;
806
        input = Base64._utf8_encode(input);
807
        while (i < input.length) {
808
            chr1 = input.charCodeAt(i++);
809
            chr2 = input.charCodeAt(i++);
810
            chr3 = input.charCodeAt(i++);
811
 
812
            enc1 = chr1 >> 2;
813
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
814
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
815
            enc4 = chr3 & 63;
816
            if (isNaN(chr2)) {
817
                enc3 = enc4 = 64;
818
            } else if (isNaN(chr3)) {
819
                enc4 = 64;
820
            }
821
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
822
        }
823
        return output;
824
    },
825
 
826
 
827
    decode: function(input) {
828
        var output = "";
829
        var chr1, chr2, chr3;
830
        var enc1, enc2, enc3, enc4;
831
        var i = 0;
832
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
833
        while (i < input.length) {
834
            enc1 = this._keyStr.indexOf(input.charAt(i++));
835
            enc2 = this._keyStr.indexOf(input.charAt(i++));
836
            enc3 = this._keyStr.indexOf(input.charAt(i++));
837
            enc4 = this._keyStr.indexOf(input.charAt(i++));
838
            chr1 = (enc1 << 2) | (enc2 >> 4);
839
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
840
            chr3 = ((enc3 & 3) << 6) | enc4;
841
            output = output + String.fromCharCode(chr1);
842
            if (enc3 != 64) {
843
                output = output + String.fromCharCode(chr2);
844
            }
845
            if (enc4 != 64) {
846
                output = output + String.fromCharCode(chr3);
847
            }
848
        }
849
        output = Base64._utf8_decode(output);
850
        return output;
851
    },
852
 
853
    _utf8_encode: function(string) {
854
        string = string.replace(/\r\n/g, "\n");
855
        var utftext = "";
856
        for (var n = 0; n < string.length; n++) {
857
            var c = string.charCodeAt(n);
858
            if (c < 128) {
859
                utftext += String.fromCharCode(c);
860
            }
861
            else if ((c > 127) && (c < 2048)) {
862
                utftext += String.fromCharCode((c >> 6) | 192);
863
                utftext += String.fromCharCode((c & 63) | 128);
864
            }
865
            else {
866
                utftext += String.fromCharCode((c >> 12) | 224);
867
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
868
                utftext += String.fromCharCode((c & 63) | 128);
869
            }
870
        }
871
        return utftext;
872
    },
873
 
874
    _utf8_decode: function(utftext) {
875
        var string = "";
876
        var i = 0;
877
        var c = c1 = c2 = 0;
878
        while (i < utftext.length) {
879
            c = utftext.charCodeAt(i);
880
            if (c < 128) {
881
                string += String.fromCharCode(c);
882
                i++;
883
            }
884
            else if ((c > 191) && (c < 224)) {
885
                c2 = utftext.charCodeAt(i + 1);
886
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
887
                i += 2;
888
            }
889
            else {
890
                c2 = utftext.charCodeAt(i + 1);
891
                c3 = utftext.charCodeAt(i + 2);
892
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
893
                i += 3;
894
            }
895
        }
896
        return string;
897
    }
15550 anikendra 898
}
899
 
900
 
901
var pma = new function() {
15584 anikendra 902
    this.apiurl = "http://45.33.50.227:8081/";
15550 anikendra 903
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};
904
 
905
    this.send = function (category,action,label,user_id,properties) {
15585 anikendra 906
    	if(!properties){
907
    		properties = {};
908
    	}
909
    	properties.location = window.location.href;
910
    	// properties.appCodeName = navigator.appCodeName;
911
    	// properties.appName = navigator.appName;
912
    	// properties.appVersion = navigator.appVersion;
913
    	properties.cookieEnabled = String(navigator.cookieEnabled);
914
    	properties.platform = navigator.platform;
915
    	properties.userAgent = navigator.userAgent;
916
    	properties.ip = ip;
917
	  	if (navigator.geolocation) {
15586 anikendra 918
	  		if(getCookie('latitude',true)){
919
	  			properties.latitude = getCookie('latitude');
920
	  		}	  		
921
	  		if(getCookie('longitude',true)){
922
		  		properties.longitude = getCookie('longitude');
923
		  	}
15585 anikendra 924
	  	}
925
	  	properties.screenHeight = String(screen.height);
926
	  	properties.screenWidth = String(screen.width);
927
    	// console.log(properties);
15550 anikendra 928
 		$.ajax({
929
			url: this.apiurl + this.endpoints.track,
930
			data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
931
			// Tell jQuery we're expecting JSONP
932
			dataType: "json",
933
			// Tell YQL what we want and that we want JSON			
934
			method: 'post',
935
			// Work with the response
936
			success: function( response ) {
937
				//Well, well, well :)
938
			}
939
		});       
940
    };
941
 
942
    this.formDataToObject = function(formdata){
943
    	var properties = {};
944
    	var keys = [];
945
		var formdata = JSON.parse(JSON.stringify(formdata));
946
		for (var i in formdata) {
947
			var key = formdata[i].name;
948
			if(index = keys.indexOf(key)==-1){
949
				properties[key] = formdata[i].value;
950
			}else{
951
				properties[key+'_'+i] = formdata[i].value;
952
			}
953
			keys.push(key);
954
		};
955
		return properties;
956
	}
15128 anikendra 957
}