/* authenticity */
var authenticity_control = function ()
{
	var that = {};

	that.init = function(h_param)
	{
		that.o_wfrom = h_param.o_wfrom;
		that.o_wtill = h_param.o_wtill;
		that.e_from = h_param.e_from;
		that.e_till = h_param.e_till;
		
		that.replace_view(that.e_from, 'from');
		that.replace_view(that.e_till, 'till');
	},
	
	that.replace_view = function(e, s_class)
	{
		var e_view = new jQuery(document.createElement("span"));
		e_view.addClass('authenticity').addClass(s_class);
		$(e.parent().get(0)).append(e_view);
		e.hide();

		that['o_w' + s_class].attachOuterObserver(
			"onchange",
			function(s_evt, ow)
			{
				e_view.get(0).style.backgroundPosition = -12*(5-parseInt(ow.getValue().get())) + 'px 0';
			}
		);
	}
	
	return that;
};

/* expand additional */

$(function(){
	
	var jForm = $('#form_filter_form');
	var jClick = jForm.find('div.additional:first');
	var jjField = jClick.nextAll('div.fieldset').hide();
	var jRegion = jForm.find('#region_id');
	var jCountry = jForm.find('#country');
	var jRajon = jForm.find('#rajon');
	var jCity = jForm.find('#city');
	var options_copy = jRegion.html();
	
	$('<span id="indicator_city" style="padding-left: 2px;"></span>').appendTo('#r_city dd');
    $('<span id="indicator_rajon" style="padding-left: 2px;"></span>').appendTo('#r_rajon dd');
    $('<span id="indicator_rajon_city" style="padding-left: 2px;"></span>').appendTo('#r_rajon_city dd');
		
	var req=null;
	var req_=null;
	var req_c=null;
	var reqIns=null;
	var console=null;
	var READY_STATE_UNINITIALIZED=0;
	var READY_STATE_LOADING=1;
	var READY_STATE_LOADED=2;
	var READY_STATE_INTERACTIVE=3;
	var READY_STATE_COMPLETE=4;
	
	
	function GetCountryCity(country_id) {
		$('#indicator_city').html('<img src="http://est.ua/f/1/commercial/global/autocomplete_indicator.gif" />');
		if (window.XMLHttpRequest) {
	        req_c = new XMLHttpRequest();
	    } else if (window.ActiveXObject) {
	        req_c = new ActiveXObject("Microsoft.XMLHTTP");
	    }
		if (req_c) {
			var url_base_c = url_base.replace('country=','');
		    req_c.onreadystatechange = processCountryChange;
			req_c.open('GET', '/__ajax/get_country_city.php?country='+country_id+'&url_base='+url_base_c, true);
		    req_c.send(null);
	    }
	}
	
	function processCountryChange(){
		var ready=req_c.readyState;
		var data_=null;

		if(ready == READY_STATE_COMPLETE){
			data_ = req_c.responseText;
			var SelCity=document.getElementById("city");
			if(data_ != ''){
				$("#city").html(data_);
				//$("#city").removeAttr("disabled");
				document.getElementById('city').disabled=false;
			} else {
				SelCity.innerHTML = '';
				document.getElementById('city').disabled = true;
			}
			$('#indicator_city').html('');
		}
	};	
	
	function GetRegionRajon(reg_id_,url_base_rr) {
		$('#indicator_rajon').html('<img src="http://est.ua/f/1/commercial/global/autocomplete_indicator.gif" />');
		if (window.XMLHttpRequest) {
	        req_rr = new XMLHttpRequest();
	    } else if (window.ActiveXObject) {
	        req_rr = new ActiveXObject("Microsoft.XMLHTTP");
	    }
		if (req_rr) {
			var url_base_rr = url_base_rr.replace('region_id=','');
		    req_rr.onreadystatechange = processRajonChange;
			req_rr.open('GET', '/__ajax/get_region_rajon.php?region_id='+reg_id_+'&url_base='+url_base_rr, true);
		    req_rr.send(null);
	    }
	}
	
	function processRajonChange(){
		var ready=req_rr.readyState;
		var data_=null;

		if(ready == READY_STATE_COMPLETE){
			data_ = req_rr.responseText;
			var SelRajon=document.getElementById("rajon");
			if(data_ != ''){
				$("#rajon").html(data_);
				//$("#city").removeAttr("disabled");
				document.getElementById('rajon').disabled=false;
				var SelRegion=document.getElementById("region_id");
				var reg_id__=SelRegion.options[SelRegion.selectedIndex].value;
				var SelRajon=document.getElementById("rajon");

				if(SelRajon.selectedIndex >= 0 )
				{
				   var raj_id=SelRajon.options[SelRajon.selectedIndex].value;
				   var url_base = String(window.location);
				   GetCity(raj_id,reg_id__,url_base);
				}
			} else {
				SelRajon.innerHTML = '';
				document.getElementById('rajon').disabled = true;
			}
			$('#indicator_rajon').html('');
		}
	};	
	
	function GetCity(raj_id,reg_id__,url_base) {
		$('#indicator_city').html('<img src="http://est.ua/f/1/commercial/global/autocomplete_indicator.gif" />');
		url_base=url_base.replace('region_id=','');
		if (window.XMLHttpRequest) {
	        req_ = new XMLHttpRequest();
	    } else if (window.ActiveXObject) {
	        req_ = new ActiveXObject("Microsoft.XMLHTTP");
	    }
		if (req_) {
		    req_.onreadystatechange = processReqChange;
			req_.open('GET', '/__ajax/get_city_filter.php?region_id='+reg_id__+'&raj='+raj_id+'&url_base='+url_base, true);
		    req_.send(null);
	    }
	}
	
	function processReqChange(){
		var ready=req_.readyState;
		var data_=null;

		if(ready == READY_STATE_COMPLETE){
			data_ = req_.responseText;
			var SelCity=document.getElementById("city");
			if(data_ != ''){
				$("#city").html(data_);
				//$("#city").removeAttr("disabled");
				document.getElementById('city').disabled=false;

				if (SelRegion.selectedIndex != 0 && SelCity.selectedIndex > 0){
					var SelCity=document.getElementById("city");
					var city_id=SelCity.options[SelCity.selectedIndex].value;
					GetRajon(city_id,url_base);
				}

			} else {
				SelCity.innerHTML = '';
				document.getElementById('city').disabled = true;
			}
			$('#indicator_city').html('');
		}
	};	
	
	function GetRajon(city_id,url_base) {
		$('#indicator_rajon_city').html('<img src="http://est.ua/f/1/commercial/global/autocomplete_indicator.gif" />');
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}

		if (req) {

			var SelRajon=document.getElementById("rajon_city");

			var option0 = new Option('',0)
			SelRajon.options[0] = option0;
			document.getElementById('rajon_city').disabled = true;
 
			req.onreadystatechange = processReqChange_rajon;
			req.open('GET', '/__ajax/get_rajon_filter.php?city_id='+city_id+'&url_base='+url_base+'&type_id=4', true);
			req.send(null);
		}
	}	
	
	function processReqChange_rajon(){
		var ready=req.readyState;
		var data=null;

		if(ready == READY_STATE_COMPLETE){
			data = req.responseText;
			var SelRajon=document.getElementById("rajon_city");
			if(data != ''){

				$("#rajon_city").html(data);
 
 				if(SelRajon.options.length == 1) {
	 				if(SelRajon.options[0].text == '--Любой район--' || SelRajon.options[0].text == '--Будь-який район--'){
	 					//$("#rajon").html('');
		 				document.getElementById('rajon_city').disabled = true;
					} else {
						document.getElementById('rajon_city').disabled = false;
					}
  
				} else {
 
					document.getElementById('rajon_city').disabled = false;
 
				}
 
			} else {

				SelRajon.innerHTML = '';
				document.getElementById('rajon_city').disabled = true;
			}
			$('#indicator_rajon_city').html('');
		}
	};
	
	
	jCountry.change(function()
	{
		$("#rajon").html('');
		$("#city").html('');
		$("#rajon_city").html('');
		if(this.value == 1){
			jRegion.html(options_copy);
			var reg_id_=SelRegion.options[SelRegion.selectedIndex].value;
			var url_base_ = String(window.location);
			document.getElementById("region_id").disabled=false;
			document.getElementById("city").disabled=true;
			document.getElementById("rajon").disabled=true;
			document.getElementById("rajon_city").disabled=true;
			GetCity(0,reg_id_,url_base_);
			GetRegionRajon(reg_id_,url_base_);
		} else {
			document.getElementById("region_id").disabled=true;
			document.getElementById("rajon").disabled=true;
			document.getElementById("rajon_city").disabled=true;
			jRegion.html("");
			GetCountryCity(this.value);
		}
	})
	
	jRegion.change(function()
	{
		var SelRegion=document.getElementById("region_id");
		var reg_id_=SelRegion.options[SelRegion.selectedIndex].value;
		var url_base_ = String(window.location);
		$("#rajon").html('');
		$("#city").html('');
		$("#rajon_city").html('');
		document.getElementById("city").disabled=true;
		document.getElementById("rajon").disabled=true;
		document.getElementById("rajon_city").disabled=true;
//		GetCity(0, reg_id_,url_base_);
		GetRegionRajon(reg_id_,url_base_);
	})
	
	jRajon.change(function()
	{
		var SelRegion=document.getElementById("region_id");
		var reg_id_=SelRegion.options[SelRegion.selectedIndex].value;
		var SelRajon=document.getElementById("rajon");
		var rajon_id=SelRajon.options[SelRajon.selectedIndex].value;
		var url_base = String(window.location);
		url_base = url_base.replace('city=','');
		$("#city").html('');
		$("#rajon_city").html('');
		document.getElementById("city").disabled=true;
		document.getElementById("rajon_city").disabled=true;
		GetCity(rajon_id, reg_id_,url_base);
	})
	
	jCity.change(function()
	{
		if(jCountry.val() != 1){
			return;
		}
		var SelCity=document.getElementById("city");
		var city_id=SelCity.options[SelCity.selectedIndex].value;
		var url_base = String(window.location);
		$("#rajon_city").html('');
		document.getElementById("rajon_city").disabled=true;
		GetRajon(city_id,url_base);
	})
	
	
	jClick.click(function()
	{
		jjField.toggle();
		jClick.toggleClass('expanded');
	})
		
	var SelCity=document.getElementById("city");
	var SelRegion=document.getElementById("region_id");
	var url_base = String(window.location);
		
	try {
		jCountry.change();
//		if($("#country").val() == 1){
//			if (SelRegion.selectedIndex != 0){
//				var reg_id=SelRegion.options[SelRegion.selectedIndex].value;
//				GetCity(reg_id,url_base);
//			}
//		} else {
//				GetCountryCity($("#country").val());
//			}
//		}
	}
	catch(err)
  {
  //Handle errors here
  }
	
});


