Subversion Repositories SmartDukaan

Rev

Rev 15232 | Rev 15274 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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