Subversion Repositories SmartDukaan

Rev

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