/**
 * @projectDescription Contains JavaScript functions from MY project templates
 */
/*
 * {Common}
 */
function showHideBlock(oid){
    elem = $(oid);
    elem.visible() ? elem.hide() : elem.show();
}

function has_javascript(){
    app_name = navigator.userAgent.toLowerCase();
    opera_exist = app_name.indexOf("opera");
    nets_exist = app_name.indexOf("netscape");
    nets_vers = parseFloat(app_name.substring(nets_exist + 9, app_name.length));
    opera_vers = parseFloat(app_name.substring(opera_exist + 6, app_name.length));
    if ((opera_exist != -1 && opera_vers <= 7.5) || (nets_exist != -1 && nets_vers < 7.1))
        return false;
    return true;
}

/**
 *
 */
function more_disabled(){
    disableness = 1;
    $('submit_' + mode + (editing == 1 ? '_edit' : '')).disable();
}

/**
 *
 */
function less_disabled(){
    if (disableness == 1) {
        $('submit_' + mode + (editing == 1 ? '_edit' : '')).enable();
    }
    disableness = 0;
}

/**
 *
 * @param {String} field
 */
function disUndisField(field){
    if ($(field).disabled == 0) {
        Field.disable(field);
    }
    else {
        Field.enable(field);
    }
}

/**
 *
 * @param {String} sid
 */
function value_select(sid){
    var el = $(sid);
    if (el == undefined)
        return;
    el.options.length = 1;
    el.options[0].value = '';
    el.options[0].text = 'Выбрать';
    el.selectedIndex = 0;
}

/**
 *
 * @param {String} sid
 */
function makeother(sid){
    list = $(sid);
    if (list == undefined)
        return;
    list.disabled = 0;
    list.options.length = 0;
    list.options.length = list.options.length + 1;
    list.options[0].text = 'Не выбрано';
    list.options.length = list.options.length + 1;
    list.options[1].value = 'other';
    list.options[1].text = 'Другое';
}

/**
 *
 * @param {String} sid
 */
function onother(sid){
    if (sid == undefined || sid == '')
        return;
    suff = editing == 1 ? "_edit" : "";
}

/**
 *
 * @param {Object} sel
 * @param {String} block_on
 */
function onblock(sel, block_on){
    if (sel.value == 'other') {
        Element.show(block_on);
    }
    else {
        Element.hide(block_on);
    }
}

/**
 *
 * @param {String} oid
 */
function ChooseOtherObj(oid){
    var list = $(oid);
    if (list.disabled == 1)
        return;
    list.selectedIndex = list.options.length - 1;
    list.onchange();
}

/**
 * Определяем top - left координаты блока obj
 * @param {Object} obj
 * @return {Object}
 */
function absPosition(obj) {
    var coords = $(obj).cumulativeOffset();
    return {x: coords[0],y: coords[1]};
}

/**
 *
 * @param {String} UserStatus
 * @param {String} UserName
 */
function FriendComplaint(UserStatus, UserName){
    if (UserStatus) {
        $('ComplaintButton').value = "OK";
        $('ComplaintText').firstChild.data = "Удалить " + UserName + " из списка друзей и отправить жалобу?";
        $('friendship').value = "die";
    }
    else {
        $('ComplaintButton').value = "Подтвердить жалобу";
        $('ComplaintText').firstChild.data = "";
        $('friendship').value = "live";
    }
}

/**
 * Set el class to "bgg"
 * @param {Object} obj
 */
function darker(obj){
    obj.className = "bgg";
}

/**
 * Set el class to "bgw"
 * @param {Object} obj
 */
function whiter(obj){
    obj.className = "bgw";
}

/**
 * Show cross
 * @param {Object} obj
 */
function showCross(obj){
    obj.parentNode.parentNode.className = 'showCross';
}

/**
 * Hide cross
 * @param {Object} obj
 */
function hideCross(obj){
    obj.parentNode.parentNode.className = 'hideCross';
}

/**
 * Check input text length
 * @param {Object} txar
 */
function checkLength(txar){
    var beginer = MaxMessageLength;
    var b = $("simbCount1");
    var span = $("strCount1");
    if (txar.value.length <= beginer) {
        b.update(txar.value.length);
        span.style.color = "#909090";
    }
    else {
        b.update(beginer);
        span.style.color = "#FF0000";
        txar.value = txar.value.substring(0, beginer);
    }
}

/**
 * Disable submit button
 * @return {Boolean}
 */
function dis_sub_but(){
    var sub_but = $("sub_but");
    if (txar.value.length != "") {
        sub_but.value = "Идет отправка";
        sub_but.disable();
        return true;
    }
    else {
        return false;
    }
}

/**
 * Disable submit button 1
 * @return {Boolean}
 */
function dis_sub_but1(){
    var val1 = $("msg1").value;
    if (val1 != "") {
        $("sub_but1").disable();
        need_block = true;
        return true;
    }
    else {
        return false;
    }
}

/**
 * Disable submit button 2
 * @return {Boolean}
 */
function dis_sub_but2(){
    var val2 = $("msg2").value;
    if (val2 != "") {
        $("sub_but2").disable();
        need_block = true;
        return true;
    }
    else {
        return false;
    }
}

/**
 * Check CTRL+ENTER for messages threads
 * @param {Object} evt
 * @param {Object,String} frm
 * @param {String} mode
 */
function checkCtrlEnter(evt, frm, sub){
	var evt = evt || event;
    if (evt.ctrlKey && evt.keyCode === 13) {
			var res;
		if (sub) res = sub();
        if (res || !sub) {
        	if(Booster.inited) {
        		Booster.go($(frm).action, $(frm).method, $(frm).serialize(), 0, 0, 0, 0, $(frm).readAttribute('nohash'));
        	}
        	else {
        		$(frm).submit();
        	}
        }
    	}
}

function thread_checkCtrlEnter(evt){
    checkCtrlEnter(evt, 'dupdate', dis_sub_but1);
}

function dialogues_send_checkCtrlEnter(evt){
    checkCtrlEnter(evt, 'dupdate', dis_sub_but);
}
/*
 * {Audio}
 */
/**
 * Show audio edit block
 * @param {String} songNum
 * @param {String} file
 */
function audio_showEditBlock(songNum, file){
    if (!songNum)
        songNum = '';
    $('edit_author').value = $('author_' + songNum).innerHTML;
    $('edit_name').value = $('name_' + songNum).innerHTML;
    $('edit_text').value = $('text_' + songNum).innerHTML;
    $('edit_num').value = songNum;
    $('edit_file').value = file;
    var edit = $('edit');
    var del = $('edit_button_' + songNum);
    edit.style.top = absPosition(del).y + del.offsetHeight;
    edit.style.display = 'block';
}

/**
 * Change audio player button image
 * @param {String} n
 * @param {String} fname
 * @param {String} ptime
 */
function changePlayerButton(n, fname, ptime){
    var mytime = ptime * 1000;
    var mydiv = $('forflash' + n);
    mydiv.className = 'div_dashed_act';
    mydiv.update('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="297" height="7" id="flash' + n + '"><param name="allowScriptAccess" value="always" /><param name="swLiveConnect" value="true" /><param name="movie" value="http://img3.imgsmail.ru/r/my/player.swf?file=' + fname + '&time=' + mytime + '&mid=' + n + '&vol=' + volume + '" /><embed src="http://img2.imgsmail.ru/r/my/player.swf?file=' + fname + '&time=' + mytime + '&mid=' + n + '&vol=' + volume + '" width="297" height="7" name="flash' + n + '" id="flashplayer' + n + '" allowScriptAccess="always" swLiveConnect="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>');
    set_image_stop_first(n);
    if (last != 0) {
        var mydivdestr = $('forflash' + last);
        mydivdestr.update('');
        mydivdestr.className = 'div_dashed';
        var myimagedistr = $('mbutton' + last);
        myimagedistr.update('<a href="#"><img src="http://img1.imgsmail.ru/r/my/play_small.gif" onclick="' + lastchange + '"></a>');
        $('muslink' + last).onClick = lastchange;
        last = n;
        lastchange = 'changePlayerButton(' + n + ',\'' + fname + '\',' + ptime + ')';
    }
    else {
        last = n;
        lastchange = 'changePlayerButton(' + n + ',\'' + fname + '\',' + ptime + ')';
    }
}

/**
 * Change player button to play
 * @param {String} n
 */
function set_image_play(n){
    $('mbutton' + n).update('<a href="#"><img src="http://img0.imgsmail.ru/r/my/play_small.gif" onclick="set_image_stop(' + n + ')"></a>');
    toplay = '0';
    var myfobj = null;
    if (isIE) {
        eval('myfobj=window.flash' + n + ';');
    }
    else {
        myfobj = $('flashplayer' + n);
    }
    myfobj.SetVariable("_root.pause", "true");
}

/**
 * Change player button to stop first
 * @param {String} n
 */
function set_image_stop_first(n){
    $('mbutton' + n).update('<a href="#"><img src="http://img1.imgsmail.ru/r/my/pause_small.gif" onclick="set_image_play(' + n + ')"></a>');
    toplay = '1';
}

/**
 * Change player button to stop
 * @param {String} n
 */
function set_image_stop(n){
    $('mbutton' + n).update('<a href="#"><img src="http://img2.imgsmail.ru/r/my/pause_small.gif" onclick="set_image_play(' + n + ')"></a>');
    toplay = '1';
    var myfobj = null;
    if (isIE) {
        eval('myfobj=window.flash' + n + ';');
    }
    else {
        myfobj = $('flashplayer' + n);
    }
    myfobj.SetVariable("_root.pause", "false");
}

/**
 * Unpause player
 * @param {String} n
 */
function unPause(n){
    $('mbutton' + n).update('<a href="#"><img src="http://img3.imgsmail.ru/r/my/pause_small.gif" onclick="set_image_play(' + n + ')"></a>');
    toplay = '1';
}

/**
 * Set player volume
 * @param {String} n
 */
function setvolume(n){
    volume = n;
}

/**
 * On song end
 * @param {String} n
 */
function endMusic(n){
    iid = n + 1;
    var myimage = $('mbutton' + iid);
    if (!myimage) {
        endMusic(0);
    }
    else {
        myimage.down().down().onclick();
    }
}

/**
 *
 * @param {Object} obj
 * @param {String} AddText
 * @param {Object} Op
 * @return {Boolean}
 */
function audio_replaceSelectedText(obj, AddText, Op){
    if (Op.document.selection) //для IE и Opera
    {
        obj.focus();
        var s = Op.document.selection.createRange();
        s.text = AddText;
        s.select();
        return true;
    }
    else
        if (typeof(obj.selectionStart) == "number")//Для FF
        {
            var start = obj.selectionStart;
            var end = obj.selectionEnd;
            obj.value = obj.value.substr(0, start) + AddText + obj.value.substr(end);
            obj.setSelectionRange(end, end);
            return true;
        }
    return false;
}

function editChanged(frm){
    $('name_'+frm.num.value).update(frm.name.value);
    $('author_'+frm.num.value).update(frm.author.value);
    $('text_'+frm.num.value).update(frm.text.value);
    $('edit').style.visibility='hidden';
    return false;
}

/*
 * {Apps}
 */
/**
 * Disable arrows
 */
function disable_arrows(){
    sort_enabled = 0;
    for (i = 0; i < AppIDs.length; i++) {
        $(AppIDs[i] + '_arrows').setOpacity(0.5);
    }
}

/**
 * Enable arrows
 */
function enable_arrows(){
    sort_enabled = 1;
    for (i = 0; i < AppIDs.length; i++) {
        $(AppIDs[i] + '_arrows').setOpacity(1.0);
    }
}

/**
 * AJAX POSITION CALL
 * @param {String} appid
 * @param {String} current_position
 * @param {String} direction
 * @return {Boolean}
 */
function position(appid, current_position, direction){
    if (!sort_enabled)
        return false;
    var second_id = 0;
    for (i = 0; i < AppIDs.length; i++) {
        if (AppIDs[i] == appid && (i + direction) < AppIDs.length && (i + direction) >= 0) {
            second_id = AppIDs[i + direction];
        }
    }
    disable_arrows();
    ajax_call('perl_change_app_position', appid, second_id, current_position, direction, magic);
    return false;
}

/**
 * @param {String} num
 * @param {String} direction
 * @return {Boolean}
 */
function magic(num, direction){
    if (!direction)
        return false;
    var cols = new Array('pic', 'desc', 'menu');
    for (i = 0; i < cols.length; i++) {
        var first = $('td_' + cols[i] + num);
        var second = $('td_' + cols[i] + (num + direction));
        var saved = first.innerHTML;
        first.update(second.innerHTML);
        second.update(saved);
    }
    enable_arrows();
    return false;
}

/*
 * {Agent}
 */
// Listing with save
/**
 * @classDescription agent_SavedListing class
 * @param {Object} params
 */
function agent_SavedListing(params){
    // SUBMIT
    this.submit = function(){
        this.save();
        if (this.finishInput)
            this.finishInput.value = 1;
        if (this.onSubmitCallback)
            this.onSubmitCallback(this.getSavedElements());
        return false;
    };
    // CHANGE PAGE
    this.changePage = function(page){
        this.save(1);
        this.pageInput.value = page;
        if (this.onPageChangeCallback)
            this.onPageChangeCallback(this.getSavedElements(), page);
        this.form.submit();
        return false;
    };
    // SELECT
    this.select = function(){
        if (this.selectAllCheckbox) {
            var elements = this.form.elements;
            for (var i = 0; i < elements.length; i++) {
                if (elements[i].type == 'checkbox' && this.selectAllCheckbox != elements[i]) {
                    elements[i].checked = this.selectAllCheckbox.checked ? true : false;
                }
            }
            this.count();
        }
    };
    // SAVE
    this.save = function(pageChange){
        var value = this.getElementsToSave();
        var count = value.length;
        value = value.join(',');
        this.saveInput.value = value;
        if (this.openerSaveInput && !pageChange)
            this.openerSaveInput.value = value;
        if (this.countHTMLElement)
            this.countHTMLElement.innerHTML = count;
        if (this.openerCountHTMLElement && !pageChange)
            this.openerCountHTMLElement.innerHTML = count;
        if (this.saveInput2) {
            this.saveInput2.value = this.getElementsToSave2().join(',');
            if (this.openerSaveInput2 && !pageChange)
                this.openerSaveInput2.value = this.saveInput2.value;
        }
    };
    // COUNT
    this.count = function(){
        var value = this.getElementsToSave();
        var count = value.length;
        if (this.countHTMLElement)
            this.countHTMLElement.innerHTML = count;
        this.checkSelectAllCheckbox();
    };
    // LOAD
    this.load = function(){
        var savedElements = this.getSavedElements();
        if (this.onLoadCallback)
            this.onLoadCallback(savedElements);
        var formElements = this.form.elements;
        for (var i = 0; i < formElements.length; i++) {
            var formElement = formElements[i];
            if (formElement.type == "checkbox" && this.selectAllCheckbox != formElement) {
                var element = formElement.value.replace(/^\s+|\s+$/g, "").toLowerCase();
                for (var k = 0; k < savedElements.length; k++) {
                    if (savedElements[k] == element) {
                        formElement.checked = true;
                    }
                }
            }
        }
        this.checkSelectAllCheckbox();
        this.save(1);
    };
    // CHECK COUNTER
    this.checkSelectAllCheckbox = function(){
        if (this.selectAllCheckbox) {
            var elements = this.form.elements;
            var checked = true;
            for (var i = 0; i < elements.length; i++) {
                if (elements[i].type == 'checkbox' && !elements[i].checked && elements[i] != this.selectAllCheckbox) {
                    checked = false;
                    break;
                }
            }
            this.selectAllCheckbox.checked = checked;
        }
    }
    // GET SAVED ELEMENTS
    this.getSavedElements = function(){
        var elements = this.openerSaveInput && this.isJustOpen() ? saveInput.value + ',' + openerSaveInput.value : saveInput.value;
        return this.uniq(elements.split(','));
    };
    // GET SAVED ELEMENTS2
    this.getSavedElements2 = function(){
        var elements = this.openerSaveInput2 && this.isJustOpen() ? saveInput2.value + ',' + openerSaveInput2.value : saveInput2.value;
        return this.uniq(elements.split(','), 1);
    };
    // GET ELEMENTS TO SAVE
    this.getElementsToSave = function(){
        var formElements = this.form.elements;
        var savedElements = this.getSavedElements();
        for (var i = 0; i < formElements.length; i++) {
            var formElement = formElements[i];
            if (formElement.type == "checkbox" && this.selectAllCheckbox != formElement) {
                if (formElement.checked) {
                    savedElements[savedElements.length] = formElement.value;
                }
                else {
                    var element = formElement.value.replace(/^\s+|\s+$/g, "").toLowerCase();
                    for (var k = 0; k < savedElements.length; k++) {
                        if (savedElements[k] == element)
                            savedElements[k] = '';
                    }
                }
            }
        }
        return this.uniq(savedElements);
    };
    // GET ELEMENTS TO SAVE2
    this.getElementsToSave2 = function(){
        var formElements = this.form.elements;
        var savedElements = this.getSavedElements2();
        for (var i = 0; i < formElements.length; i++) {
            var formElement = formElements[i];
            if (formElement.type == "checkbox" && this.selectAllCheckbox != formElement) {
                if (formElement.checked) {
                    savedElements[savedElements.length] = this.input2Callback(formElement.value);
                }
                else {
                    var element = this.input2Callback(formElement.value);
                    for (var k = 0; k < savedElements.length; k++) {
                        if (savedElements[k] == element)
                            savedElements[k] = '';
                    }
                }
            }
        }
        return this.uniq(savedElements, 1);
    };
    // IS JUST OPEN
    this.isJustOpen = function(){
        if (navigator.userAgent.indexOf("Firefox") != -1) {
            return history.length == 1 ? 1 : 0;
        }
        else {
            return history.length == 0 ? 1 : 0;
        }
    }
    // UNIQ
    this.uniq = function(arr, dontModify){
        var retArr = new Array();
        if (arr.length) {
            for (var i = 0; i < arr.length; i++) {
                var element = arr[i].replace(/^\s+|\s+$/g, "");
                if (!dontModify)
                    element = element.toLowerCase();
                if (!element || element == '')
                    continue;
                var elementNotExists = true;
                for (var k = 0; k < retArr.length; k++) {
                    if (retArr[k] == element)
                        elementNotExists = false;
                }
                if (elementNotExists)
                    retArr[retArr.length] = element;
            }
        }
        return retArr;
    };
    // ERROR
    this.error = function(msg){
        throw ('Error in agent_SavedListing: ' + msg);
    };
    // CONSTRUCTOR
    if (listing)
        this.error('constructor'); // Silly Singleton
    if (params.form && params.saveInput && params.pageInput) {
        this.form = params.form;
        this.saveInput = params.saveInput;
        this.pageInput = params.pageInput;
    }
    else {
        this.error('constructor');
    }
    this.saveInput2 = params.saveInput2 ? params.saveInput2 : null;
    this.countHTMLElement = params.countHTMLElement ? params.countHTMLElement : null;
    this.openerSaveInput = params.openerSaveInput ? params.openerSaveInput : null;
    this.openerSaveInput2 = params.openerSaveInput2 ? params.openerSaveInput2 : null;
    this.openerCountHTMLElement = params.openerCountHTMLElement ? params.openerCountHTMLElement : null;
    this.onLoadCallback = params.onLoad ? params.onLoad : null;
    this.onSubmitCallback = params.onSubmit ? params.onSubmit : null;
    this.onPageChangeCallback = params.onPageChange ? params.onPageChange : null;
    this.input2Callback = params.input2Callback ? params.input2Callback : null;
    if (this.openerSaveInput2 && !this.saveInput2)
        this.error('constructor');
    if (this.saveInput2 && !this.input2Callback)
        this.error('constructor');
    if (params.selectAllCheckbox) {
        this.selectAllCheckbox = params.selectAllCheckbox;
        this.selectAllCheckbox.onclick = function(){
            if (this.checked) {
                $('save').value = $('allemails').value
                var elements = this.form.elements;
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].type == 'checkbox' && this != elements[i]) {
                        elements[i].checked = true;
                    }
                }
            }
            else {
                $('save').value = ''
                var elements = this.form.elements;
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].type == 'checkbox' && this != elements[i]) {
                        elements[i].checked = false;
                    }
                }
            }
            listing.select();
        };
    }
    else {
        this.selectAllCheckbox = null;
    }
    if (params.finishInput) {
        this.finishInput = params.finishInput;
        this.finishInput.value = 0;
    }
    else {
        this.finishInput = null;
    }

    this.load();
    return this;
}

// Listing emails with save end

/*
 * {Career}
 */
/**
 * Geo ajax call for career
 * @param {String} geo_id
 */
function career_ajax_geo_call(geo_id){
    more_disabled();
    ajax_call('perl_get_geo', geo_id, career_FillGeo);
}

/**
 * Edit ajax call for career
 * @param {String} cid
 */
function career_ajax_edit_call(cid){
    more_disabled();
    ajax_call('perl_fetch_career', cid, career_FillEdit);
}

/**
 * Reset career form
 * @param {String} level
 */
function career_form_empty(level){
    var suff = '';
    var _editing = editing;
    if (_editing == 1)
        suff = '_edit';
    if (level < 1) {
        $('position_' + mode + suff).value = '';
    }
    if (level < 2) {
        $('region_id_' + mode + suff).options.length = 1;
        $('region_id_' + mode + suff).options[0].value = '';
        $('region_id_' + mode + suff).options[0].text = 'Выбрать';
        $('region_id_' + mode + suff).selectedIndex = 0;
        $('region_id_' + mode + suff).disabled = 1;
        //list_enter = $('enteryear_company');
        //list_leave = $('leaveyear_company');
        //list_enter.selectedIndex = list_enter.options.length - 1;
        //list_leave.selectedIndex = list_leave.options.length - 1;
    }
    if (level < 3) {
        $('city_id_' + mode + suff).options.length = 1;
        $('city_id_' + mode + suff).options[0].value = '';
        $('city_id_' + mode + suff).options[0].text = 'Выбрать';
        $('city_id_' + mode + suff).selectedIndex = 0;
        $('city_id_' + mode + suff).disabled = 1;
    }
}

/**
 * Fill geo in career
 * @param {Array} names
 * @param {Array} ids
 * @param {String} type
 * @param {String} level
 * @param {String} special
 */
function career_FillGeo(names, ids, type, level, special){
    var no_list = 0;
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    //alert(names.length+' '+type+' '+level);
    var list;
    if (type == 1) {
        list = $('country_id_' + mode + suff);
        career_form_empty(1);
    }
    else
        if (type == 2) {
            career_form_empty(2);
            list = $('region_id_' + mode + suff);
            $('region_id_' + mode + suff).enable();

            $('city_id_' + mode + suff).disable();
            $('city_id_' + mode + suff).options.length = 0;
            $('city_id_' + mode + suff).options[0] = new Option('Выбрать', '');
            if (suff != '') {
                $('ab_compose_2').disable();
            }
            else {
                $('ab_compose_1').disable();
            }
        //          $('tr_search_comp'+suff).style.display='none';

        }
        else
            if (type == 3) {
                if (level != 3) { // Not a Russia, disabling region menu
                    $('region_id_' + mode + suff).options.length = 0;
                    $('region_id_' + mode + suff).options[0] = new Option('Выбрать', '');
                    $('region_id_' + mode + suff).disable();
                }
                career_form_empty(3);
                $('city_id_' + mode + suff).enable();
                list = $('city_id_' + mode + suff);
            /* if (!editing){
         $('ab_compose_1').disabled=0;
         //          $('tr_search_comp').style.display='block';} */
            }
            else {
                no_list = 1;
                $('city_id_' + mode + suff).options.length = 0;
                $('city_id_' + mode + suff).options[0] = new Option('Другое', 'other');
                $('city_id_' + mode + suff).enable();
                $('city_id_' + mode + suff + '_other').show()
                if (suff != '') {
                    $('ab_compose_2').enable();
                }
                else {
                    $('ab_compose_1').enable();
                }
            //          $('tr_search_comp'+suff).style.display='none';
            }
    less_disabled();
    if (no_list == 0) {
        var nl = 0;
        if (names != undefined)
            nl = names.length;
        list.options.length = 0;
        var addon = 0;
        //if (editing != 1) {
        list.options[0] = new Option('Выбрать', '');
        addon = 1;
        //}
        for (var i = 0; i < nl; i++) {
            list.options[i + addon] = new Option(names[i], ids[i]);
            if (special > 0) {
                list.options[i + addon].style.fontWeight = "bold";
                special--;
            }
        }
        if (type == 3) {
            list.options[list.options.length] = new Option('Другое', 'other');

        }
        if (type == 1 || (type == 3 && is_capital == 1))//(set default country -> Russia) OR (set default city -> capital)
        {
            list.selectedIndex = 1;
            list.onchange();

        }
        else {
            if (suff != '') {
                $('ab_compose_2').disable();
            }
            else {
                $('ab_compose_1').disable();
            }
            //          $('tr_search_comp'+suff).style.display='none';
        }
        if (need_switch_star) {
            career_switchStarOfFieldCallback();
        }
        /* if (!editing){
         $('ab_compose_1').disabled=0;
         //          $('tr_search_comp').style.display='block';} */
    }
}

/**
 * @param {Object} sel
 * @param {String} block_on
 */
function career_onblock(sel, block_on){
    if (sel.value == 'other') {
        Element.hide(block_on);
        onother(sel.id);
        if (editing) {
            suff = '_edit'
        }
        else {
            suff = ''
        }
        if (suff != '') {
            $('ab_compose_2').enable();
        }
        else {
            $('ab_compose_1').enable();
        }
        //          $('tr_search_comp'+suff).style.display='none';

    }
    else {
        Element.hide(block_on);
        if (sel.value != '') {
            if (editing) {
                suff = '_edit'
            }
            else {
                suff = ''
            }
            if (suff != '') {
                $('ab_compose_2').enable();
            }
            else {
                $('ab_compose_1').enable();
            }
            //              $('tr_search_comp'+suff).style.display='block';

        }
        else {
            if (editing) {
                suff = '_edit'
            }
            else {
                suff = ''
            }
            if (suff != '') {
                $('ab_compose_2').disable();
            }
            else {
                $('ab_compose_1').disable();
            }
            //          $('tr_search_comp'+suff).style.display='none';
        }
    }
}

/**
 * Fill career list
 * @param {String} oid
 * @param {Array} names
 * @param {Array} ids
 * @param {String} sid
 */
function career_FillList(oid, names, ids, sid){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    //alert("career_FillList |"+oid+mode+suff+"|");
    var list = $(oid + mode + suff);
    if (list == undefined || list == null)
        return;
    if (names == '0' || names == 0) {
        list.disable();
        return;
    }
    //alert("career_FillList running "+names);
    list.enable();
    var nl = 0;
    if (names != undefined)
        nl = names.length;
    list.options.length = 0;
    var addon = 0;
    if (editing != 1) {
        list.options[0] = new Option('Выбрать', '');
        list.selectedIndex = 0;
        addon = 1;
    }
    if (editing == 1 && (oid == 'department_id_' || oid == 'kafedra_id_')) {
        list.options[0] = new Option('Не выбрано', '');
        list.selectedIndex = 0;
        addon = 1;
    }
    for (var i = 0; i < nl; i++) {
        list.options[i + addon] = new Option(names[i], ids[i]);
        if (ids[i] == sid)
            list.options[i + addon].selected = 1;
    }
    if (oid == 'city_id_' || oid == 'institute_id_' || oid == 'department_id_' || oid == 'kafedra_id_') {
        var le = list.options.length;
        list.options[le] = new Option('Другое', 'other');
        if (le == 0) {
            var elem = $(oid + mode + suff + '_other');
            if (elem != undefined)
                elem.show();
        }
    }
}

//function career_CheckList(oid, sid, sh){
//    var suff = "";
//    var _editing = editing;
//    var lift = (sh == 0) ? 0 : 1;
//    if (_editing == 1)
//        suff = "_edit";
//    var list = $(oid + mode + suff);
//    if (list == undefined || list == null)
//        return;
//    list.disabled = 0;
//    for (var i = 0; i < list.options.length - lift; i++) {
//        if (list.options[i].value == sid)
//            list.options[i].selected = 1;
//    }
//}

/**
 * Fill career field
 * @param {String} oid
 * @param {String} valu
 */
function career_FillField(oid, valu){
    var suff = "";
    var _editing = editing;
    if (editing == 1)
        suff = "_edit";
    var field = $(oid + mode + suff);
    if (field == undefined || field == null)
        return;
    field.value = valu;
}

/**
 * Fill career select
 * @param {String} oid
 * @param {String} valu
 */
function career_FillSelect(oid, valu){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var field = $(oid + mode + suff);
    if (field == undefined || field == null)
        return;
    for (var i = 0; i < field.options.length; i++) {
        if (field.options[i].value == valu) {
            field.selectedIndex = i;
            return;
        }
    }
}

/**
 * Fill career edit
 * @param {String} careerId
 * @param {Array} cNames
 * @param {Array} cIds
 * @param {String} cId
 * @param {Array} rNames
 * @param {Array} rIds
 * @param {String} rId
 * @param {Array} tNames
 * @param {Array} tIds
 * @param {String} tId
 * @param {String} companyName
 * @param {String} position
 * @param {String} enterYear
 * @param {String} enterMonth
 * @param {String} leaveYear
 * @param {String} leaveMonth
 * @param {String} stillHere
 */
function career_FillEdit(careerId, cNames, cIds, cId, rNames, rIds, rId, tNames, tIds, tId, companyName, position, enterYear, enterMonth, leaveYear, leaveMonth, stillHere){
    //ajax perl_fetch_career callback, filling edit form
    //receiving all data, checked.
    career_FillSelect('enteryear_', enterYear);
    career_FillSelect('leaveyear_', leaveYear);
    career_FillSelect('entermonth_', enterMonth);
    career_FillSelect('leavemonth_', leaveMonth);

    career_FillField('position_', position, 0);
    //  career_FillField('name_',companyName,0);
    if (editing == 1) {
        $('ab_compose_2').value = companyName;
    }
    else {
        $('ab_compose_1').value = companyName;
    }
    career_FillField('cid_', careerId, 0);

    career_FillList('country_id_', cNames, cIds, cId);
    career_FillList('region_id_', rNames, rIds, rId);
    if (need_switch_star) {
        career_switchStarOfFieldCallback();
    }
    career_FillList('city_id_', tNames, tIds, tId);
    if (stillHere == 1) {
        //      $('leaveyear_company_edit').options.length=1;
        //      $('leaveyear_company_edit').options[0].value='';
        $('leaveyear_company_edit').disable();
        //      $('leavemonth_company_edit').options.length=1;
        //      $('leavemonth_company_edit').options[0].value='';
        $('leavemonth_company_edit').disable();
        $('stillhere_company_edit').checked = 1;
        switchStarByDisable('leaveyear_company_edit', 'leaveyear_star_company_edit');
    }
    less_disabled();
}

/**
 *
 * @param {String} fieldName
 * @param {String} starName
 */
function career_switchStarOfField(fieldName, starName){
    star_field = fieldName;
    star_name = starName;
    need_switch_star = true;
}

/**
 *
 */
function career_switchStarOfFieldCallback(){
    if ($(star_field).disabled == 0) {
        $(star_name).className = 'red';
    }
    else {
        $(star_name).className = 'white';
    }
    need_switch_star = false;
}

/**
 *
 * @param {String} formName
 * @param {String} fieldName
 * @param {String} errorText
 * @return {String}
 */
function career_CheckFieldByNull(formName, fieldName, errorText){
    if (formName.elements[fieldName].value == null || formName.elements[fieldName].value == undefined || formName.elements[fieldName].value == "") {
        return errorText;
    }
    else {
        return '';
    }
}

/**
 *
 * @param {String} formName
 * @return {Boolean}
 */
function career_CheckFormByNull(formName){
    more_disabled();
    var errors = "";
    var suff = "";
    if (editing == 1)
        suff = "_edit";

    errors += career_CheckFieldByNull(formName, 'country_id_' + mode + suff, "Поле СТРАНА не заполнено\n");
    if (formName.elements['region_id_' + mode + suff].disabled != 1) {
        errors += career_CheckFieldByNull(formName, 'region_id_' + mode + suff, "Поле РЕГИОН не заполнено\n");
    }
    errors += career_CheckFieldByNull(formName, 'city_id_' + mode + suff, "Поле ГОРОД не заполнено\n");
    if (formName.elements['city_id_' + mode + suff].value == 'other') {
        errors += career_CheckFieldByNull(formName, 'city_name', "Поле ДРУГОЙ ГОРОД не заполнено\n");
    }

    if (editing == 1) {
        errors += career_CheckFieldByNull(formName, 'ab_compose_2', "Поле КОМПАНИЯ не заполнено\n");
    }
    else {
        errors += career_CheckFieldByNull(formName, 'ab_compose_1', "Поле КОМПАНИЯ не заполнено\n");
    }

    errors += career_CheckFieldByNull(formName, 'enteryear_' + mode + suff, "Поле НАЧАЛО РАБОТЫ - ГОД не заполнено\n");
    errors += career_CheckFieldByNull(formName, 'entermonth_' + mode + suff, "Поле НАЧАЛО РАБОТЫ - МЕСЯЦ не заполнено\n");

    if (formName.elements['leaveyear_' + mode + suff].disabled != 1) {
        errors += career_CheckFieldByNull(formName, 'leaveyear_' + mode + suff, "Поле ОКОНЧАНИЕ РАБОТЫ - ГОД не заполнено\n");
    }
    if (formName.elements['leavemonth_' + mode + suff].disabled != 1) {
        errors += career_CheckFieldByNull(formName, 'leavemonth_' + mode + suff, "Поле ОКОНЧАНИЕ РАБОТЫ - МЕСЯЦ не заполнено\n");
    }

    /*
     if(formName.elements['startdate'])
     {
     buff = career_CheckFieldByNull(formName,'startdate',"Поле Я ПОШЁЛ В ПЕРВЫЙ КЛАСС не заполнено\n");
     if (buff != '')
     {
     errors +=buff;
     } else {
     if(isNaN(formName.elements['startdate'].value) == true){
     errors += "В Поле Я ПОШЁЛ В ПЕРВЫЙ КЛАСС можно вводить только цифры\n";
     }
     if(formName.elements['startdate'].value.indexOf('+') == true || formName.elements['startdate'].value.indexOf('-') == true){
     errors += "В Поле Я ПОШЁЛ В ПЕРВЫЙ КЛАСС можно вводить только цифры положительные цифры\n";
     }
     }
     }
     */
    /*
     errors +=career_CheckFieldByNull(formName,'enterdate',"Поле " + enterdate_field_name + " не заполнено\n");
     errors +=career_CheckFieldByNull(formName,'leavedate',"Поле ОКОНЧАНИЕ ОБУЧЕНИЯ не заполнено\n");
     */
    /*
     if(formName.elements['enterdate']!='' && isNaN(formName.elements['enterdate'].value)==true)
     {
     errors += "В Поле " + enterdate_field_name + " можно вводить только цифры\n";
     }
     if(formName.elements['leavedate']!='' && isNaN(formName.elements['leavedate'].value)==true)
     {
     errors += "В Поле ОКОНЧАНИЕ ОБУЧЕНИЯ можно вводить только цифры\n";
     }
     */
    if (errors != null && errors != "") {
        alert(errors);
        less_disabled();
        return false;
    }
}

