function ID(value) {
	return document.getElementById(value);
} // end function

function NextTag(object, tagName) {
    var next = object.nextSibling;
    while ((next) && (!(next.tagName) || (next.tagName.toLowerCase() != tagName.toLowerCase())))
        next = next.nextSibling;
    return next;
} // end function

function ChildTags(object, tagName) {
    var tags = new Array();
    var current = object.firstChild;
    while (current) {
        if ((current.tagName) && (current.tagName.toLowerCase() == tagName.toLowerCase()))
            tags.push(current);
        current = current.nextSibling;
    } // end while
    return tags;
} // end function

function RemoveTags(object, tagName) {
    if (!tagName) tagName = '';
    for (var i = object.childNodes.length - 1; i >= 0; i--) {
        var node = object.childNodes[i];
        var temp = (node.tagName) ? node.tagName : '';
        if (temp == tagName) object.removeChild(node);
    } // end for
} // end function

function GetOffsetTop(obj) {
    var top = 0;
    while (obj != null) {
        top += obj.offsetTop;
        obj = obj.offsetParent;
    } // end while
    return top;
} // end function

function ForEach(arr, delegate) {
    for (var i = 0; i < arr.length; i++)
        delegate(arr[i]);
} // end function

function PasswordChanged(password, confirm) {
    var td1 = NextTag(password.parentNode, 'TD');
    var td2 = NextTag(confirm.parentNode, 'TD');
    var labels = ChildTags(td2, 'SPAN');
    var eql = labels[0];
    var neql = labels[1];
    var show = (password.value != '') && (confirm.value != '');
    var eq = (password.value != '') && (confirm.value != '') && (password.value == confirm.value);
    eql.style.display = show && eq ? '' : 'none';
    neql.style.display = show && !eq ? '' : 'none';
    password.className = confirm.className = show ? (eq ? 'text equal' : 'text error') : 'text';
    td1.className = td2.className = eq ? 'notices equal' : 'notices error';
    RemoveTags(td1);
    RemoveTags(td2);
} // end function

function AddOptionToList(select, value, text) {
    var option = document.createElement('OPTION');
    option.value = value;
    option.innerHTML = text;
    select.appendChild(option);
} // end function

function LockDirectory(select, message) {
    if (!message) message = '(выберите из списка)';
    select.disabled = true;
    select.innerHTML = '';
    select.locked = true;
    AddOptionToList(select, '', message);
} // end function

function LoadDirectory(select, uri, message) {
    select.locked = false;
    var event = 
        function (status, result) {
            if (!select.locked) {
                LockDirectory(select, message);
                if (status != null) {
                    var root = XmlRootByText(result);
                    var items = GetXmlNodesByTagName(root, 'item');
                    for (var i = 0; i < items.length; i++)
                        AddOptionToList(select, GetXmlAttributeValue(items[i], 'id'), GetXmlNodeValue(items[i]));
                    select.disabled = false;
                } // end if
            } // end if
        } // end event
    HttpRequest(SitePath + uri, null, event);
    return false;
} // end function

function LoadSubcategoryList(select, child) {
    if (select.selectedIndex > 0) {
        LockDirectory(child, 'загрузка подкатегорий...');
        LoadDirectory(child, 'Ajax/GetSubcategoryList.aspx?CategoryID=' + select.value);
    } else {
        LockDirectory(child);
    } // end if
    return false;
} // end function

function LoadRegionList(select, child) {
    if (select.selectedIndex > 0) {
        LockDirectory(child, 'загрузка регионов...');
        LoadDirectory(child, 'Ajax/GetRegionList.aspx?CountryID=' + select.value);
    } else {
        LockDirectory(child);
    } // end if
    return false;
} // end function

function LoadCityList(select, child) {
    if (select.selectedIndex > 0) {
        LockDirectory(child, 'загрузка городов...');
        LoadDirectory(child, 'Ajax/GetCityList.aspx?RegionID=' + select.value);
    } else {
        LockDirectory(child);
    } // end if
    return false;
} // end function

function AnnouncementTypeChanged(type) {
    var wizardHeader = ID('proposal_stps');
    if (wizardHeader) ForEach(ChildTags(wizardHeader, 'LI'), function (item) { if (item.className != 'not-current') item.className = 'current-' + type; });
    var wizardButtons = ID('steps_links');
    if (wizardButtons) ForEach(ChildTags(wizardButtons, 'DIV'), function (item) { if (item.className.substr(0, 6) == 'button') item.className = 'button ' + type; });
} // end function

function AnnouncementCategoryChanged(link, cid, scid) {
    var param = ID('subcategory_param');
    if (param) param.value = scid;
    var container = ID('categories_sel');
    if (container) {
        var current = link.parentNode;
        var lis = container.getElementsByTagName('LI');
        for (var i = 0; i < lis.length; i++)
            if (lis[i] != current) lis[i].className = '';
        current.className = 'selected';
        link.blur();
        var ch = ID('category_head' + cid);
        var display = ID('your_choose');
        if ((ch) && (display)) {
            var label = ChildTags(display, 'SPAN')[0];
            label.innerHTML = ch.innerHTML + ' \\ ' + link.innerHTML;
            display.style.display = 'block';
        } // end if
        var hint = ID('category_not_selected');
        if (hint) hint.style.display = 'none';
    } // end if
    return false;
} // end function

var processingPopupRequest = false;

