﻿function loadCountries(selected) 
{
	$.get(
		URLs+'/index.php?mod=jquery&submod=countries',
		{},
		function (data) 
		{
			$('#formCountry_id').html('<option value="">Выберите</option>'+data);
			if (selected != '') 
			{
				$('#formCountry_id option[value='+selected+']').attr('selected', 'selected');
			}
		});
	ajax_hide();
}

function selectCountry(country_id) {
  $('#formCountry_id').val(country_id);
}


// грузим область, город, район, если по ним уже производится поиск
function loadFormLocation(distrId, cityId, areaId)
{
	$( '#formDistrict_id' ).attr( 'disabled', true );
	$( '#formCity_id' ).attr( 'disabled', true );
    $( '#formArea_id' ).attr( 'disabled', true );
	$( '#formArea_id' ).removeClass( 'required' );

	$.get(	URLs + '/index.php?mod=jquery&submod=load_location',
		  	{
				distrId: distrId,
				cityId: cityId,
				areaId: areaId
			}, 
			function( xml )
			{	
				var districts = $( 'districts', xml ).text();
				var cities = $( 'cities', xml ).text();
				var areas = $( 'areas', xml ).text();

				if( districts != '' )
				{
					var baseOption = '<option value="">Выберите</option>';
					$( '#formDistrict_id' ).removeAttr( 'disabled' );
					$( '#formDistrict_id' ).html( baseOption + districts );
				}
				else
				{
					$( '#formCity_id' ).html( '<option value="">Выберите область</option>' );
					$( '#formArea_id' ).html( '<option value="">Выберите город</option>' );
				}

				if( cities != '' )
				{
					var baseOption = '<option value="">Выберите</option>';
					$( '#formCity_id' ).removeAttr( 'disabled' );
					$( '#formCity_id' ).html( baseOption + cities );
				}
				else
				{
					$( '#formCity_id' ).html( '<option value="">Городов нет</option>' );
					$( '#formArea_id' ).html( '<option value="">Районов нет</option>' );
				}

				if( areas != '' )
				{
					var baseOption = '<option value="">Выберите</option>';
					$( '#formArea_id' ).removeAttr( 'disabled' );
					$( '#formArea_id' ).addClass( 'required' );
					$( '#formArea_id' ).html( baseOption + areas );
				}
				else
				{
					$( '#formArea_id' ).html( '<option value="">Районов нет</option>' );
				}
				
			}, 
			'xml');
	ajax_hide();

}

function loadDistricts() {

	$( '#searchFormTableBody tr.selectedAreas' ).remove();
	
	$( '#areaCell' ).css( 'visibility', 'hidden' );
	$( '#areaCell' ).css( 'display', 'none' );

	$( '#formDistrict_id' ).attr( 'disabled', true );
	$( '#formCity_id' ).attr( 'disabled', true );
    $( '#formArea_id' ).attr( 'disabled', true );

	$( '#formCity_id' ).html( '<option value="">Выберите область</option>' );
	$( '#formArea_id' ).html( '<option value="">Выберите город</option>' );

	$( '#formDistrict_id' ).val( $( '#formDistrict_id' ).find( 'option:first' ).attr( 'value' ) );
	$( '#formCity_id' ).val( $( '#formCity_id' ).find( 'option:first' ).attr( 'value' ) );
	$( '#formArea_id' ).val( $( '#formArea_id' ).find( 'option:first' ).attr( 'value' ) );

	$.get(	URLs + '/index.php?mod=jquery&submod=load_districts',
		  	{
				id         : $('#formDistrict_id').val(),
				countryId : $('#formCountry_id').val()
			}, 
			function( xml ) {	

				var options = $( 'root', xml ).text();
				if( options != '' ) {
					var baseOption = '<option value="">Выберите</option>';
					$( '#formDistrict_id' ).removeAttr( 'disabled' );
					$( '#formDistrict_id' ).html( baseOption + options );
				} else {
					$( '#formCity_id' ).html( '<option value="">Выберите область</option>' );
					$( '#formArea_id' ).html( '<option value="">Выберите город</option>' );
				}

			}, 
			'xml');
	ajax_hide();

}

