upTime = 1000;
objRequestDebounced = false;
objCountDebounceFn = false;

$(document).ready(function(){
	if (typeof obSearchForm != 'undefined') {
		$('#utils-block').find('a.change-search-parameters').click(function(){
			if ($('#search-parameters-form').css('display') == 'none') {
				$('#search-parameters-form').show();
				if ($(this).html() == 'Показать параметры поиска') {
					$(this).html('Скрыть параметры поиска');
				} else {
					$(this).html('Скрыть форму');
				}
				
			} else {
				$('#search-parameters-form').hide();
				if ($(this).html() == 'Скрыть параметры поиска') {
					$(this).html('Показать параметры поиска');
				} else {
					$(this).html('Поиск');
				}
			}
			return false;
		});
		
		$(obSearchForm).find('input, select').change(updateObjectsCount);
			if ($.browser.msie) {
				$(obSearchForm).find('input[type=checkbox]').click(updateObjectsCount);
			}
			$(obSearchForm).find('input[type=text]').keyup(updateObjectsCount).focus(function(){
			if (objRequestDebounced) {
				updateObjectsCount();
			}
		});
		
		$(obSearchForm).submit(removeSFDefaultValues);
		
		$(obSearchForm).find('input[type=reset]').click(function(){
			resetSearchForm();
			return false;		
		});
		
	}
	
	if (typeof obObjectsTable != 'undefined') {
		$(obObjectsTable).find('input.favorite').click(processFavorite);
	}
	
	
	
});

function removeSFDefaultValues() {
	if (typeof obSearchForm != 'undefined') {
		$(obSearchForm).find('input.remember-default').each(function(){	
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			}
		});	
	}
}

function processFavorite(){	
	$(this).attr('disabled', true).hide();
	$('#object_' + $(this).val()).find('.favorite-loading').show();
	if ($(this).attr('checked')) {
		$.getJSON(ajaxBackEndUrl + 'AddToFavorites/' + $(this).val() + '/', '', function(data){			
			if (data['id'] && data['state']) {		
				$('#object_' + data['id']).find('.favorite-loading').hide();
				$('#object_' + data['id']).find('input.favorite').removeAttr('disabled').show();				
				$('#utils-block .favorites').find('.count').html(data['count']);
				
				if (!$('#utils-block .favorites').hasClass('favorites-display')) {
					$('#utils-block .favorites').addClass('favorites-display');
				}
			}
		});
	} else {
		$.getJSON(ajaxBackEndUrl + 'RemoveFromFavorites/' + $(this).val() + '/', '', function(data){
			
			if (data['id'] && data['state']) {
				if (isFavoritesPage) {
					districtId = $('#object_' + data['id']).find('.district').val();					
					$('#object_' + data['id'] ).remove();
					objectsCount--;
					if (--viewDistricts[districtId] == 0) {						
						$('#district_' + districtId).remove();
					}
					
					if (objectsCount == 0) {						
						$(obObjectsTable).remove();
						$('#the-end-of-favorites').show();
					}
				} else {
					$('#object_' + data['id']).find('.favorite-loading').hide();
					$('#object_' + data['id']).find('input.favorite').removeAttr('disabled').show();
				}
			
				$('#utils-block .favorites').find('.count').html(data['count']);
				
				if (data['count'] == 0) {
					$('#utils-block .favorites').removeClass('favorites-display');					
				}
			}
		});
	}	
}

function changeDistrictsState(containerId){

        if ($('#' + containerId).find('input[type=checkbox][checked]').length == 0) {
                $('#' + containerId).find('input[type=checkbox]').attr('checked', true);
        } else {
                $('#' + containerId).find('input[type=checkbox]').removeAttr('checked');
        }

       updateObjectsCount();
}

function changeSubwayState(containerId){
        if ($('#' + containerId).find('option[selected]').length == 0) {
                $('#' + containerId).find('option').attr('selected', true);
        } else {
                $('#' + containerId).find('option').removeAttr('selected');        
        }

       updateObjectsCount();
}

