// Add custom event to MooTools Events object
Element.Events.enterKey = {
  // set base event to 'keyup'
  base: 'keyup',
  // Condition that must be met
  condition: function(customEvent) {
    if(customEvent.key=='enter') {
      return true;
    } else {
      return false;
    }
   }
};

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', secondary : 'inactive', secondary_state : 'inactive'}
};

// cookie names
ggobj.COOKIE_WC_SEARCH_PAGE_URL = 'WC_SEARCH_PAGE_URL';
ggobj.COOKIE_WC_SEARCH_PAGE = 'WC_SEARCH_PAGE';
ggobj.COOKIE_WC_SEARCH_PAGE_POS_Y = 'WC_SEARCH_PAGE_POS_Y';

ggobj.DEFAULT_PRODUCTS_ON_PAGE = 16; // constant

ggobj.SearchObject = new Class({

  request      : null,
  requestDelay : 300, //300 milli seconds
  timer        : null,
  Implements   : [Options, Events],
  pIDs         : null,
  paths        : null,
  scrollLoader : null,

  options : {
    cookieName : 'WC_SEARCH',
    maxValueStandAlone : 5,
    catalogId : '',
    storeId : '',
    langId : '',
    searchTerm : '',
    categoryId : '',
    multipleSelectionFilters : '',
    openFilters : ''
  },

  initialize : function(options){
    this.setOptions(options);

    //1. init click toggle events on each value
    var allValues = $$('#filterNavi1 .filter_value');
    for(var idx = 0; idx < allValues.length; idx++){
      if(this.options.multipleSelectionFilters.indexOf(allValues[idx].get('filterid')) != -1) {
	      allValues[idx].addEvent('click', this.valueClickedMultiple.bind(allValues[idx], this));
	  } else {
	      allValues[idx].addEvent('click', this.valueClicked.bind(allValues[idx], this));
      }
    }

    //2. initialize reset event for each filter
    var allResets = $$('#filterNavi1 .filter_name .filter_name_text');
    for(var idx = 0; idx < allResets.length; idx++){
      allResets[idx].addEvent('click', this.resetSelectedValues.bind(allResets[idx].getParent().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 filterNameStatus = filterName.getElement('.filter_name_status');

      var tmpParent = allFilter[idx].getElement('.body').getParent();
      // added store for wrapper. this wrapper is an option in mootools 1.3
      allFilter[idx].getElement('.body').store("wrapper", tmpParent);
      var verticalSlide = new Fx.Slide(allFilter[idx].getElement('.body'), {
        onStart: function() {
          // use parent of parent as an own wrapper-div was introduced
          tmpParent.getParent().setStyle('height','auto');
        }
      });
      verticalSlide.addEvent('start', function() {
        // hide the overflow if the filter is closed
        var b_wrapper = this.getParent().getElement('.b-wrapper')
        if (b_wrapper != null && this.hasClass('filter_open')) {
          b_wrapper.addClass('filter_close_overflow');
        }
      }.bind(filterName));
      verticalSlide.addEvent('complete', function() {
        this.toggleClass('filter_open');
        this.toggleClass('filter_close');

        // restore the overflow if the filter was opened
        var b_wrapper = this.getParent().getElement('.b-wrapper')
        if (b_wrapper != null && this.hasClass('filter_open')) {
          b_wrapper.removeClass('filter_close_overflow');
        }
      }.bind(filterName));
      filterName.toggleEffect = verticalSlide;
      
      //hide all filter except defaults
      if(allFilter[idx].get("filterid") != 'Kategorie'
            && this.options.openFilters.indexOf(allFilter[idx].get('filterid')) == -1){
        verticalSlide.hide();
        filterName.toggleClass('filter_open');
        filterName.toggleClass('filter_close');
        // hide the overflow if the filter is closed
        var b_wrapper = filterName.getParent().getElement('.b-wrapper')
        if (b_wrapper != null && filterName.hasClass('filter_close')) {
          b_wrapper.addClass('filter_close_overflow');
        }
      }

      if(filterNameStatus && !filterName.hasClass("nocollapse")) {
        filterNameStatus.addEvent('click', function(e){
          e.stop();
          this.toggleEffect.toggle();
        }.bind(filterName));
      }

      //3.1 add toogle events to filter with more than one level
      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')),{
          onStart: function() {
            parentSlideElem.getParent().setStyle('height','auto');
          }
        }).slideOut('vertical');

        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. set brand input field filter
    var brandInputField = $$('#filterNavi1 .brand_input');
    if(brandInputField[0]) {
      brandInputField[0].addEvent('enterKey', this.valueEntered.bind(brandInputField[0], this));
    }
  },

  getSelectedValuesAsJSONString : function(prodSorting){
    var allValues = $$('#filterNavi1 .filter_value');
    var brandInputField = $$('#filterNavi1 .brand_input');
    var values = '#';
    var filterString = '';
    var size = allValues.length;

    var jsonTopCat ='#';
    var jsonColor ='#';
    var jsonBrand ='#';
    var jsonSize ='#';
    var jsonPrice ='#';
    var jsonAbsatzhoehe ='#';
    var jsonAusfuehrung ='#';
    var jsonAbsatzart ='#';
    var jsonPassform ='#';
    var jsonSchuhspitze ='#';
    var jsonInnensohle ='#';
    var jsonFutter ='#';
    var jsonObermaterial ='#';
    var jsonLaufsohle ='#';
    var jsonWasserschutz ='#';

    for(var idx = 0; idx < size; idx++){
      if(allValues[idx].get('currentstate') == 'activeSelected' || allValues[idx].get('currentstate') == 'inactiveSelected'){
        values = values + allValues[idx].get('filtername') + '#';
        if (allValues[idx].get('filtercategory').indexOf('CATEGORY_PATHROOT') == 0) {
          jsonTopCat = jsonTopCat + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'ASN_COLOR') {
          jsonColor = jsonColor + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'brand') {
          jsonBrand = jsonBrand + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'size') {
          jsonSize = jsonSize + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Preis') {
          jsonPrice = jsonPrice + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Absatzhoehe') {
          jsonAbsatzhoehe = jsonAbsatzhoehe + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Ausführung') {
          jsonAusfuehrung = jsonAusfuehrung + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Absatzart') {
          jsonAbsatzart = jsonAbsatzart + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Passform') {
          jsonPassform = jsonPassform + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Schuhspitze') {
          jsonSchuhspitze = jsonSchuhspitze + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Innensohle') {
          jsonInnensohle = jsonInnensohle + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Futter') {
          jsonFutter = jsonFutter + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Obermaterial') {
          jsonObermaterial = jsonObermaterial + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Laufsohle') {
          jsonLaufsohle = jsonLaufsohle + allValues[idx].get('filtername') + '#'
        } else if (allValues[idx].get('filtercategory') == 'Wasserschutz') {
          jsonWasserschutz = jsonWasserschutz + allValues[idx].get('filtername') + '#'
        }
      }
    }
    
    if(brandInputField[0]) {
      if(brandInputField[0].value) {
        jsonBrand += brandInputField[0].value + '#';
      }
    }

    var json = {
      filter      : "top_category#mapping_color#brand#size#price#Absatzhoehe#Ausfuehrung#Absatzart#Passform#Schuhspitze#Innensohle#Futter#Obermaterial#Laufsohle#Wasserschutz",
      selected    : values,
      top_category: jsonTopCat,
      mapping_color       : jsonColor,
      brand       : jsonBrand,
      size        : jsonSize,
      price       : jsonPrice,
      Absatzhoehe : jsonAbsatzhoehe,
      Ausfuehrung : jsonAusfuehrung,
      Absatzart   : jsonAbsatzart,
      Passform    : jsonPassform,
      Schuhspitze : jsonSchuhspitze,
      Innensohle  : jsonInnensohle,
      Futter      : jsonFutter,
      Obermaterial: jsonObermaterial,
      Laufsohle   : jsonLaufsohle,
      Wasserschutz: jsonWasserschutz,
      prodSorting : (prodSorting == null) ? '' : '' + prodSorting
    };

    return JSON.encode(json);
  },

  setValues: function(validValueObject, ignoreCookie){
    var allValues = $$('#filterNavi1 .filter_value');
    //check cookie - get string of selected values
    var selectedValues = '';
    var searchCookie = Cookie.read(this.options.cookieName);
    
    if(!ignoreCookie && searchCookie && JSON.decode(searchCookie).selected){
      selectedValues = JSON.decode(searchCookie).selected;
    }
    
    for(var idx = 0; idx < allValues.length; idx++){
      var tmpFilter = allValues[idx].get('filterid');
      var tmpValue = allValues[idx].get('filtername');
      if(validValueObject) {
        var validValueArray = validValueObject[''+tmpFilter];
      }
      var classSuffix = '';
      if(allValues[idx].hasClass('filter_value_icon'))
        classSuffix = '_icon';
      var currentState = allValues[idx].get('currentstate');
      if(currentState == null || '' == currentState) {
        currentState = 'active';
      }
      
      var newState;
      if(selectedValues.contains('#' + tmpValue + '#')) { // NOTE: filter "Preis" is not recognized and set this way
        newState = ggobj.filterStates['active'].secondary_state;
      } else {
        if(!validValueArray || validValueArray.contains(tmpValue)) {
          if(allValues[idx].get('filtercategory') == 'Preis') {
            newState = 'activeSelected';
          } else {
            newState = 'active';
          }
        } else {
          if(allValues[idx].get('filtercategory') == 'Preis') {
            newState = 'inactiveSelected';
          } else {
            newState = 'inactive';
          }
        }
      }
      if (currentState != newState) {
        allValues[idx].removeClass(ggobj.filterStates[currentState].primary + classSuffix);
        allValues[idx].addClass(ggobj.filterStates[newState].primary + classSuffix);
        allValues[idx].set('currentstate', newState);
      } else {
        // this is just for compatibility with the older components/search/leftnav.jspf where the 'active_icon' class was not set
        allValues[idx].addClass(ggobj.filterStates[newState].primary + classSuffix);
      }
      if(allValues[idx].getParent().hasClass('scroll')) {
        if(allValues[idx].hasClass('inactive')){
          allValues[idx].getParent().addClass('inactive_scroll');
        } else {
          allValues[idx].getParent().removeClass('inactive_scroll');
        }
      }/**/
    }
  },

  valueClickedMultiple : 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, '');
    }
  },

  valueClicked : function(naviObj){
    var currentState = this.get('currentstate');
    var classSuffix = '';
    if(this.hasClass('filter_value_icon'))
      classSuffix = '_icon';
    
    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(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.showHideFilterElements(this);
    
    naviObj.sendRequest(true, '');
  },
  
  showHideFilterElements : function(filterValue) {
	var filterId = filterValue.get('filterid');
	var filter = $$('#filterNavi1 div.filter[filterid=' + filterId + ']')[0];
	var filterName = filter.getElement('.filter_name');
	var b_wrapper = filter.getElement('.b-wrapper');
	
	// if filter is open, reset wrapper height style which might having been changed by opening / closing filter
	if (filterName.hasClass('filter_open')) {
		b_wrapper.setStyle('height','');
	}
	
	var classSuffix = '';
	if(filterValue.hasClass('filter_value_icon'))
		classSuffix = '_icon';
	
	currentState = filterValue.get('currentstate');
	if(currentState == 'activeSelected') {
		// only the selected one may be visible
		var allValues = filter.getElements('div.active' + classSuffix + '[filterid=' + filterId + ']');
		for(var idx = 0; idx < allValues.length; idx++){
			var tmpValue = allValues[idx];
			tmpValue.getParent().addClass('active_hidden' + classSuffix);
		}
		// if the filter has a scrollbar we have to hide it
		if (b_wrapper.hasClass('scrollbar_on')) {
			b_wrapper.removeClass('scrollbar_on');
			b_wrapper.addClass('scrollbar_off');
		}
	} else if (currentState == 'active') {
		// show all hidden elements again
		var allValues = filter.getElements('div.active' + classSuffix + '[filterid=' + filterId + ']');
		for(var idx = 0; idx < allValues.length; idx++){
			var tmpValue = allValues[idx];
			tmpValue.getParent().removeClass('active_hidden' + classSuffix);
		}
		// if the filter has a scrollbar we have to restore it
		if (b_wrapper.hasClass('scrollbar_off')) {
			b_wrapper.removeClass('scrollbar_off');
			b_wrapper.addClass('scrollbar_on');
		}
	}
  },
  
  initFilterElementVisibility : function() {
	var allFilter = $$('#filterNavi1 .filter');
	for(var i = 0; i < allFilter.length; i++) {
		var filter = allFilter[i];
		var filterId = filter.get('filterid');
		var filterName = filter.getElement('.filter_name');
		var b_wrapper = filter.getElement('.b-wrapper');
		var filterValues = filter.getElements('.filter_value');
		
		// check if there is a selected value
		var selectedValue = null;
		for(var j = 0; j < filterValues.length; j++) {
			if (filterValues[j].get('currentstate') == 'activeSelected') {
				selectedValue = filterValues[j];
				break;
			}
		}
		if (this.options.multipleSelectionFilters.indexOf(filterId) == -1) {
			// for single value selection
			if (selectedValue) {
				// we initialize this by simulating that the selected value gets selected
				this.showHideFilterElements(selectedValue);
			} else if (filterValues.length > 0) {
				// we only need to call this function with an arbitrary filterValue because all values are initialized
				this.showHideFilterElements(filterValues[0]);
			}
		}
		if (selectedValue) {
			// NOTE: because the value of filter "Preis" is not set the filter will never be extended but it will work if the filter Preis value is set some day...
			var priceSelected = false;
			if (filterId == 'Preis') {
				var priceFilterValue = filter.getElement('.filter_value');
				var priceSelected = priceFilterValue.get('filtername') != priceFilterValue.get('initialfiltervalue');
			}
			if (filterId != 'Preis' || priceSelected) {
				filterName.toggleEffect.show();
				filterName.removeClass('filter_close');
				filterName.addClass('filter_open');
				b_wrapper.removeClass('filter_close_overflow');
			}
		}
	}
  },
  
  resetSelectedValues : function(naviObj){
    var changed = false;
    var brandInputField = this.getElements('.brand_input');
    if(brandInputField[0]) {
      if(brandInputField[0].value) {
        brandInputField[0].value = '';
	    changed = true;
	  }
    }
    if(naviObj.resetSelectedValuesInternal(this, naviObj) || changed)
      naviObj.sendRequest(true, '');
  },
  
  resetSelectedValuesInternal : function(el, naviObj){
    var allValues = el.getElements('.filter_value');
    var changed = false;
    for(var idx = 0; idx < allValues.length; idx++){
      var tmp = allValues[idx];
      var classSuffix = '';
      if(tmp.hasClass('filter_value_icon'))
        classSuffix = '_icon';
      if(tmp.get('currentstate') == 'activeSelected' || tmp.get('currentstate') == 'inactiveSelected'){
        changed = tmp.get('currentstate') == 'activeSelected';
        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 (this.options.multipleSelectionFilters.indexOf(tmp.get('filterid')) == -1) {
          naviObj.showHideFilterElements(tmp);
        }
      }
    }

	return changed;
  },
  
  valueEntered : function(naviObj){
    naviObj.resetSelectedValuesInternal(this.getParent().getParent(), naviObj);
    naviObj.sendRequest(true, '');
  },
  
  sliderPreisSelect : function (left, right) {
    var allValues = $$('#filterNavi1 .filter_value');
    var size = allValues.length;
    for(var idx = 0; idx < size; idx++) {
      if(allValues[idx].get('filtercategory') == 'Preis') {
         allValues[idx].set('filtername', left + '-' + right) ;
      }
    }
    filterobj.sendRequest(true, '');
  },

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

  getCookieValue : function(key){
    var categoryCookie = Cookie.read(this.options.cookieName)
    var result = '';
    if(categoryCookie && JSON.decode(categoryCookie)[key]){
      result = JSON.decode(categoryCookie)[key];
    }
    return result;
  },

  sendRequest : function(addhistoryhash, prodSorting){
   if(this.timer != null){
    $clear(this.timer);
   }
   
   this.timer = this.sendRequestInternal.delay(this.requestDelay, this, [addhistoryhash, prodSorting]);
  },

  sendRequestInternal : function(addhistoryhash, prodSorting){
    var page = 1;
    var prodsOnPage = ggobj.DEFAULT_PRODUCTS_ON_PAGE;
    var previousScrollPosY = 0;
    
    var lastSearchPageUrl = this.encodeValue(Cookie.read(ggobj.COOKIE_WC_SEARCH_PAGE_URL));
    var encodedUrl = this.encodeValue(location.href);
    if (lastSearchPageUrl && encodedUrl == lastSearchPageUrl) {
      prodsOnPage *= parseInt(Cookie.read(ggobj.COOKIE_WC_SEARCH_PAGE));
    } else {
      Cookie.write(ggobj.COOKIE_WC_SEARCH_PAGE_URL, encodedUrl, {expires: 1, path: '/'});
      Cookie.write(ggobj.COOKIE_WC_SEARCH_PAGE, 1, {expires: 1, path: '/'});
      Cookie.write(ggobj.COOKIE_WC_SEARCH_PAGE_POS_Y, 0, {expires: 1, path: '/'});
    }
    if (Cookie.read(ggobj.COOKIE_WC_SEARCH_PAGE_POS_Y)) {
      previousScrollPosY = Cookie.read(ggobj.COOKIE_WC_SEARCH_PAGE_POS_Y);
    }
    
    var searchCookie = Cookie.read(this.options.cookieName);
    if(searchCookie){
      if(!prodSorting){
        if(JSON.decode(searchCookie).prodSorting){
          prodSorting = JSON.decode(searchCookie).prodSorting;
        }
      }
    }

    if(addhistoryhash){
      this.writeCookie(prodSorting);
      searchCookie = Cookie.read(this.options.cookieName);
      historyManager.addState(searchCookie);
    }
    
    if(this.request != null && this.request.running){
      this.request.cancel;
    }
    
    var targetDiv = $('content_new');
//    var targetDiv = $('content');
    var currentSearchObject = this;
    this.request = new Request.HTML({
      url        : 'AjaxSearchResultView',
      update     : targetDiv,
      evalScripts: true,
      onComplete : function() {
        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});
                            if (previousScrollPosY > 0 ) {
                              window.scrollTo(0, previousScrollPosY);
                            }
                            currentSearchObject.hookScrollPosSaver();
                          }}
       ).start(1.0);
      },
      onRequest  : function() {
        if (currentSearchObject.scrollLoader) {
			currentSearchObject.scrollLoader.detach();
		}
        currentSearchObject.removeScrollPosSaver();
        targetDiv.set('html', '');
        targetDiv.setStyles({background: 'url(/images_shop/storefront/ajax_loader.gif) no-repeat center', height: '400px'});
      }
    });

    this.request.send("storeId=" + this.options.storeId + "&langId=" + this.options.langId + "&catalogId=" + this.options.catalogId + "&searchTerm=" + encodeURIComponent(this.options.searchTerm) + "&cId=" + this.options.cookieName + "&page=" + page + "&prodsOnPage=" + prodsOnPage + "&prodSorting=" + prodSorting + "&categoryId=" + this.options.categoryId + "&log=nav");
  },
  
  sendNextPageRequest : function(page, prodSorting){
   if(this.timer != null){
    $clear(this.timer);
   }
   this.timer = this.sendNextPageRequestInternal.delay(this.requestDelay, this, [page, prodSorting]);
  },

  sendNextPageRequestInternal : function(page, prodSorting){
    page = parseInt(page);// we have to normalizes this value because it is computed in the JSP and the might be formated as float
    var prodsOnPage = ggobj.DEFAULT_PRODUCTS_ON_PAGE;
    
    var searchCookie = Cookie.read(this.options.cookieName);
    if(searchCookie){
      if(!prodSorting){
        if(JSON.decode(searchCookie).prodSorting){
          prodSorting = JSON.decode(searchCookie).prodSorting;
        }
      }
    }
    
    Cookie.write(ggobj.COOKIE_WC_SEARCH_PAGE, page, {expires: 1, path: '/'});

    if(this.request != null && this.request.running){
      this.request.cancel;
    }
    
    var targetDiv = new Element('div', {'id': 'content_products_page_' + page, 'class' : 'content_products_page', 'style': 'height:0px;'});
    $('content_products').adopt(targetDiv);
    this.request = new Request.HTML({
      url        : '/webapp/wcs/stores/servlet/AjaxSearchResultNextPageView',
      update     : targetDiv,
      evalScripts: true,
      onComplete : function() {
        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);
      },
      onRequest  : function() {
        targetDiv.set('html', '');
        targetDiv.setStyles({background: 'url(/images_shop/storefront/ajax_loader.gif) no-repeat center', height: '174px'});
      }
    });

    this.request.send("storeId=" + this.options.storeId + "&langId=" + this.options.langId + "&catalogId=" + this.options.catalogId + "&searchTerm=" + encodeURIComponent(this.options.searchTerm) + "&cId=" + this.options.cookieName + "&page=" + page + "&prodsOnPage=" + prodsOnPage + "&prodSorting=" + prodSorting + "&categoryId=" + this.options.categoryId);
  },
  
  hockSearchScrollListener : function(nextpage, sorting) {
    var currentSearchObject = this;
	window.addEvent(window.ie ? 'load' : 'domready', function(){
		if (currentSearchObject.scrollLoader) {
			currentSearchObject.scrollLoader.detach();
		}
		currentSearchObject.scrollLoader = new ScrollLoader({
			container: window,
			area: 500,
			onScroll: function(){
				// We detach the listener because we attach a new one with the next page
				this.detach();
				currentSearchObject.scrollLoader = null;
				currentSearchObject.sendNextPageRequest(nextpage, sorting);
			}
		});
	});
  },
  
  encodeValue : function(value) {
  	if (value) {
  		value = encodeURIComponent(decodeURIComponent(value));
  	}
  	return value;
  },
  
  saveScrollPosY : function() {
    var scrollPosY = 0;
	if (window.pageYOffset) {
		scrollPosY = window.pageYOffset;
	} else if (document.documentElement) {
		scrollPosY = document.documentElement.scrollTop;
	} else if (document.body.scrollTop > 0) {
		scrollPosY = document.body.scrollTop;
	} else {
		scrollPosY = document.html.scrollTop;
	}
	Cookie.write(ggobj.COOKIE_WC_SEARCH_PAGE_POS_Y, scrollPosY, {expires: 1, path: '/'});
  },
  
  hookScrollPosSaver : function() {
    window.addEvent('scroll', this.saveScrollPosY);
  },
  
  removeScrollPosSaver : function() {
    window.removeEvent('scroll', this.saveScrollPosY);
  },
  
  setPIDs : function(pIDsObject) {
    this.pIDs = pIDsObject['pIDs'];
    this.paths = pIDsObject['paths'];
  },
  
  checkNavigationLinks : function(pID) {
    if(this.pIDs.length > 0) {
      var prevI = $$("#prev-inactive");
      var prevA = $$("#prev-active");
      var nextI = $$("#next-inactive");
      var nextA = $$("#next-active");
      
      var idx = 0;
      for(i = 0; i < this.pIDs.length; i++) {
        if(pID == this.pIDs[i]) {
          idx = i;
        }
      }
      
      var state = 1;
      if(pID == this.pIDs[0]) {
        if(this.pIDs.length == 1) {
          state = 2;
        } else {
          state = 3;
        }
      } else if(pID == this.pIDs[this.pIDs.length-1]) {
        state = 4;
      }
      
      switch(state) {
        case 1:
          prevI[0].setStyle('display', 'none');
          prevA[0].setProperty('href', this.paths[idx - 1]);
          nextI[0].setStyle('display', 'none');
          nextA[0].setProperty('href', this.paths[idx + 1]);
          break;
        case 2: 
          prevA[0].setStyle('display', 'none');
          nextA[0].setStyle('display', 'none');
          break;
        case 3: 
          prevA[0].setStyle('display', 'none');
          nextI[0].setStyle('display', 'none');
          nextA[0].setProperty('href', this.paths[idx + 1]);
          break;
        case 4: 
          prevI[0].setStyle('display', 'none');
          prevA[0].setProperty('href', this.paths[idx - 1]);
          nextA[0].setStyle('display', 'none');
          break;
      }
    }
  }
});

