$(function(){
	try{
		var dslink = document.getElementById('detailSearchLink');
		dslink.onclick = function(){
			this.href += '?' + $('.search-form').serialize();
		}
	}catch(e){log(e)}


	var ReCounter = new ResultCounter('#vehicleSearchForm-3');
	ReCounter.disabled = true;
	$('.search-form :input').each(function(){
		ReCounter.bind(this);
	});

	var Ms = new ModSelect;
	Ms.optgmode = 0;
	Ms.existonly = true;


	$.getJSON('/services/data_json.php?tr[all]=16', function(data){
		if (data.tr.all.status==1){
			Ms.strChoose = data.tr.all.response;
		}
	});


	try{var TypeSelector = document.getElementById('searchParam-type');}catch(e){log(e)}
	try{var BodytypeSelector = document.getElementById('searchParam-bodytype');}catch(e){log(e)}
	Ms.filter(BodytypeSelector, Ms.filterBodytype);
	Ms.bind(TypeSelector, BodytypeSelector, Ms.changeBodytypes);
	for(var i=1; i<=3; i++){
		try{var ThisMakeSelector = document.getElementById('searchParam-cmm-'+i+'-make');}catch(e){log(e)}
		try{var ThisModelSelector = document.getElementById('searchParam-cmm-'+i+'-model_id');}catch(e){log(e)}

		Ms.bind(TypeSelector, ThisMakeSelector, Ms.changeMakes);
		Ms.bind(ThisMakeSelector, ThisModelSelector, Ms.changeModels);
		//Ms.bind('#searchParam-cmm-'+i+'-model_id', '#searchParam-cmm-'+i+'-model_period', Ms.changeModelPeriods);
	}


	/*CREATE AND HANDLE ONCHANGE ACTION*/
	$('.search-form select.multiple')
	.bind('focus change', function(){
		if (!this.options[this.selectedIndex].getAttribute('data-multiToggler')) {
			this.cachedValue = this.value;
		}
	})
	.change(function(){
		if(this.options[this.selectedIndex].getAttribute('data-multiToggler')){
			var thisName = this.name + '[]';

			var Container = document.createElement('ul');
			Container.className = 'input-checklist';

			for(var i=0; i<this.options.length; i++){
				var thisOption = this.options[i];
				if(parseInt(thisOption.value)!=0){
					var thisId = this.id + '-' + thisOption.value;
					var Input = document.createElement('input');
					Input.setAttribute('type', 'checkbox');
					Input.setAttribute('name', thisName);
					Input.value = thisOption.value;
					Input.setAttribute('id', thisId);

					ReCounter.bind(Input);

					var Label = document.createElement('label');
					Label.appendChild(document.createTextNode(this.options[i].text));
					Label.setAttribute('for', thisId);

					var Item = document.createElement('li');
					Item.appendChild(Input);
					Item.appendChild(Label);

					if (Input.value == this.cachedValue) {
						Input.setAttribute('checked', true);
						Container.insertBefore(Item, Container.firstChild);
					}
					else {
						Container.appendChild(Item);
					}
				}
			}

			this.parentNode.appendChild(Container);
			this.parentNode.removeChild(this);
		}
	});


	/*SORT SELECTED ITEMS TO FRONT*/
	$('.input-checklist.multiple').each(function(){
		var Checklist = this;
		var placeholder = Checklist.firstChild;

		$(Checklist).find('li.selected').each(function(){
			Checklist.insertBefore(this, placeholder);
			placeholder = this.nextSibling;
		});
	});


	/*BUTTON: CLEAR FILTER*/
	$('.search-form')
	/*
	.prepend(function(){
		var Form = this;
		var Controls = document.createElement('a');
		Controls.className = 'filter-delete';
		Controls.style.display = 'block';

		$(Controls).click(function(){
			$(Form)
				.find('(:checked :selected):not([data-noclear="true"])').clearForm()
					.parents('.form-item')
						.find('.selected').andSelf().removeClass('selected');
			ReCounter.count();
		});
		return Controls;
	})
	*/
	.find('.selected').each(function(){
		var this_this = this;
		var Container = $(this);
		var Controls = document.createElement('a');
		Controls.className = 'filter-delete';

		var is_multifilter = Container.parents('.multifilter').length;

		$(Controls).click(function(){
			if (is_multifilter>0){
				Container.nextAll('.selected').removeClass('selected').find(':input').clearForm();
			}
			Container.removeClass('selected').find(':input').clearForm();
			ReCounter.count();
		});


		Container.find('.label').each(function(){
			this.parentNode.insertBefore(Controls, this.parentNode.firstChild);
		});
	});


	/*GENERATE NAME FOR SEARCH SAVE*/
	var save_search_name_field = document.getElementById('save-search-name');
	if(save_search_name_field != null){
		save_search_name_field.value = '';
		$('.search-form .multifilter').each(function(){
			var tmp_val = '';
			$(this).find('.selected :input').each(function(){
				switch(this.type){
					case 'text':
						tmp_val += $.trim(this.value) + ' ';
						break;
					case 'select-one':
						tmp_val += $.trim(this.options[this.selectedIndex].text) + ' ';
						break;
					default:
						break;
				}
			});

			if(tmp_val.length>0){
				if (save_search_name_field.value.length) save_search_name_field.value += ', ';

				save_search_name_field.value += $.trim(tmp_val);
			}
		});
	}


	/* @hack purely for IE6, since it doesn't handle :hover on anything else besides a.
	 * safe to remove when IE6 becomes marginal*/
	if($.browser.msie && $.browser.version == 6){
		$('#usedVehiclesSearchResult .insearch-offers .item').hover(
			function(){
				$(this).find('.panel').css('display', 'block').css('position', 'absolute');
			},
			function(){
				$(this).find('.panel').css('display', 'none');
			}
		);
	}
});


