/*
 * Leaseweb.com
 * @author skl
 */

function updateItem (target, data) {
  //show loading icon first
  if(data.property != 'comment') 
  {
    target.find('.ajax-loading').show();
  }
  jQuery.post(cartUrl + '/update', data, function (response) {

    if(data.property != 'domain' && data.property != 'authcode')
    {
      if ('remove' == data.property)
      {
         window.location.href = cartUrl;
      }
      else
      {
        jQuery.post(cartUrl + '/updateOverview', data, function (json)
        {
          jQuery('#entity_'+ json.entity+' .cart_totalAmount').html(json.totalAmount);
          jQuery('#entity_'+ json.entity+' .cart_totalMonthlyAmount').html(json.totalMonthlyAmount);
          jQuery('#entity_'+ json.entity+' .cart_subtotalAmount').html(json.subtotalAmount);
          jQuery('#entity_'+ json.entity+' .cart_subtotalMonthlyAmount').html(json.subtotalMonthlyAmount);
          jQuery('#entity_'+ json.entity+' .cart_vatAmount').html(json.vatAmount);
          jQuery('#entity_'+ json.entity+' .cart_vatMonthlyAmount').html(json.vatMonthlyAmount);
          jQuery('#entity_'+ json.entity+' .cart_finalAmount').html(json.finalAmount);
          jQuery('div#helpCart ul#entity_'+ json.entity+' a.finalAmount').html(json.entity+' ' +json.finalAmount);
          jQuery('#entity_'+ json.entity+' .cart_finalMonthlyAmount').html(json.finalMonthlyAmount);
          jQuery('#entity_'+ json.entity+' .cart_itemCount').html(json.itemCount);
          jQuery('#numDomains').val(json.domains);
          jQuery('#numWebhost').val(json.webhosting);
          if (json.webhosting == 0 && (json.domains > json.webhosting))
          {
            jQuery('#webhosting_promo').show();
          }
          else
          {
            jQuery('#webhosting_promo').hide();
          }

          if (json.itemCount)
          {
            jQuery('#cart_prices_footer').show();
            jQuery('#cart_form').show();
          }
          else
          {
            window.location.href = cartUrl;
            jQuery('#cart_prices_footer').hide();
            jQuery('#cart_form').hide();
          }

          jQuery('.cart_itemCount').html(json.itemCount);

          if (data.property == 'remove')
          {
            jQuery('#cart_item_' + data.pid).remove();
          }

          jQuery('#cart_item_' + data.pid).html(response);
          jQuery(document).trigger('CART_LOADED');

          attachQuantityActions();

        }, 'json');
      }


      jQuery('#cart_item_' + data.pid).html(response);
    } else {
      target.find('.ajax-loading').hide();
    }
  });

}

function displayCustom(pid)
{
  var sel = jQuery("#domain_dropdown_"+pid+" option:selected").val();
  if(sel == "custom")
  {
    domainName = jQuery("#domain_custom_"+pid).val();
    jQuery("#domain_custom_"+pid).show();
    jQuery("#domain_custom_"+pid).focus();
  }
  else
  {
    domainName = sel;
    jQuery("#domain_custom_"+pid).hide();
    jQuery("#domain_custom_"+pid).val("");
  }
  if (domainName && domainName.match(/^[a-zA-Z0-9]{2}.*(\.[a-zA-Z]{2,6}){1}$/))
  {
    saveDomain(domainName, pid);
  }

  return false;
}

function saveDomain(domainName, pid)
{
    var data = {
    property: 'domain',
    value: domainName,
    pid: pid
  }
  
  updateItem(jQuery('#cart_item_' + pid), data);
}

