/**
 * jquery sfFormDynamic
 *
 * @author slemoigne@agenceinteractive.com
 * @version 0.1
 */

;(function($) {

var ver = '0.1';

$.sfFormDynamic = function(opt)
{
  //set option
  var option = $.extend({}, $.sfFormDynamic.defaults, opt);
  var nb = 1; //nb of element
  
  /**
   * construct - initialize
   *
   */
  function _initialize() {
    nb = $(option.selector.element).length;
    $(option.selector.nb).attr('value', nb);
    
    _initEvent();
  }
  
  /**
   * init event
   *
   */
  function _initEvent()
  {
    //remove event
    $(option.selector.element).find(option.selector.remove).bind('click', function(event) {
      event.preventDefault();
      _removeElement($(this).parents(option.selector.element));
    });
  
    //add event
    $(option.selector.add).bind('click', function(event) {
      event.preventDefault();
      _cloneElement();
    });

    // Check of the number of elements and event trigger if min or max is reached
    var maxElements = $(option.selector.max_elements).val();
    var nbElements = $(option.selector.container+" "+option.selector.element).size();

    if(nbElements == maxElements && maxElements != 0){
      $(option.selector.container + " " + option.selector.element).trigger(option.selector.max_elements_event);
    }
    if(nbElements <= option.nbmin){
      $(option.selector.container+" "+option.selector.element).trigger(option.selector.min_elements_event);
    }
  }
  
  /**
   * clone element
   *
   */
  function _cloneElement()
  {
    var maxElements = $(option.selector.max_elements).val();
    var nbElements = $(option.selector.container+" "+option.selector.element).size();

    // Clone element if unlimited elements or max elements not reached
    if( maxElements == 0 || nbElements < maxElements)
    {
      //clone
      var clone = $(option.selector.clone).clone(true);

      clone = option.cloneTransform(clone);

      _addElement(clone);
    }

    // Trigger event if max is reached
    nbElements = $(option.selector.container+" "+option.selector.element).size();
    if(nbElements == maxElements && maxElements != 0){
      $(option.selector.container + " " + option.selector.element).trigger(option.selector.max_elements_event);
    }
  }
  
  /**
   * remove element
   *
   * @param jQuery element
   */
  function _removeElement(element)
  {
    var nbElements = $(option.selector.container+" "+option.selector.element).size();

    if( nb > option.nbmin && nbElements > 0)
    {
      option.removeElement(element);
      element.remove();
      nb--;
      $(option.selector.nb).attr('value', nb);
      option.index(option.selector.element);

      // Trigger event if min is reached
      nbElements = $(option.selector.container+" "+option.selector.element).size();
      if(nbElements == option.nbmin){
        $(option.selector.container+" "+option.selector.element).trigger(option.selector.min_elements_event);
      }
    }
  }
  
  /**
   * add element
   *
   * @param jQuery element
   */
  function _addElement(element)
  {
	if( option.position == 'prepend' )
	{
      element.prependTo(option.selector.container);
	}
	else
	{
	  element.appendTo(option.selector.container);
	}
	
    nb++;
    $(option.selector.nb).attr('value', nb);
    option.index(option.selector.element);
  }

  _initialize();
}

//default option
$.sfFormDynamic.defaults = {
  selector : {
    add: '.add',
    remove: '.remove',
    clone: '.clone:first',
    container: '.container',
    nb: 'input[name=nb]',
    element: '.element',
    max_elements: '#max_elements',
    min_elements_event: 'min_elements_event',
    max_elements_event: 'max_elements_event'
  },
  nbmin: 1,
  position: 'append', 
  /**
   * reasign id and name
   *
   */
  index : function(element){
    var i = 0;
    var reg = new RegExp('(_|\[){1}([0-9]+)(_|\]){1}', 'g');
    $(element).each(function(){
      $(this).find('input').each(function(){
        $(this).attr('id', $(this).attr('id').replace(reg, i + '_') );
        $(this).attr('name', $(this).attr('name').replace(reg, '[' + i + ']') );
      });
      $(this).find('label').each(function(){
        $(this).attr('for', $(this).attr('for').replace(reg, i + '_') );
      });
      i++;
    });
  },
  /**
   * remove element
   * 
   */
  removeElement : function(element) {
    var reg = new RegExp('^(.*)([_]){1}([0-9]+)$', 'g');
    var model = $(element).attr('id').replace(reg, "$1");
    var id = $(element).attr('id').replace(reg, "$3");
    var newValue = $('input[name*=[del_' + model + ']]').attr('value');

    if( newValue != '' )
    {
      newValue += '|' + id;
    }
    else
    {
      newValue = id;
    }
    
    $('input[name*=del_' + model + ']]').attr('value', newValue);
  },
  /**
   * clone tansform
   *
   */
  cloneTransform : function(clone) {
    clone.find('input, textarea, select').each(function(){
      if($(this).attr("type") != "radio") $(this).attr('value', '');
      if($(this).attr("type") == "radio") $(this).attr('checked', '');
    });
    clone.find('img').each(function(){
      $(this).attr("src","/sfSympalPlugin/images/no-image.png");
    });
    clone.find('select option').each(function(){
      $(this).removeAttr('selected');
    });
  
    return clone;
  }
}

})(jQuery);
