Subversion Repositories SmartDukaan

Rev

Rev 18399 | Rev 18402 | 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) {
18220 naman 4
    if(value==0){
5
        return '';
6
    }
7
    if(type==2){
8
        return ' +'+value+' Cashback';
9
    }else if(type==1){
10
        return ' +'+value+'% Cashback';
11
    }else{
12
        return '';
13
    }
15926 anikendra 14
};
15
function showShopcluesPopup(url){
18220 naman 16
    $('#shopcluesUrl').prop('href',url);
17
    $('#shopcluesModal').modal('show');
18
    return;
15926 anikendra 19
};
16397 anikendra 20
function showPaytmPopup(url){
18220 naman 21
    $('#paytmUrl').prop('href',url);
22
    $('#paytmModal').modal('show');
23
    return;
16397 anikendra 24
};
16485 anikendra 25
function showPaytmHelpPopup() {
18220 naman 26
    $('#loadingModal').modal('hide');
27
    $('#paytmHelpModal').modal('show');
16485 anikendra 28
}
29
function redirectToPaytm(url){
18220 naman 30
    url = 'http://mobilehotindia.com/r.html?'+Base64.encode(url);
31
    $('#paytmHelpModal').modal('hide');
32
    //check if paytm is active or not
33
    var paytmactive = getCookie('paytmActive',1);
34
    if(paytmactive && paytmactive == 'true'){       
35
        document.location = url;    
36
        pma.send('apk','paytm','active',me,null);
37
    }else{
38
        pma.send('apk','paytm','inactive',me,null);
39
        $('#loadingModal').modal('hide');
40
        showPaytmPopup(url);
41
    }
16485 anikendra 42
}
17006 naman 43
 
44
function redirectTohomeShop18(url){
18220 naman 45
    url = 'http://mobilehotindia.com/r.html?'+Base64.encode(url);
46
    //check if paytm is active or not
47
    var homeShop18active = getCookie('homeshop18',1);
48
    if(homeShop18active && homeShop18active == 'true'){     
49
        document.location = url;    
50
        pma.send('apk','homeShop18','active',me,null);
51
    }else{  
52
        pma.send('apk','homeShop18','inactive',me,null);
53
        $('#loadingModal').modal('hide');
54
        showhomeShop18Popup(url);
55
    }
17006 naman 56
}
57
 
58
function showhomeShop18Popup(url){
18220 naman 59
    $('#homeShop18Url').prop('href',url);
60
    $('#homeShop18Modal').modal('show');
61
    return;
17006 naman 62
};
63
 
