if (!Kwo) var Kwo = {};

var Nwc = {};

Nwc.option = {
  "toggle": function () {
    var elm = $('options_box');
    if (elm.visible()) {
      elm.hide();
    }
    else {
      h = elm.getHeight() + 10;
      w = elm.getWidth() / 2 - 70;
      elm.setStyle({top : '-' + h + 'px',
                    left : '-' + w + 'px'});
      elm.show();
    }
  },
  searchReference: function() {
	if ($('search_ref').value == "")
		return (false);
	var elements = $('criteria-search').getElements();
	var to_reset = new Array('categories_select', 'make_id', 'carmodel_id', 'version', 'primary_fuel_type', 'transmission_type', 'doors_count', 'colour_alias', 'zip_code', 'min_value', 'max_value');
	for (i in elements)
		if (to_reset.include(elements[i].name))
			elements[i].value = "";
		$('by_vin').value = $('search_ref').value;
		$('criteria-search').submit();
	}
}

Nwc.inscrip = {
  "toggleinput": function (input_id, event) {
    $(input_id)[($F(event.element()) == 6 ? 'show' : 'hide')]();
  }
}

Nwc.Slideimg = {
  "slideright": function () {
    var position = parseInt($('img_conteur').innerHTML);
    var number = parseInt($('img_number').value);
    if(position < number) {
      $('img_announce_'+position).hide();
      position = position+1;
      $('img_conteur').innerHTML = position;
    }
    $('img_announce_'+position).show();
  },
  "slideleft": function () {
    var position = parseInt($('img_conteur').innerHTML);
    var number = parseInt($('img_number').value);
    if(position != 1){
      $('img_announce_'+position).hide();
      position = position-1;
      $('img_conteur').innerHTML = position;
    }
    $('img_announce_'+position).show();
  }
}

Nwc.Completion = Class.create({
	"elt_input": null,
	"elt_result": null,
	"waiting": false,
	
	"initialize": function (params) {
		if (!$(params.input)) {
			console.log('element : [' + params.input + '] introuvable');
			return;
		}
		if (!$(params.result)) {
			console.log('element : [' + params.result + '] introuvable');
			return;
		}
		this.elt_input = $(params.input);
		this.elt_result = $(params.result);
		this.elt_input.observe("keyup", this.pressKey.bind(this));
	},
	
	getData: function () {
		this.waiting = false;
		if (this.elt_input.value == "" || this.elt_input.value == this.elt_input.title) {
			this.elt_result.hide();
			return ;
		}
		else {
			Kwo.exec('/announces.completion', $('criteria-search'), {'loading':'small', 'container': this.elt_result});
			this.elt_result.show();
		}
	},
	
	closeZone:function(evt) {
		this.elt_result.hide();
	},
	
	resultChoosen:function(evt) {
		if (evt.originalTarget == null)
			var element = evt.target;
		else
			var element = evt.originalTarget;
		this.elt_input.value = element.title;
		this.elt_result.hide();
		Kwo.exec('/announces.count', $('criteria-search'), {'loading':'small', 'container': $('nb_search_update') });
	},
	
	pressKey: function (evt) {
		if (this.waiting == true)
			return ;
		this.waiting = true;
		setTimeout("completion.getData()", 700);
	}
});

