/*************************************************************
Damien Benier for iShopYouShop.com
*************************************************************/

Event.observe(document, 'dom:loaded', initializeMyForm, false);

var MyForm = new Object();

MyForm.showBubble = function(content, htmlElt, options)
{
  if (!$('formBubble') || !content) return;
  var options = Object.extend({setWidth:false, setHeight:false, offsetLeft:132, offsetTop:-91}, options || { });
  
  $('formBubble').clonePosition(htmlElt, options);
  $('formBubbleContent').innerHTML = content;
  $('formBubble').show();
}

MyForm.hideBubble = function()
{
  if (!$('formBubble')) return;
  $('formBubble').hide();
}

MyForm.showBubbleAt = function(content, x, y)
{
  $('formBubble').style.left = x + 'px';
  $('formBubble').style.top = y + 'px';
  $('formBubbleContent').innerHTML = content;
  $('formBubble').show();
}

/* Helper for adding an Option to select a object */
function addOptionToSelect(htmlElt, text, value, selected, index)
{
  var option = document.createElement('option');
  option.value = value;
  option.text = text;
  try { htmlElt.add(option, null); }
  catch(e) { htmlElt.add(option); }
}

/**************** Product picker stuff ****************/
ProductPicker = Class.create();
Object.extend(ProductPicker.prototype, {
  
  initialize: function(resultInputId, options){
    this.options = Object.extend({defaultProductId:0, defaultProductName:'', defaultProductImage:'', showSearch:true, showLists:true, callback:null, panelStyle:''}, options);
    this.resultInput = $(resultInputId);
    this.resultInput.productPicker = this;
    this.product = {};
    this.select(this.options.defaultProductId, this.options.defaultProductName, this.options.defaultProductImage);
  },
  
  select: function(productId, productName, productImage)
  {
    this.product = {id:productId, name:productName, image:productImage};
    
    this.resultInput.value = productId;
    
    this.hide();
    
    return false;
  },
  
  show: function()
  {
    var args = {};
    args.push('callback=' + encodeURIComponent('$("' + this.resultInput.id + '").productPicker.select'));
    if (this.product.name) args.push('name=' + encodeURIComponent(name));
    if (!this.options.showSearch) args.push('nosearch=1');
    if (!this.options.showLists)  args.push('nolists=1');
    
    lightbox.show(productPickerUrl + '?' + args.implode('&'));
  },
  
  hide: function()
  {
    if (lightbox.target.startsWith(productPickerUrl)) lightbox.hide();
    if (this.options.callback) this.options.callback(this.product);
    
    return false;
  }
});

