﻿getOrderXMLDocument = function() {
    // May have either one or two addresses - need to say whether the billing & contact addresses are the same.
    
    // get the address details from each of the address boxes
    
    // and the phone number
    
    // the payment details
    
    // send to the server.
    
}

/// <reference path="lib_core.js"/>
/// <reference path="lib_core_controls.js"/>
/// <reference path="lib_fieldeditors.js"/>
/// <reference path="lib.js"/>

var businessOrderControl;

RegisterBox.BusinessOrder = function(container, options) {
    this.container = container;
    this.options = options;
    this.init(0);
}
var p = RegisterBox.BusinessOrder.prototype;
p.inheritFrom(CDiv);
p.init = function(depth) {
    //var d = this.createMyDiv();
    this.superInit(0);
    this.setClass('BusinessOrder');
    // Put the stuff within a WizardFrame?
    
    businessOrderControl = this;
    
    // Call this BusinessOrderWizard?
    // Have it extend WizardFrame?
    // The WizardFrame provides CDivs and handles the previous / next?
    // Contact name
    
    // Business Name!!!
    
    // Billing name needed for the billing address?

    this.cdPhoneUs = new CDiv(this, { 'cssClass': 'cdPhoneUs' });
    this.cdPhoneUs.setInnerHTML('If you would prefer to sign up by phone then call us free on 0800 849 80 10.');
    
    // a central div?
    this.cdCentral = new CDiv(this, {'cssClass': 'cdCentral'});
    //var dca = nDClearAll();
    //divAddressDisplays.appendChild(dca);
    
    //this.el.appendChild(divAddressesDisplays);
    
    this.cdStageAddress = new CDiv(this.cdCentral, {'cssClass': 'cdStageAddressDetails'});
    
    this.cdReqAddress = new CDiv(this.cdStageAddress, {'cssClass': 'cdIsRequiredFieldKey'});
    this.cdReqAddress.setInnerHTML('<span class="validationFailure">*</span>&nbsp;Required field');
    
    this.cdhBillingDetails = new CDiv(this.cdStageAddress, {'cssClass': 'title'});
    this.cdhBillingDetails.setInnerHTML('Business/Site Details');
    
    // the business name
    var oTF = new Object();
    oTF.labelText = 'Company/Business Name:';
    oTF.isRequired = true;
    oTF.questionMarkText = 'As you would like it to appear on your invoices'
    this.tfBusinessName = new TextField(this.cdStageAddress, oTF);
    
    //ContactEntry
    var o = {'labelWidth':this.options.labelWidth, 'type': 'businessDetails'}
    
    this.eContact = new ContactEntry(this.cdStageAddress, o);
    //this.eContact = new ContactEntry(this.cdStageAddress, {'labelWidth':10});
    
    // then we ask how they heard about us
    
    var optsHowHear = new Array();
    optsHowHear.push(new AOption({'text': '-- Select one --', 'value': 0}));
    optsHowHear.push(new AOption({'text': 'Search Engine', 'value': 'Search Engine'}));
    optsHowHear.push(new AOption({'text': 'Word of Mouth', 'value': 'Word of Mouth'}));
    optsHowHear.push(new AOption({'text': 'Telesales Agent', 'value': 'Telesales Agent'}));
    optsHowHear.push(new AOption({'text': 'Already a Customer', 'value': 'Already a Customer'}));
    optsHowHear.push(new AOption({'text': 'Via Fax', 'value': 'Via Fax'}));
    //optsHowHear.push(new AOption({'text': 'Via Letter &amp; Email', 'value': 'Via Letter &amp; Email'}));
    optsHowHear.push(new AOption({'text': 'Via Letter or Email', 'value': 'Via Letter or Email'}));
    optsHowHear.push(new AOption({'text': 'Other', 'value': 'Other'}));
    
    
    // this width should probably be in CSS file.
    var o = new Object();
    o.labelText = 'How did you hear about us?';
    o.isRequired = true;
    o.ddlWidth = 164;
    this.ddlfHowHear = new DropDownListField(this.cdStageAddress, o, optsHowHear);
    this.ddlfHowHear.render();
    this.ddlfHowHear.onchange = function() {this.container.container.container.ddlfHowHear_onchange();}
    
    this.tfAgentCode = new TextField(this.cdStageAddress, {'labelText': 'Agent code: (if you have one)'});
    this.tfAgentCode.hide();
    
    // Have a heading saying 'Billing Details'
    
    this.cdhBillingDetails = new CDiv(this.cdStageAddress, {'cssClass': 'title'});
    this.cdhBillingDetails.setInnerHTML('Billing Details');
    this.cdhBillingDetails.setClass('title');
    
    var o = new Object();
    o.labelText = 'Address same as above?';
    o.isRequired = true;
    o.value = true;
    this.ynrf = new YesNoRadioField(this.cdStageAddress, o);
    //this.ynrf.setValue(true);
    this.ynrf.setClass('ynrfSameAddress');
    this.ynrf.render();
    //this.ynrf.onchange = function() { this.container.container.container.ynrf_onchange(); }
    
    this.ynrf.onclick = function() { this.container.container.container.ynrf_onclick(); }
    // this needs to validate.
    
    //this.chkSameAddresses = new CheckBox(this.cdStageAddress, 'My billing address is the same as my contact address');
    //this.chkSameAddresses.onchange = function() {this.container.container.container.chkSameAddresses_change();};
    
    // The various items in this will use options variables - we want to set the labelWidth on many of them.
    
    this.billingContact = new ContactEntry(this.cdStageAddress, {'labelWidth':this.options.labelWidth});
    //this.billingContact = new ContactEntry(this.cdStageAddress, {'labelWidth':10});
    this.billingContact.hide();
    
    // include the controls to validate in the option?
    //  not for the moment.
    this.addressValidationErrorDisplay = new ValidationErrorsDisplay(this.cdStageAddress);
    
    this.cdStagePhoneNumbers = new CDiv(this.cdCentral, {'cssClass':'cdStagePhoneNumbers'});
    this.cdStagePhoneNumbers.hide();
    
    this.cdReqPhoneNumbers = new CDiv(this.cdStagePhoneNumbers, {'cssClass': 'cdIsRequiredFieldKey'});
    this.cdReqPhoneNumbers.setInnerHTML('<span class="validationFailure">*</span>&nbsp;Required field');
    
    this.cdStagePhoneNumbers.topclear = new CDClear(this.cdStagePhoneNumbers);
    
    // then a phone number entry control.
    this.phoneNumbersEntry = new RegisterBox.NumbersEntry(this.cdStagePhoneNumbers);
    // this.phoneNumbersEntry raises an event when number is added to it.
    this.phoneNumbersEntry.oncomplete = function() { this.container.container.container.phoneNumbersEntry_oncomplete(); }
    
    
    this.cdStagePayment = new CDiv(this.cdCentral, {'cssClass':'cdStagePayment'});
    this.cdStagePayment.hide();
    
    this.cdReqPaymentDetails = new CDiv(this.cdStagePayment, {'cssClass': 'cdIsRequiredFieldKey'});
    this.cdReqPaymentDetails.setInnerHTML('<span class="validationFailure">*</span>&nbsp;Required field');
    
    this.paymentDetails = new PaymentDetails(this.cdStagePayment);
    //this.paymentDetails.oncomplete = function() {this.container.container.paymentDetails_oncomplete()}
    this.paymentDetails.onAccepted = function() {this.container.container.container.paymentDetails_onAccepted();}
    
    // also include authorization in the payment details section.
    
    
    
    this.cdStageConfirm = new CDiv(this.cdCentral, {'cssClass':'cdStageConfirm'});
    
    this.cdReqConfirm = new CDiv(this.cdStageConfirm, {'cssClass': 'cdIsRequiredFieldKey'});
    this.cdReqConfirm.setInnerHTML('<span class="validationFailure">*</span>&nbsp;Required field');
    
    this.cdcReqConfirm = new CDClear(this.cdStageConfirm);
    
    this.cdStageConfirm.divCheckBoxes = new CDiv(this.cdStageConfirm, {'cssClass':'confirmationCheckboxes'})
    
    // need list of items for this
    
    // putting HTML in AOptions?
    // maybe not so possible.
    
    var cbmItems = new Array();
    cbmItems.push(new AOption({'text': 'I authorise the Access Provider to activate the above choices on my behalf ', 'value': 'authoriseMove', 'isRequired': true}));
    cbmItems.push(new AOption({'text': 'I am authorised to act on behalf of the company in this matter ', 'value': 'authorisedByCompany', 'isRequired': true}));
    //cbmItems.push(new AOption({'text': 'I have read and understood the <a href="terms-of-business.aspx">terms and conditions</a> ', 'value': 'readTAndC'}));
    
    // we want to have a link to the terms and conditions in this list.
    // so not just a label, but also an HREF that is not part of the label.
    // probably best to find a way to get it to render the AOption including the link.
    cbmItems.push(new AOption({'text': 'I have read and understood the ', 'value': 'readTAndC', 'isRequired': true, 'appendedLink': {'href': 'terms-of-business.aspx', 'text': 'Terms and Conditions'}}));
    
    this.cdStageConfirm.divCheckBoxes.cbm = new CheckBoxMenu(this.cdStageConfirm.divCheckBoxes, {'items': cbmItems});
    // then add three individual checkboxes
    this.cdStageConfirm.divCheckBoxes.cbm.render();
    
    
    this.cdStageConfirm.hide();
    //this.paymentDetails = new PaymentDetails(this.cdStagePayment);
    //this.paymentDetails.oncomplete = function() {this.container.container.paymentDetails_oncomplete()}
    
    //this.cdStageConfirm.orderSummary = new OrderSummary(this.cdStageConfirm);
    
    // then an OK button that goes past this stage. It will likely be disabled/invisible until the info validates.
    //  or it will validate on click.
    
//    this.btnPrevious = new CButton(this, 'Previous');
//    this.btnPrevious.setClass('btnPrevious');
//    this.btnPrevious.onclick = function() {this.container.btnPrevious_click(); return false};
//    this.btnNext = new CButton(this, 'Next');
//    this.btnNext.setClass('btnNext');
//    this.btnNext.onclick = function() {this.container.btnNext_click(); return false};
    
    this.cdButtons = new CDiv(this);
    this.cdButtons.setClass('cdButtons');

    // &#60; <

    // want to use ImageButton rather than BoldButton

    this.btnPrevious = new ImageButton(this.cdButtons, { 'src': '/images/btn-back.gif' });
    //this.btnPrevious = new BoldButton(this.cdButtons, { 'buttonColor': 'gray', 'text': 'Back' });
    this.btnPrevious.setFloat('left');
    this.btnPrevious.hide();
    this.btnPrevious.onclick = function() {this.container.container.btnPrevious_click(); return false};

    //this.btnNext = new BoldButton(this.cdButtons, { 'buttonColor': 'green', 'text': 'Next &#62;&#62;' });
    this.btnNext = new ImageButton(this.cdButtons, { 'src': '/images/btn-next.gif' });
    this.btnNext.setFloat('left');
    this.btnNext.el.id = 'btnNext';
    //this.btnNext.setClass('btnNext');
    this.btnNext.onclick = function() {this.container.container.btnNext_click(); return false};
    
    // then the numbers entry
    //var divNumbersEntry = nDiv();
    //this.divNumbersEntry = divNumbersEntry;
    
    //this.cdPrivacyPolicy = new CDiv(this, {'cssClass': 'cdPrivacyPolicy'});
    //this.cdPrivacyPolicy.setInnerHTML('Our <a href="privacy.aspx" target="_blank">Privacy Policy</a> explains how we protect your data.');
    
    // order summary
    
    //alert ('yo');
    //this.numbersEntry = new RegisterBox.NumbersEntry(this);
    //this.numbersEntry.hide();
    
    this.order = new Order();
    
    this.addMyEl();
}

