/**
 * DMC FastCheckout
 *
 * 
 */
var Checkout = Class.create();
Checkout.prototype = {
    initialize: function( urls){
    
        this.form = $('checkoutForm');
        this.progressUrl = urls.progress;
        this.reviewUrl = urls.review;
        this.vatUrl = urls.vat;
        this.saveMethodUrl = urls.saveMethod;
        this.failureUrl = urls.failure;
        this.billingForm = false;
        this.shippingForm= false;
        this.billingEqualShipping = true;
        this.method = '';
        this.payment = '';
        this.loadWaiting = false;
        this.shippingPrice = 0;
        this.shippingTax = 0;
        this.countryId = 'DE';
    },
    
    init: function() {
        
    },

    _disableEnableAll: function(element, isDisabled) {
        var descendants = element.descendants();
        for (var k in descendants) {
            descendants[k].disabled = isDisabled;
        }
        element.disabled = isDisabled;
    },

    setLoadWaiting: function(step, keepDisabled) {
        if (step) {
            if (this.loadWaiting) {
                this.setLoadWaiting(false);
            }
            var container = $(step+'-buttons-container');
            container.setStyle({opacity:.5});
            this._disableEnableAll(container, true);
            Element.show(step+'-please-wait');
        } else {
            if (this.loadWaiting) {
                var container = $(this.loadWaiting+'-buttons-container');
                var isDisabled = (keepDisabled ? true : false);
                if (!isDisabled) {
                    container.setStyle({opacity:1});
                }
                this._disableEnableAll(container, isDisabled);
                Element.hide(this.loadWaiting+'-please-wait');
            }
        }
        this.loadWaiting = step;
    },
    
    /* --- Addresses --- */
    setUseShippingAddress: function() {
        
        if($('use_for_shipping').checked == false) {
            var elements = Form.getElements($('shipping-container'));
            for (var i=0; i<elements.length; i++) {
                    elements[i].disabled = false;
                    
            }
            $('shipping-container').show();
            this.billingEqualShipping = false;
        }
        else {
            var elements = Form.getElements($('shipping-container'));
            var method = null;
            for (var i=0; i<elements.length; i++) {
                    elements[i].disabled = true;
            }
            $('shipping-container').hide() 
            this.billingEqualShipping = true;
        }
    },
    
    setAddress: function(type, newAddress){
        var elements = Form.getElements($(type+'-new-address-form'));
        if (!newAddress) {
            $(type+'-new-address-form').hide();
            for (var i=0; i<elements.length; i++) elements[i].disabled = true;
        }
        else {
            $(type+'-new-address-form').show();
            for (var i=0; i<elements.length; i++) elements[i].disabled = false;
        }
    },
    
    fillForm: function(transport){
        var elementValues = {};
        if (transport && transport.responseText){
            try{
                elementValues = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                elementValues = {};
            }
        }
        else{
            this.resetSelectedAddress();
        }
        arrElements = Form.getElements(this.form);
        for (var elemIndex in arrElements) {
            if (arrElements[elemIndex].id) {
                var fieldName = arrElements[elemIndex].id.replace(/^billing:/, '');
                arrElements[elemIndex].value = elementValues[fieldName] ? elementValues[fieldName] : '';
                if (fieldName == 'country_id' && billingForm){
                    billingForm.elementChildLoad(arrElements[elemIndex]);
                }
            }
        }
    },
    
    setUseBliingForShipping: function(flag) {
        flag ? $('use_for_shipping').checked = true : $('use_for_shipping').checked = false;
        this.setUseShippingAddress();
    },
    
     /* --- Payment --- */
     
    setShippingMethod: function(code)
    {
       $('s_method_'+code).checked = true;
         
        var request = new Ajax.Request(
               this.saveShippingUrl,
                {
                    method: 'get',
                    onComplete: function() {
               
                    },
                    onSuccess: function(transport) {
                        
                        try{
                            response = eval('(' + transport.responseText + ')');
                        }
                        catch (e) {
                            response = {};
                        }
         
                        $('review-container').update( response.review );
                        
                    },
                    onFailure: function(transport) {
                        alert('onFailure ' + transport);
                    },
                    parameters: {'shippingId': code}
                }
            );
        return;
           
        if(checkout.shippingRates[code]) {
            
            this.grandTotal     = this.grandTotal  - this.shippingPrice;
            
             //alert('vorher '+this.shippingPrice + '  GT: ' +  this.grandTotal  );
            
            //if(this.countryId != false && $('s_method_tablerate_bestway') 
            //    && $('s_method_tablerate_bestway').checked == true) {
            //        
            //      this.shippingPrice  = checkout.shippingTableRates[this.countryId];  
            //}
            //else {
                this.shippingPrice  = checkout.shippingRates[code].price_incl * 1;
            //}

            this.grandTotal     = this.grandTotal  + this.shippingPrice;
            this.tax            = this.tax  - this.shippingTax;
            this.shippingTax    = checkout.shippingRates[code].tax;
            this.tax            = this.tax  + this.shippingTax;
            
            //alert(this.shippingPrice + '  GT: ' +  this.grandTotal  );
            
            if($('shipping-name')) {
                $('shipping-name').update(checkout.shippingRates[code].carrier);
            }
            if($('shipping-cost')) {
                $('shipping-cost').update(formatMoney(this.shippingPrice));
            }
            $('s_method_'+code).checked = true;
        }        
        this.updateGrandTotal();
    },
    
    /**
     * Updates the shipping country
     *
     */
    updateShippingRate: function(countryId, type)
    {
        // IB,BE,BG,DK,EE,FI,FR,GR,IE,IT,LV,LT,LU,MT,NL,PL,PT,AT,RO,SE,SK,SI,ES,CZ,HU,GB,CY
        
        if(in_array(countryId,['IB','BE','BG','DK','EE','FI','FR','GR','IE','IT','LV','LT','LU','MT','NL','PL','PT','AT','RO','SE','SK','SI','ES','CZ','HU','GB','CY']) == true) {
           
            $('vat-info').hide();
            $('vat-container').show(); 
            $('custom-container').hide();
        }
        else {
             $('vat-container').hide();  
             $('custom-container').show();  
        }
        
        if(this.billingEqualShipping == false && type == 'billing') {
            return;
        }
        
        $('load-bg').show();
        $('load-hint').show();
        
        
        
         var request = new Ajax.Request(
               this.saveShippingCountryUrl,
                {
                    method: 'get',
                    onComplete: function() {
                        $('load-bg').hide();
                        $('load-hint').hide();
                    },
                    onSuccess: function(transport) {
                        
                        try{
                            response = eval('(' + transport.responseText + ')');
                        }
                        catch (e) {
                            response = {};
                        }
                        // update table rates
                        checkout.shippingRates = response.config;
                        $('checkout-shipping-method-load').update(response.shipping);
                        $('review-container').update( response.review );
                        $('checkout-payment-method-load').update( response.payment );
                        
                    },
                    onFailure: function(transport) {
                        alert('onFailure ' + transport);
                    },
                    parameters: {'countryId': countryId}
                }
            );
        
        /*
        if(checkout.shippingTableRates[countryId]) {
            this.countryId      = countryId;
            this.grandTotal     = this.grandTotal  - this.shippingPrice;
            this.shippingPrice  = checkout.shippingTableRates[countryId];  
            this.grandTotal     = this.grandTotal  + this.shippingPrice;
            
            //alert(this.shippingPrice + '  GT: ' +  this.grandTotal  );
            
            //this.tax            = this.tax  - this.shippingTax;
            //this.shippingTax    = checkout.shippingRates[code].tax;
            //this.tax            = this.tax  + this.shippingTax;
            
            if($('shipping-cost')) {
                $('shipping-cost').update(formatMoney(this.shippingPrice));
            }
            $('tablerate_bestway-price').update( formatMoney(this.shippingPrice) );
            
            this.updateGrandTotal();
        }
        */
        
    },
    
    checkVatId: function()
    {
        $('load-bg').show();
        $('load-hint').show();
        
        $('vat-info').hide()
    
        var request = new Ajax.Request(
               this.vatUrl,
                {
                    method: 'post',
                    
                    onComplete: function() {
                        $('load-bg').hide();
                        $('load-hint').hide();
                    },
                    
                    onSuccess: function(transport) {
                        
                      
        
                        try{
                            response = eval('(' + transport.responseText + ')');
                        }
                        catch (e) {
                            response = {};
                        }
                        
                        
                        
                        if(response.error) {
                            $('vat-info').show().update(response.error);
                            $('vat-info').addClassName('error');
                            return false;
                        }
                        
                        $('vat-info').removeClassName('error');
                        

                        if(response.updates) {
                            $('review-container').update( response.updates.review );
                        }
                        // alert(response.code);
          
                        $('vat-info').show().update(response.message);
                        //alert(response.valid +' -- '+response.message);
                    },
                    onFailure: function(transport) {
                        alert('onFailure ' + transport);
                    },
                    parameters: Form.serialize($('billing-new-address-form'))
                }
            );
    },
    
    signIn: function()
    {
        $('login-bg').show();
        $('login-form').show();
    },

    hideLoad: function()
    {
         $('login-bg').hide();
         $('login-form').hide();
         
         $('load-bg').hide();
         $('load-hint').hide();
    },
     
    /* --- Payment --- */
    initPayment : function () {
        var elements = Form.getElements($('checkout-payment-methods'));
        var method = null;
        for (var i=0; i<elements.length; i++) {
            if (elements[i].name=='payment[method]') {
                if (elements[i].checked) {
                    method = elements[i].value;
                }
            } else {
                elements[i].disabled = true;
            }
        }
        if (method) this.switchMethod(method);
    },

    switchPaymentMethod: function(method){
        if (this.currentMethod && $('payment_form_'+this.currentMethod)) {
            var form = $('payment_form_'+this.currentMethod);
            form.style.display = 'none';
            var elements = form.select('input', 'select', 'textarea');
            for (var i=0; i<elements.length; i++) elements[i].disabled = true;
        }
        
        if ($('p_method_'+method)){
            $('p_method_'+method).checked = true;
        }
        
        if ($('payment_form_'+method)){            
            var form = $('payment_form_'+method);
            form.style.display = '';
            var elements = form.select('input', 'select', 'textarea');
            for (var i=0; i<elements.length; i++) elements[i].disabled = false;
            this.currentMethod = method;
        }
        
        
        
        
         var request = new Ajax.Request(
               this.savePaymentUrl,
                {
                    method: 'get',
                    onComplete: function() {
               
                    },
                    onSuccess: function(transport) {
                        
                        try{
                            response = eval('(' + transport.responseText + ')');
                        }
                        catch (e) {
                            response = {};
                        }
         
                        $('review-container').update( response.review );
                        
                    },
                    onFailure: function(transport) {
                        alert('onFailure ' + transport);
                    },
                    parameters: {'paymentId': method}
                }
            );
    },
    
    

    validatePayment: function() {
        var methods = document.getElementsByName('payment[method]');
        if (methods.length==0) {
            alert(Translator.translate('Your order can not be completed at this time as there is no payment methods available for it.'));
            return false;
        }
        for (var i=0; i<methods.length; i++) {
            if (methods[i].checked) {
                return true;
            }
        }
        alert(Translator.translate('Please specify payment method.'));
        return false;
    },
    
    updateGrandTotal: function() {
        if($('total-bottom')) {
            $('total-bottom').update(formatMoney(this.grandTotal));
        }
        if($('totals-grand')) {
            $('totals-grand').update(formatMoney(this.grandTotal));
        }
        if($('totals-tax')) {
            $('totals-tax').update(formatMoney(this.tax));
        }
   },
   
   order: function(checkoutForm) {
        if(checkoutForm.validator && checkoutForm.validator.validate()){
             checkoutForm.form.submit();
             $("order-button").hide();
             $("loading-message").show();
        }
        
   }

}

function formatMoney(num) {
    var CURRENCY = ' &euro;';
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + ',' + cents + CURRENCY);
};

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}
