Dvintage.Advertisments = Class.create({
    initialize: function(){

		this.options = Object.extend({
      		showOnlyNormalHits: false,
			adClassName: null,
			loadLastRequest: false,
            customShop: false
        }, arguments[0] || { });

        this.facetdrawer = $('facetdrawer');
		this.firsRequest = true;
        this.pageSize = 24;
        this.pageIndex = 0;

        var ps = this.pageSize;
        this.totalHitCount = 0;
        this.pageHitCount = 0;

        this.getString = {
			'page.size':ps,
			'page.index':0//,sort:'vintageness+asc'
		};

        this.selectedFacetElements = new Hash();

        this.sortValues = new Hash();

		this.freetext = '';

        //default sort;
        this.sortOn('displayDate', 0);
        this.facets = ['color','size','priceRange'];

		this.inProgress = false;		// temporary. todo: make more dynamic, enable user to cancel previous request...
        this.sf = new Dvintage.SizeFilter();

        this.facetlist = $('facetdrawer').select('ul[class="facetlist"]')[0];
        // $('facetdrawer').appendChild(this.facetlist);
        

        this.categoryLI = this.facetlist.select('li[class="facetlistitem category"]')[0]; //new Element('li', {className:'facetlistitem category'});
        this.categoryUL = this.categoryLI.select('ul[class="facet"]')[0]; //new Element('ul', {className:'facet'});
        this.brandLI = this.facetlist.select('li[class="facetlistitem brand"]')[0]; //new Element('li', {className:'facetlistitem brand'});
        this.brandUL= this.brandLI.select('ul[class="facet"]')[0]; //new Element('ul', {className:'facet'});
        this.colorLI = new Element('li', {className:'facetlistitem color'});
        this.colorUL = new Element('ul', {className:'facet'});
        this.sizeLI = new Element('li', {className:'facetlistitem size'});
        this.sizeUL = new Element('ul', {className:'facet'});
        this.priceRangeLI = new Element('li', {className:'facetlistitem priceRange'});
        this.priceRangeUL = new Element('ul', {className:'facet'});
        this.countryLI = this.facetlist.select('li[class="facetlistitem country"]')[0]; //new Element('li', {className:'facetlistitem country'});
        this.countryUL = this.countryLI.select('ul[class="facet"]')[0]; //new Element('ul', {className:'facet'});
        this.customShopLI = new Element('li', {id:'customshop_li', className:'facetlistitem customShop'});

		this.breadcrumb = new Dvintage.Breadcrumb();
		this.breadcrumb.insert();

        this.facetlist.appendChild(this.categoryLI);
        this.facetlist.appendChild(this.brandLI);
        this.facetlist.appendChild(this.colorLI);
        this.facetlist.appendChild(this.sizeLI);
        this.facetlist.appendChild(this.priceRangeLI);
        this.facetlist.appendChild(this.countryLI);
        this.facetlist.appendChild(this.customShopLI);        

		var options = {
			trackStyle:{
				position:'absolute',
				background:'url(../images/facets/scroll.png) no-repeat',
				width:'9px'
			},
			offsetBy:{left:-10,top:0}
		}

        this.brandScrollblock = new Dvintage.Scrollblock(this.brandLI, options);
        this.categoryScrollblock = new Dvintage.Scrollblock(this.categoryLI, options);
        this.colorScrollblock = new Dvintage.Scrollblock(this.colorLI, options);
        this.sizeScrollblock = new Dvintage.Scrollblock(this.sizeLI, options);
        this.priceRangeScrollblock = new Dvintage.Scrollblock(this.priceRangeLI, options);
        this.countryScrollblock = new Dvintage.Scrollblock(this.countryLI, options);

		var setBoxHeightAlterBy = ($('customshopbottombar'))? -34:-26;
		this.scrollbar = new Dvintage.Scrollblock($('hits'), {
			offsetBy:{left:-10,top:0},
			setBoxHeight:false,
			setBoxHeightAlterBy:setBoxHeightAlterBy,
			setBoxHeightAdditionalElements:[$('customshopbottombar'), $('footer')]
		});

		Event.observe(window, 'resize', function(){this.scrollbar.reset()}.bind(this));

       this._initHistory();

        this._loadBrands();

		var _facets = this;
        this.categoryUL.select('li.facetvalue a').each(function(facetElement) {
            // Half the code relies on html attributes to pass values, and uses different ways to get it
            // Copying the relevant attribute to the html element is the easiest way to make it work.
            facetElement.setAttribute('name', facetElement.parentNode.getAttribute('name'));
            facetElement.setAttribute('displayvalue', facetElement.parentNode.getAttribute('displayvalue'));
            
            facetElement.observe('click',function(e){
            	e.stop();
                if (_facets.inProgress) {
                    return;
                }

                // unset size, otherwise, there's no way to unset the selected size.
                if (_facets.sizeUL.down('.facetselected')) {
                    _facets.unsetElement('size', _facets.sizeUL.down('.facetselected'));
                }

                _facets.toggleElement('category', facetElement);
                _facets.setPageIndex(0);
                _facets._showFacetProgress();
                _facets.doRequest();
                
            });
            if (facetElement.hasClassName('childcategory')){
	            if (!this.alternate)
	                this.alternate = '#f6f6f6';
	                
	            facetElement.parentNode.setStyle({cursor:'pointer', background:this.alternate});
	            if (this.alternate == '#f6f6f6')
	                this.alternate = '#fff';
	            else
	                this.alternate = '#f6f6f6';
	
	            if(this.isSelectedElement('category', facetElement)) {
	                this.selectedFacetElements.unset('category');
	                this.setElement('category', facetElement);
	            }
	        }
        }.bind(this));

        this.brandUL.select('li a').each(function(facetElement) {
            // Half the code relies on html attributes to pass values, and uses different ways to get it
            // Copying the relevant attribute to the html element is the easiest way to make it work.
            facetElement.setAttribute('name', facetElement.parentNode.getAttribute('name'));
            facetElement.setAttribute('displayvalue', facetElement.parentNode.getAttribute('displayvalue'));
            
            facetElement.observe('click',function(e){
            	e.stop();
                if (_facets.inProgress) {
                    return;
                }

                // unset size, otherwise, there's no way to unset the selected size.
                if (_facets.sizeUL.down('.facetselected')) {
                    _facets.unsetElement('size', _facets.sizeUL.down('.facetselected'));
                }

                _facets.toggleElement('brand', facetElement);
                _facets.setPageIndex(0);
                _facets._showFacetProgress();
                _facets.doRequest();
            });
            
            if (!this.alternate)
                this.alternate = '#f6f6f6';
                
            facetElement.setStyle({cursor:'pointer', background:this.alternate});
            if (this.alternate == '#f6f6f6')
                this.alternate = '#fff';
            else
                this.alternate = '#f6f6f6';

            if(this.isSelectedElement('brand', facetElement)) {
                this.selectedFacetElements.unset('brand');
                this.setElement('brand', facetElement);
            }
        }.bind(this));

        this.countryUL.select('li a').each(function(facetElement) {
            // Half the code relies on html attributes to pass values, and uses different ways to get it
            // Copying the relevant attribute to the html element is the easiest way to make it work.
            facetElement.setAttribute('name', facetElement.parentNode.getAttribute('name'));
            facetElement.setAttribute('displayvalue', facetElement.parentNode.getAttribute('displayvalue'));
            
            facetElement.observe('click',function(e){
            	e.stop();
                if (_facets.inProgress) {
                    return;
                }

                // unset size, otherwise, there's no way to unset the selected size.
                if (_facets.sizeUL.down('.facetselected')) {
                    _facets.unsetElement('size', _facets.sizeUL.down('.facetselected'));
                }

                _facets.toggleElement('country', facetElement);
                _facets.setPageIndex(0);
                _facets._showFacetProgress();
                _facets.doRequest();
            });
            
            if (!this.alternate)
                this.alternate = '#f6f6f6';
                
            facetElement.setStyle({cursor:'pointer', background:this.alternate});
            if (this.alternate == '#f6f6f6')
                this.alternate = '#fff';
            else
                this.alternate = '#f6f6f6';

            if(this.isSelectedElement('country', facetElement)) {
                this.selectedFacetElements.unset('country');
                this.setElement('country', facetElement);
            }
        }.bind(this));
	},

	_initHistory: function(){

        var protoHistoryManager = new ProtoHistoryManager();
		protoHistoryManager.initialize();

		this.historyKey = '';
		this.history = protoHistoryManager.register(
			this.historyKey,
			[0],
			function(values) {
				this._doHistoryRequest(values)
			}.bind(this),
			function(values) {
				return [this.historyKey, '/', values, '/'].join('');
			}.bind(this),
			this.historyKey + '\\/(.+)\\/');

		protoHistoryManager.start();
	},

    _loadBrands:function() {

        this.brandsTransport = new Ajax.Request(Subsite.baseHref + '/ajax/sitedata.html?getbrandstructure', {
            onComplete: function(t){
                var list = t.responseText.evalJSON();
                this.brandMap=$H(list['brands']);
            }.bind(this)
        })
    },
        appendColorFacets:function(valueList) {


        this.colorUL.update();
            valueList.sort(function(a,b) {if(a.order < b.order) return -1;if(b.order< a.order) return 1;return 0;} ).each(
			function(value){


               var displayValue = value.displayName;
               var element = new Element('li', {className:'facetvalue'});
			   var element = new Element('li', {className:'facetvalue'}).writeAttribute('name', value.name).writeAttribute('displayvalue', displayValue).update(displayValue);

			   	var colorthumbnail = new Element('div', {className:'colorthumbnail'});

				if (Dvintage.customColorThumbnails.include(value.name)) {
					colorthumbnail.setStyle({background:'url(/images/wizard/colorpicker_' + value.name + '.png) 1px 1px'});
				} else {
					colorthumbnail.setStyle({backgroundColor:'#'+value.name});
				}

				// Webkit fix
				if (Prototype.Browser.WebKit) {
					colorthumbnail.setStyle({marginTop:'3px'});
				}

               //element.setAttribute('name',value.name);
               //element.update(displayValue);
			   element.insert(colorthumbnail);

				if (!this.alternate)
					this.alternate = '#f6f6f6';
	            element.setStyle({cursor:'pointer',background:this.alternate});
				if (this.alternate == '#f6f6f6')
					this.alternate = '#fff';
				else
					this.alternate = '#f6f6f6';

				element.observe('click',function(){

                    if (this.inProgress) {
						return;
                    }

                    this.toggleElement('color', element);
					this.setPageIndex(0);
					this._showFacetProgress();
					this.doRequest();

				}.bind(this))

                if(this.isSelectedElement('color', element)) {
                    this.selectedFacetElements.unset('color');
                    this.setElement('color', element);
                }

				this.colorUL.appendChild(element)
			}.bind(this)
		)
		this.colorLI.appendChild(this.colorUL);


		this.colorScrollblock.update();
    },

    appendSizeFacets:function(valueList) { //todo - fix this method, it breaks when there is no size category set

		this.sizeUL.update();

        if(this.isSelected('category') && this.sf.hasSizesByName(this.getSelectedResolvedValue('category'))) {

            var listElement = new Element('li', {className:'facetvalue '}).setStyle({height: '20px', background:'none'});
            var selectBox = new Element('select', {name:'country'});

			var handleChange = function(){

                    this.sf.setCountry(selectBox.options[selectBox.selectedIndex].value);
                    var elements = $$('.sizevalue');
                    var i=0;
                    while(elements[i]) {

						var displayValue = this.sf.getDisplayValue(elements[i].getAttribute('name'));
						elements[i].update(displayValue);

						if (elements[i].hasClassName('facetselected')) {

							this.breadcrumb.set('size', displayValue);

						}

                        i++;

                    }
			}



			for(var i = 0;i<this.sf.getCountries().length;i++) {
//
                    var option = new Element('option', {className:'facet ', value:this.sf.getCountries()[i]});
					var countryFormatted = this.sf.getCountries()[i];
					if (countryFormatted == 'S/M/L') {
						// hack to properly format s/m/l
						countryFormatted = 'S | M | L';
					}
                    option.update(countryFormatted);

					if(this.sf.getCountries()[i] == this.sf.getCountry()) {
                        option.setAttribute('selected', true);
                    }
                    selectBox.appendChild(option);
                };

                //update displayvalues on change
                selectBox.observe('change', handleChange.bind(this));
                selectBox.observe('custom:change', handleChange.bind(this));


                listElement.appendChild(selectBox);
                this.sizeUL.appendChild(listElement);

                valueList.sort(function(a,b) {if(a.name < b.name) return -1;if(b.name < a.name) return 1;return 0;});

        valueList.each(
			function(value){
               var displayValue = 'Size '+value.name;
               var element = new Element('li', {className:'facetvalue sizevalue'});
			   //var element = new Element('li', {className:'facetvalue'}).writeAttribute('name', value.name).writeAttribute('displayvalue', displayValue).update(displayValue);

                element.setAttribute('name',value.name);
               element.update(displayValue);

						if (!this.alternate)
							this.alternate = '#f6f6f6';
                        element.setStyle({cursor:'pointer',background:this.alternate});
						if (this.alternate == '#f6f6f6')
							this.alternate = '#fff';
						else
							this.alternate = '#f6f6f6';

				element.observe('click',function(){

                    if (this.inProgress) {
						return;
                    }

                    this.toggleElement('size', element);
                   //this.setGet('facet.size',value.name);
				   this.setPageIndex(0);
					this._showFacetProgress();
					this.doRequest();
				}.bind(this))



	           if(this.isSelectedElement('size', element)) {
                    this.selectedFacetElements.unset('size');
                    this.setElement('size', element);
                }




				this.sizeUL.appendChild(element)
			}.bind(this))


		} else {
			// there are no sizes.
			var availText = new Element ('span').update('please select a category for available sizes<br /><br /><a href="./sizes-conditions.html?tab=sizechartsection">SIZE CHART &gt;&gt;</a>');
			this.sizeUL.update(availText);
		}



		this.sizeLI.appendChild(this.sizeUL);

		this.sizeScrollblock.update();
		if (typeof selectBox != 'undefined') {
			selectBox.fire('custom:change');
		}

    },

    appendPriceFacets:function(valueList) {

		var sortByName = function(s) { return s.name };

		valueList = valueList.sortBy(sortByName);

        this.priceRangeUL.update();
        if(valueList.length > 0) {
            var curLabel = new Element('li', {className:'facetvalue'})
                    .setStyle({textAlign:'center', background:'none', lineHeight:'16px',height:'16px'})
                    .update(Dvintage.currencyToSymbol($$('input[name=currencypicker]')[0].value));

            this.priceRangeUL.appendChild(curLabel);
        }

        valueList.each(
			function(value){

               var displayValue = value.displayName;
			   var element = new Element('li', {className:'facetvalue'}).writeAttribute('name', value.name).writeAttribute('displayvalue', displayValue).update(displayValue);


			if (!this.alternate)
				this.alternate = '#f6f6f6';
            element.setStyle({cursor:'pointer',background:this.alternate});
			if (this.alternate == '#f6f6f6')
				this.alternate = '#fff';
			else
				this.alternate = '#f6f6f6';

				element.observe('click',function(){

                    if (this.inProgress) {
						return;
                    }

                    this.toggleElement('priceRange', element);
					this.setPageIndex(0);
					this._showFacetProgress();
                    this.doRequest();

				}.bind(this));

	           if(this.isSelectedElement('priceRange', element)) {
                    this.selectedFacetElements.unset('priceRange');
                    this.setElement('priceRange', element);
                }


                this.priceRangeUL.appendChild(element)
			}.bind(this)
		);
		this.priceRangeLI.appendChild(this.priceRangeUL);

		this.priceRangeScrollblock.update();
    },
    isSelected:function(type) {
        return typeof this.selectedFacetElements.get(type) != 'undefined';


    },
    getSelectedValue:function(type) {
        if(typeof this.selectedFacetElements.get(type) != 'undefined') {
              return this.selectedFacetElements.get(type).getAttribute('name');
        } else {
            return '';
        }
    },
    getSelectedResolvedValue:function(type) {
        if(typeof this.selectedFacetElements.get(type) != 'undefined') {
              return this.selectedFacetElements.get(type).innerHTML;
        } else {
            return '';
        }
    },
    isSelectedElement: function(type, element) {
        if(typeof this.selectedFacetElements.get(type) != 'undefined') {
            return this.selectedFacetElements.get(type).getAttribute('name')==element.getAttribute('name');
        } else {
            return false;
        }
    },
    toggleElement:function(type, facetNode) {
        if(this.selectedFacetElements.get(type) == facetNode) {
            this.unsetElement(type,facetNode);
        } else {
            this.setElement(type,facetNode);
        }
    },

    setElement: function(type, facetNode) {

        this.unsetElement(type, this.selectedFacetElements.get(type));
        this.selectedFacetElements.unset(type);
        this.selectedFacetElements.set(type, facetNode);
        facetNode.addClassName('facetselected');

		this.breadcrumb.set(type, facetNode.readAttribute('displayvalue'));

		if (true | type=='color' || type=='country' || type=='category' || type=='brand' || type=='size'|| type=='size') {
	        facetNode.addClassName('facetselectedwithunset');
			if (type == 'color') {
				facetNode.down('div').hide();
			}
		}
    },

    unsetElement: function(type, facetNode) {

		if(facetNode) {

			this.breadcrumb.unset(type);

            facetNode.removeClassName('facetselected');
			if (type=='category' || type=='brand' || type=='country') {
		        facetNode.removeClassName('facetselectedwithunset');
			}
        }
        this.selectedFacetElements.unset(type);
    },

    sortOn: function(value, direction) {
		this.sortValues = new Hash(); //unfortunatly unable to sort on multiple columns
        this.sortValues.set(value, direction);
    },

    filterOld: function(filter) {
        this.filter = filter;
    },

    setPageIndex: function(value) {
        this.pageIndex = value;
    },

    setPageSize: function(value) {
		this.pageIndex = Math.floor(this.pageIndex * (this.pageSize / value));
        this.pageSize = value;
    },

	buildQuery: function() {
        //var query = Object.toQueryString(this.getString).gsub('%2B', '+');
        var query = 'page.size='+this.pageSize+'&page.index=' + this.pageIndex;
        this.selectedFacetElements.each(function(pair) {
            query += '&facet.'+pair.key + '='+encodeURIComponent(pair.value.getAttribute('name'));
        });
        this.sortValues.each(function(pair) {
            query += '&sort='+pair.key+'+'+(pair.value==0?'desc':'asc');
        });
		if(this.freetext != '') {
			query += '&search.query='+encodeURIComponent(this.freetext);
		}
        if (this.filter != null) {
            query += '&filterOld=' + this.filter;
        }
        return query;
    },

	_setFacets: function(tuple){

		var facetname = tuple[0];
		var facetvalue = decodeURIComponent(tuple[1]);
		switch (facetname) {
			case 'facet.category':
				var element = this.categoryUL.down('li[name="' + facetvalue + '"]');
				if (element)
		            this.setElement('category', element);
			break;
			case 'facet.brand':
				var element = this.brandUL.down('li[name="' + facetvalue + '"]');
				if (element)
					this.setElement('brand', element);
			break;
			case 'facet.color':
				var element = this.colorUL.down('li[name="' + facetvalue + '"]');
				if (element)
					this.setElement('color', element);
			break;
			case 'facet.size':
				var element = this.sizeUL.down('li[name="' + facetvalue + '"]');
				if (element)
					this.setElement('size', element);
			break;
			case 'facet.priceRange':
				var element = this.priceRangeUL.down('li[name="' + facetvalue + '"]');
				if (element)
					this.setElement('priceRange', element);
			break;
			case 'facet.country':
				var element = this.categoryUL.down('li[name="' + facetvalue + '"]');
				if (element)
		            this.setElement('country', element);
			break;
		}

	},

	_doHistoryRequest: function(values){
        var string = values[0];
		if (string == 0) {
			return;
		}
		var array = string.split('/');
		var q = '';
		var tuple = [];

		// unset all facets.
		$$('.facetlist .facetselected').each(function(element){
			type = $w(element.up().up().className)[1];
			this.unsetElement(type, element);
		}.bind(this))

		var setFacets = this._setFacets.bind(this);


		array.each(function(value, i){
			value = value.gsub('/', '%2F');
			if ((i % 2) == 0) {
				tuple = [];
				tuple.push(value)
				q += value + '=';
			}
			else {
				tuple.push(value);
				setFacets(tuple);
				q += value + '&';
			}

		})


		this.doRequest(q.substr(0,q.length - 1));
	},

    doRequest:function(query){

        var requestFunction = function(query) {
            c('query1: ' + query)
    // 		can I do this?
            if (this.inProgress)
                return;
            if (this.transport)
                this.transport.transport.abort()

            this.inProgress = true;

            this.scrollbar.hideTrack();

            if (query) {
                var q = query;
            } else {
                var q = this.buildQuery();
            }
            c('query2: '+q)

            // set history
            var hq = q.gsub('&','/').gsub('=','/');
            this.history.setValue(0, hq);

            this.transport = new Ajax.Request(Subsite.baseHref + 'advertisementlist.html?' + q, {
                onSuccess: function (t) {

                    var response = t.responseText.evalJSON();
                    var totalHitCount = response.normalHits.totalHitCount;

                    this.normalHits = response.normalHits;
                    this.premiumHits = response.premiumHits;
                    this.facetList = response.facets;

                    this.firsRequest = false;

                    // update these values here or buildQuery will see the correct values. Hopefully this wont break
                    // anything else.
                    this.setPageSize(this.normalHits['pageSize']);
                    this.setPageIndex(this.normalHits['pageIndex']);

                    Dvintage.pager.update(
                            this.normalHits['pageIndex'],
                            this.normalHits['pageSize'],
                            this.normalHits['totalHitCount'],
                            this.normalHits['pageHitCount']
                    );


                    Dvintage.itemsPerPage.displayCurrentItemsPerPage(this.normalHits['pageSize']);

                    this.inProgress = false;
                    this._hideFacetProgress();
                    if (totalHitCount > 0) {
                        this.listAdvertisments();
                    }

                    if (totalHitCount == 0) {
                        this._noResultsMessage();
                    }


                    if (typeof Dvintage.cookieForLoadLastRequest != 'undefined' && this.options.loadLastRequest && q!=null) {
                        this.options.loadLastRequest = false;
                        Dvintage.cookieForLoadLastRequest.unset();
                    }


                    if(totalHitCount > 0) {
                        this.appendColorFacets(this.facetList['color']);
                        this.appendPriceFacets(this.facetList['priceRange']);
                        this.appendSizeFacets(this.facetList['size']);
                    } else {
                       this.colorUL.update();
                        this.sizeUL.update();
                        this.priceRangeUL.update();
                    }

                }.bind(this)
            })
        }.bind(this);

        if ($('editorial')) {
			this.scrollbar.hideTrack();
			new Effect.BlindUp($('editorial'), {duration:.3,afterFinish:function(){
                 this.scrollbar.reset();
                 this.scrollbar.showTrack();
                 requestFunction(query);
            }.bind(this)});
		} else {
            requestFunction(query);
        }
	},

    _noResultsMessage:function() {

        $('hits').insert(new Element('h4').update($('noresults').readAttribute('header')));
        $('hits').insert(new Element('div', {id:'whiteboard'}).update($('noresultsmessage').innerHTML));

    },

	_showFacetProgress:function() {
		var channel = Dvintage.channel.getChannel();
		var element = new Element('img', {src:'images/main/ajax_loader_white_bg_' + channel + '.gif', id:'facetprogress'});
		$('main').insert(element);
	},

	_hideFacetProgress:function() {
		if ($('facetprogress')) {
			$('facetprogress').remove();
		}
    },

    isSet:function(attr) {
        return this.getString[attr];
    },
    setGet:function(attr, val){
		this.getString[attr] = val;
	},
	unsetGet:function(attr){
		delete this.getString[attr];
	},
    wireTextSearch: function() {
        return this._wireQuery();
    },
    _wireQuery: function () {
		$('go').onclick = function(){this._doQuery($('search').value)}.bind(this)
		$('search').observe('keydown', function(evt){
			if (evt.keyCode == Event.KEY_RETURN)
				this._doQuery($('search').value);
		}.bind(this));
	},
	_doQuery: function (val) {
		if (val!='') {
			var unsetNode = new Element('img', {id:'freetextunset',src:'/images/facets/unset.png'});
			$('main').insert(unsetNode);
			unsetNode.onclick = function(){$('search').value = ''; unsetNode.remove(); this._doQuery('')}.bind(this)
		}
		this.freetext = val;
		this.doRequest();
	},

    listAdvertisments: function(){

        if (!this.options.showOnlyNormalHits) {

			this.premiumHits.each(function(hit, i){

                // show only first 2 hits.
				if (i > 1)
					return;

                var currency = Dvintage.currencyToSymbol(hit.priceCurrency);
                var cat = Dvintage.cats2cat(hit.category);

				var element = new Element('div', {className: 'premiumAd'});
				element.observe('click', function() {
					clickLink("./" + encodeURIComponent(this.brandMap.get(hit.brand).name) +
                                                   "/" + encodeURIComponent(cat) + "/" +
                                                   "advertisement/" + hit.encodedId + "/details.html");
				}.bind(this));

				var currency = Dvintage.currencyToSymbol(hit.priceCurrency);
				var cat = Dvintage.cats2cat(hit.category);
				var title = new Element('h2', {className: 'premiumAdTitle'});
				var link = new Element('a', {href: './'+ encodeURIComponent(this.brandMap.get(hit.brand).name) +
                                                   '/' + encodeURIComponent(cat) + '/' +
                                                   'advertisement/' + hit.encodedId + '/details.html'}).update(this.brandMap.get(hit.brand).name + ' ' + cat);
				
				var price_eur = new Element('div', {className: 'premiumAdPrice', pricecurrency:"EUR"}).update(Dvintage.currencyToSymbol('EUR') + ' ' + Math.round(hit.price_eur) + ',-');
				var price_usd = new Element('div', {className: 'premiumAdPrice', pricecurrency:"USD"}).update(Dvintage.currencyToSymbol('USD') + ' ' + Math.round(hit.price_usd) + ',-').hide();
				var price_jpy = new Element('div', {className: 'premiumAdPrice', pricecurrency:"JPY"}).update(Dvintage.currencyToSymbol('JPY') + ' ' + Math.round(hit.price_jpy) + ',-').hide();

				var description = new Element('div', {
					className: 'premiumAdDescription'
				}).update(hit.description.truncate(175));
				var details = new Element('div', {
					className: 'premiumAdDetails'
				}).update('DETAILS >>');

                var countryCode = new Element('div', {className:'premiumAdCountryCode'}).update(hit.country);

				title.insert(link);
                element.insert(title);
                element.insert(description);
                element.insert(details);
                if(hit.sold) {
                    var sold = new Element('div', {
                         className: 'premiumAdSold'
                     }).update("SOLD");
                    element.appendChild(sold);
                } else {
                    var createdOn = new Element('div', {
                        className: 'premiumAdCreatedOn'
                    }).update(hit.createdOn.match(/^[^ ]*/)[0]);
                    element.insert(createdOn);
                }

                if (hit.justIn) {
                    var justIn = new Element('div', {
                        className: 'premiumAdJustIn'
                    }).update("Just in")
                    element.appendChild(justIn);
                }

                element.insert(countryCode);
                element.insert(price_eur);
                element.insert(price_usd);
                element.insert(price_jpy);
                
                $('hits').insert(element);

                new Dvintage.RotatingPhoto(element, hit.encodedId, hit.owner)
			}.bind(this));

		}

		var renderNormalHits = function(hit, index) {

			var className = (this.options.adClassName)? this.options.adClassName:'normal';
            var cat = Dvintage.cats2cat(hit.category);
            var currency = Dvintage.currencyToSymbol(hit.priceCurrency);

            var element = new Element('div', {className:className+'Ad'});
            element.observe('click', function() {
				clickLink("./" + encodeURIComponent(this.brandMap.get(hit.brand).name) +
                                                   "/" + encodeURIComponent(cat) + "/" +
                                                   "advertisement/"+ hit.encodedId +"/details.html" +
                								   "?fromSearch=true&hitNo=" + ( ( this.normalHits['pageIndex'] * this.normalHits['pageSize'] ) + index ) +
            									   "&totalResults=" + this.normalHits['totalHitCount'] +
              									   "&" + this.buildQuery()+ "");
			}.bind(this));
			
			if (className == 'premium') {
				element.addClassName('noStamp');
			}
			var image = new Element('img', {className:className+'AdImage'});
			image.src = './advertisement/' + hit.encodedId + '/' + hit.owner + '/image/NORMAL/front.html';


            var country = hit.country;

            if (className == 'premium') {  //customshop has premiummode
				var title_eur = new Element('div', {className: 'premiumAdTitle', pricecurrency:"EUR"}).update(this.brandMap.get(hit.brand).name + ' ' + cat + ' ' + Dvintage.currencyToSymbol('EUR') + ' ' + Math.round(hit.price_eur) + ',-');
				var title_usd = new Element('div', {className: 'premiumAdTitle', pricecurrency:"USD"}).update(this.brandMap.get(hit.brand).name + ' ' + cat + ' ' + Dvintage.currencyToSymbol('USD') + ' ' + Math.round(hit.price_usd) + ',-').hide();
				var title_jpy = new Element('div', {className: 'premiumAdTitle', pricecurrency:"JPY"}).update(this.brandMap.get(hit.brand).name + ' ' + cat + ' ' + Dvintage.currencyToSymbol('JPY') + ' ' + Math.round(hit.price_jpy) + ',-').hide();
				element.insert(title_eur);
				element.insert(title_usd);
				element.insert(title_jpy);

                var description = new Element('div', {className: 'premiumAdDescription'}).update(hit.description.truncate(175));
                element.insert(description);

            } else {
				var title = new Element('div', {className:className+'AdTitle'}).update(String(this.brandMap.get(hit.brand).name + ' ' + cat).truncate(23));
				element.appendChild(title);
				
				var title = new Element('h3', {className:className+'AdTitle'});
				var link = new Element('a', {href: './'+ encodeURIComponent(this.brandMap.get(hit.brand).name) +
                                                   '/' + encodeURIComponent(cat) + '/' +
                                                   'advertisement/'+hit.encodedId+'/details.html' +
                								   '?fromSearch=true&hitNo=' + ( ( this.normalHits['pageIndex'] * this.normalHits['pageSize'] ) + index ) +
            									   '&totalResults=' + this.normalHits['totalHitCount'] +
              									   '&' + this.buildQuery()}).update(String(this.brandMap.get(hit.brand).name + ' ' + cat).truncate(23));
              	title.appendChild(link);
				element.appendChild(title);
			}

			if (className == 'normal') {
				var price_eur = new Element('div', {className: className + 'AdPrice', pricecurrency:"EUR"}).update(Dvintage.currencyToSymbol('EUR') + ' ' + Math.round(hit.price_eur) + ',-');
				var price_usd = new Element('div', {className: className + 'AdPrice', pricecurrency:"USD"}).update(Dvintage.currencyToSymbol('USD') + ' ' + Math.round(hit.price_usd) + ',-').hide();
				var price_jpy = new Element('div', {className: className + 'AdPrice', pricecurrency:"JPY"}).update(Dvintage.currencyToSymbol('JPY') + ' ' + Math.round(hit.price_jpy) + ',-').hide();
				element.insert(price_eur);
				element.insert(price_usd);
				element.insert(price_jpy);
			}
			var details = new Element('div', {className:className+'AdDetails'}).update('DETAILS >>');
            var countryCode = new Element('div', {className:className+'AdCountryCode'}).update(hit.country);
			element.appendChild(image);
			element.appendChild(details);
            if(hit.sold) {
                var sold = new Element('div', {className:className+'AdSold'}).update("SOLD");
                element.appendChild(sold);
            } else {
               // var createdOn = new Element('div', {className:className+'AdCreatedOn'}).update(hit.createdOn.match(/^[^ ]*/)[0]);
               // element.appendChild(createdOn);
            }

            if (hit.justIn) {
                var justIn = new Element('div', { className: className+'AdJustIn' }).update("Just in")
                element.appendChild(justIn);
            }

            element.appendChild(countryCode);

            $('hits').appendChild(element);
		}.bind(this)

		this.normalHits.hits.each(renderNormalHits)

		this.scrollbar.reset();

		Dvintage.currencySwitcher.update(null);


	}
})