p.submitOrder = function() {
    // Use a webservice to receive the order.
    
    //var order = this.order;
    
    // need to get it as XML.
    
    // get the business name
    var businessName = this.tfBusinessName.getValue();
    var contact = this.eContact.getValue();
    var billingContact = this.billingContact.getValue();
    var howHear = this.ddlfHowHear.getValue();
    
    alert ('businessName ' + businessName);
    alert ('contact ' + contact);
    alert ('billingContact ' + billingContact);
    alert ('howHear ' + howHear);
    
}

p.getOrder = function() {
    return this.order;
}

p.ddlfHowHear_onchange = function() {
    //alert ('ddlfHowHear_onchange');
    //if (
    var val = this.ddlfHowHear.getValue();
    //alert ('val ' + val);
    if (val == 'Telesales Agent') {
        this.tfAgentCode.show();
    } else {
        this.tfAgentCode.hide();
    }
}

p.paymentDetails_onAccepted = function() {
    //alert('accepted');
    
    this.moveNext();
    
}

//p.paymentDetails_oncomplete = function() {
//    alert('paymentDetails_oncomplete');
//    
//}

p.phoneNumbersEntry_oncomplete = function() {
    //alert ('phoneNumbersEntry_oncomplete');
    
    // go on to stage 3, the stage of entering the payment details.
    progressIndicator.selectStage(3);
    this.cdStagePhoneNumbers.hide();
    this.cdStagePayment.hide();
    this.cdStagePayment.show();
    
}
p.ynrf_onchange = function() {
    //alert ('ynrf_onchange');
}
p.ynrf_onclick = function() {
    //alert ('ynrf_onclick');
    
    //alert ('this.ynrf.getValue() ' + this.ynrf.getValue());
    var val = this.ynrf.getValue();
    //alert ('val' + val);
    this.billingContact.setVisibility(!val);
}

