/********************************************************************************************

 Javascript that is only relevant for the order process
 
********************************************************************************************/

var OP = new Object();

// useful to have. they're used at least twice
OP.addressFields = $w('name_first in_ca_cu_CustTussenvoegsel name_last street in_ca_cu_CustHouseNo in_ca_cu_CustHouseNoExtra zipcode city country');

// turn input fields red
OP.markInputObjectAsWrong = function(inputElement) {
    if((inputElement.type == 'text') || (inputElement.type == 'password')){
        console.log(inputElement,"red");
        $(inputElement).setStyle({backgroundColor:'#F00'});
    };
};
OP.markInputObjectAsRight = function(inputElement) {
    if((inputElement.type == 'text') || (inputElement.type == 'password')){
        $(inputElement).setStyle({backgroundColor:'#FFF'});
    };
};


// For Dept the input field will turn red via a class
OP.DPT_markInputObjectAsWrong = function(inputElement) {
    if((inputElement.type == 'text') || (inputElement.type == 'password')){
        inputElement.up("div").addClassName('turnred');
    };
};
OP.DPT_markInputObjectAsRight = function(inputElement) {
    if((inputElement.type == 'text') || (inputElement.type == 'password')){
        inputElement.up("div").removeClassName('turnred');
    };
};


ECube.registerOnLoadFunction(function(e){
    $$('input.turnred').each(function(inputObj){
        inputObj.onErrorFunction = function(formObject){
            $A(formObject.elements).each(OP.markInputObjectAsRight);
            OP.markInputObjectAsWrong(this);
        }
    })
    $$('input.validateInput').each(function(inputObj){
        inputObj.onErrorFunction = function(formObject){
            $A(formObject.elements).each(OP.DPT_markInputObjectAsRight);
            OP.DPT_markInputObjectAsWrong(this);
        }
    })
})

// toggle delivery in the registration page
OP.toggleBezorging = function(eventObject){
    var formObj = $(document.forms['customerdataform']);
    var fieldSetObj = $('shippingaddress');
    if(formObj.readAttribute('action_if_changed')){
        formObj.action = formObj.readAttribute('action_if_changed');
    };
    if(this.value == 'factuuradres') {
        // in the registration page, the shipping address fields aren't present by default. ignore them
        // if they don't exist
        if(formObj['sh_name_first']){
            OP.addressFields.each(function(billingFieldName){
                var shippingFieldName = '';
                if(billingFieldName.match(/^in_ca_cu/)) {
                    shippingFieldName = billingFieldName.replace(/^in_ca_cu_Cust/, 'in_ca_of_Shipping');
                } else {
                    shippingFieldName = billingFieldName.replace(/^/, 'sh_');
                };
                try {
                    formObj[shippingFieldName].value = formObj[billingFieldName].value;
                } catch(err){
                    console.log('billing: ', billingFieldName, ' to shipping ', shippingFieldName, ' failed:', err);
                }
            })
            if(fieldSetObj.visible()){
                Effect.BlindUp(fieldSetObj, {'duration': 0.5});
            }
        };
    } else {
        // the shipping address fields aren't necessarily present by default
        if(fieldSetObj){
            if(formObj['sh_name_first']){
                Effect.BlindDown(fieldSetObj, {'duration': 0.5});
            } else {
                new Ajax.Updater(fieldSetObj, GLOBAL_URL_STORE + '/UserTemplate/form_shippingaddress', {
                    method: 'post',
                    parameters: {'runSSSHeader' : 'yes'},
                    onCreate: function(e){
                        Effect.BlindDown(fieldSetObj, {'duration': 0.5});
                    },
                    onComplete: function(e){
                        $(fieldSetObj).select('input.turnred').each(function(inputObj){
                            inputObj.onErrorFunction = function(eventObject){
                                $A(formObj.elements).each(OP.markInputObjectAsRight);
                                OP.markInputObjectAsWrong(this);
                            };
                        });
                        $(fieldSetObj).select('input.validateInput').each(function(inputObj){
                            inputObj.onErrorFunction = function(eventObject){
                                $A(formObj.elements).each(OP.DPT_markInputObjectAsRight);
                                OP.DPT_markInputObjectAsWrong(this);
                            };
                        });
                    }
                });
            }            
        }
    }
};


ECube.registerOnLoadFunction(function(e){
    $$('input.toggle_bezorging').each(function(radioObj){
        radioObj.observe('click', OP.toggleBezorging);
    })
})

