Subversion Repositories SmartDukaan

Rev

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