Subversion Repositories SmartDukaan

Rev

Rev 18325 | Rev 18391 | 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){
18364 naman 822
    	$('#loadingModal').modal('hide');
823
    	setCookie('brandschosen', '', -1, true);
824
        setCookie('subcategorieschosen','',-1, true);	
825
    	var url = '';
826
    	if($('#brandselecter').prop('action') !== undefined )
827
    	{
828
    		url = $('#brandselecter').prop('action'); 
829
    	}
830
    	if($('#subcategoryselecter').prop('action') !== undefined )
831
    	{
832
    		url = $('#subcategoryselecter').prop('action'); 
833
    	}
834
    	document.location = url;
835
//        $('#loadingModal').modal('hide');
836
//        $('#message').html('Please choose a few brands/subcategories first').removeClass('hidden');
837
//        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
838
//        $(this).prop('disabled',false);
839
//        return false;
18220 naman 840
    }else if(brands.length==0 && subcategories.length>0 ){
841
        setCookie('subcategorieschosen', subcategories, 0.25, true);
842
        var url = $('#subcategoryselecter').prop('action');
843
        ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
844
        properties = {};
845
        for(var i in subcatnames){
846
            properties['subcategories_'+i] = subcatnames[i];
847
        }
848
        pma.send('filters','subcategories','addfilter',me,properties);
849
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
850
        $.post( "/user_filters/add", postdata, function( data ) {
851
            $('#loadingModal').modal('hide');
852
            $(this).prop('disabled',false);
853
            document.location = url+'&subcategories='+subcategories.join('^');
854
        }); 
855
    }else if(brands.length>0 && subcategories.length==0 ){
856
        setCookie('brandschosen', brands, 0.25, true);
857
        var url = $('#brandselecter').prop('action');
858
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
859
        properties = {};
860
        for(var i in brandnames){
861
            properties['brand_'+i] = brandnames[i];
862
        }
863
        pma.send('filters','brands','addfilter',me,properties);
864
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
865
        $.post( "/user_filters/add", postdata, function( data ) {
866
            $('#loadingModal').modal('hide');
867
            $(this).prop('disabled',false);
868
            document.location = url+'&brands='+brands.join('^');
869
        });     
870
    }else if(brands.length>0 && subcategories.length>0 ){
871
        setCookie('brandschosen', brands, 0.25, true);
872
        setCookie('subcategorieschosen', subcategories, 0.25, true);
873
        var url = $('#brandselecter').prop('action');
874
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
875
        ga('send', 'event', 'filter', 'subcategory', subcatnames.join('|'));
876
        properties = {};
877
        for(var i in brandnames){
878
            properties['brand_'+i] = brandnames[i];
879
        }
880
        for(var i in subcatnames){
881
            properties['subcategory_'+i] = subcatnames[i];
882
        }
883
        pma.send('filters','brandsnsubcategories','addfilter',me,properties);
884
        var dataStr = brandnames.join('|');
885
        dataStr = dataStr + subcatnames.join('|');
886
        var postdata = {'user_id':me,'type':'brandnsubcategory','filters':dataStr};
887
        $.post( "/user_filters/add", postdata, function( data ) {
888
            $('#loadingModal').modal('hide');
889
            $(this).prop('disabled',false);
890
            document.location = url+'&brands='+brands.join('^')+"&subcategories="+subcategories.join("^");
891
        });
892
    }
17691 naman 893
 