13984 anikendra 64
$(function(){	
18115 amit.gupta 65
	if($('.scrollselector > .card').length>0) {
14969 anikendra 66
		setTimeout(function(){ document.location.reload(); }, 1000*15*60);
16395 anikendra 67
		if(typeof noscrolling == 'undefined') {
18177 amit.gupta 68
			$('.scrollselector').jscroll({
16368 anikendra 69
				loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
70
			    autoTriggerUntil: 3,
71
			    padding: 20,
17804 manish.sha 72
			    callback:loadCartDetails
16368 anikendra 73
			});
74
		}
13820 anikendra 75
	}
13901 anikendra 76
	if($('.storeminprice').length>0) {
77
		var globalminprice = 9999999;
14773 anikendra 78
		var globalminsku;
79
		var globalmincashback = '';		
16124 anikendra 80
		var globalminoffer = '';		
14345 anikendra 81
		var calls = [];
13901 anikendra 82
		$('.storeminprice').each(function(){
14345 anikendra 83
			var temp = {'sort':$(this).data('searchorder'),'val':$(this)};
84
			calls.push(temp);
85
		});
86
		calls = sortByKey(calls,'sort');		
87
		for(var i in calls){
88
			fetchLivePrice(calls[i]['val'])
14969 anikendra 89
		}				
14345 anikendra 90
	};
91
	function sortByKey(array, key) {
92
	    return array.sort(function(a, b) {
93
	        var x = a[key]; var y = b[key];
94
	        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
95
	    });
15926 anikendra 96
	};		
15923 anikendra 97
	function getCouponText(coupon){
98
		return "<span class='red'>"+coupon+"</span>";
15926 anikendra 99
	};
16467 anikendra 100
	function getGrossPriceText(gross_price,available_price){
16656 anikendra 101
		if(gross_price == available_price)
102
			return "";
103
		return "Paytm cashback - "+(gross_price-available_price)+"<br>Net Price = <span class='red text-bigger'>"+available_price+"</span>"
16467 anikendra 104
	}
14432 anikendra 105
	function fetchLivePrice(obj){		
15607 anikendra 106
		ga('send', 'event', 'liveprice', 'fetch',$('#bestpriceproductname').html());
15550 anikendra 107
		var properties = {};
108
		properties.bundle_id = String($(obj).data('bundle_id'));
15607 anikendra 109
		properties.product_name = String($('#bestpriceproductname').html());
15585 anikendra 110
		pma.send('products','livesprice','fetch',me,properties);
14432 anikendra 111
		var that = obj;	
112
		var inStock = false;		
16495 anikendra 113
		var priceToCompare = 0;
14386 anikendra 114
		var req = $.ajax({
14345 anikendra 115
			url: '/store_products/getliveprice/'+$(that).data('bundle_id')+'/'+$(that).data('id'),
116
			// Tell jQuery we're expecting JSONP
117
			dataType: "json",
118
			// Tell YQL what we want and that we want JSON			
119
			method: 'get',
14430 anikendra 120
			// timeout: 30000,
14345 anikendra 121
			// Work with the response
122
			success: function( response ) {
123
				if(response.success){
124
					var i = 0;	
17006 naman 125
					var minpriceindex = 0;		
14797 anikendra 126
					if(response.products[i].in_stock == 1) {
16219 anikendra 127
						inStock = true;
16495 anikendra 128
						var minprice = 9999999;//Math.round(response.products[i]['available_price']);
14797 anikendra 129
						var minpriceurl = response.products[i]['marketPlaceUrl'];
130
					}
14345 anikendra 131
					if(response.products.length>0){
132
						//More than one products in store
133
						var variants = [];
16124 anikendra 134
						var j = 0;
135
						for(var i in response.products){								
14685 anikendra 136
							if(response.products[i].in_stock == 1){
16495 anikendra 137
								if(response.products[i].gross_price && response.products[i].gross_price > response.products[i].available_price) {
138
									priceToCompare = response.products[i].gross_price;
139
								}else{
140
									priceToCompare = response.products[i].available_price;
141
								}
15923 anikendra 142
								inStock = true;								
16495 anikendra 143
								if(priceToCompare && priceToCompare < globalminprice) {
144
									globalminprice = Math.round(priceToCompare);
14685 anikendra 145
									globalminsku = response.products[i]._id;
146
									var globalminsource = response.products[i].source_id;
14773 anikendra 147
									var globalminurl = response.products[i].marketPlaceUrl;
16124 anikendra 148
									var globalminoffer = response.products[i].offer;
14773 anikendra 149
									var globalmincashback = getcashbackstring(response.products[i].cash_back_type,response.products[i].cash_back);
14685 anikendra 150
								}
16495 anikendra 151
								if(typeof minprice == 'undefined' || priceToCompare < minprice) {
152
									minprice = Math.round(priceToCompare);
16219 anikendra 153
									minpriceindex = j;
16124 anikendra 154
								}								
16234 anikendra 155
								if(response.products[i].tagline && response.products[i].tagline.length>0 && $('#productoneliner').html().length==0) { 
16124 anikendra 156
									$('#productoneliner').html(response.products[i].tagline).removeClass('hidden').show();									
157
								}								
16467 anikendra 158
								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,'gross_price' : response.products[i].gross_price});
16124 anikendra 159
							}					
16219 anikendra 160
							j++;
13901 anikendra 161
						}
16219 anikendra 162
						if(variants.length>1){
16124 anikendra 163
							variants.splice(minpriceindex,1);							
14713 anikendra 164
							var variantslink = $('<span class="variants"> '+(variants.length+1)+' Options</span>');
165
							$(that).parent().parent().find('.pull-left',0).append(variantslink);							
14799 anikendra 166
							$(variantslink).data('variants',variants).data('minprice',minprice);
13948 anikendra 167
						}
14345 anikendra 168
					}
169
					if(inStock){
14797 anikendra 170
						$(that).html(minprice).siblings('.cashbackamount').html(getcashbackstring(response.products[minpriceindex].cash_back_type,response.products[minpriceindex].cash_back)).parent().addClass('viewproduct');
18290 naman 171
 
172
						if($(that).parent().data('storename') == "Saholic")
173
						{
174
							var url = minpriceurl;
175
							var value = url.substring(url.lastIndexOf('-') + 1);
176
							$(that).parent().attr('data-identifier', value);
18399 amit.gupta 177
							$(that).parent().attr('data-proid', response.products[minpriceindex]['_id']);
18290 naman 178
						}
179
 
14689 anikendra 180
						$('#name-'+$(that).data('id')).html(response.products[minpriceindex]['source_product_name']);
16039 anikendra 181
						if(response.products[minpriceindex]['coupon'] && response.products[minpriceindex]['coupon'].length>0){
15923 anikendra 182
							$('#couponcode-'+$(that).data('id')).show().find('span.red',0).html(getCouponText(response.products[minpriceindex]['coupon']));
16013 anikendra 183
						}			
184
						if(!response.products[minpriceindex]['codAvailable']){
16124 anikendra 185
							$('#codstatus-'+$(that).data('id')).show().removeClass('codstatus');
15923 anikendra 186
						}
16467 anikendra 187
						if(response.products[minpriceindex]['gross_price'] && response.products[minpriceindex]['gross_price'] > 0){
188
							$('#gross_price-'+$(that).data('id')).show().removeClass('gross_price').html(getGrossPriceText(response.products[minpriceindex]['gross_price'],response.products[minpriceindex]['available_price']));
189
						}
16124 anikendra 190
						if(response.products[minpriceindex]['offer'].length>0){
191
							$('#itemoffer-'+$(that).data('id')).show().html(response.products[minpriceindex]['offer']);
192
						}
14685 anikendra 193
						$('#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 194
						if(globalminprice != 9999999) {
16124 anikendra 195
							$('#bestprice').html(globalminprice).siblings('.cashbackamount').html(globalmincashback).siblings('.productoffer').html(globalminoffer);
14685 anikendra 196
							$('#beststorelink').data('id',globalminsku).data('source',globalminsource).data('price',globalminprice).data('url',globalminurl).removeClass('hidden');
14345 anikendra 197
							$('#bestpricecontainer').removeClass('hidden');
18401 amit.gupta 198
							if(typeof globalsource!= "undefined") {
199
								if (globalsource==4){
200
									var value = globalminurl.substring(url.lastIndexOf('-') + 1);
201
									$('#beststorelink').attr('data-identifier', value);
202
									$('#beststorelink').attr('data-proid', globalminsku);
203
								} else {
204
									$('#beststorelink').removeAttr('data-identifier');
205
									$('#beststorelink').removeAttr('data-proid');
206
								}						
207
							}
14432 anikendra 208
						} 
14386 anikendra 209
					} else{
15607 anikendra 210
						ga('send', 'event', 'liveprice', 'outofstock', $('#bestpriceproductname').html());
15550 anikendra 211
						var properties = {};
212
						properties.sku = String(response.products[0]._id);
15607 anikendra 213
						properties.source = String(response.products[0].source_id);
214
						properties.product_name = String($('#bestpriceproductname').html());
15767 anikendra 215
						pma.send('products','liveprice','outofstock',me,properties);
14432 anikendra 216
						outOfStockCount++;
14345 anikendra 217
						$(that).parent().parent().remove();	
13901 anikendra 218
					}
14345 anikendra 219
					if(!response.products[0].available_price){
14434 anikendra 220
						// outOfStockCount++;
221
						// $(that).parent().parent().remove();	
222
						var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
223
						$(that).html(btn);
15585 anikendra 224
						// ga('send', 'event', 'liveprice', 'failed', response.products[0]._id);
225
						// console.log('failed for '+ response);
226
						// properties = {};
227
						// properties.sku = String(response.products[0]._id); 
228
						// pma.send('products','liveprice','failed',me,properties);
14969 anikendra 229
					}					
14386 anikendra 230
				} else{
14434 anikendra 231
					// outOfStockCount++;
232
					// $(that).parent().parent().remove();
233
					var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
234
					$(that).html(btn);
14969 anikendra 235
					ga('send', 'event', 'liveprice', 'failure', response.products[0]._id);
15550 anikendra 236
					properties = {};
237
					properties.sku = String(response.products[0]._id); 
238
					pma.send('products','liveprice','failure',me,properties);
13901 anikendra 239
				}
14432 anikendra 240
				checkForOutStocks(outOfStockCount);
14345 anikendra 241
			},
15310 anikendra 242
			error: function(request, status, err) {            	
243
        		var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
244
				$(that).html(btn);
245
				try{
246
					if(response){
247
						ga('send', 'event', 'liveprice', 'error', response.products[0]._id);
15550 anikendra 248
						var properties = {};
249
						properties.sku = String(response.products[0]._id);
250
						pma.send('products','livescore','error',me,properties);
15310 anikendra 251
					}						
252
				} catch(e){}
14345 anikendra 253
			}
13901 anikendra 254
		});
14386 anikendra 255
		livePriceCalls.push(req);
14357 anikendra 256
	};
14432 anikendra 257
	function checkForOutStocks(count){
258
		if(count>=livePriceCalls.length){
259
			$('#bestpricecontainer').html('<h4>Out of stock</h4>').removeClass('hidden');	
14969 anikendra 260
		}		
14432 anikendra 261
	};
14687 anikendra 262
	$(document).on('click','.showless',function(){
263
		$(this).addClass('hidden').siblings('.varnts').hide();
264
		$(this).parent().find('.variants',0).removeClass('hidden').addClass('justshow');
265
	});
13901 anikendra 266
	$(document).on('click','.variants',function(){
267
		$('.storeproductinfo').empty();
16219 anikendra 268
		var variants = $(this).data('variants');		
14799 anikendra 269
		var minprice = $(this).data('minprice');
14026 anikendra 270
		$('#variantscount').html(variants.length);
13901 anikendra 271
		for(var i in variants){
16495 anikendra 272
			if(variants[i].gross_price && variants[i].gross_price > variants[i].available_price) {
273
				var priceToDisplay = variants[i].gross_price;
274
			}else{
275
				var priceToDisplay = variants[i].available_price;
276
			}
277
			if(minprice == priceToDisplay) {
278
				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="'+priceToDisplay+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span class="storeminprice">'+priceToDisplay+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span>';
14849 anikendra 279
			} else {
16656 anikendra 280
				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="'+priceToDisplay+'" data-url="'+variants[i].url+'" data-id="'+variants[i].id+'"><span class="cashbackrupee varnts text-right" ></span> <span class="text-small">'+priceToDisplay+'</span><span class="cashbackamount">'+getcashbackstring(variants[i].cash_back_type,variants[i].cash_back)+'</span><span class="pull-right arrowright"></span>';
16124 anikendra 281
			}
16467 anikendra 282
			if(variants[i].gross_price && variants[i].gross_price>0){
283
				html += '<p class="text-small">'+getGrossPriceText(variants[i].gross_price,variants[i].available_price)+'</p>';
284
			}	
16124 anikendra 285
			if(variants[i].offer.length>0){
286
				html += '<p class="text-small">'+variants[i].offer+'</p>';
16013 anikendra 287
			}	
16039 anikendra 288
			if(variants[i].coupon && variants[i].coupon.length>0){
16013 anikendra 289
				html += '<p class="text-small">Use Coupon <span class="red">'+variants[i].coupon+'</span></p>';
290
			}
291
			if(!variants[i].codAvailable){
16124 anikendra 292
				html += '<p class="text-small">COD not available</p>';
293
			}			
16013 anikendra 294
			html += '</div></div>';
295
			var row = $(html);			
14687 anikendra 296
			$(this).parent().parent().append(row);			
13901 anikendra 297
		}
14713 anikendra 298
		var showless = $('<div class="showless col-xs-9 text-right">Less <i class="glyphicon glyphicon-chevron-up"></i></span>');
14687 anikendra 299
		$(this).parent().parent().append(showless);
300
		$(this).addClass('hidden');
13901 anikendra 301
	});
13695 anikendra 302
	$('.categorytab').on('click','.categorytabcontrol.active',function(){
303
		$(this).toggleClass('active');
304
		$('#preferences-'+$(this).data('id')).addClass('hidden');
305
		$(this).parent().parent().children().find('.savecategorypreferences',0).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
306
	});
13759 anikendra 307
	$('.categorytab').on('click','.categorytabcontrol:not(.active)',function(){
308
		$(this).parent().parent().find('.btn',0).click();
309
	});
13695 anikendra 310
	$('.categorytab').on('click','.editcategorypreferences',function(e){
311
		var that = $(this);
312
		$(that).removeClass('editcategorypreferences').addClass('savecategorypreferences').html('Done').addClass('btn-success');
313
		$('#togglepreferences-'+$(that).data('id')).toggleClass('active');
314
		$('#preferences-'+$(that).data('id')).removeClass('hidden');
315
		$('.brandselector').each(function(){
316
			if($(this).data('catid')==$(that).data('id')){
317
				$(this).addClass('active');
318
			}
17691 naman 319
		});
320
		$('.subcategoryselector').each(function(){
321
			if($(this).data('catid')==$(that).data('id')){
322
				$(this).addClass('active');
323
			}
16066 anikendra 324
		});		
13695 anikendra 325
	});
326
	$('.categorytab').on('click','.savecategorypreferences',function(e){
327
		var that = $(this);
328
		$(that).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
329
		$('#togglepreferences-'+$(that).data('id')).toggleClass('active');
330
		$.ajax({
331
			url: $('#categorypreference-'+$(that).data('id')).attr('action'),
332
			data: $('#categorypreference-'+$(that).data('id')).serialize(),
333
			// Tell jQuery we're expecting JSONP
334
			dataType: "json",
335
			// Tell YQL what we want and that we want JSON			
336
			method: 'post',
337
			// Work with the response
338
			success: function( response ) {
339
				if(response.success){
340
					$('#preferences-'+$(that).data('id')).addClass('hidden');
341
				}
342
			}
343
		});
16066 anikendra 344
		active = getCookie('shopcluesActive',1);
16068 anikendra 345
		if(active && active == 'true'){
16066 anikendra 346
			$('.firsttimemsg').removeClass('hidden').show();
347
		}		
13695 anikendra 348
		ga('send', 'event', 'preferences', 'update', me);
15550 anikendra 349
		properties = pma.formDataToObject($('#categorypreference-'+$(this).data('id')).serializeArray());
350
		pma.send('preferences', 'update', 'set', me, properties);
13695 anikendra 351
	});
18220 naman 352
 
353
 
354
	$(document).on('click','.accsproduct',function(){
18226 naman 355
		if (typeof(Storage) !== "undefined") {
356
			localStorage.removeItem("productdetail");
357
			localStorage.setItem("productdetail", $(this).closest(".card").html());
358
		}
18220 naman 359
		$('#loadingModal').modal();
18226 naman 360
 
18220 naman 361
		var url = $(this).data('url');
18226 naman 362
 
18220 naman 363
		window.location = url;
364
	});
365
 
18290 naman 366
	$(document).on('click','.viewproduct',function(e){
367
 
368
		var proid = $(this).data("proid");
369
		var identifier = $(this).data("identifier");
370
 
14386 anikendra 371
		if(typeof livePriceCalls != undefined) {
372
	    	for(var i in livePriceCalls){
373
	    		livePriceCalls[i].abort();
374
	    	}
375
	    }
13686 anikendra 376
		$('#loadingModal').modal();
14952 anikendra 377
		if($(this).data('source')==2){
378
			//in case of flipkart, close popup after 5 seconds
15311 anikendra 379
			setTimeout(function(){ $('#loadingModal').modal('hide');$('#customMessageModal').modal('hide'); }, 1000*10);			
14952 anikendra 380
		}
15159 anikendra 381
		var store = $(this).data('source');
14345 anikendra 382
		var url = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
13579 anikendra 383
		$.ajax({
384
			url: url,
385
			// The name of the callback parameter, as specified by the YQL service
386
			jsonp: "callback",
387
			// Tell jQuery we're expecting JSONP
388
			dataType: "jsonp",
389
			// Tell YQL what we want and that we want JSON
390
			data: {
391
				format: "json"
392
			},
393
			// Work with the response
394
			success: function( response ) {
395
				if(response.success && response.type=='redirect'){
18119 amit.gupta 396
					//console.log(store);
15920 anikendra 397
					if(store == 5) {
398
						//check if shopclues is active or not
399
						active = getCookie('shopcluesActive',1);
16679 anikendra 400
						response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
401
						if(active && active == 'true'){							
15920 anikendra 402
							document.location = response.url;	
403
							pma.send('apk','shopclues','active',me,null);
404
						}else{
405
							pma.send('apk','shopclues','inactive',me,null);
406
							$('#loadingModal').modal('hide');
407
							showShopcluesPopup(response.url);
408
						}
17026 naman 409
				  	} else if(store == 6 ) {
16485 anikendra 410
				  		//display paytm help
18261 naman 411
//				  		if(needToDisplayPaytmPopup(me)){
412
//				  			showPaytmHelpPopup();
413
//					  		$('#oktatabyebye').on('click',function(){
414
//					  			redirectToPaytm(response.url);	
415
//					  		});	
416
//				  		}else{
16495 anikendra 417
				  			redirectToPaytm(response.url);	
18261 naman 418
//				  		}
17006 naman 419
 
18220 naman 420
                    } 
421
                      //for homeshop 18
422
                      else if(store == 7)
423
                      {
424
                            redirectTohomeShop18(response.url); 
425
 
426
                      }
427
                      else if (store == 3 || store == 2) {
428
                        if (store == 2){
429
                            response.url = 'http://mobilehotindia.com/r.html?'+Base64.encode(response.url);
430
                        }
431
                        if (store == 3){
432
                            response.url = '/r.html?'+Base64.encode(response.url);
433
                        }
434
                        if(response.showmessage == 1) {
435
                            $('#loadingModal').modal('hide');
436
                            $('#customMessage').html(response.message);
437
                            $('#customMessageModal').modal('show');                         
438
                            setTimeout(function(){ document.location = response.url;}, 1000*3);         
439
                        } else{
440
                            document.location = response.url;   
441
                        }
18290 naman 442
                    } else if (store == 4) {
443
                    	var urll = apihost+"categories/saholicdeal/"+proid;
444
                    	$.ajax({
445
                            method: "GET",
446
                            url:  urll,
447
                        },'json')
448
                        .done(function(msg){
18325 naman 449
                        	if (typeof(Storage) !== "undefined") {
450
	                        	localStorage.removeItem("productdetail");
451
	                			localStorage.setItem("productdetail",msg);
452
	                			document.location = apihost+"categories/dealdetail/"+identifier;
453
                        	}
18290 naman 454
                        });
455
 
456
//                        response.url = '/r.html?'+Base64.encode(response.url);
457
 
458
//                        document.location = response.url;
459
                    } 
460
 
461
					else{
462
						response.url = '/r.html?'+Base64.encode(response.url);
463
 
464
                      document.location = response.url;
465
					}
18220 naman 466
                }
467
            },
468
            error: function() {
469
                document.location = url;
470
            }
471
        });
472
        ga('send', 'event', 'product', 'click', $(this).data('url'));
473
        var properties = {};
474
        properties.sku = String($(this).data('id'));
475
        properties.source = String($(this).data('source'));
476
        properties.url = encodeURIComponent($(this).data('url'));
477
        properties.price = String($(this).data('price'));
478
        pma.send('products','url','click',me,properties);
479
    });
480
    $(document).on('click','.likeit',function(e){   
481
        var that = $(this);
482
        if($(that).find('span.likedeal').hasClass('active')){
483
            //User has already liked it,so remove like
484
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";   
485
        }else{
486
            var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
487
        }
488
        $.ajax({
489
            url: url,
490
            // The name of the callback parameter, as specified by the YQL service
491
            jsonp: "callback",
492
            // Tell jQuery we're expecting JSONP
493
            dataType: "jsonp",
494
            // Tell YQL what we want and that we want JSON
495
            data: {
496
                format: "json"
497
            },
498
            // Work with the response
499
            success: function( response ) {
500
                if(response.success){
501
                    that.find('span.likedeal').toggleClass('active');
502
                    $(".img-overlay div[name='dislikediv_"+that.data('id')+"']").find('span.dislikedeal').removeClass('active');
503
                }
504
            }
505
        });
506
        ga('send', 'event', 'product', 'like', $(this).data('id'));
507
        var properties = {};
508
        properties.sku = String($(this).data('id'));
509
        pma.send('products','favourites','like',me,properties);
510
    });
511
    $('#myModal').on('click','#unlikebtn',function(e){
512
        e.preventDefault();
513
        var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
514
        $.ajax({
515
            url: url,
516
            // The name of the callback parameter, as specified by the YQL service
517
            jsonp: "callback",
518
            // Tell jQuery we're expecting JSONP
519
            dataType: "jsonp",
520
            // Tell YQL what we want and that we want JSON
521
            data: {
522
                format: "json"
523
            },
524
            // Work with the response
525
            success: function( response ) {
526
            }
527
        });
528
        $('#myModal').modal('hide');
529
        ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
530
        pma.send('brands','hide',$('#myModal').find('#productToHide',0).val(),me);
531
    })
18066 naman 532
    $(document).on('click','.dislikeit',function(e){            
18220 naman 533
        var that = $(this);
534
        if($(that).find('span.dislikedeal').hasClass('active')){
535
            //User has already liked it,so remove like
536
            var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";    
537
        }else{
538
            $('#myModal').find('#productToHide',0).val($(this).data('id'));
539
            var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
540
        }
541
        $.ajax({
542
            url: url,
543
            // The name of the callback parameter, as specified by the YQL service
544
            jsonp: "callback",
545
            // Tell jQuery we're expecting JSONP
546
            dataType: "jsonp",
547
            // Tell YQL what we want and that we want JSON
548
            data: {
549
                format: "json"
550
            },
551
            // Work with the response
552
            success: function( response ) {
553
                if(response.success){
554
                    that.find('span.dislikedeal').toggleClass('active');
555
                    $(".img-overlay div[name='likediv_"+that.data('id')+"']").find('span.likedeal').removeClass('active');
556
                }
557
            }
558
        });
559
        ga('send', 'event', 'product', 'dislike', $(this).data('id'));
560
        var properties = {};
561
        properties.sku = String($(this).data('id'));
562
        pma.send('products','favourites','dislike',me,properties);
563
    });
564
    $('.deletefav').on('click',function(){
565
        var that = $(this);
566
        $('#loadingModal').modal();
567
        var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');         
568
        $.ajax({
569
            url: url,
570
            // The name of the callback parameter, as specified by the YQL service
571
            jsonp: "callback",
572
            // Tell jQuery we're expecting JSONP
573
            dataType: "jsonp",
574
            // Tell YQL what we want and that we want JSON
575
            data: {
576
                format: "json"
577
            },
578
            // Work with the response
579
            success: function( response ) {
580
                $('#loadingModal').modal('hide');
581
                if(response.success){           
582
                    $('#fav-'+$(that).data('id')).hide('slow');
583
                }
584
            }
585
        });
586
        ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
587
        var properties = {};
588
        properties.sku = String($(this).data('id'));
589
        pma.send('products','favourites','remove',me,properties);
590
    });
591
    $('.clearfavs').on('click',function(){
592
        var that = $(this);
593
        $('#loadingModal').modal();
594
        var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');           
595
        $.ajax({
596
            url: url,
597
            // The name of the callback parameter, as specified by the YQL service
598
            jsonp: "callback",
599
            // Tell jQuery we're expecting JSONP
600
            dataType: "jsonp",
601
            // Tell YQL what we want and that we want JSON
602
            data: {
603
                format: "json"
604
            },
605
            // Work with the response
606
            success: function( response ) {
607
                $('#loadingModal').modal('hide');
608
                if(response.success){           
609
                    $('.deletefav').each(function(){
610
                        $('#fav-'+$(this).data('id')).hide('slow');
611
                    })                  
612
                }
613
                $(that).hide();
614
            }
615
        });
616
        ga('send', 'event', 'favourites', 'removeall', me);
617
        pma.send('products','favourites','removeall',me);
618
    });
619
    $('.revealbrands').on('click',function(){
620
        $(this).parent().find('.notfeatured').toggleClass('hidden');
621
        if($(this).html()=='Others'){
622
            $(this).html('Hide');
623
        }else{
624
            $(this).html('Others');
625
        }
626
    });
627
    $(document).on('click','.showtips',function(){
628
        $('.apptips').toggleClass('hidden');
629
    });
630
    $(document).on('click','.creditedcashbacks',function(){
631
        if($(this).find('.glyphicon-plus',0).length>0){
632
            $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
633
        }else{
634
            $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
635
        }
636
        $(this).next().toggleClass('hidden');
637
    });
638
    $(document).on('click','.panel-heading a',function(){
639
        if($(this).find('.glyphicon-plus',0).length>0){
640
            $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
641
        }else{
642
            $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
643
        }
644
    });
645
    $(document).on('click','.prefcatselect',function(){
646
        $('.prefcatselect').removeClass('active')
647
        $(this).addClass('active');
648
        $('.categorypreferences').addClass('hidden');
649
        $('#cat-'+$(this).data('id')).toggleClass('hidden');
650
    });
651
    $(document).on('click','.refresh',function(){
652
        document.location.reload();
653
    });
654
    $(document).on('click','.hasmoretext',function(){
655
        $('#fulltext').html($(this).data('fulltext'));
656
        $('#fullTextModal').modal();
657
    });
658
    $(document).on('click','.favswitch',function(){
659
        $('.favswitch').removeClass('active')
660
        $(this).addClass('active');
661
        $('.clearfavs').addClass('hidden');
662
        $('.card').addClass('hidden');
663
        $('.'+$(this).data('type')).removeClass('hidden');
664
    });
665
    $(document).on('click','.brandpreferences .brands',function(){
666
        $(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
667
    });
668
    $(document).on('click','.tryagainforliveprice',function(){      
669
        fetchLivePrice($(this).parent());
670
        $(this).parent().html('Getting Live Prices');
671
    });
672
    $(document).on('click','.alert > a',function(){     
673
        ga('send', 'event', 'notifications', 'click', $(this).html());
674
        pma.send('notifications','click',$(this).html(),me);
675
    });
676
    $(document).on('click','.banner',function(){        
677
        ga('send', 'event', 'banners', 'click', $(this).data('name'));
678
        pma.send('banners','click',$(this).data('name'),me);
679
    });
13992 anikendra 680
});
15310 anikendra 681
function setCookie(cname, cvalue, days, forceCookie) {
18220 naman 682
    if(typeof(Storage) !== "undefined" && !forceCookie) {
683
        localStorage.setItem(cname, cvalue);
684
    } else{
685
        var d = new Date();
686
        d.setTime(d.getTime() + (days*24*60*60*1000));
687
        var expires = "expires="+d.toUTCString();
688
        document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
689
    }    
14849 anikendra 690
}
691
 