jQuery(document).ready(function()
{
  jQuery('.specs .fold a').live('click', function(){
    jQuery(this).parent().parent().find('.txt').show();
    jQuery(this).parent().hide();
    return false;
  });
  jQuery(document).trigger('CART_LOADED');

  var numWebhost = jQuery('#numWebhost').val();
  var numDomains = jQuery("#numDomains").val();

  if( numWebhost == 0 && (numDomains > numWebhost))
  {
    jQuery('#wrapper_webhost_promo').show();
  }
  else
  {
    jQuery('#wrapper_webhost_promo').hide();
  }

  // payment method change
  changePaymentMethod(jQuery('input[name=method]:checked').val());

  jQuery('input#no_vat').change(function(){
    var v = jQuery(this).attr('checked') ? 1 : 0;
    jQuery('input.no_vat').val(v);
  });
  jQuery('input#no_vat').change();

  if (jQuery('.domainSelect > option:selected').val() == 'custom')
  {
    //jQuery('.domainSelect > option:selected').change();
  }

  var lastKeyUp;
  jQuery('input[id^=domain_custom_]').keyup(function(){
    displayCustom(jQuery(this).attr('id').substr(14));
  });

  jQuery('input[id^=domain_]').keyup(function(){
    var domainId = jQuery(this).attr('id');
    var split = domainId.split("_");
    var last = split.length - 1;
    var pid = split[last];
    domainName = jQuery(this).val();
    clearTimeout(lastKeyUp);
    var self = this;
    lastKeyUp = setTimeout(function(){
      if (domainName && domainName.match(/^[a-zA-Z0-9]{2}.*(\.[a-zA-Z]{2,6}){1}$/))
      {
        saveDomain(domainName, pid);
      }
    }, 500);
  });

  // change billing cycle
  jQuery('.switch_billing_cycle').live('click', function () {
    var data = {
      property: 'billing_cycle',
      value: jQuery(this).val(),
      pid: jQuery(this).attr('pid')
    }
    updateItem(jQuery('#cart_item_' + data.pid), data);
  });
  
  // change quantity
  attachQuantityActions();

  (function ($) {
    var nativePlaceholder = (function () {
      var input = document.createElement('input');
      return ('placeholder' in input);
    })();

    function addPlaceholder(input, value) {
      if (nativePlaceholder) {
        return;
      }

      if ('' === value) {
        input.val(input.attr('placeholder'));
        $.data(input[0], 'hasPlaceholder', true);
      }
    }

    function removePlaceholder(input) {
      if (nativePlaceholder) {
        return;
      }

      if (true === $.data(input[0], 'hasPlaceholder')) {
        input.val('');
        $.data(input[0], 'hasPlaceholder', false);
      }
    }

    $('.authcode')
      .bind('focus', function () {
        var input = $(this);

        removePlaceholder(input);

        $.data(input[0], 'before', input.val());
      })
      .bind('blur', function () {
        var input = $(this),
            value = input.val();

        addPlaceholder(input, value);

        if (value === ($.data(input[0], 'before') || '')) {
          return;
        }

        var data = {
          property: 'authcode',
          value: escapeHtml(strip_tags(value)),
          pid: input.attr('pid')
        };

        updateItem(jQuery('#cart_item_' + data.pid), data);
      })
      .trigger('blur');
  })(jQuery);

  // remove from cart
  jQuery('.remove_item').live('click', function (e) {
    var data = {
      property: 'remove',
      pid: jQuery(this).attr('pid')
    }

    if (confirm(message_delete))
    {
      updateItem(jQuery('#cart_item_' + data.pid), data);
    }
    return false;
  });
  
  //update comment
  jQuery('.add-comment #save-comment').live('click', function (e) {
    var pid = jQuery(this).attr('name');
    var comment = jQuery('#facebox #add-comment-' + pid + ' textarea').val();
    var data = {
      property: 'comment',
      value: comment,
      pid: pid
    }
    updateItem(jQuery('#cart_item_' + data.pid), data);
    return false;
  });

  // update quantity
  jQuery('.quantityForm input.button').live('click', function (e) {
	  var input = jQuery(this).parent().find('input');
    if (jQuery(input).val())
    {
      var data = {
        property: 'quantity',
        value: jQuery(input).val(),
        pid: jQuery(input).attr('name')
      }
      jQuery(input).attr('disabled', 'disabled');
      jQuery(this).attr('disabled', 'disabled');
      updateItem(jQuery('#cart_item_' + data.pid), data);
    }
    return false;
  });
  
  // allow only numbers in quantity field
  jQuery('.numberSrv_update').live('keydown', function (e) {
    var charCode = e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) &&
        charCode > 31 && (charCode < 96 || charCode > 105)) {
      // NaN
      return false;
    }
  });

  jQuery('input[name=method]').click(function () {
    jQuery('input[name=method]').attr('checked', false);
    jQuery(this).attr('checked', 'checked');
    changePaymentMethod(jQuery(this).val());
  });

  //check if webhosting package
  jQuery("#submit_cart").click(function () {
    var cust_input = jQuery("[name=domain]");
    var authcode_inputs = jQuery('input:text.authcode');
    var invalid = false;
    var duplicateDomain = getWebhostingDomainDuplication();


    authcode_inputs.each(function(i){
      if (jQuery(this).val() == jQuery(this).attr('placeholder') || jQuery(this).val() == "") {
        jQuery(this).parent().children('span').show();
        invalid = true;
      } else {
        jQuery(this).parent().children('span').hide();
      }
    });

    cust_input.each(function(i){
      var domainId = jQuery(this).attr('id');
      var split = domainId.split("_");
      var last = split.length - 1;
      var pid = split[last];

      if(jQuery(this).val() == "")
      {
        invalid = true;
      }
      else
      {
        var domainName = jQuery(this).val();
      }

      if(jQuery(this).val() == "custom")
      {
        if(jQuery("#domain_custom_"+pid).val() == "")
        {
          invalid = true;
          //show tooltip
          jQuery("#domain_custom_"+pid).parent().children('span').show();
        }
        else
        {
          var domainName = jQuery("#domain_custom_"+pid).val();
        }
      }

      var data = {
        property: 'domain',
        value: domainName,
        pid: pid
      }

	if (!(domainName && domainName.match(/^[a-zA-Z0-9\-]{2}.*(\.[a-zA-Z]{2,6}){1}$/)))
      {
        alert(error_empty_domain);
        invalid = true;
      }
      else
      {
        updateItem (jQuery('#cart_item_' + pid), data);
      }

    });

    if (duplicateDomain)
    {
      alert(duplicate_domain_error);
      return false;
    }

    if (invalid)
    {
      return false;
    }
    else
    {
      return true;
    }
  });

  $('.choose-payment-method form').submit(function () {
    var sub = $(this).find('input[type="submit"]');
    if(sub.attr('disabled'))
    {
      return false;
    }
    sub.attr('disabled', true);
  });

  //slide down section
  jQuery("ul#cartSectionContent li div.sectionName").live('click', function() {
    if(jQuery(this).parent().children('dl').is(':hidden')) {
      jQuery(this).css('background-image', 'url(/images/lsw2/expanded.png)');
      jQuery(this).parent().children('dl').show();
    } else {
      jQuery(this).parent().children('dl').hide();
      jQuery(this).css('background-image', 'url(/images/lsw2/collapsed.png)');
    }
  });
});

