Subversion Repositories SmartDukaan

Rev

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