﻿// This should be turned into a nice control.


var paymentMethods = new Object();
paymentMethods[0] = {'name': 'Direct Debit', 'price': 0};
paymentMethods[1] = {'name': 'Postal Order', 'price': 2.95};
paymentMethods[2] = {'name': 'Cheque', 'price': 2.95};
paymentMethods[3] = {'name': 'Payment via Telephone', 'price': 2.95};


var paymentFrequencies = new Object();
paymentFrequencies[0] = 'Monthly';
paymentFrequencies[1] = 'Quarterly';

var paymentFrequency = 'Monthly';
var paymentMethod = paymentMethods[0];

PaymentDetails = function(container, options) {
    this.container = container;
    this.options = options;
    this.init(0);
}
var p = PaymentDetails.prototype;
p.inheritFrom(CDiv);
p.init = function(depth) {
    this.superInit(depth);
    this.setClass('PaymentDetails');
    
    this.divLeft = new CDiv(this);
    this.divLeft.setClass('left');
    
    // then a gap...
    // need menu where they choose their payment method.
    this.cdPaymentMethod = new CDiv(this.divLeft);
    this.cdPaymentMethod.setClass('cdPaymentMethod');
    
    this.setClass('BillingChoice');
    this.csBillingChoice = new CSpan(this.cdPaymentMethod);
    this.csBillingChoice.setClass('title');
    
    this.csBillingChoice.setInnerHTML('Select your payment method');
    var rmbMethodItems = new Array();
    this.rmbMethodItems = rmbMethodItems;
    
    rmbMethodItems.push(new AOption({'text': 'Direct Debit:', 'value': 0, 'price': 0, 'questionMarkText': 'Save money by paying by Direct Debit'}));
    rmbMethodItems.push(new AOption({'text': 'Postal Order:', 'value': 1, 'price': 2.95, 'questionMarkText': 'Obtainable and payable at a Post Office'}));
    rmbMethodItems.push(new AOption({'text': 'Cheque:', 'value': 2, 'price': 2.95, 'questionMarkText': 'Convenience of writing a cheque'}));
    rmbMethodItems.push(new AOption({'text': 'Payment via Telephone:', 'value': 3, 'price': 2.95, 'questionMarkText': 'Convenience of the Telephone'}));
    
    //rmbMethodItems[0].options.selected = true;
    // also want onchang / onselect code to hide/show the direct debit details section.
    var o = new Object();
    o.buttonSide = 'right';
    
    this.paymentMethod = paymentMethods[0];
    
    this.rbmPaymentMethods = new RadioButtonMenu(this.cdPaymentMethod, o, rmbMethodItems);
    this.rbmPaymentMethods.setClass('rbmPaymentMethod');
    //this.rbmTariffs.setSelectedByValue(0);
    this.rbmPaymentMethods.render();
    this.rbmPaymentMethods.onclick = function(text, value) {
        // maybe best not refer to a function in the prototype... or maybe that is best.
        // Advantage of a closure here, not sure if it has the memory advantage from the prototype if it is defined here.
        // This gets called, and a new copy of the function gets made for each noew object (I think).
        // Putting the function in the prototype may be more memory efficient.
        if (text) this.container.container.container.rbmPaymentMethods_onclick(text, value);
    };
    
    this.cdDDDetails = new CDiv(this.divLeft);
    this.tfBankName = new TextField(this.cdDDDetails, {'labelText': 'Bank/Building Society Name:', 'labelWidth': 240, 'isRequired':true});
    this.tfAccountHolder = new TextField(this.cdDDDetails, {'labelText': 'Account Holder Name:', 'labelWidth': 240, 'isRequired':true});
    this.tfAccountNumber = new TextField(this.cdDDDetails, {'labelText': 'Account Number:', 'labelWidth': 240, 'isRequired':true, 'maxLength': 8});
    this.tfSortCode = new SortCodeField(this.cdDDDetails, {'labelWidth': 240, 'isRequired':true});
    
    
    // this is dd authorization.
    this.tfPaymentAuthorizationName = new TextField(this.divLeft, {'labelText': 'Authorised by (name):', 'labelWidth': 240, 'isRequired':true});
    this.ddlPaymentAuthorizationPosition = new DropDownListField(this.divLeft, {'labelText': 'Authorised by', 'defaultValue': '0'}, [
            {'options': {'text': '--Position--', 'value': '0'}},
            {'options': {'text': 'Owner/Proprietor', 'value': 'Owner/Proprietor'}},
            {'options': {'text': 'Partner', 'value': 'Partner'}},
            {'options': {'text': 'Managing Director', 'value': 'Managing Director'}},
            {'options': {'text': 'Director', 'value': 'Director'}},
            {'options': {'text': 'Manager/Manageress', 'value': 'Manager/Manageress'}},
            {'options': {'text': 'Office Manager', 'value': 'Office Manager'}},
            {'options': {'text': 'Personal Assitant', 'value': 'Personal Assitant'}},
            {'options': {'text': 'Licensee', 'value': 'Licensee'}}
        ]
    );
    
    //this.tfPaymentAuthorizationPosition = new TextField(this.divLeft, {'labelText': 'Authorised by (position):', 'labelWidth': 240, 'isRequired':true});
    //this.tfPaymentAuthorizationPosition.setClass('tfPaymentAuthorizationPosition');
    
    
    
    // don't have the payment frequency. (for the moment)
    
//    this.cdPaymentFrequency = new CDiv(this.divLeft);
//    this.cdPaymentFrequency.setClass('cdPaymentFrequency');
//    
//    this.setClass('BillingChoice');
//    this.csBillingFrequencyChoice = new CSpan(this.cdPaymentFrequency);
//    this.csBillingFrequencyChoice.setClass('title');
//    
//    this.csBillingFrequencyChoice.setInnerHTML('Select your payment frequency');
//    var rmbFrequencyItems = new Array();
//    this.rmbFrequencyItems = rmbFrequencyItems;
//    
//    rmbFrequencyItems.push(new AOption({'text': 'Monthly', 'value': 0}));
//    rmbFrequencyItems.push(new AOption({'text': 'Quarterly:', 'value': 1}));
//    
//    rmbFrequencyItems[0].options.selected = true;
//    var o = new Object();
//    o.buttonSide = 'right';
//    
    // maybe good to keep it in as monthly payments, just don't offer any other options.
    this.paymentFrequency = paymentFrequencies[0]; // Monthly
    
//    this.rbmPaymentFrequencies = new RadioButtonMenu(this.cdPaymentFrequency, o, rmbFrequencyItems);
//    this.rbmPaymentFrequencies.setClass('rbmPaymentMethod');
//    //this.rbmTariffs.setSelectedByValue(0);
//    this.rbmPaymentFrequencies.render();
//    this.rbmPaymentFrequencies.onclick = function(text, value) {
//        if (text) this.container.container.container.rbmPaymentFrequencies_onclick(text, value);
//    }
    
    // the RadioButtonMenu needs to include the price - the radio button is in the middle like with CheckBoxMenu.
     
    
    
    
    
    
//    this.tfBankName = new TextField(this, {'labelText': 'Bank/Building Society Name:', 'isRequired':true});
//    this.tfAccountHolder = new TextField(this, {'labelText': 'Account Holder Name:', 'isRequired':true});
//    this.tfAccountNumber = new TextField(this, {'labelText': 'Account Number:', 'isRequired':true});
//    this.tfSortCode = new SortCodeField(this, {});
    //<div class="clearall"></div>
    
    
    this.divRight = new CDiv(this);
    this.divRight.setClass('right');
    
    this.cdc = new CDClear(this);
    
    this.cddddivs = new CDiv(this);
    
    this.cdDDInfo = new CDiv(this.cddddivs, {'cssClass': 'cdDDInfo'});
    this.cdDDInfo.setInnerHTML('<div class="ddImg"><img src="../images/dd.jpg" alt="Direct Debit" /></div><div class="ServiceUserNumberHeader">Service User Number</div><div class="ServiceUserNumber">4</div><div class="ServiceUserNumber">2</div><div class="ServiceUserNumber">8</div><div class="ServiceUserNumber">7</div><div class="ServiceUserNumber">5</div><div class="ServiceUserNumber">7</div><div class="clearall"></div>');
    
    this.cdInstruction = new CDiv(this.cddddivs, {'cssClass': 'cdInstruction'});
    this.cdInstruction.setInnerHTML('<span class="cdInstructionHeader">Instruction to your Bank or Building Society</span><br /><span>Please pay Eazipay Ltd re Continental Telecom Ltd Direct Debits from the account detailed in this instruction subject to the safeguards assured by the Direct Debit Guarantee. I understand that this instruction may remain with Eazipay Ltd re Continental Telecom Ltd and if so, debits will be passed electronically to my Bank/Building Society.</span>');
    
    this.cdc1 = new CDClear(this.cddddivs);
    
    this.cdGuarantee = new CDiv(this.cddddivs, {'cssClass': 'cdGuarantee'});
    this.cdGuarantee.setInnerHTML('<div><span class="cdGuaranteeHeader">Direct Debit Guarantee</span><img style="margin-left: 360px;" src="../images/dd.jpg" alt="Direct Debit" /></div><ul><li>This Guarantee is offered by all Banks and Building Societies that take part in the Direct Debit Scheme. The efficiency and security of the scheme is monitored andprotected by your own Bank or Building Society.</li><li>If the amounts to be paid or the payment dates change Eazipay Ltd re Continental Telecom Ltd will notify you 5 working days in advance of your account being debited or as otherwise agreed.</li><li>If an error is made by Eazipay Ltd re Continental Telecom Ltd or your Bank or Building Society, you are guaranteed a full and immediate refund from your branch of the amount paid.</li><li>You can cancel a Direct Debit at any time by writing to your Bank or Building Society. Please also send a copy of your letter to us.</li></ul>');
    
    this.cdc = new CDClear(this);
    
    this.cdValidationErrors = new CDiv(this, {'cssClass': 'ValidationErrorsDisplayNoLeftMargin'});
    
    this.cdDDDetails.hide();
    this.cddddivs.hide();
    
    this.addMyEl();
}

