countryCheckerConditionAbstract = Class.create(
{
    _getChecked: function(el, def) {
        return Object.isElement(el) ? el.checked : def;
    },
    _setChecked: function(el, val) {
        if (Object.isElement(el)) {
            el.checked = val;
        }
    }
}
);
countryCheckerConditionBilling = Class.create(countryCheckerConditionAbstract,
{
    initialize: function(useForShippingYes, useForShippingNo) {
        this.useForShippingYes = $(useForShippingYes);
        this.useForShippingNo  = $(useForShippingNo);
        this.useForShippingYesChecked = this._getChecked(this.useForShippingYes, false);
        this.useForShippingNoChecked  = this._getChecked(this.useForShippingNo, false);
    },
    isCheckRequired: function(countryChecker, fieldValue, forTrigger) {
        return this._getChecked(this.useForShippingYes, false) && countryChecker.isInOtherWebsite(fieldValue);
    },
    execFallback: function() {
        this._setChecked(this.useForShippingYes, this.useForShippingYesChecked);
        this._setChecked(this.useForShippingNo, this.useForShippingNoChecked);
    },
    execCallback: function() {}
}
);
countryCheckerConditionShipping = Class.create(countryCheckerConditionAbstract,
{
    initialize: function(sameAsBilling, sameAsBillingCallback, billingCountryId) {
        this.sameAsBilling = $(sameAsBilling);
        this.sameAsBillingChecked = this._getChecked(this.sameAsBilling, false);
        this.sameAsBillingCallback = sameAsBillingCallback;
        this.billingCountry = $(billingCountryId);
    },
    _getBillingCountryValue: function() {
        return Object.isElement(this.billingCountry) ? this.billingCountry.value : null;
    },
    isCheckRequired: function(countryChecker, fieldValue, forTrigger) {
        return (!forTrigger && countryChecker.isInOtherWebsite(fieldValue)) 
            || (this._getChecked(this.sameAsBilling, false) && countryChecker.isInOtherWebsite(this._getBillingCountryValue()));
    },
    execFallback: function() {
        this._setChecked(this.sameAsBilling, this.sameAsBillingChecked);
    },
    execCallback: function() {
        if (Object.isFunction(this.sameAsBillingCallback) && this._getChecked(this.sameAsBilling, false)) {
            return this.sameAsBillingCallback();
        }
    }
}
);
countryChecker = Class.create(
{
    websiteData:'',
    confirmMessage:'This store not working with selected country. If you want to move to the right store - press OK',
    postUrl:'',
    updateCountryUrl:'',
    initialize: function(fieldid, website_data, post_url, update_country_url) {
        this.fieldId = fieldid;
        this.websiteData = website_data;
        this.updateCountryUrl = update_country_url;
        this.postUrl = post_url;
    },
    setConfirmMessage: function(message) {
        this.confirmMessage = message;
    },
    confirmRedirect: function (countryId) {
         if(confirm(this.confirmMessage)) {
             var time = new Date();
             var expr = new Date( time.getYear() + 1901, time.getMonth(), time.getDay() );
             setCookie("cmwebsite", this.websiteData.otherWebsiteCode, expr, '/');
             this.post_to_url(this.postUrl, {country_id:countryId}, 'post');
             return true;
         } else {
             return false;
         }
    },
    resetField: function () {
        $(this.fieldId).value = this.fieldPrevValue;
    },
    getFieldValue: function () {
        return $(this.fieldId).value;
    },
    isInOtherWebsite: function (countryId) {
        return countryId && this.websiteData.currentWebsiteCountries.search(countryId) == -1;
    },
    isConfirmRedirect: function (fieldValue, forTrigger) {
        return this.checkCondition(fieldValue, forTrigger);
    },
    validateOnFormSubmit: function (event) {
        if(this.isConfirmRedirect(this.getFieldValue(), false)) {
            if(!this.confirmRedirect(this.getFieldValue())) {
                this.execFormSubmitFallback();
            }
        } else {
            this.execFormSubmitCallback();
        }
    },
    validateOnConditionChange: function (event) {
        if(this.isConfirmRedirect(this.getFieldValue(), true)) {
            if(!this.confirmRedirect(this.getFieldValue())) {
                this.execConditionFallback();
            }
        } else {
            this.execConditionCallback();
        }
    },
    validateOnChange: function (event) {
        if(this.isConfirmRedirect(this.getFieldValue(), false)) {
            if (!this.confirmRedirect(this.getFieldValue())) {
                this.resetField();
                this.execValidateFallback();
                return false;
            }
        } else {
            new Ajax.Request(this.updateCountryUrl, {
                method:'post',
                parameters: {country_id: this.getFieldValue()},
                onComplete: this.loadMiniCart.bind(this)
            });
        }
        this.fieldPrevValue = this.getFieldValue();
        this.execValidateCallback();
        return true;
    },
    loadMiniCart: function(transport) {
        transport.responseText;
        //$('mini-cart-update').innerHTML=transport.responseText;
        var my_div = document.createElement(transport.responseText);
        $('mini-cart-update').parentNode.appendChild(my_div);//.=transport.responseText;
    },
    post_to_url: function(path, params, method) {
        method = method || "post"; // Set method to post by default, if not specified.

        // The rest of this code assumes you are not using a library.
        // It can be made less wordy if you use one.
        var form = document.createElement("form");
        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var key in params) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);    // Not entirely sure if this is necessary
        form.submit();
    },
    bindOn: function (id) {
         this.fieldId = id;
         this.fieldPrevValue = $(this.fieldId).value;
         $(this.fieldId).observe('change', this.validateOnChange.bind(this));
    },
    setCondition: function (condition) {
        this.condition = condition;
    },
    checkCondition: function (fieldValue, forTrigger) {
        return Object.isUndefined(this.condition) ? this.isInOtherWebsite(fieldValue) : this.condition.isCheckRequired(this, fieldValue, forTrigger);
    },
    execConditionCallback: function () {
        return Object.isUndefined(this.condition) ? false : this.condition.execCallback();
    },
    execConditionFallback: function () {
        return Object.isUndefined(this.condition) ? false : this.condition.execFallback();
    },
    setFormSubmitCallback: function (formSubmitCallback) {
        this.formSubmitCallback = formSubmitCallback;
    },
    execFormSubmitCallback: function () {
        return Object.isFunction(this.formSubmitCallback) ? this.formSubmitCallback() : false;
    },
    setFormSubmitFallback: function (formSubmitFallback) {
        this.formSubmitFallback = formSubmitFallback;
    },
    execFormSubmitFallback: function () {
        return Object.isFunction(this.formSubmitFallback) ? this.formSubmitFallback() : false;
    },
    setValidateCallback: function (validateCallback) {
        this.validateCallback = validateCallback;
    },
    execValidateCallback: function () {
        return Object.isFunction(this.validateCallback) ? this.validateCallback() : false;
    },
    setValidateFallback: function (validateFallback) {
        this.validateFallback = validateFallback;
    },
    execValidateFallback: function () {
        return Object.isFunction(this.validateFallback) ? this.validateFallback() : false;
    }
}
);

AddressChecker = Class.create(
{
    countryChecker:'',
    address2country:'',
    baseUrl:'',
    initialize: function (countryChecker, address2country, baseUrl) {
        this.countryChecker = countryChecker;
        this.address2country = address2country;
        this.baseUrl = baseUrl;
    },
    checkAddressId: function(selectElement) {
        var addressId = $(selectElement) ? $(selectElement).value : false;
        if (addressId) {
            var needle = this.address2country[addressId];
            if(needle && this.countryChecker.websiteData.currentWebsiteCountries.search(needle) == -1) {
                if(confirm(this.countryChecker.confirmMessage)) {
                    var time = new Date();
                    var expr = new Date( time.getYear() + 1901, time.getMonth(), time.getDay() );
                    deleteCookie("cmwebsite");
                    setCookie("cmwebsite", this.countryChecker.websiteData.otherWebsiteCode, expr, '/');
                    this.countryChecker.post_to_url(this.countryChecker.postUrl, {country_id:needle}, 'post');
                    return false;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return true;
        }
    },
    bindOn: function (selectElement) {
        $(selectElement).observe('change', this.checkAddressId.bind(this));
   }
}
);
