// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function changeEnableDisableIcon(link) {
  link.select('img').invoke('toggle');
  link.up(1).select('.explain').invoke('toggle');
}

Event.addBehavior({
  '#colores': Remote.Links,
  '#color_sizes': Remote.Links,
  '#color_images': Controls.ChangeImage,
  '#zoomControls a': Controls.ImgZoom({
    containerStyle: {width: '427px', height: '427px'},
    image: 'card_image',
    remove_from_src: '_card',
    clickCallback: changeEnableDisableIcon
  }),
  '.contenido_motillo .button-to': Remote,
  '#papelera_motillo': Controls.Droppable({accept: 'linea_motillo', onDrop: remove_on_drop}),
  '.product_image': Controls.Draggable({revert: true}),
  '#motillo': Controls.Droppable({accept: 'product_image', onDrop: buy_on_drop}),
  '.columna_tracking2': Remote.Links
});
var behavior_buy = {
  '#reference_description .button-to': Remote
};
var behavior_motorbikey = {
  '#lineas_motillo .boton_eliminar form': Remote,
  '#lineas_motillo .linea_motillo': Controls.Draggable({revert: 'failure'}),
  '#lineas_motillo .unidades_motillo': Controls.InPlaceEditor({
    ajaxOptions: {method: 'put'},
    htmlResponse: false,
    cancelControl: false,
    cols: 3,
    externalControl: 'this.element.id.replace(/^.*_(\\d+)$/, "cantidad_$1")',
    clickToEditText: 'Pulsa para editar',
    savingText: 'Guardando...'
  })
};

Event.addBehavior(behavior_buy);
Event.addBehavior(behavior_motorbikey);

function remove_on_drop(draggable, droppable, event) {
  var button = draggable.select('input[type=image]')[0];
  var behavior = new Remote.Form(button.form);
  Remote.Form.prototype.onsubmit.apply(behavior);
  delete behavior;
  return true;
}

function buy_on_drop(draggable, droppable, event) {
  var form = $$('#reference_description .button-to')[0];
  new Ajax.Request(form.action, {method: 'post', postBody: Form.serialize(form)});
  return true;
}

function navigatorWithJS(form) {
  var options = form.down().childElements();
  var text = new Element('span', {'class': 'arial11boldnegra'}).update(options.shift().text + '&nbsp;');
  var link = new Element('a', {href: '#'}).update(new Element('img', {src: '/images/imgs/desplegable.gif', alt: 'desplegable'}));
  form.insert({after: link});
  form.insert({after: text});
  
  var div = new Element('div', {'class': 'float_navigator'});
  options.each(function(option) {
    var item = new Element('a', {href: form.action + '/' + option.value}).update(option.text);
    div.insert(item).insert(new Element('br'));
  });
  form.up().insert(div);
  form.remove();
  
  div.absolutize().hide().clonePosition(text.previous(), {setHeight: false, setWidth: false, offsetTop: 20});
  link.observe('click', function(event) {
    if (this.hideDiv) Effect.SlideUp(div, {queue: {position: 'end', scope: 'navigator'}});
    else Effect.SlideDown(div, {queue: {position: 'end', scope: 'navigator'}});
    this.hideDiv = !this.hideDiv;
  });
}

function flashMessage() {
  var message = $('flash_message');
  if (message.childElements().length > 0) {
    inmediateLightWindow.activateWindow({href: '#flash_message', type: 'inline'});
    $('flash_message').remove();
  }
}

Event.onReady(function() {
  $('navigator').select('form.form_navigator').each(navigatorWithJS);

  var zoomControls = $('zoomControls');
  if (zoomControls) {
    zoomControls.down('img').next().hide();
    zoomControls.down('.explain').next().hide();
    if ($('card_image').src.indexOf('/no_disponible.gif?') == -1) zoomControls.show();
  }

  var formalizar = $('formalizar_compra');
  if (formalizar) {
    formalizar.observe('submit', function(event) {
      event.stop();
      myLightWindow.activateWindow({href: this.action + '?' + Form.serialize(this)});
    });
  }

  var globalHandlers = {
    onCreate: function() {
      var item = $('loader');
      if (!item.visible()) {
        var size = item.getDimensions();
        var dim = document.viewport.getDimensions();
        item.style.left = (dim.width - size.width)/2 + "px";
        item.style.top = (dim.height - size.height)/2 + "px";
        if (item.getStyle('position') == 'absolute') {
          var offsets = document.viewport.getScrollOffsets();
          item.style.left = parseInt(item.style.left) + offsets.left + "px";
          item.style.top = parseInt(item.style.top) + offsets.top + "px";
        }
      }
      item.show();
    },
    onComplete: function() {
      if(Ajax.activeRequestCount == 0){
        Element.hide('loader');
      }
    }
  };
  Ajax.Responders.register(globalHandlers);
});
Event.observe(window, 'load', function() {
  inmediateLightWindow = new lightwindow({
    animationHandler: function() { $('lightwindow_loading').hide(); },
    classNames: {
      standard: 'inmediate_lightwindow',
      action: 'inmediate_lightwindow_action'
    }
  });
  flashMessage();
  if ($('banner_promotion') && $('banner_promotion').down()) {
    window.promotion_updater = new PeriodicalExecuter(function(pe) {
      var promotion_id = $('banner_promotion').down().id.replace(/^promotion_/, '');
      new Ajax.Request('/random_promotion', {parameters: "id=" + promotion_id, method: 'get',
        onCreate: function() { if (Ajax.activeRequestCount == 0) Element.hide.defer('loader'); }
      });
    }, 10);
  }
});
