Subversion Repositories SmartDukaan

Rev

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