p.chkSameAddresses_change = function() {
    //alert ('this.chkSameAddresses.value ' + this.chkSameAddresses.value);
    this.setSameAddress(this.chkSameAddresses.value);
}
p.setSameAddress = function(value) {
    this.useSameAddress = value;
    this.billingAddressEntry.setVisibility(!value);
}

p.contactAddressDisplay_onedit = function() {
    alert ('contactAddressDisplay_onedit');
}

p.billingAddressDisplay_onedit = function() {
    alert ('billingAddressDisplay_onedit');
}

var buttonSubmit;

p.btnPrevious_click = function() {
    var currentStageNumber = progressIndicator.stageNumber;
    if (currentStageNumber == 2) {
        //this.btnPrevious.setText('Quit');
        this.btnPrevious.hide();
        
        this.cdPhoneUs.show();
        //this.cdPrivacyPolicy.show();
        
        progressIndicator.selectStage(1);
        // should not need to render - the ProgressIndicator should update its appearance itself automatically.
        this.cdStageAddress.show();
        //this.cdStageNumberOfPhoneNumbers.hide();
        this.cdStagePhoneNumbers.hide();
        progressIndicator.render();
        
    }
//    if (currentStageNumber == 2.1) {
//        progressIndicator.selectStage(2);
//        //this.cdStageNumberOfPhoneNumbers.show();
//        //this.cdStagePhoneNumbers.hide();
//    }
    
    if (currentStageNumber == 3) {
        // it would be better to go back to the item being edited.
        
        // let's find out if the current phone number exists
        
        //alert ('phoneNumberIndex ' + phoneNumberIndex)
        //alert ('phoneNumbers[phoneNumberIndex] ' + phoneNumbers[phoneNumberIndex])
        
        if (!phoneNumbers[phoneNumberIndex]) {
            // that phone number has been removed, probably because it was blank
            // clear the phone number entry.
            
            if (removedPhoneNumber) {
                phoneNumbers[phoneNumberIndex] = removedPhoneNumber;
                numberEntry.editPhoneNumberByIndex(phoneNumberIndex);
                removedPhoneNumber = null;
            }
            
            
            //this.phoneNumbersEntry.numberEntry.clear();
        }
        
        progressIndicator.selectStage(2);
        progressIndicator.render();
        
        this.cdStagePhoneNumbers.show();
        this.cdStagePayment.hide();
        
        if (orderSummary) {
            orderSummary.options.showEditLinks = true;
            this.phoneNumbersEntry.numberEntry.cdRight.el.appendChild(orderSummary.el);
        }
        
        // Not so sure we want it to automatically go to a free one
        // (then have to delete it?).
        //phoneNumberIndex = getFreePhoneNumberIndex();
        
        
        //this.phoneNumbersEntry.numberEntry.clear();
        this.phoneNumbersEntry.updateNumberTitle();
        
        
        // but the item may have been cleared in the order summary.
        
        
        this.phoneNumbersEntry.numberEntry.updateOrderSummary();
        //this.cdStageNumberOfPhoneNumbers.show();
        //this.cdStagePhoneNumbers.hide();
    }
    
    if (currentStageNumber == 4) {
        progressIndicator.selectStage(3);
        progressIndicator.render();
        
        this.cdStagePayment.show();
        this.cdStageConfirm.hide();
        
        buttonSubmit = document.getElementById(btnSubmit);
        //var btnNext = document.getElementById('btnNext');
        buttonSubmit.parentNode.replaceChild(btnNext, buttonSubmit);
        buttonSubmit.style.display = 'none';
        //this.cdStageNumberOfPhoneNumbers.show();
        //this.cdStagePhoneNumbers.hide();
    }
    
    return false;
}

