Subversion Repositories SmartDukaan

Rev

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