var visitedTabs = [],
    configurator_page = 1,
    currentHardwareSet,
    containerAnimation = [],
    processingConfiguration = false,
    $enabledContainerInputs = [],
    $configurator, $allHwSets, $allArticles, $allFieldsets,
    setupPrice = 0,
    previousBandwidthSelectedId = null,
    FIREWALL_CLASS = 54,
    BANDWIDTH_CLASS = 69,
    UPLINK_PORT_SPEED_CLASS = 43;

$(window).load(function()
{
  $configurator = jQuery('#configurator-form');
  $allFauxServers = $configurator.find('input[id^=faux_server]');
  $allHwSets = $configurator.find('input[id^=hardware_set_]');
  $allArticles = $configurator.find('input[id^=article_]');
  $allFieldsets = $configurator.find('fieldset');
  $allBillingCycles = $configurator.find('input[id^=billing_cycle_]');

  //Normal Dedicated Server
  var datacenterLocationOptions = $configurator.find('input.changeLocation:first').parent();
  datacenterLocationOptions.attr('id', 'subcontainer_Hardware_location');
  //Colocations
  var dcLocationOptions = $configurator.find('input.changeDcLocation:first').parent();

  $('.changeLocation').live('click', function(event){
    changePriceAndCurrency(this, $allFieldsets, datacenterLocationOptions);
  });

  $('.changeDcLocation').live('click', function(event){
    changePriceAndCurrency(this, $allFieldsets, dcLocationOptions);
  });

  // Switch steps
  $configurator.find("div.options a")
    .css('cursor', 'pointer')
    .click(function()
    {
      configurator_page = jQuery(this).attr('rel');
      var containersNumber = jQuery("div[id^=container_]").length;
      var count = 0;
      $configurator.find("div[id^=container_]").hide();
      $configurator.find("div[id^=container_]:eq("+(parseInt(configurator_page - 1)) +")").show();
      $configurator.find("div[id^=container_]:eq("+(parseInt(configurator_page - 1)) +")").find('.suboptions a:first').click();
      $configurator.find('div.options a.selected')
        .removeClass('selected')
        .find('span')
        .show();
      jQuery(this)
        .addClass('selected')
        .addClass('completed')
        .find('span')
        .hide();
      // enable "ADD TO CART" button after all steps are completed
      var completedContainersNumber = $configurator.find("div.options a.completed").length;
      if (completedContainersNumber == containersNumber)
      {
        jQuery('.btn-add-to-cart').parent('div.add-to-cart-box').removeClass('invisible');
      }
      jQuery(document).trigger('CONFIGURATOR_STEPS');
      return false;
  });

  // Prev / Next step buttons
  $configurator.find('a.previous').click(function()
  {
    jQuery(document).scrollTop(1);
    var currentSubStep = $configurator.find("div.suboptions a.selected");
    if (currentSubStep.length > 0)
    {
      if (currentSubStep.prev().length > 0)
      {
        currentSubStep.prev().click();
        return false;
      }
    }
    var currentStep = $configurator.find("div.options a.selected").attr('rel');
    var previousStep = parseInt(currentStep) - 1;
    $configurator.find("div.options a[rel=" + previousStep + "]").click();

    jQuery(document).trigger('CONFIGURATOR_STEPS');
    return false;
  });

  $configurator.find('a.next').click(function()
  {
    jQuery(document).scrollTop(1);
    var currentSubStep = $configurator.find("div.suboptions a.selected");
    if (currentSubStep.length > 0)
    {
      if (currentSubStep.next().length > 0)
      {
        currentSubStep.next().click();
        return false;
      }
    }
    var currentStep = $configurator.find("div.options a.selected").attr('rel');
    var nextStep = parseInt(currentStep) + 1;
    $configurator.find("div.options a[rel=" + nextStep + "]").click();
    jQuery(document).trigger('CONFIGURATOR_STEPS');
    return false;
  });
  jQuery(document).bind('CONFIGURATOR_STEPS', function()
  {
    var containersNumber = $configurator.find("div[id^=container_]").length;
    var currentStepEl = $configurator.find("div.options a.selected");
    var currentStep = currentStepEl.attr('rel');
    if (visitedTabs[currentStep] == undefined){
      visitedTabs[currentStep] = true;
      // track visited steps with Google Analytics
      try
      {
        var label = makeSlug(currentStepEl.text());
        if (label)
        {
          _gaq.push(['_trackPageview', confData.trackingUrl + '/' + label]);
          _gaq.push(['_trackPageLoadTime']);
        }
      }
      catch (e) {}
    }
    var currentContainer = $configurator.find("div[id^=container_]:eq(" + (currentStep - 1)+ ")");
    var currentSubStep = currentContainer.find("div.suboptions a.selected");
    var prevSubStep = currentSubStep.prev().length > 0;
    var nextSubStep = currentSubStep.next().length > 0;
    var prevVisibility = (currentStep > 1 || prevSubStep) ? 'visible' : 'hidden';
    var nextVisibility = (currentStep < containersNumber || nextSubStep) ? 'visible' : 'hidden';
    var addToCartDisplay = (nextVisibility == 'hidden') ? 'block' : 'none';
    var nextDisplay = (nextVisibility == 'hidden') ? 'none' : 'block';
    $configurator.find('a.previous').css('visibility', prevVisibility);
    $configurator.find('a.next').css('visibility', nextVisibility).css('display', nextDisplay);
    $configurator.find('a.btn-add-to-cart').css('display', addToCartDisplay);
    //$configurator.find('a.btn-add-to-cart').parent('div.add-to-cart-box').css('display', addToCartDisplay);

    return false;
  });
  jQuery(document).trigger('CONFIGURATOR_STEPS');
  $configurator.find("div.options a:first").click();

  $allFauxServers.click(function()
  {
    jQuery(document).trigger('CHANGE_FAUX_SERVER', jQuery(this));
  });
  jQuery(document).bind('CHANGE_FAUX_SERVER', function(e, obj)
  {    
    $mainFauxServersLength  = $configurator.find('input[name=faux_server]:visible').length;

    if (jQuery(obj).val() > 0)
    {
      // doesn't have CPU choice
      var hardwareSetId = jQuery(obj).val();
      var container = jQuery(obj).parents('fieldset');
      var checkedCpu = container.find('div.hwset_cpu_choice input:checked');
      if (checkedCpu.attr('id') != jQuery(obj).attr('id'))
      {
        checkedCpu.removeAttr('checked');
      }
      // check parent radio
      jQuery(obj).parent('div.hwset_cpu_choice').prev('br').prev('label').prev('input').attr('checked', 'checked');
      jQuery('#hardware_set_' + hardwareSetId).attr('checked', 'checked').click();
    }
    else
    {
      if ($mainFauxServersLength > 1)
      {
        // "click" on the first available CPU choice
        var cpuDiv = jQuery(obj).next('label').next('br').next('div.hwset_cpu_choice');
        cpuDiv.find('input:first').click();
      }
    }

    // update prices
    $allFauxServers.each(function()
    {
      var hardwareSetId = jQuery(this).val();
      if (hardwareSetId > 0)
      {
        // get hardware sets price
        var hardwareSetLabel = jQuery('#hardware_set_' + hardwareSetId).next('label');
        var hardwareSetPrice = hardwareSetLabel.find('strong').html();
        var hardwareSetSpecial = hardwareSetLabel.find('span.offer').html();
        jQuery(this).next('label').find('strong').html(hardwareSetPrice);
        jQuery(this).next('label').find('span.offer').html(hardwareSetSpecial);
      }
      var hardwareSetIdElement = jQuery(this).attr('id');
      var hasSelectedLocationClass = jQuery(this).hasClass(confData.selected_location.toUpperCase());
      if (false == hasSelectedLocationClass)
      {
        enableOptions(jQuery('#' + hardwareSetIdElement), false);
        showOptions(jQuery('#' + hardwareSetIdElement), false);
      }
      else
      {
        enableOptions(jQuery('#' + hardwareSetIdElement), true);
        showOptions(jQuery('#' + hardwareSetIdElement), true);
      }
    });

    // if selected faux server is not visible - jump back to default
    var $selectedFauxServer = $allFauxServers.filter('input:enabled:checked');
    if ($selectedFauxServer.length == 0)
    {
      var $firstAvailableFaux = $allFauxServers.filter('input:enabled:first');
      $firstAvailableFaux.attr('checked', 'checked').click();
      var $siblingDiv = $firstAvailableFaux.next('label').next('br').next('div.hwset_cpu_choice');
      if ($siblingDiv.length != 0)
      {
        $siblingDiv.find('input:enabled:first').attr('checked', 'checked').click();
      }
    }
    else
    {
      var $siblingDiv = $selectedFauxServer.next('label').next('br').next('div.hwset_cpu_choice');
      if ($siblingDiv.length != 0)
      {
        if ($siblingDiv.find('input:enabled:checked').length == 0)
        {
          $siblingDiv.find('input:enabled:first').attr('checked', 'checked');

        }
      }
    }
    // only if clicked item is a sub item
    if(jQuery(obj).val() == jQuery('input[name=faux_server_sub]:checked').val())
    {
      showOnlyEnabledOS();
    }

    //check articles (cpu & chasis) that belong to hardware set
    if (jQuery(obj).val() > 0 && undefined != confData.items['hardware_set_'+jQuery(obj).val()] && undefined != confData.items['hardware_set_'+jQuery(obj).val()].blacklist)
    {
      var itemBlacklist = confData.items['hardware_set_'+jQuery(obj).val()].blacklist.split(',');
      for (i in itemBlacklist)
      {
        if (jQuery('#article_' + itemBlacklist[i]).length > 0)
        {
          enableOptions(jQuery('#article_' + itemBlacklist[i]), false);
        }
      }
    }
    
    jQuery(document).trigger('HDD_CHANGED');

    // fix to solve problem that wrong OS'es are shown in the OS list.
    var $osContainer = $configurator.find('input.changeOs:first').parent();
    updatePrices($osContainer);
    // hides strangely showing OS'es
    showOnlyEnabledOS();
    // fix end
  });

  $allHwSets.click(function()
  {
    jQuery(document).trigger('CHANGE_HARDWARE_SET', jQuery(this));
  });

  jQuery(document).bind('CHANGE_HARDWARE_SET', function(e, obj)
  {
    var articleClicked = jQuery(obj);
    enableOptions($configurator.find('input'), true);
    // hardware set is being changed
    var obj = jQuery(obj);

    var hardwareSetId = obj.attr('iid');
    var articles = confData.hardware_set_article_data[hardwareSetId];
    var affectedContainers = [];
    var containerIncluded = [];
    currentHardwareSet = hardwareSetId;
    for (articleId in articles)
    {
      var article = articles[articleId];
      var articleEl = jQuery('#article_' + articleId);
      if (articleEl.length == 0)
      {
        continue;
      }
      var container = articleEl.parent();
      if (!affectedContainers[container.attr('id')])
      {
        // disable all options in this container
        affectedContainers[container.attr('id')] = true;
        enableOptions(container.find('input'), false);
      }
      if (article.included)
      {
        // included into hardware set
        containerIncluded[container.attr('id')] = articleId;
        container.data('includedItem', 'article_' + articleId);
      }
      // update the prices for hw set items
      if (article.price)
      {
        confData.items['article_' + articleId].price = article.price;
        //confData.items['article_' + articleId].regular_price = article.regular_price;
        confData.items['article_' + articleId].included = article.included;
      }

      enableOptions(articleEl, true);
    }
    // if any of the containers has checked but disabled options,
    // let's fall back to included one, if there isn't one - to the first enabled option
    for (containerId in affectedContainers)
    {
      var includedArticle = null;
      if (containerIncluded[containerId])
      {
        var includedArticle = jQuery('#article_' + containerIncluded[containerId]);
        var includedId = containerIncluded[containerId];
        includedArticle.parent().find('input[name^=article]').each(function()
        {
          jQuery(this).attr('name', 'article[' + includedId + ']');
        });
      }

      // select
      var $container = jQuery('#' + containerId);
      if ($container.find('input:checked:disabled').length > 0)
      {
        if (containerIncluded[containerId])
        {
          includedArticle.attr('checked', 'checked');
        }
        else
        {
          $container.find('input:enabled:first').attr('checked', 'checked');
        }
        jQuery(document).trigger('FLASH_SUBCONTAINER', $container);
      }
      updatePrices(jQuery('#' + containerId));
    }

    var affectedContainers = [];
    $configurator.find('input:checked').each(function()
    {
      if (jQuery(this).attr('itype') == 'faux_server' || jQuery(this).attr('itype') == 'hardware_set')
      {
        // fix: HWRAID blacklist not updated correctly for several servers.
        // triggering CHANGE_FAUX_SERVER results in infinite loop. therefore only update the blacklists
        if (jQuery(this).val() > 0 && undefined != confData.items['hardware_set_'+jQuery(this).val()] && undefined != confData.items['hardware_set_'+jQuery(this).val()].blacklist)
        {
          var itemBlacklist = confData.items['hardware_set_'+jQuery(this).val()].blacklist.split(',');
          for (i in itemBlacklist)
          {
            if (jQuery('#article_' + itemBlacklist[i]).length > 0)
            {
              enableOptions(jQuery('#article_' + itemBlacklist[i]), false);

              // after disabling, check if it is selected
              if(jQuery('#article_' + itemBlacklist[i]).is(':checked'))
              {
                // if so, select first option from list
                var firstRaid = jQuery('#article_' + itemBlacklist[i]).parent().find('input:first:enabled');
                // Is this enough to mak it unchecked? .click() gives endless loop ofcourse
                firstRaid.attr('checked', 'checked');
              }
            }
          }
        }
        // fix end
      }
      else
      {
        var curentCheckedArticleClassId = jQuery(this).attr('classId');
        var itemBlacklist = confData.items[jQuery(this).attr('id')].blacklist.split(',');
        var article = null;
        for (i in itemBlacklist)
        {
          article = jQuery('input#article_'+itemBlacklist[i]);

          if(UPLINK_PORT_SPEED_CLASS == curentCheckedArticleClassId)
          {
            if(BANDWIDTH_CLASS == article.attr('classId')) continue;
          }

          enableOptions(jQuery('#article_' + itemBlacklist[i]), false);
          var containerId = jQuery(this).parent('fieldset').attr('id');
          affectedContainers[containerId] = true;
        }
      }
    });

    findSelectedHddAndType();
    jQuery(document).trigger('HDD_CHANGED');

    var $container = obj.parent();
    updatePrices($container);
  });

  $allArticles.click(function()
  {
    jQuery(document).trigger('CHANGE_ARTICLE', jQuery(this));
  });


  jQuery(document).bind('CHANGE_ARTICLE', function(e, obj)
  {
    var articleClicked = jQuery(obj);

    // enable ALL items
    enableOptions($allArticles, true);

    // giggle-loop through checked items and blacklist
    var affectedContainers = [];


    //exeption for bandwidth's article (pdb article class is 69). when is clicked then check if selected uplinkport article is not blacklisted with clicked. if yes then change it to not blacklisted one

    $configurator.find('input:checked').each(function()
    {
      if (jQuery(this).attr('itype') == 'hardware_set')
      {
        jQuery(document).trigger('CHANGE_HARDWARE_SET', jQuery(this));
      }
      else if (jQuery(this).attr('itype') == 'faux_server')
      {

      }
      else
      {

        var curentCheckedArticleClassId = jQuery(this).attr('classId');
        var itemBlacklist = confData.items[jQuery(this).attr('id')].blacklist.split(',');
        var article = null;

        for (i in itemBlacklist)
        {
          ///do not greyout articles for blackpairs from classes bandwidth-uplink port. Thorsten's requirement
          article = jQuery('input#article_'+itemBlacklist[i]);

          if(UPLINK_PORT_SPEED_CLASS == curentCheckedArticleClassId)
          {
            if(BANDWIDTH_CLASS == article.attr('classId')) continue;
          }

          if (jQuery(this).attr('itype') != 'unit')
          {
            enableOptions(jQuery('#article_' + itemBlacklist[i]), false);
          }
          var containerId = jQuery(this).parent('fieldset').attr('id');
          affectedContainers[containerId] = true;
        }
      }
    });

    $allFieldsets.each(function()
    {
      updatePrices(jQuery(this));
    });
    showOnlyEnabledOS(3);

    // fix, update faux prices. after selecting some article prices were gone
    updateFauxPrixes();

  });

  $allBillingCycles.click(function()
  {
    updatePrices(jQuery(this));
  });

  // OS Type
  $configurator.find('input.changeOsType').click(function()
  {
    jQuery(document).trigger('CHANGE_OS_TYPE', jQuery(this));
  });


  jQuery(document).bind('CHANGE_OS_TYPE', function(e, obj)
  {
    // show/hide all elements for the given type
    var osType = jQuery(obj).val();
    if (osType == 'type-32_bit')
    {
      showOptions($configurator.find('input.type-32_bit'), true);
      showOptions($configurator.find('input.type-64_bit'), false);
    }
    else
    {
      showOptions($configurator.find('input.type-64_bit'), true);
      showOptions($configurator.find('input.type-32_bit'), false);
    }

    // lookup selected OS
    var c = $configurator.find('input.changeOs:checked').attr('class');
    if (!c)
    {
      var c = '';
    }
    var os = c.match('os_version-[a-zA-Z0-9\-_]+');
    if (os && $configurator.find('input.changeOs.' + os[0] + ':enabled:visible').length > 0)
    {
      // same OS version has been found
      $configurator.find('input.changeOs.' + os[0] + ':enabled:visible:first').attr('checked','checked').click();
    }
    else
    {
      $configurator.find('input.changeOs:enabled:visible:first').attr('checked','checked').click();
    }

    var $osContainer = $configurator.find('input.changeOs:first').parent();
    jQuery(document).trigger('FLASH_SUBCONTAINER', $osContainer);
  });


  // Operating System
  $configurator.find('input.changeOs').click(function()
  {
    jQuery(document).trigger('CHANGE_OS', jQuery(this));
  });
  jQuery(document).bind('CHANGE_OS', function(e, obj)
  {
    if ($configurator.find('input.changeCp').length > 0)
    {
      var os = jQuery(obj).hasClass('os-windows') ? 'os-windows' : 'os-linux';
      $configurator.find('input.changeCp').each(function()
      {
        if (jQuery(this).hasClass(os) || jQuery(this).hasClass('os-null'))
        {
          showOptions(jQuery(this), true);
        }
        else
        {
          showOptions(jQuery(this), false);
        }
      });
      // if selected CP is not visible - jump back to default
      var $cps = $configurator.find('input.changeCp:first').parent('fieldset');
      if ($cps.find('input:checked:visible:enabled').length == 0)
      {
        $cps.find('input:first').click();
        updatePrices($cps);
        jQuery(document).trigger('FLASH_SUBCONTAINER', $cps);
      }
    }
  });

  //traffic type
  $configurator.find('input[name^=traffic_type]').click(function()
  {
    jQuery(document).trigger('CHANGE_TRAFFIC_TYPE', jQuery(this));
  });

  // bandwidth
  $configurator.find('input[name^=bandwidth_type]').click(function()
  {
    jQuery(document).trigger('CHANGE_BANDWIDTH_TYPE', jQuery(this));
  });

  jQuery(document).bind('CHANGE_TRAFFIC_TYPE', function(e, obj)
  {
    var bandwidthSet = jQuery(obj).parent().parent().find('fieldset.bandwidth_options');
    if (bandwidthSet.length != 0)
    {
      var bandwidth_type = jQuery('input[itype=bandwidth_type]:checked').attr('value');
      var traffic_type = jQuery('input[itype=traffic_type]:checked').attr('value');

      if(0 == bandwidthSet.find('input.bandwidth_type-' + bandwidth_type + '.traffic_type-' + traffic_type+ ':enabled').length)
      {
        var obj = jQuery('#' + previousBandwidthSelectedId);
        jQuery(obj).attr('checked', 'checked');
        jQuery(document).trigger('CHANGE_ARTICLE', obj);
        return false;
      }
      else
      {
        bandwidthSet.each(function()
        {
          showOptions(bandwidthSet.find('input'), false);
          showOptions(bandwidthSet.find('input.bandwidth_type-' + bandwidth_type + '.traffic_type-' + traffic_type), true);
          if (bandwidthSet.find('input:visible:enabled').length != 0)
          {
            var bwId = bandwidthSet.find('input:visible:first').attr('id');
            if (bwId)
            {
              jQuery('#' + bwId).attr('checked', 'checked');
              jQuery(document).trigger('CHANGE_ARTICLE', jQuery('#' + bwId));
              jQuery(document).trigger('FLASH_SUBCONTAINER', bandwidthSet);
            }
          }
        });
      }
      jQuery(document).trigger('BANDWIDTH_CHANGED');
    }
  });

  $configurator.find('.bandwidth_options input').click(function()
  {
    jQuery(document).trigger('BANDWIDTH_CHANGED');
  });


  jQuery(document).bind('CHANGE_BANDWIDTH_TYPE', function(e, obj)
  {
    var $inputButtonObject = jQuery(obj);
    var $parentDiv = $inputButtonObject.parent().parent();
    var traffic_type = jQuery('input[itype=traffic_type]:checked').attr('value');
    var bandwidth_type = jQuery('input[itype=bandwidth_type]:checked').attr('value');

    var bandwidthSet = jQuery(obj).parent().parent().find('fieldset.bandwidth_options');
    showOptions(bandwidthSet.find('input'), false);
    showOptions(bandwidthSet.find('input.bandwidth_type-' + bandwidth_type + '.traffic_type-' + traffic_type), true);

    // if selected bandwidth type is not visible - jump back to first one
    if(0 == bandwidthSet.find('input.bandwidth_type-' + bandwidth_type + '.traffic_type-' + traffic_type+ ':enabled').length)
    {
      var obj = jQuery('#' + previousBandwidthSelectedId);
      jQuery(obj).attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_ARTICLE', obj);
      return false;
    }
    else if (bandwidthSet.find('input:visible').length != 0)
    {
      var type = jQuery(obj).val().replace(' ', '_');
      // get currently selected element
      // not nice.. i know ;)
      var bwId = bandwidthSet.find('input:checked').next('label').attr('id');
      if (!bwId)
      {
        bwId = '';
      }
      if (type == 'Standard')
      {
        bwId = bwId.replace('Volume', 'Standard');
      }
      else if (type == 'Ultra Green')
      {
        bwId = bwId.replace('Ultra Green', 'Ultra Green');
      }
      else
      {
        bwId = bwId.replace('Standard', 'Volume');
      }

      var obj = jQuery('#' + bwId+':visible');
      if (1 == obj.length)
      {
        obj.prev('input').attr('checked', 'checked');
        jQuery(document).trigger('CHANGE_ARTICLE', obj.prev('input'));
      }
      else
      {
        bwId  = bandwidthSet.find('input:visible:first').attr('id');
        jQuery('#' + bwId).attr('checked', 'checked');
        jQuery(document).trigger('CHANGE_ARTICLE',  jQuery('#' + bwId));
      }
      updatePrices(bandwidthSet);
    }
    
    if($parentDiv.is(':visible') && $inputButtonObject.is(':visible') || !$parentDiv.is(':visible')) 
    {
      jQuery(document).trigger('BANDWIDTH_CHANGED');
      jQuery(document).trigger('FLASH_SUBCONTAINER', bandwidthSet);
    }
  });

  // HDD Type
  $configurator.find('input.changeHddType').click(function()
  {
    jQuery(document).trigger('CHANGE_HDD_TYPE', jQuery(this));
  });
  jQuery(document).bind('CHANGE_HDD_TYPE', function(e, obj)
  {
    var osType = jQuery(obj).val();
    if (osType == 'type-sas')
    {
      showOptions($configurator.find('input.type-sas'), true);
      showOptions($configurator.find('input.type-sata2'), false);
      showOptions($configurator.find('input.type-scsi'), false);
      showOptions($configurator.find('input.type-ssd'), false);
    }
    else if (osType == 'type-sata2')
    {
      showOptions($configurator.find('input.type-sas'), false);
      showOptions($configurator.find('input.type-sata2'), true);
      showOptions($configurator.find('input.type-scsi'), false);
      showOptions($configurator.find('input.type-ssd'), false);
    }
    else if (osType == 'type-scsi')
    {
      showOptions($configurator.find('input.type-sas'), false);
      showOptions($configurator.find('input.type-sata2'), false);
      showOptions($configurator.find('input.type-scsi'), true);
      showOptions($configurator.find('input.type-ssd'), false);
    }
    else if (osType == 'type-ssd')
    {
      showOptions($configurator.find('input.type-sas'), false);
      showOptions($configurator.find('input.type-sata2'), false);
      showOptions($configurator.find('input.type-scsi'), false);
      showOptions($configurator.find('input.type-ssd'), true);
    }

    var $hddContainer = $configurator.find('input.changeHdd:first').parent();
    if ($hddContainer.find('input:checked:visible:enabled').length == 0)
    {
      $hddContainer.find('input:visible:enabled:first').click();
      updatePrices($hddContainer);
      jQuery(document).trigger('FLASH_SUBCONTAINER', $hddContainer);
    }
    jQuery(document).trigger('HDD_CHANGED');
  });

  $configurator.find('input.changeHdd').click(function()
  {
    jQuery(document).trigger('HDD_CHANGED');
  });

  jQuery(document).bind('HDD_CHANGED', function()
  {
    $configurator.find('input.changeHddType').each(function()
    {
      var type = jQuery(this).val();
      if ($configurator.find('input.changeHdd.' + type + ':enabled').length == 0)
      {
        enableOptions(jQuery(this), false);
      }
      else
      {
        enableOptions(jQuery(this), true);
      }
    });
    if ($configurator.find('input.changeHddType:checked').is(':disabled'))
    {
      $configurator.find('input.changeHddType:enabled:first').attr('checked', 'checked').click();
    }
  });
  jQuery(document).trigger('HDD_CHANGED');
  if ($configurator.find('input.changeHddType').length < 2)
  {
    $configurator.find('input.changeHddType:first').parent().hide();
  }

    // Datacenter  Location
  $configurator.find('input.changeDcLocation').click(function()
  {
    jQuery(document).trigger('CHANGE_DC_LOCATION', jQuery(this));
  });
  jQuery(document).bind('CHANGE_DC_LOCATION', function(e, obj)
  {
    var dcLocation = jQuery(obj).val();
    if (dcLocation == 'location-nl')
    {
      showOptions($configurator.find('input.location-nl'), true);
      showOptions($configurator.find('input.location-de'), false);
      showOptions($configurator.find('input.location-us'), false);
      showOptions($configurator.find('input.location-be'), false);
    }
    else if (dcLocation == 'location-de')
    {
      showOptions($configurator.find('input.location-nl'), false);
      showOptions($configurator.find('input.location-de'), true);
      showOptions($configurator.find('input.location-us'), false);
      showOptions($configurator.find('input.location-be'), false);
    }
    else if (dcLocation == 'location-us')
    {
      showOptions($configurator.find('input.location-nl'), false);
      showOptions($configurator.find('input.location-de'), false);
      showOptions($configurator.find('input.location-us'), true);
      showOptions($configurator.find('input.location-be'), false);
    }
    else if (dcLocation == 'location-be')
    {
      showOptions($configurator.find('input.location-nl'), false);
      showOptions($configurator.find('input.location-de'), false);
      showOptions($configurator.find('input.location-us'), false);
      showOptions($configurator.find('input.location-be'), true);
    }

    //if there is only one visible datacenter option, hide the checkbox
    if ($configurator.find('input.changeDc:visible').length < 2)
    {
      $configurator.find('input.changeDc:visible:first').hide();
    }
    var $dcContainer = $configurator.find('input.changeDc:first').parent();
    if ($dcContainer.find('input:checked:visible:enabled').length == 0)
    {
      $dcContainer.find('input:visible:enabled:first').click();
      updatePrices($dcContainer);
      jQuery(document).trigger('FLASH_SUBCONTAINER', $dcContainer);
    }
    jQuery(document).trigger('DC_CHANGED');
  });

  $configurator.find('input.changeDc').click(function()
  {
    jQuery(document).trigger('DC_CHANGED');
  });

  jQuery(document).bind('DC_CHANGED', function()
  {
    $configurator.find('input.changeDcLocation').each(function()
    {
      var type = jQuery(this).val();
      if ($configurator.find('input.changeDc.' + type + ':enabled').length == 0)
      {
        enableOptions(jQuery(this), false);
      }
      else
      {
        enableOptions(jQuery(this), true);
      }
    });
    if ($configurator.find('input.changeDcLocation:checked').is(':disabled'))
    {
      $configurator.find('input.changeDcLocation:enabled:first').attr('checked', 'checked').click();
    }
  });
  jQuery(document).trigger('DC_CHANGED');

  // Network types
  jQuery(document).bind('BANDWIDTH_CHANGED', function()
  {
    if ($configurator.find('input[itype=bandwidth_type]:disabled:checked').length > 0)
    {
      var el = $configurator.find('input[itype=bandwidth_type]:enabled:visible:first');
      jQuery(el).attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_ARTICLE', el);
    }

    $configurator.find('input[itype=traffic_type]:disabled').removeAttr('disabled');
    $configurator.find('input[itype=traffic_type]:enabled').each(function()
    {
      var curTrafficType = jQuery(this).val();
      var curBandwidthType = $configurator.find('input[itype=bandwidth_type]:checked').val();
      if ($configurator.find('.bandwidth_options input.traffic_type-' + curTrafficType + '.bandwidth_type-' + curBandwidthType).length == 0)
      {
        jQuery(this).attr('disabled', 'disabled');
      }
    });

    if ($configurator.find('input[itype=traffic_type]:disabled:checked').length > 0)
    {
      var el = $configurator.find('input[itype=traffic_type]:enabled:visible:first');
      jQuery(el).attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_ARTICLE', el);
    }
    if ($configurator.find('.bandwidth_options input:disabled:checked').length > 0)
    {
      var el = $configurator.find('.bandwidth_options input:enabled:visible:first');
      jQuery(el).attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_ARTICLE', el);
    }
    if ($configurator.find('.uplinkport_options input:disabled:checked').length > 0)
    {
      var el = $configurator.find('.uplinkport_options input:enabled:visible:first');
      jQuery(el).attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_ARTICLE', el);
      jQuery(document).trigger('FLASH_SUBCONTAINER', el.parent());
    }

    $configurator.find('input[itype=bandwidth_type]:disabled').removeAttr('disabled');
    $configurator.find('input[itype=bandwidth_type]:enabled').each(function()
    {
      var curBandwidthType = jQuery(this).val();
      var curTrafficType = $configurator.find('input[itype=traffic_type]:checked').val();
      if ($configurator.find('.bandwidth_options input.traffic_type-' + curTrafficType + '.bandwidth_type-' + curBandwidthType).length == 0)
      {
        jQuery(this).attr('disabled', 'disabled');
      }
    });

    hideNetworkType();

    //if "none" option exists , always must be visable
    var bandwidthNone = $configurator.find('fieldset.bandwidth_options input[id*="_null"]');
    if (1 == bandwidthNone.length)
    {
      showOptions(bandwidthNone, true);
    }
  });

  $configurator.find('input.selected').attr('checked', 'checked');

  // find selected OS type
  var selectedOs = $configurator.find('input.changeOs:checked');
  var selectedOsType = selectedOs.hasClass('type-32_bit') ? 'type-32_bit' : 'type-64_bit';
  var obj = jQuery('#dummy_' + selectedOsType);
  obj.attr('checked', 'checked');
  jQuery(document).trigger('CHANGE_OS_TYPE', obj);
  selectedOs.attr('checked', 'checked');
  jQuery(document).trigger('CHANGE_OS', selectedOs);

  // find selected bandwidth type
  var selectedBwType = $configurator.find('fieldset.bandwidth_options input:checked').hasClass('bandwidth_type-Standard') ? 'Standard' : 'Volume';
  var obj = jQuery('#bandwidth_type_' + selectedBwType);
  obj.attr('checked', 'checked');

  jQuery(document).trigger('CHANGE_BANDWIDTH_TYPE', obj);

  $configurator.find('input.changeCp.selected').attr('checked', 'checked');

  findSelectedHddAndType();

  // find selected DC Location and display
  var selectedLocation = confData.selected_location.toLowerCase();
  var selectedDc = $configurator.find('input.changeDc:checked');
  var obj = $configurator.find('input[value=location-'+selectedLocation+']');
  obj.attr('checked', 'checked');
  jQuery(document).trigger('CHANGE_DC_LOCATION', obj);

  // first pass - update prices
  $configurator.find('input[id^=hardware_set]:checked:first, span.fixed[id^=hardware_set], input[id^=article]:checked:first, span.fixed[id^=article], input.changeCp.selected').each(function()
  {
    if (jQuery(this).attr('id').match(/hardware_set/))
    {
      jQuery(document).trigger('CHANGE_HARDWARE_SET', jQuery(this));
    }
    else
    {
      jQuery(document).trigger('CHANGE_ARTICLE', jQuery(this));
    }
  });

  // select correct faux server
  var selectedHardwareSetId = jQuery('input[id^=hardware_set]:enabled:checked:first').val();
  $allFauxServers.each(function()
  {
    if (jQuery(this).val() == selectedHardwareSetId)
    {
      jQuery(this).attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_FAUX_SERVER', jQuery(this));
    }
  });

  var $locations = $configurator.find('input.changeLocation:first').parent('fieldset');
  if ($locations.find('input:checked:disabled').length > 0 || $locations.find('input:checked:enabled').length == 0)
  {
    $locations.find('input:enabled:first').attr('checked', 'checked');
  }

  // flash affected containers
  jQuery(document).bind('FLASH_SUBCONTAINER', function(e, container)
  {
    var containerId = jQuery(container).attr('id');
    clearTimeout(containerAnimation[containerId]);
    containerAnimation[containerId] = setTimeout(function()
    {
      jQuery(container).animate({backgroundColor: "#FFCC66", queue: false}, 50).animate({backgroundColor: "#ffffff", queue: false}, 500);
    }, 100);
  });

  // init add to cart button
  var pid = $('#pid').val();
  var $addToCartBtn = jQuery('.btn-add-to-cart');
  if (pid && pid != '')
  {
    $addToCartBtn.parent('div.add-to-cart-box').removeClass('invisible');
  }
  else
  {
    $addToCartBtn.parent('div.add-to-cart-box').addClass('invisible');
  }

  $addToCartBtn.click(function()
  {
    if (processingConfiguration)
    {
      return false;
    }
    processingConfiguration = true;
    setTimeout(function(){processingConfiguration = false;}, 1000);
    // make sure that all steps are completed
    if (jQuery(this).parent('div.add-to-cart-box').hasClass('invisible'))
    {
      var incomplete = new Array();
      jQuery("div.options a:not(.completed)").each(function(){
        incomplete[incomplete.length] = '<a href="#" onclick="jQuery.facebox.close();jQuery(\'div.options a[rel=' + jQuery(this).attr('rel') + ']\').click(); return false">'
          + jQuery(this).text() + '</a>';
      });
      jQuery('#complete-all-steps-list').html(incomplete.join(', '));
      jQuery.facebox(jQuery('#complete-all-steps').html());
      return false;
    }
    else
    {
      try
      {
        // track "add to cart" using Google Analytics
        _gaq.push(['_trackPageview', confData.trackingUrl + '/addtocart']);
        _gaq.push(['_trackPageLoadTime']);
      }
      catch (e) {}
      jQuery('#configurator-form').submit();
      return false;
    }
  });

  $configurator.find('input[name^=traffic_type]:checked').click();


  //If there is only 1 datacenter location, hide the checkbox
  if ($configurator.find('input.changeDcLocation').length < 2)
  {
    var dcLocation = $configurator.find('input.changeDcLocation:first');
    if (jQuery(dcLocation).next('label').hasClass('disabled'))
    {
      jQuery(dcLocation).next('label').removeClass('disabled');
    }
    jQuery(dcLocation).hide();
  }
  //if there is only one visible datacenter option, hide the checkbox
  if ($configurator.find('input.changeDc:visible').length < 2)
  {
    $configurator.find('input.changeDc:visible:first').hide();
  }
  //if there is only one visible conract term option, hide the checkbox
  if ($configurator.find('input[id^="contract_term"]').length < 2)
  {
    $configurator.find('input[id^="contract_term"]:first').hide();
  }

  hideNetworkType()
});

