Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7272 amit.gupta 1
var totalAmount = 0.00;
2
 
3
$(document).ready(function(){
4
	checkIfUserHasAddress();
5
	if(window.location.pathname === "/cart") {
6
		changeEstimate();
7
	}
8
 
9
	$('.wantInsurance').change( function() {
10
		productId = $(this).attr('productid');
11
		if(this.checked) {
12
			trackEventWithGA('Insurance', 'Want Insurance', productId);
13
		}
14
		totalPrice = $('#totalAmountColumn').text();
15
		var initialPrice = parseFloat(totalPrice.replace(/,/g, ''));
16
		var initalNetPrice = 0.0;
17
		if($('#discountedAmount').length != 0) {
18
			initalNetPrice = parseFloat($('#discountedAmount').text().replace(/,/g, ''));
19
		}
20
		var insuranceAmount = parseFloat($('#agreeInsuranceTnc_' + productId).attr('insuranceAmount'));
21
		$(this).attr('disabled', 'disabled');
22
		//The animation will be running for 1 second
23
		var interval = parseInt(1000/(insuranceAmount/4));
24
		//If insurance amount is large we need to set a minimum possible interval. 5 ms looks safe. 
25
		if(interval < 5) {
26
			interval = 5;
27
		}
28
		if(this.checked) {
29
			$('#agreeInsuranceTncDiv_' + productId).show();
30
			//Update grand total but,
31
			//Disable the checkbox so that user can't change while animation is running 
32
 
33
			displayCounter(initialPrice, initialPrice + insuranceAmount, $('#totalAmountColumn'), "increase", interval);
34
			if($('#discountedAmount').length != 0) {
35
				displayCounter(initalNetPrice, initalNetPrice + insuranceAmount, $('#discountedAmount'), "increase", interval);
36
			}
37
		}
38
		else {
39
			var previousStatus = $('#agreeInsuranceTnc_' + productId)[0].checked;
40
			$('#agreeInsuranceTnc_' + productId)[0].checked =  false;
41
			if(previousStatus === true) {
42
				$('#agreeInsuranceTnc_' + productId).trigger('change');
43
			}
44
			$('#agreeInsuranceTncDiv_' + productId).hide();
45
 
46
			//Disable the checkbox so that user can't change while animation is running 
47
			displayCounter(initialPrice, initialPrice - insuranceAmount, $('#totalAmountColumn'), "decrease", interval);
48
			if($('#discountedAmount').length != 0) {
49
				displayCounter(initalNetPrice, initalNetPrice - insuranceAmount, $('#discountedAmount'), "decrease", interval);
50
			}
51
		}
52
		$(".payable").animate({ "background-color": "orange"}, 400 );
53
		$(".payable").animate({ "background-color": "#FFC"}, 400 );
54
	});
55
 
56
	function displayCounter(start, end, jQueryDom, direction, interval) {
57
		if(direction === "increase") {
58
			if(start + 4 < end) {
59
				start = start + 4;
60
				jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(start.toFixed(2)));
61
				window.setTimeout(function() {displayCounter(start, end, jQueryDom, direction, interval);}, interval);
62
			} else {
63
				jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(end.toFixed(2)));
64
				$('.wantInsurance').removeAttr('disabled');
65
			}
66
		} else if (direction === "decrease") {
67
			if(start + 4 > end) {
68
				start = start - 4;
69
				jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(start.toFixed(2)));
70
				window.setTimeout(function() {displayCounter(start, end, jQueryDom, direction, interval);}, interval);
71
			} else {
72
				jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(end.toFixed(2)));
73
				$('.wantInsurance').removeAttr('disabled');
74
			}
75
		}
76
	}
77
 
78
	function formatAmount(amount) {
79
		var numbers = amount.toString().split('.');
80
		var beforeDecimal = parseInt(numbers[0]);
81
		var afterDecimal = numbers[1];
82
		var finalString = '';
83
		while( beforeDecimal > 0) {
84
			if($.inArray(finalString.length, [3,6,9,12]) > -1) {
85
				finalString = ',' + finalString;
86
			}
87
			var r = beforeDecimal % 10;
88
			beforeDecimal /= 10;
89
			beforeDecimal = parseInt(beforeDecimal);
90
			finalString = r.toString() + finalString;
91
		}
92
		finalString = finalString + '.' + afterDecimal;
93
		return finalString;
94
	} 