Nwc.Slidebar = Class.create({

  "elt": null,
  "larrow": null,
  "rarrow": null,
  "lhand": null,
  "click": null,
  "rhand": null,
  "min_input": null,
  "max_input": null,
  "adjust_click" : 0,
  "adjust_click_r" : 0,
  "diff_sep" : 30,
  "max_click" : 160,
  "max_decrease": 10000,
  "callback": Prototype.emptyFunction,
  "last_position": 0,
  "new_position": 0,
  "slide_width": 0,
  "margin_left": 0,
  "min_size": 216,
  "max_size": 651,
  "ratio": 92.593,
  "min_value": 0,
  "max_value": 0,
  "step":54,

  "initialize": function (params) {
    if (!$(params.container)) {
      console.log('element : [' + params.container + '] introuvable');
      return;
    }
    if (typeof params.callback != "function" && params.callback != null) {
      console.log('fonction invalide : [' + params.callback + ']');
      return;
    }
	if ($(params.ratio))
		this.ratio = $(params.ratio);
	if ($(params.diff_sep))
		this.diff_sep = $(params.diff_sep);
	if ($(params.adjust_click))
		this.adjust_click = $(params.adjust_click);
	if ($(params.adjust_click_r))
		this.adjust_click_r = $(params.adjust_click_r);
	if ($(params.click))
		this.click = $(params.click);
	if ($(params.max_click))
		this.max_click = $(params.max_click);
	if ($(params.step))
		this.step = $(params.step); 
	if ($(params.max_decrease))
		this.max_decrease = $(params.max_decrease); 
    this.elt = $(params.container);
    this.larrow = $(this.elt).down('.left-arrow');
    this.rarrow = $(this.elt).down('.right-arrow');
	if ($(params.min_size))
		this.min_size = $(params.min_size);
	if ($(params.max_size))
		this.max_size = $(params.max_size);
    this.min_input = $(this.elt).down('input.min-value');
    this.max_input = $(this.elt).down('input.max-value');
    this.rarrow = $(this.elt).down('.right-arrow');
    this.lhand = $(params.lhand) ? $(params.lhand) : this.larrow.down('.hand');
    this.rhand = $(params.rhand) ? $(params.rhand) : this.rarrow;
	if (this.click != null)
		this.click.observe("click", this.clickPosition.bind(this));
    this.larrow.observe("mousedown", this.onLeftArrowClick.bind(this));
    this.rarrow.observe("mousedown", this.onRightArrowClick.bind(this));
    this.slide_width = this.larrow.getWidth();
    this.margin_left = parseInt(this.larrow.getStyle('marginLeft'));
    this.chooseBetterPlace();
    this.updateLeftArrowInput();
    this.updateRightArrowInput();
    if (params.callback != null) {
      this.callback = params.callback;
    }
  },
  
  "clickPosition": function(e) {
		var target = (e.originialTarget != null ? e.originalTarget : e.target);
		if (target.id == "hleft" || target.id == "hright")
			return ;
		var position = $('slidebar').positionedOffset();
		var x = e.pointerX() - position[0] - 20 - this.adjust_click;
		var diff_x = Math.abs(this.margin_left - x) + 14;
		var diff_y = Math.abs(x - (this.slide_width + this.margin_left)); 
		if (diff_x < diff_y) {
			if ((this.slide_width - (x - this.margin_left)) < this.diff_sep || x <= -14)
				return ;
			this.slide_width = this.slide_width - (x - this.margin_left);
			this.margin_left = x;
			this.chooseBetterPlace();		
			this.updateLeftArrowInput();
		}
		else {
			var pos_x = this.slide_width + (x - (this.slide_width + this.margin_left) + 18) + this.margin_left;
			if (pos_x > this.max_click)
				return ;
			this.slide_width += (x - (this.slide_width + this.margin_left) + 18) + this.adjust_click_r;
			this.chooseBetterPlace();
			this.updateRightArrowInput();			
		}
  },
  
  "onLeftArrowMove": function(e) {
    var delta = (this.last_position - e.clientX);
    this.last_position = e.clientX;
    if ((this.slide_width + delta) <= this.min_size
        || (this.margin_left - delta) < 0) {
      return;
    }
    this.slide_width = this.slide_width + delta;
    this.margin_left = this.margin_left - delta;
    this.larrow.setStyle({'width': this.slide_width + 'px',
                          'marginLeft': this.margin_left + 'px'});
    document.body.focus();
  },
  
  "onRightArrowMove": function(e) {
    var delta = (this.last_position - e.clientX);
    this.last_position = e.clientX;
    if ((this.slide_width - delta) <= this.min_size
        || (this.slide_width - delta + this.margin_left) >= this.max_size) {
      return;
    }
    this.slide_width = this.slide_width - delta;
    this.larrow.setStyle({'width': this.slide_width + 'px'});
    document.body.focus();
  },
  
  "onLeftArrowClick": function(e) {
    if ($(e.target).match('.right-arrow')
        || !$(e.target).match('.hand')) {
      return;
    }
    this.last_position = e.clientX;
    this.slide_width = this.larrow.getWidth();
    this.margin_left = parseInt(this.larrow.getStyle('marginLeft'));
    if (typeof this.onLeftArrowMoveBind != "function") {
      this.onLeftArrowMoveBind = this.onLeftArrowMove.bind(this);
    }
    if (typeof this.onLeftArrowReleaseBind != "function") {
      this.onLeftArrowReleaseBind = this.onLeftArrowRelease.bind(this);
    }
    document.observe('mousemove', this.onLeftArrowMoveBind);
    document.observe('mouseup', this.onLeftArrowReleaseBind);
    document.onselectstart = function () { return false; }
  },
  
  "onRightArrowClick": function(e) {
    this.last_position = e.clientX;
    this.slide_width = this.larrow.getWidth();
    this.margin_left = parseInt(this.larrow.getStyle('marginLeft'));
    if (typeof this.onRightArrowMoveBind != "function") {
      this.onRightArrowMoveBind = this.onRightArrowMove.bind(this);
    }
    if (typeof this.onRightArrowReleaseBind != "function") {
      this.onRightArrowReleaseBind = this.onRightArrowRelease.bind(this);
    }
    document.observe('mousemove', this.onRightArrowMoveBind);
    document.observe('mouseup', this.onRightArrowReleaseBind);
    document.onselectstart = function () { return false; }
  },
  
  "onLeftArrowRelease": function() {
    document.stopObserving('mousemove', this.onLeftArrowMoveBind);
    document.stopObserving('mouseup', this.onLeftArrowReleaseBind);
    this.chooseBetterPlace();
    this.updateLeftArrowInput();
    document.onselectstart = Prototype.emptyFunction;
  },
  
  "onRightArrowRelease": function() {
    document.stopObserving('mousemove', this.onRightArrowMoveBind);
    document.stopObserving('mouseup', this.onRightArrowReleaseBind);
    this.chooseBetterPlace();
    this.updateRightArrowInput();
    document.onselectstart = Prototype.emptyFunction;
  },
  
  "positionThis": function(left, right) {
	this.margin_left = left;
	this.slide_width = right;
	this.larrow.setStyle({'marginLeft': this.margin_left + 'px',
                            'width': this.slide_width + 'px'});
	this.chooseBetterPlace();
	this.updateLeftArrowInput();
	this.updateRightArrowInput();
  },
  
  "chooseBetterPlace": function() {
    var step = this.step;
    var delta = 0;
    if (this.margin_left%step != 0) {
      if ((this.margin_left%step) > step / 2) {
        delta = (step - this.margin_left%step);
      } else {
        delta = - this.margin_left%step;
      }
      this.margin_left += delta;
      this.slide_width -= delta;
      this.larrow.setStyle({'marginLeft': this.margin_left + 'px',
                            'width': this.slide_width + 'px'});
    }
    if (this.slide_width%step != 0) {
      if ((this.slide_width%step) > step/2) {
        this.slide_width = this.slide_width + (step - this.slide_width%step);
      } else {
        this.slide_width = this.slide_width - this.slide_width%step;
      }
      if (this.slide_width <= this.min_size) {
        this.slide_width = this.min_size;
      }
      this.larrow.setStyle({'width': this.slide_width + 'px'});
    }
  },
  
  "updateRightArrowContent": function() {
    var value = this.max_value;
    if (this.max_value == 50000) {
      value = '+ ' + value;
    }
    this.rhand.innerHTML = value + " &euro;";
  },
  
  "updateLeftArrowContent": function() {
    this.lhand.innerHTML = this.min_value + " &euro;";
  },
  
  "updateRightArrowInput": function () {
    this.max_value = parseInt((this.margin_left + this.slide_width) * this.ratio - this.max_decrease);
    if (this.max_input.value != this.max_value) {
      this.max_input.value = this.max_value;
      this.callback({"max_value": this.max_value});
      this.updateRightArrowContent();
    }
  },
  
  "updateLeftArrowInput": function () {
    this.min_value = parseInt(this.margin_left * this.ratio + 5000);
    if (this.min_input.value != this.min_value) {
      this.min_input.value = this.min_value;
      this.callback({"min_value": this.min_value});
      this.updateLeftArrowContent();
    }
  },
  
  updateFinal: function() {
	var min_value = $('m_val');
	var max_value = $('ma_val');
	$('m_val').value = this.min_value;
	$('ma_val').value = this.max_value;
	if (min_value != this.min_value || max_value != this.max_value)
		return (1);
	return (0);
  }
});