function getWebhostingDomainDuplication()
{
  var cust_input = jQuery("[name=domain]");
  var domainNames = [];
  var duplicateDomain = false;
  
  cust_input.each(function(i){
    var domainId = jQuery(this).attr('id');
    var split = domainId.split("_");
    var last = split.length - 1;
    var pid = split[last];

    if(jQuery(this).val() != "")
    {
      var domainName = jQuery(this).val();
    }

    if(jQuery(this).val() == "custom")
    {
      if(jQuery("#domain_custom_"+pid).val() != "")
      {
        var domainName = jQuery("#domain_custom_"+pid).val();
      }
    }

    if (domainName && domainName.match(/^[a-zA-Z0-9]{2}.*(\.[a-zA-Z]{2,6}){1}$/))
    {
      var inArray = jQuery.inArray(domainName, domainNames);
      if(inArray >  -1)
      {
        duplicateDomain = true;
      }
      else
      {
        domainNames[i] = domainName;
      }
    }
  });

  return duplicateDomain;
}
function changePaymentMethod(selected)
{
  if (selected == 'bank_transfer') {
    jQuery('#payment_bank_transfer').slideDown('slow');
    jQuery('#payment_debit').slideUp('slow', function(){jQuery('#payment_debit').hide();});
    jQuery('#payment_paypal').slideUp('slow', function(){jQuery('#payment_paypal').hide();});
    jQuery('#payment_ideal').slideUp('slow',  function(){jQuery('#payment_ideal').hide();});
    jQuery('#payment_creditcard').slideUp('slow',  function(){jQuery('#payment_creditcard').hide();});
  } else if (selected == 'debit') {
    jQuery('#payment_debit').slideDown('slow');
    jQuery('#payment_paypal').slideUp('slow', function(){jQuery('#payment_paypal').hide();});
    jQuery('#payment_ideal').slideUp('slow',  function(){jQuery('#payment_ideal').hide();});
    jQuery('#payment_bank_transfer').slideUp('slow',  function(){jQuery('#payment_bank_transfer').hide();});
    jQuery('#payment_creditcard').slideUp('slow',  function(){jQuery('#payment_creditcard').hide();});
  } else if (selected == 'paypal') {
    jQuery('#payment_debit').slideUp('slow',  function(){jQuery('#payment_debit').hide();});
    jQuery('#payment_paypal').slideDown('slow');
    jQuery('#payment_ideal').slideUp('slow',  function(){jQuery('#payment_ideal').hide();});
    jQuery('#payment_bank_transfer').slideUp('slow',  function(){jQuery('#payment_bank_transfer').hide();});
    jQuery('#payment_creditcard').slideUp('slow',  function(){jQuery('#payment_creditcard').hide();});
  } else if (selected == 'ideal') {
    jQuery('#payment_ideal').slideDown('slow');
    jQuery('#payment_debit').slideUp('slow',  function(){jQuery('#payment_debit').hide();});
    jQuery('#payment_paypal').slideUp('slow',  function(){jQuery('#payment_paypal').hide();});
    jQuery('#payment_bank_transfer').slideUp('slow',  function(){jQuery('#payment_bank_transfer').hide();});
    jQuery('#payment_creditcard').slideUp('slow',  function(){jQuery('#payment_creditcard').hide();});
  } else if (selected == 'creditcard') {
    jQuery('#payment_debit').slideUp('slow',  function(){jQuery('#payment_debit').hide();});
    jQuery('#payment_paypal').slideUp('slow',  function(){jQuery('#payment_paypal').hide();});
    jQuery('#payment_ideal').slideUp('slow',  function(){jQuery('#payment_ideal').hide();});
    jQuery('#payment_bank_transfer').slideUp('slow',  function(){jQuery('#payment_bank_transfer').hide();});
    jQuery('#payment_creditcard').slideDown('slow');
  } else {
    jQuery('#payment_debit').slideUp('slow',  function(){jQuery('#payment_debit').hide();});
    jQuery('#payment_paypal').slideUp('slow',  function(){jQuery('#payment_paypal').hide();});
    jQuery('#payment_ideal').slideUp('slow',  function(){jQuery('#payment_ideal').hide();});
    jQuery('#payment_bank_transfer').slideUp('slow',  function(){jQuery('#payment_bank_transfer').hide();});
    jQuery('#payment_creditcard').slideUp('slow',  function(){jQuery('#payment_creditcard').hide();});
  }
}