/**
 *
 * @param {String} field_id
 * @param {String} star_id
 */
function switchStarByDisable(field_id, star_id){
    if ($(field_id).disabled == 0) {
        $(star_id).className = 'red';
    }
    else {
        $(star_id).className = 'white';
    }
}

/**
 *
 */
function edit_company_to_orig(){
    if (editing_company == '')
        return;
    html = $(editing_company).innerHTML;
    if (html == undefined || html == '')
        return;
    $(editing_company).hide();
    $(editing_company).update('');
    $('orig_div_for_company').update(html);
    editing_company = '';
    editing = 0;
}

/**
 * Edit company by ID
 * @param {String} cid
 * @return {Boolean}
 */
function edit_company_by_id(cid){
    if (editing == 1) {
        if (editing_company == 'div_for_company_' + cid)
            return false;
        edit_company_to_orig();
    }
    mode = 'company';
    editing = 1;
    src_div = 'orig_div_for_company';
    if (editing_company != '') {
        $(editing_company).hide();
        src_div = editing_company;
    }
    editing_company = 'div_for_company_' + cid;
    if (src_div == editing_company)
        return;
    html = $(src_div).innerHTML;
    if (html == undefined || html == '')
        return;
    $(src_div).update('');
    $(editing_company).update(html);
    career_form_empty(0);
    $(editing_company).show();
    career_switchStarOfField('region_id_company_edit', 'company_edit_star_reg');
    if ($('stillhere_company_edit').check == 1) {
        disUndisField('leaveyear_company_edit');
        disUndisField('leavemonth_company_edit');
    }
    var olist = ['country_id_company_edit', 'region_id_company_edit', 'city_id_company_edit'];
    for (var i = 0; i < olist.length; i++) {
        $(olist[i]).options[0].text = 'Загрузка...';
    }

    divs = $$('div');
    for (var i in divs) {
        if (typeof(divs[i]) == 'object' &&
        divs[i].className == 'dynamic_ab_placeholder') {
            divs[i].parentNode.removeChild(divs[i]);
        }
    }

    dynamic_ab.ab_compose_2 = undefined;
    dynamic_ab.ab_compose_2_items = new Array();
    dynamic_ab.ab_compose_1 = undefined;
    dynamic_ab.ab_compose_1_items = new Array();
    if ($('ab_compose_2'))
        $('ab_compose_2').value = '';
    if ($('ab_compose_1'))
        $('ab_compose_1').value = '';

    career_ajax_edit_call(cid);
}

/**
 * Add company
 */
function add_company(){
    mode = 'company';
    editing = 0;
    if ($('company_table').visible() && show_career != 1) {
        $('company_table').hide();
    }
    else {
        $('company_table').show();
        $("country_id_company").options.length = 1;
        $("country_id_company").options[0].text = 'Загрузка...';
        career_ajax_geo_call(1);
    }
    switchStarByDisable('leaveyear_' + mode, 'leaveyear_star_' + mode);
}

/**
 * Fill company
 * @param {String} id
 * @param {Object} obj
 * @param {Array} names
 * @param {Array} ids
 */
function FillCompany(id, obj, names, ids){
    //        list=$('company_name_'+id);

    //  if (!names.length) {
    //      list.disabled=1;
    //      list.options.length=1;
    //      list.options[0].value='';
    //      list.options[0].text='';
    //  } else {
    //      list.disabled=0;
    //      list.options.length=names.length+1;
    //      list.options[0].value='';
    //      for (i=0;i<names.length;i++) {
    //          list.options[i+1].text=names[i];
    //          list.options[i+1].value=ids[i];
    //      }



    if (typeof(dynamic_ab['ab_compose_' + id]) == 'object') {
        var div = dynamic_ab['ab_compose_' + id].ab.parentNode;
        div.parentNode.removeChild(div);
        dynamic_ab['ab_compose_' + id] = undefined;
    }
    dynamic_ab['ab_compose_' + id + '_items'] = names;

    //      // FillAB('company', id);
    //  }

    // ab_keyup(LoadCompaniesObject, 1, LoadCompaniesEvent);

    CompaniesLoaded[id - 1] = true;
    RequestSent[id - 1] = false;

    var ab = ab_get(obj);
    ab.draw();
    if (ab.found) {
        ab.show();
        ab.movetop();
    }

    ab_keyup(obj, LoadCompaniesEvent[id - 1]);

}

/**
 * Load companies
 * @param {Object} obj
 * @param {String} id
 * @param {String} e
 */
function LoadCompanies(obj, id, e){
    if (editing) {
        suff = '_edit';
    }
    else {
        suff = '';
    }
    if (obj.value.length < 3) {
        if (CompaniesLoaded[id - 1]) {
            // alert('no companies');
            CompaniesLoaded[id - 1] = false;
            var ab = ab_get(obj, id);
            ab.hide();
        }
    }
    else {
        if (!RequestSent[id - 1]) {
            if (CompaniesLoaded[id - 1])
                return ab_keyup(obj, e);
            if (LoadedCompaniesPrefix[id - 1].length > 0 && LoadedCompaniesPrefix[id - 1] == obj.value.length) {
                CompaniesLoaded[id - 1] = true;
                return ab_keyup(obj, e);
            }
            else {
                //alert('loading: '+obj.value);
                $('ab_compose_' + id).disable = '1';
                RequestSent[id - 1] = true;
                LoadCompaniesObject[id - 1] = obj;
                LoadCompaniesEvent[id - 1] = e;
                LoadedCompaniesPrefix[id - 1] = obj.value;
                ajax_call('perl_get_company', $F('city_id_company' + suff), $F('ab_compose_' + id), function(names, ids){
                    FillCompany(id, obj, names, ids)
                });
            }
        }
    }
}

//function career_show_search_input(type, id){
//    $('ab_compose_' + id).value = '';
//    $(type + '_search_' + id).style.display = 'block';
//    $('choose_other_' + id).style.display = 'none';
//    RequestSent[id - 1] = false;
//    CompaniesLoaded[id - 1] = false;
//    LoadedCompaniesPrefix[id - 1] = '';
//
//    return false;
//}

//function hide_search_input(type, id){
//    $('ab_compose_' + id).value = '';
//    $(type + '_search_' + id).style.display = 'none';
//    $('choose_other_' + id).style.display = 'block';
//}

/*
 * {change-photo.tmpl}
 */
/**
 * Change photo AJAX call
 * @return {Boolean}
 */
function change_photo_ajax_call(){
    var args = change_photo_ajax_call.arguments;
    var func_name = args[0];
    var func_args = [];
    var callback;
    var callback_object;
    func_args[0] = PhotoEmail; //hack to get photouser in ajax calls
    for (var i = 1; i < args.length; i++) {
        if ((typeof(args[i]) != "undefined") && (args[i].constructor == Function)) {
            callback = args[i];
            if (args.length > i + 1) {
                callback_object = args[i + 1];
            }
            break;
        }
        else {
            func_args[func_args.length] = args[i];
        }
    }
    var pos = ajax_requests.length;
    var request = new AjaxRequest("POST", 'http://' + MyMailHost + '/cgi-bin/photo/ajax', func_name, func_args, callback, callback_object);
    ajax_requests[pos] = request;
    if (!request.send()) {
        ajax_requests.splice(ajax_requests.length - 1, 1);
        return false;
    }
    else {
        return true;
    }
}

/**
 * Set photo as main
 * @param {String} oldMainAvatarId
 * @param {String} oldMainAvatarCount
 */
function photo_make_main(oldMainAvatarId, oldMainAvatarCount){
    if ($('change_main_' + MainAvatarId))
        $('change_main_' + MainAvatarId).update("<a href=\"#\" onclick=\"change_photo_ajax_call('perl_set_avatar'," + MainAvatarId + "," + MainAvatarCount + ",setAvatarCallback); return false;\">Сделать основным</a>");
    MainAvatarId = oldMainAvatarId;
    if ($('bordForVertId_' + MainAvatarCount))
        $('bordForVertId_' + MainAvatarCount).className = 'avatar120_photo';
    MainAvatarCount = oldMainAvatarCount;
}

/**
 * Set avatar callback function
 * @param {String} isSuccess
 * @param {String} newavatarId
 * @param {String} Count
 * @param {String} errorText
 */
function setAvatarCallback(isSuccess, newavatarId, Count, errorText){
    if (!isSuccess) {
        alert('Ошибка : ' + errorText);
    }
    else {
        //alert(Count);
        $('change_main_' + newavatarId).update('<span>Основное фото</span>');
        $('bordForVertId_' + Count).className = 'avatar120_photo_best';
        $('main_avatar').style.backgroundImage = 'url(http://avt.foto.mail.ru' + ActiveDir + '_avatar180?' + newavatarId + ')';
        photo_make_main(newavatarId, Count);
    }
}

/*
 * {classmates.tmpl}
 */
/**
 * Change study type
 * @param {Object} sel
 */
function classmates_changeStudyType(sel){
    var typeArray = ["Школа", "Колледж или ПТУ", "ВУЗ"];
    var cross = ["0", "0", "0", "1", "2"];
    val = cross[sel.value];
    classmates_handleGeoLink();
    $('institute_other').hide();
    $("studyTypeId").update(typeArray[val]);
    $("univDataId").style.display = (val != 0) ? "" : "none";
    $("univYearId").style.display = (val != 0) ? "" : "none";
    $("schoolDataId").style.display = (val == 0) ? "" : "none";
    $("fakultetId").style.display = (val == 0) ? "none" : "";
    $("kafedraId").style.display = (val == 2) ? "" : "none";
}

/**
 * Reset classmates form
 * @param {String} level
 */
function classmates_form_empty(level){
    if (level < 2) {
        $('region_id').disable();
        $('region_id').options.length = 1;
        $('region_id').options[0].value = '';
        $('region_id').options[0].text = '';
    }
    if (level < 3) {
        $('city_id').disable();
        $('city_id').options.length = 1;
        $('city_id').options[0].value = '';
        $('city_id').options[0].text = '';
    }
    if (level < 4) {
        $('institute_id').disable();
        $('institute_id').options.length = 1;
        $('institute_id').options[0].value = '';
        $('institute_id').options[0].text = '';
    }
    if (level < 5 && $('type').value != 1) {
        $('faculty_id').disable();
        $('faculty_id').options.length = 1;
        $('faculty_id').options[0].value = '';
        $('faculty_id').options[0].text = '';
    }
    if (level < 6 && $('type').value == 4) {
        $('subfaculty_id').disable();
        $('subfaculty_id').options.length = 1;
        $('subfaculty_id').options[0].value = '';
        $('subfaculty_id').options[0].text = '';
    }
}

/**
 *
 */
function classmates_handleGeoLink(){
    switch ($('type').value) {
        case '1':
            _show = 'school';
            break;
        case '3':
            _show = 'ssuz';
            break;
        case '4':
            _show = 'institute';
            break;
        default:
            _show = 'school';
    }
    geo_id = $F('city_id') ? $F('city_id') : ($F('country_id') ? $F('country_id') : '');
    $('geo_azer_href').href = '/my/history?show_' + _show + '=1&add_geo_id=' + geo_id;
}

/**
 * Fill classmates geo
 * @param {Array} names
 * @param {Array} ids
 * @param {String} type
 * @param {String} level
 * @param {String} special
 */
function classmates_FillGeo(names, ids, type, level, special){
    $('institute_other').hide();
    if (type == 2) {
        list = $('region_id');
        //$('region_id').disabled=0;
        $('city_id').disable();
        $('city_id').options.length = 1;
        $('city_id').options[0].value = '';
        $('city_id').options[0].text = 'Недоступно';
    }
    else {
        //if (type==3) {
        if (level != 3) { // Not a Russia, disabling region menu
            $('region_id').options.length = 1;
            $('region_id').options[0].value = '';
            $('region_id').options[0].text = 'Недоступно';
            $('region_id').disable();
        }
        //$('city_id').disabled=0;
        list = $('city_id');
    }
    if (names.length) {
        list.enable();
    }
    else {
        classmates_handleGeoLink();
        $('othercity').show();
        return;
    }
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Выбрать';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        if (special > 0) {
            list.options[i + 1].style.fontWeight = "bold";
            special--;
        }
        list.options[i + 1].value = ids[i];
    }
    if (type == 1 || (type == 3 && is_capital == 1))//(set default country -> Russia) OR (set default city -> capital)
    {
        list.selectedIndex = 1;
        list.onchange();
    }
    if (need_switch_star) {
        classmates_switchStarOfFieldCallback();
    }
}

/**
 * Fill classmates studies
 * @param {Array} names
 * @param {Array} ids
 */
function classmates_FillStudies(names, ids){
    list = $('institute_id');
    if (!names.length) {
        list.disable();
        list.options.length = 1;
        list.options[0].value = '';
        list.options[0].text = '';
        switch ($F('type')) {
            case '1':
                _show = 'school';
                break;
            case '3':
                _show = 'ssuz';
                break;
            case '4':
                _show = 'institute';
                break;
            default:
                _show = 'school';
        }
        geo_id = $F('city_id') ? $F('city_id') : '';
        $('inst_azer_href').href = '/my/history?show_' + _show + '=1&add_geo_id=' + geo_id;
        $('institute_other').show();
        return;
    }
    list.enable();
    $('institute_other').hide();
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Выбрать';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        list.options[i + 1].value = ids[i];
    }
}

/**
 * Fill classmates departments
 * @param {Array} names
 * @param {Array} ids
 */
function classmates_FillDepartments(names, ids){
    list = $("faculty_id");
    if (!names.length) {
        list.disable();
        list.options.length = 1;
        list.options[0].value = '';
        list.options[0].text = '';
        return;
    }
    list.enable();
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Любой';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        list.options[i + 1].value = ids[i];
    }
}

/**
 * Fill classmates kafedras
 * @param {Array} names
 * @param {Array} ids
 */
function classmates_FillKafedra(names, ids){
    list = $("subfaculty_id");
    if (!names.length) {
        list.disable();
        list.options.length = 1;
        list.options[0].value = '';
        list.options[0].text = '';
        return;
    }
    list.enable();
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Любая';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        list.options[i + 1].value = ids[i];
    }
}

/**
 *
 * @param {String} formName
 * @param {String} fieldName
 * @param {String} errorText
 * @return {String}
 */
function classmates_CheckFieldByNull(formName, fieldName, errorText){
    if (formName.elements[fieldName].value == null || formName.elements[fieldName].value == undefined || formName.elements[fieldName].value == "") {
        return errorText;
    }
    else {
        return '';
    }
}

//function classmates_set_mode(v){
//    v = parseInt(v);
//    switch (v) {
//        case 1:
//            mode = 'school';
//            break;
//        case 3:
//            mode = 'ssuz';
//            break;
//        case 4:
//            mode = 'vuz';
//            break;
//    }
//}

/**
 *
 * @param {String} formName
 * @return {Boolean}
 */
function classmates_CheckFormByNull(formName){
    var errors = "";
    var institute_field_name = "ШКОЛА";
    var start_year = "ПОШЁЛ В ПЕРВЫЙ КЛАСС";

    if (mode == 'ssuz') {
        institute_field_name = "КОЛЛЕДЖ ИЛИ ПТУ";
        start_year = "НАЧАЛ УЧИТЬСЯ В";
    }
    if (mode == 'vuz') {
        institute_field_name = "ВУЗ";
        start_year = "НАЧАЛ УЧИТЬСЯ В";
    }

    errors += classmates_CheckFieldByNull(formName, 'country_id', "Поле СТРАНА не заполнено\n");
    if (formName.elements['region_id'].disabled != 1) {
        errors += classmates_CheckFieldByNull(formName, 'region_id', "Поле РЕГИОН не заполнено\n");
    }
    errors += classmates_CheckFieldByNull(formName, 'city_id', "Поле ГОРОД не заполнено\n");
    errors += classmates_CheckFieldByNull(formName, 'institute_id', "Поле " + institute_field_name + " не заполнено\n");

    if (formName.elements['start_year'] != '' && isNaN(formName.elements['start_year'].value) == true) {
        errors += "В Поле " + start_year + " можно вводить только цифры\n";
    }
    if (formName.elements['start_course'] != '' && isNaN(formName.elements['start_course'].value) == true) {
        errors += "В Поле КУРС можно вводить только цифры\n";
    }

    if (errors != null && errors != "") {
        alert(errors);
        return false;
    }
    else {
        $('but_find').disable();
    }
}

/**
 *
 * @param {String} fieldName
 * @param {String} starName
 */
function classmates_switchStarOfField(fieldName, starName){
    star_field = fieldName;
    star_name = starName;
    need_switch_star = true;
}

/**
 *
 */
function classmates_switchStarOfFieldCallback(){
    if (!$(star_field).visible()) {
        $(star_name).className = 'red starr';
    }
    else {
        $(star_name).className = 'white';
    }
    need_switch_star = false;
}

/**
 * Check studied here
 */
function classmates_checkStudiedHere(){
    var show = 1;
    if (!$F('country_id'))
        show = 0;
    if ($F('country_id') == 24 && !$F('region_id'))
        show = 0;
    if (!$F('city_id'))
        show = 0;
    if (!$F('institute_id'))
        show = 0;
    if (!$F('start_year_id'))
        show = 0;
/*  if ($F('type') != 1) {
        if (!$F('start_course_id'))
            show = 0;
    }
*/
	if(document.getElementById('me_studied_here_tab')) {
    	$('me_studied_here_tab').style.display = show ? 'block' : 'none';
    	$('me_studied_here_tab').disabled = 1 - show;
	}
}

/*
 * {additem.tmpl}
 */
/**
 * GENERATE ID
 * @param {String} oid
 * @return {String}
 */
function items_gid(oid){
    if (oid) {
        var add = items_gadd(oid);
        if (editing) {
            return oid + "_edit" + add;
        }
        else {
            return oid + "_ins" + add;
        }
    }
    else {
        return editing ? 'edit' : 'ins';
    }
}

/**
 * Generate postfix for items_gid
 * @see items_gid
 * @param {String} oid
 * @return {String}
 */
function items_gadd(oid){
    if (oid) {
        if (oid.match(/^brend/)) {
            return '_b'
        }
        if (oid.match(/^model/)) {
            return '_m'
        }
        if (oid.match(/^modification/)) {
            return '_m2'
        }
    }
    return '';
}


/**
 * Disable submit
 */
function items_disable_submit(){
    $('BlockSubmit').getElementsBySelector('input').each(function(el){el.disable()});
    disableness = 1;
}

/**
 * Enable submit
 */
function items_enable_submit(){
    if (disableness == 1)
        $('BlockSubmit').getElementsBySelector('input').each(function(el){el.disable()});
    disableness = 0;
}

/**
 * FILL LIST
 * @param {String} oid
 * @param {Array} names
 * @param {Array} ids
 * @param {String} sid
 */
function items_FillList(oid, names, ids, sid){
    var list = $(items_gid(oid));
    if (!list)
        throw 'Error items_FillList object: ' + items_gid(oid) + ' not found';
    // Used only for Brend, Model, Modification
    list.disabled = false;
    var nl = names.length;
    list.options.length = 0;
    list.options[0] = new Option('Выбрать', '');
    if (nl != '0') {
        for (var i = 0; i < nl; i++) {
            var index = list.options.length;
            list.options[index] = new Option(names[i], ids[i]);
            if (ids[i] == sid)
                list.options[index].selected = true;
        }
    }
    var elem = $(items_gid(oid) + '_other');
    if (elem && elem.style)
        elem.show();
    list.options[list.options.length] = new Option('Другое', 'other_select');
    return;
}

/**
 * FORM EMPTY
 * @param {String} level
 */
function items_form_empty(level){
    if (level < 1) {
        var id = $('brend_name');
        //        $(items_gid('position')).value='';
        $('brend_name_other').hide();
    }
    if (level < 2) {
        var id = $('model_name');
        id.options.length = 1;
        id.options[0].value = '';
        id.options[0].text = 'Выбрать';
        id.selectedIndex = 0;
        id.disable();
        $('model_name_other').hide();
    }
    if (level < 3) {
        var id = $('modification_name');
        id.options.length = 1;
        id.options[0].value = '';
        id.options[0].text = 'Выбрать';
        id.selectedIndex = 0;
        id.disable();
        $('modification_name_other').hide();
    }
}

/* AJAX CALLS ========================================================================== */

/**
 * AJAX ITEM CALL
 * @param {String} parent_id
 * @param {String} type_name
 * @param {String} category_name
 */
function items_ajax_item_call(parent_id, type_name, category_name){
    items_disable_submit();
    ajax_call('perl_get_items_dictionary', parent_id, type_name, category_name, items_FillItemNames);
}

/**
 * AJAX ITEM SEARCH CALL
 * @param {String} parent_id
 * @param {String} type_name
 * @param {String} category_name
 * @param {String} search_pattern
 */
function items_ajax_item_search_call(parent_id, type_name, category_name, search_pattern){
    items_disable_submit();
    ajax_call('perl_get_items_dictionary', parent_id, type_name, category_name, search_pattern, FillAB);
}

/* FILLS =============================================================================== */

/**
 * FILL GEO
 * @param {Array} names
 * @param {Array} ids
 * @param {String} type
 */
function items_FillItemNames(names, ids, type){
    //alert('items_FillItemNames');
    var no_list = 0;
    var list = $(type + '_name');
    if (editing) {
        var td_a = type + '_star_edit';
    }
    else {
        var td_a = type + '_star_add';
    }
    if (type == 'brend') {
        items_form_empty(1);
        $('brend_name').enable();
        $('model_name').disable();
        $('modification_name').disable();
        $('model_name').options.length = 0;
        if (!editing)
            $('model_name').options[0] = new Option('Выбрать', '');
        $(td_a).update('<b class="red">*</b>');
    }
    else
        if (type == 'model') {
            items_form_empty(2);
            $('model_name').enable();
            $('modification_name').disable();
            $('modification_name').options.length = 0;
            if (!editing)
                $('modification_name').options[0] = new Option('Выбрать', '');
            $(td_a).update('<b class="red">*&nbsp;</b>');
        }
        else
            if (type == 'modification') {
                items_form_empty(3);
                $('modification_name').enable();
                $(td_a).update('<img src="http://img0.imgsmail.ru/0.gif" width="16" height="15" alt="" class="load">');
            }
    items_enable_submit();

    var nl = 0;
    list.options.length = 0;
    var addon = 0;
    list.options[0] = new Option('Выбрать', '');
    addon = 1;
    if (names != undefined) {
        nl = names.length;
        for (var i = 0; i < nl; i++) {
            list.options[i + addon] = new Option(names[i], ids[i]);
        }
    }
    else {
        if (type == 'brend') {
            $('brend_name_other').show();
            $('model_name_other').show();
            $('model_name').options[0] = new Option('Другое', 'other_select');
            $('model_name').enable();
            $('modification_name_other').show();
            $('modification_name').options[0] = new Option('Другое', 'other_select');
            $('modification_name').enable();
        }
        else
            if (type == 'model') {
                $('model_name_other').show();
                $('modification_name_other').show();
                $('modification_name').options[0] = new Option('Другое', 'other_select');
                $('modification_name').enable();
            }
    }
    list.options[list.options.length] = new Option('Другое', 'other_select');
    if (window[type + '_name_dd'])
        window[type + '_name_dd'].init();
}

/**
 * FILL EDIT FORM -- !!!!!!TODO!!!!!
 * @param {String} aid
 * @param {Array} brend_names
 * @param {Array} brend_ids
 * @param {String} brend_id
 * @param {Array} model_names
 * @param {Array} model_ids
 * @param {String} model_id
 * @param {Array} modification_names
 * @param {Array} modification_ids
 * @param {String} modification_id
 * @param {String} ProductionYear
 * @param {String} BuyYear
 * @param {String} SellYear
 * @param {String} BuyMonth
 * @param {String} SellMonth
 * @param {String} current_time
 */
function items_FillEditForm(aid, brend_names, brend_ids, brend_id, model_names, model_ids, model_id, modification_names, modification_ids, modification_id, ProductionYear, BuyYear, SellYear, BuyMonth, SellMonth, current_time){
    if (aid == old_aid)
        return;

    var cont = $("edit_form_container_" + aid);
    var old_cont = $("edit_form_container_" + old_aid);
    var form = $("edit_form");
    editing = 1;
    old_cont.hide();
    cont.update(old_cont.innerHTML);
    old_cont.update('');
    $('update_aid').value = aid;
    old_aid = aid;

    $(items_gid('brend_id')).hide();
    $(items_gid('brend_id')).value = '';
    $(items_gid('model_id')).hide();
    $(items_gid('model_id')).value = '';
    $(items_gid('modification_id')).hide();
    $(items_gid('modification_id')).value = '';
    $('current_time_edit').checked = false;

    if (brend_names.length)
        items_FillList('brend_id', brend_names, brend_ids, brend_id);
    if (model_names.length)
        items_FillList('model_id', model_names, model_ids, model_id);
    if (modification_names.length)
        items_FillList('modification_id', modification_names, modification_ids, modification_id);

    if (period_from) {
        var from = $('period_from_edit').options;
        for (var i = 0; i < from.length; i++) {
            if (from[i].value == period_from) {
                from[i].selected = true;
                break;
            }
        }
    }
    if (period_to) {
        var to = $('toTime_edit').options;
        for (var i = 0; i < to.length; i++) {
            if (to[i].value == period_to) {
                to[i].selected = true;
                break;
            }
        }
    }
    if (current_time) {
        $('current_time_edit').checked = current_time;
        $('toTime_edit').disable();
    }
    if (house_names.length) {
        for (var i = 0; i < house_ids.length; i++) {
            if (house_ids[i] == house_id) {
                $('house_edit').value = house_names[i];
                break;
            }
        }
    }
    var activity = $('activity_id_edit').options;
    for (var i = 0; i < activity.length; i++) {
        if (activity[i].value == type) {
            activity[i].selected = true;
            if (activity[i].value == 0) {
                $('activity_name_edit').value = type_own;
                $('activity_name_edit').show();
            }
            break;
        }
    }
    cont.show();
}

/* ONCHANGE ============================================================================ */

/**
 *
 * @param {Object} obj
 */
function items_onChangeBrend(obj){
    var value = obj.value;
    items_form_empty(1);
    $('model_name').disable();
    $('model_name').options[0].text = 'Выбрать';
    if (editing) {
        var td_a = 'model_star_edit';
    }
    else {
        var td_a = 'model_star_add';
    }
    Element.hide('brend_name_other');
    Element.hide('model_name_other');
    $('model_name_dd').value = '';
    $('modification_name_dd').value = '';
    Element.hide('modification_name_other');
    if (value && value != 'other' && value != 'other_select') {
        items_ajax_item_call(obj.value, 'model');
        $(td_a).update('<img src="http://img1.imgsmail.ru/r/my/loading.gif" width="16" height="15" alt="" class="load">');
        $('model_name').options[0].text = 'Загрузка...';
    }
    else {
        if (value == 'other_select' || value == 'other') {
            if (value == 'other_select') {
                $('brend_name_other').show();
                $('brend_name_dd').value = '';
                $('brend_name_dd').focus();
            }
            else
                $('brend_name_dd').value = obj.options[obj.selectedIndex].text;
            $('model_name').options[0] = new Option('Другое', 'other_select');
            $('model_name').enable();
            Element.show('model_name_other');
            $('modification_name').options[0] = new Option('Другое', 'other_select');
            $('modification_name').enable();
            Element.show('modification_name_other');
        }
    }
}

/**
 *
 * @param {Object} obj
 */
function items_onChangeModel(obj){
    var value = obj.value;
    items_form_empty(2);
    $('modification_name').disable();
    $('modification_name').options[0].text = 'Выбрать';
    if (editing) {
        var td_a = 'modification_star_edit';
    }
    else {
        var td_a = 'modification_star_add';
    }
    $('model_name_other').hide();
    $('modification_name_other').hide();
    $('modification_name_dd').value = '';
    if (value && value != 'other' && value != 'other_select') {
        items_ajax_item_call(obj.value, 'modification');
        $(td_a).update('<img src="http://img2.imgsmail.ru/r/my/loading.gif" width="16" height="15" alt="" class="load">');
        $('modification_name').options[0].text = 'Загрузка...';
    }
    else {
        if (value == 'other_select' || value == 'other') {
            if (value == 'other_select') {
                $('model_name_other').show();
                $('model_name_dd').value = '';
                $('model_name_dd').focus();
            }
            else
                $('model_name_dd').value = obj.options[obj.selectedIndex].text;
            $('modification_name').options[0] = new Option('Другое', 'other_select');
            $('modification_name').enable();
            $('modification_name_other').show();
        }
    }
}

/**
 *
 * @param {Object} obj
 */
function items_onChangeModification(obj){
    var value = obj.value;
    Element.hide('modification_name_other');
    if (value && value == 'other_select') {
        Element.show('modification_name_other');
        $('modification_name_dd').value = '';
        $('modification_name_dd').focus();
    }
    else
        $('modification_name_dd').value = obj.options[obj.selectedIndex].text;
    ;
}

/**
 * DISABLE SELLDATE
 */
function disable_selldate(){
    if (document.forms['item_edit'].elements['SellYear'].disabled == 0 && document.forms['item_edit'].elements['SellMonth'].disabled == 0) {
        document.forms['item_edit'].elements['SellMonth'].disabled = 1;
        document.forms['item_edit'].elements['SellYear'].disabled = 1;
    }
    else
        if (document.forms['item_edit'].elements['SellYear'].disabled == 1 && document.forms['item_edit'].elements['SellMonth'].disabled == 1) {
            document.forms['item_edit'].elements['SellMonth'].disabled = 0;
            document.forms['item_edit'].elements['SellYear'].disabled = 0;
        }
}

function items_check_sub_but(){
    var type = $F('category');
    var en = false;
    switch(type){
        case 'Auto': if($F('ProductionYear')) en = true; break;
        case 'Other': if($F('item_name')) en = true; break;
        default: if($F('model_name')) en = true; break;
    };
    en ? $('submit_item').enable() : $('submit_item').disable();
}

/**
 * Add item photo
 */
function items_add_photo(){
    if (popup)
        popup.close();
    popup = window.open('http://' + PhotoImagineHost + '/cgi-bin/photo/addphoto?items=1&My=1&Title=', 'add_pict', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}

/**
 * Redraw items
 * @param {String} no_update
 */
function items_redraw(no_update){
    // Type
    var Type = '';
    if ($('type_wish') && $('type_wish').checked) {
        Type = 'Wish'
    };
    if ($('type_have') && $('type_have').checked) {
        Type = 'Have'
    };
    if ($('type_selling') && $('type_selling').checked) {
        Type = 'Selling'
    };
    if ($('type_presenting') && $('type_presenting').checked) {
        Type = 'Presenting'
    };

    // Category
    var Category = 'Other';
    var list = $('category');
    for (i = 0; i < list.length; i++) {
        if (list[i].selected) {
            Category = list[i].value;
        }
    }

    // Disabling all
    $('BlockDescription').hide();
    $('BlockLink').hide();
    $('BlockPrice').hide();
    $('BlockTags').hide();


    $('BlockName').hide();
    $('item_name').disable();

    $('BlockBrend').hide();
    $('brend_name').disable();
    $('BlockModel').hide();
    $('model_name').disable();

    $('BlockModification').hide();
    $('modification_name').disable();
    $('BlockProduction').hide();
    $('ProductionYear').disable();

    $('BlockBuy').hide();
    $('BuyYear').disable();
    $('BuyMonth').disable();
    $('BlockSell').hide();
    $('SellYear').disable();
    $('SellMonth').disable();
    $('BlockCurrent').hide();
    $('current_time_id').disable();

    //Enabling needed
    //// COMMON
    if (Type) {
        $('BlockDescription').show();
        $('BlockLink').show();
        $('BlockPrice').show();
        $('BlockTags').show();
    }
    //// OTHER
    if (Type && Category == 'Other') {
        $('BlockName').show();
        $('item_name').enable();
    }
    //// ITEM
    if (Type && Category && Category != 'Other') {
        $('BlockBrend').show();
        $('brend_name').enable();
        if (!no_update)
            items_ajax_item_call(0, 'brend', Category);
        $('BlockModel').show();
        if ($F('brend_name'))
            $('model_name').enable();
        Element.hide('brend_name_other');
    }
    //// AUTO
    if (Type && Category == 'Auto') {
        $('BlockModification').show();
        if ($F('model_name'))
            $('modification_name').enable();
        $('BlockProduction').show();
        $('ProductionYear').enable();
        //// DATES
        if (Type != 'Wish') {
            $('BlockBuy').show();
            $('BuyYear').enable();
            $('BuyMonth').enable();
            $('BlockSell').show();
            $('SellYear').enable();
            $('SellMonth').enable();
            $('BlockCurrent').show();
            $('current_time_id').enable();
        }
    }
    if ($F('brend_name'))
        $('brend_name').enable();
    if ($F('model_name'))
        $('modification_name').enable();
    if ($F('model_name'))
        $('modification_name').enable();
}

/**
 * Count symbols
 */
function items_count_symbols(){
    num = $F('description_text').length;
    digit = num % 10;
    dig = 'символов';
    ent = 'Набрано';
    switch (digit) {
        case 1:
            dig = 'символ';
            ent = 'Набран';
            break;
        case 2:
            dig = 'символа';
            break;
        case 3:
            dig = 'символа';
            break;
    }
    digit = num % 100;
    if (digit > 10 && digit < 20) {
        dig = 'символов';
        ent = 'Набрано';
    }
    $('text_symbols').update(ent + ': ' + num + ' ' + dig + ' (максимум 500)');
    if (num > 500) {
        $('text_symbols').style.color = '#C00'
    }
    if (num <= 500) {
        $('text_symbols').style.color = '#999'
    }
}

/*
 * {addwish.tmpl}
 */
/**
 * Add wish photo
 */
function wishes_add_photo(){
    if (popup)
        popup.close();
    popup = window.open('http://'+PhotoImagineHost+'/cgi-bin/photo/addphoto?items=1&My=1&Title=', 'add_pict', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}

/**
 * Show need status
 */
function show_need_status(){
    //alert(document.forms['wish_edit'].elements['Status'].value);
    if (document.forms['wish_edit'].elements['Status'].value == '1') {
        document.forms['wish_edit'].elements['Need'].disabled = false;
    }
    else {
        document.forms['wish_edit'].elements['Need'].disabled = true;
    }
}

/**
 * Count symbols
 */
function wishes_count_symbols(){
    num = $F('description_text').length;
    digit = num % 10;
    dig = 'символов';
    ent = 'Набрано';
    switch (digit) {
        case 1:
            dig = 'символ';
            ent = 'Набран';
            break;
        case 2:
            dig = 'символа';
            break;
        case 3:
            dig = 'символа';
            break;
    }
    digit = num % 100;
    if (digit > 10 && digit < 20) {
        dig = 'символов';
        ent = 'Набрано';
    }
    $('text_symbols').update(ent + ': ' + num + ' ' + dig + ' (максимум 500)');
    if (num > 500) {
        $('text_symbols').style.color = '#C00'
    }
    if (num <= 500) {
        $('text_symbols').style.color = '#CCC'
    }
}

/*
 * {colleagues.tmpl}
 */
//function colleagues_changeStudyType(sel){
//    var typeArray = ["Школа", "Колледж или ПТУ", "ВУЗ"];
//    var cross = ["0", "0", "0", "1", "2"];
//    val = cross[sel.value];
//    $("studyTypeId").innerHTML = typeArray[val];
//    $("univDataId").style.display = (val != 0) ? "" : "none";
//    $("univYearId").style.display = (val != 0) ? "" : "none";
//    $("schoolDataId").style.display = (val == 0) ? "" : "none";
//    $("fakultetId").style.display = (val == 0) ? "none" : "";
//    $("kafedraId").style.display = (val == 2) ? "" : "none";
//}

/**
 * Reset colleagues form
 * @param {String} level
 */

function colleagues_form_empty(level){
    if (level < 2) {
        $('RegionID').disable();
        $('RegionID').options.length = 1;
        $('RegionID').options[0].value = '';
        $('RegionID').options[0].text = 'Недоступно';
    }
    if (level < 3) {
        $('city_id').disable();
        $('city_id').options.length = 1;
        $('city_id').options[0].value = '';
        $('city_id').options[0].text = 'Недоступно';
    }
    if (level < 4) {
        $('company_name').disable();
        $('company_name').value = 'Недоступно';
    }
}

/**
 * Fill colleaguess geo
 * @param {Array} names
 * @param {Array} ids
 * @param {String} type
 * @param {String} level
 * @param {String} special
 */
function colleagues_FillGeo(names, ids, type, level, special){
    if (type == 2) {
        list = $('RegionID');
        $('RegionID').enable();
        $('city_id').disable();
        $('city_id').options.length = 1;
        $('city_id').options[0].value = '';
        $('city_id').options[0].text = 'Недоступно';
    }
    else {
        //if (type==3) {
        if (level != 3) { // Not a Russia, disabling region menu
            $('RegionID').options.length = 1;
            $('RegionID').options[0].value = '';
            $('RegionID').options[0].text = 'Недоступно';
            $('RegionID').disable();
        }
        //$('city_id').disabled=0;
        list = $('city_id');
    }
    if (names.length) {
        list.enable();
    }
    else {
        geo_id = $F('city_id') ? $F('city_id') : ($F('country_id') ? $F('country_id') : '');
        $('geo_azer_href').href = '/my/career?show_career=1&add_geo_id=' + geo_id;
        $('othercity').show();
        return;
    }
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Выбрать';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        if (special > 0) {
            list.options[i + 1].style.fontWeight = "bold";
            special--;
        }
        list.options[i + 1].value = ids[i];
    }
    if (type == 1 || (type == 3 && is_capital == 1))//(set default country -> Russia) OR (set default city -> capital)
    {
        list.selectedIndex = 1;
        list.onchange();
    }
    if (need_switch_star) {
        colleagues_switchStarOfFieldCallback();
    }
}