jQuery(document).ready(function($){
  jQuery('.btn-add-to-cart').click(function(){
    jQuery('.btn-add-to-cart').hide();
  });
});

function updatePrices(container)
{
  // get included article
  var includedArticlePrice = 0;
  var includedArticleId = 0;
  if (container.data('includedItem'))
  {
    includedArticlePrice = confData.items[container.data('includedItem')].price;
    includedArticleId = jQuery('#' + container.data('includedItem')).val();
  }
  else
  {
    var inc = container.find('.included');
    if (inc.length > 0)
    {
      if (confData.items[inc.attr('id')])
      {
        includedArticlePrice = confData.items[inc.attr('id')].regular_price;
      }
      includedArticleId = inc.val();
    }
  }

  // find selected container element
  var selectedPrice = 0;
  var selected = container.find('input:checked');
  var customBuiltHwSet = false;
  if (selected.length > 0)
  {
    var selectedId = selected.attr('id');

    if (confData.is_custom_built && selected.attr('id').match(/hardware_set/))
    {
      customBuiltHwSet = true;
    }

    if (customBuiltHwSet)
    {
      selectedPrice = confData.items[selectedId].regular_price;
    }
    else if (confData.items[selectedId] && confData.items[selectedId].regular_price && parseFloat(confData.items[selectedId].price) != parseFloat(confData.items[selectedId].regular_price))
    {
      // special
      selectedPrice = confData.items[selectedId].price;
    }
    else if (confData.items[selectedId])
    {
      selectedPrice = confData.items[selectedId].price - includedArticlePrice;
    }
  }

  container.find('input:enabled').each(function()
  {
    var price = 0;
    var special = false;

    var inputId = jQuery(this).attr('id');

    if (confData.items[inputId])
    {
      var itemPrice = confData.items[inputId].price;
      var itemRegularPrice = confData.items[inputId].regular_price;
      var itemIncluded = confData.items[inputId].included;
    }
    else
    {
      var itemPrice = 0;
      var itemRegularPrice = 0;
      var itemIncluded = false;
    }

    if (confData.is_custom_built && selected.length && selectedId.match(/hardware_set/))
    {
      var diff_price = itemRegularPrice - selectedPrice;
      price = parseFloat(itemRegularPrice);
    }
    else if (itemIncluded == 0 && itemRegularPrice && parseFloat(itemRegularPrice) != parseFloat(itemPrice))
    {
      // special
      if (jQuery(this).attr('type') == 'checkbox')
      {
        var diff_price = itemPrice;
        price = parseFloat(itemPrice);
      }
      else
      {
        var diff_price = itemPrice - selectedPrice;
        price = parseFloat(itemPrice);
        special = true;
      }
    }
    else
    {
      if (jQuery(this).attr('type') == 'checkbox')
      {
        var diff_price = itemPrice;
        price = parseFloat(itemPrice);
      }
      else
      {
        var diff_price = (itemRegularPrice - includedArticlePrice) - selectedPrice;
        price = parseFloat(itemRegularPrice - includedArticlePrice);
      }
    }

    if ('article_' + includedArticleId == inputId)
    {
      price = 0;
      diff_price = price - selectedPrice;
    }

    jQuery(this).data('price', price);

    if (diff_price != 0)
    {
      if (diff_price > 0)
      {
        var sign = '+';
      }
      else
      {
        var sign = '-';
      }

      if (special)
      {
        jQuery(this).next('label')
          .find('span.offer').html('(' + sign + ' <span class="currencySymbol">' + currencySign + '</span> ' + formatCurrency(Math.abs(diff_price).toFixed(2), confData.selected_location) + ') ').end()
          .find('strong').addClass('old_price').html('(' + sign + ' <span class="currencySymbol">' + currencySign + '</span> ' + formatCurrency(Math.abs(itemRegularPrice).toFixed(2), confData.selected_location) + ')').end()
      }
      else
      {
        jQuery(this).next('label').find('strong').html('(' + sign + ' <span class="currencySymbol">' + currencySign + '</span> ' + formatCurrency(Math.abs(diff_price).toFixed(2), confData.selected_location) + ')');
      }
    }
    else
    {
      jQuery(this).next('label')
        .find('strong').text('').end()
        .find('span.offer').text('');
    }
  });

  updateTotal();
}

