﻿
B4PC = function() {

    /* Private */

    /* Properties */

    var cmp = {};

    TVI.Popup.modal = true;
    TVI.Popup.overlay = 85;
    TVI.Popup.width = 1000;
    TVI.Popup.top = 30;


    /* Methods */

    var init = function() {

        var pageTracker = _gat._getTracker("UA-3855348-1");

        TVI.Forms.handlerURL = '/handlers/';

        TVI.Data.defaultURL = '/handlers/data.aspx/query';


        TVI.Popup.setTemplate(
            $('#b4ppopup').html()
        );

        $('.continueShopping').live( 'click', function() {
            TVI.Popup.close();
        });

        $('#openCheckout').live('click', function() {
        // Check wether they are logged in

        TVI.ajax({
            url: '/handlers/checkout.aspx/checkLoggedIn',
            data: {},
            success: function(d) {
                TVI.ajax({

                    url: '/handlers/checkout.aspx/getForm',
                    data: { 'form': 'deliveryOption' },
                    responseType: 'text',
                    success: function(d) {
                        TVI.Popup.show({

                            title: 'Popup',
                            template: d,
                            success: function() {
                                initForm();
                                initDeliveryChoice();
                            }

                        });
                    }
                });
            },
            failure: function(d) {
                TVI.ajax({

                    url: '/handlers/checkout.aspx/getForm',
                    data: { 'form': 'login' },
                    responseType: 'text',
                    success: function(d) {
                        TVI.Popup.show({

                            title: 'Popup',
                            template: d,
                            success: function() {
                                initForm();
                                initLoginForm();

                            }

                        });
                    }

                });
            }
        });
        return false;
        });



    };
    
    var initForm = function() {
        $('.TVI-formSubmit').after($('.loading:eq(0)'));
        $('.fancybox').fancybox();
    };

    var initLoginForm = function() {

        cmp.loginForm = new TVI.Form({

            ID: 'loginForm',
            handler: login,
            errorsEl: '.errors'
        });

        cmp.createAccountForm = new TVI.Form({

            ID: 'createAccountForm',
            handler: getRegisterForm,
            errorsEl: '.errors'
        });

        pageTracker._trackPageview("/newcheckout/login");

    }
    
    var getRegisterForm = function() {
        cmp.createAccountForm.el.find('.loading').show();
        cmp.createAccountForm.el.find('.TVI-formSubmit').hide();
        cmp.createAccountForm.validate({
            success: function() {
                cmp.createAccountForm.submit({

                    url: '/handlers/checkout.aspx/checkEmail',

                    success: function(d) {
                        TVI.ajax({

                            url: '/handlers/checkout.aspx/getForm',
                            data: { 'form': 'register' },
                            responseType: 'text',
                            success: function(d) {
                                /* Constructor */
                                TVI.Popup.show({

                                    title: 'Register',
                                    template: d,
                                    success: function() {
                                        initForm();
                                        initRegisterForm(cmp.createAccountForm.field('email').val());
                                    }

                                });
                            }

                        });
                    },
                    failure : function(d) {
                        cmp.createAccountForm.el.find('.loading').hide();
                        cmp.createAccountForm.el.find('.TVI-formSubmit').show();
                        cmp.createAccountForm.error(d.errors);
                    }
                });
            },
            failure: function(d) {
                cmp.createAccountForm.el.find('.loading').hide();
                cmp.createAccountForm.el.find('.TVI-formSubmit').show();
                cmp.createAccountForm.error(d.errors);
            }
        });
                
    }
    
    var initRegisterForm = function(email) {
    
        cmp.registerForm = new TVI.Form({

            ID: 'registerForm',
            handler: registerAccount,
            errorsEl: '.errors'
        });

        cmp.registerForm.field('email').val(email);
        pageTracker._trackPageview("/newcheckout/register");
        
    }
    
    var registerAccount = function() {
        cmp.registerForm.validate({
            success: function() {
                cmp.registerForm.submit({

                    url: '/handlers/checkout.aspx/register',

                    success: function(d) {
                        TVI.ajax({

                            url: '/handlers/checkout.aspx/getForm',
                            data: { 'form': 'deliveryOption' },
                            responseType: 'text',
                            success: function(d) {
                                /* Constructor */
                                TVI.Popup.show({

                                    title: 'Popup',
                                    template: d,
                                    success: function() {
                                        initForm();
                                        initDeliveryChoice();
                                    }

                                });
                            }

                        });
                    },
                    failure: function(d) {
                        
                        cmp.registerForm.el.find('.loading').hide();
                        cmp.registerForm.el.find('.TVI-formSubmit').show();
                        cmp.registerForm.error(d.errors);
                    }
                });
            },
            failure: function(d) {
                                
                cmp.registerForm.el.find('.loading').hide();
                cmp.registerForm.el.find('.TVI-formSubmit').show();
                cmp.registerForm.error(d.errors);
            }
        });
    }
    

    var login = function() {
        cmp.loginForm.el.find('.loading').show();
        cmp.loginForm.el.find('.TVI-formSubmit').hide();

        cmp.loginForm.validate({
            success: function() {
                cmp.loginForm.submit({

                    url: '/handlers/checkout.aspx/login',

                    success: function(d) {
                        TVI.ajax({

                            url: '/handlers/checkout.aspx/getForm',
                            data: { 'form': 'deliveryOption' },
                            responseType: 'text',
                            success: function(d) {
                                /* Constructor */
                                TVI.Popup.show({

                                    title: 'Popup',
                                    template: d,
                                    success: function() {
                                        initForm();
                                        initDeliveryChoice();
                                    }

                                });
                            }

                        });
                    },
                    failure: function(d) {
                        cmp.loginForm.el.find('.loading').hide();
                        cmp.loginForm.el.find('.TVI-formSubmit').show();
                        cmp.loginForm.error(d.errors);
                    }
                });
            },
            failure: function(d) {
                cmp.loginForm.el.find('.loading').hide();
                cmp.loginForm.el.find('.TVI-formSubmit').show();
                cmp.loginForm.error(d.errors);
            }
        });
    }


    var initDeliveryChoice = function() {

    pageTracker._trackPageview("/newcheckout/deliverycollectionchoice");

        $('.orderDelivered').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'delivery' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initDeliveryForm();
                        }

                    });
                }

            });
            return false;
        });

        $('.orderCollect').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'collection' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initCollectionForm();
                        }

                    });
                }

            });
            return false;
        });

    }

    var initCollectionForm = function() {
        pageTracker._trackPageview("/newcheckout/collection");
        $('.collectionLocation').click(function() {
            var lat = $(this).parent().find('.latitude').val();
            var lng = $(this).parent().find('.longitude').val();
            TVI.Mapping.load({

                key: 'ABQIAAAAZRljSxcQ8b5LKNn1y8IdOhQPTxSr1GRQR5V2sXrbkkejgQKDuhQXg82SkisZqG3EkaGgM_mfHJFFow',
                success: function(){

                    var map = new TVI.Mapping.GMap({
                        id: 'map',
                        mapControlType: 'small',
                        showViewButtons: false,
                        longitude: lng,
                        latitude: lat,
                        zoomLevel: 13
                    });
                    map.addMarker({
                        id: 'marker',
                        latitude:  lat,
                        longitude: lng
                    });

                }

            });

        });
    
        cmp.collectionForm = new TVI.Form({
            ID: 'collectionForm',
            handler: saveCollectionAddress,
            errorsEl: '.errors'
        });

        $('.changeToDeliver').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'delivery' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initDeliveryForm();
                        }

                    });
                }

            });
            return false;
        });

    };

    var saveCollectionAddress = function() {
        $('.contentContainer .loading').show();
        $('.contentContainer .TVI-formSubmit').hide();

        if ($("input[name='chooseAddress']:checked").val() == undefined) {
            $('.contentContainer .loading').hide();
            $('.contentContainer .TVI-formSubmit').show();
            $('.contentContainer .errors').html('Please choose an address').show();
            return;
        }
        cmp.collectionForm.submit({

            url: '/handlers/checkout.aspx/saveCollectionAddress',
            data: {
               'addressID' : $("input[name='chooseAddress']:checked").val()
            },

            success: function(d) {
                TVI.ajax({

                    url: '/handlers/checkout.aspx/getForm',
                    data: { 'form': 'billing' },
                    responseType: 'text',
                    success: function(e) {
                        /* Constructor */
                        TVI.Popup.show({

                            title: 'Popup',
                            template: e,
                            success: function() {
                                initForm();
                                initBillingForm();
                            }

                        });
                    }

                });
            },
            failure: function(d) {
                $('.loading').hide();
                $('.TVI-formSubmit').show();
                cmp.collectionForm.error(d.errors);
            }
        });
    };

    var initDeliveryForm = function() {

        pageTracker._trackPageview("/newcheckout/delivery");

        $("input[name='chooseAddress']").click(function() {
            // If cust chooses to create a new address show the address form
            if ($("input[name='chooseAddress']:checked").val() == 'new') {
                $('#createAddress').show();
                $('#existingBilling').hide();
                // Copy also billing value to new form in case they selected it first
                var alsoBillingVal = $('#existingBilling input[name="deliveryBillingSame"]:checked').val()
                $('#createAddress input[name="deliveryBillingSame"][value='+ alsoBillingVal +']').click();
            }
            else {
                $('#createAddress').hide();
                $('#existingBilling').show();
                // Copy also billing value to new form in case they selected it first
                var alsoBillingVal = $('#createAddress input[name="deliveryBillingSame"]:checked').val()
                $('#existingBilling input[name="deliveryBillingSame"][value='+ alsoBillingVal +']').click();
            }

        });


        $('.changeToCollect').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'collection' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initCollectionForm();
                        }

                    });
                }

            });
            return false;
        });



        cmp.deliveryForm = new TVI.Form({

            ID: 'deliveryForm',
            handler: saveDeliveryAddress,
            errorsEl: '.errors'
        });


        $('.lookup').click(function() {

            TVI.ajax({
                url: '/handlers/checkout.aspx/lookupPostcode',
                data: { 'postcode': cmp.deliveryForm.field('postcode').val() },
                responseType: 'text',
                success: function(d) {
                    $('#selectAddress').html(d).parent().show();
                    $('#dropAddresses').change(function() {
                        TVI.ajax({
                            url: '/handlers/checkout.aspx/fetchFullAddress',
                            data: { 'ID': $('#dropAddresses').val() },
                            success: function(d) {
                                cmp.deliveryForm.field('name').val(d.name);
                                if (d.line2 != "") {
                                    cmp.deliveryForm.field('line1').val(d.line1 + ", " + d.line2);
                                }
                                else {
                                   cmp.deliveryForm.field('line1').val(d.line1);
                                }
                                cmp.deliveryForm.field('line2').val(d.line3);
                                cmp.deliveryForm.field('town').val(d.town);
                                cmp.deliveryForm.field('county').val(d.county);
                            }

                        });
                    });
                }

            });
            return false;
        });

        TVI.event('.submitDelivery', 'click', function() {
            saveDeliveryAddress();
        });

        if (!$('#existingAddress').is(':visible')) {
            $('#createAddress').show();
            //$("input[name='chooseAddress']").click();
        }
    }

    var saveDeliveryAddress = function() {
    
        $('.contentContainer .loading').show();
        $('.contentContainer .TVI-formSubmit').hide();

        if ($("input[name='chooseAddress']:checked").val() == undefined && !$('#createAddress').is(':visible')) {
            $('.contentContainer .loading').hide();
            $('.contentContainer .TVI-formSubmit').show();
            $('.contentContainer .errors').html('Please choose or create an address').show();
            return;
        }
        
        cmp.deliveryForm.submit({

            url: '/handlers/checkout.aspx/saveDeliveryAddress',
            data: {
               'addressID' : $("input[name='chooseAddress']:checked").val(),
               'alsoBilling' : $("input[name='deliveryBillingSame']:checked").val()
            },

            success: function(d) {
                TVI.ajax({

                    url: '/handlers/checkout.aspx/getForm',
                    data: { 'form': d.nextForm },
                    responseType: 'text',
                    success: function(e) {
                        /* Constructor */
                        TVI.Popup.show({

                            title: 'Popup',
                            template: e,
                            success: function() {
                                initForm();
                                if (d.nextForm == "billing") {
                                    initBillingForm();
                                }
                                else {
                                    initConfirmForm();
                                }
                            }

                        });
                    }

                });
            },
            failure: function(d) {
                $('.loading').hide();
                $('.TVI-formSubmit').show();
                cmp.deliveryForm.error(d.errors);
            }
        });
           
    }
    
    var initBillingForm = function() {

    pageTracker._trackPageview("/newcheckout/billing");
        
        $("input[name='chooseAddress']").change(function() {
            // If cust chooses to create a new address show the address form
            if ($("input[name='chooseAddress']:checked").val() == 'new') {
                $('#createAddress').show();
                $('#existingBilling').hide();
            }
            else {
                $('#createAddress').hide();
                $('#existingBilling').show();
            }

        });


        cmp.billingForm = new TVI.Form({

            ID: 'billingForm',
            handler: saveBillingAddress,
            errorsEl: '.errors'
        });


        $('.lookup').click(function() {

            TVI.ajax({
                url: '/handlers/checkout.aspx/lookupPostcode',
                data: { 'postcode': cmp.billingForm.field('postcode').val() },
                responseType: 'text',
                success: function(d) {
                    $('#selectAddress').html(d).parent().show();
                    $('#dropAddresses').change(function() {
                        TVI.ajax({
                            url: '/handlers/checkout.aspx/fetchFullAddress',
                            data: { 'ID': $('#dropAddresses').val() },
                            success: function(d) {
                                cmp.billingForm.field('name').val(d.name);
                                 if (d.line2 != "") {
                                    cmp.billingForm.field('line1').val(d.line1 + ", " + d.line2);
                                }
                                else {
                                   cmp.billingForm.field('line1').val(d.line1);
                                }
                                cmp.billingForm.field('line2').val(d.line3);
                                cmp.billingForm.field('town').val(d.town);
                                cmp.billingForm.field('county').val(d.county);
                            }

                        });
                    });
                }

            });
            return false;
        });

        TVI.event('.submitBilling', 'click', function() {
            saveBillingAddress();
        });

        if (!$('#existingAddress').is(':visible')) {
            $('#createAddress').show();
            $("input[name='chooseAddress']").click();
        }

    }

    var saveBillingAddress = function() {
        $('.contentContainer .loading').show();
        $('.contentContainer .TVI-formSubmit').hide();

        if ($("input[name='chooseAddress']:checked").val() == undefined && !$('#createAddress').is(':visible')) {
            $('.contentContainer .loading').hide();
            $('.contentContainer .TVI-formSubmit').show();
            $('.contentContainer .errors').html('Please choose or create an address').show();
            return;
        }
        
        cmp.billingForm.submit({

            url: '/handlers/checkout.aspx/saveBillingAddress',
            data: {
               'addressID' : $("input[name='chooseAddress']:checked").val()
            },

            success: function(d) {
                cmp.billingForm.el.find('.loading').hide();
                cmp.billingForm.el.find('.TVI-formSubmit').show();
                getConfirmPage();
            },
            failure: function(d) {
                cmp.billingForm.el.find('.loading').hide();
                cmp.billingForm.el.find('.TVI-formSubmit').show();
                cmp.billingForm.error(d.errors);
            }
        });
            
    }

