Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
15403 manish.sha 1
var livePriceCalls = [];
2
var outOfStockCount = 0;
3
function getcashbackstring(type,value) {
4
	// console.log(type+' '+value);
5
	if(value==0){
6
		return '';
7
	}
8
	if(type==2){
9
		return ' +'+value+' Cashback';
10
	}else if(type==1){
11
		return ' +'+value+'% Cashback';
12
	}else{
13
		return '';
14
	}
15
}
16
 
17
$(function(){	
18
	if($('.scroll > .card').length>0) {
19
		setTimeout(function(){ document.location.reload(); }, 1000*15*60);
20
		$('.scroll').jscroll({
21
			loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
22
		    autoTriggerUntil: 3,
23
		    padding: 20,
24
		});
25
	}
26
	/*
27
	if($('.storeminprice').length>0) {
28
		var globalminprice = 9999999;
29
		var globalminsku;
30
		var globalmincashback = '';		
31
		var calls = [];
32
		$('.storeminprice').each(function(){
33
			var temp = {'sort':$(this).data('searchorder'),'val':$(this)};
34
			calls.push(temp);
35
		});
36
		calls = sortByKey(calls,'sort');		
37
		for(var i in calls){
38
			fetchLivePrice(calls[i]['val'])
39
		}				
40
	};*/
41
	function sortByKey(array, key) {
42
	    return array.sort(function(a, b) {
43
	        var x = a[key]; var y = b[key];
44
	        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
45
	    });
46
	};
47
	function fetchLivePrice(obj){		
48
		ga('send', 'event', 'liveprice', 'fetch', $(obj).data('bundle_id'));
49
		var that = obj;	
50
		var inStock = false;		
51
		var req = $.ajax({
52
			url: '/store_products/getliveprice/'+$(that).data('bundle_id')+'/'+$(that).data('id'),
53
			// Tell jQuery we're expecting JSONP
54
			dataType: "json",
55
			// Tell YQL what we want and that we want JSON			
56
			method: 'get',
57
			// timeout: 30000,
58
			// Work with the response
59
			success: function( response ) {
60
				// console.log(response);
61
				if(response.success){
62
					var i = 0;	
63
					var minpriceindex = 0;				
64
					if(response.products[i].in_stock == 1) {inStock = true;}
65
					if(response.products[i].in_stock == 1) {
66
						var minprice = Math.round(response.products[i]['available_price']);
67
						var minpriceurl = response.products[i]['marketPlaceUrl'];
68
						console.log(minprice);
69
					}
70
					if(response.products.length>0){
71
						//More than one products in store
72
						var variants = [];
73
						// var i = 0;
74
						for(var i in response.products){	
75
							if(response.products[i].in_stock == 1){
76
								inStock = true;
77
								// console.log(response.products[i]);
78
								if(response.products[i].available_price && response.products[i].available_price < globalminprice) {
79
									globalminprice = Math.round(response.products[i].available_price);
80
									globalminsku = response.products[i]._id;
81
									var globalminsource = response.products[i].source_id;
82
									var globalminurl = response.products[i].marketPlaceUrl;
83
									var globalmincashback = getcashbackstring(response.products[i].cash_back_type,response.products[i].cash_back);
84
								}
85
								if(typeof minprice == 'undefined' || response.products[i].available_price <= minprice) {
86
									minprice = Math.round(response.products[i].available_price);
87
									minpriceindex = i;
88
								}
89
								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});
90
							}						
91
						}
92
						if(variants.length>1){
93
							variants.splice(minpriceindex,1);
94
							var variantslink = $('<span class="variants"> '+(variants.length+1)+' Options</span>');
95
							$(that).parent().parent().find('.pull-left',0).append(variantslink);							
96
							$(variantslink).data('variants',variants).data('minprice',minprice);
97
						}
98
					}
99
					if(inStock){
100
						$(that).html(minprice).siblings('.cashbackamount').html(getcashbackstring(response.products[minpriceindex].cash_back_type,response.products[minpriceindex].cash_back)).parent().addClass('viewproduct');
101
						$('#name-'+$(that).data('id')).html(response.products[minpriceindex]['source_product_name']);
102
						// console.log(response.products[minpriceindex]);
103
						$('#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');
104
						// console.log(globalminprice+' '+globalminsku);
105
						if(globalminprice != 9999999) {
106
							$('#bestprice').html(globalminprice).siblings('.cashbackamount').html(globalmincashback);
107
							$('#beststorelink').data('id',globalminsku).data('source',globalminsource).data('price',globalminprice).data('url',globalminurl).removeClass('hidden');
108
							$('#bestpricecontainer').removeClass('hidden');
109
						} 
110
					} else{
111
						ga('send', 'event', 'liveprice', 'outofstock', response.products[0]._id);
112
						outOfStockCount++;
113
						$(that).parent().parent().remove();	
114
					}
115
					if(!response.products[0].available_price){
116
						// outOfStockCount++;
117
						// $(that).parent().parent().remove();	
118
						var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
119
						$(that).html(btn);
120
						ga('send', 'event', 'liveprice', 'failed', response.products[0]._id);
121
					}					
122
				} else{
123
					// outOfStockCount++;
124
					// $(that).parent().parent().remove();
125
					var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
126
					$(that).html(btn);
127
					ga('send', 'event', 'liveprice', 'failure', response.products[0]._id);
128
				}
129
				checkForOutStocks(outOfStockCount);
130
			},
131
			error: function(request, status, err) {
132
				//console.log(status+' '+err+' '+request);
133
            	// if (status == "timeout") {
134
            		var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
135
					$(that).html(btn);
136
					ga('send', 'event', 'liveprice', 'error', response.products[0]._id);
137
				// } else {
138
					// $(that).parent().parent().remove();
139
				// }
140
			}
141
		});
142
		livePriceCalls.push(req);
143
	};