p.rbmPaymentMethods_onclick = function(text, value) {
    //alert ('rbmPaymentMethods_onclick');
    
    // this needs to 
    
    this.paymentMethod = paymentMethods[value];
    paymentMethod = paymentMethods[value];
    
    //alert ('value ' + value);
    if (value != 0) {
        this.cdDDDetails.hide();
        this.cddddivs.hide();
    } else {
        this.cdDDDetails.show();
        this.cddddivs.show();
    }
    
    updateOrderSummary();
    
    if (this.onchange) this.onchange();
    
}
p.rbmPaymentFrequencies_onclick = function(text, value) {
    //alert ('rbmPaymentMethods_onclick');
    
    this.paymentFrequency = paymentFrequencies[value];
    paymentFrequency = paymentFrequencies[value];
    // maybe want to set the payment frequency of the order
    
    // need to update the order summary.
    
    updateOrderSummary();
    
    if (this.onchange) this.onchange();
    
}

// payment details validation is important.
p.validate = function(callback) {
    // only needs to validate direct debit details if direct debit is the payment method.
    
    // is a payment method selected?
    
    var isValid = true;
    var sValErrors = '';
    
    
    if (this.rbmPaymentMethods.itemIsSelected()) {
        //alert ('selected');
        if (this.paymentMethod == paymentMethods[0]) {
            
            var accountNumber = this.tfAccountNumber.getValue();
            var rxAccountNumber = /^\d{8}$/;
            
            var mAccounNumber = accountNumber.match(rxAccountNumber);
            //alert('mAccounNumber ' + mAccounNumber);
            
            var sortCode = this.tfSortCode.getValue(false);
            
            // then validate the sort code.
            var rxSortCode = /^\d{6}$/;
            var mSortCode = sortCode.match(rxSortCode);
            
            isValid = isValid && mAccounNumber;
            isValid = isValid && mSortCode;
            
            if (!this.tfPaymentAuthorizationName.isValid()) {
                sValErrors = sValErrors + '<div class="validationFailure">Please enter Authorised by (name)</div>';
            }
            
            // it won't be valid if the 'default' / '0' value is selected.
            if (!this.ddlPaymentAuthorizationPosition.isValid()) {
                sValErrors = sValErrors + '<div class="validationFailure">Please select Authorised by (position)</div>';
            }
            if (!this.tfBankName.isValid()) {
                sValErrors = sValErrors + '<div class="validationFailure">Please enter Bank/Building Society Name</div>';
            }
            if (!this.tfAccountHolder.isValid()) {
                sValErrors = sValErrors + '<div class="validationFailure">Account Holder Name</div>';
            }
            //this.cdValidationErrors.innerHTML = sValErrors;
            
            if (!mAccounNumber) sValErrors = sValErrors + '<div class="validationFailure">Please ensure you have entered a valid account number</div>';
            if (!mSortCode) sValErrors = sValErrors + '<div class="validationFailure">Please ensure you have entered a valid sort code</div>';
            
            
        } else {
            
            
            
        }
        
        var validAuthName = (this.tfPaymentAuthorizationName.getValue().length > 0);
        if (!validAuthName) {
            sValErrors = sValErrors + '<div class="validationFailure">Please enter the name of the person authorizing the purchase.</div>';
        }
        isValid = isValid && validAuthName;
        
        // only need to check direct debit info if dd is selected.
        var validPos = this.ddlPaymentAuthorizationPosition.isValid();
        if (!validPos) {
            sValErrors = sValErrors + '<div class="validationFailure">Please select Authorised by (position).</div>';
        }
        isValid = isValid && validPos;
        //alert('validPos ' + validPos);
        
        
        
        
        // still need to check the authorization
        
        
        
    } else {
        isValid = false;
        
        sValErrors = sValErrors + '<div class="validationFailure">Please select a billing method.</div>';
    }
    
    
    // first validate that the account number has 8 letters, 2 letters in each sort code box?
    
    
    // a validation errors area.
    
    
    // need to validate the authorization name + position, bank name, account holder name
    this.cdValidationErrors.setInnerHTML(sValErrors);
    
    // but set up the validation for bank details.
    
    // call the ws.
    
    this.callback = callback;
    
    //postcodeEntry = this;
    
    // only call the WS if it passes preliminary regular expression validators.
    //alert('isValid ' + isValid);
    if (isValid) {
        paymentDetails = this;
        
        // it only needs to validate the bank details if direct debit has been chosen.
        
        if (this.paymentMethod == paymentMethods[0]) {
            validateBankDetails(sortCode, accountNumber, this.cbBankVal);
        } else {
            this.cbBankVal(true);
        }
        
        
        
        
        
    }
    
}