/**************** Categories picker stuff ****************/
CategoryPicker = Class.create();
Object.extend(CategoryPicker.prototype, {

  ALL_CATEGORIES: '[toutes les catégories]',
  ALL_SUBCATEGORIES: '[toutes les sous-catégories]',
  INTRODUCTION_TEXT: 'Veuillez sélectionner une catégorie...',
  
  initialize: function(resultInputId, options){
    this.options = Object.extend({categoryInputId:'', subcategoryInputId:'', defaultCategoryId:0, defaultSubcategoryId:0, allowAll:false, callback:null, panelStyle:''}, options);
    this.resultInput = $(resultInputId);
    this.resultInput.categoryPicker = this;
    this.resultInput.onclick = function(resultInput){ this.categoryPicker.show(); };
    this.resultInput.onfocus = this.resultInput.onclick;
    
    var panelHTML = '<div style="position: relative;"><div id="' + this.resultInput.id + 'Panel" class="categoryPickerPanel" style="display:none;' + this.options.panelStyle + '"></div></div>'
    this.resultInput.insert({before:panelHTML});
    this.displayPanel = $(this.resultInput.id + 'Panel');
    
    var _this = this;
    document.executeOnceLoaded(function(){ _this.select(_this.options.defaultCategoryId, _this.options.defaultSubcategoryId); });
  },
  
  select: function(categoryId, subcategoryId)
  {
    this.categoryId =    categoryId;
    this.subcategoryId = subcategoryId;
    
    var category =    categories[this.categoryId];
    var subcategory = subcategories[this.subcategoryId];
    
    var text = '';
    if (!categoryId)         text = '';
    else if (!subcategoryId) text = category.name;
    else                     text = category.name + ' > ' + subcategory.name;
    
    this.resultInput.value = text;
    if (this.options.categoryInputId)    $(this.options.categoryInputId).value    = this.categoryId;
    if (this.options.subcategoryInputId) $(this.options.subcategoryInputId).value = this.subcategoryId;
    
    this.hide();
    
    return false;
  },
  
  show: function()
  {
    var html = '';
    var _this = this;
    
    html += '<div style="margin:0px; padding:0px; z-index:10; position:absolute;">';
    html += 'Catégorie : ';
    html += '<select onchange="$(\'' + this.resultInput.id + '\').categoryPicker.select(parseInt(this.value), \'\'); if (parseInt(this.value)) $(\'' + this.resultInput.id + '\').categoryPicker.show();">';
    html += '<option value="0"' + (0 == this.categoryId ? ' selected' : '') + '>' + (this.options.allowAll ? this.ALL_CATEGORIES : '') + '</option>';
    categories.each( function(category)
    {
      if(category) html += '<option value="' + category.id + '"' + (category.id == _this.categoryId ? ' selected' : '') + '>' + category.name + '</option>';
    } );
    html += '</select>';
    html += ' &nbsp; [<a href="#" onclick="return $(\'' + this.resultInput.id + '\').categoryPicker.hide();">Fermer</a>]<br />';
    
    if (this.categoryId)
    {
      var category = categories[this.categoryId];
      
      function getSubcategory(subcategory)
      {
        return '<div' + (subcategory.id ? ' style="float:left; width:170px;"' : '') + '><input type="radio" value="' + subcategory.id + '" onclick="$(\'' + _this.resultInput.id + '\').categoryPicker.select(' + _this.categoryId + ', parseInt(this.value));"' + (subcategory.id == _this.subcategoryId ? ' checked' : '') + ' />' + subcategory.name + '</div>';
      }
   	
      if (this.options.allowAll) html += getSubcategory({'id':0, 'name':'<b>' + this.ALL_SUBCATEGORIES + '</b>'});
      category.subcategories.each( function(tmpSubcategoryId)
      {
        html += getSubcategory(subcategories[tmpSubcategoryId])
      } );
      html += '<div class="clear"></div>';
    }
    else
    {
      html += '<br /><br /><br /><br /><br /><br /><div class="grey" align="center">' + this.INTRODUCTION_TEXT + '</div><br />';
    }
    html += '</div>';
    if (browserIsIE6) html += '<iframe style="margin:0px; padding:0px; z-index:9;"></iframe>';
     
    this.displayPanel.innerHTML = html;
    this.displayPanel.show();
    
    return false;
  },
  
  hide: function()
  {
    this.displayPanel.hide();
    if (this.options.callback) this.options.callback(this.categoryId, this.subcategoryId);
    
    return false;
  }
});

/* Parse document for lightbox Links */
function initializeMyForm()
{
  checkForMyFormMarkup();
  checkForAutocompleterMarkup();
  $('formBubble').hide();
}

/* Create form bubble and ... if they don't exist */
function checkForMyFormMarkup()
{
  var bod = document.getElementsByTagName('body')[0];
  
  if (!$('formBubble'))
  {
    var formBubble = document.createElement('div');
    formBubble.id = 'formBubble';
    formBubble.innerHTML = '<div id="formBubbleContent"></div>'
    bod.appendChild(formBubble);
  }
}

function submitContainingForm(elt, isMiddleClick)
{
  var formElt = $(elt).up('form');
  isMiddleClick = isMiddleClick || false;
  
  if (isMiddleClick || !formElt.onsubmit || (formElt.onsubmit() !== false)) formElt.submit();
  
  return false;
}

function addAutoCompletion(input, url, options)
{
  options = Object.extend({minChars:2, afterUpdateElement:submitContainingForm }, options || { });
 
  if (!input.autoCompleter)
  {
    var autoCompleterElt = $('autoCompleter');
    checkForAutocompleterMarkup();
    input.autoCompleter = new Ajax.Autocompleter(input, autoCompleterElt, url, options);
  }
 
  return false;
}

function checkForAutocompleterMarkup()
{
  var bod = document.getElementsByTagName('body')[0];
  
  if (!$('autoCompleter'))
  {
    var autoCompleterElt = document.createElement('div');
    autoCompleterElt.id = 'autoCompleter';
    autoCompleterElt.style.display = 'none';
    bod.appendChild(autoCompleterElt);
  }
}