Nwc.Search = {
  "nb_request": 0,
  "form": null,
  "timer": null,
  go: function (elm) {
    if ($('info-nb-vehicle').innerHTML.length <= 6) {
      $('criteria-search').submit();
    }
  },
  gotoOffset: function (offset) {
    $('current_offset').value = $('offset').value = offset;
    Nwc.Search.reflow($("criteria-search"));
  },
  limit: function (select) {
    $('limit').value = $F(select);
    $('offset').value = 0;
    Nwc.Search.reflow($("criteria-search"));
  },
  orderBy: function (field) {
    if (field == $F('order_field')) {
      $('order').value = $F('order') == 'ASC' ? 'DESC' : 'ASC';
    } else {
      $('order_field').value = field;
    }
	if (field == "avantage" && $('by_avantage').hasClassName('asc') === false && $('by_avantage').hasClassName('desc') === false) {
		$('order').value = 'DESC';
	}
    Nwc.Search.reflow($("criteria-search"));
  },
  reflowCounter: function(event) {
    Nwc.Search.nb_request++;
    var container = $('found-vehicles').up();
    Nwc.Search.form = $('criteria-search');
    Nwc.Search.throbber = container.down('.throbber');
    Nwc.Search.throbber.setStyle({'width': container.getWidth() + 'px',
                                  'height': container.getHeight() + 'px'}).show();
    Kwo.exec(Nwc.Search.form.action, Nwc.Search.form, {'callback': Nwc.Search.reflowCounterCallback.curry(Nwc.Search.nb_request)});
  },
  reflowCounterCallback: function(request_id, t) {
    if (request_id != Nwc.Search.nb_request) {
      return;
    }
    Nwc.Search.throbber.hide();
    if (Kwo.hasError(t)) {
      $('info-nb-vehicle').update(t.result.msg);
      $('found-vehicles').update('--');
      return;
    }
    $('info-nb-vehicle').update("&nbsp;");
    $('found-vehicles').update(t.result.announces.pagination.found_rows);
  },
  reflow: function(form) {
    Nwc.Search.nb_request++;
    var container = $('results');
    Nwc.Search.throbber = container.down('.throbber');
    Nwc.Search.form = $(Object.isElement(form) ? form : this);
    Nwc.Search.form = Nwc.Search.form.match('form') ? Nwc.Search.form : Nwc.Search.form.up('form');
    Nwc.Search.throbber.setStyle({'width': container.getWidth() + 'px',
                                  'height': container.getHeight() + 'px'}).show();
    $('found-vehicles').update('--');
    Kwo.exec(Nwc.Search.form.readAttribute('action'), Nwc.Search.form, {'container': $('results'), 'callback': function () { $('offset').setValue(0); }});
  },
  updateFoundRows: function(count) {
    $('found-vehicles').update(count);
  }
}

Nwc.toggleTab = function(elm) {
  elm = $(elm);
  var tabs = elm.up('.tabs');
  var tab = elm.up('div');
  tab.adjacent('.tab').invoke('removeClassName', 'selected').invoke('addClassName', 'unselected');
  tab.removeClassName('unselected').addClassName('selected');
  if (elm.hasAttribute('action') && $(elm.id+'_container') == null) {
    var container = new Element('div');
    container.id = elm.id+'_container';
    container.addClassName('container').addClassName('padded').addClassName('grey-box');
    container.setStyle({'borderTop': '0 solid'});
    $('container').appendChild(container);
    container.adjacent('.container').each(Element.hide);
    Kwo.exec(elm.getAttribute('action'), null, {'container': container, 'callback': container.show});
  } else {
    var container = $(elm.id+'_container');
    container.adjacent('.container').each(Element.hide);
    container.show();
  }
  Kwo.go('#;' + elm.id);
}

Nwc.AutoPopulateSelect = {
  "attachEvent": function (master, slave, action, params, reset, opts) {
    params = params || {};
    opts = opts || {};
    var has_default = (typeof opts.default_value != 'undefined' && opts.default_value > 0)
      || (typeof opts.default_value == "string" && opts.default_value.length > 0);
    if (has_default) {
      $(master).up('div').addClassName('checked');
    }
    if (master) {
      master.selectedIndex = has_default && Object.isElement(master.down('option[value="' + opts.default_value + '"]')) ? master.down('option[value="' + opts.default_value + '"]').index : 0;
      master.observe('change', Nwc.AutoPopulateSelect.onChange.curry(master, slave, action, params, reset, opts));
    }
  },
  "onChange": function (master, slave, action, params, reset, opts, event) {
    if ($(master).value) $(master).up('div').addClassName('checked');
    else $(master).up('div').removeClassName('checked');
    params[master.name.replace(/\d+/, '')] = $F(event.element());
    if (opts.disable != false) {
      slave.up('form').disable();
    }
    var req_opts = {'callback': Nwc.AutoPopulateSelect.populate.curry(slave, opts.cb)};
    [slave, reset].each(function(node) {
      if (!Object.isElement(node)) {
        return;
      }
      node.up('div').removeClassName('checked');
      node.select('*').each(Element.remove);
      if (opts.no_first !== true) {
        var opt = new Element('option');
        opt.innerHTML = typeof opts.first == 'string' ? opts.first : 'Choisir...';
        node.appendChild(opt);
      }
    });
    if ($F(event.element()) < 1) {
      slave.up('form').enable();
      return;
    }
    Kwo.exec(action, params, req_opts);
  },
  "populate": function(elm, cb, res) {
    elm.up('form').enable();
    if  (res.error > 0) {
      Kwo.error(res);
      return;
    }
    if (res.result.length < 1) {
      return;
    }
    for (var k in res.result) {
      var opt = new Element('option');
      opt.value = k;
      opt.innerHTML = res.result[k];
      elm.appendChild(opt);
    };
    if (Object.isFunction(cb)) {
      cb(elm);
    }
  }
}