p.validateStage = function(stageNumber) {
    //var caeValid = this.eContact.validate();
    //var baeValid = this.billingContact.validate();
    
    // This could provide a ValidationResult.
    //  It would contain other validation results.
    // 
    
    var isValid = true;
    //var res = true;
    var res = new ValidationResult();
    var res1;
    // then add the various other validation results to it.
    // the result will only be valid if all of the other ones that have been added are also valid.
    
    //alert('stageNumber ' + stageNumber);
    
    if (stageNumber == 1) {
        
        // need to add the validation results to the result.
        
        res1 = this.tfBusinessName.validate();
        //alert ('res.options.isValid ' + res.options.isValid);
        //alert ('res ' + res);
        isValid = isValid && res1.options.isValid; 
        res.add(res1);
        
        res1 = this.eContact.validate();
        isValid = isValid && res1.options.isValid;
        res.add(res1);
        //alert ('res.options.isValid ' + res.options.isValid);
        //alert ('res ' + res);
        //res = this.ynrf.hasValue() && res;
        //res1 = this.ynrf.validate() && res1;
        //res.add(res1);
        //alert ('res ' + res);
        
        res1 = this.ddlfHowHear.validate();
        //alert ('res1.options.isValid ' + res1.options.isValid);
        isValid = isValid && res1.options.isValid;
        res.add(res1);
        
        //alert ('this.ynrf.hasValue() ' + this.ynrf.hasValue());
        //alert ('this.ynrf.getValue() ' + this.ynrf.getValue());
        
        if (!this.ynrf.getValue()) {
        
            //alert ('this.ynrf.getValue() ' + this.ynrf.getValue());
            res1 = this.billingContact.validate();
            res.add(res1);
            isValid = isValid && res1.options.isValid;
            //alert ('res ' + res);
        }
        
    }
    if (stageNumber == 2) {
        // they need to have a phone number entered.
        // though, when moving next, if they have a valid phone number in there, it will add it.
        
        // validate the phone number,
        
        // get the phone number string
        var pnVal = this.phoneNumbersEntry.numberEntry.ukLandlineNumberField.getValue();
        //alert('pnVal ' + pnVal);
        //alert('pnVal.length ' + pnVal.length);
        
        if (pnVal.length > 0) {
            // see if the currently entered phone number is valid, if it is, add it.
            // otherwise, alert the user to the fact it is not valid.
            
            // don't add if it is the same as a previous number?
            
            // validate the number that is in there
            
            var pnIsValid = this.phoneNumbersEntry.numberEntry.isPhoneNumberValid();
            //alert('pnIsValid ' + pnIsValid);
            //alert('pnIsValid.isValid ' + pnIsValid.isValid);
            
            // if it is valid then add it, then move on.
            
            // otherwise move on if there is at least one number already entered.
            
            if (pnIsValid) {
                //alert ('is valid, so will add number');
                
                // maybe don't do the validation here.
                // 
                
                //var phoneNumber = this.phoneNumbersEntry.numberEntry.getPhoneNumber();
                // need to validate the phone number
                //this.numberEntry.hide();
                //this.btnAddPhoneNumber.hide();
                //this.cdEnterAnotherNumberQuestion.show();
                
                //addPhoneNumber(phoneNumber);
                this.phoneNumbersEntry.numberEntry.clear();
                
            } else {
                // continue if there is at least one number already entered.
                //alert ('continue if there is at least one number already entered.');
                // or tell the user that the number is not valid.
                if (phoneNumberIndex > 1) {
                    
                } else {
                    alert('Please enter a phone number');
                    isValid = false;
                }
            }
        } else {
            if (phoneNumberIndex > 1) {
                // a number has been entered, so move to the next.
                
            } else {
                isValid = false;
            }
            
        }
        
        // there may be a number that has been entered.
        // if anything is in the phone number box, it needs to be valid.
        
        
        // if there is not, there needs to be at least one number in the system already.
        
        
    }
    if (stageNumber == 3) {
        // do the validation of the payment details.
        // this will need to respond after a callback to it being accepted.
        
        // get the payement details thing to do the validation.
        
        
        this.paymentDetails.validate();
    }
    
    if (stageNumber == 4) {
        // the three options must all be selected
        isValid = this.cdStageConfirm.divCheckBoxes.cbm.allAreChecked()
    }
    
    
    res.options.isValid = isValid;
    return res;
}