// toggle the mustmatch for zipcode fields based on the selected country
OP.setZipCodeMustMatch = function(){
    var regExps = {
        'NL': "^\\s*\\d{4}\\s*[a-zA-Z]{2}\\s*$",
        'BE': "^\\s*([bB]\\-*){0,1}\\d{4}\\s*$"
    };
    var formObj = $(document.forms['customerdataform']);
    if(! formObj){
        console.log('ERROR: attempt to set mustmatch for zipcode without form object');
        return false;
    };
    var serialized = formObj.serialize(true);
    // console.log(serialized);
    $(['sh_', '']).each(function(prefix){
        // console.log('met prefix ', prefix);
        if(formObj[prefix+'country'] && formObj[prefix+'zipcode']){
            var country = serialized[prefix+'country'].toUpperCase();
            if(regExps[country]){
                $(formObj[prefix+'zipcode']).writeAttribute('mustmatch', regExps[country]);
            } else {
                $(formObj[prefix+'zipcode']).writeAttribute('mustmatch', '');
            }
            // console.log('voor ', country, ':', formObj[prefix+'zipcode'])
        }
    });

}


OP.loadBillingForm = function(containerObject) {
    if(! containerObject) {
        containerObject = $('billingdata');
        if(! containerObject) {
            console.log('ERROR: OP.loadBillingForm called without container object');
            return false;
        };
    };
    var formObj = document.forms['customerdataform'];
    if(! formObj) {
        console.log('ERROR: attempt to load billing form fields but no form object "customerdataform" exists');
        return false;
    }
    if(formObj.readAttribute('action_if_changed')){
        formObj.action = formObj.readAttribute('action_if_changed');
    };
    new Ajax.Request(GLOBAL_URL_STORE + '/UserTemplate/form_billingaddress', {
        method: 'post',
        parameters: {'runSSSHeader' : 'yes'},
        onCreate: function(){
            if(containerObject.visible()){
                Effect.BlindUp(containerObject, {'duration': 0.3});
            };
            var displayObj = $('display_billing_data');
            if(displayObj) {
                Effect.BlindUp(displayObj, {'duration': 0.1});
            };
            
        },
        onComplete: function(transport) {
            containerObject.innerHTML = transport.responseText;
            // showing the container object causes some display problems. something css-ish
            containerObject.show();
            $(containerObject).select('input.turnred').each(function(inputObj){
                inputObj.onErrorFunction = function(eventObject){
                    $A(formObj.elements).each(OP.markInputObjectAsRight);
                    OP.markInputObjectAsWrong(this);
                };
            });
            $(containerObject).select('input.validateInput').each(function(inputObj){
                inputObj.onErrorFunction = function(eventObject){
                    $A(formObj.elements).each(OP.DPT_markInputObjectAsRight);
                    OP.DPT_markInputObjectAsWrong(this);
                };
            });
            try {
                formObj['name_first'].focus();
            } catch(err) {
                console.log('In OP.loadBillingForm onComplete attempt to focus non existing field in form failed: ', err);
            };
        }
    })
}

ECube.registerOnLoadFunction(function(e){
    var linkObj = $('load_billing_form');
    if(linkObj){
        linkObj.observe('click', function(eventObject){ 
            window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
            this.hide();
            OP.loadBillingForm();
            
        });
    };
})

OP.submitBasketIntoSelf = function(eventObject){
    console.log('submitting basket into self');
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    try {
        var formObj = $(this);
        new Ajax.Updater(formObj, formObj.action, {
            'parameters' : formObj.serialize(),
            'onComplete' :  function(transport) {
                                EpagesShop.updateBasketQuantityFields.basketFormNames.each(function(formName){
                                    EpagesShop.updateBasketQuantityFields.assignListeners(formName);
                                });
                            }
            });
    } catch (err) {
        console.log('er is een fout opgetreden in OP.submitBasketIntoSelf: ', err);
    };
};


ECube.registerOnLoadFunction(function(e){
    var basketInOP = $('basket_in_op');
    if (basketInOP){
        console.log('Found Basket in orderproces ', basketInOP);
        basketInOP['submitFunction'] = OP.submitBasketIntoSelf;
    }
})

ECube.customFormValidators['selectpaymentform'] = function(eventObject){
    if($(this).serialize().toQueryParams()['Payment']){
        return true;
    };
    // console.log($(this).serialize().toQueryParams());
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    return false;
};

// Hack. check if the form is actually changed. if it is, set the action to what's in action_if_changed

// store the onload situation in the string customerdata
var customerdata = '';
ECube.registerOnLoadFunction(function(e){
    var formObj = document.forms['customerdataform'];
    if(formObj){
        customerdata = $(formObj).serialize();
    };
});

