$('#vmorderform').ready(function() {

  var create_new_vm = function(amount, storage, memory) {
    var clone = $('#order_config tbody tr:first').clone();
    $('.config_amount', clone).attr('value', amount);
    $('.config_storage', clone).attr('value', storage);
    $('.config_memory', clone).attr('value', memory);
    return clone;
  }

  var prefill_order_form = function() {
    if (window.location.href.indexOf('packages=') <= 0)
      return
    var request_data = window.location.href.split('?')[1].split('=')[1]
    var pkg_data = JSON.parse(request_data.replace(/%22/g, '"'));
    pkg_data.forEach(function(pkg) {
      var vm = create_new_vm(pkg['amount'], pkg['storage'], pkg['memory']);
      $('#order_config tbody tr:first').before(vm);
      calculate_price(vm);
      $('#order_traffic .traffic_estimated')[0].value = pkg['traffic'];
      calculate_traffic();
    });
    $('#order_config tbody tr.input:last').remove();
    $('#vmorderform').accordion("option", "active", 0);
    resize_accordion();
  };

  var create_prefill_link = function() {
    var items = new Array();
    $('#order_config tbody tr.input').each(
        function(i, item) {
        items[i] = new Object();
        items[i]["amount"] = parseInt($('.config_amount', item).attr('value')); 
        items[i]["storage"] = parseInt($('.config_storage', item).attr('value')); 
        items[i]["memory"] = parseInt($('.config_memory', item).attr('value')); 
        items[i]["traffic"] = 0;
    });
    var traffic = parseInt($("input.traffic_estimated").attr('value'));
    items[$('#order_config tbody tr.input').length - 1]["traffic"] = traffic;
    var base_url = window.location.href.split('?')[0];
    var prefill_link_full = base_url + '?packages=' + JSON.stringify(items);
    $('#create_prefill_link').attr('href', prefill_link_full);
    jQuery.get(base_url+'/tinyurlify?url='+prefill_link_full, function(data) {
        if (data)
            $('#create_prefill_link').attr('href', data);
    });

  };

  var resize_accordion = function() {
    $('#vmorderform').accordion("resize");
  };

  var format_price = function(price) {
    return parseFloat(price).toFixed(2).replace('.', ',');
  }

  var aggregate = function(id, entity) {
    var amount = 0;
    $(id).each(function(i, v) {
      var value = $(v).attr('value');
      if (!value) {
        value = $(v).text();
      }
      if (id != ".config_amount" && id != ".config_total")
          multiplicator = $(".config_amount")[i].value;
      else
          multiplicator = 1;
      amount += parseFloat(value.replace(',','.')) * multiplicator;
    });
    if (entity == '€') {
      amount = format_price(amount);
    }
    $(id+'_sum').text(amount);
  }

  var calculate_traffic =  function() {
    var incl_traffic = parseInt($('.traffic_incl').text());
    var traffic = parseInt($('.traffic_estimated').attr('value')) - incl_traffic;
    var pack_traffic = 0;
    var price = 0;
    var big_packs = 0;
    var small_packs = 0;
    if (traffic >= 0) {
      var f_packs = traffic / 1000;
      var big_packs = parseInt(f_packs);
      var rest_traffic = traffic - (big_packs * 1000);
      if (rest_traffic > 700) {
        small_packs = 0;
        big_packs += 1;
      } else {
        var f_small_packs = (f_packs - big_packs) * 10;
        small_packs = parseInt(f_small_packs);
      }
      if ((f_small_packs - small_packs) * 10) {
        small_packs += 1;
      }
      if (small_packs == 10) {
        big_packs += 1;
        small_packs = 0;
      }
      price = small_packs * 20 + big_packs * 150;
      pack_traffic = big_packs * 1000 + small_packs * 100;
    }
    $('.traffic_extra').text(pack_traffic);
    $('.traffic_price').text(format_price(price));
    $('#traffic_big_info').text(big_packs);
    $('#traffic_small_info').text(small_packs);
    $('#traffic_big_info_gb').text(big_packs * 1000);
    $('#traffic_small_info_gb').text(small_packs * 100);
    $('#traffic_big_info_price').text(format_price(big_packs * 150));
    $('#traffic_small_info_price').text(format_price(small_packs * 20));
    $('input[name=traffic_pack_big]').attr('value', big_packs);
    $('input[name=traffic_pack_small]').attr('value', small_packs);
    summarize_order();
  }

  var calculate_price = function(item) {
    var amount = parseInt($('.config_amount', item).attr('value'));
    var storage = parseInt($('.config_storage', item).attr('value'));
    var memory = parseInt($('.config_memory', item).attr('value'));

    var price = (((storage / 5 - 1) * 2.5) +
                ((memory / 128 - 2) * 2.5) +
                25);
    $('.config_price', item).text(format_price(price));
    $('.config_total', item).text(format_price(price * amount));

    aggregate('.config_amount', '');
    aggregate('.config_storage', 'GB');
    aggregate('.config_price', '€');
    aggregate('.config_memory', 'MB');
    aggregate('.config_total', '€');
    $('.traffic_incl').text((parseInt($('.config_amount_sum').text()) * 5));
    calculate_traffic();
    create_prefill_link();
  };

  var summarize_order = function() {
    var vm_amount = parseInt($('.config_amount_sum').text());
    var vm_price = $('.config_total_sum').text();
    var traffic_amount = parseInt($('#traffic_big_info').text()) +
                         parseInt($('#traffic_small_info').text());
    var traffic_costs = $('.traffic_price').text();
    $('#order_summary_vm_amount').text(vm_amount);
    $('#order_summary_vm_price').text(vm_price + ' €');
    $('#order_summary_traffic_amount').text(traffic_amount);
    $('#order_summary_traffic_price').text(traffic_costs + ' €');
    $('#order_summary_price').text(
      format_price(parseFloat(vm_price.replace(',', '.')) + parseFloat(traffic_costs.replace(',', '.'))) + ' €');
  }

  var add_new_vm = function(e) {
    var clone = create_new_vm(1, 5, 256);
    $(e.target).parents('tr').after(clone);
    calculate_price(clone);
    resize_accordion();
  }

  $('#vmorderform').accordion({ header: "h2", autoHeight: false });

  $('#order_email input').blur(function(e) {
    var pattern = new RegExp(/^([a-zA-Z0-9_.-\\+])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/);
    if (e.target.value && !pattern.test(e.target.value)) {
      $('#order_email input').addClass('error');
      $('#order_email label').addClass('error_msg');
    } else {
      $('#order_email input').removeClass('error');
      $('#order_email label').removeClass('error_msg');
    }
  });

  $('#order_config .config_amount').live('keyup', function(e) {
    var value = parseInt(e.target.value);
    if (!value) { value = 0; }
    if (value) { e.target.value = value; }
    calculate_price($(e.target).parents('tr'));
  });

  $('#order_config .config_amount, #order_config .config_storage, #order_config .config_memory').live('keypress', function(e) {
    if (e.keyCode == 13) {
      add_new_vm(e);
      e.preventDefault();
    }
  });

  $('#order_traffic .traffic_estimated, .order_summary input').live('keypress', function(e) {
    if (e.keyCode == 13) {
      e.preventDefault();
    }
  });

  $('#order_config .config_amount').live('blur', function(e) {
    if (!parseInt(e.target.value)) {
      e.target.value = 0;
    }
    calculate_price($(e.target).parents('tr'));
  });

  $('#order_config .config_storage').live('blur', function(e) {
    var f_value = parseFloat((parseInt(e.target.value) / 5));
    var value = parseInt(f_value);
    if (f_value - value) { value += 1}
    if (!value) { value = 1; }
    if (value > 2000) { value = 2000; }
    if (value) { e.target.value = value * 5; }
    calculate_price($(e.target).parents('tr'));
  });

  $('#order_config .config_memory').live('blur', function(e) {
    var f_value = parseFloat((parseInt(e.target.value) / 128));
    var value = parseInt(f_value);
    if (f_value - value) { value += 1}
    if (!value || (value < 2)) { value = 2; }
    if (value > 248) { value = 248; }
    if (value) { e.target.value = value * 128; }
    calculate_price($(e.target).parents('tr'));
  });

  

  $('#order_config .config_add').live('click', add_new_vm);

  $('#order_config .config_remove').live('click', function(e) {
    var items = $(e.target).parents('tbody').children().length;
    if (items > 3) {
      $(e.target).parents('tr').remove();
      calculate_price($(e.target).parents('tbody').first());
      resize_accordion();
    }
  });

  $('#order_traffic .traffic_estimated').keyup(function(e) {
    calculate_traffic();
  });

  $('#submit_order_form').click(function(e) {
    var projectname = $('#vmorderform #order_projectname input');
    var email = $('#vmorderform #order_email input');
    var name = $('#vmorderform #order_name input');
    var comment = $('#vmorderform #comment textarea');
    var amount = parseInt($('.config_amount_sum').text());
    var submit = true;
    if (!email.attr('value') || email.hasClass('error')) {
      submit = false;
      alert('Bitte geben Sie eine gültige E-Mail-Adresse ein.');
      $('#vmorderform').accordion("option", "active", 2);
      email.focus();
    } else if (!name.attr('value')) {
      submit = false;
      alert('Bitte geben Sie Ihren Namen ein.');
      $('#vmorderform').accordion("option", "active", 2);
      name.focus();
    } else if (!projectname.attr('value')) {
      submit = false;
      alert('Bitte geben Sie einen Projektnamen ein.');
      $('#vmorderform').accordion("option", "active", 2);
      projectname.focus();
    } else if (!amount) {
      submit = false;
      alert('Sie haben keine Virtuelle Maschine selektiert.');
      $('#vmorderform').accordion("option", "active", 0);
      $('.config_amount').focus();
    }
    if (!submit) {
      e.preventDefault();
    }
  });

  prefill_order_form();
  calculate_price();
});

