Subversion Repositories SmartDukaan

Rev

Rev 13026 | Blame | Compare with Previous | Last modification | View Log | RSS feed

var totalAmount = 0.00;

$(document).ready(function(){
        checkIfUserHasAddress();
        if(window.location.pathname === "/cart") {
                changeEstimate();
        }
        
        if(typeof couponApplied!="undefined" && couponApplied){
                if ( typeof _gaq != "undefined" && _gaq != null) {
                _gaq.push(["_trackEvent", "COUPON", "Coupon Applied", couponCode, cartItemIds]);
        }
    }
        $('.wantInsurance').change( function() {
                productId = $(this).attr('productid');
                if(this.checked) {
                        trackEventWithGA('Insurance', 'Want Insurance', productId);
                }
                totalPrice = $('#totalAmountColumn').text();
                var initialPrice = parseFloat(totalPrice.replace(/,/g, ''));
                var initalNetPrice = 0.0;
                if($('#discountedAmount').length != 0) {
                        initalNetPrice = parseFloat($('#discountedAmount').text().replace(/,/g, ''));
                }
                var insuranceAmount = parseFloat($('#agreeInsuranceTnc_' + productId).attr('insuranceAmount'));
                $(this).attr('disabled', 'disabled');
                //The animation will be running for 1 second
                var interval = parseInt(1000/(insuranceAmount/4));
                //If insurance amount is large we need to set a minimum possible interval. 5 ms looks safe. 
                if(interval < 5) {
                        interval = 5;
                }
                if(this.checked) {
                        $('#agreeInsuranceTncDiv_' + productId).show();
                        //Update grand total but,
                        //Disable the checkbox so that user can't change while animation is running 
                        
                        displayCounter(initialPrice, initialPrice + insuranceAmount, $('#totalAmountColumn'), "increase", interval);
                        if($('#discountedAmount').length != 0) {
                                displayCounter(initalNetPrice, initalNetPrice + insuranceAmount, $('#discountedAmount'), "increase", interval);
                        }
                }
                else {
                        var previousStatus = $('#agreeInsuranceTnc_' + productId)[0].checked;
                        $('#agreeInsuranceTnc_' + productId)[0].checked =  false;
                        if(previousStatus === true) {
                                $('#agreeInsuranceTnc_' + productId).trigger('change');
                        }
                        $('#agreeInsuranceTncDiv_' + productId).hide();
                        
                        //Disable the checkbox so that user can't change while animation is running 
                        displayCounter(initialPrice, initialPrice - insuranceAmount, $('#totalAmountColumn'), "decrease", interval);
                        if($('#discountedAmount').length != 0) {
                                displayCounter(initalNetPrice, initalNetPrice - insuranceAmount, $('#discountedAmount'), "decrease", interval);
                        }
                }
                $(".payable").animate({ "background-color": "orange"}, 400 );
                $(".payable").animate({ "background-color": "#FFC"}, 400 );
        });
        
        function displayCounter(start, end, jQueryDom, direction, interval) {
                if(direction === "increase") {
                        if(start + 4 < end) {
                                start = start + 4;
                                jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(start.toFixed(2)));
                                window.setTimeout(function() {displayCounter(start, end, jQueryDom, direction, interval);}, interval);
                        } else {
                                jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(end.toFixed(2)));
                                $('.wantInsurance').removeAttr('disabled');
                        }
                } else if (direction === "decrease") {
                        if(start + 4 > end) {
                                start = start - 4;
                                jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(start.toFixed(2)));
                                window.setTimeout(function() {displayCounter(start, end, jQueryDom, direction, interval);}, interval);
                        } else {
                                jQueryDom.html('<img src="/images/rupee-symbol.png" alt="Rs."> ' + formatAmount(end.toFixed(2)));
                                $('.wantInsurance').removeAttr('disabled');
                        }
                }
        }
        
        function formatAmount(amount) {
                var numbers = amount.toString().split('.');
                var beforeDecimal = parseInt(numbers[0]);
                var afterDecimal = numbers[1];
                var finalString = '';
                while( beforeDecimal > 0) {
                        if($.inArray(finalString.length, [3,6,9,12]) > -1) {
                                finalString = ',' + finalString;
                        }
                        var r = beforeDecimal % 10;
                        beforeDecimal /= 10;
                        beforeDecimal = parseInt(beforeDecimal);
                        finalString = r.toString() + finalString;
                }
                finalString = finalString + '.' + afterDecimal;
                return finalString;
        } 
        
        $('.agreeInsuranceTnc').change(function() {
                
                $('.agreeInsuranceTnc').attr('disabled', 'disabled');
                $('.wantInsurance').attr('disabled', 'disabled');
                productId = $(this).attr('productid');
                if(this.checked){
                        trackEventWithGA('Insurance', 'Agreed to Terms', productId);
                }
                jQuery.ajax({
                        type: "POST",
                        url: "/cart!insureItem",
                        data: "toInsure=" + this.checked + "&productId=" + productId + "&quantity=" + $(this).attr('quantity')+"&insurerType=1",
                        success: function(response){
                                if(response === "SUCCESS") {
                                        if ($('#agreeInsuranceTnc_' + productId)[0].checked == true) {
                                                $("#insuranceMessage").html("Your product is now insured!");
                                        } else {
                                                $("#insuranceMessage").attr('style', 'color:red;border:1px solid red;box-shadow: red 0 0 30px 1px;');
                                                $("#insuranceMessage").html("Insurance removed!");
                                        }
                                        $("#insuranceMessage").fadeIn(600, function() {
                                                window.setTimeout(function() {
                                                        $("#insuranceMessage").fadeOut(800, function() {
                                                                $('.agreeInsuranceTnc').removeAttr('disabled');
                                                                $('.wantInsurance').removeAttr('disabled');
                                                                $("#insuranceMessage").removeAttr('style');
                                                        });
                                                }, 1500);
                                        });
                                } else {
                                        //If we were not able to update user's insurance preference then let's reload.
                                        location.reload();
                                        
                                        //OR ????
                                        //window.location.href = "/exception";
                                        
                                }
                        },
                        error : function(){
                                //There was an error with AJAX call and we can't be sure what happened; 
                                //Let us reload this page and see what was persisted in cart.
                                location.reload();
                        }
                });
        });
        