function loadCities(id)
{
	$( '#searchFormTableBody tr.selectedAreas' ).remove();

	$( '#areaCell' ).css( 'visibility', 'hidden' );
	$( '#areaCell' ).css( 'display', 'none' );

	$( '#areaCaption' ).text( 'Район:' );

	$( '#formCity_id' ).attr( 'disabled', true );
    $( '#formArea_id' ).attr( 'disabled', true );

	$( '#formArea_id' ).html( '<option value="">Выберите город</option>' );

	$( '#formCity_id' ).val( $( '#formCity_id option:first' ).attr( 'value' ) );
	$( '#formArea_id' ).val( $( '#formArea_id option:first' ).attr( 'value' ) );

	$.get(	URLs + '/index.php?mod=jquery&submod=load_cities',
		  	{
				'id': id
			}, 
			function( xml )
			{	
				var options = $( 'root', xml ).text();
				if( options != '' )
				{
					var baseOption = '<option value="">Выберите</option>';
					$('#formCity_id').removeAttr( 'disabled' );
					$('#formCity_id').html( baseOption + options );
				}
				else
				{
					$( '#formCity_id' ).html( '<option value="">Городов нет</option>' );

					$( '#areaCell' ).css( 'width', '0px' );

					
					$( '#areaCell' ).css( 'visibility', 'hidden' );
					$( '#areaCell' ).css( 'display', 'none' );

					$( '#formArea_id' ).html( '' );
				}
			}, 
			'xml');
	ajax_hide();
}

function loadAreas(id)
{
	$( '#searchFormTableBody tr.selectedAreas' ).remove();

	if( $( '#ie6frame' ).length != 0 ) $( '#ie6frame' ).hide();
	$( '#areaPopup' ).hide();

    $( '#formArea_id' ).attr( 'disabled', true );
	$( '#formArea_id' ).val( $( '#formArea_id option:first' ).attr( 'value' ) );

	$.get(	URLs + '/index.php?mod=jquery&submod=load_areas',
		  	{
				'id': id
			}, 
			function( xml )
			{	
				var options = $( 'root', xml ).text();
				if( options != '' )
				{
					if( id == 8 ) $( '#areaPopupLink' ).text( 'Выберите станцию метро' );
					else $( '#areaPopupLink' ).text( 'Выберите район' );
					
					$( '#areaCell' ).css( 'width', '165px' );

					$( '#areaCell' ).css( 'visibility', 'visible' );
					$( '#areaCell' ).css( 'display', 'inline' );

					var selectAllOption = '<input type="checkbox" id="selectAllOption" style="height: 16px; width: 16px;" onclick="selectAllAreas()" /><label style="color: #FD0000;" for="selectAllOption">Все районы</label><br/>';

					$( '#areaPopup .areasList' ).html( selectAllOption + options );
				}
				else
				{
					$( '#areaCell' ).css( 'width', '0px' );

					$( '#areaCell' ).css( 'visibility', 'hidden' );
					$( '#areaCell' ).css( 'display', 'none' );

					$( '#formArea_id' ).html( '' );
				}
			}, 
			'xml');
	ajax_hide();
}

function loadAreasOne(id)
{
	if( $( '#ie6frame' ).length != 0 ) $( '#ie6frame' ).hide();
	$( '#areaPopup' ).hide();

    $( '#formArea_id' ).attr( 'disabled', true );
	var areaNonrequired = $( '#formArea_id' ).is( '.nonrequired' );
	$( '#formArea_id' ).removeClass( 'required' );

	$( '#formArea_id' ).html( '<option value="">Выберите</option>' );

	if( id == 8 ) $( '#areaCaption' ).text( 'Станция метро:' );
	else $( '#areaCaption' ).text( 'Район:' );


	$.get(	URLs + '/index.php?mod=jquery&submod=load_areas_one',
		  	{
				'id': id
			}, 
			function( xml )
			{	
				var options = $( 'root', xml ).text();
				if( options != '' )
				{
					var baseOption = '<option value="">Выберите</option>';
					$( '#formArea_id' ).html( baseOption + options );
					$( '#formArea_id' ).removeAttr( 'disabled' );

					if( !areaNonrequired ) $( '#formArea_id' ).addClass( 'required' );
				}
				else
				{
					$( '#formArea_id' ).html( '<option value="">Районов нет</option>' );
				}
			}, 
			'xml');
	ajax_hide();
}

// убирает район из строки выбранных районов
function deselectArea(areaId)
{
	if( areaId == 'all' ) 
	{
		$( '#searchFormTableBody tr.selectedAreas' ).remove();
		return;
	}

	// удаляем выбранный район из списка
	$( '#selectedAreasList' ).find( '#selectedArea' + areaId ).remove();

	// убираем "," у последнего элемента
	var lastSpan = $( '#selectedAreasList span.selectedArea:last span.text' );
	var lastSpanText = lastSpan.text();
	lastSpan.text( lastSpanText.replace( ',', '' ) );
	
	// если выбранных районнов не осталось - удаляем саму строку с ними
	if( $( '#selectedAreasList span' ).length == 0 ) $( '#searchFormTableBody tr.selectedAreas' ).remove();
}