// this would probably work much better with closures.
p.cbBankVal = function(res) {
    if (res === true) {
        if (paymentDetails.onAccepted) {
            //alert ('accepted method found');
            paymentDetails.onAccepted();
        } else {
            //alert ('accepted method not found');
        }
    } else {
        
        
        var xs = new zXMLSerializer();
        var strRes = xs.serializeToString(res);
        
        //alert ('strRes ' + strRes);
        
        // let's get the BankValResult.
        
        var bvr = res.getElementsByTagName('BankValResult')[0];
        // then look at the text inside?
        //alert ('bvr.childNodes.length ' + bvr.childNodes.length);
        //alert ('bvr.childNodes[0].nodeValue ' + bvr.childNodes[0].nodeValue);
        
        
        if (bvr.childNodes[0].nodeValue == 'VALID') {
            paymentDetails.cdValidationErrors.setInnerHTML('');
            //alert ('valid');
            if (paymentDetails.onAccepted) {
                //alert ('accepted method found');
                paymentDetails.onAccepted();
            } else {
                //alert ('accepted method not found');
            }
        } else {
            paymentDetails.cdValidationErrors.setInnerHTML('<div class="validationFailure">There has been an error validating your payment information. Please ensure you have entered it correctly.</div>');
        }
        
    }
    
    
    // probably use the ncz serialization / desearialization.
    
    
    
    
    
}

validateBankDetails = function(sortCode, accountNumber, callback) {
    var methodName = 'BankVal';
    //var id = this.selectPostcode.getValue();
    var sr = new SoapRequest(wsUrl, methodName);
    // name, value
    //alert ('id ' + id);
    sr.addNewParam('sortCode', sortCode);
    sr.addNewParam('accountNumber', accountNumber);
    sr.send(callback);
}
//cb_validateBankDetails = function(res) {
//    
//    
//}