95
 
96
	$('.agreeInsuranceTnc').change(function() {
97
 
98
		$('.agreeInsuranceTnc').attr('disabled', 'disabled');
99
		$('.wantInsurance').attr('disabled', 'disabled');
100
		productId = $(this).attr('productid');
101
		if(this.checked){
102
			trackEventWithGA('Insurance', 'Agreed to Terms', productId);
103
		}
104
		jQuery.ajax({
105
			type: "POST",
106
			url: "/cart!insureItem",
107
			data: "toInsure=" + this.checked + "&productId=" + productId + "&quantity=" + $(this).attr('quantity'),
108
			success: function(response){
109
				if(response === "SUCCESS") {
110
					if ($('#agreeInsuranceTnc_' + productId)[0].checked == true) {
111
						$("#insuranceMessage").html("Your product is now insured!");
112
					} else {
113
						$("#insuranceMessage").attr('style', 'color:red;border:1px solid red;box-shadow: red 0 0 30px 1px;');
114
						$("#insuranceMessage").html("Insurance removed!");
115
					}
116
					$("#insuranceMessage").fadeIn(600, function() {
117
						window.setTimeout(function() {
118
							$("#insuranceMessage").fadeOut(800, function() {
119
								$('.agreeInsuranceTnc').removeAttr('disabled');
120
								$('.wantInsurance').removeAttr('disabled');
121
								$("#insuranceMessage").removeAttr('style');
122
							});
123
						}, 1500);
124
					});
125
				} else {
126
					//If we were not able to update user's insurance preference then let's reload.
127
					location.reload();
128
 
129
					//OR ????
130
					//window.location.href = "/exception";
131
 
132
				}
133
			},
134
			error : function(){
135
				//There was an error with AJAX call and we can't be sure what happened; 
136
				//Let us reload this page and see what was persisted in cart.
137
				location.reload();
138
			}
139
		});
140
	});
141
 
142
	$('#checkout').click(function(){
143
		if($('input.agreeInsuranceTnc:checkbox:not(:hidden):not(:checked)').length != 0) {
144
			trackEventWithGA('Insurance', 'Alert for T&C', '');
145
			alert('Please agree to the terms and conditions to get insurance');
146
			return false;
147
		}
148
		window.location.href = "/shipping";
149
	});
150
 
151
	$('#cancelInsurance').click(function() {
152
		jQuery.ajax({
153
			type: "POST",
154
			url: "/shipping!cancelInsurance",
155
			success: function(msg){
156
				//If shipping-failure.vm page was sent then send the user to cart page.
157
				if (msg.replace(/^\s+|\s+$/g,'') === "0") {
158
					window.location.href = "/cart";
159
				} else {
160
					window.location.reload();
161
				}
162
			},
163
			error: function(msg){
164
				//We don't know what happened, send the user to cart page.
165
				window.location.href = "/cart";
166
			}
167
		});
168
	});
169
 
170
	$('#companyInsurance').click(function() {
171
		$('#insuranceDetailDiv').slideUp(400);
172
		$.ajax({
173
			type: "POST",
174
			url: "/shipping!storeInsuranceDetails?addressId=" + $('#addressid').val(),
175
			data: "&guardianName=Organisation&dob=Organisation",
176
			success: function(msg){
177
				;//Don't do anything.
178
			},
179
			error: function(response) {
180
				//Don't do anything.
181
			}
182
		});
183
	});
184
 
185
	$('#dob').focusin(function() {
186
		if($(this).val() === 'Example: 18/08/1986') {
187
			$(this).val('');
188
			$(this).removeAttr('style');
189
		}
190
	});
191
 
192
 
