//-----------------
function select_fill(id_select, options, sel_id, style)
{
	var select = $('#'+id_select);
	if (select)
	{
		select.empty();
		var aRes = eval("(" + options + ")");
		
		if(style != undefined){
			var parent = '';
			var rgx = '#^(\s|&nbsp;){0,4}[А-Яа-я]+#';
		}
		
		for (i in aRes)
		{
			
			if (typeof(aRes[i])=='string')
			{
				if (sel_id != undefined)
				{
					if (sel_id == aRes[i])
					{
						select.append( '<option selected="selected" value="' + aRes[i] + '">' + aRes[i] + '</option>' );
					}
					else
						select.append( '<option value="' + aRes[i] + '">' + aRes[i] + '</option>' );
				}
			}
			else {
				if(aRes[i].name == rgx)
				{
			        parent = ' style="color:#083c36; font:bold 12px \'Arial\';"';
				} 
				select.append( '<option value="' + aRes[i].id + '"'+parent+' >' + aRes[i].name + '</option>' );
			}
		}
	}
}
//-----------------
function wc_expand(id, prefix)
{
	if (prefix==undefined) prefix = 'add_comment';
	$('#'+prefix+'_'+id).slideDown('fast');
	$('#'+prefix+'_input_'+id).focus().val('');
	$('#'+prefix+'_input_'+id).unbind().blur( function(){ if( $(this).val()=='' ) { $('#'+prefix+'_'+id).slideUp('fast'); } });
}
//-----------------
function do_ajax_submit(frm, xajax_proc)
{
	if (frm.frm_enabled == undefined)
	{
		$(frm).append('<input type="hidden" name="frm_enabled" value="1">');
	}
	if (frm.frm_enabled.value=='1')
	{
		frm.frm_enabled.value='0';
		window.setTimeout(function() {
			frm.frm_enabled.value='1';
		}, 1000);
		xajax_proc(xajax.getFormValues( frm ));
	}
	return false; 
}
//-----------------
function form_enable(frm, is_enable, is_reset)
{
	if (typeof(frm)=='string') frm = $('#'+frm)[0];
	
	if (is_reset)	
		frm.reset();
	
	if (is_enable)	
		frm.frm_enabled.value = '1';
	else  
		frm.frm_enabled.value = '0';

	return frm.frm_enabled.value;
}
//-----------------
function toggle_blocks_display(id_hide, id_show, key)
{
	if (key!=undefined)
	{
		var today = new Date();
		var expires = new Date(today.getTime() + 365 * 10 * 24 * 60 * 60 * 1000);
		setCookie("hide_"+key, id_hide, expires,"/");
	}
	el_hide = $('#'+id_hide);
	if (el_hide.css('display')=='none')
	{
		el_hide.show();
		$('#'+id_show).hide();
	}
	else
	{
		el_hide.hide();
		$('#'+id_show).show();
	}
}
//-----------------
function div_slideToggle(id_div)
{
	$('#'+id_div).slideToggle( '', function() { $('.div_slide').not( $(this) ).slideUp();  } ); 
}
//-----------------
function toggle_filter(id_div, is_show)
{
	if (is_show == undefined )
		$('#'+id_div).slideToggle();
	else
		if (is_show) $('#'+id_div).slideDown(0);
		else $('#'+id_div).slideUp(0);
}
//-----------------
function addRequestToFriends(id, node)
{
	xajax_do_add_request_to_friends(id);
	node.style.display = 'none';
}
//-----------------
function cancelRequestToFriends(id, node)
{
	xajax_do_cancel_request_to_friends(id);
	$(node).html('Отменено');
}
//-----------------
function saveWindowSize(){
	var today = new Date();
	var expires = new Date(today.getTime() + 365 * 10 * 24 * 60 * 60 * 1000);

	  var myWidth = 0, myHeight = 0,  myTop = 0,  myLeft = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	myTop = window.screenY;
	myLeft = window.screenX;
	setCookie("cookie_cmsdialogpagesize_h_structure",myHeight,expires,"/");
	setCookie("cookie_cmsdialogpagesize_w_structure",myWidth,expires,"/");
	setCookie("cookie_cmsdialogpagesize_top_structure",myTop,expires,"/");
	setCookie("cookie_cmsdialogpagesize_left_structure",myLeft,expires,"/");
//	document.cookie = "cookie_cmsdialogpagesize_h_"+url+"="+myHeight+"; expires="+expires.toGMTString()+"; path=/";
//	document.cookie = "cookie_cmsdialogpagesize_w_"+url+"="+myWidth+"; expires="+expires.toGMTString()+"; path=/";
}
//-----------------
//Boolean variable specified if alert should be displayed if cookie exceeds 4KB
var caution = false;

