Subversion Repositories SmartDukaan

Rev

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