/* filter by type switcher */
$(function(){
	var j_container = $('#sidebar');
	var jj_switch = j_container.find('.filter-type-switcher > div');
	var jj_switch_panel = j_container.find('.filter > div');
	
	jj_switch.click(function(){
		if (! $(this).hasClass('active'))
		{
			var s_type = $(this).attr('class');
			if (s_type == 'by-number')
			{
				jj_switch_panel.filter('.'+s_type).find('form > input.search-input').focus();
			}

			jj_switch.removeClass('active');
			$(this).addClass('active');
			jj_switch_panel.hide().filter('.'+s_type).show();
		}
	});
	
});

/* regional selector */
$(function(){
	var j_container = $('#sidebar > .filter > .by-params > form > div.region-selector:first');
	var jj_switch = j_container.find('div.switcher span');
	var jj_control = j_container.find('div.fieldset');
	var j_city = jj_control.find('input#city');
	var j_region = jj_control.find('select#region_id');
	
	jj_switch.click(function(){
		if (! $(this).hasClass('active'))
		{
			var s_type = $(this).attr('type');
			jj_switch.removeClass('active');
			$(this).addClass('active');
			jj_control.hide().filter('.'+s_type).show();
		}
	});
	
	if(j_city.val())
	{
		jj_switch.filter('[type=city]').click();
	}
	
	j_region.change(function(){
		j_city.val('');
	});

});