ECube.customFormValidators['customerdataform'] = function(eventObject){
    OP.setZipCodeMustMatch();
    var validator = new ECube.formValidator(this);
    if(validator.hasErrors()) {
        window.event? event.returnValue = false : eventObject.preventDefault();
        var errors = validator.getErrors();
        var markMFErrorsBilling = false;
        var markMFErrorsShipping = false;
        for(var i = errors.length - 1 ; i >=0 ; i--){
            var elem = errors[i];
            if(elem.name == 'name2'){
                markMFErrorsBilling = true;
            };
            if(elem.name == 'sh_name2'){
                markMFErrorsShipping = true;
            };
        };
        var billingMFRadioObj = $('billing_mf_radios');
        if(billingMFRadioObj){
            if(markMFErrorsBilling){
                billingMFRadioObj.style.color = '#f00';
            } else {
                billingMFRadioObj.style.color = '#000';
            };
        };
        var shippingMFRadioObj = $('shipping_mf_radios');
        if(shippingMFRadioObj){
            if(markMFErrorsShipping){
                shippingMFRadioObj.style.color = '#f00';
            } else {
                shippingMFRadioObj.style.color = '#000';
            };
        };
        validator.markErrors();
        return false;
    };
    if(this['passwd']){
        var passwd = this['passwd'].value;
        var passwdc = this['passwdc'].value;
        if(passwd != passwdc) {
            this['passwdc'].value = '';
            this['passwd'].value = '';
            OP.markInputObjectAsWrong(this['passwd']);
            OP.markInputObjectAsWrong(this['passwdc']);
            this['passwd'].focus();
            window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
            return false;
        } else {
            OP.markInputObjectAsRight(this['passwd']);
            OP.markInputObjectAsRight(this['passwdc']);
        }
    };

    // check if an input element ShippingEQBilling is set to 'factuuradres'
    // If it is, the customer has explicitly indicated the shipping address
    // is set to the billing address. If the billing address has just been changed,
    // that may not actually be the case, so just to be sure we reset the shipping
    // address to the billing address if ShippingEQBilling is set to 'factuuradres'
    
    if(this['bezorging']){
        var formObj = $(this);
        var formData = formObj.serialize(true);
        if(formData['bezorging'] == 'factuuradres'){
            // the shipping address fields may not actually exist. if they don't,
            // create them (not a problem - we submit at the end of this)
            OP.addressFields.each(function(billingFieldName){
                var shippingFieldName = '';
                if(billingFieldName.match(/^in_ca_cu/)) {
                    shippingFieldName = billingFieldName.replace(/^in_ca_cu_Cust/, 'in_ca_of_Shipping');
                } else {
                    shippingFieldName = billingFieldName.replace(/^/, 'sh_');
                };
                if(formObj[shippingFieldName]){
                    try {
                        formObj[shippingFieldName].value = formData[billingFieldName];
                    } catch(err){
                        console.log('billing: ', billingFieldName, ' to shipping ', shippingFieldName, ' failed:', err);
                    }
                } else {
                    var elem = new Element('input', {'type' : 'hidden', 
                                                     'name' : shippingFieldName,
                                                     'value': formData[billingFieldName]});
                    try {
                        formObj.appendChild(elem);
                    } catch(err){
                        console.log('unable to attach new shipping field ', elem, ' to ', formObj);
                    }
                }
            });
        };
    };
    
    // TODO : we always go to action_if_changed because onload there
    // is no shipping data while onsubmit there is
    if(customerdata != $(this).serialize()){
       var action_if_changed = $(this).readAttribute('action_if_changed');
       if(action_if_changed){
           this.action = action_if_changed;
       };
    };
    return true;
}



ECube.registerOnLoadFunction(function(e){
    var checkoutlink = $('checkoutlink');
    if(! checkoutlink) { return false; };
    
    new Ajax.Request(GLOBAL_URL_STORE + '/UserTemplate/sys_call', {
        'method' : 'post',
        'parameters' : {'in_ca_of_TandCOK' : '1'},
        'onSuccess' : function(){
            return true;
        }
    });    
});


// fill up PM and Brand for Ogone
OP.setPMAndBrand = function(eventObject){
    var pm = 'CreditCard';
    var brand = '';
    var canSubmit = false;
    var formObj = $(this);
    formObj.select('input.paymentMethod').each(function(pmInputObj){
        if(pmInputObj.checked ){
            brand = pmInputObj.id;
            canSubmit = true;
        }
    });
    if(brand.match(/ideal/i) || brand.match(/paypal/i)){
        pm = brand;
        formObj.elements['Brand'].value = brand;
    };
    formObj.elements['PM'].value = pm;
    if(canSubmit){
        return true;
    } else {
        alert('Nog geen betaalmethode geselecteerd. Kies je betaalmethode');
    };
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    return false;
};


ECube.registerOnLoadFunction(function(e){
    if(document.forms['selectpaymentform']){
        $(document.forms['selectpaymentform']).observe('submit', OP.setPMAndBrand);
    }
})

// auto submit the ogone redirect form
ECube.registerOnLoadFunction(function(e){
    if(document.forms['gotoogoneform']){
        document.forms['gotoogoneform'].submit();
    }
})
/**********************************************************************************
    
    auto submit the gotopayment form (if it exists)
    
**********************************************************************************/
document.observe("dom:loaded", function(e){
    if(document.forms['gotopaymentform']) {
        document.forms['gotopaymentform'].submit();
    };
})

