function toggleVisibleResetSearchFormButon() {
	if($$('div[id="productTypeChecklist"] span[class="checklist-select-value"]').first())
		var s_product = $$('div[id="productTypeChecklist"] span[class="checklist-select-value"]').first().innerHTML;
	else
		var s_product = '';
	if($$('div[id="categoryChecklist"] span[class="checklist-select-value"]').first())
		var s_category = $$('div[id="categoryChecklist"] span[class="checklist-select-value"]').first().innerHTML;
	else
		var s_category = '';
	if($$('div[id="styleChecklist"] span[class="checklist-select-value"]').first())
		var s_style = $$('div[id="styleChecklist"] span[class="checklist-select-value"]').first().innerHTML;
	else
		var s_style = '';
	if($$('div[id="authorChecklist"] span[class="checklist-select-value"]').first())
		var s_author = $$('div[id="authorChecklist"] span[class="checklist-select-value"]').first().innerHTML;
	else
		var s_author = '';
	var s_template = $('tid_field').value;
	var s_keyword = $('search_words_field').value;
	var s_from = $('from_field').value;
	var s_to = $('to_field').value;
	if (s_template.replace(' ', '') == '') {
		s_template = '- Any -';
	}
	if (s_keyword.replace(' ', '') == '') {
		s_keyword = '- Any -';
	}
	if (s_from.replace(' ', '') == '') {
		s_from = '- Any -';
	}
	if (s_to.replace(' ', '') == '') {
		s_to = '- Any -';
	}
	if ((s_product.indexOf('- Any Product -') != -1) && (s_category.indexOf('- Any Category -') != -1) && (s_style.indexOf('- Any Style -') != -1) && (s_author.indexOf('- Any Author -') != -1) && (s_template.indexOf('- Any -') != -1) && (s_keyword.indexOf('- Any -') != -1) && (s_from.indexOf('- Any -') != -1) && (s_to.indexOf('- Any -') != -1)) {
		$('searchFormResetButton').style.display = 'none';
		$('tid_field').style.textAlign = 'center';
		$('search_words_field').style.textAlign = 'center';
		$('from_field').style.textAlign = 'center';
		$('to_field').style.textAlign = 'center';
	} else {
		$('searchFormResetButton').style.display = 'block';
	}
}

function resetSearchForm() {
	searchForm.productTypeField.preLoadOnRequest();
	searchForm.categoryField.preLoadOnRequest();
	searchForm.styleField.preLoadOnRequest();
	searchForm.authorField.preLoadOnRequest();
	$$('div[id="productTypeChecklist"] span[class="checklist-select-value"]').first().innerHTML = '- Any Product -';
	$$('div[id="categoryChecklist"] span[class="checklist-select-value"]').first().innerHTML = '- Any Category -';
	$$('div[id="styleChecklist"] span[class="checklist-select-value"]').first().innerHTML = '- Any Style -';
	$$('div[id="authorChecklist"] span[class="checklist-select-value"]').first().innerHTML = '- Any Author -';
	searchForm.productTypeField._uncheckAll();
	searchForm.categoryField._uncheckAll();
	searchForm.styleField._uncheckAll();
	searchForm.authorField._uncheckAll();
	$('tid_field').value = '- Any -';
	$('search_words_field').value = '- Any -';
	$('from_field').value = '- Any -';
	$('to_field').value = '- Any -';
	searchForm.productTypeField.refreshValue();
	searchForm.categoryField.refreshValue();
	searchForm.styleField.refreshValue();
	searchForm.authorField.refreshValue();
	toggleVisibleResetSearchFormButon();
}
/**
 * SearchForm class
 */