var updateTotalTimeout;
function updateTotal()
{
  clearInterval(updateTotalTimeout);
  updateTotalTimeout = setTimeout(function()
  {
    // updates selection table
    var selectionTable = jQuery('table.order'); // tr.gutter').eq(1)
    var selectionTablePlaceholder = selectionTable.find('tr.gutter').eq(1);
    selectionTable.find('tr.selection').remove();
    var selectedItems = $configurator.find('input:checked, span.fixed');
    var totalSetupPrice = parseFloat(confData.setup_price);
    var billingCycle = false;
    var comboContractTerm = confData.contract_term;
    var contractTerm = $configurator.find('input[id^="contract_term"]');

    selectedItems.each(function()
    {
      var selectedId = jQuery(this).attr('id');
      var isHardwareSet = selectedId.match(/hardware_set/);
      var inHardwareSet = confData.items[selectedId] && confData.items[selectedId].in_hardware_set ? true : false;
      var price = jQuery(this).data('price');
      var notIncluded = confData.items[selectedId] && confData.items[selectedId].included != '' && confData.items[jQuery(this).attr('id')].included != '0' ? false : true;
      var notNull = selectedId.match(/_null/) == '_null' ? false : true;
      var notType = selectedId.match(/_type/) == '_type' ? false : true;
      var notFauxServer = selectedId.match(/faux_server_/) == 'faux_server_' ? false : true;
      var isLocationSelector = selectedId.match(/dummy_location/) == 'dummy_location' ? true : false;
      var isContractTerm = selectedId.match(/contract_term/) == 'contract_term' ? true : false;

      var showAsZeroPriced = false
      if (price == 0 && notIncluded && notNull && notType && notFauxServer)
      {
        var showAsZeroPriced = true;
      }
      // if the price is larger than 0 or the item is contained inside
      // hardware set (CPU, HDD, RAM) - display it in sidebar
      if  ('billing_cycle' == jQuery(this).attr('itype'))
      {
        billingCycle = jQuery(this);
        return;
      }
      //the country selector is not displayed in the sidebar

      if ((price || isHardwareSet || inHardwareSet || showAsZeroPriced) && (!isLocationSelector && !isContractTerm))
      {
        if (jQuery(this).hasClass('fixed'))
        {
          var label = jQuery(this);
        }
        else
        {
          var label = jQuery(this).next('label');
        }
        var name_el = label.clone();
        name_el.find('strong').remove();
        name_el.find('span.special').remove();
        var text = name_el.text();
        if (jQuery.trim(text).length <= 4)
        {
          text = jQuery(this).parents('fieldset').find('span.legend').text() + ': ' +  text;
        }

        if(true == inHardwareSet)
        {
          var articleClassName = jQuery(this).parents('fieldset').find('span.legend').text();
          if('CPU' ==  articleClassName)
          {
            selectionTablePlaceholder.before('<tr class="top selection"><td class="orderlabel"  style="padding-left: 8px;padding-top:0px">'+text+'</td>' +   '<td></td><td class="price selectionPrice">'+(price || showAsZeroPriced ? formatCurrency(price.toFixed(2), confData.selected_location):'')+'</td></tr>');
          }
          else
          {
            selectionTablePlaceholder.before('<tr class="top selection"><td class="orderlabel">'+text+'</td>' +   '<td><span class="currencySymbol">' + currencySign + '</span></td><td class="price selectionPrice">'+(price || showAsZeroPriced ? formatCurrency(price.toFixed(2), confData.selected_location) : 'incl.')+'</td></tr>');
          }
        }
        else
        {
          selectionTablePlaceholder.before('<tr class="top selection"><td class="orderlabel">'+text+'</td>' +   '<td><span class="currencySymbol">' + currencySign + '</span></td><td class="price selectionPrice">'+(price || showAsZeroPriced ? formatCurrency(price.toFixed(2), confData.selected_location) : 'incl.')+'</td></tr>');
        }
      }

      // setup price
      if (confData.items[selectedId] && confData.items[selectedId].setup_price)
      {
        totalSetupPrice += parseFloat(confData.items[selectedId].setup_price);
      }
    });


    var selection = jQuery('table.order td.selectionPrice');
    var totalPrice = 0;
    selection.each(function()
    {
      if ('US' ==  confData.selected_location)
      {
        var price = parseFloat(jQuery(this).text().replace(',', ''));
      }
      else
      {
        var price = parseFloat(jQuery(this).text().replace('.', '').replace(',', '.'));
      }

      if (price)
      {
        totalPrice += price;
      }
    });

    billingCycleText = confData.items[billingCycle.attr('id')].billing_cycle_months;
    if (parseInt(comboContractTerm) > parseInt(billingCycleText))
    {
      var contractTermText = comboContractTerm;
    }
    else
    {
      var contractTermText = billingCycleText;
      var contractTerm = billingCycle;
    }
    var discount = confData.items[billingCycle.attr('id')].billing_cycle_percentage;
    var discount_show = '';
    if ('undefined' != discount && discount != 100)
    {
      if (discount < 100)
      {
        discount_show =  ' (-' + (100 - discount) + '%)';
      }
      else
      {
        discount_show =  ' (+' + (discount -  100) + '%)';
      }
    }
    billingCycleText = billingCycleText + ' '+ confData.items[billingCycle.attr('id')].month_i18n;
    contractTermText = contractTermText + ' '+ confData.items[contractTerm.attr('id')].month_i18n;
    var billingCycleName = billingCycle.parents('fieldset').find('span.legend').text();
    jQuery('table.order td.billing_term_td').text(billingCycleName+discount_show);
    jQuery('table.order td.selectionBillingCycle').text(billingCycleText);
    jQuery('table.order td.selectionContractTerm').text(contractTermText);
    jQuery('label[for^="contract_term"]:first').text(contractTermText);
    priceMy = (totalPrice.toFixed(2) * confData.items[billingCycle.attr('id')].billing_cycle_percentage) / 100;
    jQuery('table.order td.selectionFinalPrice').text(formatCurrency(priceMy, confData.selected_location));
    jQuery('table.order td.selectionSetupPrice').text(formatCurrency(totalSetupPrice.toFixed(2), confData.selected_location));


  }, 200);

}