/**
 *
 * @param {String} formName
 * @param {String} fieldName
 * @param {String} errorText
 * @return {String}
 */
function colleagues_CheckFieldByNull(formName, fieldName, errorText){
    if (formName.elements[fieldName].value == null || formName.elements[fieldName].value == undefined || formName.elements[fieldName].value == "") {
        return errorText;
    }
    else {
        return '';
    }
}

//function colleagues_set_mode(v){
//    v = parseInt(v);
//    switch (v) {
//        case 1:
//            mode = 'company';
//            break;
//    }
//}

/**
 *
 * @param {String} formName
 * @return {Boolean}
 */
function colleagues_CheckFormByNull(formName){
    var errors = "";
    errors += colleagues_CheckFieldByNull(formName, 'country_id', "Поле СТРАНА не заполнено\n");
    if (formName.elements['RegionID'].disabled != 1) {
        errors += colleagues_CheckFieldByNull(formName, 'RegionID', "Поле РЕГИОН не заполнено\n");
    }
    errors += colleagues_CheckFieldByNull(formName, 'city_id', "Поле ГОРОД не заполнено\n");
    errors += colleagues_CheckFieldByNull(formName, 'company_name', "Поле НАЗВАНИЕ КОМПАНИИ не заполнено\n");

    if (errors != null && errors != "") {
        alert(errors);
        return false;
    }
    else {
        $('but_find').disable();
    }
}

/**
 *
 * @param {String} fieldName
 * @param {String} starName
 */
function colleagues_switchStarOfField(fieldName, starName){
    star_field = fieldName;
    star_name = starName;
    need_switch_star = true;
}

/**
 *
 */
function colleagues_switchStarOfFieldCallback(){
    if ($(star_field).disabled == 0) {
        $(star_name).className = 'red starr';
    }
    else {
        $(star_name).className = 'white';
    }
    need_switch_star = false;
}

//function colleagues_switch_result(){
//    if ($('result_txt').innerHTML.match(/Скрыть/)) {
//        $('result_txt').innerHTML = "Показать параметры поиска";
//        $('result_img_plus').style.display = "block";
//        $('result_img_minus').style.display = "none";
//        $('condition_table').style.display = "none";
//
//    }
//    else {
//        $('result_txt').innerHTML = "Скрыть параметры поиска";
//        $('result_img_plus').style.display = "none";
//        $('result_img_minus').style.display = "block";
//        $('condition_table').style.display = "block";
//    }
//    return false
//}

/**
 *
 */
function colleagues_switch_result(){
    var show = 1;
    if (!$F('country_id'))
        show = 0;
    if (!$F('city_id'))
        show = 0;
    if (!$F('company_name'))
        show = 0;
    if (!$F('enteryear_company'))
        show = 0;
/*    if (!$F('entermonth_company'))
        show = 0;
*/
    if (!$('stillhere_company').checked) {
        if (!$F('leaveyear_company'))
            show = 0;
        /*if (!$F('leavemonth_company'))
            show = 0;*/
    }
	if(document.getElementById('enteryear_company').value == '') {
		$('entermonth_company').disabled = true;
	} else {
		$('entermonth_company').disabled = false;
	}	
	if(document.getElementById('had_worked_table')) {
    	$('had_worked_table').style.display = show ? 'block' : 'none';
    	$('had_worked').disabled = 1 - show;
	}
    $('but_find').disabled = (!$('country_id').value || !$('city_id').value || !$('company_name').value);
}

/*
 * {common-friends.tmpl}
 */
/**
 * Выделяем все checkbox
 */
function common_friends_select_all_checkboxes(){
    var form  = $('invitation_form');
    var label = $('select_all_checkboxes_label');
    var working_mode;

    if( $('select_all_checkbox').checked ){
        working_mode = 1;
    } else {
        working_mode = 0;
    }

    for(var i=0; i<form.elements.length; i++){
        if( form.elements[i].type == 'checkbox' && form.elements[i].id != 'select_all_checkboxes' ){
            form.elements[i].checked = working_mode ? true : false;
        }
    }
}

/**
 * Обработка ответа
 * @param {String} result
 * @param {String} id
 */
function common_friends_addToFriendResult(result, id) {
    var span = $(id);
    var link = $(id + '_friends_link');

    if(result == 'friendship_offer') {
        span.update("Приглашение отправлено");
        link.show();
        common_friends_tempDiv(false);
    } else if(result == 'friend_added') {
        span.update("Ура! Вы стали друзьями!");
        link.show();
        common_friends_tempDiv(false);
    } else if(result == 'my_invitation_sent' ) {
        span.update("Пользователю выслано предложение создать свой мир");
        link.show();
        common_friends_tempDiv(false);
    } else if(result == 'world_invitation_sent' ) {
        span.update("Вы пригласили пользователя поситить свой мир");
        link.show();
        common_friends_tempDiv(false);
    } else if(result == 'already_friends' ) {
        span.update("Вы уже друзья");
        link.show();
        common_friends_tempDiv(false);
    } else if(result == 'already_friendship_offer_sent' ) {
        span.update("Вы уже выслали предложение");
        link.show();
        common_friends_tempDiv(false);
    } else if(result == 'invalid_emails' ) {
        span.update("Неверный email");
        common_friends_tempDiv(false);
    } else {
        common_friends_tempDiv(false);
        alert('При обработке запроса произошла ошибка. Повторите попытку снова.');
    }
}

/**
 *
 * @param {String} id
 * @param {String} email
 * @return {Boolean}
 */
function common_friends_addToFriendOnMy(id, email){
    common_friends_tempDiv(true, id);
    ajax_call('perl_add_friend', email, id, common_friends_addToFriendResult);
    return false;
}

/**
 * @return {Boolean}
 */
function common_friends_check_on_invitation_send(){
    var check   = 0;
    if( $('invitation_form') ){
        var form = $('invitation_form');
        for(var i=0; i<form.elements.length; i++){
            if( form.elements[i].type == 'checkbox' && form.elements[i].checked ) check = 1;
        }
    }
    if(check){
        return true;
    } else {
        alert('Вы не ввели ни одного e-mail');
        return false;
    }
}

/**
 *
 * @param {String} flag
 * @param {String} id
 */
function common_friends_tempDiv(flag, id) {
    var div;
    var span = $(id);
    if (!$("addFriendProcessingId")) {
		var div = new Element('div', {'id': 'addFriendProcessingId'});
		div.setStyle({
			position: 'absolute',
			top: 0,
			left: 0,
			display: 'none',
			border: '1px solid #000',
			'background-color': '#FFF000',
			padding: '10px 30px',
			font: '12px arial'
		});
        div.update("Запрос обрабатывается...");
        document.body.appendChild(div);
    } else div = $("addFriendProcessingId");
    if (flag) {
        div.style.top = absPosition(span).y;
        div.style.left = absPosition(span).x;
        div.show();
    } else div.hide();
}

/*
 * {communities-invitation.tmpl}
 */
/**
 * @classDescription communities_SavedListing class
 * @param {Object} params
 */
function communities_SavedListing( params ){
    // SUBMIT
    this.submit = function() {
        this.save();
        if(this.finishInput) this.finishInput.value = 1;
        if(this.onSubmitCallback) this.onSubmitCallback(this.getSavedElements());
        this.form.submit();
        return false;
    };
    // CHANGE PAGE
    this.changePage = function( page ) {
        this.save(1);
        this.pageInput.value = page;
        if(this.onPageChangeCallback) this.onPageChangeCallback(this.getSavedElements(), page);
        this.form.submit();
        return false;
    };
    // SELECT
    this.select = function() {
        if( this.selectAllCheckbox ){
            var elements = this.form.elements;
            for(var i=0; i < elements.length; i++){
                if( elements[i].type == 'checkbox' && this.selectAllCheckbox != elements[i] ){
                    elements[i].checked = this.selectAllCheckbox.checked ? true : false;
                }
            }
            this.count();
        }
    };
    // SAVE
    this.save = function( pageChange ) {
        var value = this.getElementsToSave();
        var count = value.length;
            value = value.join(',');
        this.saveInput.value = value;
        if(this.openerSaveInput && !pageChange) this.openerSaveInput.value = value;
        if(this.countHTMLElement) this.countHTMLElement.innerHTML = count;
        if(this.openerCountHTMLElement && !pageChange) this.openerCountHTMLElement.innerHTML = count;
        if( this.saveInput2 ){
            this.saveInput2.value = this.getElementsToSave2().join(',');
            if(this.openerSaveInput2 && !pageChange) this.openerSaveInput2.value = this.saveInput2.value;
        }
    };
    // COUNT
    this.count = function() {
        var value = this.getElementsToSave();
        var count = value.length;
        if(this.countHTMLElement) this.countHTMLElement.innerHTML = count;
        this.checkSelectAllCheckbox();
    };
    // LOAD
    this.load = function() {
        var savedElements   = this.getSavedElements();
        if(this.onLoadCallback) this.onLoadCallback(savedElements);
        var formElements    = this.form.elements;
        for(var i=0; i < formElements.length; i++){
            var formElement = formElements[i];
            if(formElement.type == "checkbox" && this.selectAllCheckbox != formElement){
                var element = formElement.value.replace(/^\s+|\s+$/g,"").toLowerCase();
                for(var k=0; k < savedElements.length; k++){
                    if(savedElements[k] == element){
                        formElement.checked = true;
                    }
                }
            }
        }
        this.checkSelectAllCheckbox();
        this.save(1);
    };
    // CHECK COUNTER
    this.checkSelectAllCheckbox = function(){
        if( this.selectAllCheckbox ){
            var elements    = this.form.elements;
            var checked     = true;
            for(var i=0; i < elements.length; i++){
                if( elements[i].type == 'checkbox' && !elements[i].checked && elements[i] != this.selectAllCheckbox ){
                    checked = false;
                    break;
                }
            }
            this.selectAllCheckbox.checked = checked;
        }
    }
    // GET SAVED ELEMENTS
    this.getSavedElements = function(){
        var elements = this.openerSaveInput && this.isJustOpen() ? saveInput.value + ',' + openerSaveInput.value : saveInput.value;
        return this.uniq(elements.split(','));
    };
    // GET SAVED ELEMENTS2
    this.getSavedElements2 = function(){
        var elements = this.openerSaveInput2 && this.isJustOpen() ? saveInput2.value + ',' + openerSaveInput2.value : saveInput2.value;
        return this.uniq(elements.split(','), 1);
    };
    // GET ELEMENTS TO SAVE
    this.getElementsToSave  = function(){
        var formElements    = this.form.elements;
        var savedElements   = this.getSavedElements();
        for(var i=0; i < formElements.length; i++){
            var formElement = formElements[i];
            if(formElement.type == "checkbox" && this.selectAllCheckbox != formElement){
                if(formElement.checked){
                    savedElements[savedElements.length] = formElement.value;
                } else {
                    var element = formElement.value.replace(/^\s+|\s+$/g,"").toLowerCase();
                    for(var k=0; k < savedElements.length; k++){
                        if(savedElements[k] == element) savedElements[k] = '';
                    }
                }
            }
        }
        return this.uniq(savedElements);
    };
    // GET ELEMENTS TO SAVE2
    this.getElementsToSave2 = function(){
        var formElements    = this.form.elements;
        var savedElements   = this.getSavedElements2();
        for(var i=0; i < formElements.length; i++){
            var formElement = formElements[i];
            if(formElement.type == "checkbox" && this.selectAllCheckbox != formElement){
                if(formElement.checked){
                    savedElements[savedElements.length] = this.input2Callback(formElement.value);
                } else {
                    var element = this.input2Callback(formElement.value);
                    for(var k=0; k < savedElements.length; k++){
                        if(savedElements[k] == element) savedElements[k] = '';
                    }
                }
            }
        }
        return this.uniq(savedElements, 1);
    };
    // IS JUST OPEN
    this.isJustOpen = function(){
        if(navigator.userAgent.indexOf("Firefox")!=-1){
            return history.length == 1 ? 1 : 0 ;
        } else {
            return history.length == 0 ? 1 : 0 ;
        }
    }
    // UNIQ
    this.uniq = function(arr, dontModify){
        var retArr = new Array();
        if(arr.length){
            for(var i=0; i<arr.length; i++){
                var element = arr[i].replace(/^\s+|\s+$/g,"");
                if(!dontModify) element = element.toLowerCase();
                if( !element || element == '' ) continue;
                var elementNotExists = true;
                for(var k=0; k<retArr.length; k++){
                    if( retArr[k] == element ) elementNotExists = false;
                }
                if(elementNotExists) retArr[retArr.length] = element;
            }
        }
        return retArr;
    };
    // ERROR
    this.error = function(msg){
        throw('Error in communities_SavedListing: ' + msg);
    };
    // CONSTRUCTOR
    if( listing ) this.error('constructor'); // Silly Singleton
    if( params.form && params.saveInput && params.pageInput ){
        this.form               = params.form;
        this.saveInput          = params.saveInput;
        this.pageInput          = params.pageInput;
    } else {
        this.error('constructor');
    }
    this.saveInput2             = params.saveInput2 ? params.saveInput2 : null;
    this.countHTMLElement       = params.countHTMLElement ? params.countHTMLElement : null;
    this.openerSaveInput        = params.openerSaveInput ? params.openerSaveInput : null;
    this.openerSaveInput2       = params.openerSaveInput2 ? params.openerSaveInput2 : null;
    this.openerCountHTMLElement = params.openerCountHTMLElement ? params.openerCountHTMLElement : null;
    this.onLoadCallback         = params.onLoad ? params.onLoad : null;
    this.onSubmitCallback       = params.onSubmit ? params.onSubmit : null;
    this.onPageChangeCallback   = params.onPageChange ? params.onPageChange : null;
    this.input2Callback         = params.input2Callback ? params.input2Callback : null;
    if( this.openerSaveInput2 && !this.saveInput2 ) this.error('constructor');
    if( this.saveInput2 && !this.input2Callback ) this.error('constructor');
    if( params.selectAllCheckbox ){
        this.selectAllCheckbox = params.selectAllCheckbox;
        this.selectAllCheckbox.onclick = function(){
            listing.select();
        }
    } else {
        this.selectAllCheckbox = null;
    }
    if( params.finishInput ){
        this.finishInput = params.finishInput;
        this.finishInput.value = 0;
    } else {
        this.finishInput = null;
    }

    this.load();
    return this;
}

/*
 * {community-main.tmpl}
 */
/**
 *
 * @param {Object} el
 * @param {String} id
 * @param {String} email
 * @return {Boolean}
 */
function community_showSpamComplaintDiv(el, id, email){
    ajax_call('perl_is_friend', email, id, FriendComplaint);
    var div = $('SpamComplaintDiv');
    div.style.top = absPosition(el).y + el.offsetHeight;
//    div.style.left = absPosition(el.parentNode).x;
    document.complaint.gb_message.value = id;
    document.complaint.spamer.value = email;
    if (IsChecked) $("message").checked = true;
    div.show();
    return false;
}

/*
 * {conference_create.tmpl}
 */
/**
 * Check conference message
 */
function conference_checkMessage(){
    var len1 = $('topic1').value.length;
    var len2 = $('msg1').value.length;
    var friends = $('friends').value;
    var len3 = friends.split(',').length;
    if (len1 == 0) {
        alert('Укажите тему конференции');
    }
    else
        if (len2 == 0) {
            alert('Введите первое сообщение');
        }
        else
            if (len3 + 1 > MaxMembers) {
                alert('Число участников, включая вас, должно быть не более ' + MaxMembers);
            }
            else
                if (!friends) {
                    alert('Сначала пригласите в конференцию хотя бы одного друга.');
                }
                else {
                    var sub_but = $("sub_but");
                    sub_but.value = "Идет отправка";
                    sub_but.disable();
			        if(Booster.inited) {
			        	Booster.go($('dupdate').action, $('dupdate').method, $('dupdate').serialize());
			    	}
			    	else {
			    		$('dupdate').submit();
			    	}
                }
}

/**
 * Remove conference member
 * @param {Object} el
 */
function conferenceRemoveMember(el){
    function traverse(node){
        node = node.parentNode;
        while (!node.id)
            node = node.parentNode
        return node;
    }

    function grep(what, where){
        var e = where.split(/, ?/), r = Array();
        for (var i = 0; i < e.length; i++)
            if (e[i] == what)
                return i;
        return -1;
    }

    function trim(j, where){
        var e = where.split(/, ?/), r = Array();
        for (var i = 0; i < e.length; i++)
            if (j != i)
                r.push(e[i]);
        return r.join(', ');
    }

    el = traverse(el);

    var i = grep(el.id, $('save').value);
    $('send').value = trim(i, $F('send'));
    $('friends').value = trim(i, $F('friends'));
    $('save').value = trim(i, $F('save'));
    $('save2').value = trim(i, $F('save2'));
    el.parentNode.removeChild(el);
}

/**
 * Render conference member
 * @param {Object} elem
 * @return {HTMLElement}
 */
function conferenceRenderMemeber(elem){
    var el = new Element('div');

    var email2dir = function(email){
        return email.replace(/([^@]+)@([^.]+).*/, "/$2/$1/");
    };

	var bstr_on_click = '';
	if(Booster.inited) bstr_on_click = 'onclick="return Booster.go(this.href);"';
    var online = '<div><a href="/my/dialogues?sendmsg='+MyMailEmail+'" class="mf_o45" '+ bstr_on_click +'>на&nbsp;сайте</a></div>';
    var template = '<div class="cr_one"><a href="$Dir" class="mf_a45" style="background-image: url(http://$AvtHost$Dir_avatarsmall);" '+ bstr_on_click +'></a>$online<div class="mf_t95"><a href="http://www.mail.ru/agent?message&to=$Email"><img src="http://status.mail.ru/?$Email&9x9" width="9" height="9" alt="Щелкни, чтобы пообщаться с этим человеком в Mail.Ru Агенте" class="mr2"></a><a href="$Dir" '+ bstr_on_click +'>$name</a></div><a href="#" onClick="conferenceRemoveMember(this); return false;" class="mf_spIco mf_iDel2">удалить</a></div>';

    template = template.replace(/\$AvtHost/g, PhotoAvtHost);
    template = template.replace(/\$Email/g, elem.Email);
    template = template.replace(/\$Dir/g, email2dir(elem.Email));
    template = template.replace(/\$online/g, elem.Online ? online : '');

    var name = (elem.FirstName || elem.LastName) ? elem.FirstName + ' ' + elem.LastName : elem.Nick ? elem.Nick : elem.Email;

    template = template.replace(/\$name/g, name.replace(/(\S{9})/g, "<span>$1</span>"));

    el.update(template);
    el.firstChild.id = elem.Email;
    return el.firstChild;
}

/*
 * {conference_thread.tmpl}
 */
/**
 * Check conference thread message
 */
function conference_thread_checkMessage(){
    var len2 = $F('msg1').length;
    if (len2 == 0) {
        $('error2').show();
    }
    else {
        $('error2').hide();
        $('dupdate').submit();
    }
}

/**
 * Count symbols
 */
function conference_thread_count_symbols(){
    num = $F('msg1').length;
    $('simbCount1').update(num);
    if (num > 4000) {
        $('strCount1').style.color = '#C00'
    }
    if (num <= 4000) {
        $('strCount1').style.color = '#999'
    }
}

/**
 * Check submit buttons
 */
function checkSubButs(but_id, msg_field_id){
    var stts = 1;
    stts = ($F(msg_field_id||'msg1').length <= 0) || need_block;
    var b = $(but_id||'sub_but1');
    if(b) b.disabled = stts;
}

/*
 * {conference_threads_list.tmpl}
 */
/**
 * Show conference thread list
 * @param {String} nick
 */
function conference_threads_list_show(nick){
    name_link = "hid_link_" + nick;
    linka = $(name_link);
    linka.show();
}

/**
 * Hide conference thread list
 * @param {String} nick
 */
function conference_threads_list_hide(nick){
    name_link = "hid_link_" + nick;
    linka = $(name_link);
    linka.hide();
}

/*
 * {dialogues_send.tmpl}
 */
/**
 * Check sended dialogues message
 */
function dialogues_send_checkMessage(sub_but_id){
    var len1 = $F('friendsMailId').length;
    var len2 = $F('msg1').length;
    if (len1 == 0) {
        $('error1').show();
        $('error2').hide();
    }
    else {
        if (len2 == 0) {
            $('error1').hide();
            $('error2').show();
        }
        else {
            $('error1').hide();
            $('error2').hide();
            var sub_but = $(sub_but_id||"sub_but");
            sub_but.value = "Идет отправка";
            sub_but.disable();
            return 1;
        }
    }
    return 0;
}

/*
 * {dialogues_thread.tmpl}
 */
/**
 * Check dialogue thread message
 */
function dialogues_thread_checkMessage(){
    var len2 = $F('msg1').length;
    if (len2 == 0) {
        $('error1').hide();
        $('error2').show();
    }
    else {
        $('error1').hide();
        $('error2').hide();

        $('dupdate').submit();
    }
}

function dialogues_thread_count_symbols(){
    num = $F('msg1').length;
    $('simbCount1').update(num);
    if (num > 4000) {
        $('strCount1').style.color = '#C00'
    }
    if (num <= 4000) {
        $('strCount1').style.color = '#999'
    }
}

function dialogues_thread_showSpamComplaintDiv(el, id){
    var div = $('SpamComplaintDiv');
    div.style.top = absPosition(el).y + el.offsetHeight;
    div.style.left = absPosition(el.parentNode).x;
    document.complaint.message.value = id;
    document.complaint.del[0].checked = 1;
    div.show();
    return false;
}

/*
 * {editblacklist.tmpl}
 */
function editblacklist_add_user(email){
    var bl_name = "add_friend_";
    var new_field = false;
    if (email == '' || document.forms["Compose"].elements["add_email_" + user_count].value != '') {
        user_count++;
        var current = $(bl_name + user_count);
        if (!current)
            return false;
        var parent = current.parentNode;
        if (!parent)
            return false;
        var add_block = new Element('div', {id: bl_name + user_count}).update(
			"<table class=\"cell\">" +
            "<tr>" +
            "<td><b>" +
            user_count +
            ".</b></td>" +
            "<td class=\"w100\"><input type=\"text\" name=\"add_email_" +
            user_count +
            "\" value=\"\" class=inp></td>" +
            "</tr>" +
            "</table>"
		);
        parent.replaceChild(add_block, current);
        new_field = true;
    }
    if (email != '') {
        var values = email.split('@');
        var domain_found = false;
        if (values.length == 2 && values[0] != '' && values[1] != '') {
            var address = values[0];
            var domain = values[1];
            var options = document.forms["Compose"].elements["add_domain_" + user_count].options;
            for (var i = 0; i < options.length; i++) {
                if (options[i].value == domain) {
                    options[i].selected = true;
                    document.forms["Compose"].elements["add_email_" + user_count].value = address;
                    domain_found = true;
                    break;
                }
            }
        }
        if (!domain_found)
            document.forms["Compose"].elements["add_email_" + user_count].value = email;
    }

    if (new_field) {
        var num = user_count + 1;
		add_block = new Element('div', {id: bl_name + num}).update(
			"<table class=\"cell\">" +
	        "<tr>" +
	        "<td><b>" +
	        num +
	        ".</b></td><td class=\"w100\"><a onclick=\"return editblacklist_add_user('');\" href=\"\" class=\"grey2 t95\">Ещё одно поле</a></td>" +
	        "</tr>" +
	        "</table>"
		);
        parent.appendChild(add_block);
    }
    return false;
}

function editblacklist_CheckedOnLoad(){
    if (DOM) {
        var thisCheckBoxes = $$('input');
        for (var i = 1; i < thisCheckBoxes.length; i++) {
            var chb = thisCheckBoxes[i];
            if (chb.name == 'delete') {
                if (chb.checked) {
                    chb.enable();
                    editblacklist_Colorize($(cb.id.replace('box_', 'str')), cb);
                }
            }
        }
    }
}

function editblacklist_Colorize(element, CHBElement){
    if (element && CHBElement) {
        element.className = (CHBElement.checked ? 'bgg' : 'bgw');
    }
}

function editblacklist_sel_tr(element){
    if (DOM) {
        thisCheckbox = $(element.id.replace('row_', 'box_'));
        thisCheckbox.checked = !thisCheckbox.checked;
        editblacklist_Colorize(element, thisCheckbox);
    }
    var all_chB = 0;
    var ch_chB = 0;
    var i = 0;
    for (i = 0; i < document.listing.elements.length; i++) {
        if ((document.listing.elements[i].checked == true) && (document.listing.elements[i].name == "delete")) {
            ch_chB = ch_chB + 1;
        }
        if (document.listing.elements[i].name == "delete") {
            all_chB = all_chB + 1;
        }
    }
    if (ch_chB != all_chB) {
        document.listing.mainCheck.checked = false
    }
    else {
        document.listing.mainCheck.checked = true
    }


}

function editblacklist_sel_box(element){
    if (DOM) {
        if ($(element.id.replace('box_', 'row_'))) {
            element.checked = !element.checked;
        }
    }
}

function editblacklist_sel_all(element, Name){
    var Name = "delete";
    if (DOM) {
        thisCheckBoxes = element.parentNode.parentNode.parentNode.getElementsByTagName('input');
        for (i = 1; i < thisCheckBoxes.length; i++) {
            if (thisCheckBoxes[i].name == Name) {
                thisCheckBoxes[i].checked = element.checked;
                editblacklist_Colorize($(thisCheckBoxes[i].id.replace('box_', 'row_')), thisCheckBoxes[i]);
            }
        }
    }
}

/*
 * {editcommunity.tmpl}
 */
function editcommunity_access_wr(sel){
    var td_for = $("td_for_wr");
    var writesel = $("writesel");
    var sel0 = writesel.value == 0 ? 'selected' : '';
    var sel1 = writesel.value == 1 ? 'selected' : '';
    switch (sel.value) {
        case "0":
            td_for.update("<select id='writesel' class=inp name=\"WriteAccess\"><option value=\"0\" " + sel0 + ">только участники</option><option value=\"1\" " + sel1 + ">только зарегистрированные пользователи</option></select>");
            break;
        case "1":
            td_for.update("<select id='writesel' class=inp name=\"WriteAccess\"><option value=\"0\">только участники</option></select>");
            break;
        case "2":
            td_for.update("<select id='writesel' class=inp name=\"WriteAccess\"><option value=\"0\" " + sel0 + ">только участники</option><option value=\"1\" " + sel1 + ">только зарегистрированные пользователи</option></select>");
            break;
        default:
            break;
    }
    td_for = $("td_for_comm");
    var commsel = $("commsel");
    sel0 = commsel.value == 0 ? 'selected' : '';
    sel1 = commsel.value == 1 ? 'selected' : '';
    var sel2 = commsel.value == 2 ? 'selected' : '';
    switch (sel.value) {
        case "0":
            td_for.update("<select id='commsel' class=inp name=\"CommentAccess\"><option value=\"0\" " + sel0 + ">все</option><option value=\"1\" " + sel1 + ">только участники</option><option value=\"2\" " + sel2 + ">только зарегистрированные пользователи</option></select>");
            break;
        case "1":
            td_for.update("<select id='commsel' class=inp name=\"CommentAccess\"><option value=\"1\">только участники</select>");
            break;
        case "2":
            td_for.update("<select id='commsel' class=inp name=\"CommentAccess\"><option value=\"1\" " + sel1 + ">только участники</option><option value=\"2\" " + sel2 + ">только зарегистрированные пользователи</option></select>");
            break;
        default:
            break;
    }
}

/*
 * {editinfon.tmpl}
 */
function editinfon_newSiteForm(el){
    var num = el.getAttribute('num');
    num++;
    var addText = $('add_site_text');
    addText.setAttribute('num', num);
    var place = $('anketa_tbl');
    var TR1 = new Element('tr', {
    });
    var TR2 = new Element('tr', {
    });
    var TD11 = new Element('th', {
    });
    var TD21 = new Element('th', {
    });
    var TD12 = new Element('td', {
    });
    var TD22 = new Element('td', {
    });
    var NAME_IN = new Element('input', {
        'class': 'inp',
        'type' : 'text',
        'name' : 'Project_' + num + '_Name',
        'id'   : 'site_' + num + '_name'
    });
    var URL_IN = new Element('input', {
        'class': 'inp',
        'type' : 'text',
        'name' : 'Project_' + num + '_URL',
        'id'   : 'site_' + num + '_url'
    });
    var ID_IN = new Element('input', {
        'type' : 'hidden',
        'name' : 'Project_' + num + '_ID',
        'value': '0'
    });
    place.appendChild(TR1);
    TR1.appendChild(TD11);
    TD11.update("<strong>" + num + ".</strong>&nbsp Название");
    TR1.appendChild(TD12);
    TD12.appendChild(NAME_IN);
    place.appendChild(TR2);
    TR2.appendChild(TD21);
    TD21.update("&nbsp&nbsp&nbsp&nbsp URL");
    TR2.appendChild(TD22);
    TD22.appendChild(ID_IN);
    TD22.appendChild(URL_IN);
}

/*
 * {friend_delete.tmpl}
 */
function friend_delete_checkCtrlEnter(evt) {
    checkCtrlEnter(evt, 'frm_emails');
}

/*
 * {friends_popup.tmpl}
 */
// Listing with save
function friends_popup_SavedListing( params ){
    // SUBMIT
    this.submit = function() {
        this.save();
        this.finishInput.value = 1;
        if(this.onSubmitCallback) this.onSubmitCallback(this.getSavedElements());
        this.form.submit();
        return false;
    };
    // CHANGE PAGE
    this.changePage = function( page ) {
        this.save(1);
        this.pageInput.value = page;
        if(this.onPageChangeCallback) this.onPageChangeCallback(this.getSavedElements(), page);
        this.form.submit();
        return false;
    };
    // SELECT
    this.select = function() {
        if( this.selectAllCheckbox ){
            var elements = this.form.elements;
            for(var i=0; i < elements.length; i++){
                if( (elements[i].type == 'checkbox' || elements[i].type == 'radio') && this.selectAllCheckbox != elements[i] ){
                    elements[i].checked = this.selectAllCheckbox.checked ? true : false;
                }
            }
            this.count();
        }
    };
    // SAVE
    this.save = function( pageChange ) {
        var value = this.getElementsToSave();
        var count = value.length;
            value = value.join(',');
        this.saveInput.value = value;
        if(this.openerSaveInput && !pageChange) this.openerSaveInput.value = value;
        if(this.countHTMLElement) this.countHTMLElement.innerHTML = count;
        if(this.openerCountHTMLElement && !pageChange) this.openerCountHTMLElement.innerHTML = count;
        if( this.saveInput2 ){
            this.saveInput2.value = this.getElementsToSave2().join(',');
            if(this.openerSaveInput2 && !pageChange) this.openerSaveInput2.value = this.saveInput2.value;
        }
    };
    // COUNT
    this.count = function() {
        var value = this.getElementsToSave();
        var count = value.length;
        if(this.countHTMLElement) this.countHTMLElement.innerHTML = count;
        this.checkSelectAllCheckbox();
    };
    // LOAD
    this.load = function() {
        var savedElements   = this.getSavedElements();
        if(this.onLoadCallback) this.onLoadCallback(savedElements);
        var formElements    = this.form.elements;
        for(var i=0; i < formElements.length; i++){
            var formElement = formElements[i];
            if((formElement.type == "checkbox" || formElement.type == "radio") && this.selectAllCheckbox != formElement){
                var element = formElement.value.replace(/^\s+|\s+$/g,"").toLowerCase();
                for(var k=0; k < savedElements.length; k++){
                    if(savedElements[k] == element){
                        formElement.checked = true;
                    }
                }
            }
        }
        this.checkSelectAllCheckbox();
        this.save(1);
    };
    // CHECK COUNTER
    this.checkSelectAllCheckbox = function(){
        if( this.selectAllCheckbox ){
            var elements    = this.form.elements;
            var checked     = true;
            for(var i=0; i < elements.length; i++){
                if( (elements[i].type == 'checkbox' || elements[i].type == 'radio') && !elements[i].checked && elements[i] != this.selectAllCheckbox ){
                    checked = false;
                    break;
                }
            }
            this.selectAllCheckbox.checked = checked;
        }
    }
    // GET SAVED ELEMENTS
    this.getSavedElements = function(){
        var elements = this.openerSaveInput && this.isJustOpen() ? saveInput.value + ',' + openerSaveInput.value : saveInput.value;
        return this.uniq(elements.split(','));
    };
    // GET SAVED ELEMENTS2
    this.getSavedElements2 = function(){
        var elements = this.openerSaveInput2 && this.isJustOpen() ? saveInput2.value + ',' + openerSaveInput2.value : saveInput2.value;
        return this.uniq(elements.split(','), 1);
    };
    // GET ELEMENTS TO SAVE
    this.getElementsToSave  = function(){
        var formElements    = this.form.elements;
        var savedElements   = this.getSavedElements();
        for(var i=0; i < formElements.length; i++){
            var formElement = formElements[i];
            if((formElement.type == "checkbox" || formElement.type == "radio") && this.selectAllCheckbox != formElement){
                if(formElement.checked){
                    savedElements[savedElements.length] = formElement.value;
                } else {
                    var element = formElement.value.replace(/^\s+|\s+$/g,"").toLowerCase();
                    for(var k=0; k < savedElements.length; k++){
                        if(savedElements[k] == element) savedElements[k] = '';
                    }
                }
            }
        }
        return this.uniq(savedElements);
    };
    // GET ELEMENTS TO SAVE2
    this.getElementsToSave2 = function(){
        var formElements    = this.form.elements;
        var savedElements   = this.getSavedElements2();
        for(var i=0; i < formElements.length; i++){
            var formElement = formElements[i];
            if((formElement.type == "checkbox" || formElement.type == "radio") && this.selectAllCheckbox != formElement){
                if(formElement.checked){
                    savedElements[savedElements.length] = this.input2Callback(formElement.value);
                } else {
                    var element = this.input2Callback(formElement.value);
                    for(var k=0; k < savedElements.length; k++){
                        if(savedElements[k] == element) savedElements[k] = '';
                    }
                }
            }
        }
        return this.uniq(savedElements, 1);
    };
    // IS JUST OPEN
    this.isJustOpen = function(){
        if(navigator.userAgent.indexOf("Firefox")!=-1){
            return history.length == 1 ? 1 : 0 ;
        } else {
            return history.length == 0 ? 1 : 0 ;
        }
    }
    // UNIQ
    this.uniq = function(arr, dontModify){
        var retArr = new Array();
        if(arr.length){
            for(var i=0; i<arr.length; i++){
                var element = arr[i].replace(/^\s+|\s+$/g,"");
                if(!dontModify) element = element.toLowerCase();
                if( !element || element == '' ) continue;
                var elementNotExists = true;
                for(var k=0; k<retArr.length; k++){
                    if( retArr[k] == element ) elementNotExists = false;
                }
                if(elementNotExists) retArr[retArr.length] = element;
            }
        }
        return retArr;
    };
    // ERROR
    this.error = function(msg){
        throw('Error in friends_popup_SavedListing: ' + msg);
    };
    // CONSTRUCTOR
    if( listing ) this.error('constructor'); // Silly Singleton
    if( params.form && params.saveInput && params.pageInput && params.finishInput ){
        this.form               = params.form;
        this.saveInput          = params.saveInput;
        this.pageInput          = params.pageInput;
        this.finishInput        = params.finishInput;
        this.finishInput.value  = 0;
    } else {
        this.error('constructor');
    }
    this.saveInput2             = params.saveInput2 ? params.saveInput2 : null;
    this.countHTMLElement       = params.countHTMLElement ? params.countHTMLElement : null;
    this.openerSaveInput        = params.openerSaveInput ? params.openerSaveInput : null;
    this.openerSaveInput2       = params.openerSaveInput2 ? params.openerSaveInput2 : null;
    this.openerCountHTMLElement = params.openerCountHTMLElement ? params.openerCountHTMLElement : null;
    this.onLoadCallback         = params.onLoad ? params.onLoad : null;
    this.onSubmitCallback       = params.onSubmit ? params.onSubmit : null;
    this.onPageChangeCallback   = params.onPageChange ? params.onPageChange : null;
    this.input2Callback         = params.input2Callback ? params.input2Callback : null;
    if( this.openerSaveInput2 && !this.saveInput2 ) this.error('constructor');
    if( this.saveInput2 && !this.input2Callback ) this.error('constructor');
    if( params.selectAllCheckbox ){
        this.selectAllCheckbox = params.selectAllCheckbox;
        this.selectAllCheckbox.onclick = function(){
            listing.select();
        }
    } else {
        this.selectAllCheckbox = null;
    }

    this.load();
    return this;
}
// Listing emails with save end