Nwc.Geoloc = {
  "updateZipCode": function (zip_elm, dst, callback) {
    if (typeof google == 'undefined'
        || typeof google.loader == 'undefined'
        || $F(zip_elm).length > 0) {
      if (typeof callback == 'function') {
        callback();
      }
      return;
    }
    var params = {'longitude': google.loader.ClientLocation.longitude,
                  'latitude': google.loader.ClientLocation.latitude,
                  'distance': dst > 0 ? dst : 100000000000,
                  'limit': Object.isElement($("showcases_box")) ? 4 : 1};
    var opts = {'callback': function(res) {
      if (res.result.zip_code > 0) {
        zip_elm.value = res.result.zip_code;
      }
      if (typeof callback == 'function') {
        callback();
      }
      if (Object.isElement($("showcases_box"))) {
        Nwc.Geoloc.updateBoxesCallback(res);
      }
    }};
    Kwo.exec('/showcase.nearest', params, opts);
  },
  "updateBoxes" : function() {
    var opts = {'limit': 4, 'zip_code': $F('zip_code')};
    Kwo.exec('/showcases.nearest', opts, {'callback': Nwc.Geoloc.updateBoxesCallback});
  },
  "updateBoxesCallback" : function(res) {
    $('showcases_box').update('');
    if ('showcases' in res.result) {
      res.result.showcases.collection.each(function(showcase) {
        $('showcases_box').insert({'bottom': showcase.box});
      });
    }
  }
}

Nwc.Map = Class.create({
  infoWindow: null,
  map: null,
  markers: null,
  streetView:false,
  streetControl:null,
  
  initialize: function(map, opts) {
    var opts = typeof opts != 'undefined' ? opts : {};
    var zoom = typeof opts.zoom == 'number' ? opts.zoom : 5;
    this.markers = [];
	if (opts.streetView != undefined) {
		this.streetView = true;
		this.streetControl = opts.streetView;
	}
    this.infoWindow = new google.maps.InfoWindow;
    this.map = new google.maps.Map($(map), {
      center: new google.maps.LatLng(48, 2),
      zoom: zoom,
      mapTypeId: 'roadmap',
	  streetViewControl: this.streetView
    });
	
    google.maps.event.addListener(this.map, 'zoom_changed', function(map) {
      if (map.getZoom() < 5 ) {
        map.setZoom(5);
      }
    }.curry(this.map));
  },
  
  addMarker: function(data, streetView) {
    var point = new google.maps.LatLng(
      parseFloat(data.latitude),
      parseFloat(data.longitude));
    var html = data.address;
    var marker = new google.maps.Marker({
      map: this.map,
      position: point,
      icon: data.icon,
      shadow: data.shadow
    });
    marker.data = data;
    this.markers.push(marker);
	
	if (this.streetView === true) {
		var panoramaOptions = { position:point, pov: { heading: 0, pitch: 10, zoom: 1 } };
		var panorama = new google.maps.StreetViewPanorama(document.getElementById(this.streetControl), panoramaOptions);
		this.map.setStreetView(panorama);
		this.streetView = null;
	}
	
    this.bindInfoWindow(marker, this.map, this.infoWindow, html);
  },
  
  bindInfoWindow: function(marker, map, infoWindow, html) {
    google.maps.event.addListener(marker, 'click', function() {
      infoWindow.close();
      infoWindow.setContent(html);
      infoWindow.open(map, marker);
    });
  }
});

Nwc.Showcase = {
  onSubmit: Prototype.emptyFunction,
  localize: function (params, opts, event) {
    if (!Object.isUndefined(event) && "stop" in event && Object.isFunction(event.stop)) {
      event.stop();
    }
    if (Object.isNumber(opts)) {
      $('offset').value = opts;
      opts = {};
    } else {
      if (Object.isElement($('offset'))) {
        $('offset').value = 0;
      }
      if (!Object.isUndefined(opts) && 'type' in opts && opts.type != "change") {
        return;
      }
    }
    if ('match' in params && params.match('form')) {
      if ($F(params.zip_code) == ''
          || $F(params.make_id) < 1) {
        $('infos').update('Vous devez choisir un code postal et une marque');
        return;
      }
      $('infos').update('');
    }
    var opts = typeof opts != 'undefined' ? opts : {};
    Kwo.exec('/showcases.json', params, {'callback': Nwc.Showcase.localizeCallback.curry(new Nwc.Map('map', opts), opts), 'disable': true});
  },
  localizeCallback: function (map, opts, res) {
    map.markers.invoke('set_map', null);
    map.infoWindow.close();
    res.result.showcases.collection.each(map.addMarker.bind(map));
    if ($('container')) {
      $('container').update('');
      res.result.showcases.collection.each(Nwc.Showcase.appendShowcaseWidget);
      if ($('nbr_result')) {
        $('nbr_result').update(res.result.showcases.pagination.found_rows);
      }
      if ($('make_result')) {
        if ($('makes') && $F('makes') != '') {
          $('make_result').update($('makes').options[$('makes').selectedIndex].innerHTML);
        } else {
          $('make_result').update('');
        }
      }
      if (false && $('zip_code_result')) {
        if ($('zip_code') && $F('zip_code').length > 0) {
          $('zip_code_result').update('dans le ' + $F('zip_code'));
        } else {
          $('zip_code_result').update('');
        }
      }
    }
    if (map.markers.length > 0) {
      var mapbounds = new google.maps.LatLngBounds();
      var extended = false;
      map.markers.each(function(marker) {
        extended = true;
        mapbounds.extend(marker.position);
      });
      if (extended) {
        map.map.fitBounds(mapbounds);
      }
    }
    if (Object.isElement($('showcases_pagination-top'))) {
      $('showcases_pagination-top').update(res.result.pagination);
    }
    if (Object.isElement($('showcases_pagination-bottom'))) {
      $('showcases_pagination-bottom').update(res.result.pagination);
    }
    if (typeof opts.zoom == 'number') {
      setTimeout(function () { map.map.setZoom(opts.zoom); }, 100);
    }
  },
  appendShowcaseWidget: function(item) {
    $('container').insert({'bottom': item.widget});
  },
  openShowcase: function (url, title) {
    var screenWidth = window.screen.width;
    var width = 1100;
    var left = 0;
    if (screenWidth < width) {
      width = screenWidth;
    } else {
      left = (window.screen.width - width) / 2;
    }
	window.open(url, title.replace(/[\W]+/gi, ''), 'status=yes,menubar=yes,toolbar=yes,location=yes,scrollbars=yes,resizable=yes,width='+width+',left='+left);
  },
  "store": function(args){
     Kwo.exec('/account/nwc/showcase.store', args, {'callback': function(res){
       if  (res.error > 0) {
         Kwo.warn(res);
         return;
       }
       alert(res.result.msg);
     }});
  },
  toggleShowcase: function(elt){
     Kwo.exec('/account/nwc/showcases.toggle', {'showcase_id' : $(elt).value }, {'callback': function(res){
       if (res.error > 0) {
         Kwo.error(res);
         return;
       }
       if ($(document.body).hasClassName('action-announce-edit')
           && location.href.match('announce_id')) {
         Kwo.go('/account/nwc/account.pro');
       } else {
         Kwo.reload();
       }
     }});
  },
  "contact": function (args) {
    Kwo.exec(args.action, args, {disable:true, callback: function (res) {
      if  (res.error > 0) {
        Kwo.error(res);
        return;
      }
      Kwo.warn(res);
      Kwo.reload();
    }});
  }
}