15310 anikendra 692
function getCookie(cname,forceCookie) {
18220 naman 693
    if(typeof(Storage) !== "undefined" && !forceCookie) {
694
        return localStorage.getItem(cname);
695
    } else {       
696
        var name = cname + "=";
697
        var ca = document.cookie.split(';');
698
        for(var i=0; i<ca.length; i++) {
699
            var c = ca[i];
700
            while (c.charAt(0)==' ') c = c.substring(1);
701
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
702
        }
703
        return "";
704
    }
14849 anikendra 705
}
15310 anikendra 706
 
16495 anikendra 707
function needToDisplayPaytmPopup(me){
18220 naman 708
    var id = 'tip'
709
    var cname = 'paytm-help-count-'+me+'-'+id;
710
    var cookieval = getCookie(cname,1);
711
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
712
        incrementPopupCount(id,0,'paytm-help-count-');
713
        return true;
714
    } else if(cookieval < 5) {
715
        incrementPopupCount(id,cookieval,'paytm-help-count-');
716
        return true;
717
    } else{
718
        return false;
719
    }
16495 anikendra 720
};
721
 
14849 anikendra 722
function showpopup(id,count,interval){
18220 naman 723
    var cname = 'notif-count-'+me+'-'+id;
724
    var cookieval = getCookie(cname,1);
725
    var cname = 'notif-lastshown-'+me+'-'+id;
726
    var lastshown = getCookie(cname,1);
727
    if(!cookieval || cookieval == 'NaN' || cookieval==''){      
728
        incrementPopupCount(id,0,'notif-count-');
729
        setLastShown(id,'notif-lastshown-');
730
        return true;
731
    } else{
732
        var d = new Date();
733
        var t = d.getTime();
734
        if(t-lastshown>interval*60*1000){
735
            if(cookieval>=count){
736
                return false;
737
            }else{
738
                setLastShown(id,'notif-lastshown-');
739
                incrementPopupCount(id,cookieval,'notif-count-');
740
                return true;    
741
            }
742
        }
743
    }
14849 anikendra 744
}
15077 anikendra 745
function setLastShown(id,cookiename){
18220 naman 746
    var cname = cookiename+me+'-'+id;
747
    var d = new Date();
748
    setCookie(cname, d.getTime(), 365, 1);
14849 anikendra 749
}
15077 anikendra 750
function incrementPopupCount(id,currentCount,cookiename) {
18220 naman 751
    var cname = cookiename+me+'-'+id;
752
    setCookie(cname, parseInt(currentCount)+1, 365, 1);
14858 anikendra 753
}
754
var hidden, visibilityChange; 
755
function handleVisibilityChange() {
756
  if (document[hidden]) {
18220 naman 757
    // pagetitle = document.title;
14858 anikendra 758
  } else {
18220 naman 759
    // document.title = pagetitle;
14858 anikendra 760
  }
761
}
762
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support 
763
  hidden = "hidden";