144
	function checkForOutStocks(count){
145
		if(count>=livePriceCalls.length){
146
			$('#bestpricecontainer').html('<h4>Out of stock</h4>').removeClass('hidden');	
147
		}		
148
	};
149
	$(document).on('click','.showless',function(){
150
		$(this).addClass('hidden').siblings('.varnts').hide();
151
		$(this).parent().find('.variants',0).removeClass('hidden').addClass('justshow');
152
	});
153
	$(document).on('click','.variants',function(){
154
		$('.storeproductinfo').empty();
155
		var variants = $(this).data('variants');
156
		var minprice = $(this).data('minprice');
157
		// console.log(variants);
158
		$('#variantscount').html(variants.length);
159
		for(var i in variants){
160
			// console.log(variants[i]);
161
			// 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>');
162
			// $('#storeproducts').parent().append(row);
163
			// 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>');
164
			if(minprice == variants[i].available_price) {
165
				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>');
166
			} else {
167
				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>');
168
			}			
169
			$(this).parent().parent().append(row);			
170
		}
171
		var showless = $('<div class="showless col-xs-9 text-right">Less <i class="glyphicon glyphicon-chevron-up"></i></span>');
172
		$(this).parent().parent().append(showless);
173
		$(this).addClass('hidden');
174
	});
175
	$('.categorytab').on('click','.categorytabcontrol.active',function(){
176
		$(this).toggleClass('active');
177
		$('#preferences-'+$(this).data('id')).addClass('hidden');
178
		$(this).parent().parent().children().find('.savecategorypreferences',0).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
179
	});
180
	$('.categorytab').on('click','.categorytabcontrol:not(.active)',function(){
181
		$(this).parent().parent().find('.btn',0).click();
182
	});
183
	$('.categorytab').on('click','.editcategorypreferences',function(e){
184
		var that = $(this);
185
		$(that).removeClass('editcategorypreferences').addClass('savecategorypreferences').html('Done').addClass('btn-success');
186
		$('#togglepreferences-'+$(that).data('id')).toggleClass('active');
187
		$('#preferences-'+$(that).data('id')).removeClass('hidden');
188
		$('.brandselector').each(function(){
189
			if($(this).data('catid')==$(that).data('id')){
190
				$(this).addClass('active');
191
			}
192
		});
193
	});