$('.dataProtection').change(function() {
        $('.dataProtection').attr('disabled', 'disabled');
                productId = $(this).attr('productid');
                jQuery.ajax({
                        type: "POST",
                        url: "/cart!insureItem",
                        data: "toInsure=" + this.checked + "&productId=" + productId + "&quantity=" + $(this).attr('quantity') +"&insurerType=2",
                        success: function(response){
                                if(response === "SUCCESS") {
                                        if ($('#dataProtection_' + productId)[0].checked == true) {
                                                $("#insuranceMessage").html("Free data protection enabled!");
                                        } else {
                                                $("#insuranceMessage").attr('style', 'color:red;border:1px solid red;box-shadow: red 0 0 30px 1px;');
                                                $("#insuranceMessage").html("Free data protection disabled!");
                                        }
                                        $("#insuranceMessage").fadeIn(600, function() {
                                                window.setTimeout(function() {
                                                        $("#insuranceMessage").fadeOut(800, function() {
                                                                $('.dataProtection').removeAttr('disabled');
                                                                $("#insuranceMessage").removeAttr('style');
                                                        });
                                                }, 1500);
                                        });
                                } else {
                                        //If we were not able to update user's insurance preference then let's reload.
                                        location.reload();
                                        
                                        //OR ????
                                        //window.location.href = "/exception";
                                        
                                }
                        },
                        error : function(){
                                //There was an error with AJAX call and we can't be sure what happened; 
                                //Let us reload this page and see what was persisted in cart.
                                location.reload();
                        }
                });
        });
        
        $('#checkout').click(function(){
                if($('input.agreeInsuranceTnc:checkbox:not(:hidden):not(:checked)').length != 0) {
                        trackEventWithGA('Insurance', 'Alert for T&C', '');
                        alert('Please agree to the terms and conditions to get insurance');
                        return false;
                }
                window.location.href = "/shipping";
        });
        
        $('#cancelInsurance').click(function() {
                jQuery.ajax({
                        type: "POST",
                        url: "/shipping!cancelInsurance",
                        success: function(msg){
                                //If shipping-failure.vm page was sent then send the user to cart page.
                                if (msg.replace(/^\s+|\s+$/g,'') === "0") {
                                        window.location.href = "/cart";
                                } else {
                                        window.location.reload();
                                }
                        },
                        error: function(msg){
                                //We don't know what happened, send the user to cart page.
                                window.location.href = "/cart";
                        }
                });
        });
        
        $('#companyInsurance').click(function() {
                $('#insuranceDetailDiv').slideUp(400);
                $.ajax({
                        type: "POST",
                        url: "/shipping!storeInsuranceDetails?addressId=" + $('#addressid').val(),
                        data: "&guardianName=Organisation&dob=Organisation",
                        success: function(msg){
                                ;//Don't do anything.
                        },
                        error: function(response) {
                                //Don't do anything.
                        }
                });
        });
        
        $('#dob').focusin(function() {
                if($(this).val() === 'Example: 18/08/1986') {
                        $(this).val('');
                        $(this).removeAttr('style');
                }
        });


        function validateDob() {
                var dateStr = $('#dob').val();
                dateStrArray = dateStr.split('/');
                //array[0] is day, array[1] is month, array[2] is year 
                //Now we will interchange the first and second placed numbers so that the date is in mm/dd/yyyy format 
                //which will be accepted by the Date.parse() method
                temp = dateStrArray[0];
                dateStrArray[0] = dateStrArray[1];
                dateStrArray[1] = temp;
                var enteredDob = new Date(Date.parse(dateStrArray.join('/')));
                if(isNaN(enteredDob.getFullYear())) {
                        showInsuranceError('Please enter date of birth in given format');
                        $('#dob').attr('style', 'color:#999;');
                        $('#dob').val('Example: 18/08/1986');
                        return false;
                }
                
                var today = new Date();
                if(today.getFullYear() - enteredDob.getFullYear() < 14) {
                        showInsuranceError('You need to be at least 14 years old to get Insurance');
                        $('#dob').attr('style', 'color:#999;');
                        $('#dob').val('Example: 18/08/1986');
                        return false;
                }
                if(today.getFullYear() - enteredDob.getFullYear() > 100) {
                        showInsuranceError('Sorry but this feature is only for people below 100 years of age');
                        $('#dob').attr('style', 'color:#999;');
                        $('#dob').val('Example: 18/08/1986');
                        return false;
                }
                $('#dob').val(enteredDob.toDateString().substring(4));
                return true;
        }
        
        function showInsuranceError(msg) {
                $('#insDetErr').html(msg);
                $('#insDetErr').slideDown(300,function(){$('#shippingDetails').one('click', clickHandler);});
        }
        
        function clickHandler() {
                $('#insDetErr').slideUp(300);
                $('#insDetErr').html('');
        }
        
        function focusOutHandler() {
                if($('#dob').val() === '') {
                        $('#dob').attr('style', 'color:#999;');
                        $('#dob').val('Example: 18/08/1986');
                } else {
                        if(validateDob()) {
                                $("#dob").animate({ "background-color": "#2789C1"}, 200 );
                                $("#dob").animate({ "background-color": "white"}, 200 );
                                $('#dob').val((new Date(Date.parse(dateStrArray.join('/')))).toDateString().substring(4));
                        }
                }
        };
        
        $('#dob').focusout(focusOutHandler);
        
        $('#submitInsuranceDetails').hover(
                function() {
                        $('#dob').unbind('focusout');
                }, 
                function() {
                        $('#dob').bind('focusout', focusOutHandler);
                }
        );
        
        
        $('#submitInsuranceDetails').click(function() {
                if($('#guardianName').val() === '') {
                        showInsuranceError('Please enter the name of your Father/Husband');
                        return false;
                }
                if($('#dob').val() === '' || $('#dob').val() === 'Example: 18/08/1986') {
                        showInsuranceError('Please enter your date of birth');
                        return false;
                }
                
                if(!validateDob()) {
                        return false;
                }
                
                $('#thanks').fadeIn(1000);
                $('#insuranceDetailDiv h3').fadeOut(100);
                $('#insuranceDetailsForm').slideUp(100);
                jQuery.ajax({
                        type: "POST",
                        url: "/shipping!storeInsuranceDetails?addressId=" + $('#addressid').val(),
                        data: $('#insuranceDetailsForm').serialize(),
                        success: function(msg){
                                window.setTimeout(function() {$('#insuranceDetailDiv').slideUp(100);}, 2000);
                        },
                        error: function(response) {
                                //We dont want to bother user too much with these details.We can ignore this in case of rare failures.
                                window.setTimeout(function() {$('#insuranceDetailDiv').slideUp(100);}, 2000);
                        }
                });
        });
        