var btnNext;

// need to 

p.moveNext = function() {
    var currentStageNumber = progressIndicator.stageNumber;
    if (currentStageNumber == 3) {
        progressIndicator.selectStage(4);
        progressIndicator.render();
        this.cdStagePayment.hide();
        this.cdStageConfirm.show();
        
        // appends the order summary - could swap it with a placeholder.
        this.cdStageConfirm.el.appendChild(orderSummary.el);
        
        
        // the confirmation stage also needs the div for the checkboxts to be last.
        this.cdStageConfirm.el.appendChild(this.cdStageConfirm.divCheckBoxes.el);
        
        // btnSubmit
        // need to move the submit button to the correct place, show it.

        // but button submit may not be in the document.
        // would be better to cache it elsewhere.
        
        
        //var bs = document.getElementById(btnSubmit);

        if (!buttonSubmit) buttonSubmit = document.getElementById(btnSubmit);
        
        btnNext = document.getElementById('btnNext');
        btnNext.parentNode.replaceChild(buttonSubmit, btnNext);
        buttonSubmit.style.display = 'inline';
        
        //btnNext
        
        
    }
}

p.btnNext_click = function() {
    //alert ('btnNext_click');
    // stage transitions.
    //alert ('btnAddressOK');
    // get the current stage
    
    var currentStageNumber = progressIndicator.stageNumber;
    //alert('currentStageNumber ' + currentStageNumber);
    
    // proceed to the next stage
    
    if (currentStageNumber == 1) { /* Address Details (1) -> Phone Numbers (2) */
        //var caeValid = this.contactAddressEntry.validate();
        //var baeValid = this.billingAddressEntry.validate();
        
        var stageValidation = this.validateStage(1);
        //alert ('isValid ' + isValid);
        
        // do the first stage validation.
        // depending on different validation failures, show different validation messages.
        // could highlight fields.
        
        // anyway, needs to say that those fields need values put in them.
        // get a list of fields that need to validate.
        
        // best to mark fields that have not validated with an asterix.
        
        // these need to validate
        
        //alert ('stageValidation.isValid() ' + stageValidation.isValid());
        
        if (stageValidation.isValid()) {
            //this.contactAddressDisplay.setAddress(this.contactAddressEntry.address);
            //this.billingAddressDisplay.setAddress(this.billingAddressEntry.address);
            this.cdStageAddress.hide();
            this.cdStagePhoneNumbers.show();
            //this.cdStageNumberOfPhoneNumbers.show();
            
            progressIndicator.selectStage(2.0);
            progressIndicator.render();
            
            this.cdPhoneUs.hide();
            //this.cdPrivacyPolicy.hide();
            
            //this.btnPrevious.setText('&#60;&#60; Previous');
            //this.btnPrevious.setText('Back');
            this.btnPrevious.show();
            
            this.addressValidationErrorDisplay.setInnerHTML('');
            // 
        } else {
            // show the validation results - it has a list of fields which failed to validate.
            // alert ('stageValidation ' + stageValidation.dfsf.fdsfa.dsa);
            this.addressValidationErrorDisplay.setValidationResults(stageValidation);
            this.addressValidationErrorDisplay.show();
        }
        
        // should not need to render - the ProgressIndicator should update its appearance itself automatically.
        
    }
//    if (currentStageNumber == 2.0) {
//        //this.cdStageNumberOfPhoneNumbers.hide();
//        progressIndicator.selectStage(2.1);
//        //this.cdStagePhoneNumbers.show();
//    }
    if (currentStageNumber == 2) {
        //this.cdStageNumberOfPhoneNumbers.hide();
        
        // the validation somehow clears the inforamtion!
        //var stageValidation = this.validateStage(2);
        
        
        //if (stageValidation.isValid()) {
        if (true) {

            progressIndicator.selectStage(3);
            progressIndicator.render();
            
            this.cdStagePhoneNumbers.hide();
            this.cdStagePayment.show();
            
            // in the payments section we need to put the payment summary.
            orderSummary.cdPaymentPrice.show();
            orderSummary.options.showEditLinks = false;
            this.paymentDetails.divRight.el.appendChild(orderSummary.el);
            
            removeEmptyPhoneNumbers();
            //alert(phoneNumbers.fdsadsaf.fdsaf);
            //updateOrderSummary(phoneNumbers[phoneNumberIndex]);
            updateOrderSummary();
            // May need to remove it at a later point.
            
        } else {
            //alert ('stage 2 is not valid');
        }
        //this.cdStagePhoneNumbers.show();
    }
    
    if (currentStageNumber == 3) {
        //alert ('currentStageNumber == 3');
        //this.cdStageNumberOfPhoneNumbers.hide();
        this.paymentDetails.validate();
        
        //this.cdStageConfirm.orderSummary.setOrder(this.order);
        //this.cdStagePhoneNumbers.show();
    }
    
    if (currentStageNumber == 4) {
        // need to do the final stage of validation
        var stageValidation = this.validateStage(4);
        
        if (stageValidation.isValid()) {
            
            var xd = this.getOrderXml();
            
            var ser = new zXMLSerializer();
            // remove the namespace?
            
            var str = ser.serializeToString(xd);
            
            //alert (str);
            
            // send the details to the server.
            
            var methodName = 'SubmitOrder';
            //var postcode = this.tfPostcode.getValue();
            var sr = new SoapRequest(wsUrl, methodName);
            // name, value
            sr.addNewParam('strXmlOrder', str);
            
            sr.send(cbSubmitOrder);
            
        } else {
            alert ('You must agree to all of the terms and conditions before placing the order.');
        }
        //this.cdStageNumberOfPhoneNumbers.hide();
        //alert ('currentStageNumber == 4');
        // at this stage submit the order to the server.
        // contact / address info (stage 1)
        // the order itself.
        // put this stuff into an XML document.
        //postcodeEntry = this;
        
    }
    // What about loading page 2 on a control that has invisible tabs?
    
    // then proceed to select the phone numbers + tariffs to be used.
    //  these will be got from the DB.
    //alert ('about to reload ff page');
    return false;
}