Nwc.Vehicle = {
  comparison: function (event) {
    if ($F(event.element()) == '') {
      return;
    } else {
      $(event.element()).up('div').addClassName('checked');
    }
    var form = $(event.element()).up('form');
    var container = $('results');
    var throbber = container.down('.throbber');
    if (Object.isElement(throbber)) {
      throbber.setStyle({'width': container.getWidth() + 'px',
                         'height': container.getHeight() + 'px'}).show();
    }
    var i = 0;
    $$('.tabs .tab').each(function (node) {
      if (node.hasClassName('selected')) {
        form.down('input[name="tab_selected"]').value = i;
      }
      ++i;
    });
    var opts = {'container': container, 'disabled': true, 'callback': Nwc.Vehicle.comparisonCallback.curry(throbber)};
    Kwo.exec(form.action, form, opts);
  },
  comparisonCallback: function(throbber, tab) {
    if (Object.isElement(throbber)) {
      throbber.hide();
    }
  },
  go: function () {
    if (!$F('vehicles')) {
      return;
    }
    $('chooser').submit();
  },
  updatePrice: function (element, price) {
    var price_elms = price ? $$(price) : [$('vehicle_price')];
    var price = parseInt(price_elms[0].innerHTML.replace(/[^\d]/g, ''));
    if (element.checked) {
      price += parseInt($F(element));
    } else {
      price -= parseInt($(element).value);
    }
    price_elms.each(function(node) { node.innerHTML = Number(price).format(0, ',', ' ') + ' €' });
  }
}

Nwc.Remise = {

	"applyModel": function(el) {
		if ($('carmodel_model').value == "")
			return (alert('Choisissez un modèle'));
		if ($('remise_model').value == "" && $('aide_model').value == "")
			return (alert('Précisez la valeur de la remise'));
		Nwc.Remise.apply(el);
	},
	
	"applyAnnounce": function(el) {
		if ($('vin').value == "")
			return (alert('Entrez un VIN'));
		if ($('remise_announce').value == "" && $('aide_announce').value == "")
			return (alert('Précisez la valeur de la remise'));	
		Nwc.Remise.apply(el);
	},

	"applyVersion": function(el) {
		if ($('vehicles').value == "")
			return (alert('Choisissez une version'));
		if ($('remise_version').value == "" && $('aide_version').value == "")
			return (alert('Précisez la valeur de la remise'));
		Nwc.Remise.apply(el);
	},
	
	"apply": function(el) {
		Kwo.exec('/account/nwc/announce.remise-apply', el, {'callback': function(res){
				if (res.error > 0) {
					Kwo.error(res);
					return;
				}
				alert('Remise confirmée');
			}
		});
	}
}