/*      $('#poplogin').click(function(){
                $.colorbox({
                width: "860px",
                height: "340px",
                iframe: false,
                href: "/login-mini",
                
                onComplete: function(){
                        trackEventWithGA('Cart', 'Login/Register Popup', '');
                }
        });
        });*/
        
        $('#proceedToPay').click(function(){
                if($('#insuranceDetailsForm:visible').length == 1) {
                        showInsuranceError("Please submit the insurance details first");
                        return false;
                }
                
                if(($('#store-addresses').find('.default-address').attr('zone') !=  $('#zone-selector').val()) && ($("#tabSelector").val() == "HotSpot")) {
                        alert("Please select one store address");
                        return false;
                }
                var canProceedToPay = parseInt($('#canProceedToPay').val());
                
                if (canProceedToPay == 1)       {
                        
                        trackProceedToPay();
                        $('#formProceedToPay').submit();
                } else  {
                        var reasonActionDisability = $('#reasonActionDisability').val();
                        
                        if(reasonActionDisability.indexOf('Location not serviceable') >= 0)     {
                                trackEventWithGA('Cart', 'Location not serviceable', $('#selectedPincode').val());
                        }
                        else if (($("#tabSelector").val() == "HotSpot")) {
                                reasonActionDisability = 'Please enter an address which will be printed on the bill';
                        } else {
                                reasonActionDisability = 'Please specify a delivery address';
                        }
                        alert(reasonActionDisability);
                }
        });
        
        $('#viewOrders').click(function(){
                window.location.href = "/myaccount";
        });

        $('#cart .remove-quantitybttn').click(function(){
                var itemId = $(this).attr('id').split('_')[1];
                window.location.href = "/cart/"  + itemId + "?_method=delete" + "&productid=" + itemId;
        });
        
        $('#computeEstimate').click(function(){
                changeEstimate();
                $('#cartDetail').find('thead .dev-pincode').html($('#zipcode').val());
        });
        
        $('#applyCoupon').click(function(){
                $('#couponAction').val('applycoupon');
                $('#frmCouponCode').submit();
        });
        
        $('#removeCoupon').click(function(){
                $('#couponAction').val('removecoupon');
                $('#frmCouponCode').submit();
        });
        
        $('.cart-item-quantity').change(function(){
                var itemId = $(this).attr("id").split('_')[1];
                var quantity = parseInt($(this).val());
                //Quantity is now changed to 20
                if (quantity > 20)      {
                        alert("You can not order more than 20 pieces of same product.");
                        $(obj).focus();
                }
                else    {
                        submit("/cart/" + itemId  + "?_method=put&productid=" + itemId + "&quantity=" + quantity, "POST", []);
                }
        });
        
        $('#submitAddress').click(function(){
                if($('#guardianName').length > 0 && $('#guardianName').val() === '') {
                        showInsuranceError('Please enter the name of your Father/Husband');
                        return false;
                }
                if($('#dob').length > 0 && ($('#dob').val() === '' || $('#dob').val() === 'Example: 18/08/1986')) {
                        showInsuranceError('Please enter your date of birth');
                        return false;
                }
                
                if($('#dob').length > 0) {
                        if(!validateDob()) {
                                return false;
                        }
                }
                
                
                $('#frmShippingAddress').submit();
        });
        
        $('#addAddress').live('click', function(){
                showAddAddressForm();
        });

        $('#closeAddAddressForm').live('click', function() {
                showAddressList();
        });
        
        $('#addresses .button-address-select').click(function(){
                var addressId = $(this).attr('id').split('_')[1];
                $('#formChangeAddressTo_' + addressId).submit();
        });
                
        function checkIfUserHasAddress(){
                var addressEmpty = parseInt($('#addressEmpty').val());
                
                if (addressEmpty == 1)  {
                        showAddAddressForm();
                }
        }
        
        function showAddAddressForm(){
                //$('#main-right-container').hide();
                $('#shipping-address-div').hide();
                $('#billing-address-div').hide();
                $('#frmShippingAddress').show();
        }
        
        function showAddressList()      {
                $('#frmShippingAddress').hide();
                //$('#main-right-container').show();
                if($("#tabSelector").val() == "HotSpot") {
                        $('#billing-address-div').show();
                } else {
                        $('#shipping-address-div').show();
                }
        }
});