//name - имя cookie
//value - значение cookie
//[expires] - дата окончания действия cookie (по умолчанию - до конца сессии)
//[path] - путь, для которого cookie действительно (по умолчанию - документ, в котором значение было установлено)
//[domain] - домен, для которого cookie действительно (по умолчанию - домен, в котором значение было установлено)
//[secure] - логическое значение, показывающее требуется ли защищенная передача значения cookie
function setCookie(name, value, expires, path, domain, secure) {
     var curCookie = name + "=" + escape(value) +
             ((expires) ? "; expires=" + expires.toGMTString() : "") +
             ((path) ? "; path=" + path : "") +
             ((domain) ? "; domain=" + domain : "") +
             ((secure) ? "; secure" : "");
     if (!caution || (name + "=" + escape(value)).length <= 4000)
         document.cookie = curCookie;
     else
    	 if (confirm("Cookie превышает 4KB и будет вырезан !"))
                     document.cookie = curCookie;
}
//-----------------
//name - имя считываемого cookie
function getCookie(name) {
        var prefix = name + "=";
        var cookieStartIndex = document.cookie.indexOf(prefix);
        if (cookieStartIndex == -1)
                return null;
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length;
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}
//-----------------
//name - имя cookie
//[path] - путь, для которого cookie действительно
//[domain] - домен, для которого cookie действительно
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}
//-----------------
function createWindowEdit(url){
	var h = getCookie('cookie_cmsdialogpagesize_h_structure');
	var w = getCookie('cookie_cmsdialogpagesize_w_structure');
	var myTop = getCookie('cookie_cmsdialogpagesize_top_structure');
	var myLeft = getCookie('cookie_cmsdialogpagesize_left_structure');
	if(h==null || h=='' || h==0) h=600; 
	if(w==null || w=='' || w==0) w=800;
	newEditWindow = window.open(url,'WEdit','height='+h+',width='+w+',resizable=yes,scrollbars=yes');
	if ((myLeft!=null && myLeft>0) && (myTop!=null && myTop>0)) { newEditWindow.moveTo(myLeft, myTop); }
	if (window.focus) { newEditWindow.focus(); }
	return false;
}
//-----------------
function closeWindowEdit(){
	newEditWindow.close();
}
//-----------------
function get_tiny_text(editor_id)
{
	var ed = tinyMCE.get(editor_id);
	return ed.getContent();
}
//-----------------
function submit_form(frm, fn, aIdTextArea)
{
	if (frm instanceof String) {
		frm = $("#"+frm);
	}
	if (!frm) return false;
	if (arguments.length > 2) {
		for (var i = 0; i < aIdTextArea.length; i++)
		{
			var val = tinyMCE.get(aIdTextArea[i]).getContent();
			elem = document.getElementById(aIdTextArea[i]);
			elem.value = val;
		}
	}
	fn(xajax.getFormValues(frm));
	return false;
}
//-----------------

var SHOW_MESSAGE_DELAY = 5000;
//-----------------