function friends_popup_clickField(id){
    cur_radio = id;
    $('save').enable();
}

function friends_popup_saveIt() {
        if (opener != undefined) {
        var inputs = document.forms.select_friend.getElementsByTagName("INPUT");
        var i = 0;
        while (!inputs[i].checked && (i < inputs.length)) i++;
        if (i < inputs.length) {
            opener.$('PartnerNick').value=inputs[i].nextSibling.nextSibling.innerHTML;
            opener.$('PartnerEmail').value=inputs[i].value;
        }
    }
    window.close();
}

function friends_popup_unchckCurRadio(){
    if (cur_radio == '')
        return;
    $(cur_radio).checked = 0;
    cur_radio = '';
    $('save').disable();
}

function friends_popup_newCoo(t,l,w,h) {
    //alert('friends_popup_newCoo '+t+' '+l+' '+w+' '+h);
    $('coo_top').value = parseInt(t);
    $('coo_left').value = parseInt(l);
    $('coo_width').value = parseInt(w);
    $('coo_height').value = parseInt(h);
}

function friends_popup_startCheckInterval() {
    check_int = setInterval('friends_popup_checkFilter()',500);
}

function friends_popup_genHtml(num) {
    return '<input id="rdbx'+num+'" type="radio" name="personid" onclick="friends_popup_clickField(\'rdbx'+num+'\')" value="'+friends_list[num]['ID']+'"> <a href="http://'+MyPerlHost+friends_list[num]['Dir']+'" target="_blank" onclick="$(\'rdbx'+num+'\').checked=1;friends_popup_clickField(\'rdbx'+num+'\');return false;">'+friends_list[num]['Name']+'</a><br>';
}

function friends_popup_checkFilter() {
    var new_filter = $F('personname').toLowerCase();
    if (old_filter == new_filter) return;
    /*
    if ((new_filter.indexOf(old_filter) == 0) && (old_filter != '')) { // дополнение фильтра

    } else { // изменение фильтра

    }
    */
    filtered_list.length = 0;
    var html = '';
    for (var i = 1; i < friends_list.length; i++) {
        if ((friends_list[i]['LCName'].indexOf(new_filter) == 0) || (friends_list[i]['LCName'].indexOf(' '+new_filter) > 0)) {
            filtered_list.length++;
            filtered_list[filtered_list.length-1] = i;
            html += friends_popup_genHtml(i);
        }
    }
    if ((html != '') && !((filtered_list.length == old_filter_len) && (filtered_list.length == (friends_list.length-1)))) {
        $('for_friends').update('');
        $('for_friends').update(html);
        old_filter_len = filtered_list.length;
    }
    old_filter = new_filter;
}

/*
 * {friends.tmpl}
 */
/**
 * Выделяем все checkbox
 */
function friends_select_all_checkboxes(){
    var form  = $('invitation_form');
    var label = $('select_all_checkboxes_label');
    var working_mode;

    if( $('select_all_checkbox').checked ){
        working_mode = 1;
    } else {
        working_mode = 0;
    }

    for(var i=0; i<form.elements.length; i++){
        if( form.elements[i].type == 'checkbox' && form.elements[i].id != 'select_all_checkboxes' ){
            form.elements[i].checked = working_mode ? true : false;
        }
    }
}

/**
 * Обработка ответа
 * @param {String} result
 * @param {String} id
 */
function addToFriendResult(result, id) {
    var span = $(id);
    var link = $(id + '_friends_link');

    if(result == 'friendship_offer') {
        span.update("Приглашение отправлено");
        link.show();
        friends_tempDiv(false);
    } else if(result == 'friend_added') {
        span.update("Ура! Вы стали друзьями!");
        link.show();
        friends_tempDiv(false);
    } else if(result == 'my_invitation_sent' ) {
        span.update("Пользователю выслано предложение создать свой мир");
        link.show();
        friends_tempDiv(false);
    } else if(result == 'world_invitation_sent' ) {
        span.update("Вы пригласили пользователя поситить свой мир");
        link.show();
        friends_tempDiv(false);
    } else if(result == 'already_friends' ) {
        span.update("Вы уже друзья");
        link.show();
        friends_tempDiv(false);
    } else if(result == 'already_friendship_offer_sent' ) {
        span.update("Вы уже выслали предложение");
        link.show();
        friends_tempDiv(false);
    } else if(result == 'invalid_emails' ) {
        span.update("Неверный email");
        friends_tempDiv(false);
    } else if(result == 'ratelimited_emails' ) {
        span.update("Лимит отправки приглашений дружбы исчерпан. Попробуйте повторить попытку через 20 минут.");
        friends_tempDiv(false);
    } else {
        friends_tempDiv(false);
        alert('При обработке запроса произошла ошибка. Повторите попытку снова.');
    }
}

/**
 *
 * @param {String} id
 * @param {String} email
 */
function addToFriendOnMy(id, email) {
    friends_tempDiv(true, id);
        ajax_call('perl_add_friend', email, id, addToFriendResult);
        return false;
}

/**
 *
 */
function friends_check_on_invitation_send(){
    var check   = 0;
    if( $('invitation_form') ){
        var form = $('invitation_form');
        for(var i=0; i<form.elements.length; i++){
            if( form.elements[i].type == 'checkbox' && form.elements[i].checked ) check = 1;
        }
    }
    if(check){
        return true;
    } else {
        alert('Вы не ввели ни одного e-mail');
        return false;
    }
}

/**
 *
 * @param {String} flag
 * @param {String} id
 */
function friends_tempDiv(flag, id) {
    var div;
    var span = $(id);
    if (!$("addFriendProcessingId")) {
		div = new Element('div', {id: 'addFriendProcessingId'});
		div.setStyle({
			position: 'absolute',
			top: 0,
			left: 0,
			display: 'none',
			border: '1px solid #000',
			'background-color': '#FFF',
			padding: '10px 30px',
			font: '12px arial'
		});
        div.update("Запрос обрабатывается...");
        document.body.appendChild(div);
    } else div = $("addFriendProcessingId");
    if (flag) {
        div.style.top = absPosition(span).y;
        div.style.left = absPosition(span).x;
        div.show();
    } else div.hide();
}

/**
 *
 * @param {String} email
 * @param {String} id
 */
function setBestFriend(email, id) {
    if (ajax_call('perl_set_best', email, id, bestFriendSaved)) {

    }
}

/**
 *
 * @param {String} email
 * @param {String} id
 */
function unsetBestFriend(email, id) {
    if (ajax_call('perl_unset_best', email, id, bestFriendSaved)) {

    }
}

/**
 *
 * @param {String} id
 * @param {String} best
 * @param {String} result
 */
function bestFriendSaved(id, best, result) {
    if (best) {
        if (result==0) {
            $('best_friend_'+id).show();
            $('unset_best_friend_'+id).show();
            $('set_best_friend_'+id).hide();

            $('best_friend_avatar_'+id).className='ava90_best';
        } else {
            alert(result);
        }
    } else {
        if (result==0) {
            $('best_friend_'+id).hide();
            $('unset_best_friend_'+id).hide();
            $('set_best_friend_'+id).show();

            $('best_friend_avatar_'+id).className='ava90';
        } else {
            alert(result);
        }
    }
}

/*
 * {gift_send.tmpl}
 */
function getGiftGroup(group){
    var gifts = [];
    if (group != '') {
        if (giftsByType[group]) {
            gifts = giftsByType[group];
        }
        else
            if (group == 'new') {
                for (var i = 0; i < GiftTypes.length; i++) {
                    var j = 0;
                    while ((j < NewGifts.length) && (NewGifts[j] != GiftTypes[i][0]))
                        j++;
                    if (j < NewGifts.length) {
                        gifts.push(GiftTypes[i]);
                    }
                }
                giftsByType[group] = gifts;
            }
            else {
                for (var i = 0; i < GiftTypes.length; i++) {
                    if (GiftTypes[i][3] == group) {
                        gifts.push(GiftTypes[i]);
                    }
                }
                giftsByType[group] = gifts;
            }
    }
    else {
        gifts = GiftTypes;
    }
    return gifts;
}

function cmpGifts(a, b){
    if (sort == 'pop_d') {
        return b[4] - a[4];
    } else if (sort == 'pop_a') {
        return a[4] - b[4];
    } else if (sort == 'name_a') {
        return a[2].localeCompare(b[2]);
    } else if (sort == 'name_d') {
        return b[2].localeCompare(a[2]);
    } else {
        return b[4] - a[4];
    }
}

function showGifts(group, page, sortBy){
    if (sortBy != undefined) {
        sort = sortBy;
    }
    var div = $('gifts_gr' + group + '_' + page + '_' + sort);
    if (div == null) {
        var gifts = getGiftGroup(group);
        gifts.sort(cmpGifts);
		div = new Element('div', {id: 'gifts_gr' + group + '_' + page + '_' + sort}).hide();
        $('giftsContainer').appendChild(div);
        var st = '<table style="margin:0 0 20px 0;">';
        var start = (page - 1) * per_page;
        var end = start + per_page;
        if (end > gifts.length) {
            end = gifts.length;
        }
        for (var i = start; i < end; i++) {
            if (i % 4 == 0)
                st += '<tr>';
            st += '<td width=25% valign="top" align="left"><table cellpadding=0 cellspacing=2><tr><td></td>';
            st += '<td><label for="gr' + group + 'gift_id_' + gifts[i][0] + '"><img src="http://img3.imgsmail.ru/r/my/gifts/';
            st += gifts[i][1] + '" onclick="$(\'gr' + group + 'gift_id_' + gifts[i][0] + '\').checked=true;" /></label></td></tr>';
            st += '<tr><td valign="top"><input type="radio" id="gr' + group + 'gift_id_' + gifts[i][0] + '" name="gift_id"';
            st += ' value="' + gifts[i][0] + '"></td><td valign="top"><label for="gr' + group + 'gift_id_' + gifts[i][0] + '">';
            st += '<span class=v>' + gifts[i][2] + '</span></label></td></tr></table></td>';
            if (i % 4 == 3)
                st += '</tr><tr><td>&nbsp;</td></tr>';
        }
        st += '</table>';
        div.update(st);
    }
    $(cur_gifts).hide();
    div.show();
    showTabs(group);
    showPageNav(group, page);
    cur_gifts = div.id;
    return false;
}

function showTabs(group){
    var st = '';
    for (var i = 0; i < grNames.length; i++) {
        st += '<span>';
        st += ('' + group == '' + grNames[i][0]) ? '<b>' + grNames[i][1] + '</b>' : getLink(grNames[i][0], 1, grNames[i][1]);
        st += '</span>';
    }
    st += ' <span class="sort">Сортировать:&nbsp;';
    var cl = (sort == 'pop_a' ? 'bold_d' : '') + (sort == 'pop_d' ? 'bold_a' : '');
    st += '<span' + (cl == '' ? '' : ' class="' + cl + '"') + '>' + getLink(group, 1, 'По&nbsp;популярности', sort == 'pop_d' ? 'pop_a' : 'pop_d') + '</span>';
    st += '&nbsp;|&nbsp;';
    cl = (sort == 'name_a' ? 'bold_d' : '') + (sort == 'name_d' ? 'bold_a' : '');
    st += '<span' + (cl == '' ? '' : ' class="' + cl + '"') + '>' + getLink(group, 1, 'По&nbsp;имени', sort == 'name_a' ? 'name_d' : 'name_a') + '</span>';
    st += '</span>';
    $('groups').update(st);
}

function showPageNav(group, page){
    var len = getGiftGroup(group).length;
    if (len <= per_page) {
        $('pageNav').update('');
        return;
    }
    var st = '<table width=100% class="mt10 mb20" style="clear:left;"><tr><td nowrap style="padding-left:10px">';
    if (page > 1) {
        st += getLink(group, page - 1, '<span class=t110><b>&#0139;</b></span>&nbsp;Назад');
    }
    for (var i = 1; i < len / per_page + 1; i++) {
        if (i == page) {
            st += '<b>&middot; ' + page + ' &middot;</b>';
        }
        else {
            st += '&nbsp;' + getLink(group, i, i) + '&nbsp;';
        }
    }
    if (page < len / per_page) {
        st += getLink(group, page + 1, 'Далее&nbsp;<span class=t110><b>&#0155;</b></span>');
    }
    st += '</td></tr></table>';

    $('pageNav').update(st);
}

function getLink(group, page, text, sortBy){
    if (sortBy == undefined) {
        sortBy = sort;
    }
    var st = '<a href="gifts?send=' + sendTo + '&group=' + group + '&page=' + page + '&sort=' + sortBy + '"';
    st += ' onclick="return showGifts(\'' + group + '\',' + page + ',\'' + sortBy + '\')">' + text + '</a>';
    return st;
}

function gift_send_checkCtrlEnter(evt){
    checkCtrlEnter(evt,'giftSend');
}

/*
 * {main.tmpl}
 */
function main_count_symbols(){
    num = $('comment_text').value.length;
    digit = num % 10;
    dig = 'символов';
    ent = 'Введено';
    switch (digit) {
        case 1:
            dig = 'символ';
            ent = 'Введен';
            break;
        case 2:
            dig = 'символа';
            break;
        case 3:
            dig = 'символа';
            break;
    }
    digit = num % 100;
    if (digit > 10 && digit < 20) {
        dig = 'символов';
        ent = 'Введено';
    }
    $('text_symbols').update(ent + ': ' + num + ' ' + dig + ' (максимум 4000)');
    if (num > 4000) {
        $('text_symbols').style.color = '#C00'
    }
    if (num <= 4000) {
        $('text_symbols').style.color = '#CCC'
    }
}

function main_dis_sub_but(){
    var val = $F("comment_text");
    var sub_but = $("sub_but");
    if (val != "") {
        $('cont_div_check').hide();
        sub_but.value = "Идет отправка";
        sub_but.disable();
        return true;
    }
    else {
        return false;
    }
}

function add_comment(obj){
    max_len = 4000;
    len = obj.comment_text.value.length;
    if (len > max_len) {
        alert("Вы пытаетесь отправить " + len + " символов. Максимально разрешённая длина " + max_len + " символов.")
        return false;
    }
    else {
        main_dis_sub_but();
        return true;
    }
}

/*
 * {blocks/top_my.tmpl}
 */
function oldOperaMessage(is_opera){
    if (is_opera == 1) {
        document.writeln('<div class="mt10 mb10">Ваш браузер (Opera версии 8.51 или ниже) не позволяет вам использовать все функции проекта Мой Мир@Mail.Ru в полном объеме. Чтобы воспользоваться полнофункциональным поиском людей или заполнить анкету, пожалуйста, воспользуйтесь другим браузером или обновите версию текущего браузера.<\/div>');
    }
}

/**
 * функция для отображения popup окна, при нажатии на ссылку  "увеличить" под аватаром
 * @param {String} Url
 */
