Subversion Repositories SmartDukaan

Rev

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