194
	$('.categorytab').on('click','.savecategorypreferences',function(e){
195
		var that = $(this);
196
		$(that).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
197
		$('#togglepreferences-'+$(that).data('id')).toggleClass('active');
198
		$.ajax({
199
			url: $('#categorypreference-'+$(that).data('id')).attr('action'),
200
			data: $('#categorypreference-'+$(that).data('id')).serialize(),
201
			// Tell jQuery we're expecting JSONP
202
			dataType: "json",
203
			// Tell YQL what we want and that we want JSON			
204
			method: 'post',
205
			// Work with the response
206
			success: function( response ) {
207
				if(response.success){
208
					$('#preferences-'+$(that).data('id')).addClass('hidden');
209
				}
210
			}
211
		});
212
		ga('send', 'event', 'preferences', 'update', me);
213
	});
214
	// $('.row').on('click','.viewproduct',function(e){
215
	$(document).on('click','.viewproduct',function(e){
216
		if(typeof livePriceCalls != undefined) {
217
	    	for(var i in livePriceCalls){
218
	    		// console.log('killing ajax call '+i);
219
	    		livePriceCalls[i].abort();
220
	    	}
221
	    }
222
		$('#loadingModal').modal();
223
		/*
224
		if($(this).data('source')==2){
225
			//in case of flipkart, close popup after 5 seconds
226
			setTimeout(function(){ $('#loadingModal').modal('hide'); }, 1000*5);			
227
		}*/
228
		// console.log($(this).data('id'));
229
		var url = apihost+"clicks/add/0/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
230
		$.ajax({
231
			url: url,
232
			// The name of the callback parameter, as specified by the YQL service
233
			jsonp: "callback",
234
			// Tell jQuery we're expecting JSONP
235
			dataType: "jsonp",
236
			// Tell YQL what we want and that we want JSON
237
			data: {
238
				format: "json"
239
			},
240
			// Work with the response
241
			success: function( response ) {
242
				if(response.success && response.type=='redirect'){
243
					document.location = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
244
 
245
				}
246
			}
247
		});
248
		ga('send', 'event', 'product', 'click', $(this).data('url'));
249
	});
250
	$('.jscroll-inner').on('click','.likedeal',function(e){	
251
		var that = $(this);
252
		if($(that).hasClass('active')){
253
			//User has already liked it,so remove like
254
			var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";	
255
		}else{
256
			var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
257
		}
258
		$.ajax({
259
			url: url,
260
			// The name of the callback parameter, as specified by the YQL service
261
			jsonp: "callback",
262
			// Tell jQuery we're expecting JSONP
263
			dataType: "jsonp",
264
			// Tell YQL what we want and that we want JSON
265
			data: {
266
				format: "json"
267
			},
268
			// Work with the response
269
			success: function( response ) {
270
				if(response.success){
271
					$(that).toggleClass('active');
272
					$(that).parent().find('li.dislikedeal',0).removeClass('active');
273
				}
274
			}
275
		});
276
		ga('send', 'event', 'product', 'like', $(this).data('id'));
277
	});
278
	$('#myModal').on('click','#unlikebtn',function(e){
279
		e.preventDefault();
280
		var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
281
		// console.log(url);
282
		$.ajax({
283
			url: url,
284
			// The name of the callback parameter, as specified by the YQL service
285
			jsonp: "callback",
286
			// Tell jQuery we're expecting JSONP
287
			dataType: "jsonp",
288
			// Tell YQL what we want and that we want JSON
289
			data: {
290
				format: "json"
291
			},
292
			// Work with the response
293
			success: function( response ) {
294
				// console.log(response);						
295
			}
296
		});
297
		$('#myModal').modal('hide');
298
		ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
299
	})