193
	function validateDob() {
194
		var dateStr = $('#dob').val();
195
		dateStrArray = dateStr.split('/');
196
		//array[0] is day, array[1] is month, array[2] is year 
197
		//Now we will interchange the first and second placed numbers so that the date is in mm/dd/yyyy format 
198
		//which will be accepted by the Date.parse() method
199
		temp = dateStrArray[0];
200
		dateStrArray[0] = dateStrArray[1];
201
		dateStrArray[1] = temp;
202
		var enteredDob = new Date(Date.parse(dateStrArray.join('/')));
203
		if(isNaN(enteredDob.getFullYear())) {
204
			showInsuranceError('Please enter date of birth in given format');
205
			$('#dob').attr('style', 'color:#999;');
206
			$('#dob').val('Example: 18/08/1986');
207
			return false;
208
		}
209
 
210
		var today = new Date();
211
		if(today.getFullYear() - enteredDob.getFullYear() < 14) {
212
			showInsuranceError('You need to be at least 14 years old to get Insurance');
213
			$('#dob').attr('style', 'color:#999;');
214
			$('#dob').val('Example: 18/08/1986');
215
			return false;
216
		}
217
		if(today.getFullYear() - enteredDob.getFullYear() > 100) {
218
			showInsuranceError('Sorry but this feature is only for people below 100 years of age');
219
			$('#dob').attr('style', 'color:#999;');
220
			$('#dob').val('Example: 18/08/1986');
221
			return false;
222
		}
223
		$('#dob').val(enteredDob.toDateString().substring(4));
224
		return true;
225
	}
226
 
227
	function showInsuranceError(msg) {
228
		$('#insDetErr').html(msg);
229
		$('#insDetErr').slideDown(300,function(){$('#shippingDetails').one('click', clickHandler);});
230
	}
231
 
232
	function clickHandler() {
233
		$('#insDetErr').slideUp(300);
234
		$('#insDetErr').html('');
235
	}
236
 
237
	function focusOutHandler() {
238
		if($('#dob').val() === '') {
239
			$('#dob').attr('style', 'color:#999;');
240
			$('#dob').val('Example: 18/08/1986');
241
		} else {
242
			if(validateDob()) {
243
				$("#dob").animate({ "background-color": "#2789C1"}, 200 );
244
				$("#dob").animate({ "background-color": "white"}, 200 );
245
				$('#dob').val((new Date(Date.parse(dateStrArray.join('/')))).toDateString().substring(4));
246
			}
247
		}
248
	};
249
 
250
	$('#dob').focusout(focusOutHandler);
251
 
252
	$('#submitInsuranceDetails').hover(
253
		function() {
254
			$('#dob').unbind('focusout');
255
		}, 
256
		function() {
257
			$('#dob').bind('focusout', focusOutHandler);
258
		}
259
	);
260
 
261
 
262
	$('#submitInsuranceDetails').click(function() {
263
		if($('#guardianName').val() === '') {
264
			showInsuranceError('Please enter the name of your Father/Husband');
265
			return false;
266
		}
267
		if($('#dob').val() === '' || $('#dob').val() === 'Example: 18/08/1986') {
268
			showInsuranceError('Please enter your date of birth');
269
			return false;
270
		}
271
 
272
		if(!validateDob()) {
273
			return false;
274
		}
275
 
276
		$('#thanks').fadeIn(1000);
277
		$('#insuranceDetailDiv h3').fadeOut(100);
278
		$('#insuranceDetailsForm').slideUp(100);
279
		jQuery.ajax({
280
			type: "POST",
281
			url: "/shipping!storeInsuranceDetails?addressId=" + $('#addressid').val(),
282
			data: $('#insuranceDetailsForm').serialize(),
283
			success: function(msg){
284
				window.setTimeout(function() {$('#insuranceDetailDiv').slideUp(100);}, 2000);
285
			},
286
			error: function(response) {
287
				//We dont want to bother user too much with these details.We can ignore this in case of rare failures.
288
				window.setTimeout(function() {$('#insuranceDetailDiv').slideUp(100);}, 2000);
289
			}
290
		});
291
	});
292
 