Nwc.Announce = {
  "pe": null,
  "updatePrice": function (){
    var options_price = 0;
    $('_option').select('li').each(function (optn) {
      options_price += Number(optn.readAttribute('price'));
    });
    if ($('trim').select('option').length > 0 && $F('include_trim_price') < 1) { 
      options_price += Number($('trim').down('option', $('trim').selectedIndex).readAttribute('price'));
    }
    if ($('colour').select('option').length > 0 && $F('include_colour_price') < 1) {
      options_price += Number($('colour').down('option', $('colour').selectedIndex).readAttribute('price'));
    }
    $('catalog_price').value = Number($F('base_price')) + options_price;
    $('price').value = Number($F('catalog_price')) + Number($F('eco_bonus')) - $F('customer_bonus');
    Nwc.Announce.updateCustomerBonus();
    Nwc.Announce.updateRepriseBonus();
  },
  "onVehicleChange": function(elm) {
    var form = elm.up('form');
    $('search').value = '';
    ['trim', 'colour', 'option'].each (function(action) {
      var elm = action == 'option' ? $('option') : form['record['+action + '_id]'];
      elm.select('*').each(Element.remove);
      if (action == 'option') {
        $('_option').select('*').each(Element.remove);
      } else {
        elm.insert((new Element('option')).update('Choisir...'));
      }
      Kwo.exec('/account/nwc/'+action+'s', form, {'callback': Nwc.Announce.onVehicleChangeCallback.curry(elm, form)});
    });
    Kwo.exec('/account/nwc/price', {'vehicle_id' : form['record[vehicle_id]'].value}, {'callback': function(res) {
      form.enable();
      var eco_label = $('eco_bonus').adjacent('label[for="eco_bonus"]')[0];
      if (res['result']['eco_bonus'] > 0) {
        $(form['record[eco_bonus]']).removeClassName('green');
        $(form['record[eco_bonus]']).addClassName('rouge');
        eco_label.innerHTML = eco_label.innerHTML.replace('Bonus', 'Malus');
      } else {
        $(form['record[eco_bonus]']).removeClassName('rouge');
        $(form['record[eco_bonus]']).addClassName('green');
        res['result']['eco_bonus'] = res['result']['eco_bonus'];
        eco_label.innerHTML = eco_label.innerHTML.replace('Malus', 'Bonus');
      }
      form['record[eco_bonus]'].value = res['result']['eco_bonus'];
      $('base_price').value = Math.round(res['result']['catalog_price']);
      Nwc.Announce.updatePrice();
    }});
    form.disable();
  },
  "onVehicleChangeCallback": function(elm, form, res) {
    form.enable();
    if (res.error > 0) {
      Kwo.error(res);
      return;
    }
    for (var k in res.result) {
      if (isNaN(k)) {
        continue;
      }
      var opt;
      if (elm.id == 'option') {
        opt = new Element('li');
        opt.writeAttribute('data', res.result[k].id);
      } else {
        opt = new Element('option');
        opt.writeAttribute('value', res.result[k].id);
      }
      opt.writeAttribute('title', res.result[k].name.toLowerCase());
      opt.writeAttribute('price', res.result[k].price);
      elm.appendChild(opt.update(res.result[k].name));
    };
    //Nwc.Announce.updatePrice();
    //Nwc.Announce.updateCustomerBonus();
  },
  "addOption": function(event) {
    var from = $('option'),
    to = $('_option');
    if (typeof event != 'undefined' && event.type == 'keypress') {
      if (event.target.id == 'option' && event.keyCode != Event.KEY_RETURN) {
        return;
      }
      event.stop();
    }
    if (event && 'target' in event && from.select('li.highlighted').length == 0) {
      from = $('optionCustomised');
    }
    if (from.id == 'optionCustomised') {
      var options = $F(from).split("\n");
    } else {
      var options = from.select('li.highlighted');
    }
    options.each(function(el){
      if (from.id == 'optionCustomised') {
        if (el.blank()) return;
        var optionCustom = new Element('li', {'title': el.toLowerCase(), 'price':0, 'data': el.toLowerCase()});
        optionCustom.update(el);
        to.appendChild(optionCustom);
        return;
      }
      var optn = el.cloneNode(true);
      optn.removeClassName('highlighted');
      if ($(to).select('li[data="'+optn.readAttribute('data')+'"]').length == 0) {
        $(to).appendChild(optn);
      }
      el.remove();
      Nwc.Announce.updatePrice();
    });
    if (from.id == 'optionCustomised') {
      $('optionCustomised').clear();
    }
  },
  "removeOption": function(event) {
    var from = $('_option'),
    to = $('option');
    if (typeof event != 'undefined' && event.type == 'keypress') {
      if (event.target.id == '_option' && event.keyCode != Event.KEY_DELETE) {
        return;
      }
      event.stop();
    }
    var options = from.select('li.highlighted');
    options.each(function(el){
      var optn = el.cloneNode(true);
      optn.removeClassName('highlighted');
      if ($(to).select('li[data="'+optn.readAttribute('data')+'"]').length == 0
          && optn.hasAttribute('data')) {
        $(to).appendChild(optn);
      }
      el.remove();
      Nwc.Announce.updatePrice();
    });
  },
  "updateCustomerBonus": function (){
    var customer_bonus = Number($F('customer_bonus'));
    if (customer_bonus > 0 ) $('customer_bonus_percent').update( Math.round(customer_bonus/ Number($F('catalog_price')) * 10000) / 100  + ' %');
    else $('customer_bonus_percent').update( '0 %');
  },
  "updateRepriseBonus": function (){
    var customer_bonus = Number($F('reprise_bonus'));
    if (customer_bonus > 0 ) $('reprise_bonus_percent').update( Math.round(customer_bonus/ Number($F('catalog_price')) * 10000) / 100  + ' %');
    else $('reprise_bonus_percent').update( '0 %');
  },
  "store": function(args){
    if (!$(args).match('form')) {
      args = args.up('form');
    }
    args = args.serialize(true);
    var i = 0;
    if ($('_option')) $('_option').select('li').each(function (node) {
      if (!node.readAttribute('data').blank()) {
        args['record[options]['+(i++)+']'] = node.readAttribute('data');
      }
    });
    Kwo.exec('/account/nwc/announce.store', args, {'callback': function(res){
      if (res.error > 0) {
        Kwo.error(res);
        return;
      }
      alert(res.result.msg);
      if (res.result.id > 0) {
        if (res.result.duplicate_announce_id > 0) {
          Kwo.go('/account/nwc/announce.edit/-/announce_id/' + res.result.id);
          return;
        }
        Kwo.go('/account/nwc/account.pro', null);
      } else {
        document.location.href = '#code';
        $('code').value = '';
        $('code').focus();
      }
    }});
  },
  "remove" : function(id) {
     Kwo.exec("/account/nwc/announce.delete", {'announce_id' : id}, 
               {'callback': Kwo.go.curry('/account/nwc/announces.account.pro'), 'confirm':true});
  },
  "activate" : function(id) {
    Kwo.exec("/account/nwc/announce.activate", {'announce_id' : id},  {callback: Nwc.Announce.activateCallback , confirm:true});
  },
  "activateCallback": function (res) {
    if (res.error > 0) {
      Kwo.warn(res.result.msg.join(".\n"));
      return;
    }
    Kwo.go('/account/nwc/announces.account.pro');
  },
  "duplicate" : function(id) {
     new Kwo.Dialog('/account/nwc/announce.duplicate' ,{'announce_id' : id}, {"height": 180});   
  },
  "optionsSearch": function (event) {
    if (Nwc.Announce.pe !== null) {
      Nwc.Announce.pe.stop();
    }
    Nwc.Announce.pe = new PeriodicalExecuter(function () { 
      this.stop();
      $$('#option li').invoke('removeClassName', 'highlighted');
      if ($F(event.target) == '') {
        query = 'li';
      } else {
        query = 'li[title*="'+$F(event.target).toLowerCase()+'"]';
      }
      console.log(query);
      $$('#option ' + query).invoke('removeClassName', 'hidden');
      $$('#option :not(' + query + ')').invoke('addClassName', 'hidden');
    }, 0.1);
  }
}