764
  visibilityChange = "visibilitychange";
765
} else if (typeof document.mozHidden !== "undefined") {
766
  hidden = "mozHidden";
767
  visibilityChange = "mozvisibilitychange";
768
} else if (typeof document.msHidden !== "undefined") {
769
  hidden = "msHidden";
770
  visibilityChange = "msvisibilitychange";
771
} else if (typeof document.webkitHidden !== "undefined") {
772
  hidden = "webkitHidden";
773
  visibilityChange = "webkitvisibilitychange";
774
}
775
if (typeof document.addEventListener === "undefined" || 
776
  typeof document[hidden] === "undefined") {
18119 amit.gupta 777
  //console.log("This feature requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
14858 anikendra 778
} else {
779
  // Handle page visibility change   
780
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
781
}    
14936 anikendra 782
$('.notificationok').on('click',function(e){
18220 naman 783
    e.preventDefault();
784
    $('.notificationmodal').modal('hide');
785
    // setTimeout(function(){ $('.notificationmodal').modal('hide'); }, 1000);
786
    ga('send', 'event', 'popupnotification-'+$(this).parent().data('id'), 'ok', me);
787
    var properties = {};
788
    properties.id = String($(this).parent().data('id'));
789
    pma.send('popupnotification','click','ok',me,properties);
790
    document.location = $(this).parent().prop('href');
15015 anikendra 791
});
18220 naman 792
$(document).on('click','.clearfilter',function(){   
793
    $('.filterbrand').each(function(){
794
        $(this).prop('checked',false);
795
    }); 
796
    ga('send', 'event', 'filter', 'brand', 'reset');
797
    pma.send('filters','brands','reset',me);
15015 anikendra 798
});
17691 naman 799
 