var SearchForm = Class.create({
  initialize : function(form) {
    this.form = $(form);

    this.productTypeField = new CheckListSelect('product', 'productTypeChecklist', this.form);
    this.categoryField = new CheckListSelect('cat', 'categoryChecklist', this.form);
    this.styleField = new CheckListSelect('style', 'styleChecklist', this.form);
    this.authorField = new CheckListSelect('author', 'authorChecklist', this.form);

    var onFocusHandler = function(event) {
      if (event.element().value == '- Any -') {
        event.element().value = '';
        event.element().style.textAlign = 'left';
      }
    }

    var onBlurHandler = function(event) {
      if (event.element().value.strip() == '') {
        event.element().value = '- Any -';
        event.element().style.textAlign = 'center';
      }
    }

    $('tid_field').observe('focus', onFocusHandler);
    $('tid_field').observe('blur', onBlurHandler);

    $('search_words_field').observe('focus', onFocusHandler);
    $('search_words_field').observe('blur', onBlurHandler);

    $('from_field').observe('focus', onFocusHandler);
    $('from_field').observe('blur', onBlurHandler);

    $('to_field').observe('focus', onFocusHandler);
    $('to_field').observe('blur', onBlurHandler);

    this.form.observe('submit', this.onSubmit.bindAsEventListener(this));
    $('searchFormSubmit').observe('click', this.onSubmit.bindAsEventListener(this));
  },


  onSubmit : function(event) {
    this.productTypeField.serialize();
    this.categoryField.serialize();
    this.styleField.serialize();
    this.authorField.serialize();

    this.form.submit();
  }
});

/**
 * CheckList widget
 */
