Subversion Repositories SmartDukaan

Rev

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