18220 naman 800
$(document).on('click','.clearfiltersubcategory',function(){    
801
    $('.filtersubcategory').each(function(){
802
        $(this).prop('checked',false);
803
    }); 
804
    ga('send', 'event', 'filter', 'subcategory', 'reset');
805
    pma.send('filters','subcategory','reset',me);
17691 naman 806
});
18391 naman 807
 
808
function getJsonFromUrl() {
809
	  var query = location.search.substr(1);
810
	  var result = {};
811
	  query.split("&").forEach(function(part) {
812
	    var item = part.split("=");
813
	    result[item[0]] = decodeURIComponent(item[1]);
814
	  });
815
	  return result;
816
	}
817
 
818
$(document).on('click','.applyfilter',function(){
819
	var str = window.location.search;
820
    var urlplus = '';
821
    var urldet = getJsonFromUrl();
822
 
18220 naman 823
    $(this).prop('disabled',true);
824
    $('#loadingModal').modal();
825
    var brands = [];
826
    var brandnames = [];
827
    var subcategories = [];
828
    var subcatnames = [];
829
    $('.filterbrand').each(function(){
830
        if($(this).prop('checked')){
831
            brands.push($(this).val());
832
            brandnames.push($(this).parent().siblings('.brandname').html());
833
        }       
834
    });
835
 
836
    $('.filtersubcategory').each(function(){
837
        if($(this).prop('checked')){
838
            subcategories.push($(this).val());
839
            subcatnames.push($(this).parent().siblings('.subcategoryname').html());
840
        }
841
    });
18391 naman 842
 
843
    if($("#brandselecter").length == 0 && urldet['brands'] != undefined && urldet['brands'] != ''){
844
    	brands = urldet['brands'];
845
    }
846
    if($("#subcategoryselecter").length == 0 && urldet['subcategories'] != undefined && urldet['subcategories'] != ''){
847
    	subcategories = urldet['subcategories'];
848
    }
849
 
17691 naman 850
 
18391 naman 851
        if(brands.length==0 && subcategories.length==0){
852
        	$('#loadingModal').modal('hide');
853
//        	$('clearfilters').click();
854
//        	setCookie('brandschosen', '', -1, true);
855
//            setCookie('subcategorieschosen','',-1, true);	
856
        	var url = '';
857
        	if($('#brandselecter').prop('action') !== undefined )
858
        	{
859
        		url = $('#brandselecter').prop('action'); 
860
        	}
861
        	if($('#subcategoryselecter').prop('action') !== undefined )
862
        	{
863
        		url = $('#subcategoryselecter').prop('action'); 
864
        	}
865
        	document.location = url; 
866
 
867
//            $('#message').html('Please choose a few brands/subcategories first').removeClass('hidden');
868
//            setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
869
//            $(this).prop('disabled',false);
870
//            return false;
871
        }else if(brands.length==0 && subcategories.length>0 ){
872
//            setCookie('subcategorieschosen', subcategories, 0.25, true);
873
            var url = $('#subcategoryselecter').prop('action');
874
            ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
875
            properties = {};
876
            for(var i in subcatnames){
877
                properties['subcategories_'+i] = subcatnames[i];
878
            }
879
            pma.send('filters','subcategories','addfilter',me,properties);
880
            var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
881
            $.post( "/user_filters/add", postdata, function( data ) {
882
                $('#loadingModal').modal('hide');
883
                $(this).prop('disabled',false);
884
                document.location = url+'&subcategories='+subcategories.join('^');
885
            }); 
886
        }else if(brands.length>0 && subcategories.length==0 ){
887
//            setCookie('brandschosen', brands, 0.25, true);
888
            var url = $('#brandselecter').prop('action');
889
            ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
890
            properties = {};
891
            for(var i in brandnames){
892
                properties['brand_'+i] = brandnames[i];
893
            }
894
            pma.send('filters','brands','addfilter',me,properties);
895
            var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
896
            $.post( "/user_filters/add", postdata, function( data ) {
897
                $('#loadingModal').modal('hide');
898
                $(this).prop('disabled',false);
899
                document.location = url+'&brands='+brands.join('^');
900
            });     
901
        }else if(brands.length>0 && subcategories.length>0 ){
902
            setCookie('brandschosen', brands, 0.25, true);
903
            setCookie('subcategorieschosen', subcategories, 0.25, true);
904
            var url = $('#brandselecter').prop('action');
905
            ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
906
            ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
907
            properties = {};
908
            for(var i in brandnames){
909
                properties['brand_'+i] = brandnames[i];
910
            }
911
            for(var i in subcatnames){
912
                properties['subcategory_'+i] = subcatnames[i];
913
            }
914
            pma.send('filters','brandsnsubcategories','addfilter',me,properties);
915
            var dataStr = brandnames.join('|');
916
            dataStr = dataStr + subcatnames.join('|');
917
            var postdata = {'user_id':me,'type':'brandnsubcategory','filters':dataStr};
918
            $.post( "/user_filters/add", postdata, function( data ) {
919
                $('#loadingModal').modal('hide');
920
                $(this).prop('disabled',false);
921
                if($("#brandselecter").length == 0 && urldet['brands'] != undefined && urldet['brands'] != ''){
922
                	url = $("#subcategoryselecter").prop('action');
923
                	brands = urldet['brands'];
924
                	document.location = url.split('?')[0]+'?brands='+brands+"&subcategories="+subcategories.join("^");
925
                }
926
                else if($("#subcategoryselecter").length == 0 && urldet['subcategories'] != undefined && urldet['subcategories'] != ''){
927
                	url = $('#brandselecter').prop('action');
928
                	subcategories = urldet['subcategories'];
929
                	document.location = url.split('?')[0]+'?brands='+brands.join('^')+"&subcategories="+subcategories;
930
                }
931
//                document.location = url+'&brands='+brands.join('^')+"&subcategories="+subcategories.join("^");
932
            });
18220 naman 933
        }
18391 naman 934
//    }
17691 naman 935
 
18391 naman 936
 
18220 naman 937
    /*if(brands.length==0){
938
        $('#loadingModal').modal('hide');
939
        $('#message').html('Please choose a few brands first').removeClass('hidden');
940
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
941
        $(this).prop('disabled',false);
942
        return false;
943
    }else{
944
        setCookie('brandschosen', brands, 0.25, true);
945
        var url = $('#brandselecter').prop('action');
946
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
947
        properties = {};
948
        for(var i in brandnames){
949
            properties['brand_'+i] = brandnames[i];
950
        }
951
        pma.send('filters','brands','addfilter',me,properties);
952
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
953
        $.post( "/user_filters/add", postdata, function( data ) {
954
            $('#loadingModal').modal('hide');
955
            $(this).prop('disabled',false);
956
            document.location = url+'&brands='+brands.join('^');
957
        });     
958
    }
17691 naman 959
 
18220 naman 960
    if(subcategories.length==0){
961
        $('#loadingModal').modal('hide');
962
        $('#message').html('Please choose a few Sub-categories first').removeClass('hidden');
963
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
964
        $(this).prop('disabled',false);
965
        return false;
966
    }else{
967
        setCookie('subcategorieschosen', subcategories, 0.25, true);
968
        var url = $('#subcategoryselecter').prop('action');
969
        ga('send', 'event', 'filter', 'subcategory', brandnames.join('|'));
970
        properties = {};
971
        for(var i in brandnames){
972
            properties['brand_'+i] = brandnames[i];
973
        }
974
        pma.send('filters','subcategories','addfilter',me,properties);
975
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
976
        $.post( "/user_filters/add", postdata, function( data ) {
977
            $('#loadingModal').modal('hide');
978
            $(this).prop('disabled',false);
979
            document.location = url+'&brands='+brands.join('^');
980
        });     
981
    }*/ 
15015 anikendra 982
});
18066 naman 983
 