300
	$('.jscroll-inner').on('click','.dislikedeal',function(e){			
301
		var that = $(this);
302
		if($(that).hasClass('active')){
303
			//User has already liked it,so remove like
304
			var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";	
305
		}else{
306
			// console.log('show modal');
307
			$('#myModal').find('#productToHide',0).val($(this).data('id'));
308
			//$('#myModal').modal();
309
			var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
310
		}
311
		$.ajax({
312
			url: url,
313
			// The name of the callback parameter, as specified by the YQL service
314
			jsonp: "callback",
315
			// Tell jQuery we're expecting JSONP
316
			dataType: "jsonp",
317
			// Tell YQL what we want and that we want JSON
318
			data: {
319
				format: "json"
320
			},
321
			// Work with the response
322
			success: function( response ) {
323
				if(response.success){
324
					$(that).toggleClass('active');
325
					$(that).parent().find('li.likedeal',0).removeClass('active');
326
				}
327
			}
328
		});
329
		ga('send', 'event', 'product', 'dislike', $(this).data('id'));
330
	});
331
	$('.deletefav').on('click',function(){
332
		var that = $(this);
333
		$('#loadingModal').modal();
334
		var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');			
335
		$.ajax({
336
			url: url,
337
			// The name of the callback parameter, as specified by the YQL service
338
			jsonp: "callback",
339
			// Tell jQuery we're expecting JSONP
340
			dataType: "jsonp",
341
			// Tell YQL what we want and that we want JSON
342
			data: {
343
				format: "json"
344
			},
345
			// Work with the response
346
			success: function( response ) {
347
				$('#loadingModal').modal('hide');
348
				if(response.success){			
349
					$('#fav-'+$(that).data('id')).hide('slow');
350
				}
351
			}
352
		});
353
		ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
354
	});
355
	$('.clearfavs').on('click',function(){
356
		var that = $(this);
357
		$('#loadingModal').modal();
358
		var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');			
359
		$.ajax({
360
			url: url,
361
			// The name of the callback parameter, as specified by the YQL service
362
			jsonp: "callback",
363
			// Tell jQuery we're expecting JSONP
364
			dataType: "jsonp",
365
			// Tell YQL what we want and that we want JSON
366
			data: {
367
				format: "json"
368
			},
369
			// Work with the response
370
			success: function( response ) {
371
				$('#loadingModal').modal('hide');
372
				if(response.success){			
373
					$('.deletefav').each(function(){
374
						$('#fav-'+$(this).data('id')).hide('slow');
375
					})					
376
				}
377
				$(that).hide();
378
			}
379
		});
380
		ga('send', 'event', 'favourites', 'removeall', me);
381
	});
382
	$('.revealbrands').on('click',function(){
383
		$(this).parent().find('.notfeatured').toggleClass('hidden');
384
		if($(this).html()=='Others'){
385
			$(this).html('Hide');
386
		}else{
387
			$(this).html('Others');
388
		}
389
	});
390
	$(document).on('click','.creditedcashbacks',function(){
391
		if($(this).find('.glyphicon-plus',0).length>0){
392
			$(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
393
		}else{
394
			$(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
395
		}
396
		$(this).next().toggleClass('hidden');
397
	});
398
	$(document).on('click','.panel-heading',function(){
399
		if($(this).find('.glyphicon-plus',0).length>0){
400
			$(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
401
		}else{
402
			$(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
403
		}
404
	});
405
	$(document).on('click','.prefcatselect',function(){
406
		$('.prefcatselect').removeClass('active')
407
		$(this).addClass('active');
408
		$('.categorypreferences').addClass('hidden');
409
		$('#cat-'+$(this).data('id')).toggleClass('hidden');
410
	});
411
	$(document).on('click','.refresh',function(){
412
		document.location.reload();
413
	});
414
	$(document).on('click','.hasmoretext',function(){
415
		$('#fulltext').html($(this).data('fulltext'));
416
		$('#fullTextModal').modal();
417
	});
418
	$(document).on('click','.favswitch',function(){
419
		$('.favswitch').removeClass('active')
420
		$(this).addClass('active');
421
		$('.clearfavs').addClass('hidden');
422
		$('.card').addClass('hidden');
423
		$('.'+$(this).data('type')).removeClass('hidden');
424
	});
425
	$(document).on('click','.brandpreferences .brands',function(){
426
		$(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
427
	});
428
 
429
	$(document).on('click','.tryagainforliveprice',function(){		
430
		fetchLivePrice($(this).parent());
431
		$(this).parent().html('Getting Live Prices');
432
	});
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
	});
439
});
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();
444
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
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){
458
	var cname = 'notif-count-'+me+'-'+id;
459
	var cookieval = getCookie(cname);
460
	var cname = 'notif-lastshown-'+me+'-'+id;
461
	var lastshown = getCookie(cname);
462
	if(cookieval==''){		
463
		incrementPopupCount(id,0,'notif-count-');
464
		setLastShown(id,'notif-lastshown-');
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{
475
				setLastShown(id,'notif-lastshown-');
476
				incrementPopupCount(id,cookieval,'notif-count-');
477
				return true;	
478
			}
479
		}
480
	}