var CheckListSelect = Class.create({
  initialize: function(hidden_element_name, checklist) {
    this.hidden_element_name = hidden_element_name;
    this.checklist = $(checklist);
    this.controlElement = this.checklist.select('.checklist-select-control').first();
    this.observer = this.controlElement.observe('mousedown', this.loadOnRequest.bindAsEventListener(this));
  },


  loadOnRequest: function() {
    var container_id = this.checklist.id + "-options-container";
    this.controlElement.stopObserving('mousedown', this.observer.loadOnRequest)

	this.showProgressIndicator()

    var options_container = Builder.node('span', {'id' : container_id, 'style' : 'height: 0px;'})
    this.checklist.appendChild(options_container);

    new Ajax.Updater(container_id, '/Get/', {parameters : {mode : "ajax-search", "id" : this.checklist.id},
      onComplete: function() {
        this.weave();
        this.fillPreselectedOptions();
        this.refreshValue();
      	this.hideProgressIndicator();
        this.showList();
      }.bind(this)});
  },
  
  preLoadOnRequest:function () {
	    var container_id = this.checklist.id + "-options-container";
	    this.controlElement.stopObserving('mousedown', this.observer.loadOnRequest)
	    var options_container = Builder.node('span', {'id' : container_id, 'style' : 'height: 0px;'})
	    this.checklist.appendChild(options_container);
	    new Ajax.Updater(container_id, '/Get/', {parameters : {mode : "ajax-search", "id" : this.checklist.id},
	      onComplete: function() {
	        this.weave();
	      }.bind(this)});
  },

  showProgressIndicator : function ()
  {
	c = $('sform_container')
	if (c)
	{
		style = $H({
			'display':			'none',
			'position':			'absolute',
			'z-index':			10,
			'background-color':	"#DEF5FF",
			'opacity':			0.7,
			'filter': 			'alpha(opacity = 70)',
			'text-align':		'center'
		})


		style_str = style.inject('', function (acc, pair) {
			return pair[0] + ": " + pair[1] + "; " + acc
		})

    	var progress_indicator_div = Builder.node('div',
	    	{
	    		'id'	: "progress_indicator",
	    		'style'	: style_str
	    	},
    		[Builder.node('img', {src: "/images/templatemonster/ajax-loader-u.gif", style: "margin-top: 20px;"})]
    	)

		c.up().appendChild(progress_indicator_div)
		$('progress_indicator').clonePosition(c).show()
	}
  },


  hideProgressIndicator: function()
  {
 		$('progress_indicator').remove()
  },


  weave: function() {
    this.controlElement.observe('mousedown', this.toggleList.bindAsEventListener(this));
    this.valueElement = this.checklist.select('.checklist-select-value').first();

    this.listElement = this.checklist.select('.checklist-options').first();
    this.listElement.up().observe('mousedown', function(event) {
      Event.stop(event);
    });

    this.onBlurHandler = function(event) {
      if (event.element() != this.controlElement
          && event.element().up('div.checklist-select-control') != this.controlElement) {
        this.hideList(event);
      }
    }.bindAsEventListener(this);


    this.listOptions = this.listElement.select('input[type="checkbox"]');
    this.listOptions.each(function(option) {
      option.observe('click', this.onChange.bindAsEventListener(this));
    }.bind(this));

    this.closeButton = this.checklist.select('.btn-apply').first();
    this.closeButton.observe('click', this.hideList.bindAsEventListener(this));

    this.checkAllButton = this.checklist.select('.checkAll').first();
    this.checkAllButton.observe('click', this.checkAll.bindAsEventListener(this));

    this.uncheckAllButton = this.checklist.select('.uncheckAll').first();
    this.uncheckAllButton.observe('click', this.uncheckAll.bindAsEventListener(this));

    $A([this.uncheckAllButton, this.checkAllButton, this.closeButton]).each(function(e) {
      e.setStyle({cursor: 'pointer'});
    });
  },


  serialize: function() {
    if (this.listOptions) {
      var data = [];
      this.listOptions.each(function(option) {
        if (option.checked && !option.hasAttribute('virtual_item')) {
          data.push(option.value);
        }
      });

      $$("input[name='" + this.hidden_element_name + "']").first().value = data.join(',');
    }
  },


  fillPreselectedOptions: function() {
    var current_value = $F($$("input[name='" + this.hidden_element_name + "']").first())
    var list = $A(current_value.split(","));
    if (list.length > 0) {
      this.listOptions.each(function(e) {
        if (list.include(e.value)) {
          e.checked = true;
        }
      });
    }
  },

  refreshValue: function() {
    var labels = [];
    if (this.listOptions) {
      this.listOptions.each(function(option) {
        if (option.checked == true) {
          labels.push(option.up('label').innerHTML.stripTags());
        }
      });
      if (labels.length > 0) {
        this.valueElement.innerHTML = labels.join(', ');
        this.valueElement.style.textAlign = 'left';
      } else {
        this.valueElement.innerHTML = '- Any ' + this.controlElement.title + ' -';
        this.valueElement.style.textAlign = 'center';
      }
    }
  },


  showList: function(event) {
   	Effect.ScrollTo('search-form-header', {duration: 1.5})
    document.observe('mousedown', this.onBlurHandler);
    this.listElement.show();
  },


  hideList: function(event) {
    document.stopObserving('mousedown', this.onBlurHandler);
    this.listElement.hide();
    toggleVisibleResetSearchFormButon();
    Event.stop(event);
  },


  toggleList: function(event) {
    Element.visible(this.listElement) ? this.hideList(event) : this.showList(event);
  },


  checkAll: function(event) {
    this.listOptions.each(function(option) {
      option.checked = true;
    });
    this.refreshValue();
    Event.stop(event);
  },


  uncheckAll: function(event) {
    if (this.listOptions) {
      this.listOptions.each(function(option) {
        option.checked = false;
      });
    }
    this.refreshValue();
    Event.stop(event);
  },

  _uncheckAll: function() {
	    if (this.listOptions) {
	      this.listOptions.each(function(option) {
	        option.checked = false;
	      });
	    }
	    this.refreshValue();
	  },

  onChange: function(event) {
    var checkBox = event.element();
    checkBox.up('li').select('input[type="checkbox"]').without(checkBox).each(function(option) {
      option.checked = checkBox.checked;
    });

    var parentOption = checkBox.up('ul').up('li');
    if (parentOption) {
      if (checkBox.up('ul').select('input[type="checkbox"]:not(:checked)').length > 0) {
        parentOption.down('input[type="checkbox"]').checked = false;
      } else {
        parentOption.down('input[type="checkbox"]').checked = true;
      }
    }

    this.refreshValue();
  }
});

progress_indicator = new Image();
progress_indicator.src = "/images/templatemonster/ajax-loader-u.gif";