984
 
18220 naman 985
$(document).on('click','#showallbrands',function(){ 
986
    $('.brand').removeClass('hidden');
18066 naman 987
    $('.subcategory').removeClass('hidden');
18220 naman 988
    $(this).hide();
15019 anikendra 989
});
18220 naman 990
$(document).on('input','#brandfilter',function(){   
991
    $('.brand').addClass('hidden');
992
    $('#showallbrands').hide();
993
    var that = $(this);
994
    $('li.brand').filter(function() { 
995
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
996
    }).removeClass('hidden','slow');
15042 anikendra 997
});
17707 naman 998
 
18220 naman 999
$(document).on('input','#subcatfilter',function(){  
1000
    $('.subcategory').addClass('hidden');
1001
    $('#showallbrands').hide();
1002
    var that = $(this);
1003
    $('li.subcategory').filter(function() { 
1004
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
1005
    }).removeClass('hidden','slow');
17707 naman 1006
});
1007
 
1008
 
15077 anikendra 1009
$(document).on('click','.filterbrand',function(){
18220 naman 1010
    var clicked = $(this).parent().parent();
1011
    // all the LIs above the clicked one
1012
    var previousAll = clicked.prevAll();
15042 anikendra 1013
 
18220 naman 1014
    // only proceed if it's not already on top (no previous siblings)
1015
    if(previousAll.length > 0) {
1016
    // top LI
1017
    var top = $(previousAll[previousAll.length - 1]);
15042 anikendra 1018
 
18220 naman 1019
    // immediately previous LI
1020
    var previous = $(previousAll[0]);
15042 anikendra 1021
 
18220 naman 1022
    // how far up do we need to move the clicked LI?
1023
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
15042 anikendra 1024
 
18220 naman 1025
    // how far down do we need to move the previous siblings?
1026
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
15042 anikendra 1027
 
18220 naman 1028
    // let's move stuff
1029
    clicked.css('position', 'relative');
1030
    previousAll.css('position', 'relative');
1031
    clicked.animate({'top': -moveUp});
1032
    previousAll.animate({'top': moveDown}, {complete: function() {
1033
      // rearrange the DOM and restore positioning when we're done moving
1034
      clicked.parent().prepend(clicked);
1035
      clicked.css({'position': 'static', 'top': 0});
1036
      previousAll.css({'position': 'static', 'top': 0}); 
1037
    }});
1038
    }
15042 anikendra 1039
})
17691 naman 1040
$(document).on('click','.filtersubcategory',function(){
18220 naman 1041
    var clicked = $(this).parent().parent();
1042
    // all the LIs above the clicked one
1043
    var previousAll = clicked.prevAll();
17691 naman 1044
 
18220 naman 1045
    // only proceed if it's not already on top (no previous siblings)
1046
    if(previousAll.length > 0) {
1047
    // top LI
1048
    var top = $(previousAll[previousAll.length - 1]);
17691 naman 1049
 
18220 naman 1050
    // immediately previous LI
1051
    var previous = $(previousAll[0]);
17691 naman 1052
 
18220 naman 1053
    // how far up do we need to move the clicked LI?
1054
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
17691 naman 1055
 
18220 naman 1056
    // how far down do we need to move the previous siblings?
1057
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
17691 naman 1058
 
18220 naman 1059
    // let's move stuff
1060
    clicked.css('position', 'relative');
1061
    previousAll.css('position', 'relative');
1062
    clicked.animate({'top': -moveUp});
1063
    previousAll.animate({'top': moveDown}, {complete: function() {
1064
      // rearrange the DOM and restore positioning when we're done moving
1065
      clicked.parent().prepend(clicked);
1066
      clicked.css({'position': 'static', 'top': 0});
1067
      previousAll.css({'position': 'static', 'top': 0}); 
1068
    }});
1069
    }
17691 naman 1070
})
15042 anikendra 1071
$(document).on('click','.clearfilters',function(){
18391 naman 1072
//    setCookie('brandschosen', '', -1, true);
1073
//    setCookie('subcategorieschosen','',-1, true);
18220 naman 1074
    ga('send', 'event', 'filter', 'brand', 'clearfilters');
1075
    ga('send', 'event', 'filter', 'subcategory', 'clearfilters');
1076
    pma.send('filters','brands','clearfilters',me);
1077
    pma.send('filters','subcategory','clearfilters',me);
1078
    var postdata = {'user_id':me,'type':'clear'};
1079
    $('#loadingModal').modal('show');
1080
    $.post("/user_filters/add", postdata, function( data ) {        
1081
        // document.location.reload();
1082
        window.location.replace(window.location.href.split('?')[0]);
1083
    }); 
15042 anikendra 1084
});
1085
function selectChosenBrands(){
18391 naman 1086
 
1087
    var urldet = getJsonFromUrl();
1088
 
1089
    if (urldet['brands'] !=undefined && urldet['brands'] !="") {
1090
    	var brands = urldet['brands'].split('^');
1091
	        for(var i in brands){
1092
	        	$('[data-brandid="'+brands[i]+'"]').removeClass('hidden').find('.filterbrand',0).trigger( "click" );
1093
	        }
1094
    	}
1095
 
1096
    if (urldet['subcategories'] != undefined && urldet['subcategories'] != "") {
1097
    	var subcategories = urldet['subcategories'].split('^');
1098
    	for(var i in subcategories){
1099
	            $('.subcategory').filter(function() { 
1100
	                return $(this).data("brandid") == subcategories[i];
1101
	            }).removeClass('hidden').find('.filtersubcategory',0).trigger( "click" );
1102
	        }
1103
    	}
1104
 
15065 anikendra 1105
}
18190 amit.gupta 1106
 
