Subversion Repositories SmartDukaan

Rev

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