/* price */
$(function(){
	var j_container = $('#price_range_container');
	
	if (j_container)
	{
		var j_select = j_container.find('#currency');
		var jj_content = j_container.find('div.price-range');
		var cur_select = j_select.val();
		jj_content.hide().filter( '#price_range_'+cur_select ).show();
		
		
		j_select.change(function()
		{
			var s_val = j_select.val();
			jj_content.hide().filter( '#price_range_'+s_val ).show();
		});
	}
	
});
/* convert curilic character*/
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
  trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё
trans[0x406] = 0xB2;    // І
trans[0x456] = 0xB3;    // і
trans[0x407] = 0xAF;    // Ї
trans[0x457] = 0xBF;    // ї
trans[0x404] = 0xAA;    // Є
trans[0x454] = 0xBA;    // є

function converter(str){
	var ret = [];
	// Составляем массив кодов символов, попутно переводим кириллицу
	for (var i = 0; i < str.length; i++){
		var n = str.charCodeAt(i);
		if (typeof trans[n] != 'undefined')
			n = trans[n];
		if (n <= 0xFF)
			ret.push(n);
	}
	return escape(String.fromCharCode.apply(null, ret));
}


/* reset form*/
$(function(){

	$('#sidebar #form_filter_form  div.type_submit #reset_filter').click(function()
	{
		var temp_url = window.location.href.substring(0,window.location.href.length-window.location.search.length);
//		url_reg = /(\/ua)?(\/[a-z]{2}\/)/;
//		url_match = temp_url.match(url_reg);
//		if(url_match && url_match[2] != "/ua/"){
//			new_url = temp_url.replace(url_reg,"$1/");
//		} else {
//			new_url = temp_url;
//		}
		var new_url = temp_url;
		var country = document.getElementById('country').value;
		var s_get = "?country=" + country;
		var city = document.getElementById('city').value;
		if(country == 1){
			s_get += "&region_id=" + document.getElementById('region_id').value;
			if(city > 0)
				s_get += "&city=" + city;
		} else {
			if(city)
				s_get += "&city=" + converter(city);
		}
		window.location = new_url + s_get; 
	})
})

