Subversion Repositories SmartDukaan

Rev

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

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