function popup_larger(Url){
    if (popup_l)
        popup_l.close();
    popup_l = window.open(Url, 'popup', 'width=580,height=580,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 580) / 2 + ',top=' + (screen.height - 580) / 2);
    if (popup_l)
        popup_l.focus();
}

function show_help(event, help_text){
    if (!event)
        event = window.event;
    var element = event.target || event.srcElement;
    var div = $("help_div");
    if (element && div) {
        var coor = get_position(element);
        div.update("<a onclick=\"return clear_help()\" href=\"\"><img src=http://img0.imgsmail.ru/mail/ru/images/blogs/close_help.gif height=7 width=7 align=right><\/a><br>" + help_text);
        div.className = "help_div";
		div.setStyle({
			top: coor.top + element.offsetHeight + 'px',
			left: coor.left + 'px',
			display: 'block',
			visibility: 'visible'
		});
        event.cancelBubble = true;
    }
    return false;
}

function clear_help(){
    var div = $("help_div");
    if (div) {
        div.className = "help_div";
        div.hide();
    }
    return false;
}

function get_position(offsetTrail){
    var offsetLeft = 0;
    var offsetTop = -11;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    return {
        left: offsetLeft,
        top: offsetTop
    }
}

function add_photo_to_message(){
    //if (popup) popup.close();
    popup = window.open('http://'+PhotoImagineHost+'/cgi-bin/photo/addphoto?guestbook=1&Title=&My=1', 'add_pict', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}

function add_video_to_message(){
    popup = window.open('http://'+VideoPerlHost+'/cgi-bin/photo/addvideo?guestbook=1=', 'add_vid', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}

function add_photo(type){
    var params = {
	'mydialog':{
	    'width':600,'height':660,'toolbars':'no','scrollbars':'yes','resizable':'yes',
	    'left':(screen.width-660)/2,'top':(screen.height-660)/2
	},
	'mycommunitycontest':{
	    'width':600,'height':660,'toolbars':'no','scrollbars':'yes','resizable':'yes',
	    'left':(screen.width-660)/2,'top':(screen.height-660)/2
	}
    };
    if(!type) type = 'mydialog';
    popup = window.open('http://' + PhotoImagineHost + '/cgi-bin/photo/addphoto?' + type + '=1&My=1', 'add_pict',
	(new Hash(params[type])).map(function(v){ return v.join('=') }).join(','));
    if (popup) popup.focus();
}

function add_video(){
    popup = window.open('http://'+VideoPerlHost+'/cgi-bin/photo/addvideo?mydialog=1&Title=', 'add_vid', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}

function add_paint(){
	popup = window.open('http://'+ PaintshopHost + '/paintshop/prj_my/popup_edit.html', 'add_paint', 'width=1000,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 1000) / 2 + ',top=' + (screen.height - 660) / 2);
	if (popup) popup.focus();
}

function view_paint (url) {
	popup = window.open(url, 'view_paint', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
	if (popup) popup.focus();		
}

function embed_mp3_player(URL){
    // Get Operating System
    var isWin = navigator.userAgent.toLowerCase().indexOf("windows") != -1;
    if (isWin) { // Use MIME type application/x-mplayer2
        visitorOS = "Windows";
    }
    else { // Use MIME type audio/mpeg, audio/x-wav, etc.
        visitorOS = "Other";
    }

    var objTypeTag = "application/x-mplayer2"; // The MIME type to load the WMP plugin in non-IE browsers on Windows
    if (visitorOS != "Windows") {
        objTypeTag = "audio/mpeg"
    }; // The MIME type for Macs and Linux
    document.writeln("<div>");
    document.writeln("<object width='280' height='69'>"); // Width is the WMP minimum. Height = 45 (WMP controls) + 24 (WMP status bar)
    document.writeln("<param name='type' value='" + objTypeTag + "'>");
    document.writeln("<param name='src' value='" + URL + "'>");
    document.writeln("<param name='autostart' value='0'>");
    document.writeln("<param name='showcontrols' value='1'>");
    document.writeln("<param name='showstatusbar' value='1'>");
    document.writeln("<embed src ='" + URL + "' type='" + objTypeTag + "' autoplay='false' autostart='0' width='280' height='69' controller='1' showstatusbar='1' bgcolor='#ffffff'></embed>");

    // Firefox and Opera Win require both autostart and autoplay
    document.writeln("</object>");
    document.writeln("</div>");
}

/*
 * {blocks/menu_alert.html}
 */
function downloadfoto(){
    var popupwin = window.open("http://foto.mail.ru/cgi-bin/photo/addphoto?myphoto=1&mode=1&Title=", "dlphoto", "height=650,width=600,scrollbars=no");
    return false;
}

function openPopUp(src, width, height){
    var videoperlhost = "video.mail.ru";
    var _width = width;
    var _height = height;
    var top = 0;
    var left = (widthwindow - _width) / 2;
    var path = 'http://r.mail.ru/cln4235/' + videoperlhost + '/' + src;
    var newWin = window.open(path, '_new', 'width=' + _width + ',height=' + _height + ',top=' + top + ',left=' + left + ',resizable');
}

/*
 * {blocks/menu_career.html}
 */
function switchNeedJob(){
    var need_job = $('need_job_id');
    var job_group = $('job_group_id');
    var submit_cont = $('job_submit_container');
    var current_job_group = $('current_job_group');
    var job_submit = $('job_group_submit_button');

    submit_cont.show();
    if (need_job.checked) {
        job_submit.show();
        job_group.show();
    }
    else {
        job_submit.hide();
        job_group.hide();
    }
}

function submitNeedJob(){
    var need_job = $('need_job_id');
    var job_group = $('job_group_id');
    if (need_job.checked && !job_group.value) {
        alert('Ошибка: не указана группа специальностей');
        return false;
    }
    else {
        return true;
    }
}

function checkCheckBox(objname){
    var ch = $(objname);
    if (ch.checked) {
        ch.checked = '';
    }
    else {
        ch.checked = true;
    }
}

/*
 * {blocks/menu_items.tmpl}
 */
function changeMenu(id){
    var divmenu = new Array('ww', 'hh', 'ss', 'pp');
    for (i = 0; i < divmenu.length; i++) {
        myid = divmenu[i] + 'c';
        zid = divmenu[i] + 'z';
        if ($(divmenu[i])) {
            if (divmenu[i] == id) {
                $(divmenu[i]).className = 'filtr_act';
                $(myid).show();
                $(zid).show();
            }
            else {
                $(divmenu[i]).className = 'filtr';
                $(myid).hide();
                $(zid).hide();
            }
        }
    }
}

/*
 * {menu_gifts.html}
 */
function changePres(id){
    var divmenu = new Array('valen', 'usual');
    for (i = 0; i < divmenu.length; i++) {
        myid = divmenu[i] + 'c';
        if ($(divmenu[i])) {
            if (divmenu[i] == id) {
                $(divmenu[i]).className = 'zak_act';
                $(myid).show();
            }
            else {
                $(divmenu[i]).className = 'zak';
                $(myid).hide();
            }
        }
    }
}

/*
 * {blocks/menu_guestbook.html}
 */
function showSpamComplaintDiv(el, id, email){
    ajax_call('perl_is_friend', email, id, FriendComplaint);
    var div = $('SpamComplaintDiv');
    div.style.top = absPosition(el).y + el.offsetHeight;
    div.style.left = absPosition(el.parentNode).x;
    document.complaint.gb_message.value = id;
    document.complaint.spamer.value = email;
    $("message").checked = true;
    div.show();
    return false;
}

function menu_guestbook_checkCtrlEnter(evt){
    checkCtrlEnter(evt, 'reply', null);
}

function recurs(obj){
    if (obj.nodeType != 3 && obj.childNodes) {
        var childs = obj.childNodes;
        var cn = childs.length;
        var i;
        for (i = 0; i < cn; i++) {
            if (childs[i].nodeType == 1) {
                if (childs[i].tagName.toUpperCase() == 'IMG') {
                    if (childs[i].offsetWidth > 465) {
                        childs[i].style.width = 470;
                    }
                }
                else {
                    if (childs[i].childNodes.length > 0)
                        recurs(childs[i]);
                }
            }
        }
    }
}

/*
 * {blocks/right_my.html}
 */
function message(){
    var widthwindow = document.body.clientWidth;
    if (widthwindow < 1132) {
        $('tt').style.width = '226';
        $('g').show();
        $('gg').hide();
    }
    else {
        $('tt').style.width = '342';
        $('g').hide();
        $('gg').show();
    }
}

/*
 * {gift.tmpl}
 */
function gift_showSpamComplaintDiv(el, id){
    var div = $('SpamComplaintDiv');
    var p = getPosition(el);
    div.style.top = p.top + el.offsetHeight;
    div.style.left = p.left;
    document.complaint.gift.value = id;
    div.show();
    return false;
}
/*
 * {guestbook.tmpl}
 */
function showAddForm(a){
    var parent = a.parentNode;
    var div = $('cont_div_check').cloneNode(true);
    $('cont_div_check').parentNode.removeChild($('cont_div_check'));
    parent.insertBefore(div, a.nextSibling);
    $('cont_div_check').show();
    document.forms['reply'].elements['comment_text'].focus();
    //alert(div.innerHTML);
    return false;
}

function guestbook_dis_sub_but(){
    var val = $F("comment_text");
    var sub_but = $("sub_but");
    if (val != "") {
        $('cont_div_check').hide();
        sub_but.value = "Идет отправка";
        sub_but.disable();
        return true;
    }
    else {
        return false;
    }
}

function guestbook_showSpamComplaintDiv(el, id, email){
    ajax_call('perl_is_friend', email, id, FriendComplaint);
    var div = $('SpamComplaintDiv');
    div.style.top = absPosition(el).y + el.offsetHeight;
//  div.style.left = absPosition(el.parentNode).x - (el.offsetWidth*15);
    document.complaint.gb_message.value = id;
    document.complaint.spamer.value = email;
    <!-- IF Owner || IsActiveCommunityOwner || IsActiveCommunityModerator && !(Eq2(.PosterEmail, grishin@mail.ru) || Eq2(.PosterEmail, myadmin@corp.mail.ru) || Eq2(.PosterEmail, my@corp.mail.ru)) -->$("message").checked = true;<!-- /IF Owner || IsActiveCommunityOwner || IsActiveCommunityModerator && !(Eq2(.PosterEmail, grishin@mail.ru) || Eq2(.PosterEmail, myadmin@corp.mail.ru) || Eq2(.PosterEmail, my@corp.mail.ru)) -->
    div.show();
    return false;
}

//function FriendComplaint (UserStatus, UserName) {
//    if (UserStatus) {
//    $('ComplaintButton').value="OK";
//    $('ComplaintText').firstChild.data="Удалить " + UserName + " из списка друзей и отправить жалобу на спам?";
//    $('friendship').value="die";
//    } else {
//    $('ComplaintButton').value="Подтвердить жалобу на спам";
//    $('ComplaintText').firstChild.data="";
//    $('friendship').value="live";
//    }
//}

function subscribe(t){
    if (t) {
        var data = t.responseText.evalJSON(true);
        if (data[1] == 'OK') {
            var link = $('subscribeA');
            var image = $('subscribeImg');
            var text = $('subscribeText');
            if (subscribe_is_subscribed) {
                subscribe_is_subscribed = 0;
                text.update('Подписаться на обновления');
                image.src = 'http://img1.imgsmail.ru/r/blogs/ico_subscribe_2.png';
            }
            else {
                subscribe_is_subscribed = 1;
                text.update('Отписаться от обновлений');
                image.src = 'http://img2.imgsmail.ru/r/blogs/ico_unsubscribe.png';
            }
            subscribe_in_request = 0;
        }
    }
    else {
        if (subscribe_in_request) {
            return;
        }
        subscribe_in_request = 1;
        var req = subscribe_is_subscribed ? 'unsubscribe' : 'subscribe';
        new Ajax.Request('http://my.rapira.mail.ru/cgi-bin/my/ajax', {
            method: 'post',
            parameters: {
                ajax_call: 1,
                func_name: 'perl_subscribe_community_guestbook',
                data:[subscribe_journal,req] .toJSON()
            },
            onSuccess: subscribe
        });
    }
}

function guestbook_add_comment(obj){
    max_len = 1000;
    len = obj.comment_text.value.length;
    if (len > max_len) {
        alert("Вы пытаетесь отправить " + len + " символов. Максимально разрешённая длина " + max_len + " символов.")
        return false;
    }
    else {
        guestbook_dis_sub_but();
        return true;
    }
}

function guestbook_checkCtrlEnter(evt){
    checkCtrlEnter(evt, 'reply');
}

function guestbook_count_symbols(){
    num = $F('comment_text').length;
    digit = num % 10;
    dig = 'символов';
    ent = 'Введено';
    switch (digit) {
        case 1:
            dig = 'символ';
            ent = 'Введен';
            break;
        case 2:
            dig = 'символа';
            break;
        case 3:
            dig = 'символа';
            break;
    }
    digit = num % 100;
    if (digit > 10 && digit < 20) {
        dig = 'символов';
        ent = 'Введено';
    }
    $('text_symbols').update(ent + ': ' + num + ' ' + dig + ' (максимум 1000)');
    if (num > 1000) {
        $('text_symbols').style.color = '#C00'
    }
    if (num <= 1000) {
        $('text_symbols').style.color = '#CCC'
    }
}

//function setFocus(form, field){
//    document.form.field.focus();
//}

/*
 * {blocks/top_base_my.html}
 */
function uPicOver(span){
    var avatarPath, img;
    avatarPath = "http://" + PhotoAvtHost + "/";
    img = $("forUserPicShow");
    img.src = avatarPath + span.id + "/_avatar";
    img.style.top = absPosition(span).y + span.offsetHeight;
    img.style.left = absPosition(span).x;
    img.show();
}

function uPicOut(span){
    var img;
    var img = $("forUserPicShow");
    img.hide();
    img.src = "wait.gif";
}

function check_winsize(){
    var size;
    if (document.all)
        size = window.document.body.clientWidth;
    else
        size = window.innerWidth;
    if (size > 820) {
        $("resize_img").width = size * 0.05;
        $("zapis_div").style.width = size * 0.63;
    }
    else {
        $("resize_img").width = 1;
        $("zapis_div").style.width = 500;
    }
}

function show_add_to_friends_on_load(){
    if (window.location.search.indexOf('show_add_to_friend=1') >= 0)
        show_friend_group_selector('for_friend_group_selector', JournalEmail);
}

/*
 * {history.tmpl}
 */
function history_less_disabled(){
    if (disableness == 1) {
        $('submit_' + mode + (editing == 1 ? '_edit' : '_insert')).enable();
    }
    disableness = 0;
}

function history_form_empty(level){
    //alert('form empty -> '+level);
    var suff = '';
    var _editing = editing;
    if (_editing == 1)
        suff = '_edit';
    if (level < 1) {
        if (mode == 'school') {
            $('startdate_' + mode + suff).value = '';
        }
        if (mode == 'vuz' || mode == 'ssuz') {
            $('kurs_' + mode + suff).selectedIndex = 0;
        }
        $('enterdate_' + mode + suff).value = '';
        $('leavedate_' + mode + suff).value = '';
    }
    if (level < 2) {
        $('region_id_' + mode + suff).options.length = 1;
        $('region_id_' + mode + suff).options[0].value = '';
        $('region_id_' + mode + suff).selectedIndex = 0;
        $('region_id_' + mode + suff).disable();
    }
    if (level < 3) {
        $('city_id_' + mode + suff).options.length = 1;
        $('city_id_' + mode + suff).options[0].value = '';
        $('city_id_' + mode + suff).selectedIndex = 0;
        $('city_id_' + mode + suff).disable();
    }
    if (level < 4) {
        $('institute_id_' + mode + suff).options.length = 1;
        $('institute_id_' + mode + suff).options[0].value = '';
        $('institute_id_' + mode + suff).selectedIndex = 0;
        $('institute_id_' + mode + suff).disable();
    }
    if (level < 5 && (mode == 'vuz' || mode == 'ssuz')) {
        $('department_id_' + mode + suff).options.length = 1;
        $('department_id_' + mode + suff).options[0].value = '';
        $('department_id_' + mode + suff).selectedIndex = 0;
        $('department_id_' + mode + suff).disable();
    }
    if (level < 6 && (mode == 'vuz' || mode == 'ssuz')) {
        $('kafedra_id_' + mode + suff).options.length = 1;
        $('kafedra_id_' + mode + suff).options[0].value = '';
        $('kafedra_id_' + mode + suff).selectedIndex = 0;
        $('kafedra_id_' + mode + suff).disable();
    }
}

function history_FillGeo(names, ids, type, level, special){
    //alert(names.length+' '+type+' '+level);
    var suff = "";
    var no_list = 0;
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";

    var list;
    if (type == 1) {
        list = $('country_id_' + mode + suff);
        list.enable();
        history_form_empty(1);
    }
    else
        if (type == 2) {
            history_form_empty(2);
            list = $('region_id_' + mode + suff);
            $('region_id_' + mode + suff).enable();
            $('city_id_' + mode + suff).disable();
            $('city_id_' + mode + suff).options.length = 1;
            $('city_id_' + mode + suff).options[0].value = '';
            $('city_id_' + mode + suff).options[0].text = 'Выбрать';
        }
        else
            if (type == 3) {
                if (level != 3) { // Not a Russia, disabling region menu
                    $('region_id_' + mode + suff).options.length = 0;
                    $('region_id_' + mode + suff).options[0] = new Option('Выбрать', '');
                    $('region_id_' + mode + suff).disable();
                }
                history_form_empty(3);
                $('city_id_' + mode + suff).enable();
                list = $('city_id_' + mode + suff);

            }
            else {
                no_list = 1;
                $('city_id_' + mode + suff).options.length = 0;
                $('city_id_' + mode + suff).options[0] = new Option('Другое', 'other');
                $('city_id_' + mode + suff).enable();
                $('city_id_' + mode + suff + '_other').show();

                $('institute_id_' + mode + suff).options[0] = new Option('Другое', 'other');
                $('institute_id_' + mode + suff).enable();
                $('institute_id_' + mode + suff + '_other').show();

                if (mode == 'vuz' || mode == 'ssuz') {
                    $('department_id_' + mode + suff).options[0] = new Option('Другое', 'other');
                    $('department_id_' + mode + suff).enable();
                    $('department_id_' + mode + suff + '_other').show();

                    $('kafedra_id_' + mode + suff).options[0] = new Option('Другое', 'other');
                    $('kafedra_id_' + mode + suff).enable();
                    $('kafedra_id_' + mode + suff + '_other').show();
                }
            }
    if (no_list == 0) {
        var nl = 0;
        if (names != undefined)
            nl = names.length;

        list.options.length = 0;
        var addon = 0;
        //if (editing != 1) {
        list.options[0] = new Option('Выбрать', '');
        addon = 1;
        //}
        for (var i = 0; i < nl; i++) {
            list.options[i + addon] = new Option(names[i], ids[i]);
            if (special > 0) {
                list.options[i + addon].style.fontWeight = "bold";
                special--;
            }
        }


        if (type == 3) {
            list.options[list.options.length] = new Option('Другое', 'other');
            if (is_capital == 1) {//set default city -> capital
                //alert('set capital ' + is_capital);
                list.selectedIndex = 1;
                list.onchange();
            }
        }
        if (type == 1)//set default country -> Russia
        {
            list.selectedIndex = 1;
            list.onchange();
        }
        if (need_switch_star) {
            history_switchStarOfFieldCallback();
        }
    }
    history_less_disabled();
}

function history_FillStudies(names, ids){
    history_form_empty(4);
    //alert('history_FillStudies -> '+names);
    if (editing == 1) {
        history_showHideStudyObject(mode + 'edit', 1);
    }
    else {
        history_showHideStudyObject(mode, 1);
    }

    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var list = $("institute_id_" + mode + suff);
    list.enable();
    var nl = 0;
    if (names != undefined)
        nl = names.length;
    list.options.length = 0;
    var addon = 0;
    //if (editing != 1) {
    list.options[0] = new Option('Выбрать', '');
    list.options[1] = new Option('Поиск по списку', 'other');
    list.options[1].style.fontWeight = "bold";
    list.selectedIndex = 0;
    addon = 2;
    //}
    for (i = 0; i < nl; i++) {
        names[i].length > 73 ? html_escape(names[i].slice(0, 70) + '...') : html_escape(names[i]);
        list.options[i + addon] = new Option(names[i].length > 73 ? names[i].slice(0, 70) + '...' : names[i], ids[i]);
    }
    list.options[list.options.length] = new Option('Другое', 'other');
    institutions = 0;
    institutions = names;
    var ab = ab_get(list);
    ab.draw();
    history_less_disabled();
}

function history_FillDepartments(names, ids){
    history_form_empty(5);
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var list = $("department_id_" + mode + suff);
    list.enable();
    var nl = 0;
    if (names != undefined)
        nl = names.length;
    list.options.length = 0;
    var addon = 0;
    //if (editing != 1) {
    list.options[0] = new Option('Выбрать', '');
    list.selectedIndex = 0;
    addon = 1;
    //}
    for (i = 0; i < nl; i++) {
        list.options[i + addon] = new Option(names[i].length > 73 ? names[i].slice(0, 70) + '...' : names[i], ids[i]);
    }
    list.options[list.options.length] = new Option('Другое', 'other');
    history_less_disabled();
}

function history_FillKafedra(names, ids){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var list = $("kafedra_id_" + mode + suff);
    list.enable();
    var nl = 0;
    if (names != undefined)
        nl = names.length;
    list.options.length = 0;
    var addon = 0;
    //if (editing != 1) {
    list.options[0] = new Option('Выбрать', '');
    list.selectedIndex = 0;
    addon = 1;
    //}
    for (i = 0; i < nl; i++) {
        list.options[i + addon] = new Option(names[i].length > 73 ? names[i].slice(0, 70) + '...' : names[i], ids[i]);
    }
    list.options[list.options.length] = new Option('Другое', 'other');
    history_less_disabled();
}

function history_FillList(oid, names, ids, sid){
    //alert('history_FillList -> '+oid+' - '+names);
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    //alert("history_FillList |"+oid+mode+suff+"|");
    var list = $(oid + mode + suff);
    if (list == undefined || list == null)
        return;
    if (names == '0' || names == 0) {
        list.disable();
        return;
    }
    //alert("history_FillList running "+names);
    list.enable();
    var nl = 0;
    if (names != undefined)
        nl = names.length;
    list.options.length = 0;
    var addon = 0;
    if (editing != 1) {
        list.options[0] = new Option('Выбрать', '');
        list.selectedIndex = 0;
        addon = 1;
    }
    if (editing == 1 && (oid == 'department_id_' || oid == 'kafedra_id_')) {
        list.options[0] = new Option('Не выбрано', '');
        list.selectedIndex = 0;
        addon = 1;
    }
    if (editing == 1 && (oid == 'institute_id_')) {
        list.options[0] = new Option('Поиск по списку', 'other');
        list.options[0].style.fontWeight = "bold";
        addon = 1;
    }
    for (var i = 0; i < nl; i++) {
        list.options[i + addon] = new Option(names[i], ids[i]);
        if (ids[i] == sid)
            list.options[i + addon].selected = 'selected';
    }
    if (oid == 'city_id_' || oid == 'institute_id_' || oid == 'department_id_' || oid == 'kafedra_id_') {
        var le = list.options.length;
        list.options[le] = new Option('Другое', 'other');
        if (le == 0) {
            var elem = $(oid + mode + suff + '_other');
            if (elem != undefined)
                elem.show();
        }
    }
    if (editing == 1 && (oid == 'institute_id_')) {
        institutions = 0;
        institutions = names;
    }
}

function history_CheckList(oid, sid){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var list = $(oid + mode + suff);
    if (list == undefined || list == null)
        return;
    list.enable();
    for (var i = 0; i < list.options.length; i++) {
        if (list.options[i + 1].value == sid)
            list.options[i + 1].selected = 1;
    }
}


function history_FillField(oid, valu){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var field = $(oid + mode + suff);
    if (field == undefined || field == null)
        return;
    field.value = valu;
}

function history_FillSelect(oid, valu){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var field = $(oid + mode + suff);
    if (field == undefined || field == null)
        return;
    for (var i = 0; i < field.options.length; i++) {
        if (field.options[i].value == valu) {
            field.selectedIndex = i;
            return;
        }
    }
}

function history_FillEdit(eId, cNames, cIds, cId, rNames, rIds, rId, tNames, tIds, tId, instNames, instIds, instId, facNames, facIds, facId, subfacNames, subfacIds, subfacId, supName, kurs, startDate, enterDate, leaveDate){
    //ajax perl_fetch_edu callback, filling edit form
    //receiving all data, checked.
    history_FillSelect('startdate_', startDate);
    history_FillSelect('enterdate_', enterDate);
    history_FillSelect('leavedate_', leaveDate);
    history_FillField('ab_compose_supname', supName, 0);
    history_FillField('eid_', eId, 0);

    history_FillList('country_id_', cNames, cIds, cId);
    history_FillList('region_id_', rNames, rIds, rId);
    if (need_switch_star) {
        history_switchStarOfFieldCallback();
    }
    history_FillList('city_id_', tNames, tIds, tId);
    history_FillList('institute_id_', instNames, instIds, instId);
    history_FillList('department_id_', facNames, facIds, facId);
    history_FillList('kafedra_id_', subfacNames, subfacIds, subfacId);
    history_FillSelect('kurs_', kurs);
    $('submit_' + mode + (editing == 1 ? '_edit' : '_insert')).enable();
}

function history_ChooseOtherObj(oid){
    var list = $(oid);
    if (list.disabled == 1)
        return;
    list.selectedIndex = list.options.length - 1;
    list.onchange();
}

function history_switchStarOfField(fieldName, starName){
    star_field = fieldName;
    star_name = starName;
    need_switch_star = true;
}

function history_switchStarOfFieldCallback(){
    if ($(star_field).disabled == 0) {
        $(star_name).className = 'red';
    }
    else {
        $(star_name).className = 'white';
    }
    need_switch_star = false;
}

function history_CheckFieldByNull(formName, fieldName, errorText){
    if (formName && formName.elements[fieldName] && !formName.elements[fieldName].value) {
        return errorText;
    }
    else {
        return '';
    }
}

function history_CheckFormByNull(formName){
    history_more_disabled();
    var errors = "";
    if (editing == 1) {
        suff = "_edit";
    }
    else {
        suff = "";
    }
    switch (mode) {
        case 'school':
            institute_field_name = "ШКОЛА";
            institute_field_name_another = "НОМЕР ШКОЛЫ";
            enterdate_field_name = "НАЧАЛО ОБУЧЕНИЯ";
            break;
        case 'vuz':
            institute_field_name = "ИНСТИТУТ";
            institute_field_name_another = "ДРУГОЙ ИНСТИТУТ";
            enterdate_field_name = "НАЧАЛ УЧИТЬСЯ В";
            break;
        case 'ssuz':
            institute_field_name = "КОЛЛЕДЖ ИЛИ ПТУ";
            institute_field_name_another = "ДРУГОЙ КОЛЛЕДЖ ИЛИ ПТУ";
            enterdate_field_name = "НАЧАЛ УЧИТЬСЯ В";
            break;
    }

    /*errors +=history_CheckFieldByNull(formName,'country_id',"Поле СТРАНА не заполнено\n");
     if(formName.elements['region_id'].disabled != 1)
     {
     errors +=history_CheckFieldByNull(formName,'region_id',"Поле РЕГИОН не заполнено\n");
     }
     errors +=history_CheckFieldByNull(formName,'city_id',"Поле ГОРОД не заполнено\n");*/
    if (formName.elements['city_id'].value == 'other') {
        errors += history_CheckFieldByNull(formName, 'city_name', "Поле ДРУГОЙ ГОРОД не заполнено\n");
    }

    errors += history_CheckFieldByNull(formName, 'institute_id', "Поле " + institute_field_name + " не заполнено\n");
    if (formName.elements['institute_id'].value == 'other') {
        if (formName.elements['supname'].value == "") {
            errors += "Поле " + institute_field_name_another + " не заполнено\n";
        }
    }
    /*
     if(formName.elements['department_id'])
     {
     errors +=history_CheckFieldByNull(formName,'department_id',"Поле ФАКУЛЬТЕТ не заполнено\n");
     if(formName.elements['department_id'].value == 'other')
     {
     errors +=history_CheckFieldByNull(formName,'department_name',"Поле ДРУГОЙ ФАКУЛЬТЕТ не заполнено\n");
     }
     }
     if(formName.elements['kafedra_id'])
     {
     errors +=history_CheckFieldByNull(formName,'kafedra_id',"Поле КАФЕДРА не заполнено\n");
     if(formName.elements['kafedra_id'].value == 'other')
     {
     errors +=history_CheckFieldByNull(formName,'kafedra_name',"Поле ДРУГАЯ КАФЕДРА не заполнено\n");
     }
     }
     */
    if (formName.elements['startdate']) {
        buff = history_CheckFieldByNull(formName, 'startdate', "Поле Я ПОШЁЛ В ПЕРВЫЙ КЛАСС не заполнено\n");
        if (buff != '') {
            errors += buff;
        }
        /*else {
         if(isNaN(formName.elements['startdate'].value) == true){
         errors += "В Поле Я ПОШЁЛ В ПЕРВЫЙ КЛАСС можно вводить только цифры\n";
         }
         if(formName.elements['startdate'].value.indexOf('+') == true || formName.elements['startdate'].value.indexOf('-') == true){
         errors += "В Поле Я ПОШЁЛ В ПЕРВЫЙ КЛАСС можно вводить только цифры положительные цифры\n";
         }
         */
    }
    //}
    if (formName.elements['leavedate']) {
        buff2 = history_CheckFieldByNull(formName, 'startdate', "err");
    }

    /*
     errors +=history_CheckFieldByNull(formName,'enterdate',"Поле " + enterdate_field_name + " не заполнено\n");
     errors +=history_CheckFieldByNull(formName,'leavedate',"Поле ОКОНЧАНИЕ ОБУЧЕНИЯ не заполнено\n");
     if(formName.elements['enterdate']!='' && isNaN(formName.elements['enterdate'].value)==true)
     {
     errors += "В Поле " + enterdate_field_name + " можно вводить только цифры\n";
     }
     if(formName.elements['leavedate']!='' && isNaN(formName.elements['leavedate'].value)==true)
     {
     errors += "В Поле ОКОНЧАНИЕ ОБУЧЕНИЯ можно вводить только цифры\n";
     }
     */
    if (mode == 'school') {
        //if(formName.elements['enterdate']!='' && isNaN(formName.elements['enterdate'].value)==false && formName.elements['leavedate']!='' && isNaN(formName.elements['leavedate'].value)==false)
        if (buff == '' && buff2 == '') {
            if (20 < (formName.elements['leavedate'].value - formName.elements['startdate'].value)) {
                errors += "Мы не верим, что Вы учились в школе более 20 лет!!! :)\n";
            }
        }
    }


    if (errors != null && errors != "") {
        alert(errors);
        history_less_disabled();
        return false;
    }
}

function history_showHideStudyObject(name, state){
    if (state == 1) {
        $(name + 'obj' + '1').show();
        $(name + 'obj' + '2').show();
    }
    else {
        $(name + 'obj' + '1').hide();
        $(name + 'obj' + '2').hide();
    }
}

function history_MessageSent(res){
    $('ok_mes').show();
}

//function makeother(sid) {
//    list=$(sid);
//    if (list == undefined) return;
//    list.disabled=0;
//    list.options.length=0;
//    list.options.length=list.options.length+1;
//    list.options[0].value='';
//    list.options[0].text='Не выбрано';
//    list.options.length=list.options.length+1;
//    list.options[1].value='other';
//    list.options[1].text='Другое';
//}

function history_onother(sid){
    if (sid == undefined || sid == '')
        return;
    suff = "";
    var dID = $('department_id_' + mode + suff + '_other');
    var kID = $('kafedra_id_' + mode + suff + '_other');
    if (editing == 1)
        suff = "_edit";
    if (sid.indexOf('city_id_') == 0) {
        makeother('institute_id_' + mode + suff);
        $('institute_id_' + mode + suff + '_other').hide();
        makeother('department_id_' + mode + suff);
        if(dID) dID.hide();
        makeother('kafedra_id_' + mode + suff);
	if(kID) kID.hide();
    }
    if (sid.indexOf('institute_id_') == 0) {
        makeother('department_id_' + mode + suff);
        if(dID) dID.hide();
        makeother('kafedra_id_' + mode + suff);
	if(kID) kID.hide();
    }
    if (sid.indexOf('department_id_') == 0) {
        makeother('kafedra_id_' + mode + suff);
	if(kID) kID.hide();
    }
}

function history_getNavi(){
    var navi = navigator.userAgent;
    var myobj = document.forms['helpform'].elements['browser'];
    myobj.value = navigator.userAgent + navigator.appVersion;
    var moreinfo = document.forms['helpform'].elements['other'];
    if (navigator.cookieEnabled) {
        moreinfo.value += ' cookie: ' + navigator.cookieEnabled;
    }
    if (navigator.cpuClass) {
        moreinfo.value += ' cpu: ' + navigator.cpuClass;
    }
    if (navigator.oscpu) {
        moreinfo.value += ' os_cpu: ' + navigator.oscpu;
    }
    if (navigator.javaEnabled()) {
        moreinfo.value += ' java: ' + navigator.javaEnabled();
    }
}

function history_onblock(sel, block_on){
    if (sel.value == 'other') {
        $(block_on).show();
        history_onother(sel.id);
    }
    else {
        $(block_on).hide();
    }
}

function history_change_div(obj, div){
	$(obj).hide();
	$(div).show();
	if (div == 'hd9') {
		if (!is_bad_opera && !is_bad_ff && !is_bad_ie) {
			document.helpform.text.focus();
		}
	}
}

function history_support(flag){
	if (flag == 1) 
		$('ok_mes').hide();
        $('send_mes_div').show();
        var i = 0;
        for (i = 1; i < 10; i++) {
            var a = 'hd' + i;
            $(a).hide();
        }
	$('faq_div').show();
}

function history_check(){
    if (!is_bad_opera && !is_bad_ff && !is_bad_ie) {
        if (document.helpform.text.value == '') {
            alert('Пожалуйста, опишите проблему!');
            document.helpform.text.focus();
            return false;
        }
        else {
            var text = document.helpform.text.value;
            var browser = document.helpform.browser.value;
            var js = document.helpform.js.value;
            var other = document.helpform.other.value;
            $('send_mes_div').hide();
            ajax_message_call(text, browser, js, other);
            return false;
        }
    }
    else {
        alert('Пожалуйста обновите браузер перед отсылкой сообщения!');
    }
}

function history_edit_school_to_orig(){
    if (editing_school == '')
        return;
    html = $(editing_school).innerHTML;
    if (html == undefined || html == '')
        return;
    $(editing_school).hide();
    $(editing_school).update('');
    $('orig_div_for_school').update(html);
    editing_school = '';
    editing = 0;
}

function edit_school_by_id(eid, sddis){
    if (editing == 1) {
        if (editing_school == 'div_for_school_' + eid)
            return false;
        history_edit_school_to_orig();
    }
    mode = 'school';
    editing = 1;
    suff = '_edit';
    src_div = 'orig_div_for_school';
    if (editing_school != '') {
        $(editing_school).hide();
        src_div = editing_school;
    }
    editing_school = 'div_for_school_' + eid;
    if (src_div == editing_school)
        return;
    html = $(src_div).innerHTML;
    if (html == undefined || html == '')
        return;
    $(src_div).update('');
    $(editing_school).update(html);
    history_form_empty(0);
    $(editing_school).show();
    history_switchStarOfField('region_id_school_edit', 'school_edit_star_reg');
    var olist = ['country_id_school_edit', 'region_id_school_edit', 'city_id_school_edit', 'institute_id_school_edit'];
    for (var i = 0; i < olist.length; i++) {
        $(olist[i]).length = 1;
        $(olist[i]).options[0].text = 'Загрузка...';
    }
    if ($F('country_id_' + mode + suff) != '24') {
        $('region_id_' + mode + suff).options[0].text = '';
    }
    else {
        $('region_id_' + mode + suff).options[0].text = 'Загрузка...';
    }

    ajax_edit_call(eid);
    //$('startdate_school_edit').disabled=sddis;
}

function history_add_school(){
    mode = 'school';
    editing = 0;
    if (($('school_table').visible()) && show_school != 1) {
        $('school_table').hide();
    }
    else {
        $('school_table').show();
        if (!add_geo_id || add > 0) {
            $("country_id_school").disable();
            $("country_id_school").options.length = 1;
            $("country_id_school").options[0].text = 'Загрузка...';
            ajax_geo_call(1);
        }
    }
}

function history_edit_vuz_to_orig(){
    if (editing_vuz == '')
        return;
    html = $(editing_vuz).innerHTML;
    if (html == undefined || html == '')
        return;
    $(editing_vuz).hide();
    $(editing_vuz).update('');
    $('orig_div_for_vuz').update(html);
    editing_vuz = '';
    editing = 0;
}

function history_edit_vuz_by_id(eid){
    if (editing == 1) {
        if (editing_vuz == 'div_for_vuz_' + eid)
            return false;
        history_edit_vuz_to_orig();
    }
    mode = 'vuz';
    editing = 1;
    src_div = 'orig_div_for_vuz';
    if (editing_vuz != '') {
        $(editing_vuz).hide();
        src_div = editing_vuz;
    }
    editing_vuz = 'div_for_vuz_' + eid;
    if (src_div == editing_vuz)
        return;
    html = $(src_div).innerHTML;
    if (html == undefined || html == '')
        return;
    $(src_div).update('');
    $(editing_vuz).update(html);
    history_form_empty(0);
    $(editing_vuz).show();
    history_switchStarOfField('region_id_vuz_edit', 'vuz_edit_star_reg');
    var olist = ['country_id_vuz_edit', 'region_id_vuz_edit', 'city_id_vuz_edit', 'institute_id_vuz_edit'];
    for (var i = 0; i < olist.length; i++) {
        $(olist[i]).length = 1;
        $(olist[i]).options[0].text = 'Загрузка...';
    }
    ajax_edit_call(eid);
}

function history_add_vuz(){
    mode = 'vuz';
    editing = 0;
    if ($('vuz_table').visible()) {
        $('vuz_table').hide();
    }
    else {
        $('vuz_table').show();
        if (!add_geo_id || add > 0) {
            $("country_id_vuz").disable();
            $("country_id_vuz").options.length = 1;
            $("country_id_vuz").options[0].text = 'Загрузка...';
            ajax_geo_call(1);
        }
    }
}

function history_edit_ssuz_to_orig(){
    if (editing_ssuz == '')
        return;
    html = $(editing_ssuz).innerHTML;
    if (html == undefined || html == '')
        return;
    $(editing_ssuz).hide();
    $(editing_ssuz).update('');
    $('orig_div_for_ssuz').update(html);
    editing_ssuz = '';
    editing = 0;
}

function history_edit_ssuz_by_id(eid){
    if (editing == 1) {
        if (editing_ssuz == 'div_for_ssuz_' + eid)
            return false;
        history_edit_ssuz_to_orig();
    }
    mode = 'ssuz';
    editing = 1;
    src_div = 'orig_div_for_ssuz';
    if (editing_ssuz != '') {
        $(editing_ssuz).hide();
        src_div = editing_ssuz;
    }
    editing_ssuz = 'div_for_ssuz_' + eid;
    if (src_div == editing_ssuz)
        return;
    html = $(src_div).innerHTML;
    if (html == undefined || html == '')
        return;
    $(src_div).update('');
    $(editing_ssuz).update(html);
    history_form_empty(0);
    $(editing_ssuz).show();
    history_switchStarOfField('region_id_ssuz_edit', 'ssuz_edit_star_reg');
    var olist = ['country_id_ssuz_edit', 'region_id_ssuz_edit', 'city_id_ssuz_edit', 'institute_id_ssuz_edit'];
    for (var i = 0; i < olist.length; i++) {
        $(olist[i]).length = 1;
        $(olist[i]).options[0].text = 'Загрузка...';
    }
    ajax_edit_call(eid);
}

function history_add_ssuz(){
    mode = 'ssuz';
    editing = 0;
    if ($('ssuz_table').visible()) {
        $('ssuz_table').hide();
    }
    else {
        $('ssuz_table').show();
        if (!add_geo_id || add > 0) {
            $("country_id_ssuz").disable();
            $("country_id_ssuz").options.length = 1;
            $("country_id_ssuz").options[0].text = 'Загрузка...';
            ajax_geo_call(1);
        }
    }
}

function history_printArray(array){
    var s_array = '';
    for (var i = 0; i < array.length; i++) {
        s_array += ' | ' + array[i] + ' | \n';
    }
    return s_array;
}

function history_setArrayForABcompose(mode){
    institutions = 0;//clear array with data
    //alert('setArray before');
    //alert('type a_school->'+typeof(a_school));

    var str = history_printArray(a_school);
    //alert('a_school-> \n'+str);
    switch (mode) {
        case 'school':
            institutions = a_school;
            break;
        case 'vuz':
            institutions = a_vuz;
            break;
        case 'ssuz':
            institutions = a_ssuz;
            break;
        default:
            //alert('setArray default');
            break;
    }
    //alert('setArray after');
}

function history_more_disabled(){
    disableness = 1;
    $('submit_' + mode + (editing == 1 ? '_edit' : '_insert')).disable();
}

/*
 * {invitation_single.tmpl}
 */
function invitation_single_checkCtrlEnter(evt){
    checkCtrlEnter(evt, 'frm_emails');
}

/*
 * {invitation.tmpl}
 */
function invitation_add_user(email){
    var edit = document.forms["frm_emails"].emails.value;
    if (document.forms["frm_emails"].emails) {
        if (edit != '')
            edit += ', ';
        edit += email;
        document.forms["frm_emails"].emails.value = edit;
        return true;
    }
    return false;
}

function invitation_parse_address_book(value){
    var values = value.split('|');
    for (var i = 0; i < values.length; i++) {
        if (values[i] != '')
            invitation_add_user(values[i]);
    }
}

function invitation_address_book(){
    var bName = navigator.appName;
    var bVer = parseInt(navigator.appVersion);
    if (!(bName == "Microsoft Internet Explorer" && bVer < 4)) {
        var width = 700;
        var height = 500;
        var posX = (screen.width - 700) / 2;
        var posY = (screen.height - 500) / 2;
        window.open("http://win.mail.ru/cgi-bin/addressbook?fromsearch=1&template=quicklist.tmpl&selectfunc=invitation_parse_address_book", "sw", "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=yes,top=" + posY + ",left=" + posX);
    }
    else {
        alert("This function is not available with MS IE 3.x");
    }
    return false;
}

function invitation_empty_check(){
    var text_len = document.forms.frm_emails.emails.value;
    if (text_len) {
        return true;
    }
    else {
        alert('Вы не ввели ни одного e-mail');
        return false;
    }
}

/*
 * {items_search.tmpl}
 */
function items_search_validateForm(){
    var error = new Array();
    var search_query = $('search_query_input').value.replace(/^\s+|\s+$/g, "");
    if (!search_query) {
        error[error.length] = 'Пустой поисковый запрос'
    }
    if (!$('search_type_wish_input').checked && !$('search_type_selling_input').checked &&
    !$('search_type_have_input').checked &&
    !$('search_type_presenting_input').checked) {
        error[error.length] = 'Не указан тип поиска'
    }
    if (error.length) {
        alert(error.join('\n'));
        return false;
    }
    else {
        return true;
    }
}

/*
 * {journal.tmpl}
 */
function journal_post_commentable4all(id){
    if (!has_javascript())
        return true;
    var url = ActionDir + "jscreencomment?user=" + JournalEmail +
    "&id=" +
    EntryID +
    "&xml=1";
    get_script(url);
    return false;
}

function journal_make_post_commentable4all(id){
    $("post_commentable4all_" + id).outerHTML = '';
}

function journal_black_list_confirm(url, action, username){
    if (action == "add") {
        if (confirm("Добавить " + username + " в Черный список? ")) {
            location = "http://" + BlogsPerlHost + "/" + url;
        }
    }
    else {
        if (confirm("Удалить " + username + " из Черного списка?")) {
            location = "http://" + BlogsPerlHost + "/" + url;
        }
    }
}

function journal_setFocus(form, field) {
    document.form.field.focus();
}

function journal_showAddForm(a){
    var parent = a.parentNode;
    var div = $('cont_div_check').cloneNode(true);
    $('cont_div_check').parentNode.removeChild($('cont_div_check'));
    parent.insertBefore(div, a.nextSibling);
    $('cont_div_check').show();
    document.forms['reply'].elements['comment_text'].focus();
    //alert(div.innerHTML);
    return false;
}

//function dis_sub_but() {
//    var val = document.getElementById("comment_text").value;
//    var sub_but = document.getElementById("sub_but");
//    if (val != "") {
//        gebi('cont_div_check').style.display='none';
//        sub_but.value = "Идет отправка";
//        sub_but.disabled = true;
//        return true;
//    } else {
//        return false;
//    }
//}

function journal_add_photo(){
    if (popup)
        popup.close();
    popup = window.open('http://'+PhotoImagineHost+'/cgi-bin/photo/addphoto?guestbook=1&Title=', 'add_pict', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}

function journal_add_video(){
    if (popup)
        popup.close();
    popup = window.open('http://'+VideoPerlHost+'/cgi-bin/photo/addvideo?guestbook=1', 'add_vid', 'width=600,height=660,toolbars=no,scrollbars=yes,resizable=yes,left=' + (screen.width - 660) / 2 + ',top=' + (screen.height - 660) / 2);
    if (popup)
        popup.focus();
}


function journal_add_comment(obj){
    max_len = 1000;
    len = obj.comment_text.value.length;
    if (len > max_len) {
        alert("Вы пытаетесь отправить " + len + " символов. Максимально разрешённая длина " + max_len + " символов.")
        return false;
    }
    else {
        dis_sub_but();
        return true;
    }
}

function journal_count_symbols(){
    num = $F('comment_text').length;
    digit = num % 10;
    dig = 'символов';
    ent = 'Введено';
    switch (digit) {
        case 1:
            dig = 'символ';
            ent = 'Введен';
            break;
        case 2:
            dig = 'символа';
            break;
        case 3:
            dig = 'символа';
            break;
    }
    digit = num % 100;
    if (digit > 10 && digit < 20) {
        dig = 'символов';
        ent = 'Введено';
    }
    $('text_symbols').update(ent + ': ' + num + ' ' + dig + ' (максимум 1000)');
    if (num > 1000) {
        $('text_symbols').style.color = '#C00'
    }
    if (num <= 1000) {
        $('text_symbols').style.color = '#CCC'
    }
}

/*
 * {menu_friends.html}
 */
function PopupContent(AgentCount, AddressCount, BlogsCount, FotoCount, AgentEmails, AddressEmails, BlogsEmails, FotoEmails){
    if (AgentCount > 0) {
        $('dAgentCount').show();
        $('AgentCount').value = AgentCount;
        $('agent_checkbox').value = AgentEmails;
        $('agent_checkbox_count').update(AgentCount);
    }
    if (AddressCount > 0) {
        $('dAddressCount').show();
        $('AdresCount').value = AddressCount;
        $('adres_checkbox').value = AddressEmails;
        $('adres_checkbox_count').update(AddressCount);
    }
    if (BlogsCount > 0) {
        $('dBlogsCount').show();
        $('BlogsCount').value = BlogsCount;
        $('blogs_checkbox').value = BlogsEmails;
        $('blogs_checkbox_count').update(BlogsCount);
    }
    if (FotoCount > 0) {
        $('dFotoCount').show();
        $('FotoCount').value = FotoCount;
        $('foto_checkbox').value = FotoEmails;
        $('foto_checkbox_count').update(FotoCount);
    }
}

function show_opacity(){
    var fader = $('popup_fader');
    var popup = $('popup');

    document.body.style.overflow = 'hidden';

    var top = ((document.body.clientHeight - 500) / 2);
    var left = ((document.body.clientWidth - 500) / 2)

    if (top < 10)
        top = 10;
    if (left < 10)
        left = 10;

    popup.style.left = left + 'px';
    popup.style.top = top + 'px';

    fader.show();
    popup.show();
    ajax_call('perl_friendship_popup', PopupContent);
}

function hide_opacity(){
    $('popup_fader').hide();
    $('popup').hide();
}

function addEmailField(){
    var ol = $("emailsList");
    var li = $("LI");
    var input = new Element("INPUT", {'name': 'Emails'});
	input.className = 'inp';
    li.appendChild(input);
    ol.appendChild(li);
    input.focus();
}

function check(box){
    if (box.checked) {
        box.value = default_box_values[box.id];
        count_friends(box.id);
    }
    else {
        box.value = '';
        count_friends(box.id);
    }
}

function CheckEmails(list){
    $('SaveBtn').disable();
    if (list.length == 0) {
        return true;
    }
    var earray = list.split(",");
    var valid = true;
    for (var i = 0; i < earray.length; i++) {
        if (valid) {
            valid = validemail(earray[i].replace(/(^\s+)|(\s+$)/g, ""));
        }
    }
    if (valid) {
        return true;
    }
    else {
        $('mess_em').show();
        $('SaveBtn').enable();
        return false;
    }
}

function validemail(str){
    var at = "@";
    var dot = ".";
    var lat = str.indexOf(at);
    var lstr = str.length;
    var ldot = str.indexOf(dot);
    if (str.indexOf(at) == -1) {
        return false;
    }

    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false;
    }

    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false;
    }

    if (str.indexOf(at, (lat + 1)) != -1) {
        return false;
    }

    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false;
    }

    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false;
    }

    if (str.indexOf(" ") != -1) {
        return false;
    }

    return true;
}

function count_friends(type){
    var emails = $F(type).split(',');
    var emails2 = new Array();
    emails.each(function(email){
        if (email && email != null && email != '')
            emails2.push(email);
    });
    //    for (var i = 0; i < emails.length; i++) {
    //        if (emails[i] && emails[i] != null && emails[i] != '')
    //            emails2[emails2.length] = emails[i];
    //    }
    $(type + '_count').update(emails2.length);
    if (emails2.length == 0) {
        $(type).checked = false;
    }
    else {
        $(type).checked = true;
    }
}

/*
 * {menu_community.html}
 */
function showStatus(){
    StatusSelect = $('ajaxStatusSelect').selectedIndex;
    StatusText = $F('ajaxStatusText');

    $('changeStatus').show();
    if ($('ajaxStatusSelect').options[StatusSelect].value == -1) {
        $('editStatusText').show();
    }
}

function funcStatusSelect(){
    if ($('ajaxStatusSelect').options[$('ajaxStatusSelect').selectedIndex].value == '-1') {
        $('editStatusText').show();
    }
    else {
        $('ajaxStatusText').value = '';
        $('editStatusText').hide();
    }
}

function saveStatus(){
    var select = $('ajaxStatusSelect').options[$('ajaxStatusSelect').selectedIndex].value;
    var text = $F('ajaxStatusText');
    if (!ajax_call('perl_save_status', select, text, statusSaved)) {
        window.location = 'http://'+MyMailHost+MyMailDir+'editprops';
    }
    $('changeStatus').hide();
    delete select;
    delete text;
}

function statusSaved(select, text){
    if (select == -1 && text == '')
        select = 0;
    if (document.all) {
        $('StatusSelect_-1').innerText = 'состояние: ' + text;
    }
    else {
        $('StatusSelect_-1').textContent = 'состояние: ' + text;
    }
    for (i = -1; i <= 12; i++) {
        if (i != select) {
            $('StatusSelect_' + i).hide();
        }
        else {
            $('StatusSelect_' + i).show();
        }
    }
}

function cancelStatus(){
    $('ajaxStatusSelect').selectedIndex = StatusSelect;
    if ($('ajaxStatusSelect').options[StatusSelect].value == -1) {
        $('ajaxStatusText').value = StatusText;
        $('editStatusText').show();
    }
    else {
        $('editStatusText').value = '';
        $('editStatusText').hide();
    }
    $('changeStatus').hide();
}

/*
 * {menu_user.html}
 */
function toggleStatus(action){
    if (StatusSelect == -1) {
        localStatusSelect = 13;
    }
    else {
        localStatusSelect = StatusSelect;
    }
    $('ajaxStatusSelect').selectedIndex = localStatusSelect;
    $('ajaxStatusText').value = StatusText;
    if (action) {
        if (action == 'close') {
            _toggleStatus(0);
        }
        else {
            _toggleStatus(1);
        }
    }
    else {
        if (!$('changeStatus').visible()) {
            _toggleStatus(1);
        }
        else {
            _toggleStatus(0);
        }
    }
}

function _toggleStatus(action){
    if (StatusSelect == -1) {
        localStatusSelect = 13;
    }
    else {
        localStatusSelect = StatusSelect;
    }
    if (action) {
        if ($('ajaxStatusSelect').options[localStatusSelect].value == -1) {
            $('editStatusText').show();
        }
        else {
            $('editStatusText').hide();
        }
        $('changeStatus').show();
    }
    else {
        if ($('ajaxStatusSelect').options[localStatusSelect].value == -1) {
            $('editStatusText').show();
        }
        else {
            $('editStatusText').hide();
        }
        $('changeStatus').hide();
    }
}


function funcStatusSelect(){
    if ($('ajaxStatusSelect').options[$('ajaxStatusSelect').selectedIndex].value == '-1') {
        $('editStatusText').show();
    }
    else {
        $('ajaxStatusText').value = '';
        $('editStatusText').hide();
    }
}

function saveStatus(){
    var select = $('ajaxStatusSelect').options[$('ajaxStatusSelect').selectedIndex].value;
    var text = $F('ajaxStatusText');
    if (!ajax_call('perl_save_status', select, text, statusSaved)) {
        window.location = 'http://'+MyMailHost+'/my/editprops';
    }
}

function statusSaved(select, text){
    if (select == -1 && text == '')
        select = 0;
    if (document.all) {
        $('StatusSelect_-1').innerText = 'состояние: ' + text;
    }
    else {
        $('StatusSelect_-1').textContent = 'состояние: ' + text;
    }
    for (i = -1; i <= 12; i++) {
        if (i != select) {
            $('StatusSelect_' + i).hide();
        }
        else {
            $('StatusSelect_' + i).show();
        }
    }
    StatusSelect = select;
    StatusText = text;
    toggleStatus('close');
}

/*
 * {menu_users.html}
 */
//function close_help2(){
//    $('help_div12').hide();
//}

function show_help2(evt){
    evt = evt || window.event;
    evt.cancelBubble = true;
    $('help_div12').show();
}

/*
 * {search_users.html}
 */
///**
// * Обработка ответа
// * @param {String} result
// * @param {String} id
// */
//function addToFriendResult(result, id){
//    var span = $(id);
//    var link = $(id + '_friends_link');
//
//    if (result == 'friendship_offer') {
//        span.update("Приглашение отправлено");
//        link.show();
//        tempDiv(false);
//    }
//    else
//        if (result == 'friend_added') {
//            span.update("Ура! Вы стали друзьями!");
//            link.show();
//            tempDiv(false);
//        }
//        else
//            if (result == 'my_invitation_sent') {
//                span.update("Пользователю выслано предложение создать свой мир");
//                link.show();
//                tempDiv(false);
//            }
//            else
//                if (result == 'world_invitation_sent') {
//                    span.update("Вы пригласили пользователя посетить свой мир");
//                    link.show();
//                    tempDiv(false);
//                }
//                else
//                    if (result == 'already_friends') {
//                        span.update("Вы уже друзья");
//                        link.show();
//                        tempDiv(false);
//                    }
//                    else
//                        if (result == 'already_friendship_offer_sent') {
//                            span.update("Вы уже выслали предложение");
//                            link.show();
//                            tempDiv(false);
//                        }
//                        else
//                            if (result == 'invalid_emails') {
//                                span.update("Неверный email");
//                                tempDiv(false);
//                            }
//                            else {
//                                tempDiv(false);
//                                alert('При обработке запроса произошла ошибка. Повторите попытку снова.');
//                            }
//}

//function addToFriendOnMy(id, email){
//    tempDiv(true, id);
//    ajax_call('perl_add_friend', email, id, addToFriendResult);
//    return false;
//}

function tempDiv(flag, id){
    var div;
    var span = $(id);
    if (!$("addFriendProcessingId")) {
        div = new Element("div", {
            'id': 'addFriendProcessingId',
            'class': 'zapros'
        });
        div.setStyle({
            'position': 'absolute', 
            'top': '0px',
            'left': '0px',
            'display': 'none'

        });
        div.update("Запрос обрабатывается...");
        document.body.appendChild(div);
    }
    else
        div = $("addFriendProcessingId");
    if (flag) {
        div.style.top = absPosition(span).y;
        div.style.left = absPosition(span).x;
        div.show();
    }
    else
        div.hide();
}

function sendCommunityInvite(id, community, email){
    tempDiv(true, id);
    ajax_call('perl_community_invite', community, email, id, invitedToCommunity);
    return false;
}

function invitedToCommunity(result, id){
    var span = $(id);
    if (result == "offered") {
        span.update("Приглашение отправлено");
        tempDiv(false);
    }
    else
        if (result == "already") {
            span.update("Пользователь уже является участником сообщества");
            tempDiv(false);
        }
        else
            if (result == "blacklisted") {
                span.update("Мир пользователя закрыт для вас");
                tempDiv(false);
            }
            else if (result == "CLOSED") {
                tempDiv(false);
            }
            else if (result == "NOINPUT") {
                alert('Введите число, изображенное на картинке.');
            }
            else if (result == "WRONGINPUT") {
                alert('Вы неверно ввели число, изображенное на картинке.');
            }
            else if (result == "invite") {
                if ( id ) {
                var str = "Этого пользователя приглашать в сообщества могут только друзья";
                if ( id == 2) {
                str = "Этого пользователя приглашать в сообщества могут только друзья и друзья друзей"
                }
               $("addFriendProcessingId").update('<div onclick="this.parentNode.style.display=\'none\';">'+str+'</div>');
                }
            }
            else {
                tempDiv(false);
                alert('При обработке запроса произошла ошибка. Повторите попытку снова.');
            }
}

/*
 * {military_edit.html}
 */
function military_edit_form_empty(level){
    var suff = '';
    var _editing = editing;
    if (_editing == 1)
        suff = '_edit';
    if (level < 1) {
        $('position_' + mode + suff).value = '';
    }
    if (level < 2) {
        $('region_id_' + mode + suff).options.length = 1;
        $('region_id_' + mode + suff).options[0].value = '';
        $('region_id_' + mode + suff).options[0].text = 'Выбрать';
        $('region_id_' + mode + suff).selectedIndex = 0;
        $('region_id_' + mode + suff).disable();
    }
    /*  if (level<3) {

     $('city_id_'+mode+suff).options.length=1;

     $('_'+mode+suff).options[0].value='';

     $('city_id_'+mode+suff).options[0].text='Выбрать';

     $('city_id_'+mode+suff).selectedIndex = 0;

     $('city_id_'+mode+suff).disabled=1;

     }

     */

}

function military_edit_FillGeo(names, ids, type, level, special){
    var no_list = 0;
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var list;
    if (type == 1) {
        list = $('country_id_' + mode + suff);
        military_edit_form_empty(1);
    }
    else
        if (type == 2) {
            military_edit_form_empty(2);
            list = $('region_id_' + mode + suff);
            $('region_id_' + mode + suff).enable();

        /*      $('city_id_'+mode+suff).disabled=1;
         $('city_id_'+mode+suff).options.length=0;
         $('city_id_'+mode+suff).options[0] = new Option('Выбрать', '');
         */
        }
        else
            if (type == 3) {
                if (level != 3) { // Not a Russia, disabling region menu
                    $('region_id_' + mode + suff).options.length = 0;
                    $('region_id_' + mode + suff).options[0] = new Option('Выбрать', '');
                    $('region_id_' + mode + suff).disable();
                }
                military_edit_form_empty(3);
				no_list = 1;
            /*      $('city_id_'+mode+suff).disabled=0;
         list=$('city_id_'+mode+suff);
         */
            }
            else {
                no_list = 1;
            /*      $('city_id_'+mode+suff).options.length=0;
         $('city_id_'+mode+suff).options[0] = new Option('Другое', 'other');
         $('city_id_'+mode+suff).disabled=0;
         $('city_id_' + mode + suff + '_other').style.display = ''
         */
            }
    less_disabled();
    if (no_list == 0) {
        var nl = 0;
        if (names != undefined)
            nl = names.length;
        list.options.length = 0;
        var addon = 0;
        list.options[0] = new Option('Выбрать', '');
        addon = 1;
        for (var i = 0; i < nl; i++) {
            list.options[i + addon] = new Option(names[i], ids[i]);
            if (special > 0) {
                list.options[i + addon].style.fontWeight = "bold";
                special--;
            }
        }
        if (type == 3) {
            list.options[list.options.length] = new Option('Другое', 'other');
        }
        if (type == 1 || (type == 3 && is_capital == 1))//(set default country -> Russia) OR (set default city -> capital)
        {
            list.selectedIndex = 1;
            list.onchange();
        }
        if (need_switch_star) {
            military_edit_switchStarOfFieldCallback();
        }
    }
}

function military_edit_FillList(oid, names, ids, sid){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var list = $(oid + mode + suff);
    if (list == undefined || list == null)
        return;
    if (names == '0' || names == 0) {
        list.disable();
        return;
    }
    list.enable();
    var nl = 0;
    if (names != undefined)
        nl = names.length;
    list.options.length = 0;
    var addon = 0;
    if (editing != 1) {
        list.options[0] = new Option('Выбрать', '');
        list.selectedIndex = 0;
        addon = 1;
    }
    for (var i = 0; i < nl; i++) {
        list.options[i + addon] = new Option(names[i], ids[i]);
        if (ids[i] == sid)
            list.options[i + addon].selected = 1;
    }
    if (oid == 'city_id_' || oid == 'institute_id_') {
        var le = list.options.length;
        list.options[le] = new Option('Другое', 'other');
        if (le == 0) {
            var elem = $(oid + mode + suff + '_other');
            if (elem != undefined)
                elem.show();
        }
    }
}

function military_edit_CheckList(oid, sid, sh){
    var suff = "";
    var _editing = editing;
    var lift = (sh == 0) ? 0 : 1;
    if (_editing == 1)
        suff = "_edit";
    var list = $(oid + mode + suff);
    if (list == undefined || list == null)
        return;
    list.disabled = 0;
    for (var i = 0; i < list.options.length - lift; i++) {
        if (list.options[i].value == sid)
            list.options[i].selected = 1;
    }
}


function military_edit_FillField(oid, valu){
    var suff = "";
    var _editing = editing;
    if (editing == 1)
        suff = "_edit";
    var field = $(oid + mode + suff);
    if (field == undefined || field == null)
        return;
    field.value = valu;
}

function military_edit_FillSelect(oid, valu){
    var suff = "";
    var _editing = editing;
    if (_editing == 1)
        suff = "_edit";
    var field = $(oid + mode + suff);
    if (field == undefined || field == null)
        return;
    for (var i = 0; i < field.options.length; i++) {
        if (field.options[i].value == valu) {
            field.selectedIndex = i;
            return;
        }
    }
}

function military_edit_FillEdit(mid, cNames, cIds, cId, rNames, rIds, rId, unitName, position, enterYear, enterMonth, leaveYear, leaveMonth, stillHere){
    military_edit_FillSelect('enteryear_', enterYear);
    military_edit_FillSelect('leaveyear_', leaveYear);
    military_edit_FillSelect('entermonth_', enterMonth);
    military_edit_FillSelect('leavemonth_', leaveMonth);

    military_edit_FillField('position_', position, 0);
    military_edit_FillField('name_', unitName, 0);
    military_edit_FillField('mid_', mid, 0);

    military_edit_FillList('country_id_', cNames, cIds, cId);
    military_edit_FillList('region_id_', rNames, rIds, rId);
    if (need_switch_star) {
        military_edit_switchStarOfFieldCallback();
    }
    //  military_edit_FillList('city_id_',tNames,tIds,tId);
    if (stillHere == 1) {
        $('leaveyear_unit_edit').disable();
        $('leavemonth_unit_edit').disable();
        $('stillhere_unit_edit').checked = 1;
        military_edit_switchStarByDisable('leaveyear_unit_edit', 'leaveyear_star_unit_edit');
    }
    less_disabled();
}

function military_edit_ChooseOtherObj(oid){
    list = $(oid);
    if (list.disabled == 1)
        return;
    list.selectedIndex = list.options.length - 1;
    list.onchange();
}

function military_edit_switchStarOfField(fieldName, starName){
    star_field = fieldName;
    star_name = starName;
    need_switch_star = true;
}

function military_edit_switchStarOfFieldCallback(){
    if ($(star_field).disabled == 0) {
        $(star_name).className = 'red';
    }
    else {
        $(star_name).className = 'white';
    }
    need_switch_star = false;
}

function military_edit_CheckFieldByNull(formName, fieldName, errorText){
    if (formName.elements[fieldName].value == null || formName.elements[fieldName].value == undefined || formName.elements[fieldName].value == "") {
        return errorText;
    }
    else {
        return '';
    }
}

function military_edit_CheckFormByNull(formName){
    more_disabled();
    var errors = "";
    var suff = "";
    if (editing == 1)
        suff = "_edit";

    /*  errors +=military_edit_CheckFieldByNull(formName,'country_id_'+mode+suff,"Поле СТРАНА не заполнено\n");
     if(formName.elements['region_id_'+mode+suff].disabled != 1)
     {
     errors +=military_edit_CheckFieldByNull(formName,'region_id_'+mode+suff,"Поле РЕГИОН не заполнено\n");
     }
     errors +=military_edit_CheckFieldByNull(formName,'city_id_'+mode+suff,"Поле ГОРОД не заполнено\n");
     if(formName.elements['city_id_'+mode+suff].value == 'other')
     {
     errors +=military_edit_CheckFieldByNull(formName,'city_name',"Поле ДРУГОЙ ГОРОД не заполнено\n");
     }
     */
    errors += military_edit_CheckFieldByNull(formName, 'name_' + mode + suff, "Поле ВОИНСКАЯ ЧАСТЬ не заполнено\n");

    errors += military_edit_CheckFieldByNull(formName, 'enteryear_' + mode + suff, "Поле НАЧАЛО СЛУЖБЫ - ГОД не заполнено\n");
    errors += military_edit_CheckFieldByNull(formName, 'entermonth_' + mode + suff, "Поле НАЧАЛО СЛУЖБЫ - МЕСЯЦ не заполнено\n");

    if (formName.elements['leaveyear_' + mode + suff].disabled != 1) {
        errors += military_edit_CheckFieldByNull(formName, 'leaveyear_' + mode + suff, "Поле ОКОНЧАНИЕ СЛУЖБЫ - ГОД не заполнено\n");
    }
    if (formName.elements['leavemonth_' + mode + suff].disabled != 1) {
        errors += military_edit_CheckFieldByNull(formName, 'leavemonth_' + mode + suff, "Поле ОКОНЧАНИЕ СЛУЖБЫ - МЕСЯЦ не заполнено\n");
    }

    if (errors != null && errors != "") {
        alert(errors);
        less_disabled();
        return false;
    }
}

function military_edit_switchStarByDisable(field_id, star_id){
    if ($(field_id).disabled == 0) {
        $(star_id).className = 'red';
    }
    else {
        $(star_id).className = 'white';
    }
}

function military_edit_makeother(sid){
    list = $(sid);
    if (list == undefined)
        return;
    list.enable();
    list.options.length = 0;
    list.options.length = list.options.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Не выбрано';
    list.options.length = list.options.length + 1;
    list.options[1].value = 'other';
    list.options[1].text = 'Другое';
}

function military_edit_onother(sid){
    if (sid == undefined || sid == '')
        return;
    suff = "";
    if (editing == 1)
        suff = "_edit";
}

function military_edit_onblock(sel, block_on){
    if (sel.value == 'other') {
        $(block_on).show();
        military_edit_onother(sel.id);
    }
    else {
        $(block_on).hide();
    }
}

function military_edit_disUndisField(field){
    if ($(field).disabled == 0) {
        $(field).disable();
    }
    else {
        $(field).enable();
    }
}

function military_edit_selectLastInList(list){
    list.selectedIndex = list.options.length;
}

function military_edit_edit_unit_to_orig(){
    if (editing_unit == '')
        return;
    html = $(editing_unit).innerHTML;
    if (html == undefined || html == '')
        return;
    $(editing_unit).hide();
    $(editing_unit).update('');
    $('orig_div_for_unit').update(html);
    editing_unit = '';
    editing = 0;
}

function military_edit_edit_unit_by_id(mid){
    if (editing == 1) {
        if (editing_unit == 'div_for_unit_' + mid)
            return false;
        military_edit_edit_unit_to_orig();
    }
    mode = 'unit';
    editing = 1;
    src_div = 'orig_div_for_unit';
    if (editing_unit != '') {
        $(editing_unit).hide();
        src_div = editing_unit;
    }
    editing_unit = 'div_for_unit_' + mid;
    if (src_div == editing_unit)
        return;
    html = $(src_div).innerHTML;
    if (html == undefined || html == '')
        return;
    $(src_div).update('');
    $(editing_unit).update(html);
    military_edit_form_empty(0);
    $(editing_unit).show();
    military_edit_switchStarOfField('region_id_unit_edit', 'unit_edit_star_reg');
    if ($('stillhere_unit_edit').check == 1) {
        military_edit_disUndisField('leaveyear_unit_edit');
        military_edit_disUndisField('leavemonth_unit_edit');
    }
    var olist = ['country_id_unit_edit', 'region_id_unit_edit'];
    for (var i = 0; i < olist.length; i++) {
        $(olist[i]).options[0].text = 'Загрузка...';
    }
    ajax_edit_call(mid);
}

function military_edit_add_unit(){
    mode = 'unit';
    editing = 0;
    if ($('unit_table').visible() && show_military != 1) {
        $('unit_table').hide();
    }
    else {
        $('unit_table').show();
        $("country_id_unit").options.length = 1;
        $("country_id_unit").options[0].text = 'Загрузка...';
        ajax_geo_call(1);
    }
    military_edit_switchStarByDisable('leaveyear_' + mode, 'leaveyear_star_' + mode);
}

/*
 * {military_search.tmpl}
 */
//function changeStudyType(sel){
//    var typeArray = ["Школа", "Колледж или ПТУ", "ВУЗ"];
//    var cross = ["0", "0", "0", "1", "2"];
//    val = cross[sel.value];
//    $("studyTypeId").update(typeArray[val]);
//    $("univDataId").style.display = (val != 0) ? "" : "none";
//    $("univYearId").style.display = (val != 0) ? "" : "none";
//    $("schoolDataId").style.display = (val == 0) ? "" : "none";
//}

function military_search_form_empty(level){
    if (level < 2) {
        /*      $('RegionID').disabled=1;
         $('RegionID').options.length=1;
         $('RegionID').options[0].value='';
         $('RegionID').options[0].text='Недоступно';
         */
    }
    /*
     if (level<3) {
     $('city_id').disabled=1;
     $('city_id').options.length=1;
     $('city_id').options[0].value='';
     $('city_id').options[0].text='Недоступно';
     }
     */
    if (level < 4) {
        $('unit_name').enable();
        $('unit_name').value = 'Недоступно';
    }
}

function military_search_FillGeo(names, ids, type, level, special){
//    if (type == 2) {
//        /*      list=$('RegionID');
//         $('RegionID').disabled=0;
//         $('city_id').disabled=1;
//         $('city_id').options.length=1;
//         $('city_id').options[0].value='';
//         $('city_id').options[0].text='Недоступно';
//         */
//    }
//    else {
//        //if (type==3) {
//        if (level != 3) { // Not a Russia, disabling region menu
//            /*          $('RegionID').options.length=1;
//             $('RegionID').options[0].value='';
//             $('RegionID').options[0].text='Недоступно';
//             $('RegionID').disabled=1;
//             */
//        }
//        //$('city_id').disabled=0;
//        //      list=$('city_id');
//    }
    if (names.length) {
        list.enable();
    }
    else {
        geo_id = $F('country_id') ? $F('country_id') : '';
        $('geo_azer_href').href = '/my/military_edit?show_military=1&add_geo_id=' + geo_id;
        return;
    }
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Выбрать';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        if (special > 0) {
            list.options[i + 1].style.fontWeight = "bold";
            special--;
        }
        list.options[i + 1].value = ids[i];
    }
    if (type == 1 || (type == 3 && is_capital == 1))//(set default country -> Russia) OR (set default city -> capital)
    {
        list.selectedIndex = 1;
        list.onchange();
    }
    if (need_switch_star) {
        military_search_switchStarOfFieldCallback();
    }
}

function military_search_CheckFieldByNull(formName, fieldName, errorText){
    if (formName.elements[fieldName].value == null || formName.elements[fieldName].value == undefined || formName.elements[fieldName].value == "") {
        return errorText;
    }
    else {
        return '';
    }
}

function military_search_set_mode(v){
    v = parseInt(v);
    switch (v) {
        case 1:
            mode = 'unit';
            break;
    }
}

function military_search_CheckFormByNull(formName){
    var errors = "";

    $('but_find').disable();

    //  errors +=military_search_CheckFieldByNull(formName,'country_id',"Поле СТРАНА не заполнено\n");
    //  if(formName.elements['RegionID'].disabled != 1)
    //  {
    //      errors +=military_search_CheckFieldByNull(formName,'RegionID',"Поле РЕГИОН не заполнено\n");
    //  }
    //  errors +=military_search_CheckFieldByNull(formName,'city_id',"Поле ГОРОД не заполнено\n");
    errors += military_search_CheckFieldByNull(formName, 'unit_name', "Поле НОМЕР ЧАСТИ не заполнено\n");

    if (errors != null && errors != "") {
        alert(errors);
        return false;
    }
}

function military_search_switchStarOfField(fieldName, starName){
    star_field = fieldName;
    star_name = starName;
    need_switch_star = true;
}

function military_search_switchStarOfFieldCallback(){
    /* if($(star_field).disabled==0)
     {
     $(star_name).className='red';
     } else {
     $(star_name).className='white';
     } */
    need_switch_star = false;
}

function military_search_switch_result(){
    if ($('result_txt').innerHTML.match(/Скрыть/)) {
        $('result_txt').update("Показать параметры поиска");
        $('result_img_plus').show();
        $('result_img_minus').hide();
        $('condition_table').hide();

    }
    else {
        $('result_txt').update("Скрыть параметры поиска");
        $('result_img_plus').hide();
        $('result_img_minus').show();
        $('condition_table').show();
    }
    return false
}

function military_search_check_form(){
    var show = 1;
    if (!$F('country_id'))
        show = 0;
    if (!$F('unit_name'))
        show = 0;
    if (!$F('enteryear_unit'))
        show = 0;
/*    if (!$F('entermonth_unit'))
        show = 0;*/
    if (!$('stillhere_unit').checked) {
        if (!$F('leaveyear_unit'))
            show = 0;
/*        if (!$F('leavemonth_unit'))
            show = 0;*/
    }
    $('had_served_table').style.display = show ? 'block' : 'none';
    $('had_served').disabled = 1 - show;
    $('but_find').disabled = (!$('unit_name').value || !$('country_id').value);
}

/*
 * {neighbour.tmpl}
 */
function neighbour_form_empty(level){
    if (level < 2) {
        $('region_id').disable();
        $('region_id').options.length = 1;
        $('region_id').options[0].value = '';
        $('region_id').options[0].text = '';
    }
    if (level < 3) {
        $('city_id').disable();
        $('city_id').options.length = 1;
        $('city_id').options[0].value = '';
        $('city_id').options[0].text = '';
    }
    if (level < 4) {
        $('street_search_1').hide();
        $('street_name_1').disable();
        $('street_name_1').options.length = 1;
        $('street_name_1').options[0].value = '';
        $('street_name_1').options[0].text = '';
    }
    if (level < 5) {
        $('house_id').disable();
        $('house_id').options.length = 1;
        $('house_id').options[0].value = '';
        $('house_id').options[0].text = '';
    }
}

function neighbour_FillGeo(names, ids, type, level, special){
    $('street_other').hide();
    $('street_search_1').hide();
    if (type == 2) {
        list = $('region_id');
        $('city_id').disable();
        $('city_id').options.length = 1;
        $('city_id').options[0].value = '';
        $('city_id').options[0].text = 'Недоступно';
    }
    else {
        if (level != 3) { // Not a Russia, disabling region menu
            $('region_id').options.length = 1;
            $('region_id').options[0].value = '';
            $('region_id').options[0].text = 'Недоступно';
            $('region_id').disable();
        }
        list = $('city_id');
    }
    if (names.length) {
        list.enable();
    }
    else {
        handleGeoLink();
        $('othercity').show();
        return;
    }
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Выбрать';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        if (special > 0) {
            list.options[i + 1].style.fontWeight = "bold";
            special--;
        }
        list.options[i + 1].value = ids[i];
    }
    if (type == 1 || (type == 3 && is_capital == 1))//(set default country -> Russia) OR (set default city -> capital)
    {
        list.selectedIndex = 1;
        list.onchange();
    }
}