Nwc.Selection = {
  "offset": 0,
  "next": function (link) {
    if (Nwc.Selection.offset > 1) {
      return;
    }
    Nwc.Selection.offset++;
    $('box_left').select(".announce").each(Element.hide);
    for (var i = 0; i < 3; ++i) {
      if ($('box_left').down(".announce", Nwc.Selection.offset*3 + i)) {
        $('box_left').down(".announce", Nwc.Selection.offset*3 + i).show();
      }
    }
    if (Nwc.Selection.offset == 2) {
      $(link).addClassName('disable');
    }
    if (Nwc.Selection.offset == 1) {
      $(link).adjacent('a')[0].removeClassName('disable');
    }
  },
  "prev": function (link) {
    if (Nwc.Selection.offset < 1) {
      return;
    }
    Nwc.Selection.offset--;
    $('box_left').select(".announce").each(Element.hide);
    for (var i = 0; i < 3; ++i) {
      if ($('box_left').down(".announce", Nwc.Selection.offset*3 + i)) {
        $('box_left').down(".announce", Nwc.Selection.offset*3 + i).show();
      }
    }
    if (Nwc.Selection.offset == 0) {
      $(link).addClassName('disable');
    }
    if (Nwc.Selection.offset == 1) {
      $(link).adjacent('a')[0].removeClassName('disable');
    }
  },
  "remove": function (announce_id) {
    var args = {"announce_id" : announce_id};
    Kwo.exec('/selection.remove', args, {callback: Kwo.reload, disabled: true});
  },
  "set": function (elm, event) {
    if (!Object.isUndefined(event) && 'stop' in event) {
      event.stop();
    }
    var args = elm;
    if (elm.type == 'checkbox') {
      elm.check(true);
      args = {"announces[]": $F(elm)};
    }
    Kwo.exec('/selection.set', args, {callback: Nwc.Selection.setCallback.curry(elm), disabled: true});
    return false;
  },
  "setCallback": function (input, res) {
    if (res.error > 0) {
      Kwo.warn(res.result.msg.join(".\n"));
      if (Object.isElement(input)) {
        input.check(false);
      }
      return;
    }
    if (Object.isElement(input) && input.match('input[name="announces[]"]')) {
      input.adjacent('.saved-img')[0][(input.checked ? 'show' : 'hide')]();
    }
    if (Object.isElement($('selection-widget'))) {
      Kwo.exec('/selection.widget', {}, {container: $('selection-widget')});
    }
    if (Object.isElement($('offset'))) {
      $('offset').value = $F('current_offset');
    }
    var callback = Object.isElement($('criteria-search')) ? Nwc.Search.reflow.curry($('criteria-search')) : Prototype.emptyFunction;
    if (typeof res.result.msg == 'string') {
      var diag = new Kwo.Dialog;
      diag.callback = callback;
      diag.support.update('<div class="padded">' + res.result.msg + '<a href="javascript:void(0);" onclick="Kwo.getDialog().apply()" class="orange-button align-right">Fermer</a></div>');
    } else {
      callback();
    }
  }
}

Nwc.Stock = {
  "add": function (args, redirect) {
    Kwo.exec('/stock.add', args, {callback: Nwc.Stock.onAddStockCallback.curry(redirect), disabled: true});
  },
  "onAddStockCallback": function (redirect, res) {
    if (res.error > 0) {
      Kwo.error(res);
      return;
    }
    Kwo.warn(res);
    if (redirect) {
      if (_user_id > 0) {
        Kwo.go('/account/nwc/account.public#;mes-alertes-stock');
      } else {
        Kwo.go('/signup?stock');
      }
    }
  },
  "remove": function (args) {
    if (!args.match('form')) {
      args = args.up('form');
    }
    Kwo.exec('/account/nwc/stock.remove', args, {callback: Nwc.Stock.onRemoveStockCallback, disabled: true});
  },
  "onRemoveStockCallback": function (res) {
    if (res.error > 0) {
      Kwo.error(res);return;
    }
    Kwo.reload();
  },
  "view": function () {
    $('stocks').submit();
  }
}

