/**
 * @company: DP2I
 * @author: Nicolas Pelletier
 */
jQuery.ajaxSetup
( { beforeSend: function (xhr)
    {
      xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
      this.data = this.data.split('&').map(function (p) {
        p = p.split('=');
        var k = p[0];
        var v = escape(UTF8.decode(unescape(p[1])));
        return k + '=' + v;
      }).join('&');
      
      //console.log(this, xhr);
      //xhr.setRequestHeader('Accept-Charset', 'utf-8');
    }
/*  , headers:
    { 'Content-Type': 'text/html; charset=utf-8'
    }*/
  , traditional: true
  }
);
 
var UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};

var LightBox = new (function ($) {
  this.elements = [];
  this.top = 0;

  this.open = function (className) {
    var $window = $(window);
    var lb = $('.lightbox-frames .' + className);
    if (lb.size() < 1) return ;
    $('.lightbox-displayed .lightbox-content').empty().append(lb);
    Axessia.dom.clear(lb);
    Axessia.dom.autofill(lb);
    if (this.elements.length > 0)
      this.elements[this.elements.length - 1].appendTo('.lightbox-frames');
    else {
      this.top = $window.scrollTop();
      $window.scrollTop(0);
      $('body').addClass('lightbox-active');
    }
    this.expose();
    this.elements.push(lb);
  };

  this.close = function () {
    this.elements.pop().appendTo('.lightbox-frames');
    if (this.elements.length > 0)
      this.elements[this.elements.length - 1].appendTo('.lightbox-content');
    else {
      $(window).scrollTop(this.top);
      $('body').removeClass('lightbox-active');
      Current.hash.set();
    }
  };

  this.expose = function () {
    var $window = $(window), h = $window.height(), w = $window.width();
    $('#LightBox-Elements').height(h).width(w).css('line-height', h + 'px');
    $('#LightBox-Background').height(h).width(w);
    if ($.browser.msie && parseFloat($.browser.version) <= 7) {
      var $box = $('.lightbox-displayed');
      $box.addClass('msie').css
      ({ top: Math.max(0, (h - $box.height()) / 2) + 'px'
       , left: Math.max(0, (w - $box.width()) / 2) + 'px'
       });
    }
  };
})(jQuery);