function neighbour_FillStreets(names, ids){
    list = $('street_name_1');
    if (!names.length) {
        list.disable();
        list.options.length = 1;
        list.options[0].value = '';
        list.options[0].text = '';
        geo_id = $F('city_id') ? $F('city_id') : '';
        $('inst_azer_href').href = '/my/places?add_geo_id=' + geo_id;
        $('street_other').show();
        $('street_search_1').hide();
        return;
    }
    list.enable();
    $('street_other').hide();
    list.options.length = names.length + 2;
    list.options[0].value = '';
    list.options[0].text = 'Не имеет значения';
    list.options[1].value = 'search';
    list.options[1].text = 'Быстрый поиск';
    list.options[1].style.fontWeight = 'bold';
    for (i = 0; i < names.length; i++) {
        list.options[i + 2].text = names[i];
        list.options[i + 2].value = ids[i];
    }
    FillAB('street', 1);
    $('choose_other_1').show();
}

function neighbour_FillHouses(names, ids){
    list = $("house_id");
    if (!names.length) {
        list.disable();
        list.options.length = 1;
        list.options[0].value = '';
        list.options[0].text = '';
        return;
    }
    list.enable();
    list.options.length = names.length + 1;
    list.options[0].value = '';
    list.options[0].text = 'Не имеет значения';
    for (i = 0; i < names.length; i++) {
        list.options[i + 1].text = names[i];
        list.options[i + 1].value = ids[i];
    }
}

function neighbour_CheckFieldByNull(formName, fieldName, errorText){
    if (formName.elements[fieldName].value == null || formName.elements[fieldName].value == undefined || formName.elements[fieldName].value == "") {
        return errorText;
    }
    else {
        return '';
    }
}

function neighbour_CheckFormByNull(formName){
    //  var errors = "";
    //  errors +=neighbour_CheckFieldByNull(formName,'country_id',"Поле СТРАНА не заполнено\n");
    //  if(formName.elements['region_id'].disabled != 1)
    //  {
    //      errors +=neighbour_CheckFieldByNull(formName,'region_id',"Поле РЕГИОН не заполнено\n");
    //  }
    //  errors +=neighbour_CheckFieldByNull(formName,'city_id',"Поле ГОРОД не заполнено\n");
    //  errors += neighbour_CheckFieldByNull(formName,'street_name_1',"Поле " + street_name_1 + " не заполнено\n") ? //neighbour_CheckFieldByNull(formName,'street_name',"Поле " + street_field_name + " не заполнено\n") : '';

    //  if(formName.elements['start_year']!='' && isNaN(formName.elements['start_year'].value)==true)
    //  {
    //      errors += "В Поле " + start_year + " можно вводить только цифры\n";
    //  }

    //  if (errors != null && errors != "") { alert (errors); return false; }
}

function neighbour_check_form(){
    var show = 1;
    if (!$F('country_id'))
        show = 0;
    if (!$F('city_id'))
        show = 0;
/*  if (!$F('start_year'))
        show = 0;
    if (!$('stillhere_place').checked) {
        if (!$F('leave_year'))
            show = 0;
    }
*/
	if(document.getElementById('had_lived_table')) {
    	$('had_lived_table').style.display = show ? 'block' : 'none';
	    $('had_lived').disabled = 1 - show;
	}
    if($('country_id') && $('city_id')) $('but_find').disabled = ($('country_id').value == '' || $('city_id').value == '');
    else $('but_find').disabled = true;
}

function neighbour_show_search_input(type, id){
    $('ab_compose_' + id).value = '';
    $(type + '_search_' + id).show();
    $('choose_other_' + id).hide();
    return false;
}

/*
 * {orders_edit.tmpl}
 */
function orders_edit_dropMy(){
    if (confirm("Все данные о ваших друзьях будут утеряны без возможности восстановления. Вы уверены, что хотите полностью закрыть свой мир?")) {
        document.location = 'editprops?delete=1';
    }
    else {
        return false;
    }
}

function orders_edit_send(){
    /* if (!$('WelcomeText').value) {$('my_welcome').checked = false;} */
    var string = '', string2 = '';
    for (var i = 0; i < struct.length; i++) {
        string += '%' + struct_names[i] + ':$';
        for (var j = 0; j < struct[i].length; j++) {
            string += struct[i][j] + ',$'
            string3 = '$' + struct[i][j] + ':'
            if (!$(struct_names[i] + '_' + struct[i][j] + '_show'))
                continue;
            if (!$(struct_names[i] + '_' + struct[i][j] + '_show').checked)
                string2 += string3 + 'off;';
        }
        string += ';';
    }
    string += string2;
    $('sort_input').value = string;
    $('main_submit').submit();
}

function orders_edit_change_position(obj_id, diff){
    var obj = $(obj_id);
    var tbody = obj.parentNode;
    var nodes = tbody.childNodes;
    var prev;
    var names = obj_id.split('_');
    var tmp_arr;
    var order_exclude = 'guestbook';
    eval("tmp_arr = order_" + names[0]);
    for (var j = 0; j < tmp_arr.length; j++) {
        if (!$("'+names[0]+'_'+tmp_arr[j]+'_show"))
            continue;
        eval('var tmp_' + names[0] + '_' + tmp_arr[j] + '_show = $("' + names[0] + '_' + tmp_arr[j] + '_show").checked');
    }
    for (var j = 0; j < tmp_arr.length; j++) {
        eval('var tmp_' + tmp_arr[j] + '_show = $(obj_id+"_show").checked');
        if (tmp_arr[j] == names[1]) {
            if (j - diff < 0 || j - diff > tmp_arr.length)
                return false;
	    var diff_ie = 0;// i hate IE
	    if(tmp_arr[j-diff] == order_exclude) { diff_ie = diff }// here
            var tmp_name = tmp_arr[j - (diff + diff_ie)];// here
            tmp_arr[j - (diff + diff_ie)] = tmp_arr[j];// and here!
            tmp_arr[j] = tmp_name;
            obj_pos = j;
            vict_pos = j - diff;
            break;
        }
    }
    var vict_id = names[0] + '_' + tmp_name;
    var vict = $(vict_id);
    var allTR = new Array();
    var clickPosition = false;
    var node, counter = 0;
	$A(nodes).each(function(node){
		if (node.nodeType != 1)
            return;
        if (node.nodeName.toLowerCase() != "tr")
            return;
        allTR.push(node);
        if (node == obj) {
            clickPosition = counter;
            var tmp_arrow_up = $(vict_id + '_arrow_up').style.display;
            var tmp_arrow_down = $(vict_id + '_arrow_down').style.display;
            $(vict_id + '_arrow_up').style.display = $(obj_id + '_arrow_up').style.display;
            $(obj_id + '_arrow_up').style.display = tmp_arrow_up;
            $(vict_id + '_arrow_down').style.display = $(obj_id + '_arrow_down').style.display;
            $(obj_id + '_arrow_down').style.display = tmp_arrow_down;
            var tmp_classname = vict.className;
            vict.className = obj.className;
            obj.className = tmp_classname;
        }
        counter++;
	});

    if (clickPosition === false)
        return;

    var newTBody = new Element("TBODY");
    var bufer = allTR[clickPosition];
    allTR[clickPosition] = allTR[clickPosition - diff];
    allTR[clickPosition - diff] = bufer;
	allTR.each(function(tr){
		newTBody.appendChild(tr)
	});
    tbody.parentNode.replaceChild(newTBody, tbody);
    for (var j = 0; j < tmp_arr.length; j++) {
        if (!$("'+names[0]+'_'+tmp_arr[j]+'_show"))
            continue;
        eval('$("' + names[0] + '_' + tmp_arr[j] + '_show").checked = tmp_' + names[0] + '_' + tmp_arr[j] + '_show');
    }
    eval("order_" + names[0] + " = tmp_arr");
    return false;
}

function orders_edit_checkLength(txar, max, ending){
    var beginer = max ? max : 500;
    var b = $("simbCount" + ending);
    var span = $("strCount" + ending);
    if (txar.value.length <= beginer) {
        b.update(txar.value.length);
        span.style.color = "#909090";
    }
    else {
        b.update(beginer);
        span.style.color = "#FF0000";
        txar.value = txar.value.substring(0, beginer);
    }
}

function orders_edit_serveStatusSelect(){
    var sel = $('statusSelect');
    var inp = $('statusText');
    if (sel.options[sel.selectedIndex].value == '-1') {
        inp.enable();
    }
    else {
        inp.value = '';
        inp.disable();
    }
}

function orders_edit_EnableNotify(){
    for(var i=0; i < document.forms['notify'].elements.length; i++) {
        var item = document.forms['notify'].elements[i];
        if (item.id.indexOf('notify_') != 0) continue;
        if ($('NotifyHistory').checked) {
            item.disabled = false;
            $('NotifyTable').className = "podpiska";
            item.checked = true;
        }
        else {
            item.disabled = true;
            $('NotifyTable').className = "podpiska grey";
            item.checked = false;
        }
    }
}

function orders_edit(type){
    for(var i = 0; i < document.forms['notify'].elements.length; i++) {
        var item =  document.forms['notify'].elements[i];
        if (item.id.indexOf(type+'_') != 0) continue;
        if ($(type+'Notify').checked) {
            item.disabled = false;
            $(type+'Div').className = "";
	    if(item.type == 'checkbox') item.checked = true;
        }
        else {
            item.disabled = true;
            $(type+'Div').className = "grey";
	    if(item.type == 'checkbox') item.checked = false;
        }
    }
}

function orders_edit_switchDropDisplay(){
    if (!$('dropworldform').visible()) {
        $('dropworldform').show();
        $('truth_form').hide();
    }
    else {
        $('dropworldform').hide();
        $('truth_form').show();
        document.forms['truth_form'].elements['truth_form_reason'].focus();
    }
    return false;
}

function orders_edit_DropMy_GlamurEdition(){
    div = $('tell_us_truth');
    var _top = absPosition('DeleteMyDisclaimer').y + (-10);
    var _left = absPosition('DeleteMyDisclaimer').x + 0;
    div.style.top = _top;
    div.style.left = _left;
    div.show();
}

function orders_edit_submit_truth_form(){
    var f = $('truth_form');
    var r = $('truth_form_reason');
    if (r.value.length == 0) {
        r.disable();
        f.action = "http://"+MyMailHost+"/my/delete_my";
    }
    else {
        r.disable();
        f.action = "http://"+MyMailHost+"/my/delete_my";
    }
    f.submit();
}

function orders_edit_drop_access(level){
    var types = new Array('LogsAccessAll', 'FriendsAccessAll', 'FriendsFriendsAccessAll', 'CommunityAccessAll');
    for (i = 0; i < types.length; i++) {
        var rb = document.all['access'][types[i]];
        if (i.value > level)
            i.value = level;
    }
}