18220 naman 894
    /*if(brands.length==0){
895
        $('#loadingModal').modal('hide');
896
        $('#message').html('Please choose a few brands first').removeClass('hidden');
897
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
898
        $(this).prop('disabled',false);
899
        return false;
900
    }else{
901
        setCookie('brandschosen', brands, 0.25, true);
902
        var url = $('#brandselecter').prop('action');
903
        ga('send', 'event', 'filter', 'brand', brandnames.join('|'));
904
        properties = {};
905
        for(var i in brandnames){
906
            properties['brand_'+i] = brandnames[i];
907
        }
908
        pma.send('filters','brands','addfilter',me,properties);
909
        var postdata = {'user_id':me,'type':'brand','filters':brandnames.join('|')};
910
        $.post( "/user_filters/add", postdata, function( data ) {
911
            $('#loadingModal').modal('hide');
912
            $(this).prop('disabled',false);
913
            document.location = url+'&brands='+brands.join('^');
914
        });     
915
    }
17691 naman 916
 
18220 naman 917
    if(subcategories.length==0){
918
        $('#loadingModal').modal('hide');
919
        $('#message').html('Please choose a few Sub-categories first').removeClass('hidden');
920
        setTimeout(function(){ $('#message').addClass('hidden'); }, 3000);
921
        $(this).prop('disabled',false);
922
        return false;
923
    }else{
924
        setCookie('subcategorieschosen', subcategories, 0.25, true);
925
        var url = $('#subcategoryselecter').prop('action');
926
        ga('send', 'event', 'filter', 'subcategory', brandnames.join('|'));
927
        properties = {};
928
        for(var i in brandnames){
929
            properties['brand_'+i] = brandnames[i];
930
        }
931
        pma.send('filters','subcategories','addfilter',me,properties);
932
        var postdata = {'user_id':me,'type':'subcategory','filters':subcatnames.join('|')};
933
        $.post( "/user_filters/add", postdata, function( data ) {
934
            $('#loadingModal').modal('hide');
935
            $(this).prop('disabled',false);
936
            document.location = url+'&brands='+brands.join('^');
937
        });     
938
    }*/ 
15015 anikendra 939
});
18066 naman 940
 
941
 
18220 naman 942
$(document).on('click','#showallbrands',function(){ 
943
    $('.brand').removeClass('hidden');
18066 naman 944
    $('.subcategory').removeClass('hidden');
18220 naman 945
    $(this).hide();
15019 anikendra 946
});
18220 naman 947
$(document).on('input','#brandfilter',function(){   
948
    $('.brand').addClass('hidden');
949
    $('#showallbrands').hide();
950
    var that = $(this);
951
    $('li.brand').filter(function() { 
952
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
953
    }).removeClass('hidden','slow');
15042 anikendra 954
});
17707 naman 955
 
18220 naman 956
$(document).on('input','#subcatfilter',function(){  
957
    $('.subcategory').addClass('hidden');
958
    $('#showallbrands').hide();
959
    var that = $(this);
960
    $('li.subcategory').filter(function() { 
961
      return $(this).data("brand").toLowerCase().indexOf($(that).val().toLowerCase()) != -1;
962
    }).removeClass('hidden','slow');
17707 naman 963
});
964
 
965
 
