Subversion Repositories SmartDukaan

Rev

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