Subversion Repositories SmartDukaan

Rev

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