jQuery(function () {
  var $ = jQuery;
  window.isDocumentLoaded = true;

  /**
   * enable Lightboxes
   */
  $('.lightbox').appendTo('#LightBox-Elements .hidden');
  $('.lightbox-close').click(proxify(LightBox.close, LightBox));
  $(window).resize(proxify(LightBox.expose, LightBox));
  Current.hash.routes.push
  ( { pattern: /^\lightbox:([a-z\-0-9A-Z_]+)($|[,])/
    , callback: function (hash, match) { LightBox.open(match); }
    }
  );

  /** 
   * overload root links to extend clickable area
   * overflow root links to extend hover modifier area
   */
  $('.axessia .root-link:has(a)').click(function () {
    window.location = $(this).find('a').attr('href');
  });
  $('.axessia .root-link-js:has(a)').each(function () {
    var $this = $(this);
    //console.log($this.find('a'),$this.find('a[href^=javascript]'));
    var $link = $this.find('a[href^=javascript]');
    if ($link.size() > 0)
      $this.css({ cursor: 'pointer' }).click(function () {
        eval($link.attr('href').substr(11));
      });
    else
      window.location = $(this).find('a').attr('href');
  });

  /** 
   * overload dom object, check if has className fix-hover,
   * in this case, set the class hover went mouse over the object
   */
  $('.axessia .fix-hover').each(function () {
    var remanence = null;
    $(this)
      .removeClass('fix-hover')
      .mouseover(function () {
        if (remanence) clearTimeout(remanence);
        $(this).addClass('hover').removeClass('hover-remanence');
        remanence = null;
      })
      .mouseout(function () {
        if (remanence) return ;
        var element = $(this).addClass('hover-remanence')
          .removeClass('hover');
        remanence = setTimeout
        ( function () { element.removeClass('hover-remanence'); }
        , 250
        );
      })
  });

  /**
   * overloading input text, add thaousand separator `.', limit numeric input
   */
  $('.axessia input[type=text].with-mask').each(function () {
    var $this = $(this);
    var $hidden = $('<input type="hidden" />').attr('name', $this.attr('name')).val($this.val());
    var sync = function () { $hidden.val($this.autoNumericGet()); };
    if ($this.hasClass('amount-field')) $this.autoNumeric({ aPad: false });
    else if ($this.hasClass('numeric-field')) $this.autoNumeric({ aPad: false, aSep: ' ' });
    $this.after($hidden).removeAttr('name');
    $this.change(sync).keypress(sync);
  });

  /**
   * push as hidden field any param in the action attribute of a get form
   */
  $('.axessia form[method=get][action]').each(function () {
    var action = $(this).attr('action').split('?');
    if (action.length < 2) return ;
    var form = $(this);
    form.attr('action', action[0]);
    action[1].split('&').map(function (v) {
      var kv = v.split('=');
      form.prepend
      ( $('<input type="hidden" />')
        .attr('name', kv[0])
        .val(kv[1])
      );
    });
  });

  /**
   * enable photo-show
   */
  $('.axessia .product-photo-show').each(function () {
    var $this = $(this);
    var images = $this.find('.photo-control .control-preview a:has(img)');
    var previewUpdate = function () {
      if (!(images.size() > 4)) return ;
      setTimeout(function () {
        var active = images.hide().filter('.activeSlide').show();
        if (active.next().size() > 0) active.next().show();
        else images.first().show();
        if (active.prev().size() > 0) active.prev().show();
        else images.last().show();
      }, 10);
    };

    var get2DCenter = function (container, item) {
      var rc = container.height / container.width
        , ri = item.height / item.width
        , r
      ;
      if (item.width > container.width || item.height > container.height) {
        if (ri > rc) return (r = container.height / item.height,
          { width: item.width * r, height: container.height
          , horizontal: (container.width - (item.width * r)) / 2, vertical: 0
          }
        );
        else return (r = container.width / item.width,
          { width: container.width
          , height: item.height * r
          , horizontal: 0, vertical: (container.height - (item.height * r)) / 2
          }
        );
      } else return (
        { width: item.width, height: item.height
        , vertical: (container.height - item.height) / 2
        , horizontal: (container.width - item.width) / 2
        }
      );
    };
    
    var widget = $this.find('.photo-display:has(img)')
      .cycle({ pager: '.photo-control .control-preview'
             , pagerEvent: 'click'
             , onPagerEvent: previewUpdate
             , timeout: 0
             , fx: 'scrollHorz'
             , height: null
             , width: null
             , fit: true
             , after: (function (index, img) {
                setTimeout(function () {
                  var $img = $(img);
                  var c = $img.data('position');
                  if (!c) {
                    img.style.height = 'auto';
                    img.style.width = 'auto';
                    c = get2DCenter({ width: widget.width(), height: widget.height() }, { width: $img.width(), height: $img.height() })
                    $img.data('position', c);
                  }
                  console.log(c);
                  $img.css({ 'top': c.vertical, 'left': c.horizontal, width: c.width, height: c.height });
                }, 1);
                return arguments.callee;
               })(0, $this.find('.photo-display img').first().get(0))
             , width: $this.width()
             , speed: 'fast'
             , pagerAnchorBuilder: function (idx) {
                 return $this.find('.photo-control .elements a[class=item-' + idx + ']');
               } 
             })
      .cycle('pause')
    ;
    $this.find('.photo-control').each(function () {
      var self = $(this);
      self.find('.control-prev a').click(function (e) {
        widget.cycle('prev');
        previewUpdate();
        e.preventDefault();
      });
      self.find('.control-next a').click(function (e) {
        widget.cycle('next');
        previewUpdate();
        e.preventDefault();
      });
      previewUpdate();
    });
  });

  /**
   * input-select nouvelle implem les checkbox selectionné
   */
  $('.axessia .input-select.rewrited').each(function () {
      var $this = $(this).click(function (e) {
        var $this = $(this);
        e.stopPropagation();
        if ($this.hasClass('on')) return ;
        $(document).click(function () { $this.removeClass('on'); });
        $this.addClass('on');
      });
      var example = $this.find('.select-example').text();
      var resume = $this.find('input.resume').val(example);
      var $checkboxes = $this.find('input[type=checkbox],input[type=radio]')
        .change(function () {
          var texts = [];
          $checkboxes.filter(':checked').next('label')
            .each(function () { texts.push($(this).text()); });
          if (texts.length > 0) resume.val(texts.join(', '));
          else resume.val(example);
        });
      $checkboxes.first().trigger('change');
    });
  
  /**
   * enable google-maps
   */
  $('.widget-google-map.not-loaded').each(function () {
    var $this = $gmap = $(this).removeClass('not-loaded');
    var markers = [];
    var bounds = new google.maps.LatLngBounds();
    var geocoder = new google.maps.Geocoder();
    var request = 0;
    
    $this.find('.marker').each(function () {
      var $this = $(this);
      var lng = parseFloat($this.find('.marker-longitude').text());
      var lat = parseFloat($this.find('.marker-latitude').text());
      var address;
      var marker = {};
      marker.title = $this.find('.marker-title').text();
      marker.address = $this.find('.marker-address').text();
  
      if (lat && lng) {
        marker.position = new google.maps.LatLng(lat, lng);
        bounds.extend(marker.position);
      } else if (marker.address) {
        request += 1;
        geocoder.geocode
        ( { address: marker.address }
        , function (results, status)
          {
            request -= 1;
            if (status == google.maps.GeocoderStatus.OK) {
              marker.position = results[0].geometry.location;
              bounds.extend(marker.position);
            } else if (typeof console != 'undefined') {
              console.log("Geocode was not successful for the following reason: " + status);
            }
          }
        )
      }
      var infowindow = $this.find('.marker-infowindow').get(0);
      if (infowindow) {
        marker.infowindow = new google.maps.InfoWindow({ content: infowindow });
      }
      markers.push(marker);
    });

    var map = new google.maps.Map
    ( $this.get(0)
    , {// zoom: parseInt($this.find('.map-zoom').text())
//      , center: center
//      , disableDefaultUI: true
       maxZoom: 16
      , mapTypeId: google.maps.MapTypeId.ROADMAP
      }
    );

    var relocate = function () {
      var currentwindow;
      var bad_markers = 0;
      for (var i = 0; i < markers.length; i++) {
        if (!markers[i].position) { bad_markers++; continue ; }
        markers[i].marker = new google.maps.Marker
        ( { position: markers[i].position
          , map: map
          , title: markers[i].title
          }
        );
        if (markers[i].infowindow) {
          ( function (marker) {
            google.maps.event.addListener(marker.marker, 'mouseover', function () {
              //if (currentwindow == marker.infowindow) return ;
              if (currentwindow) currentwindow.close();
              currentwindow = marker.infowindow;
              marker.infowindow.open(map, marker.marker);
            });
          })(markers[i]);
        }
      }
      //console.log(bad_markers, markers.length);
      if (bad_markers >= markers.length)
        $gmap
          .after
          ( $('<div class="widget-google-map" />')
              .css({ 'text-align': 'center' })
              .html(
                $('<span />').css({ 'display': 'inline-block', 'margin-top': '50px' })
                .text('Localisation non disponible')
              )
          )
          .remove();
      else
        map.fitBounds(bounds);
    };
    
    if (request < 1) relocate();
    else 
      (function () {
        var self = arguments.callee;
        setTimeout(function () {
          //console.log('wait');
          if (request > 0) self();
          else relocate();
        }, 200);
      })();
  });

  /**
   * Product rooms
   */
  $('.form-field.product-rooms').each(function () {
    var $this = $(this);
    $this.find('input[name=s_prd_Pieces]').change(function () {
      var $this = $(this);
      var $field = $this.parents('form').first();
      //LJN var $min = $field.find('input[name=s_prd_PiecesRange_min]');
      //LJN var $max = $field.find('input[name=s_prd_PiecesRange_max]');
      var min = 0, max = 0;
      $field.find('input[name=s_prd_Pieces]:checked, input[name=s_prd_Pieces].checked').each(function () {
        var value = $(this).val();
        if (parseInt(value) > 0) {
          min = (min > 0) ? Math.min(min, parseInt(value)) : parseInt(value);
          max = (max > 0) ? Math.max(max, parseInt(value)) : parseInt(value);
        }
        if (~(value.indexOf('+'))) max = Infinity;
        else if (~(value.indexOf('-'))) min = -Infinity;
      });
      //LJN $min.val(min > 0 ? min : '');
      //$max.val(max > 0 && max < Infinity ? max : '');
    })
    .filter(':checked').each(function () {
      $(this).parents('.item').first().addClass('checked');
    });
    $this.find('label').click
    ( $.browser.msie
      ? function (e) {
          e.preventDefault();
          var id = $(this).attr('for');
          var $target = $('#' + id);
          if ($target.is(':checked')) $target.attr('checked', false);
          else $target.attr('checked', true);
          $target.change();
        }
      : null
    );
  });
  $('.form-field.product-rooms-range').each(function () {
    var $this = $(this);
    var min = Infinity;
    var max = -Infinity;
    $('.form-field.product-rooms input:checkbox:checked').each(function () {
      $(this).val().split(',').map(function (i) {
        i = parseInt(i);
        if (i < min) min = i;
        if (i > max) max = i;
      });
    });
    $this.find('.min select').val(min);
    $this.find('.max select').val(max);
  });

  /**
   * Product area
   */
  $('.form-field.product-area-range').each(function () {
    var $this = $(this);
    $this.find('.min input').val($('.form-field.product-area.min input').val());
    $this.find('.max input').val($('.form-field.product-area.max input').val());
  });
  
  /**
   * Product price
   */
  $('.form-field.product-price-range').each(function () {
    var $this = $(this);
    $this.find('.min input').val($('.form-field.product-price.min input').val());
    $this.find('.max input').val($('.form-field.product-price.max input').val());
  });
  
  /**
   * enable suggestion for location search
   */
  (function () {
    var data = [], no_double = {};
    Axessia.get('search.location.elements.item', [])
      .map(function (e) {
        var key = '' + e.value + ':' + e.text;
        if (!(key in no_double)) {
          data.push({ value: ('' + e.value), text: ('' + e.text) });
          no_double[key] = null;
        }
      });
    var getCurrentElement = function () {
      var counter = $input.caret().start;
      var result = { text: '', index: 0 };
      var value = $input.val();
      var list = value.split(',');
      list.map(function (i, j) {
        if (counter <= 0 || value.length == 0) return ;
        counter -= i.length;
        if (counter <= 0 ) {
          result.text = (i + '').trim();
          result.index = j;
        } else {
          counter -= 1;
          if (counter <= 0) counter++;
        }
      });
      return result;
    };
    var getMatchedList = function (list, element) {
      var value = $input.val().toLowerCase();
      var result = [];
      list.map(function (i) {
        if (~i.text.toLowerCase().indexOf(element.text.toLowerCase())) {
          if (~value.indexOf(i.text.toLowerCase())) i.alreadyDefined = true;
          else i.alreadyDefined = false;
          i.index = element.index;
          result.push(i);
        }
      });
      //console.log(result, element.text);
      if (result.length == 1 && result[0] == element.text) return [];
      return result;
    };
    var refreshDomList = function (list) {
      var max_item = 10;
      $list.empty();
      if (list.length <= 0) $list.append('<li>Pas de resultat</li>');
      else {
        list.map(function (item) {
          if (item.alreadyDefined) return ;
          if (max_item-- <= 0) return ;
          $list.append
          ( $('<li></li>')
              .text(item.text)
              .hover
              ( function () { $(this).addClass('hover'); }
              , function () { $(this).removeClass('hover'); }
              )
              .click(function () {
                var items = $input.val().split(',').map(function (i) { return i.trim(); });
                items[item.index] = (item.text + '').trim();
                var value = items.join(', ') + ', ';
                $input.val(value).caret({ start: value.length, end: value.length }).focus();
                close_completion();
              })
          );
        });
      }
    };
    var selectItem = function (sens) {
      var index = parseInt(($list.get(0).className.match(/select-(\d+)/) || [])[1]);
      var $items = $list.find('li');
      $list.removeClass('select-' + index).find('.on').removeClass('on');
      index = isNaN(index) ? 0
            : sens == 'backward' ? Math.max(0, index - 1)
            : sens == 'forward' ? Math.min($items.size() - 1, index + 1)
            : index
      ;
      $items.eq(index).addClass('on');
      $list.addClass('select-' + index);
    };
    var useSelectedItem = function () {
      $list.find('.on').click();
    };
    var specialKeys = function (e) {
      switch (parseInt(e.which)) {
      case 10/*enter*/: case 13/*enter*/: 
      case 9/*tab*/: 
        e.preventDefault();
      case 188/*comma*/: 
        if (completion_state == 'opened')
          useSelectedItem();
      break ;
      case 38: case 40:
        e.preventDefault();
        selectItem(e.which == 38 ? 'backward' : 'forward');
      break ;
      default: /*console.log(e.which);*/ return false;
      }
      return true;
    };
    var completion_state = 'closed';
    var open_completion = function (e) {
      if (e instanceof Object && typeof e.preventDefault == 'function') e.preventDefault();
      $list.removeClass(($list.get(0).className.match(/(select-\d+)/) || [])[1] || '');
      var element = getCurrentElement();
      if (element.text.trim().length < 1) return close_completion();
      var list = getMatchedList(data, element);
      refreshDomList(list);
      completion_state = 'opened';
      if ($list.children('li').size() > 0) $list.show();
      else close_completion();
    };
    var close_completion = function () {
      $list.hide(); $input.attr('title', $input.val());
      completion_state = 'closed';
    };
    
    var $list = $('.product-location ul');
    var $input = $('.product-location input:text')
      .click(open_completion)
      .keydown(function (e) {
        specialKeys(e) ||
        setTimeout(open_completion, 1);
      })
      .focus(function () { $(this).filter('.dismiss').val('').removeClass('dismiss'); })
      .blur(function () {
        $(this).filter(function () { return ($(this).val() || '').trim() == ''; })
          .val(Axessia.get('search.location.example', 'séparer par des virgules'))
          .addClass('dismiss');
      })
      .trigger('blur');
    ;
    $(document).click(close_completion);
  })();

  /**
   * content flow
   */
  Axessia.get('widget.content-flow', []).map(function (wdt) {
    var timeout, $elements, $displayed, $others, $widget = $('#' + wdt.id);
    var rotate = function (sens, count) {
      var $to_hide, $to_show;
      count = $elements.size() > (count + wdt.display.size)
        ? count
        : $elements.size() - wdt.display.size;
      if (!(count > 0)) return ;
      if (sens == 'forward') {
        $to_hide = $displayed.filter(Predicate.Math('<', count));
        $to_hide.animate
        ( { width: 0 }
        , wdt.cycle.duration || 800
        , function () { $elements.parent().append($to_hide); refresh(); }
        );
        $to_show = $others.filter(Predicate.Math('<', count)).animate
        ( { width: width }
        , wdt.cycle.duration || 800
        );
      } else if (sens == 'backward') {
        $to_hide = $displayed.filter(Predicate.Math('>=', $displayed.size() - count));
        $to_hide.animate({ width: 0 }, wdt.cycle.duration || 800);
        $to_show = $others.filter(Predicate.Math('>=', $others.size() - count));
        $elements.parent().prepend($to_show);
        $to_show.animate({ width: width }, wdt.cycle.duration || 800, refresh);
      }
    };
    var refresh = (function () {
      $elements = $widget.find('.elements .element').css({ 'overflow': 'hidden', 'float': 'left' });
      $displayed = $elements.filter(Predicate.Math('<', wdt.display.size || 1));
      $others = $elements.filter(Predicate.Math('>', (wdt.display.size || 1) - 1)).css({ width: 0 });
      return arguments.callee;
    })();
    var width = $elements.first().width();
    var startTimeout = function (delay) {
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        if ($elements.parents($widget).filter('.hover').size() < 1)
          rotate('forward', wdt.cycle.size);
        startTimeout(delay);
      }, delay);
    };
    $widget.find('.elements').css({ overflow: 'hidden', height: $widget.find('.elements .element').first().height() + 'px' });
    $widget.find('.button.previous a.link').click(function () { rotate('backward', wdt.cycle.size); });
    $widget.find('.button.next a.link').click(function () { rotate('forward', wdt.cycle.size); });
    startTimeout(1000 * (wdt.cycle.wait.begin || 1));
  });
  
  /**
   * lazy appear
   */
  $('.axessia .lazy-appear').each(function () {
    var $this = $(this).hide()
      .css
      ( { 'position': 'absolute'
        , 'z-index': '40'
        }
      );
    $this.parent()
      .mouseover(function () { $this.show(); })
      .mouseout(function () { $this.hide(); })
    ;
  })
  
  /**
   *  auto targeting blank for external links
   */
    $('a[href^=http]')
      .not(function () { return $(this).attr('href').match(Axessia.RegExp.host); })
      .attr('target', '_blank');

  /**
   * form field validator
   */
  $('.validity-check').each(function () {
    var rxp, rule =
      ( this.className.split(' ').filter
        ( proxify(RegExp.prototype.test, /^valid-if/)
        ).pop() || '')
      .split('valid-if-').pop();
    switch (rule) {
    case 'phone': rxp = /^[0-9 +()]+$/; break ;
    case 'mail': rxp = /^.+@.+\..{2,}$/; break ;
    case 'zipcode': rxp = /^[0-9]{5}$/; break ;
    case 'numeric': rxp = /^[0-9]+$/; break ;
    default: rxp = /./; break ;
    }
    var check = function (s) { return rxp.test(s); };
    $(this).blur(function () {
      var $this = $(this);
      if (!(check($this.val())) && $this.val().length > 0) $this.addClass('incorrect');
      else $this.not('.mandatory').removeClass('incorrect');
    });
  });

  /**
   * form field not empty & prevent send
   */
  $('form').live('submit', function (e) {
    var $this = $(this);
    $set = $this.find('input[type=text].mandatory, textarea.mandatory, select.mandatory');
    radios = {};
    $this.find('input[type=radio][name!=].mandatory').each(function () {
      var name = $(this).attr('name');
      if (name in radios) return ;
      else radios[name] = null;
      $set.add($this.find('input[name=' + name + ']:checked'));
    });
    $set.each(function () {
      var $this = $(this);
      if (($this.val() || '').trim() == '') {
        $this.addClass('incorrect');
      } else $this.removeClass('incorrect');
    });
    $this.find('.validity-check').trigger('blur');
    if ($this.find('.mandatory.incorrect').size() > 0) {
      e.preventDefault();
      e.stopImmediatePropagation();
      e.stopPropagation();
      alert('Un ou plusieurs champs obligatoires sont invalides');
    }
  });
  
  /**
   *  form no resend
   */
  $('form').live('submit', function () {
    $(this).addClass('submitting')
      .find('input[type=submit]').attr('disabled', true);
  }).each(function () { $(this).data('onrelease', []) });

  /**
   * form ajax
   */
  $('form.ajax').live('submit', function (e) {
    e.preventDefault();
    var fields =
      [ 'select', 'textarea', 'input[type=text]', 'input[type=hidden]'
      , 'input[type=radio]:checked'
      , 'input[type=checkbox]:checked'
      ];
    var $this = $(this), data = {};
    setTimeout(function () {
      $this.find(fields.join(',')).not('[disabled]').filter('[name]').each(function () {
        var $this = $(this);
        var name = $this.attr('name'), value = $this.val();
        if (name in data) {
          if (data[name] instanceof Array) data[name].push(value);
          else data[name] = [data[name], value];
        } else data[name] = value;
      });
      $.ajax
      ( { url: $this.attr('action')
        , type: 'post'
        , dataType: 'html'
        , data: data
        , success: function (html)
          {
            Axessia.release.form($this);
            $response = $('<div>' + html + '</div>').find('.response');
            if ($response.hasClass('success')) {
              if ($this.parents('.ajax-content').size() > 0) {
                $this.parents('.ajax-content').first().after($response).remove();
              } else {
                $this.after($response).remove();
              }
            } else {
              alert('une erreur s\'est produite');
            }
          }
        , error: function ()
          {
            Axessia.release.form($this);
          }
        }
      )
    }, 1);
  });
  
  /**
   * search form submition
   */
  (function () {
    var $city = $('<input name="s_prd_Ville" type="hidden" />');
    var $zipcode = $('<input name="s_prd_CodePostal" type="hidden" />');
    $('.search form').submit(function () {
      var $this = $(this);
      var selectors =
        [ 'input[name=s_prd_pieces]'
        , 'input[name=s_prd_Localisation]'
        , 'input[name=s_prd_VilleCodePostal]'
        , 'input[name][value=]'
        , 'input[name][value=0]'
        , '.product-location input.as-values'
        , '.dismiss input'
        ];
      var location_values = $this.find('.product-location .as-values').val() || '';
      $this.find('input[name=s_prd_Ville]').val
      ( location_values.split(',')
        .filter(function (e) { return !/\d+/.test(e) && e != ''; })
        .join(',')
      );
      $this.find(selectors.join(',')).attr('disabled', true);
      $this.find('input[name=s_prd_VilleCodePostal]:not(.dismiss)').each(function () {
        var cities = [], zipcodes = [];
        $(this).val().split(',').map(function (i) {
          var value = i.trim();
          if (value.length > 1)
            (parseInt(value) == value ? zipcodes : cities).push(value);
        });
        $city.val(cities.join(','));
        $zipcode.val(zipcodes.join(','));
        $this.append($city).append($zipcode);
      });
      setTimeout(function () { $(selectors.join(',')).attr('disabled', false); }, 10);
    });
  })();
  
  
});