Nwc.Option = {
  "check": function (elm, type, prefix, price_target) {
    if (!elm.match('form')) {
      elm = elm.up('form');
    }
    function getSelected (elm) {
      if (!('checked' in elm) || !elm.checked) {
        return;
      }
      elm = $(prefix + $F(elm));
      if (!elm.checked && (type != 'exclude' && type != 'include')
          || elm.checked && (type == 'exclude' || type == 'include')) {
        elm.check(type != 'exclude' && type != 'include');
        Nwc.Vehicle.updatePrice(elm, price_target);
        Nwc.Option.checkAssociation(prefix, price_target, elm);
      }
    }
    elm.select('input[type="radio"][name^="'+type+'-"]').each(getSelected);
    Kwo.getDialog().close();
  },
  "checkAssociation": function () {
    var prefix = 'option-';
    var target = null;
    var price_target = null;
    var caller = null;
    if (Object.isString(arguments[0])) { 
      prefix = arguments[0];
      price_target = arguments[1];
      target = Object.isElement(arguments[2]) ? arguments[2] : $(arguments[2].target); 
      caller = Object.isElement(arguments[3]) ? arguments[3] : null; 
    } else {
      target = Object.isElement(arguments[0]) ? arguments[0] : $(arguments[0].target);
    }
    if (!target.match('label') && !target.match('input[type="checkbox"]')) {
      (Object.isString(arguments[0]) && !Object.isElement(arguments[2]) ? arguments[2] : arguments[0]).stop();
      if (!Object.isElement(arguments[0])
          && typeof event != 'undefined'
          && "stop" in event) {
        event.stop();
      }
      return;
    }
    if (target.match('label')) {
      target = $(target.readAttribute('for'));
    }
    if (target == null || !('checked' in target) || !target.checked) {
      return;
    }
    var no_selected;
    Nwc.Option.checkProperties(target, prefix, price_target);
    function checkIncludeOptionChecked(node) {
      if ('checked' in node && node.checked) {
        no_selected = false;
      }
    }
    function checkCondition(type, cond) {
      if (cond == '') {
        return;
      }
      if (cond.substr(0,2) == 'or') {
        var ids = cond.substr(3).split(' ');
        if (Object.isElement(caller)) {
          var caller_id = caller.readAttribute('id');
          for (var k = 0, l = ids.length; k < l; ++k) {
            if (prefix + ids[k] == caller_id) {
              delete ids[k];
            }
          }
        }
        var options = $$('input[id="' + prefix + ids.join('"], input[id="' + prefix) + '"]');
        if (options.length < 1) {
          return;
        }
        no_selected = true;
        if (options.length == 1) {
          options[0].check(type != 'exclude' && type != 'include');
          Nwc.Vehicle.updatePrice(options[0], price_target);
          Nwc.Option.checkAssociation(prefix, price_target, options[0], target);
          return;
        } else {
          options.each(checkIncludeOptionChecked);
        }
        if (no_selected) {
          (new Kwo.Dialog('/options.chooser', {'type': type, 'options': cond.substr(3), 'target': target.id, 'prefix': prefix, 'price_target': price_target}, {'name': 'dialog-'+Math.round(Math.random() * 100000)}));
        }
      } else {
        var query = 'input[id="' + prefix + cond.substr(4).split(' ').join('"], input[id="' + prefix) + '"]';
        var options = $$(query);
        if (options.length < 1) {
          return;
        }
        options.each(function(node) {
          if (node.checked != (type != 'exclude' && type != 'include')) {
            node.check(type != 'exclude' && type != 'include');
            Nwc.Vehicle.updatePrice(node, price_target);
            Nwc.Option.checkAssociation(prefix, price_target, node);
          }
        });
      }
    }
    function checkAttribute(type) {
      var attribute = target.readAttribute(type);
      attribute.split('|').each(checkCondition.curry(type));
    }
    ['include', 'require', 'exclude'].each(checkAttribute);
  },
  "checkProperty": function(elm, prefix, price_target, prop) {
    var options = $$('input[type="checkbox"][id^="' + prefix + '"][properties~="' + prop + '"]:not([id="' + elm.id  + '"]):not([include~="' + elm.id.replace(prefix, '') + '"]):not([require~="' + elm.id.replace(prefix, '') + '"])');
    if (options.length == 0) {
      return;
    }
    options.each(function(opt) {
      if (opt.checked) {
        opt.check(false);
        Nwc.Vehicle.updatePrice(opt, price_target);
      }
    });
  },
  "checkProperties": function(elm, prefix, price_target) {
    var properties = elm.getAttribute('properties').split(' ');
    properties.each(Nwc.Option.checkProperty.curry(elm, prefix, price_target));
  }
}

Nwc.init = function() {
  if (Prototype.Browser.IE) {
    var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, "");
    if (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) < 7) {
      $$(".trans").each(Nwc.display.alphaBackgrounds);
    }
  }
}

Nwc.statistics = {
  "showGraph": function (el, type){
    $('period-selector').select('a').invoke('removeClassName', 'selected');
    $('preriod-graph').select('img').invoke('hide');
    $(el).addClassName('selected');
    $(type+'-graph').show();
  }
}

Nwc.display = {
  "alphaBackgrounds" : function (e) {
    var bg = e.currentStyle.backgroundImage;
    if (bg.match(/\.png/i) != null) { 
      var mypng = bg.substring(5,bg.length-2);
      e.setStyle({  
        filter : "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + mypng + "', sizingMethod='" + (e.currentStyle.backgroundRepeat == "no-repeat" ? "crop" : "scale") + "')",
        backgroundImage : "none"}); 
    }
  },
  "textLineFeed" : function (text, max) {
    interval = max-10;
    _return = '';
    if (text.length < max) return text;
    while (text.length > 0) {
      pos = text.substr(interval,text.length - interval).indexOf(' ') + interval;
      _return += text.substr(0,pos)+' <br/> \n';
      text = text.substr(pos+1,text.length-pos);
      if (text.length < max) {
        _return += text;
        text     = '';
      }
    }
    return _return;
  },
  "enlargeSelect" : function (size, event) {
    elt = $(event.target);
    if (elt.length < 2) return;
    elt.absolutize();
    elt.activate();
    elt.setStyle({height:'1.5em', width:size+'px', zIndex:10});
  
  },
  "reduceSelect" : function (size, event) {
    elt = $(event.target);
    if (elt.length < 2) return;
    elt.setStyle({width:size+'px', zIndex:1});
    elt.relativize();
  }
}

document.observe('dom:loaded', Nwc.init);

Number.prototype.format = function (decimals, dec_point, thousands_sep) {
  var n = this, prec = decimals;
 
  var toFixedFix = function (n,prec) {
    var k = Math.pow(10,prec);
    return (Math.round(n*k)/k).toString();
  };
 
  n = !isFinite(+n) ? 0 : +n;
  prec = !isFinite(+prec) ? 0 : Math.abs(prec);
  var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
  var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
  var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
  var abs = toFixedFix(Math.abs(n), prec);
  var _, i;
 
  if (abs >= 1000) {
    _ = abs.split(/\D/);
    i = _[0].length % 3 || 3;
 
    _[0] = s.slice(0,i + (n < 0)) +
      _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
    s = _.join(dec);
  } else {
    s = s.replace('.', dec);
  }
 
  var decPos = s.indexOf(dec);
  if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
    s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
  }
  else if (prec >= 1 && decPos === -1) {
    s += dec+new Array(prec).join(0)+'0';
  }
  return s;
}

Element.addMethods({'check': function (elm, value) {
  if (elm.readAttribute("type") != 'checkbox') {
    return elm;
  }
  value =  value == true || value == 'checked' ? true : false;
  elm.writeAttribute('checked', value);
  elm.checked = value;
  return elm;
}});