15077 anikendra 966
$(document).on('click','.filterbrand',function(){
18220 naman 967
    var clicked = $(this).parent().parent();
968
    // all the LIs above the clicked one
969
    var previousAll = clicked.prevAll();
15042 anikendra 970
 
18220 naman 971
    // only proceed if it's not already on top (no previous siblings)
972
    if(previousAll.length > 0) {
973
    // top LI
974
    var top = $(previousAll[previousAll.length - 1]);
15042 anikendra 975
 
18220 naman 976
    // immediately previous LI
977
    var previous = $(previousAll[0]);
15042 anikendra 978
 
18220 naman 979
    // how far up do we need to move the clicked LI?
980
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
15042 anikendra 981
 
18220 naman 982
    // how far down do we need to move the previous siblings?
983
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
15042 anikendra 984
 
18220 naman 985
    // let's move stuff
986
    clicked.css('position', 'relative');
987
    previousAll.css('position', 'relative');
988
    clicked.animate({'top': -moveUp});
989
    previousAll.animate({'top': moveDown}, {complete: function() {
990
      // rearrange the DOM and restore positioning when we're done moving
991
      clicked.parent().prepend(clicked);
992
      clicked.css({'position': 'static', 'top': 0});
993
      previousAll.css({'position': 'static', 'top': 0}); 
994
    }});
995
    }
15042 anikendra 996
})
17691 naman 997
$(document).on('click','.filtersubcategory',function(){
18220 naman 998
    var clicked = $(this).parent().parent();
999
    // all the LIs above the clicked one
1000
    var previousAll = clicked.prevAll();
17691 naman 1001
 
18220 naman 1002
    // only proceed if it's not already on top (no previous siblings)
1003
    if(previousAll.length > 0) {
1004
    // top LI
1005
    var top = $(previousAll[previousAll.length - 1]);
17691 naman 1006
 
18220 naman 1007
    // immediately previous LI
1008
    var previous = $(previousAll[0]);
17691 naman 1009
 
18220 naman 1010
    // how far up do we need to move the clicked LI?
1011
    var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
17691 naman 1012
 
18220 naman 1013
    // how far down do we need to move the previous siblings?
1014
    var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
17691 naman 1015
 
18220 naman 1016
    // let's move stuff
1017
    clicked.css('position', 'relative');
1018
    previousAll.css('position', 'relative');
1019
    clicked.animate({'top': -moveUp});
1020
    previousAll.animate({'top': moveDown}, {complete: function() {
1021
      // rearrange the DOM and restore positioning when we're done moving
1022
      clicked.parent().prepend(clicked);
1023
      clicked.css({'position': 'static', 'top': 0});
1024
      previousAll.css({'position': 'static', 'top': 0}); 
1025
    }});
1026
    }
17691 naman 1027
})
15042 anikendra 1028
$(document).on('click','.clearfilters',function(){
18220 naman 1029
    setCookie('brandschosen', '', -1, true);
1030
    setCookie('subcategorieschosen','',-1, true);
1031
    ga('send', 'event', 'filter', 'brand', 'clearfilters');
1032
    ga('send', 'event', 'filter', 'subcategory', 'clearfilters');
1033
    pma.send('filters','brands','clearfilters',me);
1034
    pma.send('filters','subcategory','clearfilters',me);
1035
    var postdata = {'user_id':me,'type':'clear'};
1036
    $('#loadingModal').modal('show');
1037
    $.post("/user_filters/add", postdata, function( data ) {        
1038
        // document.location.reload();
1039
        window.location.replace(window.location.href.split('?')[0]);
1040
    }); 
15042 anikendra 1041
});
1042
function selectChosenBrands(){
18220 naman 1043
    var brandschosen = decodeURIComponent(getCookie('brandschosen',true));
1044
    var subcategorieschosen = decodeURIComponent(getCookie('subcategorieschosen',true));
1045
    if(brandschosen && brandschosen.length>0){
1046
        var brands = brandschosen.split(',');
1047
        for(var i in brands){
1048
            $('.brand').filter(function() { 
1049
                return $(this).data("brandid") == brands[i];
1050
            }).removeClass('hidden').find('.filterbrand',0).trigger( "click" );
1051
        }
1052
    }
1053
    if(subcategorieschosen && subcategorieschosen.length>0){
1054
        var subcategories = subcategorieschosen.split(',');
1055
        for(var i in subcategories){
1056
            $('.subcategory').filter(function() { 
1057
                return $(this).data("brandid") == subcategories[i];
1058
            }).removeClass('hidden').find('.filtersubcategory',0).trigger( "click" );
1059
        }
1060
    }
15065 anikendra 1061
}
18190 amit.gupta 1062
 
