(function($){var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.toJSON=typeof JSON==='object'&&JSON.stringify?JSON.stringify:function(o){if(o===null){return'null';}
var type=typeof o;if(type==='undefined'){return undefined;}
if(type==='number'||type==='boolean'){return''+o;}
if(type==='string'){return $.quoteString(o);}
if(type==='object'){if(typeof o.toJSON==='function'){return $.toJSON(o.toJSON());}
if(o.constructor===Date){var month=o.getUTCMonth()+1,day=o.getUTCDate(),year=o.getUTCFullYear(),hours=o.getUTCHours(),minutes=o.getUTCMinutes(),seconds=o.getUTCSeconds(),milli=o.getUTCMilliseconds();if(month<10){month='0'+month;}
if(day<10){day='0'+day;}
if(hours<10){hours='0'+hours;}
if(minutes<10){minutes='0'+minutes;}
if(seconds<10){seconds='0'+seconds;}
if(milli<100){milli='0'+milli;}
if(milli<10){milli='0'+milli;}
return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i])||'null');}
return'['+ret.join(',')+']';}
var name,val,pairs=[];for(var k in o){type=typeof k;if(type==='number'){name='"'+k+'"';}else if(type==='string'){name=$.quoteString(k);}else{continue;}
type=typeof o[k];if(type==='function'||type==='undefined'){continue;}
val=$.toJSON(o[k]);pairs.push(name+':'+val);}
return'{'+pairs.join(',')+'}';}};$.evalJSON=typeof JSON==='object'&&JSON.parse?JSON.parse:function(src){return eval('('+src+')');};$.secureEvalJSON=typeof JSON==='object'&&JSON.parse?JSON.parse:function(src){var filtered=src.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered)){return eval('('+src+')');}else{throw new SyntaxError('Error parsing JSON, source is not valid.');}};$.quoteString=function(string){if(string.match(escapeable)){return'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};})(jQuery);

function lng(str) {
    if (typeof (LANG_CACHE[str]) != 'undefined') str = LANG_CACHE[str];
    return str;
}

function setCommunityMemberAlvl(select) {
    $.post(CURRENT_SITE + '/communities/set_access_level', {
        id: select.id.substr(7),
        alvl: select.value
    }, function (data) {
        alert(lng('Права доступа изменены'))
    });
}

function get_location() {
    return window.location.toString();
}

function rpc_action(param) {
    performAction(param);
}

function utime() {
    var d = new Date();
    return Math.floor(d.getTime() / 1000);
}

/*
var __openWindowsCount = 0;
var __currentWindowsZindex = 10000;

function __createWindow(width, height, title, icon, url, id, html) {
    if (document.getElementById(id)) return modal_to_top(id);
    if (typeof (userIsLogged) != 'undefined' && userIsLogged == 1) {
        var offset = 32;
        var topshift = 50;
    } else {
        var offset = 0;
        var topshift = 10;
    }
    var window_width = $(window).width();
    if (navigator.appName == 'Opera') {
        window_width = window.innerWidth;
    }
    if (!document.getElementById('window_dimmer')) {
        if (IE6) {
            offset = $(window).scrollTop();
            topshift = offset + 10;
            var hh = $(window).height() + offset;
        } else {
            var hh = $(window).height() - offset;
        }
        $('body').append('<div id="window_dimmer" style="width: ' + window_width + 'px;height: ' + hh + 'px;left: 0px;top: ' + offset + 'px;background-color:#a2a8af;z-index: 9999; opacity:0.5; filter: alpha(opacity = 50);">&nbsp;</div>');
    }
    if (__openWindowsCount == 0) {
        var fo;
        if (fo = document.getElementsByName('flash_object_div')) {
            for (var i = 0; i < fo.length; i++) {
                fo[i].style.display = 'none';
            }
        }
    }
    if (!width) width = '98%';
    if (!height) height = '100%';
    if (!title) title = "";
    if (!icon) icon = "default_50.png";
    width = width.toString();
    height = height.toString();
    if (width.match(/\%/)) {
        width = window_width * parseInt(width) / 100;
    } else {
        width = parseInt(width);
    }
    if (width > 1600) width = 1600;
    var leftpoint = (window_width - width) / 2;
    if (IE6) {
        if (height.match(/\%/)) {
            height = ($(window).height() * parseInt(height) / 100);
        } else {
            height = parseInt(height);
        }
        var toppoint = topshift + ($(window).height() - height) / 2;
    } else {
        if (height.match(/\%/)) {
            height = ($(window).height() * parseInt(height) / 100) - topshift;
        } else {
            height = parseInt(height);
        }
        var toppoint = topshift + ($(window).height() - height - topshift) / 2;
    }
    var contentHeight = height - 52;
    $('body').append('<div class="window1" id="' + id + '" style="top: ' + toppoint + 'px;left: ' + leftpoint + 'px;width: ' + width + 'px;height: ' + height + 'px;z-index: ' + __currentWindowsZindex + '">' + '<div class="popup"><div class="shadow_lt"></div><div class="shadow_t"></div><div class="shadow_rt"></div><div class="shadow_l" style="height: ' + contentHeight + 'px"></div>' + '<div class="icon" style="background: url(' + RESOURCE_PATH + '/img/id.ua/panel/' + icon + ') no-repeat;//background: none !important;filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + RESOURCE_PATH + '/img/id.ua/panel/' + icon + '\', sizingMethod=\'crop\');"></div><div class="title">' + title + '</div>' + ((html && html != 'undefined') ? '' : '<!-- <a href="javascript:void(0)" onclick="__reloadWindow(\'' + id + '\', \'' + url + '\')" class="reloadB">' + lng('Обновить') + '</a><a href="javascript:void(0)" onclick="__reloadWindow(\'' + id + '\',\'' + url + '\')" class="reloadBtn"><img src="' + RESOURCE_PATH + '/img/___window/reloadButton.png"></a> -->') + '<a href="javascript:void(0)" onclick="__closeWindow(\'' + id + '\')" class="closeB">' + lng('Закрыть') + '</a><a href="javascript:void(0)" onclick="__closeWindow(\'' + id + '\')" class="closeBtn"><img src="' + RESOURCE_PATH + '/img/___window/closeButton.png"></a><div><div class="spacer"></div><div class="cont" id="' + id + '_cont" style="height: ' + (contentHeight - 40) + 'px"><img src="' + RESOURCE_PATH + '/img/misc/indicator.gif" /></div></div>' + '<div class="shadow_r" style="height: ' + contentHeight + 'px"></div><div class="shadow_lb"></div><div class="shadow_b"></div><div class="shadow_rb"></div></div></div>');
    $('#' + id + '_cont').ifixpng();
    if (html && html != 'undefined') $('#' + id + '_cont').html(html);
    else $('#' + id + '_cont').load(url);
    __openWindowsCount++;
    __currentWindowsZindex++;
}

function __closeWindow(id) {
    if (typeof (swfu) != 'undefined' && id == 'win_add') {
        var movie = swfu.getMovieElement();
        var placeHolder = document.createElement("span");
        placeHolder.id = "spanButtonPlaceHolder";
        movie.parentNode.replaceChild(placeHolder, movie);
        swfu.destroy();
    }
    __openWindowsCount--;
    if (__openWindowsCount == 0) {
        var fo;
        if (fo = document.getElementsByName('flash_object_div')) {
            for (var i = 0; i < fo.length; i++) {
                fo[i].style.display = 'block';
            }
        }
    }
    $('#' + id).remove();
    if (__openWindowsCount <= 0) $('#window_dimmer').remove();
}

function __reloadWindow(id, url) {
    $('#' + id + '_cont').load(url);
}

function open_dialog(opt) {
    __createWindow(opt.w, opt.h, opt.title, opt.icon, opt.url, opt.id);
}*/

function modal_to_top(id) {
    __currentWindowsZindex++;
    $("#" + id).css('z-index', __currentWindowsZindex);
}

function open_win_remindpassword() {
    /*var win = 'win_remindpassword';
    var jdiv = open_dialog({
        title: lng('Напоминание пароля'),
        id: win,
        w: '600px',
        h: '300px',
        url: CURRENT_SITE + '/remindpassword'
    });*/
	
	Window.load(CURRENT_SITE + '/remindpassword', 'win_remindpassword', lng('Восстановление пароля'));
}

function getZIndex(element) {
    if (element.currentStyle) {
        zIndex = element.currentStyle['zIndex'];
    } else if (window.getComputedStyle) {
        zIndex = window.getComputedStyle(element, '').getPropertyValue("z-index");
    }
}
/*
function open_win_reg(action, community, laters) {
    action = (action) ? "?action=" + action : '';
    if (community) w = 980;
    else w = 600;
    w = 800;
    if (community) h = "100%";
    else h = 500;
    var url = CURRENT_SITE + '/register' + action;
    if (!laters) laters = '';
    else url = CURRENT_SITE + '/register/?laters=' + laters;
    var win = 'win_register';
    var jdiv = open_dialog({
        modal: false,
        title: lng('Регистрация'),
        id: win,
        url: url,
        w: w,
        h: h
    });
    return false;
}*/

function form_hilite_errors(form_id, errors) {
    var jF = $(form_id);
    if (!typeof (errors) == 'mbject') return;
    $(form_id + ' .error').removeClass('error');
    $('.err_msg').hide();
    for (var fld in errors) {
        if (fld.indexOf('fields[') >= 0) {
            var inp = $("input[name='" + fld + "'], textarea[name='" + fld + "'], select[name='" + fld + "']", jF);
        } else {
            var inp = $("input[name='item[" + fld + "]'], textarea[name='item[" + fld + "]'], select[name='item[" + fld + "]']", jF);
        }
        inp.addClass("error");
        $('.err_msg.' + fld).show();
    }
}

function resetErrors(form_id) {
    $(form_id + ' .error').removeClass('error');
    $(form_id + ' .error').parent().find('.err_msg').hide();
}

function formHighlightErrors(form_id, errors) {
    var jF = $(form_id);
    if (!typeof (errors) == 'mbject') return;
    $(form_id + ' .error').removeClass('error');
    for (var fld in errors) {
        var inp = $("input[name='" + fld + "'], textarea[name='" + fld + "'], select[name='" + fld + "']", jF);
        inp.addClass("error");
        inp.parent().find('.err_msg').show();
    }
}

function reset_value(el, defvalue, chcolor) {
    if (typeof (chcolor) === "undefined") chcolor = true;
    if (el.value == defvalue) {
        el.value = '';
    }
    if (chcolor) {
        $(el).removeClass('grayed');
        if ($(el).hasClass('error')) {} else {}
    }
}

function unset_value(el, defvalue) {
    if (el.value == '') {
        el.value = defvalue;
        $(el).addClass('grayed');
    }
}

function quotemeta(str) {
    bs = String.fromCharCode(92);
    unsafe = bs + ".+*?[^]$(){}=!<>|:";
    for (i = 0; i < unsafe.length; ++i) {
        str = str.replace(new RegExp(bs + unsafe.charAt(i), "g"), bs + unsafe.charAt(i));
    }
    return str;
}

function win_close(el) {
	Window.close($(el).parents('.window1').attr('id'));
}

function win_close_by_win_id(id) {
    Window.close(id);
}

function win_title(el, title) {}

function LoginPrecheck(form) {
    var rep = $.post(CURRENT_SITE + "/check_login", {
        "item[login]": $('#panel_login').val(),
        "item[pass]": $('#panel_pass').val()
    }, function (data) {
        if (data.success == "true") {
            form.submit();
        } else {
            $.jGrowl(lng("Логин или пароль неправильные :("), {
                header: lng("Войти не получилось")
            });
            return false;
        }
    }, "json");
    return false;
}

function setSubtitle(modal_name, text) {
    $('.win_' + modal_name + '_ico').parent().children('.ui-dialog-subtitle').html('' == text ? '' : '| ' + text)
}

function newGroup(select, name) {
    var name = name ? name : 'new_group'
    if ('new_g' === select.value) {
        if ($('#' + name).attr('id') == name) {
            $('#' + name).show()
        } else $(select).after('<br /><input type="text" name="' + name + '" id="' + name + '" style="width: 100px; margin-top: 5px;" />')
        $('#' + name).focus()
    } else {
        $('#' + name).hide()
    }
}

function sendForm(form, target, callback) {
    var form_data = new Object()
    form_data['rnd'] = Math.random()
    var form = $(form)
    form.find(':input, :text, :password, :radio, :checkbox, :file, :hidden').each(function (i) {
        if (this.name) {
            if ('checkbox' === this.type || 'radio' === this.type) {
                if ('checked' === this.checked || true === this.checked) {
                    form_data[this.name] = this.value
                }
            } else form_data[this.name] = this.value
        }
    });
    $.post(form.attr('action'), form_data, function (data) {
        if ($.isFunction(callback)) {
            callback(data, target)
        } else {
            $(target).html(data);
        }
    }, 'json');
    return false;
}

function sendFormHTML(form, target, callback) {
    var form_data = new Object()
    form_data['rnd'] = Math.random()
    $(form).find(':input, :text, :password, :radio, :checkbox, :file, :hidden').each(function (i) {
        if (this.name) {
            if ('checkbox' === this.type || 'radio' === this.type) {
                if ('checked' === this.checked || true === this.checked) {
                    form_data[this.name] = this.value
                }
            } else form_data[this.name] = this.value
        }
    });
    $.post(form.action, form_data, function (data) {
        if ($.isFunction(callback)) {
            callback(data, target)
        } else {
            $(target).html(data);
        }
    }, 'html');
    return false;
}

function translit(str) {
    A = new Array();
    A["Ё"] = "YO";
    A["Й"] = "I";
    A["Ц"] = "TS";
    A["У"] = "U";
    A["К"] = "K";
    A["Е"] = "E";
    A["Н"] = "N";
    A["Г"] = "G";
    A["Ш"] = "SH";
    A["Щ"] = "SCH";
    A["З"] = "Z";
    A["Х"] = "H";
    A["Ъ"] = "'";
    A["ё"] = "yo";
    A["й"] = "i";
    A["ц"] = "ts";
    A["у"] = "u";
    A["к"] = "k";
    A["е"] = "e";
    A["н"] = "n";
    A["г"] = "g";
    A["ш"] = "sh";
    A["щ"] = "sch";
    A["з"] = "z";
    A["х"] = "h";
    A["ъ"] = "'";
    A["Ф"] = "F";
    A["Ы"] = "Y";
    A["В"] = "V";
    A["А"] = "A";
    A["П"] = "P";
    A["Р"] = "R";
    A["О"] = "O";
    A["Л"] = "L";
    A["Д"] = "D";
    A["Ж"] = "ZH";
    A["Э"] = "E";
    A["ф"] = "f";
    A["ы"] = "y";
    A["в"] = "v";
    A["а"] = "a";
    A["п"] = "p";
    A["р"] = "r";
    A["о"] = "o";
    A["л"] = "l";
    A["д"] = "d";
    A["ж"] = "zh";
    A["э"] = "e";
    A["Я"] = "YA";
    A["Ч"] = "CH";
    A["С"] = "S";
    A["М"] = "M";
    A["И"] = "I";
    A["Т"] = "T";
    A["Ь"] = "'";
    A["Б"] = "B";
    A["Ю"] = "YU";
    A["я"] = "ya";
    A["ч"] = "ch";
    A["с"] = "s";
    A["м"] = "m";
    A["и"] = "i";
    A["т"] = "t";
    A["ь"] = "'";
    A["б"] = "b";
    A["ю"] = "yu";
    var result = str.replace(/([\u0410-\u0451])/g, function (str, p1, offset, s) {
        if (A[str] != 'undefined') {
            return A[str];
        }
    });
    return result;
}
var action = document.location.toString();
if (action.match('#register')) {
    jQuery(document).ready(function () {
        open_win_reg('', '');
    })
}
if (action.match('#community_register')) {
    jQuery(document).ready(function () {
        open_win_reg('', '1');
    })
}

function get_com_list(i) {
    var rep = $.post(CURRENT_SITE + "/get_com_list", {
        "item": i
    }, function (response) {
        $("#com_list").html(response);
    }, "html");
    return false;
}

function open_win_avatar_callback(func) {
    window.win_avatar_callback = func;
    open_win_avatar();
    return false;
}

function cup_open_win_avatar(fid, avatar_id) {
    $('#edit_pf_form').attr('avatar_field_id', fid);
    open_win_avatar_callback(cup_set_avatar_id);
    return false;
}

function cup_set_avatar_id(id, src) {
    var fid = $('#edit_pf_form').attr('avatar_field_id');
    var jel = $("#edit_pf_form input[name='item[field_" + fid + "]']");
    if (id && jel.size()) jel.val(id);
    if (src) $("#img_avatar_" + fid).attr('src', src + '_s');
}

function openWinAvatar(fid, avatar_id, el) {
    window.avatar_field_id = fid;
    window.cur_element = el;
    open_win_avatar_callback(setAvatarID);
    return false;
}

function setAvatarID(id, src) {
    var fid = window.avatar_field_id;
    var jel = $(window.cur_element).prev();
    if (id && jel.size()) jel.val(id);
    if (src) {
        $(window.cur_element).children('#avatar_img').attr('src', src + '_s');
    }
}

function postData(to, p) {
    var myForm = document.createElement("form");
    myForm.method = "post";
    myForm.action = to;
    for (var k in p) {
        var myInput = document.createElement("input");
        myInput.setAttribute("name", k);
        myInput.setAttribute("value", p[k]);
        myForm.appendChild(myInput);
    }
    document.body.appendChild(myForm);
    myForm.submit();
    document.body.removeChild(myForm);
}

function open_win_file(cid) {
   /* var win = 'win_file';
    var jdiv = open_dialog({
        title: lng('Файлы'),
        id: win,
        url: CURRENT_SITE + '/file?cid=' + cid,
        w: 600,
        h: 450
    });*/
	Window.load(CURRENT_SITE + '/file?cid=' + cid, 'win_file', lng('Файлы'));
}

function open_win_file_callback(func, field_id, imid, cid) {
    window.win_file_callback = func;
    window.cur_field_id = field_id;
    window.cur_image_id = imid;
    open_win_file(cid);
    return false;
}

function file_callback(fid, src, name) {
    if (window.cur_field_id) {
        $("input[name='" + window.cur_field_id + "']").val(fid);
        if (src) $("#" + window.cur_image_id).attr('src', src);
        if (name) $("#" + window.cur_image_id).attr('title', name);
    }
}

function openWinRules() {
    /*var win = 'wm_rules';
    var jdiv = open_dialog({
        title: lng('Пользовательское соглашение'),
        id: win,
        url: '/site/rules',
        w: 620,
        h: 560
    });*/
	
	Window.load('/site/rules', 'win_rules', '');
}

function openWinAddSiteToFavs() {
    _gaq.push(['_trackEvent', 'Loyalty', 'HomePage', location.href]);
    /*var win = 'wm_addtofavs';
    var jdiv = open_dialog({
        title: lng('Добавить сайт в избранное'),
        id: win,
        url: '/site/addtofavs',
        w: 520,
        h: 360
    });*/
	
	Window.load('/site/addtofavs', 'win_addtofavs', lng('Добавить сайт в избранное'));
}

function addSiteToFavs(elem, title, url) {
    _gaq.push(['_trackEvent', 'Loyalty', 'Bookmark', url]);
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    } else if (document.all) {
        window.external.AddFavorite(url, title);
    } else if (window.opera && window.print) {
        elem.setAttribute('href', url);
        elem.setAttribute('title', title);
        elem.setAttribute('rel', 'sidebar');
    }
}

function setCursorSatellite(img) {
    if ($('#cursorSatellite').length <= 0) {
        $('body').append('<div id="cursorSatellite"></div>');
        $('#cursorSatellite').append('<img src="' + img + '" />');
        if (window.cursorPosX != 'undefined' && window.cursorPosY != 'undefined') {
            $('#cursorSatellite').css('top', window.cursorPosY);
            $('#cursorSatellite').css('left', window.cursorPosX + 15);
        }
    }
}

function resetCursorSatellite() {
    if ($('#cursorSatellite').length > 0) {
        $('#cursorSatellite').remove();
    }
    return true;
}

function insert_into_position_cursor(textarea, text) {
    var textarea = document.getElementById();
    if (textarea.createTextRange && textarea.caretPos) {
        var caretPos = textarea.caretPos;
        caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
    } else {
        if (is_nav && document.getElementById) {
            mozillaWr(textarea, '', text);
        } else {
            textarea.value += text;
        }
    }
    textarea.focus();
}

function getKeyValueFromString(string, separator) {
    if (!string || string == 'undefined') return false;
    if (!separator || separator == 'undefined') separator = '_';
}

function openWinLogin(goto) {
    if (!goto || goto == 'undefined') goto = '';
    Window.load(CURRENT_SITE + '/modal/login/?goto=' + escape(goto), 'win_login');
    return false;
}
var lightBoxOptions = {
    fixedNavigation: true,
    imageLoading: RESOURCE_PATH + '/img/misc/indicator.gif',
    txtImage: lng(''),
    txtOf: lng('из')
};
$(function () {
    $('.childAvatar a, #childAvatar a').lightBox(lightBoxOptions);
    $('#advPhoto').lightBox(lightBoxOptions);
});

function initCaptcha(captcha, func) {
    window.win_submitForm_callback = func;
    /*__createWindow(350, 250, 'CAPTCHA', '', '', 'win_captcha_code', '<div class="popupHeader">Введите код с картинки</div><form id="checkCaptcha" action="/captcha/check"><table class="thinFrame"><tr><td class="frame_tl"><div></div></td><td class="frame_tm"></td><td class="frame_tr"></td></tr><tr><td class="frame_ml"></td><td class="frame_mm" style="padding: 10px;"><table width="200px"><tr><td align="center" width="150px"><span id="captcha">' + captcha + '</span></td><td align="left"><a href="javascript:void(0)" onclick="reloadCaptcha(this)"><img src="' + RESOURCE_PATH + '/img/___window/reloadButton.png"></a></td></tr></table><br/><center><input type="text" name="code" id="captchaCode"/></center><br /><div align="center"><input type="image" class="pngfix" src="' + RESOURCE_PATH + '/img/buttons/' + ((LANGUAGE != 'undefined' && LANGUAGE == 'ua') ? 'ukr' : '') + '/addBtn.png" value=Вставить onclick="checkCaptcha(); return false;" /></div></td><td class="frame_mr"></tr><tr></td><td class="frame_bl"></td><td class="frame_bm"></td><td class="frame_br"><div></div></td></tr></table></form>');*/
	
	Window.create({header: lng('Введите код с картинки'), body: '<form id="checkCaptcha" action="/captcha/check"><table class="thinFrame"><tr><td class="frame_tl"><div></div></td><td class="frame_tm"></td><td class="frame_tr"></td></tr><tr><td class="frame_ml"></td><td class="frame_mm" style="padding: 10px;"><table width="200px"><tr><td align="center" width="150px"><span id="captcha">' + captcha + '</span></td><td align="left"><a href="javascript:void(0)" onclick="reloadCaptcha(this)"><img src="' + RESOURCE_PATH + '/img/___window/reloadButton.png"></a></td></tr></table><br/><center><input type="text" name="code" id="captchaCode"/></center><br /><div align="center"><input type="image" class="pngfix" src="' + RESOURCE_PATH + '/img/buttons/' + ((LANGUAGE != 'undefined' && LANGUAGE == 'ua') ? 'ukr' : '') + '/addBtn.png" value=Вставить onclick="checkCaptcha(); return false;" /></div></td><td class="frame_mr"></tr><tr></td><td class="frame_bl"></td><td class="frame_bm"></td><td class="frame_br"><div></div></td></tr></table></form>'}, 'win_captcha_code');
}

function reloadCaptcha() {
    $('#captcha').empty();
    $('#captcha').load('/captcha/reload');
}

function checkCaptcha() {
    if ($('#captchaCode').val() == '') {
        $('#captchaCode').addClass('error');
        return false;
    }
    $('#checkCaptcha').ajaxSubmit({
        dataType: 'json',
        type: 'post',
        beforeSubmit: function () {},
        success: function (data) {
            if (data.status == 'success') {
                Window.close('win_captcha_code');
                if ($.isFunction(window.win_submitForm_callback)) {
                    window.win_submitForm_callback();
                }
            } else {
                $('#captchaCode').addClass('error');
                if (data.captcha) {
                    $('#captcha').empty();
                    $('#captcha').html(data.captcha);
                }
            }
        }
    });
    return false;
}

function popup(url) {
    var popupName = '_blank';
    var width = 554;
    var height = 349;
    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;
    var popupParams = 'scrollbars=0, resizable=1, menubar=0, left=' + left + ', top=' + top + ', width=' + width + ', height=' + height + ', toolbar=0, status=0';
    var popup = window.open(url, popupName, popupParams);
    popup.blur();
    popup.focus();
}

function openVKtest() {
   /* var win = 'win_vk_login';
    var jdiv = open_dialog({
        title: lng('Vkontakte: STEP 2'),
        id: win,
        url: CURRENT_SITE + '/login/vk/step2',
        w: 850,
        h: 500
    });*/
	
	Window.load(CURRENT_SITE + '/login/vk/step2', 'win_vk_login', '');
}

function getCookie(name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    return (setStr);
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

function ajaxGetContent(el, withMenu, push, container) {
    if (container && $(container).length > 0) {} else container = '#mainContent';
    window.pushContainer = container;
    var top = $(window).scrollTop();
    var height = $(window).height();
    var containerTop = ($(container).position().top);
    var href = '';
    if (typeof (el) == 'object') href = $(el).attr('href');
    else href = el;
    var path = href.replace(/http:\/\/[0-9A-z\.]+/, '');
    var offset = 0;
    if (withMenu == 'undefined') withMenu = 0;
    window.reqWithMenu = withMenu;
    offset = (top + Math.floor(height / 2)) - containerTop;
    $.ajax({
        url: href,
        data: {
            'ajaxRequest': '1'
        },
        dataType: ((withMenu) ? 'json' : 'html'),
        type: 'POST',
        async: false,
        beforeSend: function () {
            $(container).html('<table><tr><td align="center" valign="center" style="padding-top:' + offset + 'px"><img src="/resources/img/misc/loaderBig.gif" /></td></tr></table>');
        },
        success: function (data) {
            if (withMenu) {
                $("#pageUserSiteMenu").remove();
                $("#leftSidebar").after(data.menu);
                $(container).html(data.content);
            } else $(container).html(data);
            _gaq.push(['_trackPageview', path]);
            if (withMenu && top > containerTop) $(window).scrollTop($("#pageUserSiteMenu").position().top);
			
			 if(!window.hasherGettingContent) {
				window.hasherGettingContent = 1;
				if (push && history.pushState) {
					history.pushState({
						page: Math.random()
					}, null, path);
				} else {
					$.history.load('!' + path);
				}
			} else {
				setTimeout(function(){window.hasherGettingContent = 0}, 100);
			}
        }
    });
    return false;
}
/*
function ajaxGetContent(el,withMenu){var top=$(window).scrollTop();var height=$(window).height();var containerTop=($("#mainContent").position().top);var href='';if(typeof(el)=='object')
href=$(el).attr('href');else
href=el;var path=href.replace(/http:\/\/[0-9A-z\.]+/,'');var offset=0;if(withMenu=='undefined')
withMenu=0;window.reqWithMenu=withMenu;offset=(top+Math.floor(height/2))-containerTop;$.ajax({url:href,data:{'ajaxRequest':'1'},dataType:((withMenu)?'json':'html'),type:'POST',async:false,beforeSend:function(){$("#mainContent").html('<table width="100%" style="float:left; padding-top:'+offset+'px"><tr><td align="center" valign="center"><img src="/resources/img/misc/loaderBig.gif" /></td></tr></table>');},success:function(data){if(withMenu){$("#pageUserSiteMenu").remove();$("#leftSidebar").after(data.menu);$("#mainContent").html(data.content);}
else
$("#mainContent").html(data);_gaq.push(['_trackPageview',path]);if(withMenu&&top>containerTop)
$(window).scrollTop($("#pageUserSiteMenu").position().top);}});window.location.hash=('#!'+path);innerReHash=1;return false;}
*/

/*function hasher(initMode) {
    if (innerReHash == 0 || innerReHash == 'undefined') {
        var hash = window.location.hash;
        if (hash && hash.substr(0, 2) == '#!') {
            url = hash.replace('#!', '');
            if (window.reqWithMenu == 'undefined') window.reqWithMenu = 0;
			
			window.changeHash = 0;
            ajaxGetContent(url, window.reqWithMenu,null,window.pushContainer);
			window.changeHash = 1;
        } else if (initMode !== true) window.location.reload(true);
    }
    innerReHash = 0;
}*/

function showMoreWall(el) {
    $(el).parent().find('#show').toggle();
    if ($(el).attr('blockHidden') == 1) {
        $(el).attr('blockHidden', 0);
        var tailHide = $(el).attr('tailHide');
        $(el).html(tailHide);
    } else {
        $(el).attr('blockHidden', 1);
        var tailShow = $(el).attr('tailShow');
        $(el).html(tailShow);
    }
}

function intl_ends_in_punct(a) {
    if (typeof a != 'string') return false;
    return a.match(new RegExp(intl_ends_in_punct.punct_char_class + '[' + ')"' + "'" + '\u00BB' + '\u0F3B' + '\u0F3D' + '\u2019' + '\u201D' + '\u203A' + '\u3009' + '\u300B' + '\u300D' + '\u300F' + '\u3011' + '\u3015' + '\u3017' + '\u3019' + '\u301B' + '\u301E' + '\u301F' + '\uFD3F' + '\uFF07' + '\uFF09' + '\uFF3D' + '\s' + ']*$'));
}
intl_ends_in_punct.punct_char_class = '[' + '.!?' + '\u3002' + '\uFF01' + '\uFF1F' + '\u0964' + '\u2026' + '\u0EAF' + '\u1801' + '\u0E2F' + '\uFF0E' + ']';

function intl_render_list_separator() {
    return _tx("{previous-items}, {next-items}", {
        'previous-items': '',
        'next-items': ''
    });
}

function intl_phonological_rules(e) {
    var c, b = e,
        d = window.intl_locale_rewrites;
    try {
        if (d) {
            var pats = [],
                reps = [];
            for (var p in d.patterns) {
                var pat = p,
                    rep = d.patterns[p];
                for (var m in d.meta) {
                    c = new RegExp(m.slice(1, -1), 'g');
                    pat = pat.replace(c, d.meta[m]);
                    rep = rep.replace(c, d.meta[m]);
                }
                pats[pats.length] = pat;
                reps[reps.length] = rep;
            }
            for (var ii = 0; ii < pats.length; ii++) {
                c = new RegExp(pats[ii].slice(1, -1), 'g');
                if (reps[ii] == 'javascript') {
                    if (m = new String(e.match(c))) e = e.replace(c, m.slice(1).toLowerCase());
                } else e = e.replace(c, reps[ii]);
            }
        }
    } catch (a) {
        e = b;
    }
    c = new RegExp('\x01', 'g');
    e = e.replace(c, '');
    return e;
}

function _tx(e, a) {
    if (!a) return e;
    var d;
    for (var c in a) {
        if (intl_ends_in_punct(a[c])) {
            d = new RegExp('\\{' + c + '\\}' + intl_ends_in_punct.punct_char_class + '*', 'g');
        } else d = new RegExp('\\{' + c + '\\}', 'g');
        var b = '';
        if (a[c][0] != '~') b = '\x01';
        e = e.replace(d, b + a[c] + b);
    }
    e = intl_phonological_rules(e);
    return e;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function getTail(num, one, some, many) {
    var x = num % 10
    var xx = num % 100
    if (x > 4 || (xx > 4 && 21 > xx) || 0 == x) return many
    if (1 == x) return one
    if (x > 1 && 5 > x) return some
}

function Dump(d, l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof (d) == "object") {
        s += typeof (d) + " {\n";
        for (var k in d) {
            for (var i = 0; i < l; i++) s += "  ";
            s += k + ": " + Dump(d[k], l + 1);
        }
        for (var i = 0; i < l - 1; i++) s += "  ";
        s += "}\n"
    } else {
        s += "" + d + "\n";
    }
    return s;
}
var LiveTimer = {
    restart: function (a) {
        this.serverTime = parseInt(a);
        this.localStartTime = new Date().getTime() / 1000;
        this.updateTimeStamps();
    },
    updateTimeStamps: function () {
        LiveTimer.startLoop(20000);
    },
    addTimeStamps: function (a) {
        LiveTimer.startLoop(0);
    },
    startLoop: function (a) {
        this.stop();
        this.timeout = setTimeout(function () {
            LiveTimer.loop();
        }, a);
    },
    stop: function () {
        clearTimeout(this.timeout);
    },
    loop: function (d) {
        if (d) LiveTimer.updateTimeStamps();
        var c = Math.floor(new Date().getTime() / 1000 - LiveTimer.localStartTime);
        var a = -1;
        $(".timestamp").each(function (intIndex) {
            var f = +new Date($(this).attr('data-date')) / 1000;
            var e = LiveTimer.renderRelativeTime(LiveTimer.serverTime + c, f);
            if (e.text) $(this).html(e.text);
            if (e.next != -1 && (e.next < a || a == -1)) a = e.next;
        });
        if (a != -1) {
            var b = Math.max(20000, a * 1000);
            LiveTimer.timeout = setTimeout(function () {
                LiveTimer.loop();
            }, b);
        }
    },
    renderRelativeTime: function (c, d) {
        var e = {
            text: "",
            next: -1
        };
        if (c - d > (12 * 3600) || (new Date(c * 1000).getDay() != new Date(d * 1000).getDay())) return e;
        var f = c - d,
            b = Math.floor(f / 60),
            a = Math.floor(b / 60);
        if (b < 1) {
            e.text = lng("несколько секунд назад");
            e.next = 60 - f % 60;
            return e;
        }
        if (a < 1) {
            if (b == 1) {
                e.text = lng("около минуты назад");
            } else e.text = b + " " + lng("мин. назад");
            e.next = 60 - f % 60;
            return e;
        }
        if (a != 11) e.next = 3600 - f % 3600;
        if (a == 1) {
            e.text = lng("около часа назад");
            return e;
        }
        e.text = a + " " + lng("ч. назад");
        return e;
    }
};





onScrollLoader = {
    scrollDetectorEnabled: true,
    scrollDetector: null,
    url: '',
    elPath: '',
    init: function (url, elPath) {
        onScrollLoader.url = url;
        onScrollLoader.elPath = elPath;
        $(elPath).parent().parent().append('<div id="scroll-detector" align="center"><img src="/resources/img/misc/loaderBig.gif" /></div>');
        onScrollLoader.scrollDetector = $('#scroll-detector');
        $(window).scroll(onScrollLoader.scroll);
    },
    scroll: function() {
		if (onScrollLoader.scrollDetectorEnabled && ($(window).scrollTop() + $(window).height() + 300) >= onScrollLoader.scrollDetector.offset().top) {
			onScrollLoader.load();
		}
	},
    load: function () {
        if (!onScrollLoader.scrollDetectorEnabled) return false;
        onScrollLoader.scrollDetectorEnabled = false;
        var id = $(onScrollLoader.elPath + ':last').attr('data-id');
        if (id != 'undefined' && id > 0) {
            $.post(onScrollLoader.url + id, {}, function (html) {
                if (html) {
                    var rid = 'nt' + id;
                    $(onScrollLoader.elPath).parent().append('<div id="' + rid + '" style="display:none;">' + html + '</div>');
                    onScrollLoader.scrollDetectorEnabled = true;
                    $('#' + rid).fadeIn('slow');
					onScrollLoader.scroll();
                } else {
                    onScrollLoader.scrollDetectorEnabled = false;
                    onScrollLoader.scrollDetector.hide();
                }
            })
        }
    }
}

	
Topper = {
    prevPosition: 0,
    limit: 300,
    disabled: false,
    sidebar: false,
    init: function () {
        $('body').append('<div class="goTop"><div><a class="goTopBtn" onclick="return Topper.goTop();" style="display:none;">' + lng('перейти вверх') + '</a></div></div>');
        var limit;
		
		var mpl = Math.floor($('#mainContent').position().left);
        if ($('#leftSidebar').length) {
            limit = $('#leftSidebar').position().top + $('#leftSidebar').height() + 250;
			$('.goTop div').css('margin-left', mpl + 'px');
            Topper.sidebar = true;
        } else if ($('.rightSidebarToLeft').length) {
            limit = $('#rightSidebar').position().top + $('#rightSidebar').height() + 250;
			$('.goTop div').css('margin-left', mpl + 'px');
            Topper.sidebar = true;
        } else {
            if (Window.mwWidth > 1200) {
                $('.goTop div').css('margin-left', (mpl - 100) + 'px');
                limit = Window.mwHeight;
            } else {
                Topper.disabled = true;
            }
        }
        if (limit > Topper.limit) {
            Topper.limit = limit;
        }
        $(window).scroll(function () {
            if (Topper.disabled) return false;
            var wst = $(window).scrollTop();
            var w_height = Window.mwHeight;
            if ((wst + w_height) > Topper.limit && $('#pageBottom').position().top - 20 > $('.goTop').position().top) {
                $('.goTopBtn').show();
            } else {
                $('.goTopBtn').hide();
            }
        });
        $(window).resize(function () {
            if (!Topper.sidebar) {
                if (Window.mwWidth > 1200) {
                    var mpl = Math.floor($('#mainContent').position().left);
                    $('.goTop div').css('margin-left', (mpl - 100) + 'px');
                    Topper.limit = Window.mwHeight;
                    $('.goTopBtn').show();
                    Topper.disabled = false;
                } else {
                    if (!Topper.disabled) {
                        $('.goTopBtn').hide();
                        Topper.disabled = true;
                    }
                }
            }
        });
    },
    calc: function () {},
    goTop: function () {
        $(window).scrollTop(0);
        return false;
    }
}
 
 
	
function open_win_photo_viewer(url) {    
	Window.load(url, 'win_photo_viewer', lng('Просмотр фото'), function() {
		$('.win_photo_viewer').parent().click(function(e) {
            if($(e.target).children('.win_photo_viewer').length > 0) {
				innerReHash = 1;
				$.history.load('1');
				
				Window.close('win_photo_viewer');
			}
        });
	}, true);
	return false;
}

function open_win_video_viewer(url) {    
	Window.load(url, 'win_video_viewer', lng('Просмотр видео'), function() {
		$('.win_video_viewer').parent().click(function(e) {
            if($(e.target).children('.win_video_viewer').length > 0) {
				innerReHash = 1;
				$.history.load('1');
				
				Window.close('win_video_viewer');
			}
        });
	}, true);
	return false;
}

Liker = {
							type: '',
							oid: 0,
							container: '',
							init: function(t, i, c) {
								Liker.type = t;
								Liker.oid = i;
								Liker.container = c; 
							},
							sendCount: function (s, c) {
								var soc = ['vk', 'fb'];
								if($.inArray(s, soc) == -1)
									return false;

								$.post('/setLikesCount/'+Liker.type+'/'+Liker.oid+'/'+s+'/'+c, {}, function(html){Liker.setTotalCount(html);});
							},
							setTotalCount: function(c) {
								$(Liker.container).html(c);
							}
						}

