Subversion Repositories SmartDukaan

Rev

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