Subversion Repositories SmartDukaan

Rev

Rev 16261 | Rev 16308 | 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'){
15920 anikendra 289
							document.location = response.url;	
290
							pma.send('apk','shopclues','active',me,null);
291
						}else{
292
							pma.send('apk','shopclues','inactive',me,null);
293
							$('#loadingModal').modal('hide');
294
							showShopcluesPopup(response.url);
295
							// return;
296
						}
16271 anikendra 297
				  	} 
298
				  	/*else if(store == 1 ) {
299
					 	url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
300
					 	document.location = url;
301
					} */
302
					else if (store == 3 || store == 2) {
15310 anikendra 303
						if (store == 2){
304
							response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
305
						}
15188 anikendra 306
						if(response.showmessage == 1) {
307
							$('#loadingModal').modal('hide');
308
							$('#customMessage').html(response.message);
15310 anikendra 309
							$('#customMessageModal').modal('show');							
15311 anikendra 310
							setTimeout(function(){ document.location = response.url;}, 1000*3);			
15310 anikendra 311
						} else{
15206 anikendra 312
							document.location = response.url;	
15188 anikendra 313
						}
15203 anikendra 314
					} else {
15128 anikendra 315
						document.location = response.url;
316
					}										
13579 anikendra 317
				}
15310 anikendra 318
			},
319
			error: function() {
320
				document.location = url;
13579 anikendra 321
			}
322
		});
14432 anikendra 323
		ga('send', 'event', 'product', 'click', $(this).data('url'));
15550 anikendra 324
		var properties = {};
325
		properties.sku = String($(this).data('id'));
326
		properties.source = String($(this).data('source'));
327
		properties.url = encodeURIComponent($(this).data('url'));
328
		properties.price = String($(this).data('price'));
329
		pma.send('products','url','click',me,properties);
13583 anikendra 330
	});
13719 anikendra 331
	$('.jscroll-inner').on('click','.likedeal',function(e){	
13583 anikendra 332
		var that = $(this);
13682 anikendra 333
		if($(that).hasClass('active')){
13583 anikendra 334
			//User has already liked it,so remove like
335
			var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";	
336
		}else{
337
			var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
338
		}
339
		$.ajax({
340
			url: url,
341
			// The name of the callback parameter, as specified by the YQL service
342
			jsonp: "callback",
343
			// Tell jQuery we're expecting JSONP
344
			dataType: "jsonp",
345
			// Tell YQL what we want and that we want JSON
346
			data: {
347
				format: "json"
348
			},
349
			// Work with the response
350
			success: function( response ) {
351
				if(response.success){
13672 anikendra 352
					$(that).toggleClass('active');
353
					$(that).parent().find('li.dislikedeal',0).removeClass('active');
13583 anikendra 354
				}
355
			}
356
		});
13686 anikendra 357
		ga('send', 'event', 'product', 'like', $(this).data('id'));
15550 anikendra 358
		var properties = {};
359
		properties.sku = String($(this).data('id'));
360
		pma.send('products','favourites','like',me,properties);
13583 anikendra 361
	});
13688 anikendra 362
	$('#myModal').on('click','#unlikebtn',function(e){
13682 anikendra 363
		e.preventDefault();
364
		var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
365
		$.ajax({
366
			url: url,
367
			// The name of the callback parameter, as specified by the YQL service
368
			jsonp: "callback",
369
			// Tell jQuery we're expecting JSONP
370
			dataType: "jsonp",
371
			// Tell YQL what we want and that we want JSON
372
			data: {
373
				format: "json"
374
			},
375
			// Work with the response
376
			success: function( response ) {
377
			}
378
		});
379
		$('#myModal').modal('hide');
13686 anikendra 380
		ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
15550 anikendra 381
		pma.send('brands','hide',$('#myModal').find('#productToHide',0).val(),me);
13682 anikendra 382
	})
