/* Checkout 
_____________________________________________________________ */

$(document).ready(function() {
    checkout.add_custom_validators();
});

checkout = {

    aCustomerDetails : null,
    bNoCheckout : false,
    iNoRegUserId : null,
    iRetailByPass : 3,
    iCallCentre : 2,
    iSubTotal: 0,
    aRewards : new Array(),
    aPromoCode : null,
    aBookingFee : 0.00,
    bViewingSummary: false,
    iConfirmedSMS: null,

    displaySummary : function() {

        // booking.displayLogin(1); // login prompt
        $("#service_information_bot").hide();
        checkout.bNoCheckout = true;
        $('#main_content #content_panel')
                .html('<div id="booking_panel"></div>');
        $('body').removeClass('return').removeClass('single');
        checkout.customerDetails();
        booking.displaySidePanelSummary();
    },
    sortTicketsByPrice : function(a, b) {
        return a.ticket_price - b.ticket_price;
    },
    ticketSummary : function() {
        checkout.iSubTotal = 0;

         for ( var i in booking.aTicketSelection) {
            checkout.iSubTotal += parseFloat(booking.aTicketSelection[i].standard_departure_price);
        }
        checkout.iSubTotal += parseFloat(booking.iBookingFee);
        checkout.iSubTotal += parseFloat(checkout.getAddonCost());
        $.ajax({url: '/ticket_booking.php?action=summary_form',
                dataType: 'json',
                async: false,
                success: function(response){
                    $('#main_content #content_panel #booking_panel').prepend(response.html);
                    checkout.setSubtotal();
                    checkout.applyRewards(booking.aTicketSelection);
                    checkout.cleanPromo();
                    checkout.initPromo();
                    checkout.initSMSFee();
                    checkout.initAddOns();
                    checkout.initAddonItems();
                    $('.booking_total_cost span').html(
                            'Total Cost: &pound;' + general.formatNumber(
                                    checkout.getTotalCost(), 2));
                    $('#booking_fee .journey_price').html('&pound;' + general.formatNumber(booking.iBookingFee, 2));
                }});
    },
    getAddonCost: function(){
        var cost = 0.00
        $.ajax({url: '/ticket_booking.php?action=get_addon_cost',
                dataType: 'json',
                async : false,
                cache : false,
                success: function(response){
                    cost = response.cost;
                }});
        return cost;
    },
    setSubtotal: function(valueOfTickets) {
        $('#subTotal').html('Subtotal: &pound;' + checkout.iSubTotal.toFixed(2));
    },
    initAddOns: function(){
        $('.addon_open').click(function(e){
            e.preventDefault();
            if($('#addon_modal').length == 0)
            {
                $('body').append('<div id="addon_modal"></div>');
            }
            $.ajax({url: $(this).attr('href'),
                    dataType: 'json',
                    success: function(response)
                    {
                        $('#addon_modal').html(response.html);
                        $("#addon_modal").dialog('destroy');
                        $('#addon_modal').attr('title','Add-ons');
                        $("#addon_modal").dialog({ autoOpen: false, modal: true, bgiframe: true, buttons: {
                        "Cancel": function() {
                                    $("#addon_modal").dialog('close');
                                    return false;
                                },
                        "Add": function() {
                                    $("#addon_form").submit();
                                    return false;
                                }        
                                
                            },
                            overlay: {
                                opacity: 0.6,
                                background: '#000000' 
                            },
                            width: 714, height: 416
                        });
                        
                        $("#addon_modal").dialog('open');
                        $('#addon_modal_scroll_area').jScrollPane({showArrows:true, scrollbarWidth: 16});
                        checkout.initAddonForm();
                    }});
        });
    },
    initAddonForm: function() {
        $('ul#addons li span select').change(function(e){
            if($(this).parent().parent().children('span.added').children('input:checked').length > 0)
            {
                var new_amount = parseFloat($(this).parent().parent().children('.hidden_cost').val()) * parseInt($(this).val());
                $(this).parent().parent().children('.line_amount').html('&pound;'+general.formatNumber(new_amount,2));
                $(this).parent().parent().children('.line_cost').val(new_amount);
                checkout.addonTotal();
            }
        });
        
        $('ul#addons li span.added input').click(function(e){
            if($(this).parent().parent().children('span.added').children('input:checked').length > 0)
            {
                var new_amount = parseFloat($(this).parent().parent().children('.hidden_cost').val()) * parseInt($(this).parent().parent().children('span.passengers').children('select').val());
                $(this).parent().parent().children('.line_amount').html('&pound;'+general.formatNumber(new_amount,2));
                $(this).parent().parent().children('.line_cost').val(new_amount);
                $(this).parent().parent().addClass('active');
                checkout.addonTotal();
            }
            else
            {
                $(this).parent().parent().children('.line_amount').html('&pound;0.00');
                $(this).parent().parent().removeClass('active');
                $(this).parent().parent().children('.line_cost').val(0.00);
                checkout.addonTotal();
            }
            
        });
        
        $('.more_link').click(function(e){
            e.preventDefault();
            $(this).parent().parent().children('.description').toggle('fast', function(){
                  $('#addon_modal_scroll_area').jScrollPaneRemove();
                  $('#addon_modal_scroll_area').jScrollPane({showArrows:true, scrollbarWidth: 16});
              });

        });
        
        $('#addon_form').submit(function(e){
            e.preventDefault();
            $.ajax({url: $(this).attr('action'),
                   dataType: 'json',
                   data: $(this).serialize(),
                   async: 'false',
                   method: 'get',
                   success: function(response){
                        $('#journey_'+response.id+' table').append(response.html);
                        if($('#journey_'+response.id+' tr.add_on').length > 0)
                        {
                          $('#journey_'+response.id+' span.addonButton a').hide()
                        }
                        $("#addon_modal").dialog('close');
                        $('#addon_modal_scroll_area').jScrollPaneRemove();
                        $('#addon_modal').empty();
                        checkout.initAddonItems();
                        checkout.iSubTotal += response.cost;
                        booking.iAddonCost += response.cost;
                        booking.iAddonCount += response.count;
                        checkout.setSubtotal();
                        booking.displaySidePanelSummary();
                        $('.booking_total_cost span').html('Total Cost: &pound;' + checkout.getTotalCost().toFixed(2));
                   }});
            
        });
    },
    addonTotal: function(){
        var total_cost = 0.00;
        $('.line_cost').each(function(){
            total_cost += parseFloat($(this).val());
        });
        if(total_cost == 0)
        {
          $('#addon_total_cost').html('Add-ons Total: &pound;0.00');
        }
        else
        {
          $('#addon_total_cost').html('Add-ons Total: &pound;'+general.formatNumber(total_cost,2));
        }
    },
    initAddonItems: function(){
        $('tr.add_on span.remove a').click(function(e){
            e.preventDefault();
            var ids = $(this).parent().parent().parent().attr('id').split('_');
            $.ajax({url: '/ticket_booking.php?action=remove_addon&d_id='+ids[1]+'&a_id='+ids[2],
                    dataType: 'json',
                    async: 'false',
                    success: function(response){
                        checkout.iSubTotal -= response.cost;
                        booking.iAddonCost -= response.cost;
                        booking.iAddonCount--;
                        checkout.setSubtotal();
                        $('.booking_total_cost span').html('Total Cost: &pound;' + checkout.getTotalCost().toFixed(2))
                        $('#addon_'+response.d_id+'_'+response.a_id).remove();
                        if($('#journey_'+response.d_id+' tr.add_on').length == 0)
                        {
                          $('#journey_'+response.d_id+' span.addonButton a').show()
                        }
                        booking.displaySidePanelSummary();
                    }}); 
        });
    },
    initSMSFee : function() {
        if (booking.iSMSPassenger) { // only show the SMS stuff if its been enabled in the globals
            var totalTickets = booking.aTicketSelection.length;
            
            if (!checkout.iConfirmedSMS) {
                var html = '<span class="left">SMS alerts:</span><span class="right"><input id="confirmation_sms" type="checkbox" />Please SMS me my confirmation (&pound;'+parseFloat(booking.iSMSFee).toFixed(2)+' x '+totalTickets+')</span>';
                $('.sms_fee').html(html);
                checkout.removeSMSFeeFromSession(); // could be hanging over in session
            
                $('#confirmation_sms').click(function() {
                    checkout.addSMSFee();
                });
            }
            else {
                var html = '<span class="remove"><a href="javascript: checkout.removeSMSFee();">Remove</a></span><span class="left"><span class="sms_text">Send SMS confirmation to '+ checkout.iConfirmedSMS +'</span></span><span class="right">&pound;' + (parseFloat(booking.iSMSFee) * totalTickets).toFixed(2) + '</span>';
                $('.sms_fee').html(html);
                checkout.updateTotalWithSMSFee();
            }
        }
    },
    updateTotalWithSMSFee: function() {
        // Update totals
        var totalTickets = booking.aTicketSelection.length;
        booking.iTicketSelectionCost = parseFloat(booking.iTicketSelectionCost);
        booking.iTicketSelectionCost = booking.iTicketSelectionCost 
            + (parseFloat(booking.iSMSFee) * totalTickets);
        
        $('.booking_total_cost span').html('Total Cost: &pound;' + checkout.getTotalCost().toFixed(2));
    },
    addSMSFee: function() {
        var mobile_number = '';
        var totalTickets = booking.aTicketSelection.length;
        
        if (booking.aLoggedIn && booking.aLoggedIn.mobile) {
            mobile_number = booking.aLoggedIn.mobile;
        }
        html = '<span class="remove"><a href="javascript: checkout.removeSMSFee();">Remove</a></span><span class="sms_text">Send SMS confirmation to </span><form id="sms_form"><input type="text" class="required" maxlength="11" size="11" id="sms_number" value="'+mobile_number+'"/>';
        html += '<button type="button" id="confirm_sms">Confirm</button></form>';
        $('.sms_fee').html(html);
        
        $('#confirm_sms').click(function(){
            var submitted_sms = $('#sms_number').val();
            var regex = /^07\d{9}$/;

            if(!(submitted_sms.match(regex))) {
                $('#sms_form').append('<span id="sms_error"></span>');
                $('#sms_error').html('Sorry! That doesn\'t look like a valid mobile number');
            }
            else {
                var confirmed_number = $('#sms_number').val();
                checkout.iConfirmedSMS = confirmed_number;
                $('#sms_error').remove();
                $('#sms_number').replaceWith(' ' + confirmed_number);
                $('#confirm_sms').remove();
                $('.sms_text').remove();
                
                $('#sms_form').replaceWith('<span class="left"><span class="sms_text">Send SMS confirmation to '+ confirmed_number +'</span></span><span class="right">&pound;' + (parseFloat(booking.iSMSFee) * totalTickets).toFixed(2) + '</span>');
                
                // If not logged in OR call centre or rpbu
                if((!booking.aLoggedIn || !booking.aLoggedIn.accountType) || (booking.aLoggedIn && (booking.aLoggedIn.accountType == checkout.iRetailByPass || booking.aLoggedIn.accountType == checkout.iCallCentre))) {
                    $('#phone_mobile').val(confirmed_number);
                }
                
                $.ajax( {
                    url : 'ticket_booking.php?action=add_sms_fee',
                    type : 'POST',
                    cache: false,
                    async : false,
                    data: {mobile_number: confirmed_number, amount: booking.iSMSFee},
                    dataType : 'json',
                    success : function(response) {
                        // do nothing just now
                    }
                });
                
                // Update totals
                checkout.updateTotalWithSMSFee();
            }
        });
    },
    removeSMSFee : function() {
        checkout.iConfirmedSMS = null;
        $('.sms_fee').html('');
        
        // If not logged in OR call centre or rpbu
        if((!booking.aLoggedIn || !booking.aLoggedIn.accountType) || (booking.aLoggedIn && (booking.aLoggedIn.accountType == checkout.iRetailByPass || booking.aLoggedIn.accountType == checkout.iCallCentre))) {
            $('#phone_mobile').val('');
        }
        
        checkout.removeSMSFeeFromSession();
        
        $('.booking_total_cost span').html('Total Cost: &pound;' + checkout.getTotalCost().toFixed(2));
        
        checkout.initSMSFee();
    },
    removeSMSFeeFromSession: function() {
        checkout.iConfirmedSMS  = null;
        
        $.ajax( {
            url : 'ticket_booking.php?action=remove_sms_fee',
            type : 'GET',
            cache: false,
            async : false,
            success : function(response) {
                // do nothing just now
            }
        });
    },
    cleanPromo : function() {
        costtmp = booking.iTicketSelectionCost;
        $.ajax( {
            url : 'ticket_booking.php?action=clean_promo',
            type : 'GET',
            dataType : 'json',
            success : function(response) {
                booking.iTicketSelectionCost = costtmp;
                if (response.code != "NULL") {
                    checkout.applyPromos(response.code);
                }
            }
        });
    },
    resetPromo : function() {
        $.ajax( {
            url : 'ticket_booking.php?action=remove_promo',
            type : 'GET'
        });
    },
    removePromo : function() {
        costtmp = booking.iTicketSelectionCost;
        booktmp = checkout.aBookingCost;
        bookingtmp = booking.iBookingFee;
        $
                .ajax( {
                    url : 'ticket_booking.php?action=remove_promo',
                    type : 'GET',
                    dataType : 'json',
                    success : function(response) {
                        booking.iBookingFee = bookingtmp;
                        booking.iTicketSelectionCost = costtmp;
                        checkout.aBookingCost = booktmp;
                        checkout.aPromoCode = null;
                        booking.iBookingFee = parseFloat(checkout.aBookingFee);
                        booking.iTicketSelectionCost += parseFloat(response.discount);
                        if (response.suppress_booking_fee == 1) {
                            checkout.aBookingFee = 0.00;
                        }
                        $('.booking_total_cost span').html(
                                'Total Cost: &pound;' + parseFloat(
                                        checkout.getTotalCost())
                                        .toFixed(2));
                        $('#promo_code_container')
                                .html(
                                        '<span class="left">Promo Code:</span><span class="right"><form name="promo_form" id="promo_form"><input type="text" class="textfield" name="promo_code" id="promo_code" /><button type="button" id="apply_promo">Apply Promo</button></form><span id="promo_error"></span></span>');
                        $('.promo_journey').remove();
                        
                        checkout.initPromo();

                    }
                });
    },
    
    
    initPromo : function() {
      $('#promo_form').submit(function(e) {
          e.preventDefault();
      });
      $('#apply_promo')
              .click(
                      function(e) {
                          e.preventDefault();
                          costtmp = booking.iTicketSelectionCost;
                          $.get(
                                          'ticket_booking.php?action=check_promo_valid&promo_code=' + $(
                                                  '#promo_code').val(),
                                          function(response) {
                                              booking.iTicketSelectionCost = costtmp;
                                              if (response) {
                                                  checkout.applyPromos($(
                                                          '#promo_code')
                                                          .val());
                                              } else {
                                                  $('#promo_error').html(
                                                          response);
                                                  $('#promo_error').show();
                                              }
                                          }, 'text');

                      });

    },
    
    
    applyPromos : function(promo_code) {
        costtmp = booking.iTicketSelectionCost;
        bookingtmp = booking.iBookingFee;

        $.ajax( {
            url : 'ticket_booking.php?action=set_promo&promo_code=' + promo_code,
            type : 'GET',
            dataType : 'json',
            success : function(response) {
                booking.iTicketSelectionCost = costtmp;
                booking.iBookingFee = bookingtmp;
                if (response.old_booking_fee != '') checkout.aBookingFee = response.old_booking_fee;

                if (response.error == "false") {
                    $('#promo_error').hide();

                    $.each(response.ticket_ids,function(k,v) {
                        $('#journey' + v).append('<p class="promo_journey">Promo!</p>');    
                    });

                    var applies_to = (response.promo_type == "lowest_ticket") ? 'The discount applies to the cheapest ticket in your basket' : 'The discount applies to all valid tickets in your basket';
                    $('#promo_code_container').html('<span class="remove"><a href="javascript: void(0);" onclick="checkout.removePromo()">Remove</a></span><span class="left">'
                                                  + response.name + ' (' + response.value + ')'
                                                  + '</span><span class="right promo_applied">Includes discount worth &pound;'
                                                  + parseFloat(response.discount).toFixed(2)
                                                  + '</span><span class="left applies_to">'+applies_to+'</span>');
                    booking.iTicketSelectionCost -= response.discount;
                    checkout.aPromoCode = response.code;

                    if (response.suppress_booking_fee == 1) {
                        $('#booking_fee').append('<p class="promo_journey">Promo!</p>');
                        $('.promo_applied').html($('.promo_applied').html() + '<br />No Booking Fee &pound;' + response.old_booking_fee);
                    }

                    var totalCost = checkout.getTotalCost();

                    $('.booking_total_cost span').html('Total Cost: &pound;' + totalCost.toFixed(2));
                } else {
                    booktmp = checkout.aBookingCost;
                    $.ajax({
                        url : 'ticket_booking.php?action=remove_promo',
                        type : 'GET',
                        dataType : 'json',
                        success : function(response) {
                            booking.iTicketSelectionCost = costtmp;
                            booking.iBookingFee = bookingtmp;
                            booking.iTicketSelectionCost = costtmp;
                            checkout.aBookingCost = booktmp;
                            checkout.aPromoCode = null;
                            booking.iBookingFee = parseFloat(checkout.aBookingFee);

                            if (response.suppress_booking_fee == 1) {
                                booking.iTicketSelectionCost += booking.iBookingFee;
                                checkout.aBookingFee = 0.00;
                            }

                            $('.booking_total_cost span').html('Total Cost: &pound;' + checkout.getTotalCost().toFixed(2));
                        }
                    });
                    
                    $('#promo_error').html(response.error);
                    $('#promo_error').show();
                }
            }
        });
    },
    
    
    
    applyRewards : function(aTickets) {
        if ((booking.aLoggedIn && booking.aLoggedIn.id)) {
            checkout.aRewards = [];
            
            $.ajax( {
                type : "POST",
                url : '/ticket_booking.php?action=get_rewards',
                async : false,
                cache : false,
                dataType : "json",
                data : ( {
                    user_id : booking.aLoggedIn.id
                }),
                success : function(data) {
                    for (var i in data) checkout.aRewards.push(data[i]);
                }
            });

            var iFreeTicketsUsed = checkout.aRewards.length;
            
            if (iFreeTicketsUsed > 0) {
                var fValueOfFreeTickets = 0;
                var freeTicketsToDepartures = new Array();
                
                for (var i in checkout.aRewards) {
                    var freebie = checkout.aRewards[i];

                    booking.iTicketSelectionCost -= parseFloat(freebie.amount);
                    fValueOfFreeTickets += parseFloat(freebie.amount);

                    if (!freeTicketsToDepartures[freebie.id]) freeTicketsToDepartures[freebie.id] = 0;

                    freeTicketsToDepartures[freebie.id]++;
                }
                
                for (var ticket_id in freeTicketsToDepartures) $('#journey' + ticket_id).append('<p class="free_journey">' + freeTicketsToDepartures[ticket_id] + ' Free!</p>');
                
                $('.free_ticket').html('<span class="left">Greyhound Rewards:</span><span class="right">Includes ' + iFreeTicketsUsed + ' FREE Ticket(s) worth &pound;' + fValueOfFreeTickets.toFixed(2) + '</span>');

                $('.free_ticket').show();
            }
        }
        
        return '';
    },


    removeTickets : function(id) {

        if (booking.aTicketSelection) {
            booking.selectedTicketToggle(id);

            var aTmp = new Array();
            for ( var i in booking.aTicketSelection) {
                if (id != booking.aTicketSelection[i].id) {
                    aTmp.push(booking.aTicketSelection[i]);
                }
            }

            booking.aTicketSelection = aTmp;
            //checkout.iConfirmedSMS = null;
            $.ajax({url: '/ticket_booking.php?action=remove_departure_addons&d_id='+id,
                    dataType: 'json',
                    async: false,
                    success: function(response){
                      booking.iAddonCost -= response.cost;
                      booking.iAddonCount -= response.count;
                    }
            });
            booking.saveSessionTicketSelection();
            if (booking.aTicketSelection.length > 0) {
                booking.resetForm();
                checkout.displaySummary();
                booking.displaySidePanelSummary();
            } else {
                booking.resetForm();
                $('#main_content #content_panel #homepage_panel').append(
                        '' + booking.sHomepagePanel + '');
                booking.homepagePanelInit();
            }
        }
    },

    detailsSummary : function() {
        var regex = /\d/g; // any number

        sHTML = '<div id="checkout_details"><h2>Your Details</h2><p class="edit_details"><a href="javascript: booking.loadUserDetails(1)">Edit your details</a></p><ul class="your_details">';
        sHTML += '<li>' + checkout.aCustomerDetails.name + ' '
                + checkout.aCustomerDetails.surname + '</li>';
                if(checkout.aCustomerDetails.house_no !='' || checkout.aCustomerDetails.street !='')
        if (regex.test(checkout.aCustomerDetails.house_no)) {
            sHTML += '<li>' + checkout.aCustomerDetails.house_no + ' '
                    + checkout.aCustomerDetails.street + '</li>';
        } else {
            sHTML += '<li>' + checkout.aCustomerDetails.house_no + '</li>';
            sHTML += '<li>' + checkout.aCustomerDetails.street + '</li>';
        }
                if(checkout.aCustomerDetails.town != '')
                {
                    sHTML += '<li>' + checkout.aCustomerDetails.town + '</li>';
                }
                if(checkout.aCustomerDetails.town != '')
                { 
                    sHTML += '<li>' + checkout.aCustomerDetails.postcode + '</li>';
                }
        if (checkout.aCustomerDetails.phone != '')
            sHTML += '<li><span>Phone</span>' + checkout.aCustomerDetails.phone + '</li>';
        if (checkout.aCustomerDetails.mobile != '')
            sHTML += '<li><span>Mobile</span>' + checkout.aCustomerDetails.mobile + '</li>';
        sHTML += '<li><span>Email</span>' + checkout.aCustomerDetails.email + '</li></ul></div>';

        $('#main_content #content_panel #booking_panel').append(sHTML);
    },

    formSkipRegistration : function() {

        var sHTML = '<div id="no_register"><h2>Buy without Registering</h2><form class="registration_basic_form" method="post" action="/registration.php?action=save_basic">'
                + '<fieldset><legend>Buy without Registering</legend><ol>'
                + '<li class="error"><p class="msg" style="display: none;"></p></li>'
                + '<li><label for="name">First Name:<span class="required">*</span></label><input class="textfield required" type="text" id="name" name="application_name" /></li>'
                + '<li><label for="surname">Last Name:<span class="required">*</span></label><input class="textfield required" type="text" id="surname" name="application_surname" /></li>'
                + '<li><label for="email">Email:<span class="required">*</span></label><input class="textfield required email alreadyregistered" type="text" id="email" name="application_email" /></li>'
                + '<li><label for="phone_mobile">Mobile: <span class="notice">For free SMS <br />service updates!</span></label><input class="textfield" type="text" id="phone_mobile" name="application_phone_mobile" /></li>'
                + '<li class="tcs"><label for="terms">I agree to the <a href="/terms-conditions" class="external_link" target="_blank">Terms &amp; Conditions</a></label><input type="checkbox" id="terms" value="1" class="termsXXconditions"/></li>'
                + '<li class="tcs"><label for="terms">I understand tickets are not transferable</label><input type="checkbox" id="notrans" value="1" class="termsXXconditions"/></li>'
                + '<li class="tcs"><label for="application_optin">Send me information and news of special offers from Greyhound UK</label><input type="checkbox" name="application_optin" id="noreg_optin" value="1" class="termsXXconditions"/></li>'
                + '<li><button type="button" class="register">Continue</button></li>'
                + '</li></ol></fieldset></form></div>';

        return sHTML;
    },

    customerDetailsNoReg : function(responseText, statusText) {
        if (responseText) {
            var aData = eval('(' + responseText + ')');
            if (aData.id && aData.name && aData.email) {
                $('#main_content #content_panel #booking_panel #no_register')
                        .remove();
                $('#main_content #content_panel #booking_panel #login_register')
                        .remove();
                
                checkout.iNoRegUserId = aData.id;
                $('#main_content #content_panel #booking_panel .login_form')
                        .remove();
                $(
                        '#main_content #content_panel #booking_panel .registration_basic_form')
                        .remove();

                sHTML = '<h2>Your Details</h2><ul class="your_details">';
                sHTML += '<li>' + aData.name + '</li>';
                sHTML += '<li><span>Email</span>' + aData.email + '</li>';
                sHTML += '<li><span>Mobile</span>' + aData.mobile + '</li>';

                $('#main_content #content_panel #booking_panel').append(
                        sHTML + '</ul>');

                checkout.world_pay_form();
            }
        }
    },

    customerDetails : function() {
        if (!booking.aLoggedIn || !booking.aLoggedIn.id) {
            checkout.ticketSummary();
            $('#main_content #content_panel #booking_panel').append('<div id="login_register"><h2>Login or Register</h2>' + $('#login_dialog').html() + '</div>');
            $('#main_content #content_panel #booking_panel .login_form fieldset ol').append('<li><button type="button" class="register">Continue</button></li>');
            $('#main_content #content_panel #booking_panel').append(checkout.formSkipRegistration());
            $('#login_email').blur(function() {
                var login_email = $('#login_email').val();
                login_email = $.trim(login_email);
                $('#login_email').val(login_email);
            });

            $('#booking_panel .login_form .register') .click(function() {
                if ($('#booking_panel .login_form input#sign_in_new_customer').is(':checked')) {
                    if ($("#main_content #content_panel #booking_panel .login_form").validate().form() == true) {
                        var sEmail = $('#main_content #content_panel #booking_panel .login_form #login_email').val();

                        $('#main_content #content_panel #booking_panel #login_register').remove();
                        $('#main_content #content_panel #booking_panel #no_register').remove();

                        $('#main_content #content_panel #booking_panel').append('<h2>Register</h2>');
                        $('#main_content #content_panel #booking_panel').append($('.registration_form_wrap').html());
                        //$('#main_content #content_panel #booking_panel #password-strength').remove();
                        //$(".password").pstrength();
                        $('#main_content #content_panel #booking_panel .registration_form fieldset ol').append('<li><button type="button" class="register">Continue</button></li>');
                        $('#main_content #content_panel #booking_panel .registration_form #registration_email').val(sEmail);
                        $('#main_content #content_panel #booking_panel .registration_form .register').click(function() {
                            if ($("#booking_panel .registration_form").validate({
                                invalidHandler: function(e, validator) {
                                    var errors = validator.numberOfInvalids();

                                    if (errors) $("#reg_error").show();
                                    else $("#reg_error").hide();
                                }
                            }).form() == true) {
                                if ($('#booking_panel .registration_form input#terms').is(':checked')) {
                                    booking.iCheckoutRedirect = 1;
                                    $('#reg_error').hide();
                                    $('#main_content #content_panel #booking_panel .registration_form').ajaxSubmit({
                                        success : function(responseText, statusText) {
                                            booking.updateLogin(responseText, statusText);
                                        },
                                        timeout : 10000
                                    });
                                    return false;
                                } else {
                                    if ($("#booking_panel .registration_form label#agree").length <= 0) {
                                        $("#booking_panel .registration_form input#terms").parent().append('<label id="agree">You must agree to the Terms &amp; Conditions to register</label>');
                                        $('#reg_error').show();
                                    }
                                }
                            }

                            return false;
                        });
                    }
                } else if ($('#booking_panel .login_form input#sign_in_existing_customer').is(':checked')) {
                    $('#booking_panel .login_form input.passfield').addClass('required');

                    if ($("#main_content #content_panel #booking_panel .login_form").validate().form() == true) {
                        booking.iCheckoutRedirect = 1;

                        $('#main_content #content_panel #booking_panel .login_form').ajaxSubmit({
                            success : function(responseText, statusText) {
                                booking.updateLogin(responseText, statusText);
                            },
                            timeout : 10000
                        });
                    }

                    $('#booking_panel .login_form input.passfield').removeClass('required');
                }
            });

            $('#booking_panel .registration_basic_form .register').click(function() {
                var fail = 0;

                if (!$('#main_content #content_panel #booking_panel .registration_basic_form').validate().form()) fail += 1;
                if (!$('#booking_panel .registration_basic_form input#terms').is(':checked')) fail += 2;
                if (!$('#booking_panel .registration_basic_form input#notrans').is(':checked')) fail += 4;

                if (fail > 0) {
                    if (fail & 2) {
                        if ($("#booking_panel .registration_basic_form label#agree_terms").length <= 0)
                            $("#booking_panel .registration_basic_form input#terms").parent().append('<label class="agree" id="agree_terms">You must agree to the Terms &amp; Conditions to continue</label>');
                    } else {
                        $("#booking_panel .registration_basic_form label#agree_terms").remove();
                    }

                    if (fail & 4) {
                        if ($("#booking_panel .registration_basic_form label#agree_notrans").length <= 0)
                            $("#booking_panel .registration_basic_form input#notrans").parent().append('<label class="agree" id="agree_notrans">You must acknowledge that tickets cannot be transferred to continue</label>');
                    } else {
                        $("#booking_panel .registration_basic_form label#agree_notrans").remove();
                    }
                } else {
                    booking.iCheckoutRedirect = 1;

                    $('#main_content #content_panel #booking_panel .registration_basic_form').ajaxSubmit({
                        success : function(responseText, statusText) {
                            checkout.customerDetailsNoReg(responseText, statusText);
                        },
                        timeout : 10000
                    });
                }
            });
        } else {
            var tempCost = booking.iTicketSelectionCost;
            $.ajax({
                type : "POST",
                url : '/registration.php?action=registered_user_details',
                async : false,
                cache : false,
                dataType : "json",
                data : ( {
                    user_id : booking.aLoggedIn.id
                }),
                success : function(data) {
                    checkout.aCustomerDetails = data;
                },
                complete : function() {
                    booking.iTicketSelectionCost = tempCost; 
                    checkout.ticketSummary();
                    checkout.detailsSummary();
                    checkout.handleRetailCustomers();
                    checkout.world_pay_form(checkout.aCustomerDetails);
                    checkout.aCustomerDetails = null;
                }
            });
        }
    },
    // - rpbu and call centre
    handleRetailCustomers : function(accountType) {
        if (!accountType) {
            accountType = checkout.aCustomerDetails.accountType;
        }

        if (accountType == checkout.iRetailByPass
                || accountType == checkout.iCallCentre) {
            $('#checkout_details').html();
            var html = '<form class="registration_basic_form" method="post" action="/registration.php?action=save_basic">'
                    + '<h2>Retail Code</h2>'
                    + '<ul class="retail_bypass"><li><label for="retail_code">Retail Code:<span class="required">*</span></label><input name="application_retail_code" id="retail_code" value="" class="textfield required validateretailcode" type="password"/></ul>'
                    + '<h2>Customer details</h2>'
                    + '<ol><li><label for="name">First Name:<span class="required">*</span></label><input class="textfield required" type="text" id="name" name="application_name" /></li>'
                    + '<li><label for="surname">Last Name:<span class="required">*</span></label><input class="textfield required" type="text" id="surname" name="application_surname" /></li>'
                    + '<li><label for="email">Email:<span class="required">*</span></label><input class="textfield required email" type="text" id="email" name="application_email" /></li>'
                    + '<li><label for="phone_mobile">Mobile:</label><input class="textfield" type="text" id="phone_mobile" name="application_phone_mobile" /></li>'
                    + '</li></ol></form>';

            $('#checkout_details').html(html);
        }
    },



    world_pay_form: function(details) {
        var customer_id = (checkout.iNoRegUserId) ? checkout.iNoRegUserId : booking.aLoggedIn.id;

        $.ajax({
            type: "POST",
            url: '/ticket_booking.php?action=world_pay_form', // Gets the world pay form as html
            async: false,
            cache: false,
            dataType: "html",
            data: ({ user_id : customer_id }),
            success : function(data) {
                $('#main_content #content_panel #booking_panel').append(data);
                
                if (details) {
                    if (details.accountType == checkout.iRetailByPass) {
                        // change the action on the form to point direct to callback
                        $('form#booking').attr("action", '/ticket_booking.php?action=rpbu_booking_callback');
                    }
                }
                
                $('#main_content #content_panel #booking_panel .submit:first').click(function() {
                    if ($('input#notrans').val() && !$('input#notrans').is(':checked')) {
                        $('#notrans_error').show();

                        $('input#notrans').click(function() {
                            if ($('input#notrans').is(':checked')) $('#notrans_error').hide();
                            else $('#notrans_error').show();
                        });
                    } else {
                        $('#main_content #content_panel #booking_panel .submit:first').attr('disabled', 'disabled');

                        if (details) {
                            if (details.accountType == checkout.iRetailByPass || details.accountType == checkout.iCallCentre) {
                                // Save the customers details to the DB
                                if ($('#booking_panel .registration_basic_form').validate().form() == true) {
                                    $('#booking_panel .registration_basic_form').ajaxSubmit({
                                        success: function(responseText, statusText) {
                                            var actualCustomer = eval('(' + responseText + ')');

                                            $('#hidden_email').val($('.registration_basic_form input#email').val());
                                            $('#hidden_name').val($('.registration_basic_form input#name').val() + ' ' + $('.registration_basic_form input#surname').val());
                                            $('#hidden_tel').val(''); // Maybe grab these at a later date via the form?
                                            $('#hidden_postcode').val('');
                                            $('#hidden_address').val('');
                                            $('form#booking').append('<input type="hidden" name="rpbu_user" value="' + customer_id + '" />');

                                            if (details.accountType == checkout.iRetailByPass) checkout.save_booking(actualCustomer.id);
                                            else checkout.save_booking(actualCustomer.id, customer_id); // Call centre
                                        },
                                        timeout : 10000
                                    });
                                } else {
                                    $('#main_content #content_panel #booking_panel .submit:first').removeAttr('disabled');
                                }
                            } else { // any other type of user
                                checkout.save_booking();
                            }
                        } else {
                            checkout.save_booking(); // unregistered user
                        }
                    }
                });
            }
        });
    },



    save_booking : function(customer_id, call_centre_user_id) {
        $.ajax({
            url: '/ticket_booking.php?action=check_ticket_validity',
            dataType: 'json',
            success: function(response) {
                if (response.status == "valid") {
                    if (!customer_id) customer_id = (checkout.iNoRegUserId) ? checkout.iNoRegUserId : booking.aLoggedIn.id;
      
                    if (customer_id) {
                        var cost = 0;
                  
                        $.ajax( {
                            type : "POST",
                            url : '/ticket_booking.php?action=save_booking',
                            async : false,
                            cache : false,
                            dataType : "json",
                            data : ( {
                                user_id : customer_id,
                                buy_optin: $('#buy_optin').attr('checked')
                            }),
                            success : function(data) {
                                $("input[name='cartId']").val(data.cartId);
                                $("input[name=signature]").val(data.hash);
                                
                                if (!call_centre_user_id) $("input[name='M_id']").val(data.M_id);
                                else $("input[name='M_id']").val(data.M_id + '|' + call_centre_user_id);
                                
                                $("input[name='amount']").val(data.amount);
                                cost = data.amount;
                            },
                            complete : function() {
                                if ((parseFloat(cost) == 0) && (booking.aLoggedIn && booking.aLoggedIn.id && booking.aLoggedIn.accountType != checkout.iRetailByPass && booking.aLoggedIn.accountType != checkout.iCallCentre)) {
                                    // change the action on the form to point direct to callback
                                    $('form#booking').attr("action", '/ticket_booking.php?action=booking_callback');   
                                }
      
                                // xxx
                                
                                $('#booking').submit();
                            }
                        });
                    }
                } else {
                    booking.loadSessionTicketSelectionOnly();
                    
                    if (booking.aTicketSelection.length > 0) {
                        checkout.displaySummary();
                    } else {
                        booking.resetForm();
                        $('#main_content #content_panel #homepage_panel').append('' + booking.sHomepagePanel + '');
                        $('#add_journey_panel').html(booking.novalid_msg).attr('id','error_add_journey_panel');
                        booking.homepagePanelInit();
                        booking.displaySidePanel();
                    }
                }
            }
        });
    },
    
    
    getTotalCost: function() { 
        var cost = 0;
        $.ajax( {
            type : "POST",
            url : '/ticket_booking.php?action=get_total_cost',
            async : false,
            cache : false,
            dataType : "json",
            success : function(data) {
                cost = data.total_cost;    
            },
            complete : function() {
                // rien
            }
        });
        
        return cost;
    },

    /*reserve_availablity: function() {
        
        $.ajax({
            type: "POST",
            url: '/ticket_booking.php?action=save_booking_reserve',
            async: false,
            cache: false,
            dataType: "json",
            data: ({ user_id : booking.aLoggedIn.id, booking_code : $("input[name='cartId']").val() }),
            success: function(data) {
                
                if (data.confirmed == 1)
                {
                    $('#booking').submit();
                }
                else
                {
                    booking.resetForm();
                    booking.error('The tickets you have selected have become unavailable. Please re-enter your journey details and re-select a new fare.');
                }
            }
        });
    },*/
    add_custom_validators : function() {
        // Add a custom validator: checking to see of the email is associated with a registered user
        $.validator.addMethod(
            "alreadyregistered",
            function(value, element) {
                var isRegistered = 0;

                $.ajax({
                    url : '/registration.php?action=check_registered_user&email=' + value,
                    async : false,
                    cache : false,
                    dataType : "json",
                    success : function(data) {
                        isRegistered = data.registered;
                    }
                });

                return isRegistered == 0;
            },
            "Email in use. Please Login or use the Forgotten Password facility."
        );

        $.validator.addMethod(
            "alreadyregistered2",
            function(value, element) {
                var isRegistered = 0;

                if ($('#sign_in_new_customer:checked').val() == 'new_customer') {
                    $
                            .ajax( {
                                url : '/registration.php?action=check_registered_user&email=' + value,
                                async : false,
                                cache : false,
                                dataType : "json",
                                success : function(data) {
                                    isRegistered = data.registered;
                                }
                            });
                }
                return isRegistered == 0;
            },
            "Email in use. Please Login or use the Forgotten Password facility."
        );

        $.validator.addMethod(
            "termsconditions",
            function(value, element) {
                var temp = $(element).is(':checked');

                return temp;
            },
            'You must agree to the Terms &amp; Conditions.'
        );

        $.validator.addMethod(
            "notransfer",
            function(value, element) {
                var temp = $(element).is(':checked');

                return temp;
            },
            'You must acknowledge that tickets cannot be transferred.'
        );

        $.validator.addMethod(
            "validateretailcode",
            function(value, element) {
                var userCode;

                $.ajax( {
                    url : '/registration.php?action=get_retail_code_json&user_id=' + booking.aLoggedIn.id,
                    async : false,
                    cache : false,
                    dataType : "json",
                    success : function(data) {
                        userCode = data.code;
                    }
                });

                return userCode == value;
            },
            'Incorrect Retail Code entered.'
        );
    }
}