1063
function clearFilters(){
1064
	setCookie('brandschosen', '', -1, true);
1065
	setCookie('subcategorieschosen','',-1, true);
1066
}
15585 anikendra 1067
function showPosition(position) {
15586 anikendra 1068
    setCookie('latitude',position.coords.latitude,1,true); 
18220 naman 1069
    setCookie('longitude',position.coords.longitude,1,true);    
15585 anikendra 1070
}
15065 anikendra 1071
$(function () {
18115 amit.gupta 1072
	$("#popovertrigger5").popover('hide').remove();
18033 amit.gupta 1073
	$('.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 1074
	setPopOver("popovertrigger5", ".plusqtybutton", 'click', 3000);
18023 amit.gupta 1075
	callBackFunction = function(){
1076
		return document.location.pathname=="/category/6";		
1077
	};
18191 amit.gupta 1078
	setPopOver("popovertrigger4", callBackFunction,undefined,3000);
18115 amit.gupta 1079
	//$('[data-toggle="popover"]#'+id).popover('show');
18023 amit.gupta 1080
	if (navigator.geolocation) {
1081
        navigator.geolocation.getCurrentPosition(showPosition);
1082
    } 
1083
});
1084
 
18176 amit.gupta 1085
function setPopOver(poid, callBack1, eventString, fadeAfter){
15310 anikendra 1086
	var cname = 'popover-count-'+me+'-'+poid;
15721 anikendra 1087
	var cookieval = getCookie(cname,1);
18023 amit.gupta 1088
	if(typeof callBack1=="function"){
1089
		if (callBack1()){
1090
			var cname = 'popover-count-'+me+'-'+poid;
1091
			var cookieval = getCookie(cname,1);
1092
			$('#' + poid).popover('hide');
1093
			if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1094
				incrementPopupCount(poid,0,'popover-count-');
1095
			} else if(cookieval > 0) {
1096
				incrementPopupCount(poid, cookieval, 'popover-count-');
1097
			}
1098
			setLastShown(poid,'popover-lastshown-');
15310 anikendra 1099
		}
18023 amit.gupta 1100
	} else {
1101
		$('div.content').on(eventString, callBack1, function(){
1102
			var cname = 'popover-count-'+me+'-'+poid;
1103
			var cookieval = getCookie(cname,1);
1104
			$('#' + poid).popover('hide');
1105
			if(!cookieval || cookieval == 'NaN' || cookieval == ''){
1106
				incrementPopupCount(poid,0,'popover-count-');
1107
			} else if(cookieval > 0) {
1108
				incrementPopupCount(poid, cookieval, 'popover-count-');
1109
			}
1110
			setLastShown(poid,'popover-lastshown-');
1111
		}); 
18008 amit.gupta 1112
	}
18176 amit.gupta 1113
 
1114
	if(typeof fadeAfter!="undefined"){
18181 amit.gupta 1115
		var s = setInterval(function(){
1116
			if($('#' + poid +':in-viewport').length>0) {
1117
				setTimeout(function(){
1118
					$('#' + poid).popover('hide');
1119
				}, fadeAfter);
1120
				clearInterval(s);
1121
			}
1122
		}, 2000);
18176 amit.gupta 1123
	}
15310 anikendra 1124
 
15077 anikendra 1125
	var cname = 'popover-lastshown-'+me+'-'+poid;
15721 anikendra 1126
	var lastshown = getCookie(cname,1);
15310 anikendra 1127
	if(cookieval=='' || cookieval == 'NaN' || !cookieval){				
15077 anikendra 1128
		showpopover(poid);
15521 anikendra 1129
	} 
1130
	//Donot show popover anymore as long as we don't find a suitable solution
15721 anikendra 1131
	else{
15077 anikendra 1132
		var d = new Date();
1133
		var t = d.getTime();
15085 anikendra 1134
		if(t-lastshown>18*3600*1000){
15310 anikendra 1135
			if(cookieval>=2){
15077 anikendra 1136
				return false;
1137
			}else{
15310 anikendra 1138
				showpopover(poid);				
15077 anikendra 1139
			}
1140
		}
15721 anikendra 1141
	}
15583 anikendra 1142
	ga('send', 'event', 'popover', me, cookieval);
18023 amit.gupta 1143
}
16656 anikendra 1144
$('.getapp').on('click',function(){
18220 naman 1145
    /*var that = $(this);
1146
    var req = $.ajax({
1147
        url: 'http://104.200.25.40:8057/appAffiliates/generateRedirectUrl/'+me+'/'+$(that).data('id'),
1148
        // Tell jQuery we're expecting JSONP
1149
        dataType: "jsonp",
1150
        // Tell YQL what we want and that we want JSON          
1151
        method: 'get',
1152
        // timeout: 30000,
1153
        // Work with the response
1154
        success: function( response ) {
1155
            console.log(response);
1156
        }
1157
    });*/
1158
    $('#loadingModal').modal('show');
1159
    document.location = '/abouts/apphint';
16656 anikendra 1160
});
15077 anikendra 1161
function showpopover(id){
18220 naman 1162
    try {
1163
        $('[data-toggle="popover"]#'+id).popover({html:true,viewport:{container:'body'}, trigger:'manual'});
1164
        $('[data-toggle="popover"]#'+id).popover('show');       
1165
    }catch(err){
1166
        //
1167
    }
15085 anikendra 1168
}
1169
$(document).on('click','.nodeals',function(){
18220 naman 1170
    document.location = $(this).data('href');
16018 anikendra 1171
});
1172
$(document).on('click','.selectbrand',function(e){
18220 naman 1173
    e.preventDefault();
1174
    var brands = $(this).data('id');
1175
    var brandname = $(this).html();
1176
    //console.log(brandname);
17703 naman 1177
 
18220 naman 1178
    setCookie('brandschosen', brands, 1, true);
1179
    var url = $(this).data('href');
1180
    ga('send', 'event', 'selectbrand', 'brand', brandname);
1181
    properties = {};
1182
    properties['brand'] = brandname;
1183
    pma.send('filters','brands','selectbrand',me,properties);
1184
    var postdata = {'user_id':me,'type':'brand','filters':brandname};
1185
    $.post( "/user_filters/add", postdata, function( data ) {
1186
        $('#loadingModal').modal('hide');
1187
        $(this).addClass('activebrand');
1188
        document.location = url+'&brands='+brands;
1189
    });
16018 anikendra 1190
});
17703 naman 1191
 