function enableOptions (element, enable)
{
  if (enable)
  {
    jQuery(element).removeAttr('disabled').next('label').removeClass('disabled');
  }
  else
  {
    jQuery(element).attr('disabled', 'disabled').next('label').addClass('disabled').find('strong').text('');
  }
}

function showOptions (element, show)
{
  if (show)
  {
    jQuery(element).show().next('label').show().next('br').show();
  }
  else
  {
    jQuery(element).hide().next('label').hide().next('br').hide();
  }
}

function formatCurrency(num, location)
{
  if ('US' == location)
  {
    digitSeparator = ',';
    decimalMark = '.'
  }
  else
  {
    digitSeparator = '.';
    decimalMark = ','
  }
  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))+ digitSeparator +
  num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + num + decimalMark + cents);
}

function dotCurrency(num)
{
  var price = num.replace(/\./g,'');
  return price.toString().replace(/\$|\,/g,'.');
}

function isAnyUplinkPortAvailable()
{
  return jQuery('input[classId=43]:visible:enabled').length;
}

function showOnlyEnabledOS()
{
    var clickedOSVisable = true;
    var osType = $configurator.find('input.changeOsType:checked').val();
    var clickedOS = jQuery('input.'+osType+':checked');
    var os = jQuery('input.'+osType);
    os.each(function()
    {
      if(true == jQuery(this).attr('disabled'))
      {
        if(clickedOS.attr('id') == jQuery(this).attr('id'))
        {
          clickedOSVisable = false;
        }
        jQuery(this).hide().next('label').hide().next('br').hide();
      }
      else
      {
        jQuery(this).show().next('label').show().next('br').show();
      }
    });

    if(true == clickedOS.attr('disabled'))
    {
      var osToSelect = jQuery('input[classId=42]:enabled:first');
      osToSelect.attr('checked', 'checked');
      jQuery(document).trigger('CHANGE_ARTICLE', osToSelect);
      updatePrices($container);
    }
}