function sumOfColumns(tableID, columnIndex, hasHeader)  {
        var tot = 0;
        var inc = 1;
        var tableElement = $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""));
        var tableChildren = tableElement.children("td:nth-child(" + columnIndex + ")");

        tableChildren.each(function() {
                var currentVal = document.getElementById('totalPrice' + inc).innerHTML;
                inc ++;
                var splitVal = currentVal.split("Rs.");
                var num = parseFloat(splitVal[1].replace(/[^\d\.-]/g,''));
                tot += parseFloat(num);
        });
        totalAmount = tot;
        var formated_value = $().number_format(tot, {
                numberOfDecimals:2,
                decimalSeparator: '.',
                thousandSeparator: ',',
                symbol: 'Rs.'
        });
        return formated_value;
}

function subtractionOfColumns(tableID, columnIndex, hasHeader) {
        var tot = 0;

        $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : "")).children("td:nth-child(" + columnIndex + ")").each(function(){
                var currentVal=$(this).html();
                var splitVal=currentVal.split("Rs.");
                var num = parseFloat(splitVal[1].replace(/[^\d\.-]/g,''));
                tot += parseInt(num);
        });

        var formated_value = $().number_format(tot, {
                numberOfDecimals: 2,
                decimalSeparator: '.',
                thousandSeparator: ',',
                symbol: 'Rs.'
        });
        return formated_value;
}