function orders_edit_EnableB(){
	for(var i = 0; i < document.forms['notify'].elements.length; i++) {
	    var item =  document.forms['notify'].elements[i];
        if (item.id.indexOf('Birthday_') != 0) continue;
        if ($('BirthdayNotify').checked) {
            item.disabled = false;
            $('Birthdaytable').className = "podpiska";
        }
        else {
            item.disabled = true;
            $('Birthdaytable').className = "podpiska grey";
        }
    }
}

/*
 * {people.tmpl}
 */
/**
 * Обработка ответа
 * @param {String} result
 * @param {String} id
 */
function people_addToFriendResult(result, id){
    var span = $(id);
    var link = $(id + '_friends_link');

    if (result == 'friendship_offer') {
        span.update("Приглашение отправлено");
        link.show();
        people_tempDiv(false);
    }
    else if (result == 'friend_added') {
        span.update("Ура! Вы стали друзьями!");
        link.show();
        people_tempDiv(false);
    }
    else if (result == 'my_invitation_sent') {
        span.update("Пользователю выслано предложение создать свой мир");
        link.show();
        people_tempDiv(false);
    }
    else if (result == 'world_invitation_sent') {
        span.update("Вы пригласили пользователя поситить свой мир");
        link.show();
        people_tempDiv(false);
    }
    else if (result == 'already_friends') {
        span.update("Вы уже друзья");
        link.show();
        people_tempDiv(false);
    }
    else if (result == 'already_friendship_offer_sent') {
        span.update("Вы уже выслали предложение");
        link.show();
        people_tempDiv(false);
   }
   else if (result == 'invalid_emails') {
        span.update("Неверный email");
        people_tempDiv(false);
   }
   else {
        people_tempDiv(false);
        alert('При обработке запроса произошла ошибка. Повторите попытку снова.');
   }
}

function people_addToFriendOnMy(id, email){
    people_tempDiv(true, id);
    ajax_call('perl_add_friend', email, id, people_addToFriendResult);
    return false;
}

function people_tempDiv(flag, id){
    var div;
    var span = $(id);
    if (!$("addFriendProcessingId")) {
        div = new Element("div", {id: "addFriendProcessingId"});
		div.setStyle({
			'position': "absolute",
			'top': 0,
			'left': 0,
			'display': 'none',
			'border': "1px solid #000",
			'background-color': "#FFF",
			'padding': "10px 30px",
			'font': "12px arial"
		});
        div.update("Запрос обрабатывается...");
        document.body.appendChild(div);
    }
    else
        div = $("addFriendProcessingId");
    if (flag) {
        div.style.top = absPosition(span).y;
        div.style.left = absPosition(span).x;
        div.show();
    }
    else
        div.hide();
}

/*
 * {photo_for_vote.tmpl}
 */
function photo_for_vote_vote(mark){
    if (mark == 0) {
        document.forms['voteform'].elements['Vote_Skip'].value = '1';
    }
    else {
        //alert(mark);
        document.forms['voteform'].elements['Vote_Mark'].value = mark;
    }
    document.forms['voteform'].submit();
}

function photo_for_vote_downloadfoto(host){
    var popupwin = window.open("http://"+PhotoImagineHost+"/cgi-bin/photo/addphoto?myphoto=1&mode=1&Title=", "dlphoto", "height=300,width=600,scrollbars=no");
    var i = setInterval(function(){
	if(popupwin.closed){
	    //location.href = 'http://'+host+'photo';
	    location.href = 'http://' + host;
	    clearInterval(i);
	}
    }, 1000);
}

function photo_for_vote_select_age(age){
    //alert(age);
    document.location = '/cgi-bin/my/photo_for_vote?Filter_Age=' + age + '&Filter_Sex='+FilterSex;
}

/*
 * {photo.tmpl}
 */
function photo_viewFlyHelp(objId, textMes){
    if (objId)// && textMes
    {
        if ($(objId) && $(objId).visible()) {
            $(objId).hide();
        }
        else {
            if (!$(objId)) {
                var div_for_voting_block = new Element('DIV', {id: 'for_voting_block'}).update('<div id="for_voting_block_close"><a href="#" onClick="photo_viewFlyHelp(this.offsetParent.id); return false;"><img src="http://img3.imgsmail.ru/mail/ru/images/blogs/close_help.gif" width="7" height="7"><\/a><\/div><div id="for_voting_block_text"><\/div>');
                document.body.appendChild(div_for_voting_block);
            }
            $('for_voting_block_text').update(textMes);
            $(objId).style.left = parseInt(absPosition($('voting_block')).x) - 80 + 'px';
            $(objId).style.top = parseInt(absPosition($('voting_block')).y) + 23 + 'px';
//            $(objId).observe('click', cancelBubbling);
            $(objId).show();
        }
    }
}

/**
 * закрытие всех блоков помощи при клике на пустое место страницы
 */
function photo_closeHelpBlock()
{
    if ($('for_voting_block') && $('for_voting_block').visible()) {
        photo_viewFlyHelp('for_voting_block');
    }
    if ($('distDivId') && $('distDivId').visible()) {
        hideDistribDiv();
    }
}

//unused
function photo_uPicOver(span){
    var avatarPath, img;
    avatarPath = "http://avt.photo.mail.ru/";
    img = $("forUserPicShow");
    img.src = avatarPath + span.id + "/_avatar";
    img.style.top = absPosition(span).y + span.offsetHeight;
    img.style.left = absPosition(span).x;
    img.show();
}

//unused
function photo_uPicOut(span){
    var img;
    var img = $("forUserPicShow");
    img.hide();
    img.src = "wait.gif";

}


//unused
function photo_CheckEditPhoto(frm){
    if (frm == undefined) {
        alert("photo_CheckEditPhoto. Не определена форма.");
        return false
    }
    var obContest = frm.Contest;
    var obMoveto = frm.moveto;
    if (obContest == undefined || obMoveto == undefined) {
        alert("photo_CheckEditPhoto. Не найден элемент формы.");
        return false
    }
    alert('obMoveto.value=' + obMoveto.value + ', obContest.selectedIndex=' + obContest.selectedIndex);

    return true;
}

function photo_hideObject(obj){
    theStyle = (obj.style ? obj.style : obj);
    if (theStyle.visibility != undefined) {
        theStyle.visibility = "hidden"
    }
    if (theStyle.display != undefined) {
        theStyle.display = "none"
    }
}

/**
 * Показать/скрыть комментарий.
 * Лишние параметры, объявленные под контейнером ниже, будут убраны.
 */
function photo_commentRep(id, quote, comment_thread, comment_page, image_id, album_id, curbox){
    photo_commentRepHide();
    var divContainer;
    if (!$("place_" + id))
        return;
    var container = $("place_" + id);

    var replyto = id;
    var author_mail = ActiveUserMail();
    var comment_id = id;
    var c_id = 'c_' + id;
    var from = 0;
    var to = id;
    //var obform = document.forms['frmAddComm'];
    //if(obform != undefined){
    //Подставить событие
    //  obform.onsubmit = ...;
    //}
    var defaultusername = ActiveUserFullName();
    container.update("<div id=\"commentAddBlockId\"><div class=\"border_grey\" style=\"width: 500px;\">\
        <input type=hidden name=\"page\" value=\"" + comment_page + "\">\
        <input type=hidden name=\"replyto\" value=\"" +
    id +
    "\">\
        <input type=hidden name=\"thread\" value=\"" +
    comment_thread +
    "\">\
        <input type=hidden name=\"author\" value=\"" +
    author_mail +
    "\">\
        <input type=hidden name=\"id\" value=\"" +
    image_id +
    "\">\
        <input type=hidden name=\"album\" value=\"" +
    album_id +
    "\">\
        <table class=\"pad5 w100\">\
            <tr>\
                <td class=\"grey\">Ваше имя:</td>\
                <td><input type=\"text\" name=\"alias\" id=\"com_alias\" disabled class=\"inp\" value=\"" +
    defaultusername +
    "\" /></td>\
            </tr>\
            <tr>\
                <td class=\"grey\">Текст:</td>\
                <td><textarea id=\"com_text\" name=\"comment\" class=\"inp_area\" cols=\"50\" rows=\"5\">" +
    (quote ? $("comment_text_" + id).value : "") +
    "</textarea></td>\
            </tr>\
            <tr>\
                <th> </th>\
                <td class=\"link\"><input id=\"sub_but\" type=\"button\" value=\"добавить\" onclick='photo_AddComment(\"" +
    to +
    "\",\"" +
    comment_thread +
    "\", \"" +
    author_mail +
    "\", \"" +
    image_id +
    "\", \"" +
    album_id +
    "\", \"" +
    curbox +
    "\", \"" +
    image_id +
    "\", \"" +
    comment_id +
    "\", \"" +
    c_id +
    "\");return false;' />&nbsp;&nbsp;&nbsp;&nbsp;<a onclick=\"return photo_commentRepHide();\" href=\"#\" class=\"dels\"><i></i>закрыть</a></div></td>\
            </tr>\
            <tr>\
                <th></th>\
                <td><div class='capchaNew_left' name='for_capcha_comment' id='for_capcha_comment'>\
    <div><a href='#' onclick='photo_hideObject(for_capcha_comment); return false;' id='wee11'><i></i></a></div>\
    <img name='img_for_capcha_comment' id='img_for_capcha_comment' src='http://img0.imgsmail.ru/0.gif'>\
    <p>Введите число,<br>изображенное на картинке:</p>\
    <input id='security_image_addcomment_answer' type=text name='security_image_addcomment_answer'  value='' class='inp mt5'>\<input type=submit name='btn_ok' onclick='photo_AddComment(\"" +
    to +
    "\",\"" +
    comment_thread +
    "\", \"" +
    author_mail +
    "\", \"" +
    image_id +
    "\", \"" +
    album_id +
    "\", \"" +
    curbox +
    "\", \"" +
    image_id +
    "\", \"" +
    comment_id +
    "\", \"" +
    c_id +
    "\");return false;' value=' ок ' id='gg11'/>\
                </div></td>\
            </tr>\
        </table>\
        </div></div>");
//    document.forms['frmAddComm'].elements['alias'].focus();
    document.forms['frmAddComm'].elements['comment'].focus();
    return false;
}


function photo_commentRepHide(){
    if ($("commentAddBlockId")) {
        $("commentAddBlockId").parentNode.removeChild($("commentAddBlockId"));
    }
    return false;
}

function photo_ClearCapchaParams(){
    capcha_mark = 0;
    capcha_id = 0;
    check_capcha_result = 0;
    var ob = $('security_image_answer');
    if (ob != undefined) {
        ob.value = '';
    }
}

function photo_FreshVoteCapchaCallback(st, id){
    if (st == 1) {
        capcha_id = id;
        $('img_for_capcha').src = 'http://' + PhotoPerlHost() + '/cgi-bin/get_image_photo?id=' + capcha_id;
        var ob = $('for_capcha');
        ob.style.visibility = "visible";
        ob.show();
        var ob = $('security_image_answer');
        if (ob != undefined) {
            ob.focus()
        };

        document.onclick = function hide_VoteCapcha(evt){
            var ob = $("for_capcha");
            if (ob) {
                evt = (evt) ? evt : ((window.event) ? event : null);
                elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
                if (elem.id != "img_for_capcha" && elem.id != "security_image_answer" && elem.tagName != "A") {
                    photo_hideObject(ob);
                    document.onclick = "";
                }
            }
        }
    }
    else {
        alert('Не удалось сформировать картинку. Повторите пожалуйста ваш выбор.');
    }
}

function photo_FreshVoteCapcha(){
    var st = ajax_call('perl_get_capcha_id', photo_FreshVoteCapchaCallback);
    return st;
}

function photo_FreshCapchaCommentCallback(st, id){
    if (st == 1) {
        capcha_comment_id = id;
        $('img_for_capcha_comment').src = 'http://' + PhotoPerlHost() + '/cgi-bin/get_image_photo?id=' + capcha_comment_id;
        var ob = $('for_capcha_comment');
        ob.style.display = "block";
        var ob = $('security_image_addcomment_answer');
        if (ob != undefined) {
            ob.focus()
        };
            }
    else {
        alert('Не удалось сформировать картинку. Повторите пожалуйста ваш выбор.');
    }
    photo_ShowSendButton('sub_but');
}

function photo_FreshCapchaComment(){
    var st = ajax_call('perl_get_capcha_id', photo_FreshCapchaCommentCallback);
    if (st == 1) {
        photo_HideSendButton('sub_but');
    };
    return st;
}

function photo_addVoteCallback(st, newrating, votescount, errorcode, errortext){
    if (st == 1) {
        voted = true;
        $('image_Rate').update(newrating);
      //  $('image_VotesCount').update(votescount);
		$('image_VotesCount').innerHTML = ++$('image_VotesCount').innerHTML;
		if (window.photoMark == 10) $('image_MegaVoteCnt').innerHTML = ++$('image_MegaVoteCnt').innerHTML;
		$('image_Rate_Vote_Access').update('Спасибо, Ваш голос принят!');
		$('image_Rate_Vote_Access').className = 'imageRateVoteAccess2';
    }
    else {
        if (errorcode == 2) { //Вы уже голосовали
            voted = true;
            photo_hideObject($('image_Rate_Vote_Access'));
        }
        alert('Проголосовать не удалось: ' + errortext);
    }
}

function photo_addVote(mark, image_id, album_id){
    rating += mark;
	window.photoMark = mark;
    if (voted) {
        alert('Вы уже проголосовали за фото');
        return;
    }

    var answer = '';
    /*if(need_capcha){alert('need_capcha' + need_capcha);
     capcha_mark = mark;
     answer=$('security_image_answer').value;
     if(answer == '' || check_capcha_result != 1){
     var st = photo_FreshVoteCapcha();
     }
     return;
     }
     photo_ClearCapchaParams();alert('photo_ClearCapchaParams');*/
    var st = ajax_call('perl_add_vote', mark, image_id, album_id, capcha_id, answer, photo_addVoteCallback);
    if (!st) {
        alert('Проголосовать не получилось');
		} else {
			$('image_Rate_Vote_Access').style.backgroundImage = "none";	
			$('image_Rate_Vote_Access').style.paddingTop = "15px";	
			$('image_Rate_Vote_Access').update('Запрос обрабатывается');
			$('image_Rate_Vote_Access').className = 'imageRateVoteAccess2';
		}
}

function photo_CheckVoteCapchaCallback(st, ok){
    if (st == 1) {
        check_capcha_result = ok;
        if (ok == 1) {
            var answer = $F('security_image_answer');
            var mark = capcha_mark;
            var id = capcha_id;
            photo_ClearCapchaParams();
            $('for_capcha').style.visibility = "hidden";
            var st = ajax_call('perl_add_vote', mark, CurrentImageId(), CurrentAlbumId(), id, answer, photo_addVoteCallback);
            if (!st) {
                alert('Проголосовать не получилось');
            }
        }
        else {
            alert('Неверно введён код защиты');
            photo_ClearCapchaParams();
            var st = photo_FreshVoteCapcha();
        }
    }
    else {
        alert('Проголосовать не получилось');
    }
}

//unused
function photo_CheckVoteCapcha(){
    var answer = $F('security_image_answer');
    var st = ajax_call('perl_check_capcha', capcha_id, answer, photo_CheckVoteCapchaCallback);
    return st;
}

function photo_HideSendButton(buttonID){
    if (buttonID == undefined) {
        buttonID = 'sub_but'
    }
    ob = $(buttonID);
    if (ob != undefined) {
        ob.value = "Идет отправка";
        ob.disable();
    }
    SendButtonTimerButtonID = buttonID;
    SendButtonTimer = setTimeout(function(){
        clearTimeout(SendButtonTimer);
        photo_ShowSendButton(SendButtonTimerButtonID);
    }, 3000);
}

function photo_ShowSendButton(buttonID){
    if (buttonID == undefined) {
        buttonID = 'sub_but'
    }
    ob = $(buttonID);
    if (ob != undefined) {
        ob.value = "добавить";
        ob.enable();
    }
}

function photo_AddCommentCallback(st, errorcode, errortext, ref){
    if (st == 1) {
        if (ref != undefined && ref != '') {
            //              window.location.replace(ref);
            document.location = ref;
            //              window.location.href = ref;
            return;
        }
        else {
            window.location.reload(true);
        }
    }
    else {
        if (errorcode == 2 || errorcode == 3) {
            photo_FreshCapchaComment();
            if (errorcode == 3) {
                alert(errortext);
            };
            return;
        }
        alert('Добавить комментарий не получилось: ' + errortext);
    }
    photo_ShowSendButton('sub_but');
    ClearTempVars();
}

function photo_AddComment(replyto, thread, author, id, album, curbox, image_id, comment_id, c_id){
    var ob = $('com_text');
    if (ob == undefined) {
        alert('Не найден комментарий.');
        return;
    }
    if (ob.value == '') {
        alert('Необходимо заполнить комментарий перед отправкой');
        return;
    }
    var comment = ob.value;

    var com_alias = '';
    var ob = $('com_alias');
    if (ob != undefined) {
        com_alias = ob.value
    };

    //alert('Добавляем комментарий через ajax');
    //Заполняем временные переменные. Временное решение (см выше)
    last_replyto = replyto;
    last_thread = thread;
    last_author = author;
    last_id = id;
    last_album = album;
    last_curbox = curbox;
    last_image_id = image_id;
    last_comment_id = comment_id;
    last_c_id = c_id;
    last_capcha_id = capcha_id;
    last_answer = answer;
    last_comment = comment;

    var answer = '';
    ob = $('security_image_addcomment_answer');
    if (ob != undefined) {
        answer = ob.value;
    }
    //alert('capcha_id='+capcha_comment_id+'  answer='+answer);
    var captchaDiv = $('for_capcha_comment');
    if(capcha_comment_id && !answer) {
        captchaDiv.style.display = 'block';
        captchaDiv.style.visibility = '';
        return;
    }

    var st = ajax_call('perl_add_comment', replyto, thread, author, id, album, curbox, image_id, comment_id, c_id, capcha_comment_id, answer, comment, com_alias, 'http://'+MyMailHost+CurrentURL, photo_AddCommentCallback);
    if (st == 1) {
        photo_HideSendButton('sub_but');
    }
}

function photo_HideComments(ar_hidden_comments_id){
    ar_hidden_comments_id.each(function(id){
        ob = $("tab" + id);
        if (ob != undefined) {
        //    ob.className = "HiddenComment";
		ob.update("<img src=\"http://img1.imgsmail.ru/r/blogs/ico_deleted.png\" class=\"IEpng ico\" height=\"16\" width=\"16\">Комментарий удален");
		ob.className = "pb20";
        }
    });
}

function DelCommentCallback(st, errorcode, errortext, str_hidden_comments_id){
    if (st == 1) {
        var ar_hidden_comments_id = str_hidden_comments_id.split(/\s/);
        photo_HideComments(ar_hidden_comments_id);
    }
    else {
        alert('Удалить комментарий не получилось: ' + errortext);
    }
}

function photo_DelComment(ob_id, image_id, album_id, comment_page){
    var lin_num = ob_id.substring(2, ob_id.length);
    //alert("image_id="+image_id+", album_id="+album_id+", lin_num="+lin_num+", comment_page="+comment_page+", delete_with_child="+delete_with_child);
    deleted_comment_id = lin_num;
    var delete_with_child = 1;
    var ob = $("with_child");
    delete_with_child = 0;
    if (ob != undefined) {
        delete_with_child = ob.checked ? 1 : 0;
    };
    var st = ajax_call('perl_del_comment', image_id, album_id, lin_num, comment_page, delete_with_child, DelCommentCallback);

    return st;
}

function photo_DelCommentDialog(ob, image_id, album_id, comment_page){
    var ob_id = ob.id;
    var check_f = $("del_dialog");
    if (check_f) {
        check_f.parentNode.removeChild(check_f.parentNode.lastChild);
    }
    del_div = new Element("div", {'id': 'del_dialog', 'class': 'del_min'}).update("<div class='border_grey w-200'>Удалить комментарий?<div class='pt5 pb5'><input type=checkbox id=with_child class='vmi'>с&nbsp;вложенными&nbsp;комментариями</div><input type=button value=' Да ' onclick='photo_hideObject(this.offsetParent);photo_DelComment(\"" + ob_id + '","' + image_id + '","' + album_id + '","' + comment_page + "\");'>&nbsp;&nbsp;<input type=button value=' Нет ' onclick='hide_CommentDialog(event);'></div>");
    ob.parentNode.appendChild(del_div);
    document.onclick = function hide_CommentDialog(evt){
        var ob = $("del_dialog");
        if (ob) {
            evt = (evt) ? evt : ((window.event) ? event : null);
            elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            if (elem.id != "del_dialog" && elem.tagName != "A" && elem.id != "with_child") {
                photo_hideObject(ob);
                document.onclick = "";
            }
        }
    }
    return false;
}

function hide_CommentDialog(evt){
        var ob = $("del_dialog");
        if (ob) {
            evt = (evt) ? evt : ((window.event) ? event : null);
            elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            if (elem.id != "del_dialog" && elem.tagName != "A" && elem.id != "with_child") {
                photo_hideObject(ob);
                document.onclick = "";
            }
        }
    }







function photo_f2_highLight(f2_r){
    var i = 1;
    while ($('f2_r' + i)) {
        $('f2_r' + i).style.background = '#fff';
        $('f2_r' + i + i).style.color = '#999';
        i++
    }
    if (f2_r != 0) {
        $('f2_r' + f2_r).style.background = '#14CE0F';
        $('f2_r' + f2_r + f2_r).style.color = '#fff'
    }
}

function photo_filterFriendList()
{
    var stringForFilter = document.formNameFriendName.inpNameFriend.value;// значение вводимое пользователем
    var blockContentFriendList = $('listFriend_nameFriend');
    var goodName = false;
    var string_listFriend = '';
    while(blockContentFriendList.lastChild) {blockContentFriendList.removeChild(blockContentFriendList.lastChild);}
    if (stringForFilter != '')
    {
        tmp_ul = blockContentFriendList;
        for (var i = 0; i < arrFriendList.length; i++)
        {
            var splitName = arrFriendList[i][1].split(' ');
            splitName = splitName.length ? splitName : [splitName];

            for (var j = 0; j < splitName.length; j++)
            {
                if (splitName[j].toLowerCase().substr(0, stringForFilter.length) == stringForFilter.toLowerCase())
                    {goodName = true; break;}
                else {goodName = false;}
            }
            if (goodName)
                {string_listFriend += '<li><label><input type="radio" name="nameOfSelectedMan" id="iam' + arrFriendList[i][2] + '" value="' + arrFriendList[i][0] + '" style="margin-bottom: -2px;"><span class="aslink">' + arrFriendList[i][1] + '<\/span><\/label><\/li>';}
        }
        tmp_ul.update(string_listFriend);
    }
    else
    {
        tmp_ul = blockContentFriendList;
        for (var i = 0; i < arrFriendList.length; i++)
            {string_listFriend += '<li><label><input type="radio" name="nameOfSelectedMan" id="iam' + arrFriendList[i][2] + '" value="' + arrFriendList[i][0] + '" style="margin-bottom: -2px;"><span class="aslink">' + arrFriendList[i][1] + '<\/span><\/label><\/li>';}
        tmp_ul.update(string_listFriend);
    }
}

function photo_loadMyFriendsCallback(arr,error)
{
    if (!isOpera)
    {
        //alert(arr);
        if(arr == 0)
            {alert('Владелец фото не является вашим другом.');return false;}
        if(!arr.length)
            {arr = [arr];}

        var string_listFriend = "";
        for (var i=0; i<arr.length; i++)
        {
            if ((arr[i].LastName != null && arr[i].FirstName != null) && (arr[i].LastName != '' || arr[i].FirstName != ''))
                {tmp_nameFriendInList = arr[i].LastName + " " + arr[i].FirstName;}
            else if (arr[i].Nick != null && arr[i].Nick != '')
                {tmp_nameFriendInList = arr[i].Nick;}
            else if (arr[i].Email != '')
                {tmp_nameFriendInList = arr[i].Email;}
            else
                {tmp_nameFriendInList = 'Отсутствуют идентификационные данные';}

            nameFriendInList = (i == 0) ? 'Это я!' : tmp_nameFriendInList;
            string_valueLi = arr[i].ID;

            // Код для фильтра
            arrFriendList[i] = [string_valueLi,nameFriendInList,i];
            // Код для фильтра

            string_listFriend += '<li><label><input type="radio" name="nameOfSelectedMan" id="iam' + i + '" value="' + string_valueLi + '" style="margin-bottom: -2px;"><span class="aslink">' + nameFriendInList + '<\/span><\/label><\/li>';
        }
        document.formNameFriendName.inpNameFriend.value = '';
        document.formNameFriendName.inpNameFriend.focus();
        $('listFriend_nameFriend').innerHTML = string_listFriend;
    }
}

function photo_whichOneChecked(obj){
    if (!obj.length) {
        obj = [obj];
    }
    var checkedValue;
    $A(obj).each(function(el){
        if (el.checked) {
            checkedValue = el.value;
        }
    });
    return checkedValue;
}

function photo_submitFormNameFriendName()
{
    var nameOfSelectedManObj = document.forms['formNameFriendName'].elements['nameOfSelectedMan'];
    var person_id = (!nameOfSelectedManObj || photo_whichOneChecked(nameOfSelectedManObj) == undefined) ? 0 : photo_whichOneChecked(nameOfSelectedManObj);

    var person_nick = (person_id == 0) ? document.formNameFriendName.inpNameFriend.value : 0;

    if (person_id == 0 && person_nick == 0)
    {
        alert('Для обозначения выделенного друга выберите его Имя из списка или впишите самостоятельно');
        photo_disabledFieldsTimer('formNameFriendName','formNameFriendSubmit','formNameFriendNameCancel','disFalse');
        return;
    }

    var top = absPosition($('mdlblck')).y - parseInt(absPosition($('centralImgId')).y) + 8;
    var left = absPosition($('mdlblck')).x - parseInt(absPosition($('centralImgId')).x) + 8;
    var height = getBounds($('mdlblck')).height;
    var width = getBounds($('mdlblck')).width;
    //alert(top + ' ' + left + ' ' + height + ' ' + width + ' person_id = ' + person_id + ' person_nick = ' + person_nick)
    var person_email = 0;

    ajax_call('perl_add_person',current_album_id,current_image_id,top,left,height,width,person_email,person_id,person_nick,photo_addPersonCallback);
    return false;
}

function photo_addPersonCallback(id, top, left, height, width, person_nick, person_email, path){
    person_Items++;
    //mark_working = 0;
    //alert(id+" : "+top+" : "+left+" : "+height+" : "+width+" : "+person_nick+" : "+person_email+" : "+path);
    if (!id) {
        alert(top);
        photo_formNameFriendNameReset();
        return false;
    }
    //TODO: make selection with top,left,height,width,person_nick
    //alert(person_nick + ' и ' + person_email);
    if (!person_nick) {
        person_nick = person_email;
    }
    if (person_email != 0) {
        person_nick_signature = '<a href="http://' + path + '">' + person_nick + '<\/a>';
        person_space = '<a href="http://' + path + '"><img src="http://img2.imgsmail.ru/0.gif" width="' + width + '" height="' + height + '" alt=""><\/a>';
    }
    else {
        person_nick_signature = '<span>' + person_nick + '<\/span>';
        person_space = '<img src="http://img3.imgsmail.ru/0.gif" width="' + width + '" height="' + height + '" alt="">';
    }

    var amendment_x = isIE ? 6 : 10;
    var amendment_y = isIE ? 17 : 21;
    var string_borderFriend = '<div style="position:absolute;top:' + (parseInt(top) - 3 - amendment_y) + 'px; left:' + (parseInt(left) - 3 - amendment_x) + 'px;width:' + (parseInt(width) + 6) + 'px;" class="invis" id="pers_' + id + '">' +
    '<div class="pic" style="width:' +
    width +
    'px;height:' +
    height +
    'px;" onMouseOver="$(\'pers_' +
    id +
    '\').className=\'vis\';" onMouseOut="$(\'pers_' +
    id +
    '\').className=\'invis\';">' +
    person_space +
    '<\/div>' +
    '<div class="txt" style="width:' +
    width +
    'px;" align="center" onMouseOver="$(\'pers_' +
    id +
    '\').className=\'vis\';" onMouseOut="$(\'pers_' +
    id +
    '\').className=\'invis\';">' +
    person_nick_signature +
    '<img src="http://img0.imgsmail.ru/0.gif" width="' +
    width +
    '" height="3" alt=""><\/div>' +
    '<\/div>';
    var deleteButton = '';
    //if(var_OwnAlbum == 1){
    deleteButton = '<span class="link"<a href="#" onclick="if(confirm(\'Удалить отмеченного друга?\')){ajax_call(\'perl_delete_person\',\'' + current_album_id + '\',' + current_image_id + ',' + id + ',photo_deletePersonCallback);return false;}" onMouseOver="if (mark_working == 0) $(\'pers_' + id + '\').className=\'vis dells\';" onMouseOut="if (mark_working == 0) $(\'pers_' + id + '\').className=\'invis dells\'" class="dells"><i></i><\/a></span>';
    //}

    var string_nameFriendHead = '<span id="AlbumName_listNames" class="nowrap">На фото: <\/span>';// style="margin-left:-82px;"
    var string_comma = '';
    var string_nameFriend = '';
    if ($('AlbumName_listNames') && ($('AlbumName_listNames').visible() || $('AlbumName_listNames').visible())) {
        string_comma = ', ';
    }
    else
        if (!$('AlbumName_listNames')) {
            string_nameFriend += string_nameFriendHead;
        }
        else
            if ($('AlbumName_listNames') && !$('AlbumName_listNames').visible()) {
                $('AlbumName_listNames').show();
            }

    if (person_email != 0) {
        string_nameFriend += '<span id="span_' + id + '">' + string_comma + '<a href="http://www.mail.ru/agent?message&amp;to=' + person_email + '" title="Щелкни, чтобы пообщаться с этим человеком в Mail.Ru Агенте"><i class="spr-mrim-13" email="' + person_email + '"></i><\/a><a href="http://' + path + '" target="_blank" onMouseOver="$(\'pers_' + id + '\').className=\'vis\';" onMouseOut="$(\'pers_' + id + '\').className=\'invis\'">' + person_nick + '<\/a>' + deleteButton + '<\/span';
    }// style="margin-right:3px;"
    else {
        string_nameFriend += '<span id="span_' + id + '">' + string_comma + '<span onMouseOver="if (mark_working == 0) $(\'pers_' + id + '\').className=\'vis\';" onMouseOut="if (mark_working == 0) $(\'pers_' + id + '\').className=\'invis\'" style="color:#666666; cursor: hand; cursor: pointer;">' + person_nick + '<\/span>' + deleteButton + '<\/span>';
    }

    $('pic_containerRelativeId').innerHTML += string_borderFriend;
    $('block_selFriends').innerHTML += string_nameFriend;
    $('pers_' + id).show();
    photo_formNameFriendNameReset();
    return true;
}

function photo_deletePersonCallback(id, error){
    //alert('id = ' +id);
    if (!id) {
        alert(error);
        return false;
    }
    //alert($('pers_' + id));
    //TODO: remove selection with id == id

    $('pers_' + id).hide();
    $('span_' + id).hide();
    person_Items--;
    if (person_Items <= 0) {
        $('AlbumName_listNames').hide();
    }

    var curDate_bsv = new Date();
/* TODO Petrov: остаемся на той же фотке
    if (next_image_url)
        window.location.href = next_image_url;
    else
        if (previos_image_url)
            window.location.href = previos_image_url;
        else
            window.location.href = empty_image_url;
*/
}

/**
 * Дисаблит поля на 10 секунд.
 * Если нет аргументов или есть спец. флаг - функция открывает формы.
 */
function photo_disabledFieldsTimer(formName,but_1,but_2,flagTimer)
{
    if (!formName)
    {
        if (!arrShadowButton.length)
        {
            arrShadowButton[0] = document.forms[formName].elements[but_1];
            arrShadowButton[1] = document.forms[formName].elements[but_2];
        }
        arrShadowButton[0].disabled = false;
        arrShadowButton[1].disabled = false;
        clearTimeout(timer_disabledFields);
        timer_disabledFields = null;
        arrShadowButton = [];
    }
    else
    {
        arrShadowButton[0] = document.forms[formName].elements[but_1];
        arrShadowButton[1] = document.forms[formName].elements[but_2];

        if (flagTimer == 'disFalse')
        {
            arrShadowButton[0].disabled = false;
            arrShadowButton[1].disabled = false;
            clearTimeout(timer_disabledFields);
            timer_disabledFields = null;
            arrShadowButton = [];
        }
        else
        {
            arrShadowButton[0].disabled = arrShadowButton[0].disabled == true ? false : true;
            arrShadowButton[1].disabled = arrShadowButton[1].disabled == true ? false : true;

            if (flagTimer == true) {running = true;}
            else {running = false;}

            var disFlag = arrShadowButton[0].disabled == true && arrShadowButton[1].disabled == true ? true : false;
            if (running == true && disFlag)
                {timer_disabledFields = setTimeout('photo_disabledFieldsTimer()', 10000);}
        }
    }
}

/**
 * Показывает указанный блок и передаёт формы для дисебла другой функции
 */
function photo_upListFriendBlock(idBlock, formName, but_1, but_2, flagTimer){
    $(idBlock).show();
    photo_disabledFieldsTimer(formName, but_1, but_2, flagTimer);
}

/**
 * Деблокирует все кнопки и закрывает слои выделения и блок друзей
 */
function photo_formNameFriendNameReset(){
    photo_disabledFieldsTimer('formNameFriendName', 'formNameFriendSubmit', 'formNameFriendNameCancel', 'disFalse');
    photo_disabledFieldsTimer('cropperForm', 'person_pop_up_submit', 'person_pop_up_reset', 'disFalse');
    $('div_nameFriend').hide();
    flipCrop();
}

//unused
function photo_saveTagsCallback(tags, user_tags, encoded){
    if (tags == 'error') {
        alert(user_tags);
        return false;
    }
    var span = $('labelLinkListId');
    span.update('');
    for (var i = 0; i < tags.length; i++) {
        span.innerHTML += '<a href="http://foto.mail.ru' + MyMailDir + 'tags/' + encoded[i] + '" class="additional">' + tags[i] + '</a>&nbsp;&nbsp;';
    }
    span.innerHTML += '<a onclick="showLabelsEditDiv();return false;" href="#"><img src="http://img1.imgsmail.ru/r/foto2/ico_pencil.gif" width="16" height="16" alt="" class="ico">Редактировать<\/a>';
    var user_span = $('UserTags');
    user_span.update('');
    for (var i = 0; i < user_tags.length; i++) {
        user_span.innerHTML += '<a href="#" onclick="return addLabel(this, "txtarForEditLabelsId");" class="t/0 tahoma additional">' + user_tags[i] + '<\/a> ';
    }
    hideLabelsEditDiv();
}

//unused
function photo_dis_but() {
    value=$F("com_text");
    sub_but=$("sub_but");
    if (value) {
        sub_but.value = "идет отправка";
        sub_but.disable();
        return true;
    }else{
        return false;
    }
}

/*
 * {places.tmpl}
 */
// GENERATE ID
function places_gid(oid){
    if (oid) {
        if (editing) {
            return oid + "_edit";
        }
        else {
            return oid + "_ins";
        }
    }
    else {
        return editing ? 'edit' : 'ins';
    }
}

// DISABLE/ENABLE SUBMIT
function places_disable_submit(){
    $(places_gid('submit')).disable();
    disableness = 1;
}

