jQuery(document).ready(function () {
    jQuery.fn.colorbox.settings.bgOpacity = "0.75";

    jQuery("a[rel='pimage']").colorbox({
        transition:"elastic",
        contentCurrent:"{current} / {total}"
    });

    jQuery(".productDetails a").each(function () {
      this.target = '_blank';
    });

    jQuery('#submitLeaseApplication').click(function () { cartSubmit('/lease/apply') });
    
    if (jQuery('#approveLeaseAgreement').length || jQuery("#submitOrder").attr('quick') == 'yes')
    {
      jQuery("#submitOrder").click(cartSubmitOrder);
    }
    else
    {
      jQuery("#submitOrder").colorbox({inline:true, href:"#paymentTypeContent"});
    }

    jQuery("#submitOrderWithPaymentType").click(function(){
        jQuery.get('/cart/paymenttype/' + jQuery("select#select-payment-type").attr('value'), function(data) {
          cartSubmitOrder();
        });
    });
    jQuery("input#cartChange").addClass("fadedButton").attr("disabled", 1);

    jQuery("table.cart > tbody > tr > td > input.quantity").change(function(){
        jQuery("input#cartChange").removeClass("fadedButton").click();
    });

    jQuery("table.cart > tbody > tr > td > input.quantity").bind('keypress', (function(){
        jQuery("input#cartChange").removeClass("fadedButton").attr("disabled", 0);
    }));

    //LeaseCalculator

    jQuery('#form-item-BankAccount').append(
        '<li id="form-item-Sum"><label class="optional">Kuumakse:</label>&#160;<span id="LeaseRequest-Payment" class="bold">&#160;</span></li>'
    );

    jQuery('select#leaseCalculatorPaymentPeriod,select#leaseCalculatorAdvancePayment').setSelectedByTitle();
    jQuery('#leaseCalculator,#LeaseRequest-').calculatePayment();
    jQuery('#leaseCalculatorSum,#LeaseRequest-Sum').formatCurrency({region: 'et-EE'});

    jQuery('select#leaseCalculatorPaymentPeriod,select#leaseCalculatorAdvancePayment').change(function(){
        jQuery('#leaseCalculator').calculatePayment();
    });
    jQuery('select#LeaseRequest-PaymentPeriod,select#LeaseRequest-AdvancePayment').change(function(){
        jQuery('#LeaseRequest-').calculatePayment();
    });

    // jQuery('#LeaseRequest-submit').addClass('coolButtonGreen').before('<button id="submitOrder" style="" onclick="document.location=\'/cart/preview\'; return false;">Kinnita tellimus</button>&#160;');

    jQuery('select#LeaseRequest-Client-IdentityType').change(function() {
        setCompanyDetailInputsVisibility(jQuery(this).attr('value'));
    });
    setCompanyDetailInputsVisibility(jQuery('select#LeaseRequest-Client-IdentityType').attr('value'));

    var f;
    jQuery('select#LeaseRequest-Client-Region').change(f = function() {
        if (jQuery.trim(jQuery(this).attr('value')) == '') {
            showTaxBoardSelect('');
        } else {
            showTaxBoardSelect(jQuery('select#LeaseRequest-Client-Region :selected').text());
        }
    }).click(f).triggerHandler('change');

    //Confirm order form
    jQuery('#showAgreement').click(function() {
        jQuery('#cartPreviewAgreement').toggle();
        return false;
    });
    jQuery('#approveLeaseAgreement').length && jQuery("#submitOrder").addClass("fadedButton").attr("disabled", 1)
    jQuery('#approveLeaseAgreement').click(function() {
        $(this).is(':checked') && $('#approveOrderAgreement').is(':checked') && jQuery("#submitOrder").removeClass("fadedButton").attr("disabled", 0) || jQuery("#submitOrder").addClass("fadedButton").attr("disabled", 1);
    });

    jQuery('#approveOrderAgreement').length && jQuery("#submitOrder").addClass("fadedButton").attr("disabled", 1)
    jQuery('#approveOrderAgreement').click(function() {
        var lease = $('#approveOrderAgreement');
        $(this).is(':checked') && (lease.length < 1 || lease.is(':checked')) && jQuery("#submitOrder").removeClass("fadedButton").attr("disabled", 0) || jQuery("#submitOrder").addClass("fadedButton").attr("disabled", 1);
    });

    //ShippingMethod
    jQuery("select#select-shipping-method").change(function(){
        jQuery.getJSON('/cart/shipping/' + jQuery(this).attr('value'), function(data) {
            var target = jQuery('#shipping-cost');
            if (data != 'false') {
                target.html(data.shipping).formatCurrency({symbol: ''});
                jQuery('#cart-total').html(data.total).formatCurrency({symbol: '', digitGroupSymbol: ' '});
            } else {
                target.html('&#160;');
            }
        });
    });
});