function resetSearchForm() {
	$(obSearchForm).find('input[type=checkbox]').removeAttr('checked');
	$(obSearchForm).find('option').removeAttr('selected');
	$(obSearchForm).find('input[type=text]').val('');
	$(obSearchForm).find('input.remember-default').trigger('blur');
	updateObjectsCount();
}

function updateObjectsCount() {
        objRequestDebounced = true;

        if (!objCountDebounceFn) {
                objCountDebounceFn = $.debounce(getObjectsCount, upTime);
        }
        $(obSearchForm).find('.objects-count').addClass('objects-count-loading');
        objCountDebounceFn();
}





(function($) {

	function logValue(min, max, val) {
		return val == 0 ? min : Math.round(Math.exp(Math.log(max)*val/60));
	}

	function logSlider(min, max, val) {
		return val == min ? 0 : Math.round(Math.log(val)*60/Math.log(max));
	}

	$.fn.inputSlider = function(min, max, step) {
		var input = this, form = input.closest('form');
		var slider = $('<span>').insertBefore(input).slider({
			min: 0, max: 60, step: 1, value: logSlider(min, max, input.val()),
			slide: function(ev, ui) {
				input.val(logValue(min, max, ui.value));
				form.change();
			}
		});
		input.change(function() {
			slider.slider('value', logSlider(min, max, input.val()));
		});
	};

        $.extend({
                postSearchForm: function(url, form, callback, type){
                data = new Object();

                this.isArrayElement = function (name) {
                        return name.substring(name.length  - 2);
                }

                jQuery(form).find('input[name!=""],select[name!=""],textarea[name!=""]').each(function(id, element){
                        jElement = jQuery(element);
                        tagName = jElement.attr('tagName');
                        elementName = jElement.attr('name');
                        isArray = elementName.substring(elementName.length - 2) == '[]';
                        elementValue = false;

                        switch (tagName.toLowerCase()) {
                                case 'input':
                                        elementType = jElement.attr('type');

                                        switch (elementType) {
                                                case 'checkbox':
                                                        if (jElement.attr('checked') == true) {
                                                                elementValue = jElement.val();
                                                        }
                                                break;
                                                default:
                                                		if (jElement.val() != jElement.get(0)._defaultValue) {
                                                        	elementValue = jElement.val();
                                                        }
                                                break;
                                        }
                                break;
                                case 'select':
                                        if (isArray) {
                                                data[elementName] = new Array();
                                                optionsCount = 0;
                                                jElement.find('option').each(function(optionId, option){
                                                        jOption = jQuery(option);
                                                        if (jOption.attr('selected')) {
                                                                data[jElement.attr('name')][optionsCount++] = jOption.val();
                                                        }
                                                });
                                        } else {
                                                elementValue = jElement.val()
                                        }
                                break;
                                case 'textarea':
                                        elementValue = jElement.val();
                                break;
                        }

                        if (isArray) {
                                if (!data[elementName])  {
                                        data[elementName] = new Array();
                                }

                                newElementId = data[elementName].length;
                                try {
                                    if (elementValue) {
                                            data[elementName][newElementId] = elementValue;
                                    }
                                } catch (e) {}
                        } else if(elementValue) {
                                data[elementName] = elementValue;
                        }
                });

                if (typeof type != 'undefined' && type == 'json') {                	
                        postFn = jQuery.getJSON;
                } else {
                        postFn = jQuery.post;
                }

                delete(elementValue);

                postFn(url, data, callback);
        }
        })
})(jQuery);

function getObjectsCount(){
    objRequestDebounced = false;
    
    $(obSearchForm).find('.objects-count').addClass('objects-count-loading');
    $.postSearchForm(ajaxFormAction, obSearchForm, function(data){
    	
    	$(obSearchForm).find('.objects-count span').html(data['count'] + ' ');
		$(obSearchForm).find('.objects-count').removeClass('objects-count-loading').show();
    	}, 'json');
	}