function findSelectedHddAndType()
{
  // find selected HDD type
  var selectedHdd = $configurator.find('input.changeHdd:checked');
  var selectedHddType = '';
  if(selectedHdd.hasClass('type-sas'))
  {
    selectedHddType = 'type-sas';
  }
  else if(selectedHdd.hasClass('type-sata2'))
  {
    selectedHddType = 'type-sata2';
  }
  else if(selectedHdd.hasClass('type-scsi'))
  {
    selectedHddType = 'type-scsi';
  }
  else if(selectedHdd.hasClass('type-ssd'))
  {
    selectedHddType = 'type-ssd';
  }
  var obj = jQuery('#dummy_' + selectedHddType);
  obj.attr('checked', 'checked');
  jQuery(document).trigger('CHANGE_HDD_TYPE', obj);
  selectedHdd.attr('checked', 'checked');
}

// updates the prices next to the faux checkboxes
function updateFauxPrixes()
{
  $allFauxServers.each(function()
  {
    var hardwareSetId = jQuery(this).val();
    if (hardwareSetId > 0)
    {
      // get hardware sets price
      var hardwareSetLabel = jQuery('#hardware_set_' + hardwareSetId).next('label');
      var hardwareSetPrice = hardwareSetLabel.find('strong').html();
      var hardwareSetSpecial = hardwareSetLabel.find('span.offer').html();
      jQuery(this).next('label').find('strong').html(hardwareSetPrice);
      jQuery(this).next('label').find('span.offer').html(hardwareSetSpecial);
    }
  });
}