Dvintage.RotatingPhoto = Class.create({
        initialize: function(element, encodedId, owner){

            if(!element) {
                return;
            }
                this.element = element;
                this.encodedId = encodedId;
                this.owner = owner;
                this.image = new Element('img', {className: 'premiumAdImage'});
                this.image.src = './advertisement/' + this.encodedId + '/' + this.owner + '/image/NORMAL/front.html';
                this.views = ['front.html', 'label.html', 'rear.html'];
                this.index = 0;
                this.element.insert(this.image);
				if (!this.element.down('img', 1)) {
					this.image2 = new Element('img', {className: 'premiumAdImage'});
					this.element.insert(this.image2);
				}
		        setTimeout(function(){this._setNextImage();this._rotate();}.bind(this), 1000);
        },

        _setNextImage: function(){

				var topimage = this.element.down('img', 1);
				var bottomimage = this.element.down('img', 0);

                this.element.insert({top:topimage})

				// looks as if IE sometimes loses this image. check for that.
				if (topimage) {
					topimage.src = './advertisement/' + this.encodedId + '/' + this.owner + '/image/NORMAL/' + this.views[this.index];
					topimage.show();
				}

                this.index++;

				if (this.index >= 3) {
					this.index = 0;
				}
        },
        _rotate: function () {
				// looks as if IE sometimes loses this image. check for that.
				if (!this.element.down('img', 1)) {
					return;
				}
                new Effect.Fade(this.element.down('img', 1), {
                        duration: 3,
                        afterFinish:function(){
								if ($$('#hits .premiumAd').length == 0)
									return;
                                this._setNextImage();
                                setTimeout(function(){this._rotate()}.bind(this), 4000);
                        }.bind(this)
                })
        }
})


