Subversion Repositories SmartDukaan

Rev

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