function cartSubmit(targetPath)
{
    jQuery.post('/cart/comments/', { text: jQuery("textarea#order-comments").val() }, function(data) {
        document.location = targetPath || '/cart/order';
    });
}

function cartSubmitOrder()
{
    cartSubmit('/cart/order');
}

var taxboardCache = null;
function showTaxBoardSelect(region) {
    jQuery('li#form-item-Taxboard').hide();
    var taxboard = jQuery("select#LeaseRequest-Client-Taxboard");
    if (taxboardCache == null)
    {
      taxboardCache = jQuery('optgroup', taxboard);
    }
    taxboardCache.remove();
    
    var optgroup;
    taxboardCache.each(function (key, el) {
      if ($(el).attr('label') == region)
      {
        optgroup = $(el);
        return false;
      }
    });
    taxboard.append(optgroup);
    
    if (jQuery('option', optgroup).length == 1)
    {
      taxboard.attr('value', jQuery('option', optgroup).attr('value'));
    }
    else
    {
      if (jQuery('option[selected]', optgroup).length < 1)
      {
        taxboard.attr('value', ' ');
      }
      optgroup && jQuery('option', optgroup).length > 1 && jQuery('li#form-item-Taxboard').show();
    }
}

jQuery.fn.calculatePayment = function() {
    return this.each(function() {
        var prefix = '#' + this.id;
        var sum = parseInt(jQuery(prefix + 'Sum').html().replace(/[^0-9.,]/g,''));
        sum = sum * (100 - parseInt(jQuery(prefix + 'AdvancePayment').val())) / 100;
        var deadline = parseInt(jQuery(prefix + 'PaymentPeriod').val());
        var rate = parseFloat(jQuery(prefix + 'InterestRate').html());

        if (rate == 0.0) {
            sum = sum / deadline;
        } else {
            rate = rate / 12;
            sum = (sum * rate) / (1 - Math.pow( (1 + rate), (deadline * -1) ) );
        }

        jQuery(prefix + 'Error').hide();

        if (sum < jQuery(prefix + 'Error').attr('min-payment')) {
            jQuery(prefix + 'Error').show();
        }

        jQuery(prefix + 'Payment').html(sum.toFixed()).formatCurrency({region: 'et-EE'});
    });
};

jQuery.fn.setSelectedByTitle = function() {
	return this.each(function() {
        jQuery('> option[value=' + jQuery(this).attr('title') + ']', this).attr('selected','selected');
	});
};

(function(jQuery) {
    jQuery.formatCurrency.regions['et-EE'] = {
        symbol: '€',
        positiveFormat: '%s%n',
        negativeFormat: '%s-%n',
        decimalSymbol: '.',
        digitGroupSymbol: ' ',
        groupDigits: true
    };
})(jQuery);

function setCompanyDetailInputsVisibility(state) {
    if (state == 'P') {
        jQuery('#form-item-CompanyCode,#form-item-CompanyName').hide();
    } else {
        jQuery('#form-item-CompanyCode,#form-item-CompanyName').show();
    }
}

function setupPagingSelect()
{
  function doSetCookie(val)
  {
    document.cookie = 'page_count=' + val;
  }
  jQuery('#pagingSelect option[selected]').each(function () {
    doSetCookie(this.value);
  });
  jQuery('#pagingSelect').change(function () {
      doSetCookie(this.value);
      document.location.reload()
  });
}

function cntct() {
  var a = String.fromCharCode(0x40);
  document.write('<a href="');
  document.write('ma' + String.fromCharCode(105) + 'lto:');
  document.write('galador'); document.write(a); document.write('galador' + '.' + 'ee');
  document.write('">');
  document.write('galador'); document.write(a); document.write('galador' + '.' + 'ee');
  document.write('</a>');
};