// Confirmation page
    var initConfirmForm = function() {

    pageTracker._trackPageview("/newcheckout/confirm");
        
        $('.editBilling').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'billing' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initBillingForm();
                        }

                    });
                }

            });
            return false;
        });
        
         $('.editAddress').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'delivery' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initDeliveryForm();
                        }

                    });
                }

            });
            return false;
        });
        
         $('.editCollection').click(function() {

            TVI.ajax({

                url: '/handlers/checkout.aspx/getForm',
                data: { 'form': 'collection' },
                responseType: 'text',
                success: function(d) {
                    /* Constructor */
                    TVI.Popup.show({

                        title: 'Popup',
                        template: d,
                        success: function() {
                            initForm();
                            initCollectionForm();
                        }

                    });
                }

            });
            return false;
        });
        
        $('.confirmProducts a').click(function() {
            TVI.ajax({

                url: '/handlers/checkout.aspx/updateBasketProduct',
                data: {
                   'itemID' : $(this).parents('.product').attr('id').substring(7),
                   'quantity' : $(this).parent().find('input').val(),
                   'action' : $(this).attr('class')
                },

                success: function(d) {
                    getConfirmPage();
                },
                failure: function(d) {
                    $('.itemErrors').html(d.errors[0].message);
                }
            });
            return false;
        });

        $('.offerProducts a').click(function() {
            TVI.ajax({

                url: '/handlers/checkout.aspx/addToBasket',
                data: {
                   'itemID' : $(this).parents('.product').attr('id').substring(14),
                   'quantity' : $(this).parent().find('input').val()
                },

                success: function(d) {
                    getConfirmPage();
                },
                failure: function(d) {
                    $('.specialErrors').html(d.errors[0].message);
                }
            });
            return false;
        });
        
        $('.promoCode a').click(function() {
            TVI.ajax({

                url: '/handlers/checkout.aspx/addDiscount',
                data: {
                   'discountCode' : $(this).parent().find('input').val()
                },
                success: function(d) {
                    getConfirmPage();
                },
                failure: function(d) {
                    $('.discountErrors').html(d.errors[0].message);
                }
            });
            return false;
        });
        
        $('.discount a').click(function() {
            TVI.ajax({

                url: '/handlers/checkout.aspx/removeDiscount',
                data: {
                   'discountID' : $(this).parent().attr('ID').substring(8)
                },
                success: function(d) {
                    getConfirmPage();
                },
                failure: function(d) {
                    $('.discountErrors').html(d.errors[0].message);
                }
            });
            return false;
        });
        
    };

    var getConfirmPage = function() {
        TVI.ajax({
            url: '/handlers/checkout.aspx/getForm',
            data: { 'form':'confirm' },
            responseType: 'text',
            success: function(e) {
                /* Constructor */
                TVI.Popup.show({
                    title: 'Popup',
                    template: e,
                    success: function() {
                        initForm();
                        initConfirmForm();
                    }
                });
            }
        });
    };

    /* Public */

    TVI.apply(cmp, {

    /* Properties */

    /* Methods */

});


TVI.ready(init);


return cmp;


} ();