1192
$(document).on('click','.selectsubcat',function(e){
18220 naman 1193
    e.preventDefault();
1194
    $('.clearfilters').click();
1195
    var brands = $(this).data('id');
1196
    var brandname = $(this).html();
1197
    //console.log(brandname);
1198
 
1199
    setCookie('subcategorieschosen', brands, 1, true);
1200
    var url = $(this).data('href');
1201
    // alert(url);
1202
    // ga('send', 'event', 'subcategorieschosen', 'brand', brandname);
1203
    document.location = url;
1204
    // properties = {};
1205
    // properties['brand'] = brandname;
1206
    // pma.send('filters','brands','selectbrand',me,properties);
1207
    // // var postdata = {'user_id':me,'type':'brand','filters':brandname};
1208
    // $.post( "/user_filters/add", postdata, function( data ) {
1209
    //  $('#loadingModal').modal('hide');
1210
    //  $(this).addClass('activebrand');
1211
 //         document.location = url+'&brands='+brands;
1212
    // });
17703 naman 1213
});
1214
 
16495 anikendra 1215
$(document).on('click','.shownexttip',function(e){
18220 naman 1216
    $(this).addClass('hidden').remove();
1217
    $('#firsttip').addClass('hidden').remove();
1218
    $('#secondtip').removeClass('hidden');
1219
    $('.gotit').removeClass('hidden');
16495 anikendra 1220
});
15128 anikendra 1221
var Base64 = {
1222
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
1223
    encode: function(input) {
1224
        var output = "";
1225
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
1226
        var i = 0;
1227
        input = Base64._utf8_encode(input);
1228
        while (i < input.length) {
1229
            chr1 = input.charCodeAt(i++);
1230
            chr2 = input.charCodeAt(i++);
1231
            chr3 = input.charCodeAt(i++);
1232
 
1233
            enc1 = chr1 >> 2;
1234
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
1235
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
1236
            enc4 = chr3 & 63;
1237
            if (isNaN(chr2)) {
1238
                enc3 = enc4 = 64;
1239
            } else if (isNaN(chr3)) {
1240
                enc4 = 64;
1241
            }
1242
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
1243
        }
1244
        return output;
1245
    },
1246
 
1247
 
1248
    decode: function(input) {
1249
        var output = "";
1250
        var chr1, chr2, chr3;
1251
        var enc1, enc2, enc3, enc4;
1252
        var i = 0;
1253
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
1254
        while (i < input.length) {
1255
            enc1 = this._keyStr.indexOf(input.charAt(i++));
1256
            enc2 = this._keyStr.indexOf(input.charAt(i++));
1257
            enc3 = this._keyStr.indexOf(input.charAt(i++));
1258
            enc4 = this._keyStr.indexOf(input.charAt(i++));
1259
            chr1 = (enc1 << 2) | (enc2 >> 4);
1260
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
1261
            chr3 = ((enc3 & 3) << 6) | enc4;
1262
            output = output + String.fromCharCode(chr1);
1263
            if (enc3 != 64) {
1264
                output = output + String.fromCharCode(chr2);
1265
            }
1266
            if (enc4 != 64) {
1267
                output = output + String.fromCharCode(chr3);
1268
            }
1269
        }
1270
        output = Base64._utf8_decode(output);
1271
        return output;
1272
    },
1273
 
1274
    _utf8_encode: function(string) {
1275
        string = string.replace(/\r\n/g, "\n");
1276
        var utftext = "";
1277
        for (var n = 0; n < string.length; n++) {
1278
            var c = string.charCodeAt(n);
1279
            if (c < 128) {
1280
                utftext += String.fromCharCode(c);
1281
            }
1282
            else if ((c > 127) && (c < 2048)) {
1283
                utftext += String.fromCharCode((c >> 6) | 192);
1284
                utftext += String.fromCharCode((c & 63) | 128);
1285
            }
1286
            else {
1287
                utftext += String.fromCharCode((c >> 12) | 224);
1288
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
1289
                utftext += String.fromCharCode((c & 63) | 128);
1290
            }
1291
        }
1292
        return utftext;
1293
    },
1294
 
1295
    _utf8_decode: function(utftext) {
1296
        var string = "";
1297
        var i = 0;
1298
        var c = c1 = c2 = 0;
1299
        while (i < utftext.length) {
1300
            c = utftext.charCodeAt(i);
1301
            if (c < 128) {
1302
                string += String.fromCharCode(c);
1303
                i++;
1304
            }
1305
            else if ((c > 191) && (c < 224)) {
1306
                c2 = utftext.charCodeAt(i + 1);
1307
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
1308
                i += 2;
1309
            }
1310
            else {
1311
                c2 = utftext.charCodeAt(i + 1);
1312
                c3 = utftext.charCodeAt(i + 2);
1313
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
1314
                i += 3;
1315
            }
1316
        }
1317
        return string;
1318
    }
15550 anikendra 1319
}
1320
 