293
	$('#poplogin').click(function(){
294
		$.colorbox({
295
    		width: "860px",
296
    		height: "340px",
297
    		iframe: false,
298
    		href: "/login-mini",
299
 
300
    		onComplete: function(){
301
    			trackEventWithGA('Cart', 'Login/Register Popup', '');
302
    		}
303
    	});
304
	});
305
 
306
	$('#proceedToPay').click(function(){
307
		if($('#insuranceDetailsForm:visible').length == 1) {
308
			showInsuranceError("Please submit the insurance details first");
309
			return false;
310
		}
311
 
312
		if(($('#store-addresses').find('.default-address').attr('zone') !=  $('#zone-selector').val()) && ($("#tabSelector").val() == "HotSpot")) {
313
			alert("Please select one store address");
314
			return false;
315
		}
316
		var canProceedToPay = parseInt($('#canProceedToPay').val());
317
 
318
		if (canProceedToPay == 1)	{
319
 
320
			trackProceedToPay();
321
			$('#formProceedToPay').submit();
322
		} else	{
323
			var reasonActionDisability = $('#reasonActionDisability').val();
324
 
325
			if(reasonActionDisability.indexOf('Location not serviceable') >= 0)	{
326
				trackEventWithGA('Cart', 'Location not serviceable', $('#selectedPincode').val());
327
			}
328
			else if (($("#tabSelector").val() == "HotSpot")) {
329
				reasonActionDisability = 'Please enter an address which will be printed on the bill';
330
			} else {
331
				reasonActionDisability = 'Please specify a delivery address';
332
			}
333
			alert(reasonActionDisability);
334
		}
335
	});
336
 
337
	$('#viewOrders').click(function(){
338
		window.location.href = "/myaccount";
339
	});
340
 
341
	$('#cart .remove-quantitybttn').click(function(){
342
		var itemId = $(this).attr('id').split('_')[1];
343
		window.location.href = "/cart/"  + itemId + "?_method=delete" + "&productid=" + itemId;
344
	});
345
 
346
	$('#computeEstimate').click(function(){
347
		changeEstimate();
348
		$('#cartDetail').find('thead .dev-pincode').html($('#zipcode').val());
349
	});
350
 
351
	$('#applyCoupon').click(function(){
352
		$('#couponAction').val('applycoupon');
353
		$('#frmCouponCode').submit();
354
	});
355
 
356
	$('#removeCoupon').click(function(){
357
		$('#couponAction').val('removecoupon');
358
		$('#frmCouponCode').submit();
359
	});
360
 
361
	$('.cart-item-quantity').change(function(){
362
		var itemId = $(this).attr("id").split('_')[1];
363
		var quantity = parseInt($(this).val());
364
 
365
		if (quantity > 5)	{
366
			alert("You can not order more than 5 pieces of same product.");
367
			$(obj).focus();
368
		}
369
		else	{
370
			jQuery.ajax({
371
				type: "POST",
372
				url: "/cart/" + itemId + "?_method=put&productid=" + itemId + "&quantity=" + quantity,
373
				data: "productid=" + itemId + "&quantity=" + quantity,
374
				success: function(msg){
375
					window.location.reload();
376
				}
377
			});
378
		}
379
	});
380
 
381
	$('#submitAddress').click(function(){
382
		if($('#guardianName').length > 0 && $('#guardianName').val() === '') {
383
			showInsuranceError('Please enter the name of your Father/Husband');
384
			return false;
385
		}
386
		if($('#dob').length > 0 && ($('#dob').val() === '' || $('#dob').val() === 'Example: 18/08/1986')) {
387
			showInsuranceError('Please enter your date of birth');
388
			return false;
389
		}
390
 
391
		if($('#dob').length > 0) {
392
			if(!validateDob()) {
393
				return false;
394
			}
395
		}
396
 
397
 
398
		$('#frmShippingAddress').submit();
399
	});
400
 
401
	$('#addAddress').live('click', function(){
402
		showAddAddressForm();
403
	});
404
 
405
	$('#closeAddAddressForm').live('click', function() {
406
		showAddressList();
407
	});
408
 
409
	$('#addresses .button-address-select').click(function(){
410
		var addressId = $(this).attr('id').split('_')[1];
411
		$('#formChangeAddressTo_' + addressId).submit();
412
	});
