Subversion Repositories SmartDukaan

Rev

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