Dvintage.ItemsPerPage = Class.create({
	initialize: function() {
		document.observe('dom:loaded', this._initialize.bind(this));
	},
    _initialize: function() {        
        if (!$('sorting'))
			return;

		this.itemsPerPageUL = new Element('ul', {className:'itemsperpage'});
        this.label		= new Element('li').addClassName('label').update('ITEMS PER PAGE:');
        this.label8		= new Element('li', {key:8}).update(10).setStyle({border:0});
        this.label16	= new Element('li', {key:16}).update(18);
        this.label24	= new Element('li', {key:24}).update(26);
        this.label32	= new Element('li', {key:32}).update(34);
		this.labels = [this.label, this.label8, this.label16, this.label24, this.label32];
		this.labels.each(function(label){this.itemsPerPageUL.insert(label)}.bind(this));
		$('sorting').insert(this.itemsPerPageUL);
		this.labels.each(function(label){label.observe('click', function(){this.setItemsPerPage(label)}.bind(this))}.bind(this));
	},

	displayCurrentItemsPerPage: function(itemsperpage){

		var setFunction = function() {
			if (this.itemsPerPageUL.down('li.active')) {
				this.itemsPerPageUL.down('li.active').setStyle({color:'#ADA5A3'}).removeClassName('active');
	        }
	        if(this.itemsPerPageUL.down('li[key="' + itemsperpage + '"]')) {
	            this.itemsPerPageUL.down('li[key="' + itemsperpage + '"]').setStyle({color:'#000'}).addClassName('active');
	        }
		}.bind(this)

		var setFunctionUlLoaded = function() {

			if (this.itemsPerPageUL) {

				setFunction();
				clearInterval(interval);
			}

		}.bind(this)

		if (this.itemsPerPageUL) {

			setFunction();

		} else {

			var interval = setInterval(setFunctionUlLoaded, 100);

		}

	},

	setItemsPerPage: function(label){
		if (!this.itemsPerPageUL) {return;}

		var size = label.readAttribute('key');
		if (size) {
			Dvintage.advertisements.setPageSize(size);
            $('hits').update().setStyle({left:0});
            Dvintage.advertisements.doRequest();
		}
		this.itemsPerPageUL.down('li.active').setStyle({color:'#ADA5A3'}).removeClassName('active');
	}
})
Dvintage.itemsPerPage = new Dvintage.ItemsPerPage();

