Subversion Repositories SmartDukaan

Rev

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