function PopupHttpRequest(uri, data, callback) {
    if (processingPopupRequest) {
        alert('Идет выполнение операции. Пожалуйста, подождите...');
    } else {
        var event = 
            function (status, result) {
                processingPopupRequest = false;
                if (status == 200) {
					callback(result);
				} else {
					alert('Во время выполнения операции произошла ошибка. Попробуйте выполнить операцию позже.');
				} // end if
            } // end event
        processingPopupRequest = true;
        try {
            HttpRequest(SitePath + uri, data, event);
        } catch (e) {
            processingPopupRequest = false;
        } // end try
    } // end if
} // end function

function ShowPopup(uri, link) {
    var popup = ID('add_comment_form');
    if (popup) {
        var event =
            function (result) {
                popup.innerHTML = result;
                popup.style.display = 'block';
                var height = popup.offsetHeight;
                var top = GetOffsetTop(link) - parseInt(height / 2);
                if (top > document.body.offsetHeight) top = document.body.offsetHeight - height;
                if (top < 0) top = 0;
                popup.style.top = top + 'px';
            } // end event
        PopupHttpRequest(uri, null, event);
    } // end if
    return false;
} // end function

function ClosePopup() {
    var popup = ID('add_comment_form');
    if (popup) {
        popup.style.display = 'none';
        popup.innerHTML = '';
    } // end if
    return false;
} // end function

function FormFieldChanged(submit) {
    var enabled = true;
    for (var i = 0; i < submit.form.elements.length; i++) {
        var el = submit.form.elements[i];
        if ((el.name) && ((!el.type) || (el.type != 'hidden')) && (!submit.form.elements[i].value)) enabled = false;
    } // end for
    submit.disabled = !enabled;
    return enabled;
} // end function

function PostPopupForm(form, uri, id, hide, flag_id) {
    var data = '';
    for (var i = 0; i < form.elements.length; i++)
        if (form.elements[i].name) data += form.elements[i].name + '=' + escape(form.elements[i].value) + '&';
    var event =
        function (result) {
            var root = XmlRootByText(result);
            var message = GetXmlNodeValue(GetXmlNodeByTagName(root, 'message'));
            var html = GetXmlNodeValue(GetXmlNodeByTagName(root, 'html'));
            var url = GetXmlNodeValue(GetXmlNodeByTagName(root, 'url'));
            var flag = parseInt(GetXmlNodeValue(GetXmlNodeByTagName(root, 'flag')));
            if (message) {
                alert(message);
            } else {
                if (hide) ClosePopup();
                if (id) {
					var container = ID(id);
					if (container) container.innerHTML = html;
				} else if (url) {
					window.location.href = url;
				} // end if
                if (flag_id) {
                    var flag_container = ID(flag_id);
                    if (flag_container) flag_container.style.display = (flag == 1) ? 'block' : 'none';
                } // end if
            } // end if
        } // end event
    PopupHttpRequest(uri, data, event);
    return false;
} // end function

function ShowPhoto(link) {
	var container = ID('representation');
	if (container) {
		var image = link.getElementsByTagName('IMG')[0];
		var item = link.parentNode;
		if (item.className != 'current') {
			image.src = image.src.replace('c.jpg', 'b.jpg');
			var items = item.parentNode.getElementsByTagName('LI');
			for (var i = 0; i < items.length; i++) {
				if (items[i].className == 'current') {
					var temp = items[i].getElementsByTagName('IMG')[0];
					temp.src = temp.src.replace('b.jpg', 'c.jpg');
				} // end if
				items[i].className = (item == items[i]) ? 'current' : '';
			} // end for
			var large = container.getElementsByTagName('IMG')[0];
			large.src = image.src.replace('b.jpg', 'd.jpg');
			large.alt = image.alt;
			large.parentNode.href = link.href;
		} // end if
	} // end if
	return false;
} // end function

function MainSelectorClick(cb) {
	var container = ID('letters-container');
	if (container) ForEach(container.getElementsByTagName('INPUT'), function (item) { if (item.className == 'item') item.checked = cb.checked; });
} // end function

function SelectionChanged() {
	var container = ID('letters-container');
	if (container) {
		var checked = true;
		var mcb = null;
		var handler =
			function (item) {
				if (item.className == 'all') mcb = item;
				if ((item.className == 'item') && (!item.checked)) checked = false;
			} // end event
		ForEach(container.getElementsByTagName('INPUT'), handler);
		if (mcb) mcb.checked = checked;
	} // end if
} // end function

function RemoveSelectedMessages(link) {
	var container = ID('letters-container');
	if (container) {
		var values = new Array();
		ForEach(container.getElementsByTagName('INPUT'), function (item) { if ((item.className == 'item') && (item.checked)) values.push(item.value); });
		if (values.length > 0) {
			ShowPopup('AJAX/GetMessageRemoveForm.aspx?MessageID=' + values.join(',') + '&ReturnUrl=' + escape(window.location.href), link);
		} else {
			alert('Выберите сообщения, которые необходимо удалить.');
		} // end if
	} // end if
	return false;
} // end function

function ChangeSearchSortOrder(order, direction) {
	var form = ID('search_form');
	if (form) {
		form.SortOrder.value = order;
		form.SortDirection.value = direction;
		form.submit();
	} // end if
	return false;
} // end function

function ChangeSearchPage(page) {
	var form = ID('search_form');
	if (form) {
		form.Page.value = page;
		form.submit();
	} // end if
	return false;
} // end function