// Class for displaying all custom shops in the facet bar
Dvintage.ListCustomShops = Class.create({

    initialize: function(){
		new Ajax.Request(Subsite.baseHref + 'ajax/sitedata.html?getactiveshops', {
            onComplete: function(t){
				this.makeUL();
				var shoplist = t.responseText.evalJSON();
				this.processList(shoplist.shops);
			}.bind(this)
		})

	},

	makeUL: function(){
		this.liDOM = $('customshop_li');
		this.customShopUL = new Element('ul', {className:'facet'});
		this.liDOM.insert(this.customShopUL);
	},

	processList: function(list){
		list.each(this.fillUL.bind(this));

		var options = {
			trackStyle:{
				position:'absolute',
				background:'url(../images/facets/scroll.png) no-repeat',
				width:'9px'
			},
			offsetBy:{left:-10,top:0}
		}

        new Dvintage.Scrollblock(this.liDOM, options);

	},

	fillUL:function(obj) {

		var element = new Element('li', {className:'facetvalue'});
//		element.setAttribute('name',value.code);
		element.update(obj.title);
		if (!this.alternate)
			this.alternate = '#f6f6f6';
		element.setStyle({cursor:'pointer',background:this.alternate});
		if (this.alternate == '#f6f6f6')
			this.alternate = '#fff';
		else
			this.alternate = '#f6f6f6';

		this.customShopUL.insert(element);

		var suffix = (Dvintage.channel.isKids())? '/kids/':'/';
		if(Dvintage.channel.isFashion()) {
            element.observe('click', function(){location.href = 'http://' + obj.subdomain + '.'+ Dvintage.channel.getDomain() + suffix});
        } else {
            element.observe('click', function(){location.href = 'http://' + obj.subdomain + '.'+ Dvintage.channel.getDomain() + suffix});
        }
	}
})

