Subversion Repositories SmartDukaan

Rev

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