﻿
App.Checkout = function () {

    /* Private */

    /* Properties */

    var cmp = {};

    /* Methods */
    var checkoutMode = true;

    TVI.Popup.modal = true;
    TVI.Popup.overlay = 80;
    TVI.Popup.width = 940;


    var init = function () {

        if ($('#login').length > 0) {
            initLogin();
        }

        TVI.event('#btn_logout', 'click', function () {
            var cookie_date = new Date();  // current date & time
            cookie_date.setTime(cookie_date.getTime() - 1);
            document.cookie = "TviEcom=;expires=" + cookie_date.toGMTString();

            TVI.ajax({
                url: TVI.handlers + '/account.aspx/logout',
                success: function (d) {

                    if (window.location.pathname.indexOf('/account/') != -1)
                        window.location.href = '/';

                    $('#accountHolder').html(d.accountForm);
                    initLogin();

                }
            });
        });
        TVI.event('.backToShopping', 'click', function () {
            if ($(this).parents('.makePaymentStage').length > 0) {
                window.location = $('#lastCat').text();
            }
            else {
                TVI.Popup.close();
            }
        });


        TVI.event('#btn_register', 'click', function () {
            TVI.ajax({

                url: '/handlers/general.aspx/getControl',
                data: { 'control': 'login', 'checkout': 'false' },
                responseType: 'text',
                success: function (d) {

                    TVI.Popup.show({

                        template: d,
                        success: function () {

                            checkoutMode = false;
                            initCheckoutLogin();
                            TVI.Components.initialize();

                        }
                    });

                }

            });
        });


        TVI.event('.checkoutButton', 'click', function () {
            // Check wether they are logged in
            checkoutMode = true;

            TVI.ajax({
                url: '/handlers/checkout.aspx/checkLoggedIn',
                data: {},
                success: function (d) {
                    TVI.ajax({

                        url: '/handlers/general.aspx/getControl',
                        data: { 'control': 'delivery' },
                        responseType: 'text',
                        success: function (d) {
                            TVI.Popup.show({
                                template: d,
                                success: function () {
                                    initDeliveryForm();
                                    TVI.Components.initialize();
                                }

                            });
                        }
                    });
                },
                failure: function (d) {
                    TVI.ajax({

                        url: '/handlers/general.aspx/getControl',
                        data: { 'control': 'login' },
                        responseType: 'text',
                        success: function (d) {
                            TVI.Popup.show({

                                template: d,
                                success: function () {
                                    TVI.Components.initialize();
                                    initCheckoutLogin();
                                }

                            });
                        }

                    });
                }
            });
        });


    };


    var initLogin = function () {
        // Login Form
        var loginForm = new TVI.Form({
            ID: 'login',
            url: TVI.handlers + 'account.aspx/login',
            success: function (d) {
                $('#accountHolder').html(d.accountForm);
            }
        });

    };


    var initCheckoutLogin = function () {

        var checkoutLoginForm = new TVI.Form({

            ID: 'checkoutLogin',
            url: TVI.handlers + 'account.aspx/login',

            success: function (d) {
                $('#accountHolder').html(d.accountForm);

                if (!checkoutMode) {
                    window.location.href = '/account/default.aspx';
                }
                else {
                    TVI.ajax({

                        url: '/handlers/general.aspx/getControl',
                        data: { 'control': 'delivery' },
                        responseType: 'text',
                        success: function (d) {
                            /* Constructor */
                            TVI.Popup.show({
                                template: d,
                                success: function () {
                                    initDeliveryForm();
                                    TVI.Components.initialize();
                                }

                            });
                        }

                    });
                }
            }
        });

        var createAccountForm = new TVI.Form({

            ID: 'checkoutStartRegister',
            url: '/handlers/checkout.aspx/checkEmail',

            success: function (d) {
                TVI.ajax({

                    url: '/handlers/general.aspx/getControl',
                    data: { 'control': 'register', 'checkout': checkoutMode },
                    responseType: 'text',
                    success: function (d) {
                        TVI.Popup.show({
                            template: d,
                            success: function () {
                                TVI.Components.initialize();

                                initRegisterForm(createAccountForm.field('email').val());
                            }

                        });
                    }

                });
            }

        });

    };


    var initRegisterForm = function (email) {

        registerForm = new TVI.Form({
            ID: 'checkoutCreateAccount',
            url: '/handlers/checkout.aspx/register',

            success: function (d) {
                $('#accountHolder').html(d.accountForm);

                if (!checkoutMode) {
                    window.location.href = '/account/default.aspx';
                }
                else {

                    TVI.ajax({

                        url: '/handlers/general.aspx/getControl',
                        data: { 'control': 'delivery' },
                        responseType: 'text',
                        success: function (d) {
                            TVI.Popup.show({
                                template: d,
                                success: function () {
                                    TVI.Components.initialize();
                                    initDeliveryForm();
                                }

                            });
                        }

                    });
                }
            }
        });
        registerForm.field('email').val(email);

        if ($('#fastCheckout').length > 0) {

            fastCheckout = new TVI.Form({
                ID: 'fastCheckout',
                url: '/handlers/checkout.aspx/fastCheckout',

                success: function (d) {
                    $('#accountHolder').html(d.accountForm);

                    TVI.ajax({

                        url: '/handlers/general.aspx/getControl',
                        data: { 'control': 'delivery' },
                        responseType: 'text',
                        success: function (d) {
                            TVI.Popup.show({
                                template: d,
                                success: function () {
                                    TVI.Components.initialize();
                                    initDeliveryForm();
                                }

                            });
                        }

                    });
                }
            });
            fastCheckout.field('email').val(email);

        }
        

    };


    var initDeliveryForm = function () {


        $("input[name='chooseAddress']").click(function () {
            // If cust chooses to create a new address show the address form
            if ($("input[name='chooseAddress']:checked").val() == 'new') {
                $('.checkoutRight fieldset:first').show();
                deliveryForm.clear();
                deliveryForm.clearErrors();
            }
            else {
                $('.checkoutRight fieldset:first').hide();
                $('#existingBilling fieldset').show();
                // Fill out new address form in the background so that it passes validation
                deliveryForm.field('name').val('existing');
                deliveryForm.field('street').val('existing');
                deliveryForm.field('town').val('existing');
                deliveryForm.field('postcode').val('existing');
            }

        });

        if (!$('#checkoutDeliverySelect fieldset').is(':visible')) {
            $('.checkoutRight').css('float', 'left');
            $('.checkoutRight fieldset:first').show();
        }

        var deliveryForm = new TVI.Form({

            ID: 'checkoutNewDelivery',
            url: '/handlers/checkout.aspx/saveDeliveryAddress',
            validation: function (d) {

                if ($("input[name='chooseAddress']:checked").val() == undefined && $('#checkoutDeliverySelect fieldset').is(':visible')) {
                    d.errors.push({ message: 'Please choose or create an address' });
                }
                else if ($("input[name='checkoutDeliveryBilling']:checked").length < 1) {
                    d.errors.push({ message: 'Please indicate if this is also your billing address' });
                }

                if (($("input[name='chooseAddress']:checked").val() == undefined || $("input[name='chooseAddress']:checked").val() == 'new') && $('#checkoutNewDelivery-country-control').val() == null) {
                    d.errors.push({ message: 'Please choose your country' });
                }

            },
            submit: function () {
                this.submit();
                if ($("input[name='chooseAddress']:checked") == undefined) {
                    this.hiddenData.addressID = 'new';
                }
                else {
                    this.hiddenData.addressID = $("input[name='chooseAddress']:checked").val();
                }
                this.hiddenData.alsoBilling = $("input[name='checkoutDeliveryBilling']:checked").val();
            },
            success: function (d) {

                TVI.ajax({

                    url: '/handlers/general.aspx/getControl',
                    data: { 'control': d.nextForm },
                    responseType: 'text',
                    success: function (e) {
                        /* Constructor */
                        TVI.Popup.show({

                            template: e,
                            success: function () {
                                if (d.nextForm == "billing") {
                                    TVI.Components.initialize();
                                    initBillingForm();
                                }
                                else {
                                    TVI.Components.initialize();
                                    initConfirmForm();
                                }
                            }

                        });
                    }

                });

            }
        });

    };


    var initBillingForm = function () {


        $("input[name='chooseAddress']").click(function () {
            // If cust chooses to create a new address show the address form
            if ($("input[name='chooseAddress']:checked").val() == 'new') {
                $('.checkoutRight fieldset:first').show();
                billingForm.clear();
                billingForm.clearErrors();
            }
            else {
                $('.checkoutRight fieldset:first').hide();
                $('#existingBilling fieldset').show();
                // Fill out new address form in the background so that it passes validation
                billingForm.field('name').val('existing');
                billingForm.field('street').val('existing');
                billingForm.field('town').val('existing');
                billingForm.field('postcode').val('existing');
            }

        });

        var billingForm = new TVI.Form({

            ID: 'checkoutNewBilling',
            url: '/handlers/checkout.aspx/saveBillingAddress',
            validation: function (d) {

                if ($("input[name='chooseAddress']:checked").val() == undefined && $('#checkoutBillingSelect fieldset').is(':visible')) {
                    d.errors.push({ message: 'Please choose or create an address' });
                }

            },
            submit: function () {
                this.submit();
                this.hiddenData.addressID = $("input[name='chooseAddress']:checked").val();
            },
            success: function (d) {

                TVI.ajax({

                    url: '/handlers/general.aspx/getControl',
                    data: { 'control': 'confirm' },
                    responseType: 'text',
                    success: function (e) {
                        /* Constructor */
                        TVI.Popup.show({

                            template: e,
                            success: function () {

                                TVI.Components.initialize();
                                initConfirmForm();
                            }

                        });
                    }

                });

            }
        });

    };


    // Confirmation page
    var initConfirmForm = function () {

        $('.lightbox').fancybox({
            padding: '20'
        });

        if ($('#giftCardTextbox-message-control').length > 0) {
            var tb = $('#giftCardTextbox-message-control');

            $(tb).data('original', $(tb).val());

            $(tb).focus(function () {
                if ($(tb).val() === $(tb).data('original')) {
                    $(tb).val('');
                }
            });

            $(tb).blur(function () {
                if ($(tb).val() === '') {
                    $(tb).val($(tb).data('original'));
                }
            });

            $('.discountRemove').click(function () {
                $('#confirmLoading').show();
                $('.makePayment').hide();

                TVI.ajax({

                    url: '/handlers/checkout.aspx/removeDiscount',
                    data: {
                        'discountID': $(this).attr('data-discountID')
                    },
                    success: function (d) {
                        getConfirmPage();
                    }
                });
                return false;
            });

        }

        $('.editBilling').click(function () {

            TVI.ajax({

                url: '/handlers/general.aspx/getControl',
                data: { 'control': 'billing' },
                responseType: 'text',
                success: function (d) {
                    /* Constructor */
                    TVI.Popup.show({

                        template: d,
                        success: function () {
                            TVI.Components.initialize();
                            initBillingForm();
                        }

                    });
                }

            });
            return false;
        });

        $('.editDelivery').click(function () {

            TVI.ajax({

                url: '/handlers/general.aspx/getControl',
                data: { 'control': 'delivery' },
                responseType: 'text',
                success: function (d) {
                    /* Constructor */
                    TVI.Popup.show({

                        template: d,
                        success: function () {
                            TVI.Components.initialize();
                            initDeliveryForm();
                        }

                    });
                }

            });
            return false;
        });


        $('.quantity .buttonContainer a').click(function () {
            var thisProduct = $(this);
            $('#confirmLoading').show();
            $('.makePayment').hide();

            TVI.ajax({

                url: '/handlers/checkout.aspx/updateBasketProduct',
                data: {
                    'itemIndex': $(this).attr('data-itemIndex'),
                    'quantity': $(this).closest('.quantity').find('input').val(),
                    'action': $(this).attr('data-command')
                },

                success: function (d) {
                    getConfirmPage();
                },
                failure: function (d) {

                    thisProduct.parents('.yourOrderProduct:first').find('.errors').html('<span style="color:Red;">' + d.errors[0].message + '</span>');

                    $('#confirmLoading').hide();
                    $('.makePayment').show();
                }
            });
            return false;
        });


        // Handle promo code form

        var promoForm = new TVI.Form({

            ID: 'promoForm',
            url: '/handlers/checkout.aspx/addDiscount',
            success: function (d) {
                getConfirmPage();
            }

        });

        $('.discount a').click(function () {
            $('#confirmLoading').show();
            $('.makePayment').hide();

            TVI.ajax({

                url: '/handlers/checkout.aspx/removeDiscount',
                data: {
                    'discountID': $(this).attr('data-discountID')
                },
                success: function (d) {
                    getConfirmPage();
                }
            });
            return false;
        });

        $('.postage select').change(function () {
            $('#confirmLoading').show();
            $('.makePayment').hide();

            TVI.ajax({

                url: '/handlers/checkout.aspx/changePostage',
                data: {
                    'postageIndex': $(this).val()
                },
                success: function (d) {
                    getConfirmPage();
                }
            });
            return false;
        });

    };

    //Add special offer product
    TVI.event('.addButtonSpecial', 'click', function (e) {

        var button = $(this);
        var parentForm = $(this).parent();

        // Make sure the added message disappears first (in case they add two in quick succession)
        parentForm.children('.TVI-form-field-error-message').hide();
        button.fadeOut('fast', function () {
            parentForm.children('.ajaxLoadingContainer').fadeIn('fast');
        });

        data = {};

        // Build the data
        data['productID'] = button.attr('productID');
        data['quantity'] = button.prev('.specQuantity').val();

        TVI.ajax({

            url: '/handlers/product.aspx/addToBasket',
            data: data,
            success: function (d) {

                getConfirmPage();
                parentForm.children('.addedToBasket').text(data["quantity"] + " Added to basket").fadeIn();
                setTimeout(function () {
                    parentForm.children('.addedToBasket').fadeOut('fast');
                }, 1500);

            }, failure: function (d) {

                parentForm.children('.TVI-form-field-error-message').text('');
                for (var i = 0; i < d.errors.length; i++) {
                    parentForm.children('.TVI-form-field-error-message').append(d.errors[i].message + "<br />");
                }
                parentForm.children('.TVI-form-field-error-message').show();
                parentForm.children('.ajaxLoadingContainer').fadeOut('fast', function () {
                    button.fadeIn('fast');
                });

            }

        });

    });

    // Add Giftcard
    TVI.event('.addGiftCard', 'click', function (e) {

        // Make sure the added message disappears first (in case they add two in quick succession)
        $('#giftCardTextbox .TVI-form-field-error-message').hide();
        $('#giftCardTextbox .addGiftCard').fadeOut('fast', function () {
            $('#giftCardTextbox .ajaxLoadingContainer').fadeIn('fast');
        });

        data = {};

        // Build the data
        data["productID"] = 1;
        data["customised"] = true;
        data["productOptions-Text"] = $('#giftCardTextbox-message-control').val();
        data['quantity'] = 1;

        TVI.ajax({

            url: '/handlers/product.aspx/addToBasket',
            data: data,
            success: function (d) {

                getConfirmPage();

            }, failure: function (d) {

                $('#giftCardTextbox .TVI-form-field-error-message').text('');
                for (var i = 0; i < d.errors.length; i++) {
                    $('#giftCardTextbox .TVI-form-field-error-message').append(d.errors[i].message + "<br />");
                }
                $('#giftCardTextbox .TVI-form-field-error-message').show();
                $('#giftCardTextbox .ajaxLoadingContainer').fadeOut('fast', function () {
                    $('#giftCardTextbox .addGiftCard').fadeIn('fast');
                });

            }

        });


    });

    var getConfirmPage = function () {
        TVI.ajax({
            url: '/handlers/general.aspx/getControl',
            data: { 'control': 'confirm' },
            responseType: 'text',
            success: function (e) {
                /* Constructor */
                TVI.Popup.show({
                    template: e,
                    success: function () {
                        TVI.Components.initialize();
                        initConfirmForm();

                    }
                });
            }
        });
    };


    /* Public */

    TVI.apply(cmp, {


    });


    TVI.ready(init);


    return cmp;


} ();
