﻿function BindDistrict(e, collection) {
    if (collection.parent.value && collection.parent.value != '')
	$.ajax({
		type: "POST",
		url: "/WebServices/CascadingDropDownList.asmx/DistrictGetList",
		contentType: "application/json; charset=utf-8",
		data: '{"regionNameId":"' + collection.parent.value + '"}',
		dataType: "json",
		success: function(dataObj) {
		Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{ alert(errorThrown); }
	});
}

function BindDistrictFilter(e, collection) {
    if (collection.parent.value && collection.parent.value != '')
    $.ajax({
		type: "POST",
		url: "/WebServices/CascadingDropDownList.asmx/DistrictGetList",
		contentType: "application/json; charset=utf-8",
		data: '{"regionNameId":"' + collection.parent.value + '"}',
		dataType: "json",
		success: function(dataObj) {
			var dList = $('input[name="districtIds"]');
			var sdList = $('input[name="subdistrictIds"]');
			Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
			if (collection.parent.value == "kiev") {
				collection.current.style.display = "none";
				$('div[id="chooseDistrict"]').show();
			}
			else {
				collection.current.style.display = "block";
				dList[0].value = sdList[0].value = "";
				$('div[id="chooseDistrict"]').hide();
			}
			$('a[class="chooseDistrict"]')[0].innerHTML = GetCaptionForDistrict(dList[0].value);

		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{ alert(errorThrown); }
	});
}

//Вызывается на District.OnChange
function BindSubDistrictFilter(e, collection) {
	var selected = collection.parent.value == '' ? collection.parentValue : collection.parent.value;

	if (selected && selected != '')
	    $.ajax({
	        type: "POST",
	        url: "/WebServices/CascadingDropDownList.asmx/SubDistrictGetList",
	        contentType: "application/json; charset=utf-8",
	        data: '{"districtId":"' + selected + '"}',
	        dataType: "json",
	        success: function(dataObj) {
	            var sdHolder = $('#SubDistrictHolder')[0];
	            var sdList = $('input[name="subdistrictIds"]');
	            var region = $('#Region')[0];
	            Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
	            if (collection.parent.value == "0"
					|| collection.current.options.length == 1	/*нет элементов в списке кроме "любой"*/
					|| region.value == "kiev") {
	                sdHolder.style.display = "none"; //->disable/enable
	            }
	            else {
	                sdHolder.style.display = "block"; //->disable/enable
	                sdList[0].value = "";
	            }
	        },
	        error: function(XMLHttpRequest, textStatus, errorThrown)
	        { alert(errorThrown); }
	    });
}
function BindDistrictFilterByUser(e, collection) {
    if (collection.parent.value && collection.parent.value != '')
        $.ajax({
            type: "POST",
            url: "/WebServices/CascadingDropDownList.asmx/DistrictGetListByUser",
            contentType: "application/json; charset=utf-8",
            data: '{"regionId":"' + collection.parent.value + '", "userId": "' + collection.userId + '", "userIdView": "' + collection.userIdView + '"}',
            dataType: "json",
            success: function(dataObj) {
                var dList = $('input[name="districtIds"]');
                var sdList = $('input[name="subdistrictIds"]');
                Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
                if (dataObj.d.length > 0) {
                    $('#DistrictId').removeAttr('disabled');                    
                    //                if (collection.parent.value == "kiev") {
                    //                    collection.current.style.display = "none";
                    //                    $('div[id="chooseDistrict"]').show();
                    //                }
                    //                else {
                    //                    collection.current.style.display = "block";
                    //                    dList[0].value = sdList[0].value = "";
                    //                    $('div[id="chooseDistrict"]').hide();
                    //                }
                    //                $('a[class="chooseDistrict"]')[0].innerHTML = GetCaptionForDistrict(dList[0].value);
                }
                else {
                    $('#DistrictId').attr('disabled', 'disabled');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            { alert(errorThrown); }
        });
}


function BindDistrictByRegionId(e, collection)
{
    if (collection.parent.value && collection.parent.value != '')
    $.ajax({
        type: "POST",
        url: "/WebServices/CascadingDropDownList.asmx/DistrictGetListByRegioId",
        contentType: "application/json; charset=utf-8",
        data: '{"regionId":"' + collection.parent.value + '"}',
        dataType: "json",
        success: function(dataObj)
        {
        	Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        { alert(errorThrown); }
    });
}

function BindSubDistrict(e, collection) {

	var selected = collection.parent.value == '' ? collection.parentValue : collection.parent.value;

	if (selected && selected != '')
	    $.ajax({
	        type: "POST",
	        url: "/WebServices/CascadingDropDownList.asmx/SubDistrictGetList",
	        contentType: "application/json; charset=utf-8",
	        data: '{"districtId":"' + selected + '"}',
	        dataType: "json",
	        success: function(dataObj) {
	            Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
	            if (collection.current.options.length < 2)
	                $("#tdSubDistrictId").hide();
	            else
	                $("#tdSubDistrictId").show();
	        },
	        error: function(XMLHttpRequest, textStatus, errorThrown) {
	            var i = 0;
	            //alert(errorThrown); 
	        }
	    });
}

function BindStreet(e, collection)
{
	var selected = collection.parent.value == '' ? collection.parentValue : collection.parent.value;
	if (selected && selected != '')
    $.ajax({
		type: "POST",
		url: "/WebServices/CascadingDropDownList.asmx/StreetGetList",
		contentType: "application/json; charset=utf-8",
		data: '{"districtId":"' + selected + '"}',
		dataType: "json",
		success: function(dataObj) {
			var data = Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
			AutoComplete("RealtyEditLocation_StreetName", data, collection.current, collection.isOnLoad, collection.parent.value);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);            
		}
	});
}
function BindBuildingNumber(e, collection) {
	var selected = collection.parent.value == '' ? collection.parentValue : collection.parent.value;
	if (selected && selected != '')
    $.ajax({
		type: "POST",
		url: "/WebServices/CascadingDropDownList.asmx/BuildingNumberGetList",
		contentType: "application/json; charset=utf-8",
		data: '{"streetId":"' + selected + '"}',
		dataType: "json",
		success: function(dataObj) {
		Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);            
		}
	});
}
function BindBuildingMaterials(e, collection)
{
    if (collection.parent.value && collection.parent.value != '')
    $.ajax({
        type: "POST",
        url: "/WebServices/CascadingDropDownList.asmx/BuildingMaterialGetList",
        contentType: "application/json; charset=utf-8",
        data: '{"buildingTypeId":"' + collection.parent.value + '"}',
        dataType: "json",
        success: function(dataObj)
        {
        	Bind(collection.current, dataObj.d, collection.selected, collection.isOnLoad, collection.defaultText);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert(errorThrown); 
        }
    });
   }
//Привязывает список к input полю
//выбранное значение записывает в hidden-input
   function BindConstructionComplex(inputId, hiddenInputId/*, builderId, isAdmin*/,complexType) {
	$.ajax({
		type: "POST",
		url: "/WebServices/CascadingDropDownList.asmx/ConstructionComplexGetList",
		//data: '{"builderId":"' + builderId + '","isAdmin":"' + isAdmin + '"}',
		data: '{"complexType":"' + complexType + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(dataObj) {
			var input = $('#' + inputId);
			input.autocomplete(dataObj.d, {
				minChars: 1,
				max: 200,
				maxItemsToShow: 10,
				//показывает элементы в списке
				formatItem: function(data, i, max) {
					return data.Name;
				},
				//это значение записывается в input-поле
				formatResult: function(data) {
					return data.Name;
				}
			});
			//отрабатывает, когда выбрано значение в списке autocomplete
			input.result(function(event, data, formatted) {
				$('#' + hiddenInputId).val(data.Id);
			});
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);            
		}
	});
}

function Bind(districtList, districtValues, selectedValue, isOnLoad, defaultText)
{

	var arr = new Array();
	districtList.options.length = 0;
	newOption = new Option(defaultText, "0");
	districtList.options.add(newOption);
	districtList.options[0].selected = true;
	for (var i = 1; i <= districtValues.length; i++) 
	{
		newOption = new Option(districtValues[i - 1].Name, districtValues[i - 1].Id);
		arr[i - 1] = districtValues[i - 1].Name;
		districtList.options.add(newOption);
		if (districtList.options[i].value == selectedValue) {
			districtList.options[i].selected = true;
		}

	}
	if (!isOnLoad || (selectedValue == "" || selectedValue == 0)) {
		DoListClick(districtList);
	}
	return arr;

}

function DoListClick(list) {


	if (list.dispatchEvent != undefined) {
		var mine = document.createEvent("MouseEvents");
		mine.initEvent("change", true, true);
		list.dispatchEvent(mine);
	}
	else {
		var evt = document.createEventObject();
		list.fireEvent('onchange', evt);
	}
		
}
function GetSelectedIndex(list, text) {
	for (var i = 0; i < list.length; i++) {
		if (list[i].text == text)
			return i;
	}
	return 0;
}

function GetSelectedValue(list, text) {
    for (var i = 0; i < list.length; i++) {
        if (list[i].text == text)
            return i;
    }
    return -1;
}
function AutoComplete(inputId, data, hiddenList, isOnLoad, parentId) {
	//var transaction = GetQueryParam("transaction", window.location);
	//var isSnimautPokupaut = (transaction.indexOf("snimajut") > -1) || (transaction.indexOf("pokupajut") > -1)
	//if (hiddenList.length < 2 && parentId == "0" && !isSnimautPokupaut) {
	if (hiddenList.length < 2 && parentId == "0") {
		$("#" + inputId).attr("readonly", "true");
		$("#" + inputId).attr("value", "");
		return;
	}
	$("#" + inputId).removeAttr('readonly');
	if (isOnLoad == "true") { 
		if (hiddenList.value != 0)
			$("#" + inputId).attr("value", hiddenList[hiddenList.selectedIndex].text);
	}
	else
	    $("#" + inputId).attr("value", "");
	if (data.length == 0) {
	    $("#" + inputId).unautocomplete();
	}
	else {
	    $("#" + inputId).autocomplete(data, {
    	    minChars: 1,
	        max: 200
	    });
	}

	$("#" + inputId).result(function(event, data, formatted) {
	    hiddenList.selectedIndex = GetSelectedIndex(hiddenList, formatted);
	    DoListClick(hiddenList);
	});
	$("#" + inputId).blur(function() {
	    hiddenList.selectedIndex = GetSelectedIndex(hiddenList, $("#" + inputId).val());
	    DoListClick(hiddenList);
	    SetMarker();
	});
}
function CleanHiddenIfEmpty(ctrl,hiddenId){
	if (ctrl.value == '')
		$('#'+hiddenId).val('');
}

function FilterDeveloper(inputId, service, saveId) {
    if ($('#' + inputId).length > 0)
        $.ajax({
            type: "POST",
            url: "/WebServices/CascadingDropDownList.asmx/" + (service ? service : "ConstructionComplexGetList"),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(dataObj) {
                var input = $('#' + inputId);
                input.autocomplete(dataObj.d, {
                    minChars: 1,
                    formatItem: function(data, i, max) {
                        return data.Value;
                    },
                    formatResult: function(data) {
                        return data.Value;
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }

   function AlertIfNoDistrict(distrCtrlId) {
   	if ($('[id=' + distrCtrlId + ']').val() == "0")
   		alert("Район должен быть указан");
   }

   function GetCaptionForDistrict(dIds) 
   {
   	var dCount = dIds == "" ? 0 : dIds.split(',').length;
   	var text = "";
   	if (dCount > 0)
   		text += dCount + " районов "
   	return text == "" ? "Выберите район" : "Выбрано " + text;
   }


   function DistrictIdToIds() 
   {
   		$("input[name=districtIds]").val(this.value == '0' ? "" : this.value);
   }

	//устанавливает значение из ddl(this) в hidden поле с заданным name-аттрибутом
   function IdToIds(name) 
   {
   		$("input[name=" + name + "]").val(this.value == '0' ? "" : this.value);
   }

