Subversion Repositories SmartDukaan

Rev

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