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('Права доступа изменены')) // for debug only
           });
}
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) {

	//deleteng sfwobject if defined
	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);
/*

    var jdiv=$("<div id='"+opt.id+"' title='"+opt.title+"'></div>");
    if (opt.contents) jdiv.html(opt.contents);


    if (!document.getElementById(opt.id)) {
        jdiv.dialog({
            dialogClass: 'flora',
            modal: typeof(opt.modal)!='undefined'?opt.modal:true,
            height: opt.h?opt.h:$(window).height()-140,
            width:  opt.w?opt.w:$(window).width()-200,
            open: function(){
                if (opt.url) $(this).html("<div align='center'><img src='"+RESOURCE_PATH+"/img/ui/indicator.gif' /></div>").load(opt.url);
            },
            close: function(){
                $(this).dialog('destroy');
                $('#'+opt.id).remove();
            }
        });

        if (opt.id != "win_register") { 
            var d=jdiv.parents('.ui-dialog');
            d.css({top: '45px'});  //fix for correct positioning
        }
        $(".ui-resizable-handle",d).ifixpng();
 
        return jdiv;
    }
    else {
        modal_to_top(opt.id);
        return false;
    }
*/
}

function modal_to_top(id) {

    __currentWindowsZindex++;

    $("#"+id).css('z-index',__currentWindowsZindex);    
/*
//    var modal = win.parent().parent();
    var maxZ = parseInt(win.css('z-index'), 10);
    alert(maxZ);
    alert(win);
    alert(win.css('z-index'));
    
    $('.__window').each(function() {
                        maxZ = Math.max(maxZ, parseInt($(this).css('z-index'), 10));
                        alert ($(this).css('z-index'));
                });
                alert(maxZ);
    win.css('z-index',maxZ+2);
    //win.dialog("open");
*/
}

function open_win_remindpassword(){

 var win = 'win_remindpassword';
 var jdiv=open_dialog({
  title: lng('Напоминание пароля'),
  id: win,
  w: '600px',
  h: '300px',
  url: CURRENT_SITE + '/remindpassword'
 });



 return false;

}


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");
    	//inp.parent().find('.err_msg').show();
		$('.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')) {
			//    el.style.color = '#fff';
		}
		else {
			//    el.style.color = '#000';
		}
	}
}

function unset_value(el, defvalue){
 if (el.value == '') {
    el.value = defvalue;
    $(el).addClass('grayed');
    //el.style.color = '#c2c2c2'; 
 }
    
}

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;
}

//close modal/window which contains element el
function win_close(el){

    __closeWindow($(el).parents('.window1').attr('id'));
    
}

function win_close_by_win_id (id) {
    __closeWindow(id);
}


function win_title(el, title){
// $(el).parents('.ui-dialog-container').find('.ui-dialog-title:first').html(title);
}

//used in login form in panel
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;
}

// modal
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()
    }
}

// usage: onsubmit="return sendForm(this, '#target_container')"
function sendForm(form, target, callback)
{
    var form_data = new Object()
    form_data['rnd'] = Math.random()
    
    //$(form).css({border:"1px dashed #008000"});
    //console.log('id='+ form.id)
    //console.log('jq id='+ $(form).attr('id'))
    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) {
              //console.log(this.name +' = '+ this.value)
              //console.log('this.checked = ' + this.checked)
              
              if('checked' === this.checked || true === this.checked) {
                  //console.log('this.value = ' + this.value)
                  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).css({border:"1px dashed #008000"});
    
    $(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');
})
}


//Get community list 
function get_com_list (i) {
	 
	 //$("div.com_list").append("ss");
    var rep = $.post (
        CURRENT_SITE + "/get_com_list",
        {"item": i},
        function(response){
			$("#com_list").html(response);
        }, 
        "html"
    );
    return false;
}



//prepares win_avatar_callback and opens win_avatar
// win_avatar_callback should be a function that called after avatar selected
// callback params: id, src
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) ;
}

/****************************************/
/* File upload functions////////////////*/
/****************************************/
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
	});
}

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
	});
}


function openWinAddSiteToFavs()
{
	var win = 'wm_addtofavs';
	var jdiv=open_dialog({
		title: lng('Добавить сайт в избранное'),
		id: win,
		url: '/site/addtofavs',
		w: 520,
		h: 360
	});
}



/****************************************/
/*////////////////File upload functions	*/
/****************************************/


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 = '_';
		
	//todo
}

function openWinLogin(goto){
	if(!goto || goto == 'undefined')
		goto = '';
		
var win = 'win_login';
 var jdiv=open_dialog({
  title: lng('Логин'),
  id: win,
  url: CURRENT_SITE + '/modal/login/?goto='+escape(goto),
  w: 420,
  h: 340
 });

return false;
}

var lightBoxOptions = {	fixedNavigation:true,
						imageLoading: RESOURCE_PATH+'/img/misc/indicator.gif',
						txtImage: lng(''),
						txtOf: lng('из')
						};

$(function() {
	$('#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>');
}


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')
										{
											__closeWindow('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
														 });
}