function hideNetworkType()
{
    if ($configurator.find('input[name^=traffic_type]').length == 1)
    {
      $configurator.find('input[name^=traffic_type]').parent().hide();
    }
}

function changePriceAndCurrency(configuratorElement, $allFieldsets, datacenterLocationOptions)
{
  var $configuratorElement = $(configuratorElement);
  $configuratorElement.siblings('input[type="checkbox"]').attr('checked',false);
  if ($configuratorElement.attr('checked') && $configuratorElement.is(":visible"))
  {
    $configuratorElement.siblings('input[type="checkbox"]').attr('checked','');
    var selected = $configuratorElement.val();
    var selectedLocation = selected.match('location-([a-zA-Z]{2})+');
    var urlForAjaxCall = '/'+confData.culture+'/rest/getConfiguratorData?id='+confData.combo_id+'&selectedLocation='+ selectedLocation[1] +'&culture='+confData.culture;
    if (confData.is_custom_built)
    {
      urlForAjaxCall = urlForAjaxCall + '&customBuilt=1'
    }
    jQuery.ajax(
    {
      url: urlForAjaxCall,
      cache: false,
      type: 'GET',
      beforeSend: function(){
        var html = '<img id="spinningCircle" src="/images/ajax-loader.gif">';
        var $spinningCircle = $('#spinningCircle');
        if ($spinningCircle.length <= 0)
        {
          datacenterLocationOptions.append(html);
        }
      },
      success: function (resp)
      {
        var dataSet = jQuery.parseJSON(resp);
        $('#spinningCircle').remove();

        for (index in dataSet.components)
        {
          for (articleClass in dataSet.components[index])
          {
            var articleClassName = articleClass;
            articleClassName = articleClassName.replace(/\s+$/ig,'').toLowerCase();
            articleClassName = articleClassName.replace(/^\s+/ig,'');
            articleClassName = articleClassName.replace(/ /ig, '_');
            for (articleId in dataSet.components[index][articleClass])
            {
              var variablePrefix = dataSet.components[index][articleClass][articleId].type + '_';
              if (confData.items[variablePrefix + articleId] != undefined)
              {
                if (dataSet.components[index][articleClass][articleId].prices != undefined)
                {
                  confData.items[variablePrefix + articleId].regular_price = dataSet.components[index][articleClass][articleId].prices.regular;
                  confData.items[variablePrefix + articleId].setup_price = dataSet.components[index][articleClass][articleId].prices.setup;
                  confData.items[variablePrefix + articleId].price = dataSet.components[index][articleClass][articleId].prices.base;
                }
                var currencySymbol = dataSet.comboCurrency[selectedLocation[1].toUpperCase()];
                $('.currencySymbol').replaceWith('<span class="currencySymbol">' + currencySymbol + '</span>');
              }
              if (dataSet.components[index][articleClass][articleId].upgradeables != null)
              {
                for (upgradeable in dataSet.components[index][articleClass][articleId].upgradeables)
                {
                  var upgradeableId = dataSet.components[index][articleClass][articleId].upgradeables[upgradeable]['id'];
                  if (confData.items[variablePrefix + upgradeableId] != undefined)
                  {
                    if (dataSet.components[index][articleClass][articleId].upgradeables[upgradeable].prices != undefined)
                    {
                      confData.items[variablePrefix + upgradeableId].regular_price = dataSet.components[index][articleClass][articleId].upgradeables[upgradeable].prices.regular;
                      confData.items[variablePrefix + upgradeableId].setup_price = dataSet.components[index][articleClass][articleId].upgradeables[upgradeable].prices.setup;
                      confData.items[variablePrefix + upgradeableId].price = dataSet.components[index][articleClass][articleId].upgradeables[upgradeable].prices.base;
                    }
                  }
                }
              }
            }
            confData.selected_location = selectedLocation[1].toUpperCase();
            currencySign = dataSet.comboCurrency[selectedLocation[1].toUpperCase()];
          }
        }
        $allFieldsets.each(function(index, Element)
        {
          updatePrices(jQuery(Element));
        });
        $('#basePrice').text(formatCurrency(dataSet.comboPrice, selectedLocation[1].toUpperCase()));
        updateTotal();
        jQuery(document).trigger('CHANGE_FAUX_SERVER', $(configuratorElement));
      }
    });
  }
}