function places_enable_submit(){
    if (disableness == 1)
        $(places_gid('submit')).enable();
    disableness = 0;
}

// FILL LIST
function places_FillList(oid, names, ids, sid){
    var list = $(places_gid(oid));
    if (!list)
        throw 'Error places_FillList object: ' + places_gid(oid) + ' not found';
    if (names.length == '0') {
        list.disable();
        return;
    }
    else {
        list.enable();
    }
    //if(!editing) list.options[0] = new Option('Выбрать', '', true, true);

    var nl = names.length;
    list.options.length = 0;
    if (oid == 'street_name' || oid == 'subway_id') {
        list.options[0] = new Option('Выбрать', '');
        if (oid == 'street_name') {
            list.options[1] = new Option('Поиск по списку', 'other');
            list.options[1].style.fontWeight = 'bold';
        }
    }

    for (var i = 0; i < nl; i++) {
        var index = list.options.length;
        list.options[index] = new Option(names[i], ids[i]);
        if (ids[i] == sid)
            list.options[index].selected = true;
    }
    /* XXX DIRTYHACK */
    if (oid == 'city_id') {
        var le = list.options.length;
        list.options[le] = new Option('Другое', 'other');
        if (le == 0) {
            var elem = $(places_gid(oid) + '_other');
            if (elem && elem.style)
                elem.show();
        }
    }
}

// FORM EMPTY
function places_form_empty(level){
    if (level < 1)
        $(places_gid('position')).value = '';
    if (level < 2) {
        var id = places_gid('region_id');
        $(id).options.length = 1;
        $(id).options[0].value = '';
        $(id).options[0].text = 'Выбрать';
        $(id).selectedIndex = 0;
        $(id).disable();
    }
    if (level < 3) {
        var id = places_gid('city_id');
        $(id).options.length = 1;
        $(id).options[0].value = '';
        $(id).options[0].text = 'Выбрать';
        $(id).selectedIndex = 0;
        $(id).disable();
    }
}

// CHECK FIELD BY NULL
function places_CheckFieldByNull(form, fieldName, errorText){
    if (!form.elements[fieldName].value && form.elements[fieldName].value != 0 && form.elements[fieldName].value.match('^\s*$')) {
        return errorText;
    }
    else {
        return '';
    }
}

// CHECK FORM BY NULL
function places_CheckFormByNull(formName){
    places_disable_submit();
    var errors = "";
    errors += places_CheckFieldByNull(formName, 'country_id', "Поле СТРАНА не заполнено\n");
    if (formName.elements['region_id'].disabled != 1)
        errors += places_CheckFieldByNull(formName, 'region_id', "Поле РЕГИОН не заполнено\n");
    errors += places_CheckFieldByNull(formName, 'city_id', "Поле ГОРОД не заполнено\n");
    if (formName.elements['city_id'].value == 'other' && formName.elements['city_name'].value.match('^\s*$'))
        errors += places_CheckFieldByNull(formName, 'city_name', "Поле ДРУГОЙ ГОРОД не заполнено\n");
    /*
     if(!formName.elements['subway_id'].disabled && formName.elements['subway_id'].value === null && formName.elements['subway_id'].value === undefined)
     errors += "Поле СТАНЦИЯ МЕТРО не заполнено\n";
     if(!formName.elements['street_id'].value && formName.elements['street_name'].value.match('^\s+$'))
     errors += "Поле УЛИЦА не заполнено\n";
     if(!formName.elements['house_name'].value || formName.elements['house_name'].value.match('^\s*$') )
     errors += "Поле ДОМ не заполнено\n";
     */
    if (errors != null && errors != "") {
        alert(errors);
        places_enable_submit();
        return false;
    }
}

// MAKEOTHER
//unused
function places_makeother(sid){
    var list = $(sid);
    if (list) {
        list.enable();
        list.options.length = 0;
        list.options.length = list.options.length + 1;
        list.options[0].value = '';
        list.options[0].text = 'Не выбрано';
        list.options.length = list.options.length + 1;
        list.options[1].value = 'other';
        list.options[1].text = 'Другое';
    }
    else {
        throw 'Error showblock oid: ' + sid + ' not found';
    }
}

// ONBLOCK
function places_onblock(sel, block_on){
    if (sel.value == 'other') {
        $(block_on).show();
    }
    else {
        $(block_on).hide();
    }
}

// EDIT FORM
function places_editForm(pid){
    ajax_call('perl_fetch_place', pid, places_fillEditForm);
}

// SHOW FORM
function places_show_form(){
    editing = 0;
    if ($('insert_form_container').visible()) {
        $('insert_form_container').hide();
    }
    else {
        $('insert_form_container').show();
        $("country_id_ins").options.length = 0;
        $("country_id_ins").options[0] = new Option('Загрузка...', '', true, true);
        places_ajax_geo_call(1);
    }
}

// TO CURRENT TIME TOGGLE
function places_toCurrentTimeToggle(obj){
    if (obj.checked) {
        $(places_gid('toTime')).disable();
    }
    else {
        $(places_gid('toTime')).enable();
    }
}

// SHOW OWN ACTIVITY
function places_showOwnActivity(obj){
    if (obj.options[obj.selectedIndex].value == OWN) {
        $(places_gid('activity_name')).value = '';
        $(places_gid('activity_name')).show();
    }
    else {
        $(places_gid('activity_name')).hide();
    }
}

/* AJAX CALLS ========================================================================== */

// AJAX GEO CALL
function places_ajax_geo_call(geo_id){
    places_disable_submit();
    ajax_call('perl_get_geo', geo_id, places_FillGeo);
}

// AJAX PLACES CALL
function places_ajax_places_call(geo_id){
    if (geo_id == 'other' || !geo_id) {
        places_FillStreet();
        places_FillSubway();
    }
    else {
        if (editing) {
            var td_a = 'street_star_edit';
        }
        else {
            var td_a = 'street_star_add';
        }
        $(td_a).update('<img src="http://img2.imgsmail.ru/r/my/loading.gif" width="16" height="15" border="0" class="load">');
        places_disable_submit();
        ajax_call('perl_get_house', geo_id, 0, places_FillStreet);
        ajax_call('perl_get_place_marks', geo_id, subwayFlag, places_FillSubway);
    }
}

/* FILLS =============================================================================== */

// FILL GEO
function places_FillGeo(names, ids, type, level, special){
    var no_list = 0;
    var list;
    var is_capital = 0;
    if (type == 1) {
        list = $(places_gid('country_id'));
        places_form_empty(1);
    }
    else
        if (type == 2) {
            places_form_empty(2);
            list = $(places_gid('region_id'));
            $(places_gid('region_id')).enable();
            $(places_gid('city_id')).disable();
            $(places_gid('city_id')).options.length = 0;
            if (editing) {
                var td_a = 'region_star_edit';
            }
            else {
                var td_a = 'region_star_add';
            }
            $(td_a).update('<img src="http://img3.imgsmail.ru/0.gif" width="16" height="15" border="0" class="load">');
            if (!editing)
                $(places_gid('city_id')).options[0] = new Option('Выбрать', '');
        }
        else
            if (type == 3) {
                if (level != 3) { // Not a Russia, disabling region menu
                    $(places_gid('region_id')).options.length = 0;
                    $(places_gid('region_id')).options[0] = new Option('Выбрать', '');
                    $(places_gid('region_id')).disable();
                }
                places_form_empty(3);
                $(places_gid('city_id')).enable();
                if (editing) {
                    var td_a = 'city_star_edit';
                }
                else {
                    var td_a = 'city_star_add';
                }
                $(td_a).update('<b class="red starr">*</b>');
                list = $(places_gid('city_id'));
            }
            else {
                no_list = 1;
                $(places_gid('city_id')).options.length = 0;
                $(places_gid('city_id')).options[0] = new Option('Другое', 'other');
                $(places_gid('city_id')).enable();
                if (editing) {
                    var td_a = 'city_star_edit';
                }
                else {
                    var td_a = 'city_star_add';
                }
                $(td_a).update('<b class="red starr" >*</b>');
                $(places_gid('city_id_other')).show();
            }
    places_enable_submit();
    if (no_list == 0) {
        var nl = 0;
        if (names != undefined)
            nl = names.length;
        list.options.length = 0;
        var addon = 0;
        list.options[0] = new Option('Выбрать', '');
        addon = 1;
        for (var i = 0; i < nl; i++) {
            list.options[i + addon] = new Option(names[i], ids[i]);
            if (special > 0) {
                list.options[i + addon].style.fontWeight = "bold";
                special--;
            }
        }
        if (type == 3) {
            list.options[list.options.length] = new Option('Другое', 'other');
        }
        if (type == 1 || (type == 3 && is_capital == 1)) {
            list.selectedIndex = 1;
            list.onchange();
        }
    }
    if (!$F(places_gid('city_id')) || $F(places_gid('city_id')) == 'other') {
        places_FillSubway();
        places_FillStreet();
    }
}

// FILL STREET
function places_FillStreet(names, ids, id, not_addable){
    if (!id)
        id = 0;
    places_cleanStreet();
    if (names && names.length) {
        places_FillList('street_name', names, ids, id);
        FillAB('street', places_gid());
        street_length = $(places_gid('street_name')).options.length;
        if (!not_addable) {
            $(places_gid('street_name')).options[street_length] = new Option('Другое', 'other');
        }
    }
    if ($F(places_gid('city_id')) == 'other' || (names && names.length === 0)) {
        $(places_gid('street_name')).enable();
        $(places_gid('ab_compose')).value = '';
        $(places_gid('ab_compose')).show();
        $(places_gid('example_street')).show();
    }
    if (editing) {
        var td_a = 'street_star_edit';
    }
    else {
        var td_a = 'street_star_add';
    }
    $(td_a).update('<img src="http://img0.imgsmail.ru/0.gif" width="16" height="15" border="0" class="load">');
    if (names)
        places_enable_submit();
}

// FILL SUBWAY
function places_FillSubway(names, ids, id){
    if (!id)
        id = 0;
    places_cleanSubway();
    if (names && names.length) {
        places_FillList('subway_id', names, ids, id);
        $(places_gid('subway_id')).enable();
    }
    if (names)
        places_enable_submit();
}

// FILL EDIT FORM
function places_fillEditForm(pid, country_names, country_ids, country_id, region_names, region_ids, region_id, city_names, city_ids, city_id, street_names, street_ids, street_id, house_names, house_ids, house_id, district_name, subway_names, subway_ids, subway_id, type, type_own, period_from, period_to, current_time, main_place, not_addable){
    if (pid == old_pid)
        return;

    var cont = $("edit_form_container_" + pid);
    var old_cont = $("edit_form_container_" + old_pid);
    var form = $("edit_form");
    editing = 1;
    old_cont.hide();
    cont.update(old_cont.innerHTML);
    old_cont.update();
    $('update_pid').value = pid;
    old_pid = pid;

    $('main_place_edit').checked = false;
    $('activity_name_edit').hide();
    $('city_id_other_edit').hide();
    $('city_id_other_edit').value = '';
    $('current_time_edit').checked = false;
    $('toTime_edit').enable();
    $('district_id_edit').value = '';
    $('house_edit').value = '';
    if ($('toTime_edit').options[0])
        $('toTime_edit').options[0].selected = true;
    if ($('period_from_edit').options[0])
        $('period_from_edit').options[0].selected = true;
    $('region_id_edit').options.length = 0;
    $('region_id_edit').disable();
    $('subway_id_edit').options.length = 0;
    $('subway_id_edit').disable();

    if (country_names.length)
        places_FillList('country_id', country_names, country_ids, country_id);
    if (region_names.length)
        places_FillList('region_id', region_names, region_ids, region_id);
    if (city_names.length)
        places_FillList('city_id', city_names, city_ids, city_id);
    if (district_name)
        $('district_id_edit').value = district_name;
    if (subway_names.length)
        places_FillSubway(subway_names, subway_ids, subway_id);
    if (street_names.length)
        places_FillStreet(street_names, street_ids, street_id, not_addable);
    if (period_from) {
        var from = $('period_from_edit').options;
        for (var i = 0; i < from.length; i++) {
            if (from[i].value == period_from) {
                from[i].selected = true;
                break;
            }
        }
    }
    if (period_to) {
        var to = $('toTime_edit').options;
        for (var i = 0; i < to.length; i++) {
            if (to[i].value == period_to) {
                to[i].selected = true;
                break;
            }
        }
    }
    if (current_time) {
        $('current_time_edit').checked = current_time;
        $('toTime_edit').disable();
    }
    $('main_place_edit').checked = main_place ? true : false;
    if (house_names.length) {
        for (var i = 0; i < house_ids.length; i++) {
            if (house_ids[i] == house_id) {
                $('house_edit').value = house_names[i];
                break;
            }
        }
    }
    var activity = $('activity_id_edit').options;
    for (var i = 0; i < activity.length; i++) {
        if (activity[i].value == type) {
            activity[i].selected = true;
            if (activity[i].value == 0) {
                $('activity_name_edit').value = type_own;
                $('activity_name_edit').show();
            }
            break;
        }
    }
    cont.show();
}

/* ONCHANGE ============================================================================ */

// COUNTRTY
function places_onChangeCountry(obj){
    var value = obj.value;
    if (value && value != 'other') {
        places_form_empty(1);
        $(places_gid('region_id')).disable();
        $(places_gid('region_id')).options[0].text = value == '24' ? 'Загрузка...' : 'Выбрать';
        if ($(places_gid('region_id')).options[0].text == 'Загрузка...') {
            if (editing) {
                var td_a = 'region_star_edit';
            }
            else {
                var td_a = 'region_star_add';
            }
            $(td_a).update('<img src="http://img1.imgsmail.ru/r/my/loading.gif" width="16" height="15" border="0" class="load">');
        }
        places_ajax_geo_call(value);

    }
    //places_onblock('close', places_gid('city_id_other'));
}


// REGION
function places_onChangeRegion(obj){
    var value = obj.value;
    is_capital = value == '25' || value == '226' ? 1 : 0;
    if (value && value != 'other') {
        places_form_empty(2);
        $(places_gid('city_id')).disable();
        $(places_gid('city_id')).options[0].text = 'Загрузка...';
        if (editing) {
            var td_a = 'city_star_edit';
        }
        else {
            var td_a = 'city_star_add';
        }
        $(td_a).update('<img src="http://img2.imgsmail.ru/r/my/loading.gif" width="16" height="15" border="0" class="load">');
        places_ajax_geo_call(value);
    }
    //places_onblock('close', places_gid('city_id_other'));
}

// CITY
function places_onChangeCity(obj){
    var value = obj.value;
    places_onblock(obj, places_gid('city_id_other'));
    places_ajax_places_call(value);
}

// STREET
function places_onChangeStreet(obj){
    if (obj.options[obj.selectedIndex].value == 'other') {
        $(places_gid('ab_compose')).show();
        $(places_gid('example_street')).show();
    }
    else {
        $(places_gid('ab_compose')).hide();
        $(places_gid('example_street')).hide();
    }
}

/* CLEAN =============================================================================== */

// STREET
function places_cleanStreet(){
    CleanAB('street', places_gid());
    $(places_gid('street_name')).options.length = 0;
    $(places_gid('street_name')).options[0] = new Option('Другое', 'other');
    $(places_gid('street_name')).options[0].selected = true;
    $(places_gid('street_name')).disable();
    $(places_gid('ab_compose')).value = '';
    $(places_gid('ab_compose')).hide();
    $(places_gid('example_street')).hide();
}

// SUBWAY
function places_cleanSubway(){
    $(places_gid('subway_id')).options.length = 0;
    $(places_gid('subway_id')).disable();
}

/*
 * {reg.tmpl}
 */
function reg_ShowMaidenName(){
    var a = $('sex1').checked;
    var b = $('sex2').checked;
    if (a)
        $('FemaleDiv').hide();
    if (b)
        $('FemaleDiv').show();
}

function reg_downloadfoto(){
    var popupwin = window.open("http://"+PhotoImagineHost+"/cgi-bin/photo/addphoto?myphoto=1&mode=1&Title=&setavatar=1", "dlphoto", "height300,width=600,scrollbars=no");
}


/*
 * {school_search.tmpl}
 */
function EduUpdate(type, opt){
    function decorate(type2, type, string){
        if (type2 == type)
            return '<b>' + string + '</b>';
        else
            return '<a class="dashed" href="#" onclick=school_search_EduUpdate("' + type2 + '")>' + string + '</a>';
    }

    $('edu_menu_school').update(decorate('school', type, 'Найти&nbsp;одноклассников'));
    $('edu_menu_ssuz').update(decorate('ssuz', type, 'Найти&nbsp;друзей&nbsp;по&nbsp;колледжу&nbsp;или&nbsp;ПТУ'));
    $('edu_menu_vuz').update(decorate('vuz', type, 'Найди&nbsp;друзей&nbsp;по&nbsp;ВУЗу'));

    opt = opt ||
    {};
    opt.container = 'edu_container';
    opt.onChange = function onChange(){
        if (this.$F('type') == 'school')
            $('simpbut').disabled = !(this.$('institute_id').selectedIndex != '0' &&
            this.$('startdate').selectedIndex != '0' &&
            this.$('enterdate').selectedIndex != '0' &&
            $('rules_accepted').checked);
        else
            $('simpbut').disabled = !(this.$('institute_id').selectedIndex != '0' &&
            this.$('enterdate').selectedIndex != '0' &&
            $('rules_accepted').checked);
    };
    opt.onLoad = function(){
        $('simpbut').enable();
    };
    EduObjects = {};
    $('edu_container').update();
    $('simpbut').disable();
    cEdu = new Edu(type, opt);
    $('simpbut').value = _eduSearchMessage[type];
    $('edu_top_menu').update(_eduSearchTopMenu[type]);
    return false;
}

/*
 * {search_bare.tmpl}
 */
function search_bare_toggleSubmit(){
    var form = $('search_form');
    $('submitbut').disabled = (form.firstname.value.blank() &&
    form.lastname.value.blank() &&
    form.country.selectedIndex == 0 &&
    form.city.selectedIndex == 0)
}

/*
 * {search_by_interests.tmpl}
 */
function search_by_interests_showHideBlock(oid){
    elem = $(oid);
    if (elem.visible()) {
        elem.hide();
    }
    else {
        elem.show();
    }
}

//function search_by_interests_search_type(){
//    var form = $("search_form");
//    if ($("type1").checked) {
//        type1 = true;
//        bg1 = "#FFF";
//        bg2 = "#D4D0C8";
//    }
//    else {
//        type1 = false;
//        bg1 = "#D4D0C8";
//        bg2 = "#FFF";
//    }
//
//    for (i = 0; i < form.elements.length; i++) {
//        if (form.elements[i].id != "type1" && form.elements[i].id != "type2" && form.elements[i].type != "submit" && form.elements[i].type != "hidden") {
//            if (form.elements[i].id == "email") {
//                form.elements[i].disabled = type1;
//                if (form.elements[i].type != "radio")
//                    form.elements[i].style.backgroundColor = bg2;
//            }
//            else {
//                form.elements[i].disabled = !type1;
//                if (form.elements[i].type != "radio")
//                    form.elements[i].style.backgroundColor = bg1;
//            }
//        }
//    }
//    if ($("type1").checked)
//        birth_type();
//}

/*
 * {search_simple.tmpl}
 */
function search_simple_addToFriendResult(result, id, user_dir){
    var span = $(id);
    var link = $(id + '_friends_link');

    if (result == 'friendship_offer') {
        span.update("Приглашение отправлено");
        link.show();
        tempDiv(false);
    }
    else
        if (result == 'friend_added') {
            span.update("Ура! Вы стали друзьями!");
            link.show();
            tempDiv(false);
        }
        else
            if (result == 'my_invitation_sent') {
                span.update("Пользователю выслано предложение создать свой мир");
                link.show();
                tempDiv(false);
            }
            else
                if (result == 'world_invitation_sent') {
                    span.update("Вы пригласили пользователя поситить свой мир");
                    link.show();
                    tempDiv(false);
                }
                else
                    if (result == 'already_friends') {
                        span.update("Вы уже друзья");
                        link.show();
                        tempDiv(false);
                    }
                    else
                        if (result == 'already_friendship_offer_sent') {
                            span.update("Вы уже выслали предложение");
                            link.show();
                            tempDiv(false);
                        }
                        else
                            if (result == 'invalid_emails') {
                                span.update("Неверный email");
                                tempDiv(false);
                            }
                            else {
                                tempDiv(false);
                                alert('При обработке запроса произошла ошибка. Повторите попытку снова.');
                            }
}

//unused
function search_simple_addToFriendOnMy(id, email){
    tempDiv(true, id);
    ajax_call('perl_add_friend', email, id, search_simple_addToFriendResult);
    return false;
}

//unused
function search_simple_search_type(){
    var form = $("search_form");
    if ($("type1").checked) {
        type1 = true;
        bg1 = "#FFF";
        bg2 = "#D4D0C8";
    }
    else {
        type1 = false;
        bg1 = "#D4D0C8";
        bg2 = "#FFF";
    }

    $A(form.elements).each(function(el){
        if (el.id != "type1" && el.id != "type2" && el.type != "submit" && el.type != "hidden") {
            if (el.id == "email") {
                el.disabled = type1;
                if (el.type != "radio")
                    el.style.backgroundColor = bg2;
            }
            else {
                el.disabled = !type1;
                if (el.type != "radio")
                    el.style.backgroundColor = bg1;
            }
        }
    });
    if ($("type1").checked)
        search_simple_birth_type();
}

//unused
function search_simple_birth_type(){
    if ($("type1").checked) {
        if ($("date1").checked) {
            $("birth_day").enable().style.backgroundColor = "#FFF";
            $("birth_month").enable().style.backgroundColor = "#FFF";
            $("birth_zodiac").disable().style.backgroundColor = "#D4D0C8";
        }
        else {
            $("birth_day").disable().style.backgroundColor = "#D4D0C8";
            $("birth_month").disable().style.backgroundColor = "#D4D0C8";
            $("birth_zodiac").enable().style.backgroundColor = "#FFF";
        }
    }
}

function search_simple_toggleSubmit(){
    var form = $('search_form');
    $('submitbut').disabled = (form.firstname.value.blank() &&
    form.lastname.value.blank() &&
    form.country.selectedIndex == 0 &&
    form.city.selectedIndex == 0)
}

/*
 * {search.tmpl}
 */
function search_search_type(){
    var form = $("search_form");
    if ($("type1").checked) {
        type1 = true;
        bg1 = "#FFF";
        bg2 = "#D4D0C8";
    }
    else {
        type1 = false;
        bg1 = "#D4D0C8";
        bg2 = "#FFF";
    }

    $A(form.elements).each(function(el){
        if (el.id != "type1" && el.id != "type2" && el.type != "submit" && el.type != "hidden") {
            if (el.id == "email") {
                el.disabled = type1;
                if (el.type != "radio")
                    el.style.backgroundColor = bg2;
            }
            else {
                el.disabled = !type1;
                if (el.type != "radio")
                    el.style.backgroundColor = bg1;
            }
        }
    });
    if ($("type1").checked)
        search_birth_type();
}

function search_birth_type(){
    if ($("type1").checked) {
        if ($("date1").checked) {
            $("birth_day").enable().style.backgroundColor = "#FFF";
            $("birth_month").enable().style.backgroundColor = "#FFF";
            $("birth_zodiac").disable().style.backgroundColor = "#D4D0C8";
        }
        else {
            $("birth_day").disable().style.backgroundColor = "#D4D0C8";
            $("birth_month").disable().style.backgroundColor = "#D4D0C8";
            $("birth_zodiac").enable().style.backgroundColor = "#FFF";
        }
    }
}

function search_toggleSubmit(){
    var form = $('search_form');
    $('submitbut').disabled = (form.firstname.value.blank() &&
    form.sex0.checked &&
    form.age.value.blank() &&
    form.lastname.value.blank() &&
    form.country.selectedIndex == 0 &&
    form.city.selectedIndex == 0 &&
    form.religion_custom.value.blank() &&
    form.politics.value.blank())
}

/*
 * {selectsubject_compiled.tmpl}
 */
function selectsubject_compiled_nopen(id){
    $('d' + id).show();
    $('i' + id).src = open_img;
}

function selectsubject_compiled_nclose(id){
    $('d' + id).hide();
    $('i' + id).src = close_img;
}

function selectsubject_compiled_nclick(id){
    if (close_re.test($('i' + id).src)) {
        selectsubject_compiled_nopen(id);
    }
    else {
        selectsubject_compiled_nclose(id);
    }
}

function selectsubject_compiled_rclick(robj){
    var node = robj.parentNode;
    var path = '';
    var first = true;
    var uid, text;
    robj.checked = 1;
    while (node != 'undefined') {
        if (node.tagName == 'P' || node.tagName == 'DIV') {
            uid = node.id;
            uid = uid.substr(1);
            for (var i = 0; i < id.length; i++) {
                if (id[i] == uid) {
                    text = name[i];
                    break;
                }
            }
            if (uid <= 2)
                break;
            if (first) {
                path = text;
                first = false;
            }
            else {
                path = text + '/' + path;
            }
        }
        node = node.parentNode;
    }
    document.forms['subject'].elements['subject_id'].value = robj.value;
    document.forms['subject'].elements['subject_text'].value = path;
}

function selectsubject_compiled_closewindow(){
    var subject_id = document.forms['subject'].elements['subject_id'].value;
    var subject_text = document.forms['subject'].elements['subject_text'].value;
    opener.document.forms['community'].elements['SubjectID'].value = subject_id;
    opener.$('SubjectText').update(subject_text);
    close();
    return false;
}

/*
 * {startfriendship_popup.tmpl}
 */
function startfriendship_popup_check_all(){
    $('invite').getElementsBySelector('input[type=checkbox]').invoke('writeAttribute', 'checked', $('check_all').checked);
}

function startfriendship_popup_save_please(exit_popup){
    var savevinp = $('save');
    var emails = savevinp.value.split(',');
    $('invite').getElementsBySelector('input[type=checkbox]').each(function(el){
        var duplicate = 1;
        emails.each(function(em){
            if (em && em.toLowerCase() == el.value.toLowerCase()) {
                if (el.checked) {
                    duplicate = 0;
                }
                else {
                    em = null;
                }
            }
        });
        if (el.checked && duplicate)
            emails.push(el.value);
    });

    var emails2 = emails.compact();

    if (opener != undefined) {
        opener.$(Type+"_checkbox").value = emails2.join(',');
        savevinp.value = emails2.join(',');
        if (exit_popup) {
            window.opener.count_friends(Type+"_checkbox");
            window.close();
        }
        else {
            window.opener.count_friends(Type+"_checkbox");
            $('invite').submit();
        }
    }
}

function startfriendship_popup_checking_all(){
    if (!checking_ready)
        return;
    var checked_all = true;
    elements.each(function(el){
        emails.each(function(em){
            if (em.toLowerCase() == el.value.toLowerCase()) {
                el.checked = true;
            }
        });
        if (!el.checked) {
            checked_all = false;
        }
    });
    $('check_all').checked = checked_all;
}

/*
 * {startfriendship.tmpl}
 */
function startfriendship_sendOrNo(){
    var flag = 0
    $A(window.document.forms['startform'].elements).each(function(el){
        if (el.checked)
            flag = 1;
    });
    if (flag != 1) {
        window.document.forms['startform'].elements['Save'].value = ' Перейти в Мой Мир ';
    }
    else {
        window.document.forms['startform'].elements['Save'].value = ' Отправить приглашения и перейти в Мой Мир ';
    }
}

function startfriendship_check(box){
    if (box.checked) {
        box.value = default_box_values[box.id];
        startfriendship_count_friends(box.id);
    }
    else {
        box.value = '';
        startfriendship_count_friends(box.id);
    }
}

function startfriendship_count_friends(type){
    var emails = $F(type).split(',');
    var emails2 = emails.compact();
    $(type + '_count').update(emails2.length);
    if (emails2.length == 0) {
        $(type).checked = false;
    }
    else {
        $(type).checked = true;
    }
}

function startfriendship_addEmailField(){
    var ol = $("emailsList");
    var li = new Element("LI");
    var input = new Element("INPUT", {'name': 'Emails', 'class': 'inp'});
    li.appendChild(input);
    ol.appendChild(li);
    input.focus();
}

/*
 * {userinfo.tmpl}
 */
function userinfo_formUnload(){
    var msg = "На странице есть несохраненные изменения. ";
    msg += "Чтобы сохранить изменения, нажмите \"Отмена\", ";
    msg += "а затем \"Сохранить\".";
    return msg;
}

function userinfo_formSubmit(){
    window.onbeforeunload = null;
    return true;
}

function userinfo_formChanged(){
    if (window.onbeforeunload == null)
        window.onbeforeunload = userinfo_formUnload;
}

function userinfo_ShowMaidenName(){
    var a = $('sex1').checked;
    var b = $('sex2').checked;
    if (a)
        $('FemaleDiv').hide();
    if (b)
        $('FemaleDiv').show();
}

function userinfo_partner(value1){
    if (!partnershipPermitted.exists(value1)) {
        flag = 1;
        $('PartnerNick').hide();
        $('partner_select_button_tr').hide();
        $('PartnerNick').value = 'Выберите партнера';
        $('PartnerNick2').value = '';
        $('PartnerEmail').value = '';
    }
    else {
        flag = 0;
        $('PartnerNick').show();
        $('partner_select_button_tr').show();
    }
    $('partner_select_button').disabled = flag;
}

function userinfo_part_symbols(){
    num = $F('PartnerNick');
    if (num != 'Выберите партнера' && num != PartnerNick) {
        $('AlertText').show();
    }
    else {
        $('AlertText').hide();
    }
}

function userinfo_insertFriendsMail(nicks, mails){
    $("PartnerNick").value = nicks;
    $("PartnerNick2").value = nicks;
    $("PartnerEmail").value = mails;
}

function userinfo_showFriendsList(){
    if (mailPopup && mailPopup.close)
        mailPopup.close();
    mailPopup = window.open(MyMailDir + "friends?popup_list=2", 'mailPopup', 'width=240,height=350,top=' + (parseInt(screen.height / 2) - 150) + ',left=' + (parseInt(screen.width / 2) - 150) + ',toolbars=no,scrollbars=no,menubar=no,resizable=no,location=no,status=no,directories=no');
    if (mailPopup && mailPopup.focus)
        mailPopup.focus();
}

function setDefaultValueForInput(event, element){
        element = $(element);
        if(!element.readAttribute('passiveClass')) element.writeAttribute('passiveClass', element.className);
        if(!element.readAttribute('defaultValue')) element.writeAttribute('defaultValue', element.value);
        element.observe('blur', function(){setDefaultValueForInput(null, element)});
        if(event) { if(element.value == element.readAttribute('defaultValue')) 
            element.value = ''; element.className = element.readAttribute('passiveClass') + ' black' }
        else { if(!element.value) 
            element.value = element.readAttribute('defaultValue'); element.className = element.readAttribute('passiveClass') }
}

/*
 * common captcha
 */


function CaptchedForm( p ) {
	this.form = $(p.formId);
	if(!this.form)
		return;
	
	var _this = this;
	this.form.captcha = {
		submit: function(){
			_this.onSubmit.apply(_this, arguments);
		}
	}
	
	if(p.handleSumbit) {
		this.form.onsubmit = function (){ return false;};
		this.form.observe('submit', this.onSubmit.bindAsEventListener(this));
	}
	
	this.p = p;
	
	if(p.captchaURL)
		this.captchaURL = p.captchaURL;
		
}

CaptchedForm.prototype = {
	captchaURL: 'http://my.mail.ru/cgi-bin/my/get_image?id=',
	htmlCreated: false,
	firstSend: true,
	captchaShown: false,
	captchaOpen:false,
	
	onSubmit: function(e){
		e && e.stop();
		
		if(typeof this.p.onBeforeSubmit == 'function')
			this.p.onBeforeSubmit.apply(this, arguments);
		
		if(!this.captchaOpen && this.captchaShown) {
			this.show();
		} else if(this.captchaOpen && this.captchaShown && this.captcha_input.value.replace(/\s*/, '')=='') {
			alert('Введите число, изображенное на картинке');
			this.show();
		} else {
		
			var seq = this.p.sequence;
			var req = [];
			for(var i = 0, seq_len = this.p.sequence.length; i < seq_len; i++){
				var t = $(seq[i]);
				if(t)
					req[req.length] = t.value;
				else
					req[req.length] = null;
				t = null;
			}
			
			new Ajax.Request(this.p.action, {
				method: 'post',
				postBody: 'data=' + req.toJSON(),
				onSuccess: this.responseHandler.bindAsEventListener(this)
			});
			
			if(this.captcha_input)
				this.captcha_input.value = '';
				
		
		}
	},
	
	
	
	responseHandler: function(t){
		if(t){
			var data = t.responseText.evalJSON(true);
			
			if(data[0] != 'AjaxResponse')
				return;
			if(data[1] == 'OK') {
				data.splice(0, 2);
				
				var captcha_id = this.p.resultDispatcher.apply(this, data);
				if(captcha_id) {
					this.show();
					$(this.p.prefix+'_captcha_id').value = captcha_id;
					this.captchaPointer.style.backgroundImage = 'url('+this.captchaURL+captcha_id+')';
					
					this.captchaShown = true;
					
					if(!this.firstSend)
						alert('Вы неверно ввели число, изображенное на картинке');
					this.firstSend = false;
					
				} else {
					this.hide();
					if(typeof this.p.onSuccess == 'function')
						this.p.onSuccess(t);

					this.captchaShown = false;
					
					this.firstSend = true;
				}
			}
		}
	},
	
	show: function(){
		if( !this.htmlCreated && !this.captchaPointer ) {
			if( (this.captchaPointer = $(this.p.prefix+'_captcha_container')) ){
				this.htmlCreated = true;
			} else {
				var t = this.form.appendChild(document.createElement('div'));
				t.innerHTML = '\
<div style="display: none;" id="'+this.p.prefix+'_captcha_container" class="capchaNewLeft">\
	<i id="'+this.p.prefix+'_toggle_captcha_button" class="mf_spIco"></i>Введите число,<br/>изображенное на картинке:\
	<div class="mt5">\
		<input name="captcha_id" type="hidden" id="'+this.p.prefix+'_captcha_id"/>\
		<input name="captcha_value" type="text" onkeypress="if(event.keyCode == 13) { document.getElementById(\''+this.p.prefix+'_captcha_submit\').click(); return false;}" id="'+this.p.prefix+'_captcha_input" class="capchaNewInp"/>\
		<input type="submit" id="'+this.p.prefix+'_captcha_submit" value="ОК" name="btn_ok"/>\
	</div>\
</div>';
				this.captchaPointer = $(this.p.prefix+'_captcha_container');
				this.htmlCreated = true;
			}
			
			$(this.p.prefix+'_toggle_captcha_button').observe('click', this.onClose.bindAsEventListener(this));
			if( this.p.onCaptchaSubmit )
				$(this.p.prefix+'_captcha_submit').observe('click', this.p.onCaptchaSubmit);
			this.captcha_input = $(this.p.prefix+'_captcha_input');
		}
		
		this.captchaPointer.style.display = 'block';
		this.captchaOpen = true;
		
	},
	
	hide: function(){
		if(this.captchaPointer)
			this.captchaPointer.style.display = 'none';
		this.captchaOpen = false;
	},
	
	onClose: function() {
		
		this.hide();
		this.firstSend = true;
	}
	
	
}