function show_loading(is_show)
{
	if (is_show) {
		$("#process_loading").show();
	}
	else {
		$("#process_loading").hide();
	}
}
//-----------------
function jqmShowCenter(hash) {
	hash.w.show();
	var top = $(document).scrollTop() + ($(window).height() - $(hash.w).outerHeight()) / 2;
	var left = $(document).scrollLeft() + ($(window).width() - $(hash.w).outerWidth(true)) / 2;
	hash.w.css('top', (top > 0 ? top : 0)+'px');
	hash.w.css('left', (left > 0 ? left : 0)+'px');
}; 
//-----------------
function jqmConfirm(msg,callback) {
	$('#confirm').addClass("jqmWindow").find('span.jqmConfirmMsg').html(msg).end()
	  .jqm({ onShow:jqmShowCenter, overlay: 10, modal: true, trigger: false})
		.jqmShow()
	    .find(':submit:visible').unbind()
	      .one('click', function(){
	        if((this.value == 'Да')||(this.value == 'Yes')||(this.value == 'Si'))
	          (typeof callback == 'string') ?  window.location.href = callback :  callback();
	        $('#confirm').jqmHide();
	      });
}
//-----------------
function do_delete(msg, name, param1, param2)
{
	jqmConfirm(msg, function(){ xajax_do_delete(name, param1, param2) } );
}
//-----------------
function do_popup(name, param1, param2)
{
	//show_loading(true);
	xajax_do_popup(name, param1, param2);
}
//-----------------
var onHidePopup=null;
//-----------------
function show_popup()
{
	show_loading(false);
	var myClose=function(hash) {
		hash.w.fadeOut(2000, function(){ hash.o.remove(); });
		$('#popup_dlg').html('');
		if (onHidePopup) onHidePopup();
	}; 
	$("#popup_dlg").addClass("jqmWindow").jqm( { onShow:jqmShowCenter, onHide:myClose, modal: true, overlay:0} ).jqmShow();
}
//-----------------
function hide_popup()
{
	onHidePopup=null;
	$("#popup_dlg").jqmHide();
}
//-----------------
function show_login(is_modal)
{
	/*
	if (is_modal == undefined) is_modal = true;
	$(".clear_input_value").val("");
	if (is_modal) {
		$("#login_dlg").addClass("jqmWindow").jqm({modal: true, overlay:30}).jqmShow();
		$(".for_modal_login_dlg").show();
		$(".for_nomodal_login_dlg").hide();
	}
	else {
		$("#login_dlg").addClass("jqmWindow").jqm({overlay:30}).jqmShow();
		$(".for_modal_login_dlg").hide();
		$(".for_nomodal_login_dlg").show();
	}
	*/
}
//-----------------
function clear_input_value()
{
	$(".clear_input_value").val('');
}
//-----------------
function show_auth_text( iOk, sResult )
{
	if (iOk) {
		$('#result_auth_text').removeClass('warning2');
		$('#result_auth_text').addClass('message_success2')
	}
	else {
		$('#result_auth_text').removeClass('message_success2');
		$('#result_auth_text').addClass('warning2');
	}
	$("#result_auth_text").html(sResult);
}
//-----------------
//для вызова в body onload
function show_message(iOk, delay)
{
	sResult = $("#result_text").html();
	sResultLink = $("#result_link").html();
	
//	alert(sResultLink);
//	alert(sResult.length);
	
	if (sResult=="") return false;
	var aResult = eval("(" + sResult + ")");
	var sOutput = '';

	if (aResult.length == 1)
	{
		sOutput = aResult[0];
		if (sResultLink) sOutput=sOutput+'</br>'+sResultLink;
	}
	else 
	{
		for (sFieldName in aResult)
		{
			var type;
			if (iOk > 0) type = 2;
			show_field_message(sFieldName, aResult[sFieldName], type);
		}
		if (LANG=='ru')
			sOutput = 'Проверьте правильность заполнения полей';
		else if  (LANG=='es')
			sOutput = 'Verifique que todos los campos esten llenados correctamente';
		else
			sOutput = 'Please complete all fields';
	}
	
	if (iOk==0) {
		sClass = 'mesageGreen';
	}
	else {
		sClass = 'mesageRed';
	}

	$("#apply_result_dlg").removeClass('mesageGreen mesageRed').addClass(sClass);
	$("#apply_result").html(sOutput);
	
	$(".jqmClose").one("click", function() { $('#apply_result_dlg').hide(); return false; });
	if (delay==undefined) 
		delay=SHOW_MESSAGE_DELAY;
	else
		delay=delay*1000;
	
	//alert('delay='+delay);
	setTimeout( function() { $("#apply_result_dlg").hide(); }, delay );
	$("#apply_result_dlg").show();
	//$("#apply_result_dlg").addClass("jqmWindow").jqm({overlay:30}).jqmShow();
}
//-----------------
function remove_errors()
{
	// удаляем класс ошибок для всех полей ввода
	$('.error').removeClass('error');
	// удаляем сообщения об ошибках
	$('.errormes').removeClass('errormes').html('');
	//$('.p_error').remove();
}
//-----------------
function show_field_message( field, str, type )
{
	var mess_elem = $('#'+'result_check_'+field).get(0);
	if (mess_elem)
	{
		$(mess_elem).html(str);
		
		var mess_class;
		if ( type == 0 ) mess_class = 'message_normal';
		else if ( type == 1 ) mess_class = 'message_info';
		else if ( type == 2 ) mess_class = 'message_error';

		var parent_elem = $('#'+'check_'+field).get(0);
		
		//alert('mess_class='+mess_class+' type='+type);
		$(parent_elem).attr('class' ,mess_class);
	}
}
//-----------------
// для вызова в php ajax responce
function show_result_apply(type, sResult, bShowPopup)
{	// по умолчанию показывать всплывающее окошко результата
	if (bShowPopup == undefined) bShowPopup = true;
	// sResult - json format

	var aResult = eval("(" + sResult + ")");
	var sOutput = '';
	//alert( typeof(aResult) );

	remove_errors();
	//if (aResult.hasOwnProperty('length')&&!(aResult instanceof String)) 
	if (aResult.length == 1)
	{
		sOutput = aResult[0];
	}
	else 
	{ // Object
		for (sFieldName in aResult)
		{
			//var type;
			//if (iOk) type = 0; else	type = 2;
			//if (iOk > 0) type = 2 else type = 1;

			//alert('type='+type+' sMessageName='+sMessageName+' length='+$('#'+sMessageName).length);
			if ( $('#id_message_'+sFieldName).length > 0 )
			{
				$('#id_message_'+sFieldName).html(aResult[sFieldName]).addClass('errormes');
				
				if ( $('#id_input_'+sFieldName).length > 0 )
				{
					$('#id_input_'+sFieldName).addClass('error');	
				}
			}
			else
				show_field_message(sFieldName, aResult[sFieldName], type);
		}		
		if (LANG=='ru')
			sOutput = 'Проверьте правильность заполнения полей';
		else if  (LANG=='es')
			sOutput = 'Verifique que todos los campos esten llenados correctamente';
		else
			sOutput = 'Please complete all fields';
	}
	if (!bShowPopup) return;
	
	if (type==0) sClass = 'mesageGreen';
	else if ( type == 1 ) sClass = 'mesageRed';
	else if ( type == 2 ) sClass = 'mesageRed';
	$("#apply_result_dlg").removeClass('mesageGreen mesageRed').addClass(sClass);
	$("#apply_result").html(sOutput);

	$(".jqmClose").one("click", function() { $('#apply_result_dlg').hide(); return false; });
	setTimeout( function() { $("#apply_result_dlg").hide(); }, SHOW_MESSAGE_DELAY );
	$("#apply_result_dlg").show();
	
	//$("#apply_result_dlg").addClass("jqmWindow").jqm({overlay:30}).jqmShow();
}
//-----------------