// Class for displaying facet breadcrumb
Dvintage.Breadcrumb = Class.create({
    initialize: function() {
		this.html =
			'<div style="display:none;" id="breadcrumb">' +
				'<span style="display:none;"></span>' +
				'<span style="display:none;"></span>' +
				'<span style="display:none;"></span>' +
				'<span style="display:none;"></span>' +
				'<span style="display:none;"></span>' +
				'<span style="display:none;"></span>' +
				'<a href="profile/mysearches.html">bookmark search &gt;&gt;</a>' +
			'</div>';

		this.sorting = new Hash; this.sorting.set('country', 0); this.sorting.set('category', 1); this.sorting.set('brand', 2); this.sorting.set('color', 3); this.sorting.set('size', 4); this.sorting.set('priceRange', 5);
		this.activeCrumbs = new Hash;
		this.collapsed = true;
	},

	_animate: function(){
		if (this.collapsed && this.activeCrumbs.values().length > 0) {
			this.collapsed = false;
			new Effect.BlindDown(this.topnode, { duration: .5 });
		}

		if (!this.collapsed && this.activeCrumbs.values().length == 0) {
			this.collapsed = true;
			new Effect.BlindUp(this.topnode, { duration: .5 });
		}
	},

	_removeLastBreadCrumbDiv : function(){
		var all_breadcrumb_div = this.topnode.select('.breadcrumb_div');
		all_breadcrumb_div.invoke('show');

		var last_breadcrumb_div = all_breadcrumb_div.pop();
		if (last_breadcrumb_div) {
			last_breadcrumb_div.hide();
		}
	},

	insert: function() {
		$('content').insert({before: this.html});
		this.topnode = $('breadcrumb');
	},

	set: function(type, string) {
		if (string != null) {
			var index = this.sorting.get(type);
			var element = $('main').down('#breadcrumb > span', index);
			element.update(string + '&nbsp;&nbsp;&nbsp;&nbsp; <span class="breadcrumb_div">+</span> &nbsp;&nbsp;&nbsp;&nbsp;').show();
			this._removeLastBreadCrumbDiv();
			this.activeCrumbs.set(index, '');
			this._animate.bind(this).delay(.1);
		}
	},

	unset: function(type) {
		var index = this.sorting.get(type);
		var element = $('main').down('#breadcrumb > span', index);
		element.update('').hide();
		this._removeLastBreadCrumbDiv();
		this.activeCrumbs.unset(index);
		this._animate.bind(this).delay(.1);
	}

});