/* submit cleaner */
$(function(){

	$('#sidebar #form_filter_form').submit(function()
	{
		var s_currency = $(this).find('#currency').val();
		var jj_input = $(this).find('input[name!=submit_filter]:not([name^=to-str-]), select[name!=city_list]')
			.not(':checkbox:not(:checked)')
			.not('[name^=price_till_][name!=price_till_'+s_currency+']')
			.not('[name^=price_from_][name!=price_from_'+s_currency+']');
		var s_get = '?';
		
		jj_input.each(function(){

			var s_name = $(this).attr('name');
			var s_value = jQuery.trim($(this).val());

			if (s_value.length == 0)
			{
				return;
			}
			else if ( s_name.indexOf('_from')>0 )
			{
				if (xForm1.getWidgetById(s_name).oParent.dMin >= parseInt(s_value))
					return;
			}
			else if ( s_name.indexOf('_till')>0 )
			{
				if (xForm1.getWidgetById(s_name).oParent.dMax <= parseInt(s_value))
					return;
			}
			//s_get += s_name +'='+s_value.replace(/[:\/;?&]/g,'')+'&';
			//s_get += s_name+'='+encodeURIComponent(s_value)+'&';
//			s_get += s_name+'='+escape(s_value)+'&';
//			s_get += s_name+'='+s_value+'&';
			s_get += s_name+'='+converter(s_value)+'&';
			
		});

		s_get = s_get.substring(0,s_get.length-1);
		temp_url = window.location.href.substring(0,window.location.href.length-window.location.search.length);
		fl = temp_url.indexOf("/city/");
		if(fl != -1){
			temp_url = temp_url.substring(0, fl+1);
		}
		url_reg = /(\/ua)?(\/[a-z]{2}\/)/;
		url_match = temp_url.match(url_reg);
		if(url_match && url_match[2] != "/ua/"){
			new_url = temp_url.replace(url_reg,"$1/");
		} else {
			new_url = temp_url
		}
		
		window.location = new_url+s_get; 

		return false;
	});

});