13719 anikendra 383
	$('.jscroll-inner').on('click','.dislikedeal',function(e){			
13583 anikendra 384
		var that = $(this);
13682 anikendra 385
		if($(that).hasClass('active')){
13583 anikendra 386
			//User has already liked it,so remove like
387
			var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";	
388
		}else{
13682 anikendra 389
			$('#myModal').find('#productToHide',0).val($(this).data('id'));
13583 anikendra 390
			var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
391
		}
392
		$.ajax({
393
			url: url,
394
			// The name of the callback parameter, as specified by the YQL service
395
			jsonp: "callback",
396
			// Tell jQuery we're expecting JSONP
397
			dataType: "jsonp",
398
			// Tell YQL what we want and that we want JSON
399
			data: {
400
				format: "json"
401
			},
402
			// Work with the response
403
			success: function( response ) {
404
				if(response.success){
13672 anikendra 405
					$(that).toggleClass('active');
406
					$(that).parent().find('li.likedeal',0).removeClass('active');
13583 anikendra 407
				}
408
			}
409
		});
13686 anikendra 410
		ga('send', 'event', 'product', 'dislike', $(this).data('id'));
15550 anikendra 411
		var properties = {};
412
		properties.sku = String($(this).data('id'));
413
		pma.send('products','favourites','dislike',me,properties);
13583 anikendra 414
	});
13731 anikendra 415
	$('.deletefav').on('click',function(){
416
		var that = $(this);
417
		$('#loadingModal').modal();
418
		var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');			
419
		$.ajax({
420
			url: url,
421
			// The name of the callback parameter, as specified by the YQL service
422
			jsonp: "callback",
423
			// Tell jQuery we're expecting JSONP
424
			dataType: "jsonp",
425
			// Tell YQL what we want and that we want JSON
426
			data: {
427
				format: "json"
428
			},
429
			// Work with the response
430
			success: function( response ) {
431
				$('#loadingModal').modal('hide');
432
				if(response.success){			
433
					$('#fav-'+$(that).data('id')).hide('slow');
434
				}
435
			}
436
		});
437
		ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
15550 anikendra 438
		var properties = {};
439
		properties.sku = String($(this).data('id'));
440
		pma.send('products','favourites','remove',me,properties);
13731 anikendra 441
	});
442
	$('.clearfavs').on('click',function(){
443
		var that = $(this);
444
		$('#loadingModal').modal();
14300 anikendra 445
		var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');			
13731 anikendra 446
		$.ajax({
447
			url: url,
448
			// The name of the callback parameter, as specified by the YQL service
449
			jsonp: "callback",
450
			// Tell jQuery we're expecting JSONP
451
			dataType: "jsonp",
452
			// Tell YQL what we want and that we want JSON
453
			data: {
454
				format: "json"
455
			},
456
			// Work with the response
457
			success: function( response ) {
458
				$('#loadingModal').modal('hide');
459
				if(response.success){			
460
					$('.deletefav').each(function(){
461
						$('#fav-'+$(this).data('id')).hide('slow');
462
					})					
463
				}
464
				$(that).hide();
465
			}
466
		});
467
		ga('send', 'event', 'favourites', 'removeall', me);
15550 anikendra 468
		pma.send('products','favourites','removeall',me);
13731 anikendra 469
	});
13759 anikendra 470
	$('.revealbrands').on('click',function(){
471
		$(this).parent().find('.notfeatured').toggleClass('hidden');
472
		if($(this).html()=='Others'){
473
			$(this).html('Hide');
474
		}else{
475
			$(this).html('Others');
476
		}
477
	});