function hideTooltip(tooltip_id) {
  jQuery("#"+tooltip_id).hide();
}

function hideTooltip2(tooltip_id, input_id) {
  if(jQuery("#"+input_id).val() != "") {
    hideTooltip(tooltip_id);
  }
}

var attachQuantityActions = function () {
  jQuery('input.numberSrv_update').change(function() {
    var data = {
      property: 'quantity',
      value: jQuery('#' + jQuery(this).attr('id')).val(),
      pid: jQuery(this).attr('name')
    }
    updateItem(jQuery('#cart_item_' + data.pid), data);
  });
}

////////////////////////////////////////////////////////////////////////////////
// OGONE Credit card payment
////////////////////////////////////////////////////////////////////////////////

/**
 * name : creditcardFormSubmitClicked()
 * First time the submit button is clicked a call is made to the server
 * to the same url as where this jscript is loaded.
 * Two POST parameter: 'method' with value 'creditcard' and 'no_vat' with value of the no_vat field
 * When succes the response should be formdata AND a form action!
 * The formaction will be set with the returned action
 * The form body filled with the data. 
 * The form is send to Ogone
 */
function creditcardFormSubmitClicked(){

  jQuery.ajax({

    dataType: 'json',
    type: 'post',
    data: {'method': 'creditcard', 'no_vat' : jQuery('#creditCardForm #no_vat').val() },
    cache: false,


    success: function(data){
      jQuery('#creditCardForm').css('display','none');                               // Hide the form
      jQuery('#creditCardForm').attr('action', data['formaction']);                  // Set the action (got form server)
      jQuery('#creditCardForm').html(data['formfields']);                            // Move in the form data
      jQuery('#creditCardForm').submit();                                            // And submit
    },
    error: function(data){
      alert(data.responseText);
    }
      
  });  
}

/* needed for the footer, copied from default.js */
function InsertMailToTag( userName, domainName, text, className)
{
  var EmailId;
  var atSign = "&#64;";
  var fullStop = "&#46";
  EmailId = userName;
  EmailId = "" + EmailId + atSign;
  EmailId = EmailId + domainName;
  if(typeof text == 'undefined' && !text)
  {
    text = EmailId;
  }

  if(typeof className == 'undefined' && !className)
  {
    className = "";
  }

  document.write( "<a class='" + className + "' href='mail" + "to:" + EmailId + "'>" + text
  +"</A>" );
}