413
 
414
	function checkIfUserHasAddress(){
415
		var addressEmpty = parseInt($('#addressEmpty').val());
416
 
417
		if (addressEmpty == 1)	{
418
			showAddAddressForm();
419
		}
420
	}
421
 
422
	function showAddAddressForm(){
423
		//$('#main-right-container').hide();
424
		$('#shipping-address-div').hide();
425
		$('#billing-address-div').hide();
426
		$('#frmShippingAddress').show();
427
	}
428
 
429
	function showAddressList()	{
430
		$('#frmShippingAddress').hide();
431
		//$('#main-right-container').show();
432
		if($("#tabSelector").val() == "HotSpot") {
433
			$('#billing-address-div').show();
434
		} else {
435
			$('#shipping-address-div').show();
436
		}
437
	}
438
});
439
 
440
function sumOfColumns(tableID, columnIndex, hasHeader)	{
441
	var tot = 0;
442
	var inc = 1;
443
	var tableElement = $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""));
444
	var tableChildren = tableElement.children("td:nth-child(" + columnIndex + ")");
445
 
446
	tableChildren.each(function() {
447
		var currentVal = document.getElementById('totalPrice' + inc).innerHTML;
448
		inc ++;
449
		var splitVal = currentVal.split("Rs.");
450
		var num = parseFloat(splitVal[1].replace(/[^\d\.-]/g,''));
451
		tot += parseFloat(num);
452
	});
453
	totalAmount = tot;
454
	var formated_value = $().number_format(tot, {
455
		numberOfDecimals:2,
456
		decimalSeparator: '.',
457
		thousandSeparator: ',',
458
		symbol: 'Rs.'
459
	});
460
	return formated_value;
461
}
462
 
463
function subtractionOfColumns(tableID, columnIndex, hasHeader) {
464
	var tot = 0;
465
 
466
	$("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : "")).children("td:nth-child(" + columnIndex + ")").each(function(){
467
		var currentVal=$(this).html();
468
		var splitVal=currentVal.split("Rs.");
469
		var num = parseFloat(splitVal[1].replace(/[^\d\.-]/g,''));
470
		tot += parseInt(num);
471
	});
472
 
473
	var formated_value = $().number_format(tot, {
474
		numberOfDecimals: 2,
475
		decimalSeparator: '.',
476
		thousandSeparator: ',',
477
		symbol: 'Rs.'
478
	});
479
	return formated_value;
480
}
481
 
482
function changeEstimate(item_id)	{
483
	if(item_id == null )	{
484
		$("#cartDetail tbody tr").each(function(index, item){
485
			var itemId = $(item).attr("id");
486
			changeEstimate(itemId);
487
		});
488
 
489
	} else	{
490
		jQuery.ajax({
491
			type: "GET",
492
			url: "/estimate/" + $("#zipcode").val() + "_" + item_id,
493
			beforeSend: function(){
494
				$("#img" + "_" + item_id).html("<img src='/images/loader_l.gif'>").show();
495
				$("#block" + "_" + item_id).hide();
496
				$("#serv_" + item_id).hide();
497
			},
498
			success: function(data){
499
				$("#img" + "_" + item_id).html("<img src='/images/loader_l.gif'>").hide();
500
				var response = eval('(' + data + ')');
501
				var deliveryEstimate = parseInt(response['delivery_estimate']);
502
				var otg= response['on_time_guarantee'];
503
 
504
				if(deliveryEstimate == -1)	{
505
					$("#serv_" + item_id).show();
506
					return;
507
 
508
				} else if(deliveryEstimate == 1)	{
509
					$("#days_" + item_id).html('1 Business Day');
510
				}
511
				else	{
512
					$("#days_" + item_id).html(deliveryEstimate + ' Business Days');
513
				}
514
				if(otg == "true")	{
515
					$("#otg_" + item_id).show();
516
				} else {
517
					$("#otg_" + item_id).hide();
518
				}
519
				$("#block" + "_" + item_id).show();
520
			}
521
		});
522
	}
523
}