1321
 
1322
var pma = new function() {
15584 anikendra 1323
    this.apiurl = "http://45.33.50.227:8081/";
15550 anikendra 1324
    this.endpoints = {'identify':'identify','profile':'profile','track':'track'};
1325
 
1326
    this.send = function (category,action,label,user_id,properties) {
18220 naman 1327
        if(!properties){
1328
            properties = {};
1329
        }
1330
        properties.location = window.location.href;
1331
        // properties.appCodeName = navigator.appCodeName;
1332
        // properties.appName = navigator.appName;
1333
        // properties.appVersion = navigator.appVersion;
1334
        properties.cookieEnabled = String(navigator.cookieEnabled);
1335
        properties.platform = navigator.platform;
1336
        properties.userAgent = navigator.userAgent;
1337
        properties.ip = ip;
1338
        if (navigator.geolocation) {
1339
            if(getCookie('latitude',true)){
1340
                properties.latitude = getCookie('latitude');
1341
            }           
1342
            if(getCookie('longitude',true)){
1343
                properties.longitude = getCookie('longitude');
1344
            }
1345
        }
1346
        properties.screenHeight = String(screen.height);
1347
        properties.screenWidth = String(screen.width);
1348
        // console.log(properties);
1349
        $.ajax({
1350
            url: this.apiurl + this.endpoints.track,
1351
            data: {'category':category,'action':action,'label':label,'user_id':user_id,'properties':cassandraMAP.stringify(properties)},
1352
            // Tell jQuery we're expecting JSONP
1353
            dataType: "json",
1354
            // Tell YQL what we want and that we want JSON          
1355
            method: 'post',
1356
            // Work with the response
1357
            success: function( response ) {
1358
                //Well, well, well :)
1359
            }
1360
        });       
15550 anikendra 1361
    };
1362
 
1363
    this.formDataToObject = function(formdata){
18220 naman 1364
        var properties = {};
1365
        var keys = [];
1366
        var formdata = JSON.parse(JSON.stringify(formdata));
1367
        for (var i in formdata) {
1368
            var key = formdata[i].name;
1369
            if(index = keys.indexOf(key)==-1){
1370
                properties[key] = formdata[i].value;
1371
            }else{
1372
                properties[key+'_'+i] = formdata[i].value;
1373
            }
1374
            keys.push(key);
1375
        };
1376
        return properties;
1377
    }
16704 anikendra 1378
}
1379
//App page
1380
$.fn.stars = function() {
1381
    return $(this).each(function() {
1382
        // Get the value
1383
        var val = parseFloat($(this).html());
1384
        // Make sure that the value is in 0 - 5 range, multiply to get width
1385
        val = Math.round(val * 2) / 2;
1386
        var size = Math.max(0, (Math.min(5, val))) * 16;
1387
        // Create stars holder
1388
        var $span = $('<span />').width(size);
1389
        // Replace the numerical value with stars
1390
        $(this).html($span);
1391
    });
1392
}
1393
$(function() {
18220 naman 1394
    $('span.stars').stars();    
18023 amit.gupta 1395
});
1396
 
1397
function sendCartChangeEvent(){
18220 naman 1398
    var cart_details_old = localStorage.getItem('cart_details_old');
1399
    var cart_details = localStorage.getItem('cart_details');
1400
    if (cart_details_old == cart_details){
1401
        return;
1402
    } else if(cart_details!=null){
1403
        JSON.parse(cart_details);
1404
 
1405
    }
18023 amit.gupta 1406
}
1407
 
1408
//setInterval(30000, )