Subversion Repositories SmartDukaan

Rev

Rev 18391 | Rev 18401 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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