Subversion Repositories SmartDukaan

Rev

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