// выводит или скрывает попап выбора районов
function toggleAreaPopup()
{
	if( $('#areaPopup').css('display') == 'none' )
	{
		// проходим по выбранным районам и расставляем соответствующие
		// галки в попапе
		if( $( '#selectedAreasList [name=areasAllSelected]' ).val() == 1 )
		{
			$('#areaPopup .areasList' ).find( 'input[type=checkbox]' ).attr( 'checked', 'checked' );
		}
		else
		{
			$( '#selectedAreasList span.selectedArea' ).each(function()
			{
				var selectedAreaSpan = $( this );
				var areaId = selectedAreaSpan.find( 'input[name="areasIds[]"]' ).val();
				$('#areaPopup .areasList' ).find( 'input[areaId=' + areaId + ']' ).attr( 'checked', 'checked' );
			});
		}

		if( $( '#ie6frame' ).length != 0 )
		{
			$( '#ie6frame' ).css( 'height', $(document).height() + 'px' );
			$( '#ie6frame' ).show();
		}
		$('#areaPopup').show();
	}
	else 	
	{
		$('#areaPopup .areasList' ).find( 'input[type=checkbox]' ).removeAttr( 'checked' );

		if( $( '#ie6frame' ).length != 0 ) $( '#ie6frame' ).hide();

		$('#areaPopup').hide();
	}
}

// добавляет районы в строку выбранных районов
function selectAreas()
{
	// скрываем попап с районами
	if( $( '#ie6frame' ).length != 0 ) $( '#ie6frame' ).hide();

	$( '#areaPopup' ).hide();

	// если ни одного района не выбрано ничего не делаем
	if( $( '#areaPopup .areasList' ).find( 'input:checked' ).length == 0 ) return;
	
	// очищаем текущий список районов
	$( '#selectedAreasList' ).html( '' );

	// если строка с выбранными районами отсутствует - добавляем ее
	if( $( '#searchFormTableBody tr.selectedAreas' ).length == 0 )
	{
		var row = '<tr class="selectedAreas"><td colspan="4"><strong>Вы выбрали районы:&nbsp;&nbsp;</strong><span id="selectedAreasList"></span></td></tr>';
		$( '#searchFormTableBody' ).find( 'tr.firstLine' ).after( row );
	}

	// формируем список добавленных районов
	var selectedAreasList = '';
	var isAllAreasSelected = false;
	
	$( '#areaPopup .areasList' ).find( 'input:checked' ).each( function()
	{
		if( isAllAreasSelected ) return;

		if( $( this ).attr( 'id' ) != 'selectAllOption' )
		{
			var areaId = $( this ).attr( 'areaId' );
			var areaName = $( '#areaPopup label[for="area' + areaId + '"]' ).text();
			selectedAreasList += '	<span class="selectedArea" id="selectedArea' + areaId + '">\
										<input type="hidden" name="areasIds[]" value="' + areaId + '" />\
										<a href="#" onclick="deselectArea(' + areaId + ')">\
											<img border="0" src="' + URLs +'/data/i/site/closeIcon.png"/>\
										</a>\
										&nbsp;\
										<span class="text">' + areaName + ',</span>\
										&nbsp;&nbsp;&nbsp;\
									</span>';
		}
		else
		{
			if( $( this ).attr( 'checked' ) )
			{
				selectedAreasList = '<span class="selectedArea">\
										<input type="hidden" name="areasAllSelected" value="1" />\
										<a href="#" onclick="deselectArea(\'all\')">\
											<img border="0" src="' + URLs +'/data/i/site/closeIcon.png"/>\
										</a>\
										&nbsp;\
										<span class="text">Все районы</span>\
									</span>';
				isAllAreasSelected = true;
			}
		}
	} );

	// добавляем его
	$( '#selectedAreasList' ).html( selectedAreasList );

	// убираем "," у последнего элемента
	var lastSpan = $( '#selectedAreasList span.selectedArea:last span.text' );
	var lastSpanText = lastSpan.text();
	lastSpan.text( lastSpanText.replace( ',', '' ) );

	// очищаем флажки в скрытом ранее попапе
	$( '#areaPopup .areasList' ).find( 'input[type="checkbox"]' ).each(function()
	{
		$( this ).removeAttr( 'checked' );
	});

}

function selectAllAreas()
{	
	// определяем как установлен флажок "все районы"
	var isChecked = ( $( '#selectAllOption:checked' ).length != 0 );

	// проходим по остальным флажкам устанавливая их или снимая, в зависимости
	// от isChecked
	$( '#areaPopup .areasList' ).find( 'input[type="checkbox"]' ).each(function()
	{
		if( $( this ).attr( 'id' ) != 'selectAllOption' )
		{
			if( isChecked ) $( this ).attr( 'checked', 'checked' );
			else $( this ).removeAttr( 'checked' );
		}
	});
}

