Subversion Repositories SmartDukaan

Rev

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