$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form') {
      return $(':input',this).clearForm();
    }
    if (type == 'text' || type == 'password' || tag == 'textarea') {
      this.value = '';
    }
    else if (type == 'checkbox' || type == 'radio') {
      this.checked = false;
    }
    else if (tag == 'select') {
      this.selectedIndex = 0;
    }
  });
};


function log(e){
	//alert(e);
}


function ResultCounter (form_selector) {
	_self = this;

	if(form_selector){
		this.jform = $(form_selector);
	}

	this.disabled = true;
	if(this.jform instanceof jQuery && this.jform.length==1){
		this.disabled = false;
	}
}
ResultCounter.prototype.disabled = false;
ResultCounter.prototype.ticker_enabled = true;
ResultCounter.prototype.count_result = -1;
ResultCounter.prototype.timeout = 1000;
ResultCounter.prototype.timeout_handler;
ResultCounter.prototype.jform;
ResultCounter.prototype.s_result_info = '';

ResultCounter.prototype.count = function(){
	if(this.disabled) return;

	if(this.ticker_enabled){
		$('.item-submit .label').html('<img class="count-result" src="/images/loading_image.gif">');
	}

	clearTimeout(this.timeout_handler);
	this.timeout_handler = setTimeout(function(){
		var query = '/services/count.php?' + _self.jform.serialize();
		$.getJSON(query, function(count){
			_self.count_result = count.result;
			_self.print();
		});
	}, this.timeout);
}

ResultCounter.prototype.bind = function(target){
	if(this.disabled) return;

	if(target.type=='checkbox'){
		$(target).click(function(){
			_self.count();
		});
	}
	else{
		$(target).change(function(){
			_self.count();
		});
	}
}

ResultCounter.prototype.print = function(){
	if(this.disabled) return;
	$('.item-submit .label').html('<span class="count-result">' + this.s_result_info + ': <b>' + this.count_result + '</b></span>');
}