/*
function selectCity()
{
	$.get(	URLs + '/index.php?mod=jquery&submod=city',
		  	{
				id: $('#formCity_id').val()
			}, 
			function( xml )
			{	
				$( '#formArea_id' ).removeAttr( 'disabled' );
				$( '#formArea_id' ).html( $( 'root', xml ).text() );
			}, 
			'xml');
	ajax_hide();

}
*/
function selectCity(select, area_id) 
{
    $('#formArea_id').attr('disabled',true);
	$.getJSON(
		URLs+'/index.php?mod=jquery&submod=city',
		{
			id: $('#formCity_id').val(), 
			selected: select
		}, 
		function(j)
		{
			var option = '';
			var areas = '';
			if(j.length == 0)
			{
				$("td:contains('Район')").find('span.lblue').hide();
				$('#formArea_id').attr('disabled', 'disabled');
				if( $('#formArea_id option:selected').length == 0 )
				{ 
					$('#formArea_id option:first').html('Районов нет');
					$('#formArea_id option:first').val('-1');
				}
				else
				{
					$('#formArea_id option:selected').html('Районов нет');
					$('#formArea_id option:selected').val('-1');
				}
				return;
			}
			else $("td:contains('Район')").find('span.lblue').show();

			
			for (var i = 0; i < j.length; i++) 
			{
				option += '<option value="' + j[i].optionValue + '" ' + j[i].optionId + '>' + j[i].optionDisplay + '</option>';
				areas  += '<input style="width: 16px; height:16px;" type="checkbox" value="' + j[i].optionValue + '"/>' + j[i].optionDisplay + '<br>';
			}

			$('#areaPopup .areasList').html(areas);

			$('#formArea_id').html('<option value="">Выберите</option>' + option);
			$('#formArea_id option#selectedArea').attr('selected', 'selected');
			$('#formArea_id').attr('disabled',false);

			if (area_id != '') $('#formArea_id').val(area_id);
			if($('#formArea_id').val()=='') $('#formArea_id').addClass('yes');
		});
	ajax_hide();
}

function selectCity2(select, area_id) {
	$.getJSON(URLs+'/index.php?mod=jquery&submod=city',{id: select, selected: select}, function(j){
		var option = '';
		for (var i = 0; i < j.length; i++) {
			option += '<option value="' + j[i].optionValue + '" ' + j[i].optionId + '>' + j[i].optionDisplay + '</option>';
		}
		$('#formArea_id').html('<option value="">Выберите</option>' + option);
		$('#formArea_id option#selectedArea').attr('selected', 'selected');
    if (area_id != '') {
      $('#formArea_id').val(area_id);
    }
		if($('#formArea_id').val()=='')$('#formArea_id').addClass('yes');
	});
  ajax_hide();
}

function selectCityApp(select,status) {
	$.getJSON(URLs+'/index.php?mod=jquery&submod=city',{id: $('#formCity_id').val(), selected: select}, function(j){
		var option = '';
		var formArea = $('#formArea').val().split('::');
		for (var i = 0; i < j.length; i++) {
			if (j.length == (i+1)){separ = '';}else{separ = ', ';}
			option += '<a href="javascript:;" id="areaId' + j[i].optionValue +'" onclick="selectCityAppSelected(\'' + j[i].optionValue + '\',\'' + j[i].optionDisplay + '\');" style="font-size: 0.9em; text-decoration: none; position: static">' + j[i].optionDisplay + '</a>' + separ;
		}
		if (status == 2) {$('#formArea').val('');}
		$('#selectAreaAddress').css('display','').html('Выберите требуемые районы:<br /><div style="height: 80px; padding: 5px 5px 10px 5px; overflow: auto; border: 1px solid #C7C7C7; width: 285px">' + option + '</div>');
		if (status == 1) {
			for (var i = 0; i < j.length; i++) {
				for (var ii = 0; ii < formArea.length; ii++) {
					if (j[i].optionDisplay == formArea[ii]) {
						$('#areaId' + j[i].optionValue).css('color','#DE0000');
						$('#areaId' + j[i].optionValue).attr('class','#areaId' + j[i].optionValue);
					}
				}
			}
		}
	});
  ajax_hide();
}


function selectCityAppSelected(id,name) {
	var v = $('#formArea').val();
	if ($('#areaId' + id).attr('class') == '') {
		$('#areaId' + id).css('color','#DE0000');
		$('#areaId' + id).attr('class','#areaId' + id);
		$('#formArea').val(v + name + '::');
	} else {
		$('#areaId' + id).css('color','#389525');
		$('#areaId' + id).attr('class','');
		v=v.split(name + '::').join('');
		$('#formArea').val(v);
	}
  ajax_hide();
}


/*
$(document).ready(function() 
				  {
				  });*/
