/**
 * Initialize project behaviors
 */

(function($){
  $(document).ready(function() {
    
    /* Prepare configuration */
    if(typeof project === 'undefined'){
      throw new Error('project object not defined');
    }
    if(typeof project.config === 'undefined'){
      throw new Error('project config object not defined');
    }
    if(typeof userConfig === 'object'){
      project.config = $.extend(project.config, userConfig);
    }
    
    // get page language
    project.language = $('html').attr('lang');
    
    /* Common events */
    project.loadCommon();
    
    /* Initializations */
    project.initialize();
    
  });
    
})(jQuery);



/**
 * Define project local methods
 */

var project = {

  // Set project configuration
  config: {
    fancybox: {zoomSpeedOut: 0}
  },

  // page language
  defaultLanguage: 'fr',
  language: null,

  translations: {
    "confirm-change-quote":
      {
        'fr': "Vous êtes sur le point de changer de devis, cela annulera le devis en cours s'il n'a pas été enregistré.\nSouhaitez-vous continuer ?",
        'en': "You are about to change your quote, this will cancel the current quote if it has not been saved.\nDo you want to continue?"
      },
    "confirm-cancel-quote":
      {
        'fr': "Vous êtes sur le point d'annuler un devis, ce qui le rendra inaccessible pour des utilisations futures.\nSouhaitez-vous continuer ?",
        'en': "You are about to cancel your quote, which means it will not be available for future use.\nDo you want to continue?"
      },
    "confirm-duplicate-quote":
      {
        'fr': "Etes-vous certain(e) de vouloir dupliquer ce devis ?",
        'en': "Are you sure you want to duplicate this quote?"
      },
    "confirm-create-new-quote":
      {
        'fr': "Vous êtes sur le point de créer un nouveau devis, cela annulera les modifications sur devis en cours s'il n'a pas été enregistré.\nSouhaitez-vous continuer ?",
        'en': "You are about to create a new quote, this will cancel the current modifications if it has not been saved.\nDo you want to continue ?"
      },
    "items-found-use-droplist-for-accurate-results":
      {
        'fr': 'matériels sont affichés, utilisez les listes déroulantes pour affiner ces résultats',
        'en': 'items are displayed, use the scrolling lists to refine these results'
      },
    "error-make-another-choice":
      {
        'fr': 'Une erreur s\'est produite durant la mise à jour, veuillez modifier votre choix',
        'en': 'An error occured during the update, please modify your choice'
      },
    "confirm-align-quote":
      {
        'fr': 'Etes-vous certain de vouloir aligner les durées de votre devis sur',
        'en': 'Are you sure you want to align the durations of your quote on'
      },
    "choose-at-least-one-offer":
      {
        'fr': 'Veuillez choisir au moins une offre à laquelle vous souhaitez vous inscrire',
        'en': 'Please choose at least one proposal for which you want to register'
      },
    'items-found':
      {
        'fr': 'Matériels informatiques trouvés',
        'en': 'Computing equipment found'
      },
    'no-item-found':
      {
        'fr': 'Aucun matériel trouvé',
        'en': 'No equipment found'
      },
    'change-your-criteria':
      {
        'fr': 'Veuillez modifier vos critères de recherche afin de trouver la liste de matériel correspondant à vos besoins',
        'en': 'Please modifiy your search criteria to find a list of  equipment corresponding to your requirements'
      },
    'error':
      {
        'fr': 'Erreur',
        'en': 'Error'
      },
    'error-renew-your-operation':
      {
        'fr': 'Une erreur s\'est produite pendant l\'appel au serveur, veuillez recommencer l\'opération',
        'en': 'Server error, please start your operation again'
      },
    'display-results':
      {
        'fr': 'Affiner la recherche',
        'en': 'Refine search'
      },
    'add-to-quote':
      {
        'fr': 'Ajouter au devis',
        'en': 'Add to quote'
      }
  },

  // translate a text to current page language
  translate: function(text){
    if(typeof this.translations[text] == 'undefined'){
      return text;
    }

    if((this.language != this.defaultLanguage) && typeof this.translations[text][this.language] !== undefined) {
      return this.translations[text][this.language];
    }

    return this.translations[text][this.defaultLanguage];
  },

  // Initialization
  initialize: function(){
    // disable ajax caching
    $.ajaxSetup({cache: false});
    
    // product types page, initialize
    project.initializeProductTypes();

    // product details page, tabs initialization
    project.initializeProductSelector();

    // product details page, tabs initialization
    project.initializeProductDetailsTabs();

    // checkout pages initialization
    project.initializeCheckout();
    
    // search wizard initialization
    project.initializeSearchWizard();
    
    // second hand products initialization
    project.initializeSecondHandProducts();

    // homepage slider
    project.initializeHomepageSlider();

  },

  
  // Load common events and initializations
  loadCommon: function(){
    // activate hover on menus
    $('.menu img').hover(
      function() {
        if($.browser.msie && $.browser.version < 7){
          $(this).attr('style', $(this).attr('style').replace(/_off./, "_on." ));
        } else {
          $(this).attr('src', $(this).attr('src').replace(/_off./, "_on." ));
        }
      },
      function() {
       if($.browser.msie && $.browser.version < 7){
          $(this).attr('style', $(this).attr('style').replace(/_on./, "_off." ));
       } else {
          $(this).attr('src', $(this).attr('src').replace(/_on./, "_off." ));
       }
      }
    );
  
    // changing duration, update prices
    $('select.update-renting-duration').change(function(e){
      var duration = $(this).val();
      var taxIncluded = $('input.update-tax-included:checked').val();
      project.updateProductPriceContainer(duration, taxIncluded);
    });

    // change tax included display
    $('input.update-tax-included').click(function(e){
      var duration = $('select.update-renting-duration').val();
      var taxIncluded = $(this).val();
      project.updateProductPriceContainer(duration, taxIncluded);
    });

    // fancybox
    $('a.zoom').fancybox(this.config.fancybox);
    
    // empty form fields on first click
    $('input.empty-first').click(function(e){
      if(!$(this).data('emptied')){
        $(this).val('');
        $(this).data('emptied', true);
      }
    });
    
    // rich date selector
    //$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['']));
    //$("input.rich-date").datepicker($.extend($.datepicker.regional.fr, {dateFormat: 'dd/mm/yy', duration: '', showButtonPanel: true, constrainInput: false}));
    $("input.rich-date").datepicker($.extend($.datepicker.regional[project.language], {dateFormat: 'dd/mm/yy', duration: '', showButtonPanel: true, constrainInput: false}));

    
    // open link into a popup window
    $('a.popup').click(function(e){
      e.preventDefault();
      
      // get data for centering window
      var windowWidth = $('body').innerWidth();
      var windowHeight = $('body').innerHeight();
      
      window.open($(this).attr('href'), '', 'resizable=yes,width=500,height=540,top=' + Math.round((windowHeight - 540) / 2) + ',left=' + Math.round((windowWidth - 500) / 2));
    });
    
    // popup logo link
    $('a.popup-logo').click(function(e){
      e.preventDefault();
      if(confirm('Etes-vous certain de vouloir fermer cette fenêtre ?')){
        window.close();
      }
    });
    
    // popup close link
    $('a.popup-close').click(function(e){
      e.preventDefault();
      window.close();
    });

    // transform mailtos
    $('a.mailto').each(function(){
      var email = $(this).attr('data-email').replace(/\s/, '@');
      $(this)
        .text(email)
        .attr('href', 'mailto:' + email)
      ;
    });
    
    // scroll to top
    $('a.button-anchor-top').click(function(e){
      e.preventDefault();
      if($('html').scrollTop()){
        $('html').animate({scrollTop: 0}, 'fast');
      } else {
        $('body').animate({scrollTop: 0}, 'fast');
      }
    });

    // submit links
    $('form a.form-submit').click(function(e){
      e.preventDefault();
      $(this).closest('form').submit();
    });
    
  },
  

  // inititialize product types page
  initializeProductTypes: function(){
    var container = $('table#table-list-hardware');
    if(container.length){
    }
  },
  

  // Update product price containers
  initializeProductSelector: function(){
    var container = $('select.display-product-details');
    if(container.length){
      container.change(function(e){
        window.location = $(this).val();
      });
    }
  },


  // Update product price containers
  updateProductPriceContainer: function(duration, taxIncluded, updatePreferences){
    // prepare selectors
    var priceSelector = '.' + duration;
   // var priceElementSelector = '';
    var cautionSelector = '';
    if(parseInt(taxIncluded)){
      priceSelector += '.tax-included';
//      priceElementSelector += '.tax-included-element';
      cautionSelector += '.tax-included';
    } else {
      priceSelector += '.out-of-tax';
    //  priceElementSelector += '.out-of-tax-element';
      cautionSelector += '.out-of-tax';
    }

    // hide all prices
    // $('.product-price-container .product-price, .product-price-container .product-caution').hide();

    // display prices and cautions matching with user choices
    // $('.product-price-container .product-price' + priceSelector + ', .product-price-container .product-price' + priceElementSelector + ', .product-price-container .product-caution' + cautionSelector).show();

    // update table classes
    $('.product-price-container').closest('div#display-container')
      .attr('class', '')
      .addClass('duration-' + duration)
      .addClass(parseInt(taxIncluded) ? 'tax-included' : 'out-of-tax')
    ;
  
    // update duration label
    $('.product-price-container .duration-label').text(project.config.durations[duration]);
    
    // update user preferences
    var data = {};
    var hasData = false;
    if(typeof duration != 'undefined' && duration.length){
      data['preferences[renting-duration]'] = duration;
      hasData = true;
    }
    if(typeof taxIncluded && taxIncluded.length){
      data['preferences[tax-included]'] = taxIncluded;
      hasData = true;
    }
    if(hasData && updatePreferences !== false){
      $.ajax({
        url: project.config.setUserPreferencesUrl,
        "data": data
      });
    }
    
  },
  
  
  // Initialize product details tabs and behaviors
  initializeProductDetailsTabs: function(){

    // tabs container
    var tabsContainer = $('div#product-tabs');
    
    if(tabsContainer.length){
      
      /* Local methods */
      // display a product detail tab
      var displayTab = function(containerId){
        // remove selection on tas
        $('li', tabsContainer).removeClass('selected');
      
        // select clicked tab
        $('li:has(a[href=#' + containerId + '])', tabsContainer).addClass('selected');
    
        // hide all tabs contents
        $('div.product-tab.tabs-body').hide();
    
        // display selected tab content
        $('div.product-tab.tabs-body#tab-' + containerId).show();
        
        // change location hash
        window.location.hash = containerId;
        
        // scroll to top if required
        if(tabsContainer.position().top < $('html').scrollTop()){
          $('html').animate({scrollTop: tabsContainer.position().top}, 'fast', 'linear', null);
        }
      };
      
      // display a configuration detail
      var displayConfiguration = function(configurationId, title){
        // hide all the other configuration
        $('div#tab-product-configurations div.configuration').hide();
        
        // show the selected configuration
        $('div#tab-product-configurations div#product-configuration-' + configurationId).show();
        
        // update the select configuration index
        $('select.display-configuration-detail').val(configurationId);
        
        // update tab title
        $('li a[href=#product-configurations] em', tabsContainer).text(title);
        
        // display configuration detail tab
        displayTab('product-configurations');
      };
      
      // compare configurations
      var compareConfigurations = function(ids){
        // need at least two ids for comparison display
        if(ids.length < 2){
          // hide comparison table
          $('#tab-product-comparison .compare-configurations').hide();
          
          // show comparison selector
          $('#tab-product-comparison div.select-configurations').show();
          
          // show message
          $('#tab-product-comparison .too-less-configurations').effect('pulsate');
          
        }
        
        // go for comparison
        else {
          var comparisonTable = $('table.table-compare');
          
          // hide comparison table columns
           $('td.configuration', comparisonTable).hide();
           
          // hide messages
          $('#tab-product-comparison .too-many-configurations').hide();
          $('#tab-product-comparison .too-less-configurations').hide();
          
          // get width percentual foreach column
          var columnWidth = ids.length >= 3 ? '30%' : parseInt(90 / ids.length) + '%'; 
          
          // display all columns matching with prodived configurations
          var counter = 0;
          for(id in ids){
            counter++;
            if(counter <= 3){
              $('td.configuration-' + ids[id], comparisonTable).show().css('width', columnWidth);
            }
          }
          
          // hide comparison selector
          $('#tab-product-comparison .select-configurations').hide();
          
          // show comparison table
          $('#tab-product-comparison .compare-configurations').show();
          
          // display a message if user tried to display more than 3 configurations
          if(counter > 3){
            $('#tab-product-comparison .too-many-configurations').effect('pulsate');
          }
        }
        
        // display comparison tab
        displayTab('product-comparison');
      };
      
      // display configuration selector for comparisons
      var displayCompareSelector = function(){
        // hide messages
        $('#tab-product-comparison .too-many-configurations').hide();
        $('#tab-product-comparison .too-less-configurations').hide();
        
        // hide comparison table
        $('#tab-product-comparison .compare-configurations').hide();
        
        // show comparison selector
        $('#tab-product-comparison .select-configurations').show();
        
      };

      
      /* Events */
      // click on tab
      $('li a[href^="#"]', tabsContainer).click(function(e){
        e.preventDefault();
        displayTab($(this).attr('href').substr(1));
      });
      
      // click a configuration detail link, display it in the configuration detail tab
      $('a.display-configuration-detail').click(function(e){
        e.preventDefault();
        displayConfiguration($(this).attr('href').replace(/^[^0-9]*/, ''), $(this).attr('title'));
      });
      
      
      // use configuration select list, display selected entry in the configuration detail tab
      $('select.display-configuration-detail').change(function(e){
        displayConfiguration($(this).val(), $('option:selected', this).text());
      });
      
      // display configurations comparison on button click
      $('p.button-link-compare a').click(function(e){
        e.preventDefault();
        
        // get checkbox selector
        var selector = $(this).attr('href').replace(/^#/, '');
        
        // get selected ids
        var ids = [];
        $(':checkbox.' + selector + ':checked').each(function(index, element){ids.push($(element).val());});
        
        // display comparison table
        compareConfigurations(ids);
      });
      
      // link .compare-1 with .compare-2 checkboxes
      $(':checkbox.compare-1, :checkbox.compare-2').click(function(e){
        if($(this).hasClass('compare-2')){
          $(':checkbox.compare-1[value=' + $(this).val() + ']').attr('checked', $(this).is(':checked') ? 'checked' : '');
        } else {
          $(':checkbox.compare-2[value=' + $(this).val() + ']').attr('checked', $(this).is(':checked') ? 'checked' : '');
        }
      });
      
      // display configuration selection when new-compare button is clicked
      $('a.new-compare').click(function(e){
        displayCompareSelector();
      });

      
      /* Initialization */
      // Display tab aimed by url anchor
      var noTabDisplayed = true;
      if(window.location.hash){
        var containerId = window.location.hash.substr(1);

        // tab configuration detail
        var containerActionLink = $('a[href="#' + containerId + '"]:eq(0)');
        if(containerActionLink.length){
          containerActionLink.click();
          noTabDisplayed = false;
        }

        else {
          // check containerId existency
          if($('a[href=#' + containerId + ']', tabsContainer).length){
            $('div.product-tab.tabs-body').hide();
            displayTab(containerId);
            noTabDisplayed = false;
          }
        }
      }
      
      // Default: show only first tab
      if(noTabDisplayed) {
        $('div.product-tab.tabs-body:gt(0)').hide();
      }
      
    }
  },


  // Initialize checkout pages
  initializeCheckout: function(){
    var container;
    
    // display page
    if((container = $('div.checkout-display')).length){
      /* Local methods */

      /* Events */
      // advise user on order edit
      $('.order-update').submit(function(e){
        if(confirm(project.translate("confirm-change-quote"))){
          return true;
        }
        return false;
      });
      
      // cancel an order
      $('a.cancel-order').click(function(e){
        if(confirm(project.translate("canfirm-cancel-quote"))){
          return true;
        }
        return false;
      });
      
      // duplicate an order
      $('a.duplicate-order').click(function(e){
        if(confirm(project.translate("confirm-duplicate-quote"))){
          return true;
        }
        return false;
      });
      
      // email an order
      $('a.email-order').click(function(e){
      });
      
      // print an order
      $('a.print-order').click(function(e){
        e.preventDefault();
        window.open($(this).attr('href'));
      });
      
      // new order
      $('a.new-order').click(function(e){
        if(confirm(project.translate("confirm-create-new-quote"))){
          return true;
        }
        return false;
      });
      
      // update cart on quantity change
      $('select.quantity', container).change(function(e){
        $(this).closest('form').submit();
      });
      
      // toggle product selector visibility on button clicked
      $('a.toggle-product-selector').click(function(e){
        e.preventDefault();
        $('.product-selector').toggle();
      });
      
      // cascading selects for product selection
      $('.product-selector select.cascading', container).live('change', function(e){
      // jquery / live extension bug, must redeclare container
      var container = $('div.checkout-display');
      
        var updatedSelect = $(this);
        var productSelector = container.find('.product-selector');
        
        // delete all selects being next sibbling of this one
        updatedSelect.nextAll().remove('select');
        
        // check for a valid selected value
        if(!updatedSelect.val()){
          return false;
        }
        
        // set loading
        productSelector.addClass('loading');
        
        // ajax request, get next select tag definition and products matching user parameters
        $.ajax({
          url: updatedSelect.closest('form').attr('action'),
          data: updatedSelect.closest('form').serializeArray(),
          dataType: 'xml',
          success: function(data, textStatus){
          
            if($(data).find('select option').length){
              // create a new select tag
              var select = 
                $('<select/>')
                  .attr('name', $(data).find('select:eq(0)').attr('name')) 
                  .attr('class', 'cascading')
              ;
              
              // add a blank option when user have to make a choice
              if($(data).find('select option').length >= 1){
                select.append('<option value="">' + project.translate('display-results') + '</option>');
              }
                
              // add options to select
              $(data).find('select option').each(function(index, element){
                select.append(
                  $('<option/>')
                    .attr('value', $(element).attr('value'))
                    .text($(element).text())
                );
              });
              
              // display select
              updatedSelect.after(select);
            }

            // delete current product list
            $('table.results tbody tr', productSelector).remove();
            
            // update product list
            var products = $(data).find('products product');
            if(products.length)
            {
              // display an advisory message when all products could not be displayed
              var productsNumber = parseInt($(data).find('products:eq(0)').attr('number'));
              var productsTotalNumber = parseInt($(data).find('products:eq(0)').attr('total-number'));
              if(productsNumber > 15){
                var tr = '<tr><td colspan="5">' + productsNumber + ' ' + project.translate('items-found-use-droplist-for-accurate-results') + '</td></tr>';
                $('table.results tbody', productSelector).append(tr);
              }
              
              // add products
              products.each(function(index, element){
                var tr = 
                  $('<tr/>')
                    .attr('class', index % 2 ? 'odd' : 'even')
                    // <td class="img"><img src="xxxxx" /></td>
                    .append(
                      $('<td/>')
                        .attr('class', 'img')
                        .append(
                          $('<img/>')
                            .attr('src', $(element).find('image-url').text())
                        )
                    )
                    // <td class="tt"><a href="xxxxxx">xxxxxx</a></td>
                    .append(
                      $('<td/>')
                        .attr('class', 'tt')
                        .append('[' + $(element).find('family').text() + '] ')
                        .append(
                          $('<a/>')
//                            .attr('href', $(element).find('product-url').text())
                            .attr('href', $(element).find('order-url').text())
                            .html($(element).find('name').text())
                        )
                    )
                    // <td><b>xxxxxx</b></td>
                    .append(
                      $('<td class="price txt-r"/>')
                        .append(
                          $('<b/>')
                            .html($(element).find('price').text())
                        )
                    )
                    // <td>xxxxxx</td>
                    .append(
                      $('<td class="caution txt-r"/>')
                        .html($(element).find('caution').text())
                    )
                    // <td class="actions"><a class="button-link-green-dark" href="xxxxxx"><span></span><em>Ajouter au devis</em></a></td>
                    .append(
                      $('<td class="actions"/>')
                        .append(
                          $('<a/>')
                            .attr('href', $(element).find('order-url').text())
                            .attr('class', 'button-link-green-dark')
                            .html('<span/><em>' + project.translate('add-to-quote') + '</em>')
                        )
                    )
                ;
              
                // append tr to results
                $('table.results tbody', productSelector).append(tr);
                
                // remove loading
                productSelector.removeClass('loading');
                
              });
            }
          },
          error: function(XMLHttpRequest, textStatus, errorThrown){
            // delete current product list
            $('table.results tbody tr', productSelector).remove();
            
            // display an error message
            $('table.results tbody', productSelector).append('<tr class="even"><td colspan="5">' + project.translate('error-make-another-choice') + '</td></tr>');
          }
        });
      });
      
      // align order durations
      $('form.update-order-duration', container).submit(function(e){
        // get user selected duration
        var duration = $('select',$(this)).val();
        
        // get duration label
        var durationLabel = project.config.durations[duration];
        
        // ask for confirmation
        return confirm(project.translate('confirm-align-quote') + ' ' + durationLabel + ' ?');
      });
      
      // update basket items
      $('select.update-basket', container).change(function(e){
        $(this).closest('form').submit();
      });
      
      // update unavailable item
      $('.unavailable select').change(function(e){
        $(this).closest('form').submit();
      });

      /* Initialization */

    }


    // client data page
    if((container = $('div.checkout-client')).length){
      /* Local variables */
      var billingAddressSelector =  $('.estimate-info-invoice select.update-address');

      /* Local methods */
      var updateShippingAddressDisplay =  function(){
        if($(':checkbox[name=same_delivery_address]', container).is(':checked')){
          $('.shipping-fields', container).hide();
        } else {
          $('.shipping-fields', container).show();
        }
      };
      
      /* Events */
      // display or hide shipping address form
      $(':checkbox[name=same_delivery_address]', container).click(function(e){
        updateShippingAddressDisplay();
      });
      
      // update user inputs on address select
      $('select.update-address').change(function(e){
        // get selected id
        var contactId = $(this).val();

        // get input prefix
        var inputPrefix = $(this).attr('name').replace(/\[.*$/, '');

        if(contactId){
          // get matching address
          if(typeof addresses === 'undefined' || typeof addresses[contactId] === 'undefined'){
            return true;
          }
          var address = addresses[contactId];

          // get all fields with the same prefix
          $(':input[name^=' + inputPrefix +'], :select[name^=' + inputPrefix + ']').each(function(index, element){
            var elementName = $(element).attr('name').replace(/^.*\[/, '').replace(/\]$/, '');
            if(typeof address[elementName] !== 'undefined' && (address[elementName].length || address[elementName] > 0)){
              $(element).val(address[elementName]);
            }
          });
        }
          // reset fields to empty
        else {
          $(':input[name^=' + inputPrefix +'], :select[name^=' + inputPrefix + ']').each(function(index, element){
            $(this).val('');
          });
        }
        
      });
      
      /* Initialization */
      updateShippingAddressDisplay();

      if(billingAddressSelector.length){
        if(!billingAddressSelector.val().length){
          billingAddressSelector.val($('option:last', billingAddressSelector).attr('value'));
        }
        billingAddressSelector.change();
      }
    }


    // newsletter form
    $('form.newsletter-subscribe').submit(function(e){
      if(!$(':checkbox:checked').length){
        alert(project.translate('choose-at-least-one-offer'));
        return false;
      }
    });


  },
  
  
  // Initialize search wizard
  initializeSearchWizard: function(){
    var container;
    if((container = $('.wizard')) && container.length){
      /* Local methods*/
      // update results
      var updateResults = function(){
        var form = $('.form-wizard form', container);
        
        var resultsContainer = $('.results', container);
        var resultTpl = $('.result-tpl', container).html();
        $.ajax({
          url: form.attr('action'),
          data: form.serialize(),
          dataType: 'xml',
          success: function(data, textStatus){
            // empty result container
            resultsContainer.empty();

            // display result container (hidden first)
            resultsContainer.show();

            // add title
            resultsContainer.append('<h4>' + project.translate('items-found') + '</h4>');

            // add entries
            if($(data).find('entry').length){
              $(data).find('entry').each(function(index, element){
                // create a new result element
                var resultElement = resultTpl;
                var imageUrl = $(element).find('image-url').text();
                resultElement = 
                  resultElement.replace('__image__', imageUrl.length ? '<img src="' + imageUrl + '" />' : '&nbsp;')
                    .replace('__name__', $(element).find('name').text())
                    .replace(/__product_url__/g, $(element).find('product-url').text())
                ;
  
                // append to results
                resultsContainer.append(resultElement);
              });
            } else {
              resultsContainer.html('<h4>' + project.translate('no-item-found') + '</h4><p class="error">' + project.translate('change-your-criteria') + '</p>');
            }
          },
          error: function(XMLHttpRequest, textStatus, errorThrown){
            // display error message
            resultsContainer.html('<h4>' + project.translate('error') + '</h4><p class="error">' + project.translate('error-renew-your-operation') + '</p>');
          },
          complete: function(){
            // remove all loaders
            $('.form-wizard ul', container).removeClass('loading');
          }
        });
      };

      /* Events */
      // input clicked, update results
      $('.wizard .form-wizard input').click(function(e){
        // add loader to option group
        $(this).closest('ul').addClass('loading');

        // update results
        updateResults();

      });
    }

  },
  
  
  // Initialize second hand product
  initializeSecondHandProducts: function(){
    var container;
    if((container = $('.second-hand-products')) && container.length){
      /* Local methods*/
      // submit form
      var displaySecondHandProducts = function(){
        $('form#second-hand', container).submit();
      };

      /* Events */
      // Change on select list
      $('form#second-hand select', container).change(function(e){
        displaySecondHandProducts();
      });
      
      /* Initialization */
    }
  },


  // inititialize homepage slider
  initializeHomepageSlider: function(){
    var container = $('.homepage-slider .slider');
    if(container.length){
        // activate carousel
				container.carouFredSel({
          "items": 1,
          "width": 672,
          "height": 192,
          "scroll": {
            "duration": 500
          },
          "auto": {
            "pauseDuration": 5000
          },
          "pagination": '.pagination'
				});

        // activate link on whole slides
        $('.slide', container).click(function(e){
          // get link values
          var
            $button = $('a.button', $(this)),
            slideLinkUrl = $button.attr('href'),
            slideLinkTarget = $button.attr('target')
          ;

          // open link in same/other window
          if(slideLinkUrl.length && slideLinkUrl != '#'){
            if(slideLinkTarget == '_blank'){
              window.open(slideLinkUrl);
            } else {
              window.location = slideLinkUrl;
            }
          }
        });
      
    }
  }


  


};

