Subversion Repositories SmartDukaan

Rev

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