14068 anikendra 478
	$(document).on('click','.creditedcashbacks',function(){
479
		if($(this).find('.glyphicon-plus',0).length>0){
480
			$(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
481
		}else{
482
			$(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
483
		}
484
		$(this).next().toggleClass('hidden');
485
	});
486
	$(document).on('click','.panel-heading',function(){
487
		if($(this).find('.glyphicon-plus',0).length>0){
488
			$(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
489
		}else{
490
			$(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
491
		}
492
	});
14135 anikendra 493
	$(document).on('click','.prefcatselect',function(){
494
		$('.prefcatselect').removeClass('active')
495
		$(this).addClass('active');
496
		$('.categorypreferences').addClass('hidden');
497
		$('#cat-'+$(this).data('id')).toggleClass('hidden');
14150 anikendra 498
	});
499
	$(document).on('click','.refresh',function(){
500
		document.location.reload();
501
	});
14215 anikendra 502
	$(document).on('click','.hasmoretext',function(){
503
		$('#fulltext').html($(this).data('fulltext'));
504
		$('#fullTextModal').modal();
505
	});
14300 anikendra 506
	$(document).on('click','.favswitch',function(){
507
		$('.favswitch').removeClass('active')
508
		$(this).addClass('active');
509
		$('.clearfavs').addClass('hidden');
510
		$('.card').addClass('hidden');
511
		$('.'+$(this).data('type')).removeClass('hidden');
512
	});
14386 anikendra 513
	$(document).on('click','.brandpreferences .brands',function(){
514
		$(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
515
	});
516
	$(document).on('click','.tryagainforliveprice',function(){		
517
		fetchLivePrice($(this).parent());
518
		$(this).parent().html('Getting Live Prices');
519
	});
14579 anikendra 520
	$(document).on('click','.alert > a',function(){		
521
		ga('send', 'event', 'notifications', 'click', $(this).html());
15550 anikendra 522
		pma.send('notifications','click',$(this).html(),me);
14579 anikendra 523
	});
524
	$(document).on('click','.banner',function(){		
525
		ga('send', 'event', 'banners', 'click', $(this).data('name'));
15550 anikendra 526
		pma.send('banners','click',$(this).data('name'),me);
14579 anikendra 527
	});
13992 anikendra 528
});
15310 anikendra 529
function setCookie(cname, cvalue, days, forceCookie) {
530
	if(typeof(Storage) !== "undefined" && !forceCookie) {
531
		localStorage.setItem(cname, cvalue);
532
	} else{
533
		var d = new Date();
534
	    d.setTime(d.getTime() + (days*24*60*60*1000));
535
	    var expires = "expires="+d.toUTCString();
536
	    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
537
	}    
14849 anikendra 538
}
539
 
15310 anikendra 540
function getCookie(cname,forceCookie) {
541
	if(typeof(Storage) !== "undefined" && !forceCookie) {
542
	    return localStorage.getItem(cname);
543
	} else {	   
544
	    var name = cname + "=";
545
	    var ca = document.cookie.split(';');
546
	    for(var i=0; i<ca.length; i++) {
547
	        var c = ca[i];
548
	        while (c.charAt(0)==' ') c = c.substring(1);
549
	        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
550
	    }
551
	    return "";
552
	}
14849 anikendra 553
}
15310 anikendra 554
 
14849 anikendra 555
function showpopup(id,count,interval){
14851 anikendra 556
	var cname = 'notif-count-'+me+'-'+id;
15797 anikendra 557
	var cookieval = getCookie(cname,1);
14851 anikendra 558
	var cname = 'notif-lastshown-'+me+'-'+id;
15797 anikendra 559
	var lastshown = getCookie(cname,1);
15310 anikendra 560
	if(!cookieval || cookieval == 'NaN' || cookieval==''){		
15077 anikendra 561
		incrementPopupCount(id,0,'notif-count-');
562
		setLastShown(id,'notif-lastshown-');
14849 anikendra 563
		return true;
564
	} else{
565
		var d = new Date();
566
		var t = d.getTime();
567
		if(t-lastshown>interval*60*1000){
568
			if(cookieval>=count){
569
				return false;
570
			}else{
15077 anikendra 571
				setLastShown(id,'notif-lastshown-');
572
				incrementPopupCount(id,cookieval,'notif-count-');
14849 anikendra 573
				return true;	
574
			}
575
		}
576
	}
577
}
15077 anikendra 578
function setLastShown(id,cookiename){
579
	var cname = cookiename+me+'-'+id;
14849 anikendra 580
	var d = new Date();
15721 anikendra 581
	setCookie(cname, d.getTime(), 365, 1);
14849 anikendra 582
}
15077 anikendra 583
function incrementPopupCount(id,currentCount,cookiename) {
584
	var cname = cookiename+me+'-'+id;
15721 anikendra 585
	setCookie(cname, parseInt(currentCount)+1, 365, 1);
14858 anikendra 586
}
587
var hidden, visibilityChange; 
588
function handleVisibilityChange() {
589
  if (document[hidden]) {
15058 anikendra 590
  	// pagetitle = document.title;
14858 anikendra 591
  } else {
15058 anikendra 592
  	// document.title = pagetitle;
14858 anikendra 593
  }
594
}
595
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
596
  hidden = "hidden";
597
  visibilityChange = "visibilitychange";
598
} else if (typeof document.mozHidden !== "undefined") {
599
  hidden = "mozHidden";
600
  visibilityChange = "mozvisibilitychange";
601
} else if (typeof document.msHidden !== "undefined") {
602
  hidden = "msHidden";
603
  visibilityChange = "msvisibilitychange";
604
} else if (typeof document.webkitHidden !== "undefined") {
605
  hidden = "webkitHidden";
606
  visibilityChange = "webkitvisibilitychange";
607
}
608
if (typeof document.addEventListener === "undefined" || 
609
  typeof document[hidden] === "undefined") {
15077 anikendra 610
  console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
14858 anikendra 611
} else {
612
  // Handle page visibility change   
613
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
614
}    
14936 anikendra 615
$('.notificationok').on('click',function(e){
14932 anikendra 616
	e.preventDefault();
14931 anikendra 617
	$('.notificationmodal').modal('hide');
15159 anikendra 618
	// setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
16133 anikendra 619
	ga('send', 'event', 'popupnotification-'+$(this).parent().data('id'), 'ok', me);
620
	var properties = {};
621
	properties.id = String($(this).parent().data('id'));
622
	pma.send('popupnotification','click','ok',me,properties);
14932 anikendra 623
	document.location = $(this).parent().prop('href');
15015 anikendra 624
});
625
$(document).on('click','.clearfilter',function(){	
626
	$('.filterbrand').each(function(){
627
		$(this).prop('checked',false);
628
	});	
15550 anikendra 629
	ga('send', 'event', 'filter', 'brand', 'reset');
630
	pma.send('filters','brands','reset',me);
15015 anikendra 631
});
632
$(document).on('click','.applyfilter',function(){	
15584 anikendra 633
	$(this).prop('disabled',true);
634
	$('#loadingModal').modal();
15015 anikendra 635
	var brands = [];
15026 anikendra 636
	var brandnames = [];
15015 anikendra 637
	$('.filterbrand').each(function(){
638
		if($(this).prop('checked')){
639
			brands.push($(this).val());
15026 anikendra 640
			brandnames.push($(this).parent().siblings('.brandname').html());
15015 anikendra 641
		}		
642
	});
643
	if(brands.length==0){
15721 anikendra 644
		$('#loadingModal').modal('hide');
15015 anikendra 645
		$('#message').html('Please choose a few brands first').removeClass('hidden');
646
		setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
15722 anikendra 647
		$(this).prop('disabled',false);
15015 anikendra 648
		return false;
649
	}else{
16240 anikendra 650
		setCookie('brandschosen', brands, 0.25, true);
15015 anikendra 651
		var url = $('#brandselecter').prop('action');
15026 anikendra 652
		ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
15550 anikendra 653
		properties = {};
654
		for(var i in brandnames){
655
			properties['brand_'+i] = brandnames[i];
656
		}
657
		pma.send('filters','brands','addfilter',me,properties);
15085 anikendra 658
		var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
659
		$.post( "/user_filters/add", postdata, function( data ) {
15584 anikendra 660
			$('#loadingModal').modal('hide');
15722 anikendra 661
			$(this).prop('disabled',false);
15584 anikendra 662
	  		document.location = url+'&brands='+brands.join('^');
15085 anikendra 663
		});		
15015 anikendra 664
	}	
665
});
666
$(document).on('click','#showallbrands',function(){	
667
	$('.hidden').removeClass('hidden');
668
	$(this).hide();
15019 anikendra 669
});
670
$(document).on('input','#brandfilter',function(){	
671
	$('.brand').addClass('hidden');
672
	$('#showallbrands').hide();
673
	var that = $(this);
674
	$('li.brand').filter(function() { 
675
	  return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
676
	}).removeClass('hidden','slow');
15042 anikendra 677
});
15077 anikendra 678
$(document).on('click','.filterbrand',function(){
679
	var clicked = $(this).parent().parent();
15042 anikendra 680
	// all the LIs above the clicked one
681
	var previousAll = clicked.prevAll();
682
 
683
	// only proceed if it's not already on top (no previous siblings)
684
	if(previousAll.length > 0) {
685
	// top LI
686
	var top = $(previousAll[previousAll.length - 1]);
687
 
688
	// immediately previous LI
689
	var previous = $(previousAll[0]);
690
 
691
	// how far up do we need to move the clicked LI?
692
	var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
693
 
694
	// how far down do we need to move the previous siblings?
695
	var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
696
 
697
	// let's move stuff
698
	clicked.css('position', 'relative');
699
	previousAll.css('position', 'relative');
700
	clicked.animate({'top': -moveUp});
701
	previousAll.animate({'top': moveDown}, {complete: function() {
702
	  // rearrange the DOM and restore positioning when we're done moving
703
	  clicked.parent().prepend(clicked);
704
	  clicked.css({'position': 'static', 'top': 0});
705
	  previousAll.css({'position': 'static', 'top': 0}); 
706
	}});
707
	}
708
})
709
$(document).on('click','.clearfilters',function(){
15310 anikendra 710
	setCookie('brandschosen', '', -1, true);
15058 anikendra 711
	ga('send', 'event', 'filter', 'brand', 'clearfilters');
15550 anikendra 712
	pma.send('filters','brands','clearfilters',me);
15085 anikendra 713
	var postdata = {'user_id':me,'type':'clear'};
16240 anikendra 714
	$('#loadingModal').modal('show');
715
	$.post("/user_filters/add", postdata, function( data ) {		
716
	  	document.location.reload();
15085 anikendra 717
	});	
15042 anikendra 718
});
719
function selectChosenBrands(){
16261 anikendra 720
	var brandschosen = decodeURIComponent(getCookie('brandschosen',true));
15042 anikendra 721
	if(brandschosen && brandschosen.length>0){
722
		var brands = brandschosen.split(',');
723
		for(var i in brands){
724
			$('.brand').filter(function() { 
725
			  	return $(this).data("brandid") == brands[i];
15077 anikendra 726
			}).removeClass('hidden').find('.filterbrand',0).trigger( "click" );
15042 anikendra 727
		}
728
	}
15065 anikendra 729
}
15585 anikendra 730
function showPosition(position) {
15586 anikendra 731
    setCookie('latitude',position.coords.latitude,1,true); 
732
    setCookie('longitude',position.coords.longitude,1,true);	
15585 anikendra 733
}
15065 anikendra 734
$(function () {
15077 anikendra 735
	var poid = 'popovertrigger';
15310 anikendra 736
	var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 737
	var cookieval = getCookie(cname,1);
15310 anikendra 738
	$('#dropdownMenu1').on('click',function(){
739
		var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 740
		var cookieval = getCookie(cname,1);
15310 anikendra 741
		$('#popovertrigger').popover('hide');
742
		if(!cookieval || cookieval == 'NaN' || cookieval == ''){
743
			incrementPopupCount(poid,0,'popover-count-');
15526 anikendra 744
		} else if(cookieval > 0) {
15310 anikendra 745
			incrementPopupCount(poid, cookieval, 'popover-count-');
746
		}
747
		setLastShown(poid,'popover-lastshown-');
748
	})
749
 
15077 anikendra 750
	var cname = 'popover-lastshown-'+me+'-'+poid;
15721 anikendra 751
	var lastshown = getCookie(cname,1);
15310 anikendra 752
	if(cookieval=='' || cookieval == 'NaN' || !cookieval){				
15077 anikendra 753
		showpopover(poid);
15521 anikendra 754
	} 
755
	//Donot show popover anymore as long as we don't find a suitable solution
15721 anikendra 756
	else{
15077 anikendra 757
		var d = new Date();
758
		var t = d.getTime();
15085 anikendra 759
		if(t-lastshown>18*3600*1000){
15310 anikendra 760
			if(cookieval>=2){
15077 anikendra 761
				return false;
762
			}else{
15310 anikendra 763
				showpopover(poid);				
15077 anikendra 764
			}
765
		}
15721 anikendra 766
	}
15583 anikendra 767
	ga('send', 'event', 'popover', me, cookieval);
15585 anikendra 768
	if (navigator.geolocation) {
769
        navigator.geolocation.getCurrentPosition(showPosition);
770
    } 
15077 anikendra 771
});
772
function showpopover(id){
773
	$('[data-toggle="popover"]#'+id).popover({'html':true});
774
	$('[data-toggle="popover"]#'+id).trigger('click');		
15085 anikendra 775
}
776
$(document).on('click','.nodeals',function(){
777
	document.location = $(this).data('href');
16018 anikendra 778
});
779
$(document).on('click','.selectbrand',function(e){
780
	e.preventDefault();
781
	var brands = $(this).data('id');
782
	var brandname = $(this).html();
783
	console.log(brandname);
784
	setCookie('brandschosen', brands, 1, true);
785
	var url = $(this).data('href');
786
	ga('send', 'event', 'selectbrand', 'brand', brandname);
787
	properties = {};
788
	properties['brand'] = brandname;
789
	pma.send('filters','brands','selectbrand',me,properties);
790
	var postdata = {'user_id':me,'type':'brand','filters':brandname};
791
	$.post( "/user_filters/add", postdata, function( data ) {
792
		$('#loadingModal').modal('hide');
793
		$(this).addClass('activebrand');
794
  		document.location = url+'&brands='+brands;
795
	});
796
});
15128 anikendra 797
var Base64 = {
798
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
799
    encode: function(input) {
800
        var output = "";
801
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
802
        var i = 0;
803
        input = Base64._utf8_encode(input);
804
        while (i < input.length) {
805
            chr1 = input.charCodeAt(i++);
806
            chr2 = input.charCodeAt(i++);
807
            chr3 = input.charCodeAt(i++);
808
 
809
            enc1 = chr1 >> 2;
810
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
811
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
812
            enc4 = chr3 & 63;
813
            if (isNaN(chr2)) {
814
                enc3 = enc4 = 64;
815
            } else if (isNaN(chr3)) {
816
                enc4 = 64;
817
            }
818
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
819
        }
820
        return output;
821
    },
822
 
823
 
824
    decode: function(input) {
825
        var output = "";
826
        var chr1, chr2, chr3;
827
        var enc1, enc2, enc3, enc4;
828
        var i = 0;
829
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
830
        while (i < input.length) {
831
            enc1 = this._keyStr.indexOf(input.charAt(i++));
832
            enc2 = this._keyStr.indexOf(input.charAt(i++));
833
            enc3 = this._keyStr.indexOf(input.charAt(i++));
834
            enc4 = this._keyStr.indexOf(input.charAt(i++));
835
            chr1 = (enc1 << 2) | (enc2 >> 4);
836
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
837
            chr3 = ((enc3 & 3) << 6) | enc4;
838
            output = output + String.fromCharCode(chr1);
839
            if (enc3 != 64) {
840
                output = output + String.fromCharCode(chr2);
841
            }
842
            if (enc4 != 64) {
843
                output = output + String.fromCharCode(chr3);
844
            }
845
        }
846
        output = Base64._utf8_decode(output);
847
        return output;
848
    },
849
 
850
    _utf8_encode: function(string) {
851
        string = string.replace(/\r\n/g, "\n");
852
        var utftext = "";
853
        for (var n = 0; n < string.length; n++) {
854
            var c = string.charCodeAt(n);
855
            if (c < 128) {
856
                utftext += String.fromCharCode(c);
857
            }
858
            else if ((c > 127) && (c < 2048)) {
859
                utftext += String.fromCharCode((c >> 6) | 192);
860
                utftext += String.fromCharCode((c & 63) | 128);
861
            }
862
            else {
863
                utftext += String.fromCharCode((c >> 12) | 224);
864
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
865
                utftext += String.fromCharCode((c & 63) | 128);
866
            }
867
        }
868
        return utftext;
869
    },
870
 
871
    _utf8_decode: function(utftext) {
872
        var string = "";
873
        var i = 0;
874
        var c = c1 = c2 = 0;
875
        while (i < utftext.length) {
876
            c = utftext.charCodeAt(i);
877
            if (c < 128) {
878
                string += String.fromCharCode(c);
879
                i++;
880
            }
881
            else if ((c > 191) && (c < 224)) {
882
                c2 = utftext.charCodeAt(i + 1);
883
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
884
                i += 2;
885
            }
886
            else {
887
                c2 = utftext.charCodeAt(i + 1);
888
                c3 = utftext.charCodeAt(i + 2);
889
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
890
                i += 3;
891
            }
892
        }
893
        return string;
894
    }
15550 anikendra 895
}
896
 
897
 
898
var pma = new function() {
15584 anikendra 899
    this.apiurl = "http://45.33.50.227:8081/";
15550 anikendra 900
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};
901
 
902
    this.send = function (category,action,label,user_id,properties) {
15585 anikendra 903
    	if(!properties){
904
    		properties = {};
905
    	}
906
    	properties.location = window.location.href;
907
    	// properties.appCodeName = navigator.appCodeName;
908
    	// properties.appName = navigator.appName;
909
    	// properties.appVersion = navigator.appVersion;
910
    	properties.cookieEnabled = String(navigator.cookieEnabled);
911
    	properties.platform = navigator.platform;
912
    	properties.userAgent = navigator.userAgent;
913
    	properties.ip = ip;
914
	  	if (navigator.geolocation) {
15586 anikendra 915
	  		if(getCookie('latitude',true)){
916
	  			properties.latitude = getCookie('latitude');
917
	  		}	  		
918
	  		if(getCookie('longitude',true)){
919
		  		properties.longitude = getCookie('longitude');
920
		  	}
15585 anikendra 921
	  	}
922
	  	properties.screenHeight = String(screen.height);
923
	  	properties.screenWidth = String(screen.width);
924
    	// console.log(properties);
15550 anikendra 925
 		$.ajax({
926
			url: this.apiurl + this.endpoints.track,
927
			data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
928
			// Tell jQuery we're expecting JSONP
929
			dataType: "json",
930
			// Tell YQL what we want and that we want JSON			
931
			method: 'post',
932
			// Work with the response
933
			success: function( response ) {
934
				//Well, well, well :)
935
			}
936
		});       
937
    };
938
 
939
    this.formDataToObject = function(formdata){
940
    	var properties = {};
941
    	var keys = [];
942
		var formdata = JSON.parse(JSON.stringify(formdata));
943
		for (var i in formdata) {
944
			var key = formdata[i].name;
945
			if(index = keys.indexOf(key)==-1){
946
				properties[key] = formdata[i].value;
947
			}else{
948
				properties[key+'_'+i] = formdata[i].value;
949
			}
950
			keys.push(key);
951
		};
952
		return properties;
953
	}
15128 anikendra 954
}