function changeEstimate(item_id)        {
        if(item_id == null )    {
                $("#cartDetail tbody tr").each(function(index, item){
                        var itemId = $(item).attr("id");
                        if(itemId.length != "0") changeEstimate(itemId);
                });
                
        } else  {
                jQuery.ajax({
                        type: "GET",
                        url: "/estimate/" + $("#zipcode").val() + "_" + item_id,
                        beforeSend: function(){
                                $("#img" + "_" + item_id).html("<img src='/images/loader_l.gif'>").show();
                                $("#block" + "_" + item_id).hide();
                                $("#serv_" + item_id).hide();
                        },
                        success: function(data){
                                $("#img" + "_" + item_id).html("<img src='/images/loader_l.gif'>").hide();
                                var response = eval('(' + data + ')');
                                var deliveryEstimate = response['delivery_estimate'];
                                var otg= response['on_time_guarantee'];
                                var codDeliveryEstimate = response['cod_delivery_estimate'];
                                var isCODAvailableForLocation = (response['is_cod_available_for_location'] === 'true');
                                
                                if(deliveryEstimate == -1)      {
                                        $("#serv_" + item_id).show();
                                        return;
                                } else  {
                                        $("#days_" + item_id).html(deliveryEstimate);
                                        $("#show_cod_" + item_id).hide();
                                        if(isCODAvailableForLocation && (deliveryEstimate != codDeliveryEstimate)){
                                                $("#coddays_" + item_id).html(codDeliveryEstimate);
                                                $("#show_cod_" + item_id).show();       
                                        }       
                                }
                                if(otg == "true")       {
                                        $("#otg_" + item_id).show();
                                } else {
                                        $("#otg_" + item_id).hide();
                                }
                                $("#block" + "_" + item_id).show();
                        }
                });
        }
}

function submit(action, method, values) {
    var form = $('<form/>', {
        action: action,
        method: method
    });
    $.each(values, function() {
        form.append($('<input/>', {
            type: 'hidden',
            name: this.name,
            value: this.value
        }));    
    });
    form.appendTo('body').submit();
}