ggobj.filterStates = {
  active           : {primary : 'active', secondary : 'active_selected', secondary_state : 'activeSelected'},
  inactive         : {primary : 'inactive', secondary : 'inactive', secondary_state : 'inactive'},
  activeSelected   : {primary : 'active_selected', secondary : 'active', secondary_state : 'active'},
  inactiveSelected : {primary : 'inactive_selected', secondary : 'inactive', secondary_state : 'inactive'}
};


ggobj.FilterObject = new Class({

  request      : null,
  requestDelay : 300, //300 milli seconds
  timer        : null,
  Implements   : [Options, Events],
  
  options : {
    category : '',
    maxValueStandAlone : 5,
    catalogId : '',
    storeId : '',
    langId : '',
    targetDivList : 'content',
    targetDivProd : 'product_browse'
  },

  initialize : function(options){
    this.setOptions(options);
    
    //1. init click toggle events on each vaalue
    var allValues = $$('#filterNavi1 .filter_value');
    for(var idx = 0; idx < allValues.length; idx++) {
      var tmpValue = allValues[idx];
      if (tmpValue.hasClass('single_selection') && !tmpValue.hasClass('direct_link')) {
        tmpValue.addEvent('click', this.singleSelectionClicked.bind(tmpValue, this));
      } else if(!tmpValue.hasClass('direct_link')) {
        tmpValue.addEvent('click', this.valueClicked.bind(tmpValue, this));
      } else {
        tmpValue.addEvent('click', function(event, filterObj){
          if(this.hasClass('inactive')) {
            event.stop();
          } else {
            tmpFunc = filterObj.singleSelectionClicked.bind(this, [filterObj, true]);
            tmpFunc();
            filterobj.refreshCookie();
          }
        }.bindWithEvent(tmpValue, this));
        
      }
    }
    
    //2. initialize reset event for each filter
    var allResets = $$('#filterNavi1 .filter_reset');
    for(var idx = 0; idx < allResets.length; idx++){
      allResets[idx].addEvent('click', this.resetSelectedValues.bind(allResets[idx].getParent(), this));
    }

    //3. add toogle events for each filter -> open close
    var allFilter = $$('#filterNavi1 .filter');
    for(var idx = 0; idx < allFilter.length; idx++){
      var filterName = allFilter[idx].getElement('.filter_name');

      var tmpParent = allFilter[idx].getElement('.body').getParent();
      var verticalSlide = new Fx.Slide(allFilter[idx].getElement('.body'), {
        onStart: function() {
          tmpParent.setStyle('height','auto');
        }
      });    
      verticalSlide.addEvent('complete', function() {
        this.toggleClass('filter_open');
        this.toggleClass('filter_close');
        filterobj.refreshCookie();
      }.bind(filterName));
      filterName.toggleEffect = verticalSlide;

      //hide all filter except defaults
      if(allFilter[idx].get("filtername") != 'FILTER_brand' && allFilter[idx].get("filtername") != 'catfilterkey'){
        verticalSlide.hide();
        filterName.toggleClass('filter_open');
        filterName.toggleClass('filter_close');
      }
      
      filterName.addEvent('click', function(e){
        e.stop();
        this.toggleEffect.toggle();
      }.bind(filterName));
      
      //init scrolling if necessary
      if( allFilter[idx].getElements('.filter_value').length > this.options.maxValueStandAlone && 
         !(allFilter[idx].getElements('.filter_value')[0].hasClass('filter_value_icon') ||
         allFilter[idx].get("filterid") == 'catfilterkey' || allFilter[idx].get("filterid") == 'FILTER_price'))
      {
        var scroller = new MooScroller(allFilter[idx].getElement('.value_list_'+allFilter[idx].get("filtername")), allFilter[idx].getElement('.scrollKnob_'+allFilter[idx].get("filtername")), {
          scrollLinks: {
            forward: allFilter[idx].getElement('.scrollForward_'+allFilter[idx].get("filtername")),
            back: allFilter[idx].getElement('.scrollBack_'+allFilter[idx].get("filtername"))
          }
        });
        allFilter[idx].scrollEffect = scroller;
      }
      
      
      //3.1 add toogle events to filter with more than one level
      //var allToggles = allFilter[idx].getElements((singleSelection) ? '.single_selection' : '.toggle_icon');
      var allToggles = allFilter[idx].getElements('.toggle_icon');
      for(var idx1= 0; idx1 < allToggles.length; idx1++){
        var toggle = allToggles[idx1];
      
        var parentSlideElem = allFilter[idx].getElement('.body');
        
        
        var verticalSlide = new Fx.Slide(toggle.getParent().getParent().getElement('.child_ul_'+ toggle.get('id')),{
          open   : true,
          onStart: function() {
            parentSlideElem.getParent().setStyle('height','auto');
          }
        }).hide();
        
        verticalSlide.addEvent('complete', function() {
          this.toggleClass('expanded_icon');
          this.toggleClass('collapsed_icon');
        }.bind(toggle));
        toggle.toggleEffect = verticalSlide;
      
        toggle.addEvent('click', function(e){
          e.stop();
          this.toggleEffect.toggle();
        }.bind(toggle));
      }

    }

    //4. finally set values and states to initial state (check cookie)
    if(this.options.resetFilter){
      this.clearCookieValue();
    }
    this.setValues();
    this.positionScroller();
  },
  
  positionScroller : function(){
    var allFilter = $$('#filterNavi1 .filter');
    for(var idx = 0; idx < allFilter.length; idx++) {
      //position scrolling if necessary
      if(allFilter[idx].scrollEffect)
      {
        var values = allFilter[idx].getElements('.filter_value');
        var i = 0;
        var valueFound = false;
        for(var ii = 0; ii < values.length; ii++){
          // increase count if active, break when found
          if(values[ii].hasClass('active')){
            i++;
          }
          if(values[ii].hasClass('active_selected') || values[ii].hasClass('inactive_selected')){
            i++;
            valueFound = true;
            break;
          }
        }
        if(i > 0 && valueFound){
          allFilter[idx].scrollEffect.content[allFilter[idx].scrollEffect.horz ? 'scrollLeft' : 'scrollTop'] = (i - 3)*18;
        } else {
          allFilter[idx].scrollEffect.update();
        }
      }
    }
  },
  
  getSelectedValuesAsJSONString : function(page, prodsOnPage, prodSorting, preselectValue){
    var filterObj = new Object();
    var openFilterString = '#';
    
    var allValues = $$('#filterNavi1 .filter');
    var size = allValues.length;
    for(var idx = 0; idx < size; idx++){
      filterObj[allValues[idx].get('filterId')] = [];
    }
    
    var preselectFilter = '';
    allValues = $$('#filterNavi1 .filter_value');
    var size = allValues.length;
    for(var idx = 0; idx < size; idx++){
      if(preselectValue && allValues[idx].get('valueId') == preselectValue) {
        filterObj[allValues[idx].get('filterid')] = [(allValues[idx].get('valueId'))];
        preselectFilter = allValues[idx].get('filterid');
      } else if(!(preselectFilter == allValues[idx].get('filterid')) && (allValues[idx].get('currentstate') == 'activeSelected' || allValues[idx].get('currentstate') == 'inactiveSelected')){
        filterObj[allValues[idx].get('filterid')].push(allValues[idx].get('valueId'));
      }
    }
    
    var openFilters = $$('#filterNavi1 .filter_open');
    var size = openFilters.length;
    for(var idx = 0; idx < size; idx++){
      openFilterString = openFilterString + openFilters[idx].getParent().getParent().get('filterid') + '#';
    }
      
    var tmp = {
      category    : this.options.category,
      filterObject: filterObj,
      page        : (page == null) ? '' : '' + page,
      prodsOnPage : (prodsOnPage == null) ? '' : '' + prodsOnPage,
      prodSorting : (prodSorting == null) ? '' : '' + prodSorting,
      openFilters : openFilterString
    };
    return JSON.encode(tmp);
  },

  setNaviCounts: function(countArray){
    //get all navi values
    /*var allValues = $$('#filterNavi1 .filter')[0].getElements('.filter_value');
    
    //loop navi items and set counts
    for(var idx = 0; idx < allValues.length; idx++){
      var tmpValue = allValues[idx];
      if(!tmpValue.hasClass('single_selection')){
        if(countArray[tmpValue.get('valueid')]){
          tmpValue.set('html', tmpValue.get('html').replace(/\([0-9]+\)$/, '(' + countArray[tmpValue.get('valueid')] + ')'));
        }
        else{
          tmpValue.set('html', tmpValue.get('html').replace(/\([0-9]+\)$/, '(0)'));
        }
      }
    }*/
  },
  
  setValues: function(validValueArray){
    var allValues = $$('#filterNavi1 .filter_value');

    //check cookie - get string of selected values and open filters
    var filterObj = {};
    var openFilters = '';
    var categoryCookie = Cookie.read(this.options.category);
      
    // decode open filters
    if(categoryCookie && JSON.decode(categoryCookie).filterObject){
      filterObj = JSON.decode(categoryCookie).filterObject;
      if(JSON.decode(categoryCookie).openFilters) {
        openFilters = JSON.decode(categoryCookie).openFilters;
      }
    }
    
    // open/close each filter on last state stored in cookie
    var filter = $$('#filterNavi1 .filter');
    for(var idx = 0; idx < filter.length; idx++){
      var tmpValue = filter[idx].get('filterid');
      if(openFilters.contains('#' + tmpValue + '#')) {
        var filterName = filter[idx].getElement('.filter_name');
        filterName.toggleEffect.show();
        filter[idx].getElement('.body').getParent().setStyle('height','auto');
        filterName.removeClass('filter_close');
        filterName.addClass('filter_open');
      } else if(openFilters.length > 1) {
        var filterName = filter[idx].getElement('.filter_name');
        filterName.toggleEffect.hide();
        //filter[idx].getElement('.body').getParent().setStyle('height','auto');
        filterName.addClass('filter_close');
        filterName.removeClass('filter_open');
      }
    }
    
    for (var idx = 0; idx < allValues.length; idx++) {
      var tmpValue = allValues[idx].get('valueid');
      //if (!allValues[idx].hasClass('single_selection')) {
        var classSuffix = '';
        if (allValues[idx].hasClass('filter_value_icon'))
          classSuffix = '_icon';
        var currentState = allValues[idx].get('currentstate');
        if (currentState == null || '' == currentState)
          currentState = 'active';

        allValues[idx].removeClass(ggobj.filterStates[currentState].primary + classSuffix);
        
        if (filterObj[allValues[idx].get('filterid')] && filterObj[allValues[idx].get('filterid')].contains(tmpValue)) {
          if ((validValueArray && validValueArray.contains(tmpValue)) || !validValueArray) {
            allValues[idx].addClass(ggobj.filterStates['active'].secondary + classSuffix);
            allValues[idx].set('currentstate', ggobj.filterStates['active'].secondary_state);
            var toggleId = 'div.toggle_icon[id='+ allValues[idx].get('id') + "]";
            if(allValues[idx].get('parentid')) {
              toggleId = 'div.toggle_icon[id='+ allValues[idx].get('parentid') + "]";
            }
            
            var toggle = $$(toggleId)[0];
            if(toggle && toggle.toggleEffect) {
              if(currentState == 'active_selected') {
                toggle.toggleEffect.hide();
                toggle.toggleClass('expanded_icon');
                toggle.toggleClass('collapsed_icon');
              } else if (currentState == 'active') {
                toggle.toggleEffect.show();
                toggle.toggleClass('expanded_icon');
                toggle.toggleClass('collapsed_icon');
              }
            }
            
          } else {
            allValues[idx].set('currentstate', 'inactiveSelected');
            allValues[idx].addClass(ggobj.filterStates['inactiveSelected'].primary + classSuffix);
          }
        } else {
          if ((validValueArray && validValueArray.contains(tmpValue)) || !validValueArray) {
            allValues[idx].addClass(ggobj.filterStates['active'].primary + classSuffix);
            allValues[idx].set('currentstate', 'active');
          } else {
            allValues[idx].addClass(ggobj.filterStates['inactive'].primary + classSuffix);
            allValues[idx].set('currentstate', 'inactive');
          }
        }
        
        
        if (allValues[idx].getParent().hasClass('scroll')) {
          if(allValues[idx].hasClass('inactive')) {
            allValues[idx].getParent().addClass('inactive_scroll');
          } else {
            allValues[idx].getParent().removeClass('inactive_scroll');
          }
        }
        
      //}
      
      
      
    }
    this.positionScroller();
  },
  
  valueClicked : function(naviObj){
    var currentState = this.get('currentstate');
    var classSuffix = '';
    if(this.hasClass('filter_value_icon'))
      classSuffix = '_icon';
    if(currentState != 'inactive') {
      this.removeClass(ggobj.filterStates[currentState].primary + classSuffix);
      this.addClass(ggobj.filterStates[currentState].secondary + classSuffix);
      this.set('currentstate', ggobj.filterStates[currentState].secondary_state);
 
      naviObj.sendRequest(true, '1');
    }
  },
  
  urlValueClicked : function(naviObj){
    this.singleSelectionClicked(naviObj, true);
  },
  
  singleSelectionClicked : function(naviObj, dontSendRequest){
    var currentState = this.get('currentstate');
    var classSuffix = '';
    var deselectAction;
    if(this.hasClass('filter_value_icon'))
      classSuffix = '_icon';
    
    if(currentState == 'activeSelected') {
      deselectAction = this.get('deselectlink');
    }
    
    if(currentState == 'active') {
      var allValues = $$('div.active_selected' + classSuffix + '[filterid=' + this.get('filterid') + ']');
      for(var idx = 0; idx < allValues.length; idx++){
        var tmpValue = allValues[idx];
        var tmpState = tmpValue.get('currentstate');
        tmpValue.removeClass(ggobj.filterStates[tmpState].primary + classSuffix);
        tmpValue.addClass(ggobj.filterStates[tmpState].secondary + classSuffix);
        tmpValue.set('currentstate', ggobj.filterStates[tmpState].secondary_state);
        if($$('div.toggle_icon[id='+ tmpValue.get('id') + "]")[0] && $$('div.toggle_icon[id='+ tmpValue.get('id') + "]")[0].toggleEffect
          && $$('div.toggle_icon[id='+ this.get('id') + "]")[0] && $$('div.toggle_icon[id='+ this.get('id') + "]")[0].toggleEffect) {
          $$('div.toggle_icon[id='+ tmpValue.get('id') + "]")[0].toggleEffect.toggle();
        }
      }
    }
    if(currentState != 'inactive') {
      this.removeClass(ggobj.filterStates[currentState].primary + classSuffix);
      this.addClass(ggobj.filterStates[currentState].secondary + classSuffix);
      this.set('currentstate', ggobj.filterStates[currentState].secondary_state);
      var toggle = $$('div.toggle_icon[id='+ this.get('id') + "]")[0];
      if(toggle && toggle.toggleEffect) {
        if(currentState == 'activeSelected') {
          //console.log('hide select');
          toggle.toggleEffect.hide();
          if(toggle.hasClass('expanded_icon')) {
            toggle.toggleClass('expanded_icon');
            toggle.toggleClass('collapsed_icon');
          }
        } else if (currentState == 'active') {
          //console.log('show select');
          toggle.toggleEffect.show();
          if(toggle.hasClass('collapsed_icon')) {
            toggle.toggleClass('expanded_icon');
            toggle.toggleClass('collapsed_icon');
          }
        }
      }
    }
    if(deselectAction && !dontSendRequest) {
      //alert(deselectAction);
      filterobj.refreshCookie();
      window.location.href = deselectAction;
    } else if(!dontSendRequest) {
      naviObj.sendRequest(true, '1');
    }
  },
  
  resetSelectedValues : function(naviObj, noRequest){
    var deselectAction;
    
    var allValues = this.getElements('.filter_value');
    var changed = false;
    for(var idx = 0; idx < allValues.length; idx++){
      var tmp = allValues[idx];
      //if(!tmp.hasClass('single_selection')){
        var classSuffix = '';
        if(tmp.hasClass('filter_value_icon'))
          classSuffix = '_icon';
        if(tmp.get('currentstate') == 'activeSelected' || tmp.get('currentstate') == 'inactiveSelected'){
          changed = tmp.get('currentstate') == 'activeSelected';
          if(tmp.get('currentstate') == 'activeSelected') {
            deselectAction = tmp.get('deselectlink');
          }
          
          var currentState = tmp.get('currentstate');
          tmp.removeClass(ggobj.filterStates[currentState].primary + classSuffix);
          tmp.addClass(ggobj.filterStates[currentState].secondary + classSuffix);
          tmp.set('currentstate', ggobj.filterStates[currentState].secondary_state);
        }
      //}
    }
    if(deselectAction && changed && !noRequest) {
      filterobj.refreshCookie();
      window.location.href = deselectAction;
    } else if(changed && !noRequest) {
      naviObj.sendRequest(true, '1');
    }
  },

  writeCookie : function(page, prodsOnPage, prodSorting){
    Cookie.write(this.options.category, this.getSelectedValuesAsJSONString(page, prodsOnPage, prodSorting), {expires: 1, path: '/'});
  },

  preselectFilter : function(filterValueId, productId){
    var prodsOnPage = this.getCookieValue('prodsOnPage');
    var prodSorting = this.getCookieValue('prodSorting');
    
    Cookie.write(this.options.category, this.getSelectedValuesAsJSONString(null, prodsOnPage, prodSorting, filterValueId), {expires: 1, path: '/'});
    this.setValues();
    if(productId == null || productId == '' || productId == 'false'){
      this.sendRequest(true, 1, null, null);
    }
    
    this.positionScroller();
  },

  getCookieValue : function(key){
    var categoryCookie = Cookie.read(this.options.category)
    var result = '';
    if(categoryCookie && JSON.decode(categoryCookie)[key]){
      result = JSON.decode(categoryCookie)[key];
    }
    return result;
  },
  
  clearCookieValue : function(){
    Cookie.write(this.options.category, '', {expires: 1, path: '/'});  
  },

  fixBreadcrumb : function(){
    var entries = $('breadcrumb').getElements('span');
    var lastElement = $('breadcrumb').getElements('h1');
 
    if(entries.length == 3 && entries[2].getChildren('a').get('html') != ''){
       var href = entries[2].getChildren('a').get('html');
       if (href == ''){
         var href = entries[2].getChildren('span').get('html');
       }
       entries[2].set('html', href);      
       //MT1101: check if element exists
       if(lastElement[0]) lastElement[0].set('html', '');       
    }

    if(entries.length > 3){
      if(entries[1].getChildren('a')[0]){
        if(entries[1].getChildren('span').length > 0){
          var href = entries[1].getChildren('a')[0].clone();
          entries[1].set('html', '');
          href.inject(entries[1]);
        } else{
          var href = entries[1].getChildren('a')[0].clone();
          entries[1].set('html', '');
          href.inject(entries[1]);
 
          entries[1].set('html', entries[1].get('html') + '&nbsp;|&nbsp;');          

          for(var i = 3; i < entries.length; i++){              
           entries[i].parentNode.removeChild(entries[i]);
          }
         
          //single element without |
          if($('breadcrumb').getElements('span').length == 2 && $('breadcrumb').getElements('h1').length == 0){
            var cnt = $('breadcrumb').get('html').replace('|', '');           
            $('breadcrumb').set('html',cnt);
          }
        }
      }
    }
  },
  
  refreshCookie : function(page, prodsOnPage, prodSorting){
    var categoryCookie = Cookie.read(this.options.category);
    
    if(categoryCookie){
      if(!page){
        if(JSON.decode(categoryCookie).page){
          page = JSON.decode(categoryCookie).page;
        }
      }
      if(!prodsOnPage){
        if(JSON.decode(categoryCookie).prodsOnPage){
          prodsOnPage = JSON.decode(categoryCookie).prodsOnPage;
        }
      }
      if(!prodSorting){
        if(JSON.decode(categoryCookie).prodSorting){
          prodSorting = JSON.decode(categoryCookie).prodSorting;
        }
      }
    }
    this.writeCookie(page, prodsOnPage, prodSorting);
  },
  
  sendRequest : function(addhistoryhash, page, prodsOnPage, prodSorting){
   if(this.timer != null){
    $clear(this.timer); 
   }
   this.timer = this.sendRequestInternal.delay(this.requestDelay, this, [addhistoryhash, page, prodsOnPage, prodSorting]);
  },
  
  sendRequestInternal : function(addhistoryhash, page, prodsOnPage, prodSorting, productId, articleNumber){
    var categoryCookie = Cookie.read(this.options.category);
    
    if(categoryCookie){
      if(!page){
        if(JSON.decode(categoryCookie).page){
          page = JSON.decode(categoryCookie).page;
        }
      }
      if(!prodsOnPage){
        if(JSON.decode(categoryCookie).prodsOnPage){
          prodsOnPage = JSON.decode(categoryCookie).prodsOnPage;
        }
      }
      if(!prodSorting){
        if(JSON.decode(categoryCookie).prodSorting){
          prodSorting = JSON.decode(categoryCookie).prodSorting;
        }
      }
    }
    
    if(addhistoryhash){
      this.writeCookie(page, prodsOnPage, prodSorting);
      categoryCookie = Cookie.read(this.options.category);
      this.addHashToHistoryManager(categoryCookie);
      //historyManager.addState(encodeURIComponent(categoryCookie));
    }
    
    if(this.request != null && this.request.running){
      this.request.cancel;
    }
    
    var targetDiv = $(this.options.targetDivList);
    if(productId){
      targetDiv = $(this.options.targetDivProd);
    }
    else{
      this.fixBreadcrumb();
      productId = '';
    }
    if(articleNumber) {
    } else {
      articleNumber = '';
    }
    
    this.request = new Request.HTML({
      url        : 'FilterNaviResultView',
      update     : targetDiv,
      evalScripts: true,
      onComplete : function() {
        if(targetDiv.get('id') == 'content'){
          targetDiv.setStyles({opacity: 0.0, background: '', height: 'auto'}); 
          new Fx.Tween(targetDiv, {
                property  : 'opacity',
                duration  : 300,
                onStart   : function () {
                              new Fx.Tween(targetDiv, {property : 'opacity', duration: 300}).start(1.0);
                            },
                onComplete: function () {
                              targetDiv.setStyles({opacity: 1.0});
                            }}
          ).start(1.0);
        }
        else{
          targetDiv.setStyles({opacity: 1.0, background: ''}); 
        }
      },
      onRequest  : function() {
        if(targetDiv.get('id') == 'content'){
          targetDiv.set('html', '');
          targetDiv.setStyles({background: 'url(/images_shop/storefront/ajax_loader.gif) no-repeat center', height: '400px'});
        }
        else{
          targetDiv.setStyles({background: 'url(/images_shop/storefront/ajax_loader_20.gif) no-repeat center'});
        }
        
      }
    });
    this.request.send("pagenr=" + this.options.pagenr + "&storeId=" + this.options.storeId + "&langId=" + this.options.langId + "&catalogId=" + this.options.catalogId + "&categoryId=" + this.options.currentCategory + "&filterCategoryId=" + this.options.category + "&page=" + page + "&prodsOnPage=" + prodsOnPage + "&prodSorting=" + prodSorting + "&productId=" + productId + "&articleNumber=" + articleNumber);
  },
  
  addHashToHistoryManager : function(categoryCookie) {
    if(historyManager) {
      historyManager.addState(encodeURIComponent(categoryCookie));
    } else {
      this.addHashToHistoryManager.delay(this.requestDelay, this, categoryCookie);
    }
  },
  
  
  sendRequestProductNavi : function(productId, articleNumber){
    this.sendRequestInternal(false, null, null, null, productId, articleNumber);
  }

});