escapeXmlAttribute = function(str) {
    var res = str.replace(/&/, '&amp;');
    //alert ('res ' + res);
    return res;
}


p.getOrderXml = function() {
    var xd = zXmlDom.createDocument();
    var eBusinessOrder = xd.createElement('BusinessOrder');
    eBusinessOrder.setAttribute('BusinessName', escapeXmlAttribute(this.tfBusinessName.getValue()));
    
    eBusinessOrder.setAttribute('AgentCode', this.tfAgentCode.getValue());
    eBusinessOrder.setAttribute('HowHear', this.ddlfHowHear.getValue());
    
    xd.appendChild(eBusinessOrder);
    
    var eContactDetails = xd.createElement('ContactDetails');
    eBusinessOrder.appendChild(eContactDetails);
    //this.eContact
    var title = this.eContact.nameAndTitle.ddlTitle.getValue();
    var name = this.eContact.nameAndTitle.tbName.getValue();
    
    eContactDetails.setAttribute('title', title);
    eContactDetails.setAttribute('name', name);
    
    var address1 = this.eContact.address.tfAddress1.getValue();
    var address2 = this.eContact.address.tfAddress2.getValue();
    var address3 = this.eContact.address.tfAddress3.getValue();
    
    //var address4 = this.eContact.address.tfAddress4.getValue();
    
    var addressTown = this.eContact.address.tfPostTown.getValue();
    var county = this.eContact.address.tfCounty.getValue();
    var postcode = this.eContact.address.tfPostcode.getValue();
    
    eContactDetails.setAttribute('address1', address1);
    eContactDetails.setAttribute('address2', address2);
    eContactDetails.setAttribute('address3', address3);
    //eContactDetails.setAttribute('address4', address4);
    eContactDetails.setAttribute('addressTown', addressTown);
    eContactDetails.setAttribute('county', county);
    eContactDetails.setAttribute('postcode', postcode);
    
    var email = this.eContact.tfEmail.getValue();
    var mobile = this.eContact.tfMobile.getValue();
    //var county = this.eContact.tfCounty.getValue();
    
    eContactDetails.setAttribute('email', email);
    eContactDetails.setAttribute('mobile', mobile);
    eContactDetails.setAttribute('county', county);
    
    // need to put the sort code + account number + bank name + billing name in there.
    //this.paymentDetails.tfBankName.getValue();
    //this.paymentDetails.tfAccountHolder.getValue();
    //this.paymentDetails.tfAccountNumber.getValue();
    //this.paymentDetails.tfSortCode.getValue();
    
    eBusinessOrder.setAttribute('billingAuthorizationName', this.paymentDetails.tfPaymentAuthorizationName.getValue());
    eBusinessOrder.setAttribute('billingAuthorizationPosition', this.paymentDetails.ddlPaymentAuthorizationPosition.getValue());
    
    // also get the billing method, frequency
    eBusinessOrder.setAttribute('billingMethod', this.paymentDetails.paymentMethod.name);
    eBusinessOrder.setAttribute('billingFrequency', this.paymentDetails.paymentFrequency);
    
    // only include this if the billing method is 'Direct Debit'.
    if (this.paymentDetails.paymentMethod.name == 'Direct Debit') {
        eBusinessOrder.setAttribute('bankName', this.paymentDetails.tfBankName.getValue());
        eBusinessOrder.setAttribute('accountHolder', this.paymentDetails.tfAccountHolder.getValue());
        eBusinessOrder.setAttribute('accountNumber', this.paymentDetails.tfAccountNumber.getValue());
        eBusinessOrder.setAttribute('sortCode', this.paymentDetails.tfSortCode.getValue());
    }
    
    
    var ynrfValue = this.ynrf.getValue();
    //alert ('ynrfValue ' + ynrfValue);
    
    if (!ynrfValue) {
        var eBillingDetails = xd.createElement('BillingDetails');
        eBusinessOrder.appendChild(eBillingDetails);
        
        var title = this.billingContact.nameAndTitle.ddlTitle.getValue();
        var name = this.billingContact.nameAndTitle.tbName.getValue();
        
        eBillingDetails.setAttribute('title', title);
        eBillingDetails.setAttribute('name', name);
        
        eBillingDetails.setAttribute('authorisedByName', this.paymentDetails.tfPaymentAuthorizationName.getValue());
        eBillingDetails.setAttribute('authorisedByPosition', this.paymentDetails.ddlPaymentAuthorizationPosition.getValue());
        
        address1 = this.billingContact.address.tfAddress1.getValue();
        address2 = this.billingContact.address.tfAddress2.getValue();
        address3 = this.billingContact.address.tfAddress3.getValue();
        //address4 = this.billingContact.address.tfAddress4.getValue();
        addressTown = this.billingContact.address.tfPostTown.getValue();
        county = this.billingContact.address.tfCounty.getValue();
        postcode = this.billingContact.address.tfPostcode.getValue();
        
        eBillingDetails.setAttribute('address1', address1);
        eBillingDetails.setAttribute('address2', address2);
        eBillingDetails.setAttribute('address3', address3);
        //eBillingDetails.setAttribute('address4', address4);
        eBillingDetails.setAttribute('addressTown', addressTown);
        eBillingDetails.setAttribute('county', county);
        eBillingDetails.setAttribute('postcode', postcode);
        
        var email = this.billingContact.tfEmail.getValue();
        var mobile = this.billingContact.tfMobile.getValue();
        //var county = this.billingContact.tfCounty.getValue();
        
        eBillingDetails.setAttribute('email', email);
        eBillingDetails.setAttribute('mobile', mobile);
        eBillingDetails.setAttribute('county', county);
        
    }
    // then add the information about phone numbers
    
    var ePhoneNumberOrders = xd.createElement('PhoneNumberOrders');
    eBusinessOrder.appendChild(ePhoneNumberOrders);
    
    
    // Why is this not working?
    // Maybe this needs to look through the phone numbers in a different way.
    // Also, perhaps the index is lower than phoneNumberIndex
    //alert ('phoneNumbers.length ' + phoneNumbers.length);
    
    //for (var c = 1; c < phoneNumberIndex; c++) {
    for (var c = 1; c < phoneNumbers.length; c++) {
        var ePhoneNumberOrder = xd.createElement('PhoneNumberOrder');
        ePhoneNumberOrders.appendChild(ePhoneNumberOrder);
        ePhoneNumberOrder.setAttribute('index', c);
        
        var phoneNumberOrder = phoneNumbers[c];
        
        // number, numLines, tariff, addOns, index
        
        //var phoneNumber = phoneNumberOrder.number;
        //var numLines = phoneNumberOrder.numLines;
        var phoneNumber = phoneNumberOrder.options.landlineNumber;
        var numLines = phoneNumberOrder.options.numLines;
        
        //alert('phoneNumber ' + phoneNumber);
        //alert('numLines ' + numLines);
        
        var tariffName = phoneNumberOrder.options.tariff.name;
        var tariffId = phoneNumberOrder.options.tariff.id;
        var paperBillingChoice = phoneNumberOrder.options.paperBillingChoice;
        //var paperB
        
        //alert('paperBillingChoice ' + paperBillingChoice);
        //alert('paperBillingChoice.name ' + paperBillingChoice.name);
        
        ePhoneNumberOrder.setAttribute('phoneNumber', phoneNumber);
        ePhoneNumberOrder.setAttribute('numLines', numLines);
        ePhoneNumberOrder.setAttribute('tariffName', tariffName);
        ePhoneNumberOrder.setAttribute('tariffId', tariffId);
        ePhoneNumberOrder.setAttribute('paperBillingChoice', paperBillingChoice.name);
        // need to include calling features.
        //phoneNumberOrder.fsadfasdgf.gsdgdsffg.dsaf;
        
//                alert ('phoneNumberOrder.addOns.length ' + phoneNumberOrder.addOns.length);
//                for (var c = 0; c < phoneNumberOrder.addOns.length; c++) {
//                    
//                }
        ePhoneNumberOrder.setAttribute('featuresString', phoneNumberOrder.getFeaturesString());
        
        // phone number
        // number of lines
        // tariff name
        // tariff id
        
        // list of add-ons, both name and id
    }
    return xd;
}

addToHid = function() {
    // this should also validate the checkbox controls in the business order, seeing that they have agreed to the terms and conditions.
    
    // get the results of the last stage validation.
    var stageValidation = businessOrderControl.validateStage(4);
    if (stageValidation.isValid()) {
        
        var hf = document.getElementById(hidid);
        
        // then get the order.
        var ox = businessOrderControl.getOrderXml();
        var ser = new zXMLSerializer();
        // remove the namespace?
        
        var str = ser.serializeToString(ox);
        hf.value = str;
        return true;
    } else {
        alert ('You must agree to all of the terms and conditions before placing the order.');
        return false;
    }
    
}

cbSubmitOrder = function() {
    location.href = 'join-complete.aspx';
}