var RailCards = Class.create({
    initialize: function(labels){
        this._labels = labels;
		if(this._railCardSelections().size() == 0) 
            this.create();
        else
            this.recreate();
    },
    _railCardSelections: function(){
        var values = this._railCardInformation().getValue();
        return values!="" ? new Hash(values.evalJSON()): new Hash();
    },
    _size: function(){
        return new Number(this._container().readAttribute('size'));
    },
    _types: function(){
        return this._container().readAttribute('types').evalJSON();
    },
    _numbers: function(){
        return this._container().readAttribute('numbers').evalJSON();
    },
    _showLabel: function(){
        var label = this._container().readAttribute('label');
        if(!label || label.toLowerCase() == "false")
            return false;
        return true;	    
    },
    _disabled: function(){
         var disabled = this._container().readAttribute('railCardDisabled');
        if(!disabled || disabled.toLowerCase() == "false")
            return false;
        return true;
    },
    _defaultRailcardValue: function(){
         return this._container().readAttribute('defaultValue');
    },
   
    add: function(){
        this.create();
        this._updateRailCardInformation();
    },
    create: function(){
        var railCard = new Element('div',{'class':'field_container'});
        var railcardType = this._createRailCardType(railCard);
        var railcardNumbers = this._createRailCardNumbers(railCard,railcardType.id);
        if(this._count() > 0) railCard.appendChild(new Element('span',{'class':'remove'}).update(this._createRemoveLink(railcardType.id)));
        this._container().appendChild(railCard);
        this._handleAddButtonDisplay();
    },
    _handleAddButtonDisplay: function(){
        if((this._size() == this._count()) || this._disabled())this._toggleAddRailcardButtonState(false);
        else this._toggleAddRailcardButtonState(true);
    },
    _addRailcardButton: function (){
        return $('addRailcard');
    },
    _createRailCardType: function(container){
      var that = this;
      var div = new Element('div');
   
      if(this._showLabel()){
          var cardTypeLabel = new Element('label',{'for':'railCardsType' + this.nextRailCardId()}).update(this._labels.LabelRailCard);
          div.appendChild(cardTypeLabel);
      }
      var comboBoxName = 'railCardsType_' + this.nextRailCardId();
      var comboBox = new Element('select',{
                                            'id':comboBoxName
                                            ,'class':'rail_cards_type'
                                            ,'sibling':	'railCardNumber_' + this.nextRailCardId()
                                            ,'name':comboBoxName
                                           });
      comboBox.observe('change',function (e) {that._railCardTypeChanged(e.target);});
      var IsRailCardDisabled = this._disabled();
      var defaultValueRailCard = this._defaultRailcardValue(); 
      this._types().each(function(railCardType){
          if(!IsRailCardDisabled || railCardType.code== defaultValueRailCard)  {
          var option = new Element('option',{'value':railCardType.code}).update(railCardType.name);
          comboBox.appendChild(option);
          }
      });
      if(IsRailCardDisabled && defaultValueRailCard==""){
        comboBox.disabled=true;
      }
   
      if(this._showLabel()){
          div.appendChild(comboBox);
          container.appendChild(div);
      }
      else{
          container.appendChild(comboBox);
      }
      return comboBox;
    },
    _createRailCardNumbers: function(container,railCardTypeId){
        var that = this;
        var div = new Element('div',{'class':'two_col_2'});
        if(this._showLabel()){
            var cardNumberLabel = new Element('label',{'for':'railCardNumber_' + this.nextRailCardId(),'class':'side'}).update(this._labels.LabelHowMany);
            div.appendChild(cardNumberLabel);	
        }
        var comboBox = new Element('select',{'id':'railCardNumber_' + this.nextRailCardId(),'class':'railCardNumbers','sibling':railCardTypeId,'name':'railCardNumber_' + this.nextRailCardId()});
        comboBox.observe('change',function(e){ that._railCardNumberChanged(e.target) });
        this._numbers().each(function(railCardNumber){
            var option = new Element('option',{'value':railCardNumber.key}).update(railCardNumber.value);
            comboBox.appendChild(option);
        });
        if(this._showLabel()){
            div.appendChild(comboBox);
            container.appendChild(div);
        }
        else{
            container.appendChild(comboBox);
        }
        return comboBox;
    },
    _createRemoveLink: function(railcardTypeId){
        var that = this;
        var link = new Element('a',{'id':'railcardRemoveLink','class':'removehlink','href':'javascript:void(0);','sibling':railcardTypeId}).update(this._labels.LabelRemove);
		$(link).observe('click',function(e) {that._removeHandler(e.target)}); 
        return link;
    },
    _railCardTypeChanged: function(elem){
        this._updateRailCardCount(elem);
        this._updateRailCardInformation();
    },
    _updateRailCardCount: function(elem){
        var sibling = this._sibling(elem);
        if(elem.getValue() == 'None'){
          sibling.setValue('0');
        } else if(sibling.getValue() == '0'){
            sibling.setValue('1');
        }
    },
    _railCardInformation: function(){
        return $('railCardInformation');
    },
    _railCardNumberChanged: function(elem){
        this._updateRailCardType(elem);
        this._updateRailCardInformation();
    },
    _updateRailCardType: function(elem){
         elem.getValue() == '0' && this._sibling(elem).setValue('None');
    },
    _removeHandler: function(elem){
        this.remove(elem);
        this._updateRailCardInformation();
        this._toggleAddRailcardButtonState(true);
    },
    remove : function(link){
        $(link).up('div').remove();
    },
    nextRailCardId: function(){
        if($$('.railCardNumbers').size() == 0) return 0;
        var max =0;
        $$('.railCardNumbers').each(function(railCardNumber){
            id =parseInt(railCardNumber.id.split('_')[1]);
            if(id>max) max =id;
        })
        return max+1;
    },
    recreate: function(){
		var that = this;
        var defaultRailcardValue = this._defaultRailcardValue();
        this._railCardSelections().each(function(railCardSelected){
            that.create();
            var _id = railCardSelected.key.split('_')[1];
   
            var index = that._count() -1;
            var type = that._railCardsType()[index];
            type.id = 'railCardsType_'+_id;
            that._sibling(type,'railCardNumber_' +_id)
   
            var number = that._railCardNumbers()[index];
            number.id = 'railCardNumber_' +_id;
            that._sibling(number,'railCardsType_'+_id);
            if($$('.removehlink').size()>0)
                that._sibling($$('.removehlink')[$$('.removehlink').size()-1],'railCardsType_'+_id);
            if(railCardSelected.value.code != "")
			  type.setValue(railCardSelected.value.code);
			else
			  type.setValue(defaultRailcardValue);
			/*if(defaultRailcardValue != "") {
                type.setValue(defaultRailcardValue);
            }else{
                type.setValue(railCardSelected.value.code);
            }*/
            number.setValue(railCardSelected.value.number);
            that._container().show();
        });
    },
    _sibling: function(elem, attribute){
        return attribute ? $(elem).writeAttribute('sibling',attribute):$($(elem).readAttribute('sibling'));
    },
    _container: function(){
        return $('railCards');
    },
    _count: function(){
        return this._railCardsType().length;
    },
    _railCardsType: function(){
        return $$('.rail_cards_type');
    },
    _railCardNumbers: function(){
        return $$('.railCardNumbers');
    },
    _updateRailCardInformation: function(){
        var that = this;
        var railCardSelections = new Hash();
        this._railCardsType().each(function(railCardType){
            var railCardSelection = new Hash();
            railCardSelection.set('code', railCardType.getValue());
            railCardSelection.set('number', that._sibling(railCardType).getValue());
            railCardSelections.set(railCardType.id, railCardSelection);
        });
        this._railCardInformation().setValue(railCardSelections.toJSON());
    },
    total: function(){
        var total = 0;
        this._railCardNumbers().each(function(number){
            total += new Number(number.getValue());
        });
        return total;
    },
    _toggleAddRailcardButtonState: function(makeButtonVisible){
      var railcardAddButtonParentElement = this._addRailcardButton().up('span');
      if(makeButtonVisible){
        railcardAddButtonParentElement.show();
        this._addRailcardButton().enable();
        }
      else{
        railcardAddButtonParentElement.hide();
        this._addRailcardButton().disable();
        }
    },
    _railcardsMainContainer : function(){
     return $('railCardsContainer');
    },
    enable: function(selection){
        if(selection){
             if(this._count()==0)this.create();
             this._railcardsMainContainer().show();
        }
        else{
             this._railcardsMainContainer().hide();
             this.removeAll();
        }
    },
    removeAll : function(){
     this._container().immediateDescendants().each(function(ele){$(ele).remove();});
     this._railCardInformation().setValue("");
    }
});

document.observe("dom:loaded", function(){
	$('railCards').show();
	$('addRailCardDiv').show();
}); 