1107
function clearFilters(){
1108
	setCookie('brandschosen', '', -1, true);
1109
	setCookie('subcategorieschosen','',-1, true);
1110
}
15585 anikendra 1111
function showPosition(position) {
15586 anikendra 1112
    setCookie('latitude',position.coords.latitude,1,true); 
18220 naman 1113
    setCookie('longitude',position.coords.longitude,1,true);    
15585 anikendra 1114
}
15065 anikendra 1115
$(function () {
18115 amit.gupta 1116
	$("#popovertrigger5").popover('hide').remove();
18033 amit.gupta 1117
	$('.data-up:first').append('<a id="popovertrigger5"  data-container="body" data-toggle="popover" data-placement="left" data-content="Quick buy multiple items together"></a>');
18191 amit.gupta 1118
	setPopOver("popovertrigger5", ".plusqtybutton", 'click', 3000);
18023 amit.gupta 1119
	callBackFunction = function(){
1120
		return document.location.pathname=="/category/6";		
1121
	};
18191 amit.gupta 1122
	setPopOver("popovertrigger4", callBackFunction,undefined,3000);
18115 amit.gupta 1123
	//$('[data-toggle="popover"]#'+id).popover('show');
18023 amit.gupta 1124
	if (navigator.geolocation) {
1125
        navigator.geolocation.getCurrentPosition(showPosition);
1126
    } 
1127
});
1128
 
18176 amit.gupta 1129
function setPopOver(poid, callBack1, eventString, fadeAfter){
15310 anikendra 1130
	var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 1131
	var cookieval = getCookie(cname,1);
18023 amit.gupta 1132
	if(typeof callBack1=="function"){
1133
		if (callBack1()){
1134
			var cname = 'popover-count-'+me+'-'+poid;
1135
			var cookieval = getCookie(cname,1);
1136
			$('#' + poid).popover('hide');
1137
			if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1138
				incrementPopupCount(poid,0,'popover-count-');
1139
			} else if(cookieval > 0) {
1140
				incrementPopupCount(poid, cookieval, 'popover-count-');
1141
			}
1142
			setLastShown(poid,'popover-lastshown-');
15310 anikendra 1143
		}
18023 amit.gupta 1144
	} else {
1145
		$('div.content').on(eventString, callBack1, function(){
1146
			var cname = 'popover-count-'+me+'-'+poid;
1147
			var cookieval = getCookie(cname,1);
1148
			$('#' + poid).popover('hide');
1149
			if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1150
				incrementPopupCount(poid,0,'popover-count-');
1151
			} else if(cookieval > 0) {
1152
				incrementPopupCount(poid, cookieval, 'popover-count-');
1153
			}
1154
			setLastShown(poid,'popover-lastshown-');
1155
		}); 
18008 amit.gupta 1156
	}
18176 amit.gupta 1157
 
1158
	if(typeof fadeAfter!="undefined"){
18181 amit.gupta 1159
		var s = setInterval(function(){
1160
			if($('#' + poid +':in-viewport').length>0) {
1161
				setTimeout(function(){
1162
					$('#' + poid).popover('hide');
1163
				}, fadeAfter);
1164
				clearInterval(s);
1165
			}
1166
		}, 2000);
18176 amit.gupta 1167
	}
15310 anikendra 1168
 
15077 anikendra 1169
	var cname = 'popover-lastshown-'+me+'-'+poid;
15721 anikendra 1170
	var lastshown = getCookie(cname,1);
15310 anikendra 1171
	if(cookieval=='' || cookieval == 'NaN' || !cookieval){				
15077 anikendra 1172
		showpopover(poid);
15521 anikendra 1173
	} 
1174
	//Donot show popover anymore as long as we don't find a suitable solution
15721 anikendra 1175
	else{
15077 anikendra 1176
		var d = new Date();
1177
		var t = d.getTime();
15085 anikendra 1178
		if(t-lastshown>18*3600*1000){
15310 anikendra 1179
			if(cookieval>=2){
15077 anikendra 1180
				return false;
1181
			}else{
15310 anikendra 1182
				showpopover(poid);				
15077 anikendra 1183
			}
1184
		}
15721 anikendra 1185
	}
15583 anikendra 1186
	ga('send', 'event', 'popover', me, cookieval);
18023 amit.gupta 1187
}
16656 anikendra 1188
$('.getapp').on('click',function(){
18220 naman 1189
    /*var that = $(this);
1190
    var req = $.ajax({
1191
        url: 'http://104.200.25.40:8057/appAffiliates/generateRedirectUrl/'+me+'/'+$(that).data('id'),
1192
        // Tell jQuery we're expecting JSONP
1193
        dataType: "jsonp",
1194
        // Tell YQL what we want and that we want JSON          
1195
        method: 'get',
1196
        // timeout: 30000,
1197
        // Work with the response
1198
        success: function( response ) {
1199
            console.log(response);
1200
        }
1201
    });*/
1202
    $('#loadingModal').modal('show');
1203
    document.location = '/abouts/apphint';
16656 anikendra 1204
});
15077 anikendra 1205
function showpopover(id){
18220 naman 1206
    try {
1207
        $('[data-toggle="popover"]#'+id).popover({html:true,viewport:{container:'body'}, trigger:'manual'});
1208
        $('[data-toggle="popover"]#'+id).popover('show');       
1209
    }catch(err){
1210
        //
1211
    }
15085 anikendra 1212
}
1213
$(document).on('click','.nodeals',function(){
18220 naman 1214
    document.location = $(this).data('href');
16018 anikendra 1215
});
1216
$(document).on('click','.selectbrand',function(e){
18220 naman 1217
    e.preventDefault();
1218
    var brands = $(this).data('id');
1219
    var brandname = $(this).html();
1220
    //console.log(brandname);
17703 naman 1221
 
18391 naman 1222
//    setCookie('brandschosen', brands, 1, true);
18220 naman 1223
    var url = $(this).data('href');
1224
    ga('send', 'event', 'selectbrand', 'brand', brandname);
1225
    properties = {};
1226
    properties['brand'] = brandname;
1227
    pma.send('filters','brands','selectbrand',me,properties);
1228
    var postdata = {'user_id':me,'type':'brand','filters':brandname};
1229
    $.post( "/user_filters/add", postdata, function( data ) {
1230
        $('#loadingModal').modal('hide');
1231
        $(this).addClass('activebrand');
18391 naman 1232
//        document.location = url+'&brands='+brands;
1233
        document.location = url;
18220 naman 1234
    });
16018 anikendra 1235
});
17703 naman 1236
 