481
}
482
function setLastShown(id,cookiename){
483
	var cname = cookiename+me+'-'+id;
484
	var d = new Date();
485
	setCookie(cname, d.getTime(), 365);
486
}
487
function incrementPopupCount(id,currentCount,cookiename) {
488
	var cname = cookiename+me+'-'+id;
489
	setCookie(cname, parseInt(currentCount)+1, 365);
490
}
491
var hidden, visibilityChange; 
492
function handleVisibilityChange() {
493
  if (document[hidden]) {
494
  	// pagetitle = document.title;
495
  } else {
496
  	// document.title = pagetitle;
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") {
514
  console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
515
} else {
516
  // Handle page visibility change   
517
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
518
}    
519
$('.notificationok').on('click',function(e){
520
	e.preventDefault();
521
	$('.notificationmodal').modal('hide');
522
	setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
523
	ga('send', 'event', 'popupnotification', 'ok', me);
524
	document.location = $(this).parent().prop('href');
525
});
526
$(document).on('click','.clearfilter',function(){	
527
	$('.filterbrand').each(function(){
528
		$(this).prop('checked',false);
529
	});	
530
	ga('send', 'event', 'filter', 'brand', 'clearfilter');
531
});
532
$(document).on('click','.applyfilter',function(){	
533
	var brands = [];
534
	var brandnames = [];
535
	$('.filterbrand').each(function(){
536
		if($(this).prop('checked')){
537
			// console.log($(this).parent().siblings('.brandname').html());
538
			brands.push($(this).val());
539
			brandnames.push($(this).parent().siblings('.brandname').html());
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{
547
		setCookie('brandschosen', brands, 1);
548
		var url = $('#brandselecter').prop('action');
549
		ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
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
		});		
554
	}	
555
});
556
$(document).on('click','#showallbrands',function(){	
557
	$('.hidden').removeClass('hidden');
558
	$(this).hide();
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');
567
});
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);
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);
603
	ga('send', 'event', 'filter', 'brand', 'clearfilters');
604
	var postdata = {'user_id':me,'type':'clear'};
605
	$.post("/user_filters/add", postdata, function( data ) {
606
	  document.location.reload();
607
	});	
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];
616
			}).removeClass('hidden').find('.filterbrand',0).trigger( "click" );
617
		}
618
	}
619
}
620
$(function () {
621
	var poid = 'popovertrigger';
622
	/*
623
  var popovershown = getCookie('popovershown');
624
  if(!popovershown){
625
  	popovershown = 0;
626
  }
627
  if(popovershown < 2){
628
  	$('[data-toggle="popover"]').popover({'html':true});
629
  	$('[data-toggle="popover"]').trigger('click');
630
  }  
631
  */
632
  $('#dropdownMenu1').on('click',function(){
633
  	$('#popovertrigger').popover('hide');
634
  	incrementPopupCount(poid,0,'popover-count-');
635
	setLastShown(poid,'popover-lastshown-');
636
  })
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));
648
		if(t-lastshown>18*3600*1000){
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');		
662
}
663
$(document).on('click','.nodeals',function(){
664
	document.location = $(this).data('href');
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
}