Subversion Repositories SmartDukaan

Rev

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