1237
 
18391 naman 1238
 
16495 anikendra 1239
$(document).on('click','.shownexttip',function(e){
18220 naman 1240
    $(this).addClass('hidden').remove();
1241
    $('#firsttip').addClass('hidden').remove();
1242
    $('#secondtip').removeClass('hidden');
1243
    $('.gotit').removeClass('hidden');
16495 anikendra 1244
});
15128 anikendra 1245
var Base64 = {
1246
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
1247
    encode: function(input) {
1248
        var output = "";
1249
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
1250
        var i = 0;
1251
        input = Base64._utf8_encode(input);
1252
        while (i < input.length) {
1253
            chr1 = input.charCodeAt(i++);
1254
            chr2 = input.charCodeAt(i++);
1255
            chr3 = input.charCodeAt(i++);
1256
 
1257
            enc1 = chr1 >> 2;
1258
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
1259
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
1260
            enc4 = chr3 & 63;
1261
            if (isNaN(chr2)) {
1262
                enc3 = enc4 = 64;
1263
            } else if (isNaN(chr3)) {
1264
                enc4 = 64;
1265
            }
1266
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
1267
        }
1268
        return output;
1269
    },
1270
 
1271
 
1272
    decode: function(input) {
1273
        var output = "";
1274
        var chr1, chr2, chr3;
1275
        var enc1, enc2, enc3, enc4;
1276
        var i = 0;
1277
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
1278
        while (i < input.length) {
1279
            enc1 = this._keyStr.indexOf(input.charAt(i++));
1280
            enc2 = this._keyStr.indexOf(input.charAt(i++));
1281
            enc3 = this._keyStr.indexOf(input.charAt(i++));
1282
            enc4 = this._keyStr.indexOf(input.charAt(i++));
1283
            chr1 = (enc1 << 2) | (enc2 >> 4);
1284
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
1285
            chr3 = ((enc3 & 3) << 6) | enc4;
1286
            output = output + String.fromCharCode(chr1);
1287
            if (enc3 != 64) {
1288
                output = output + String.fromCharCode(chr2);
1289
            }
1290
            if (enc4 != 64) {
1291
                output = output + String.fromCharCode(chr3);
1292
            }
1293
        }
1294
        output = Base64._utf8_decode(output);
1295
        return output;
1296
    },
1297
 
1298
    _utf8_encode: function(string) {
1299
        string = string.replace(/\r\n/g, "\n");
1300
        var utftext = "";
1301
        for (var n = 0; n < string.length; n++) {
1302
            var c = string.charCodeAt(n);
1303
            if (c < 128) {
1304
                utftext += String.fromCharCode(c);
1305
            }
1306
            else if ((c > 127) && (c < 2048)) {
1307
                utftext += String.fromCharCode((c >> 6) | 192);
1308
                utftext += String.fromCharCode((c & 63) | 128);
1309
            }
1310
            else {
1311
                utftext += String.fromCharCode((c >> 12) | 224);
1312
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
1313
                utftext += String.fromCharCode((c & 63) | 128);
1314
            }
1315
        }
1316
        return utftext;
1317
    },
1318
 
1319
    _utf8_decode: function(utftext) {
1320
        var string = "";
1321
        var i = 0;
1322
        var c = c1 = c2 = 0;
1323
        while (i < utftext.length) {
1324
            c = utftext.charCodeAt(i);
1325
            if (c < 128) {
1326
                string += String.fromCharCode(c);
1327
                i++;
1328
            }
1329
            else if ((c > 191) && (c < 224)) {
1330
                c2 = utftext.charCodeAt(i + 1);
1331
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
1332
                i += 2;
1333
            }
1334
            else {
1335
                c2 = utftext.charCodeAt(i + 1);
1336
                c3 = utftext.charCodeAt(i + 2);
1337
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
1338
                i += 3;
1339
            }
1340
        }
1341
        return string;
1342
    }
15550 anikendra 1343
}
1344
 
1345
 
1346
var pma = new function() {
15584 anikendra 1347
    this.apiurl = "http://45.33.50.227:8081/";
15550 anikendra 1348
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};
1349
 
1350
    this.send = function (category,action,label,user_id,properties) {
18220 naman 1351
        if(!properties){
1352
            properties = {};
1353
        }
1354
        properties.location = window.location.href;
1355
        // properties.appCodeName = navigator.appCodeName;
1356
        // properties.appName = navigator.appName;
1357
        // properties.appVersion = navigator.appVersion;
1358
        properties.cookieEnabled = String(navigator.cookieEnabled);
1359
        properties.platform = navigator.platform;
1360
        properties.userAgent = navigator.userAgent;
1361
        properties.ip = ip;
1362
        if (navigator.geolocation) {
1363
            if(getCookie('latitude',true)){
1364
                properties.latitude = getCookie('latitude');
1365
            }           
1366
            if(getCookie('longitude',true)){
1367
                properties.longitude = getCookie('longitude');
1368
            }
1369
        }
1370
        properties.screenHeight = String(screen.height);
1371
        properties.screenWidth = String(screen.width);
1372
        // console.log(properties);
1373
        $.ajax({
1374
            url: this.apiurl + this.endpoints.track,
1375
            data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
1376
            // Tell jQuery we're expecting JSONP
1377
            dataType: "json",
1378
            // Tell YQL what we want and that we want JSON          
1379
            method: 'post',
1380
            // Work with the response
1381
            success: function( response ) {
1382
                //Well, well, well :)
1383
            }
1384
        });       
15550 anikendra 1385
    };
1386
 
1387
    this.formDataToObject = function(formdata){
18220 naman 1388
        var properties = {};
1389
        var keys = [];
1390
        var formdata = JSON.parse(JSON.stringify(formdata));
1391
        for (var i in formdata) {
1392
            var key = formdata[i].name;
1393
            if(index = keys.indexOf(key)==-1){
1394
                properties[key] = formdata[i].value;
1395
            }else{
1396
                properties[key+'_'+i] = formdata[i].value;
1397
            }
1398
            keys.push(key);
1399
        };
1400
        return properties;
1401
    }
16704 anikendra 1402
}
1403
//App page
1404
$.fn.stars = function() {
1405
    return $(this).each(function() {
1406
        // Get the value
1407
        var val = parseFloat($(this).html());
1408
        // Make sure that the value is in 0 - 5 range, multiply to get width
1409
        val = Math.round(val * 2) / 2;
1410
        var size = Math.max(0, (Math.min(5, val))) * 16;
1411
        // Create stars holder
1412
        var $span = $('<span />').width(size);
1413
        // Replace the numerical value with stars
1414
        $(this).html($span);
1415
    });
1416
}
1417
$(function() {
18220 naman 1418
    $('span.stars').stars();    
18023 amit.gupta 1419
});
1420
 
1421
function sendCartChangeEvent(){
18220 naman 1422
    var cart_details_old = localStorage.getItem('cart_details_old');
1423
    var cart_details = localStorage.getItem('cart_details');
1424
    if (cart_details_old == cart_details){
1425
        return;
1426
    } else if(cart_details!=null){
1427
        JSON.parse(cart_details);
1428
 
1429
    }
18023 amit.gupta 1430
}
1431
 
1432
//setInterval(30000, )