/*
Script: search.js
	Contains <Search>

Author:
	Alan Roemen
	June 14, 2010

Class: Search
	Ajax page search
*/

var Search = new Class({

  initialize: function() {
    this.hidden = false;
    this.changing = false;

    this.filters = []
    $('sidebar').getElements('div.filter-menu').each(this.setup_filters.bind(this));

    this.tags = [];
    location.pathname.split('/').each(this.setup_tags.bind(this));

		this.query = location.search.match(/q\=(.+?)(?:\&|$)/);
		if ($chk(this.query)) this.query = this.query[1];
		else this.query = '';
		this.setup_search();
		$$('div#top-search-filter input').addEvent('click', this.change.bindWithEvent(this, ['search', false]));

    this.links = [];
    this.filters.each(this.setup_links.bind(this));

    this.setup_menus();

    this.per_page = $$('div.content-nav-number span.select-default');
    $$('div.content-nav-number ul a[href^=limit]').addEvent('click', this.change.bindWithEvent(this, 'per_page'));

    this.sort = $$('div.content-nav-sortby span.select-default');
    $$('div.content-nav-sortby ul a[href^=sortby]').addEvent('click', this.change.bindWithEvent(this, 'sort'));

    this.pages = $$('div.results-pagination a[href^=page]');
    this.pages.addEvent('click', this.change.bindWithEvent(this, 'page'));
    this.page_prev = this.pages[0].getProperty('href').replace(/[^\d]/g, '');
    this.page_next = this.pages.getLast().getProperty('href').replace(/[^\d]/g, '');

    this.search_data = {
      per_page: this.per_page[0].getText().toInt(),
      page: null,
			pages: null,
      sort_by: null,
      items: null,
      item_start: null,
      item_end: null,
      results: null,
      shown: null
    };

    $$('div.content-nav-sortby ul a[href^=sortby]').each(function(el) {
      if (el.getProperty('title') == this.sort[0].getText())
        this.search_data.sort_by = el.getProperty('href').replace(/(?:^\s|\/)|(?:\s|\/)/g, '');
    }.bind(this));

    this.search(false);
		this.scroll = new Fx.Scroll(window, {
			wait: true,
			duration: 400,
			offset: {'x': 0, 'y': -150},
			transition: Fx.Transitions.linear
		});
  },

	setup_search: function() {
		$('search-field').removeEvents();
		$('search-field').addEvent('keydown', function(e) {
			e = new Event(e);
			if (e.key != 'enter') return;
			e.stop();
			this.query = e.target.getProperty('value');
			this.send_query = this.query;
			this.clear_filters();
			this.search();
		}.bind(this));
		$('search-field').addEvent('keyup', function(e) {
			e = new Event(e);
			this.query = e.target.getProperty('value');
		}.bind(this));
	},

  setup_filters: function(el) {
    var filter = {}
    filter.id = this.filters.length;
    filter.selected = el.getElements('.selected').length;
    filter.el = el;
		filter.height = el.getElement('div.filter-options').getSize().scrollSize.y.toInt() - 15;
    this.filters.push(filter);
  },

  setup_tags: function(tag) {
    tag = tag.trim();
    if (tag == '' || tag == 'search') return;
    this.tags.push(tag);
  },

  setup_links: function(menu) {
    menu.el.getElements('li a[href^=/search/]').each(function(el) {
      el.addEvent('click', this.change.bindWithEvent(this, 'tag'));
      this.links.push(el);
    }.bind(this));
    menu.el.getElements('div#choose-rating a[href^=/search/]').each(function(el) {
      el.addEvent('click', this.change.bindWithEvent(this, 'rating'));
      this.links.push(el);
    }.bind(this));
  },

  setup_menus: function() {
    this.filters.each(function(menu) {
      menu.el.getElement('li.filter-button').addEvent('click', this.toggle.bindWithEvent(this, menu));
      if (menu.selected > 0) return;
      this.shut(menu);
    }.bind(this));
  },

	clear_filters: function() {
		this.filters.each(function(filter){
			filter.el.getElements('.selected').each(function(el){ el.removeClass('selected'); });
		}.bind(this));
		this.tags = [];
	},

	change: function(e, what, stop) {
		stop = stop === false ? false : true;
		e = new Event(e);
		if (stop) e.stop();
		if (null === this.search_data.results) return;
		this['change_' + what](e);
		this.changing = true;
	},

  change_tag: function(e) {
    var tag;
    if (e.target.getTag() != 'a') e.target = e.target.getParent();
    tag = e.target.getProperty('href').replace(/^(?:\s|\/)|(?:\s|\/)$/g, '').split('/').pop();

    if (this.tags.contains(tag)) {
      e.target.removeClass('selected');
      this.tags.remove(tag);
    } else {
      e.target.addClass('selected');
      this.tags.push(tag);
    }
    this.search_data.page = 1;
    this.search();
  },

  change_rating: function(e) {
    var tag, match, rating;
    if (e.target.getTag() != 'a') e.target = e.target.getParent();
    tag = e.target.getProperty('href').replace(/^(?:\s|\/)|(?:\s|\/)$/g, '').split('/').pop();
		rating = tag.replace(/[^0-9]/g, '');

		this.tags.each(function(t){
			match = t.match(/rating\-\d+/);
			if (match) this.tags.remove(match[0]);
		}.bind(this));
		if (tag == match)
			rating = 0;
		else this.tags.push(tag);

		e.target.getParent().getElements('a[href^=/search/]').each(function(el){
			var link_rating = el.getProperty('href').match(/rating\-(\d+)/)[1];
			el = el.getElement('img');
			if (link_rating <= rating)
				el.setProperty('src', '/images/star.png').addClass('selected');
			else
				el.setProperty('src', '/images/empty-star.png').removeClass('selected');
		}.bind(this));
    this.search_data.page = 1;
    this.search();
  },

  change_per_page: function(e) {
    if (this.changing) return;
		var limit = e.target.getProperty('href').replace(/^(?:\s|\/)|(?:\s|\/)$/g, '');
    this.search_data.per_page = limit.replace(/[^\d]/g, '').toInt();
    this.per_page.each(function(el) {
      el.setHTML(el.innerHTML.replace(/^\d+\</, this.search_data.per_page + '<'));
    }.bind(this));
    this.build_pages();
    this.hide_results();
    this.build();
		this.tags.push(limit);
		this.search(false);
		this.tags.remove(limit);
  },

  change_sort: function(e) {
    this.search_data.sort_by = e.target.getProperty('href').replace(/(?:^\s|\/)|(?:\s|\/)/g, '');
    var sort = e.target.getProperty('title');
    this.sort.each(function(el) {
      el.setHTML(el.innerHTML.replace(/^.+?\</, sort + '<'));
    });
		this.tags.push(this.search_data.sort_by);
    this.search();
		this.tags.remove(this.search_data.sort_by);
  },

  change_page: function(e) {
    if (this.changing) { return; }
		e.target = $(e.target);
    if (e.target.getTag() != 'a') e.target = e.target.getParent();
    var page = e.target.getProperty('href').replace(/[^\d]/g, '');
    if (page == this.search_data.page) {
			(function(){ this.changing = false; }).delay(200, this);
			return;
		}
    this.search_data.page = page.toInt();
    this.build_pages();
    this.hide_results();
    this.build();
		this.search(false);
  },

  toggle: function(e, menu) {
    new Event(e).stop();
    if (menu.el.getElement('li.collapsed'))
      this.open(menu);
    else this.close(menu);
  },
  
  open: function(menu) {
    menu.el.getElement('li.filter-button').removeClass('collapsed');
    menu.el.getElement('div.filter-options')
      .setStyles({'padding-left': '15px', 'padding-right': '15px'})
      .effects({duration: 750, transition: Fx.Transitions.Sine.easeInOut})
      .start({
        'height': menu.height,//.el.getElement('div.filter-options').getSize().scrollSize.y.toInt(),
        'padding-top': '15px'
      });
  },
  
  close: function(menu) {
    menu.el.getElement('div.filter-options')
      .setStyle('overflow', 'hidden')
      .effects({duration: 750, transition: Fx.Transitions.Sine.easeInOut})
      .start({
        'height': 0,
        'padding-top': 0
      }).chain(function(){
        menu.el.getElement('li.filter-button').addClass('collapsed');
      }.bind(this));
  },

  shut: function(menu) {
    menu.el.getElement('li.filter-button').addClass('collapsed');
    menu.el.getElement('div.filter-options').setStyles({
      'overflow': 'hidden',
      'height': 0,
      'padding-top': 0
    });
  },

  hide_results: function() {
    //if (this.hidden) return;
		this.scroll.toElement.delay(200, this.scroll, 'main-content');
		$$('div#main-content div.results-none').each(function(el){ el.remove(); this.hidden = true; }.bind(this));
		$$('div#main-content div.results-product, div#main-content div.content-nav-bottom').each(function(el) {
			el.effect('opacity', {duration: (el.hasClass('content-nav-bottom')?0:300), wait: false}).start(0);
    }.bind(this));
		(function(){
			$$('div.results-row').each(function(row){ row.remove(); });
			this.hidden = true;
		}).delay(300, this);
  },

  search: function(rebuild) {
    var url = '/search/';
    rebuild = rebuild === false ? rebuild : true;
    if (rebuild) this.hide_results();

		if (this.tags.length > 0)
	    url = url + this.tags.join('/') + '/';
		if (this.send_query === null)
			$('search-field').setProperty('value', '');
    if (this.remote) this.remote.cancel();
    this.remote = new Json.Remote(url, {
      method: 'get',
      onSuccess: function(obj) {
        obj = Json.evaluate(obj);
        var arr = [];
        $each(obj, function(o, prod_code) {
          o.prod_code = prod_code;
          arr.push(o);
        });
        this.search_data.results = arr;
        if (rebuild)
					this.build();
				else this.build_data();
      }.bind(this)
    }).send({q: this.send_query});
		this.send_query = null;
  },

	build_data: function() {
    this.search_data.items = this.search_data.results.length;
    this.search_data.item_start = this.search_data.per_page * (this.search_data.page - 1) + 1;
    this.search_data.item_end = Math.min(this.search_data.items, this.search_data.per_page + this.search_data.item_start - 1);
    this.search_data.shown = this.search_data.results.slice((this.search_data.item_start - 1), ((this.search_data.item_start - 1) + this.search_data.per_page));
		this.search_data.pages = Math.ceil(this.search_data.items / this.search_data.per_page);
	},

  build_pages: function() {
    var i, pages = [];
    this.page_prev = this.search_data.page - 1 < 1 ? 1 : this.search_data.page - 1;
    this.page_next = this.search_data.page + 1 > this.search_data.pages ? this.search_data.pages : this.search_data.page + 1;
		$$('div.content-nav span.pag-total').each(function(el){
			el.setHTML('of&nbsp;&nbsp;' + this.search_data.pages);
		}.bind(this));

		if (this.search_data.pages > 2) {
			if (this.search_data.page == this.page_prev)
				for (i = this.search_data.page + 2; i >= this.search_data.page; i--) pages.push(i);
			else if (this.search_data.page == this.page_next)
				for (i = this.search_data.page; i >= this.search_data.page - 2; i--) pages.push(i);
			else for (i = this.search_data.page + 1; i >= this.search_data.page - 1; i--) pages.push(i);
		} else {
			for (i = this.search_data.pages; i >= 1; i--) pages.push(i);
		}

    this.pages.each(function(el) {
      if (el.hasClass('results-back'))
        el.setProperty('href', 'page-' + this.page_prev +'/');
      else if (el.hasClass('results-next'))
        el.setProperty('href', 'page-' + this.page_next +'/');
      else if (el.hasClass('number'))
				el.remove();
    }.bind(this));

    $each(pages, function(page) {
      var el = new Element('a', {
        'class': 'number',
        'href': 'page-' + page + '/',
        'events': {
          'click': this.change.bindWithEvent(this, 'page')
        }
      }).setHTML(page + '<span></span>');
      var el2 = el.clone();
      el2.addEvent('click', this.change.bindWithEvent(this, 'page'));
      el.injectAfter($$('div.results-pagination')[0].getFirst());
      el2.injectAfter($$('div.results-pagination')[1].getFirst());
      if (page == this.search_data.page) {
        el.addClass('current-page');
        el2.addClass('current-page');
      }
    }.bind(this));
		this.pages = $$('div.results-pagination a[href^=page]');
		$$('div.content-nav span.items-info').each(function(el){
			el.setHTML(' Items ' + this.search_data.item_start + '-' + this.search_data.item_end + ' of ' + this.search_data.items);
		}.bind(this));
  },

  build: function() {
    if (!this.hidden) {
      this.build.delay(250, this);
      return;
    }
		if (this.search_data.page === null) {
			if ($$('div.results-pagination a.current-page').length != 0)
				this.search_data.page = $$('div.results-pagination a.current-page')[0].getProperty('href').replace(/[^\d]/g,'').toInt();
			else this.search_data.page = 1;
		}
		this.build_data();
		this.build_pages();

    this.counter = 0;
		this.result_row = new Element('div', {'class': 'results-row'});
		this.search_data.shown.each(function(item, i) {
			if (this.counter == 0)
				this.result_row.injectBefore($$('div#main-content div.content-nav-bottom')[0]);
			this.load_result(item, i);
			if (++this.counter >= 4) {
				this.counter = 0;
				new Element('div', {'class': 'clear'}).inject(this.result_row);
				this.result_row = new Element('div', {'class': 'results-row'});
			}
    }.bind(this));
		if (this.counter < 4)
			new Element('div', {'class': 'clear'}).inject(this.result_row);
		this.reload();

		// Call to external JS
    new AddToCart('.add-cart');
  },

  reload: function() {
		$$('div#main-content div.results-product').each(function(el, i) {
			el.effect('opacity', {duration: 300}).start(1);
    }.bind(this));

		if (this.search_data.items == 0) {
			new Element('div', {
				'class': 'results-none'
			}).setHTML('Your search did not find any results.').injectBefore($$('div#main-content div.content-nav-bottom')[0]);
			this.hidden = false;
			this.changing = false;
		} else {
			var el = $$('div#main-content div.content-nav-bottom')[0];
			el.effect('opacity', {duration: 350, wait: false}).start(1).chain(function(){
				this.hidden = false;
				this.changing = false;
			}.bind(this));
		}
  },

  load_result: function(item) {
    var a, div;
		div = new Element('div', {
			'class': 'results-product' + (this.counter == 0?' first-product':''),
			'styles': {'opacity': 0}
		});
		a = new Element('div', {'class': 'total-in-cart'})
			.setHTML('<div>You have ' + item.in_cart + ' of this item in your cart.</div><span>' + item.in_cart + '</span>')
			.inject(div);
		if (item.in_cart == 0) a.setStyle('display', 'none');
		a = new Element('a', {
			'class': 'image-link',
			'title': item.title,
			'href': '/product/' + item.prod_code.toLowerCase() + '/'
		}).adopt(
			new Element('img', {
				'class': 'product',
				'alt': item.title,
				'src': item.image
			})
		).inject(div);
		if (item.rating >= 1) {
			new Element('img', {'src': '/images/' + (item.rating < 1?'empty-':'') + 'star.png', 'class': 'rating'}).inject(div);
			new Element('img', {'src': '/images/' + (item.rating < 2?'empty-':'') + 'star.png', 'class': 'rating'}).inject(div);
			new Element('img', {'src': '/images/' + (item.rating < 3?'empty-':'') + 'star.png', 'class': 'rating'}).inject(div);
			new Element('img', {'src': '/images/' + (item.rating < 4?'empty-':'') + 'star.png', 'class': 'rating'}).inject(div);
			new Element('img', {'src': '/images/' + (item.rating < 5?'empty-':'') + 'star.png', 'class': 'rating'}).inject(div);
		}
		new Element('div', {'class': 'clear'}).inject(div);
		a.clone().removeClass('image-link').setHTML(item.title_short).inject(div);
		//new Element('p').setHTML('&nbsp;&nbsp;$' + item.list_price.toFloat().toFixed(2)).inject(div);
		new Element('p').setHTML('&nbsp;&nbsp;$' + item.price.toFloat().toFixed(2)).inject(div);
		new Element('a', {
			'title': 'Add to Cart',
			'href': '/cart/?add=' + item.prod_code.toUpperCase(),
			'class': 'add-cart',
			'events': {
				'click': function(){
				_gaq.push( [ '_trackEvent', 'add_to_cart', 'atc_search_results', item.prod_code.toUpperCase() ] );
				_gaq.push( [ 'glg._trackEvent', 'add_to_cart', 'atc_search_results', item.prod_code.toUpperCase() ] );
				}.bindWithEvent(this)
			}
		}).inject(div);
		new Element('a', {
			'title': 'Add to Wish List',
			'href': '/cart/?wish=' + item.prod_code.toUpperCase(),
			'class': 'add-wishlist'
		}).setHTML('Add to Wish List').inject(div);
		div.inject(this.result_row);
    this.pointer++;
  }

});

Search.implement(new Events)
