function load_what() {
	if(jQuery("#Itemid").val()==62)
		jQuery("#id").html("<option value='51'>Квартиру</option><option value='52'>Комнату</option><option value='53'>Гараж</option>");
	if(jQuery("#Itemid").val()==63)
		jQuery("#id").html("<option value='54'>Квартиру</option><option value='55'>Комнату</option><option value='56'>Гараж</option>");
	if(jQuery("#Itemid").val()==59)
		jQuery("#id").html("<option value='46'>Квартиру</option><option value='48'>Комнату</option><option value='50'>Гараж</option>");
	if(jQuery("#Itemid").val()==58)
		jQuery("#id").html("<option value='45'>Квартиру</option><option value='47'>Комнату</option><option value='49'>Гараж</option>");
	if(jQuery("#Itemid").val()==86)
		jQuery("#id").html("<option value='70'>Квартиру</option><option value='71'>Комнату</option>");
}

function change_city(o){
	//block_elem_small('#district_td');
	jQuery('#district_td').html('Загрузка...');
	jQuery('#district_td').load('index2.php?option=com_content&view=article&layout=districts&no_html',{city: jQuery(o).val(),type:2, district:'', input_name:'district[]'},
			function(){
				//jQuery('#district_td').unblockUI();
				jQuery("#district_td > select[id=district]").asmSelect({removeLabel:"", removeClass:"deleteIco inline-block"});
			});
}

function get_editor() {
	if(jQuery('#all_var').val()=='') {
		jQuery('#editor_content').html('');
		jQuery('#part1').hide();
		jQuery('#part2').hide();
	}
	else {
		var index = 0;
		switch(jQuery('#all_var').val()) {
			case '4_51_10':
			case '3_54_11':
			case '2_45_7':
			case '1_46_8':
			case '5_53_10':
			case '5_56_11':
			case '5_49_7':
			case '5_50_8':
				index = 2;
				break;
			case '4_52_10':
			case '3_55_11':
			case '2_47_7':
			case '1_48_8':
				index = 3;
				break;
			case '0_57_13':
				index = 5;
				break;
			case '6_70_17':
			case '6_71_17':
				index = 6;
				break;
			default:
				index = 4;
				break;
		}
		show_block();
		jQuery('#editor_content').load('index2.php?option=com_content&view=article&layout=form'+index+'&Itemid=51&no_html',{ var_id:jQuery('#all_var').val(), act:'get_editor'},
			function(){
				jQuery.unblockUI();
			//	jQuery("#district_td_form > select[id=district]").asmSelect({removeLabel:"", removeClass:"deleteIco inline-block"});
				jQuery('#part1').show();
				jQuery('#part2').show();
			}
		);
	}
}

function change_what() {
	if(jQuery("#id").val()==53||jQuery("#id").val()==56||jQuery("#id").val()==50||jQuery("#id").val()==49) {
		jQuery("#komn_cnt").html("<input type='text' id='ploshad' name='ploshad' value='площадью' onfocus='jQuery(\"#ploshad\").val(\"\");' />");
	} else {
		jQuery("#komn_cnt").html('<select id="count" multiple="multiple" name="count[]" title="любую"><option value="1">1-комнатную</option><option value="2">2-комнатную</option><option value="3">3-комнатную</option><option value="4">4-комнатную</option><option value="5">5-комнатную</option><option value="6">6-комнатную</option><option value="6+">6-комнатную+</option><option value="Спец-проект">спец-проект</option></select>');
    //<option value="">любую</option>
        jQuery("select[id=count]").asmSelect({removeLabel:"", removeClass:"deleteIco inline-block"});
    }
}

function send_feedb() {
	if(jQuery("#message_feedb").val()==""||jQuery("#name_feedb").val()==""||jQuery("#mail_feedb").val()=="") {
		jQuery("#error_feedb").html("Для отправки сообщения необходимо заполнить все поля.");
		return false;
	}
	var re = /[0-9a-z_]+@[0-9a-z_^.]+.[a-z]{2,3}/i;
	if(!re.test(document.getElementById('mail_feedb').value)) {
		jQuery("#error_feedb").html("Некорректный e-mail!");
		return false;
	}
	jQuery("#error_feedb").html('<img id="loading_photo1" src="afu/loading.gif" style="width:15px; height:15px;">');
	jQuery.post("index2.php?option=com_content&view=article&layout=feedback&no_html",
	{mail:jQuery("#mail_feedb").val(), msg:jQuery("#message_feedb").val(), name:jQuery("#name_feedb").val()},
	function(data){
	if(data==1){
		jQuery("#error_feedb").html('');
		alert('Выше сообщение отправлено!');
		jQuery.nyroModalRemove();
	} else
	jQuery("#error_feedb").html(data);});
}

/**
 *
 * @access public
 * @return void
 **/
function load_presettings(){
	//jQuery.nyroModalSettings({ bgColor: '#fff'});
    jQuery('.nyroModal').nyroModal({ css: {zIndex: 9999} });
	jQuery('.wComm, .hasTip').tooltip({
	  track: true,
	  delay: 0,
	  showURL: false,
	  fade: 250
	});
	jQuery('.wComm2').tooltip({
	    track: false,
	    delay: 0,
	    showURL: false,
	    fade: 250,
	    positionLeft: true
	});
    jQuery('.wCommLeft').tooltip({
	    track: false,
	    delay: 0,
	    showURL: false,
	    fade: 250
	});

	jQuery('.modal_my_close').click(function(){
        rm_news(jQuery(this).attr('id'));
        jQuery('.modal_my').hide();
        return false;
	});

    jQuery(".searchBoxMoreLink").live("click", function(){
        jQuery("#bottom_search").show();
        jQuery(".searchBoxMoreLink").removeClass("searchBoxMoreLink").addClass("searchBoxMoreLink-");
        jQuery(".searchBox").addClass("searchboxFull", "slow");
    });
    jQuery(".searchBoxMoreLink-").live("click", function(){
        jQuery("#bottom_search").hide();
        jQuery(".searchBoxMoreLink-").removeClass("searchBoxMoreLink-").addClass("searchBoxMoreLink");
        jQuery(".searchBox").removeClass("searchboxFull", "slow");
    });
//    jQuery("select[id=count]").asmSelect({removeLabel:"", removeClass:"deleteIco inline-block"});
   // jQuery("select[id=district]").asmSelect({removeLabel:"", removeClass:"deleteIco inline-block"});

    jQuery(".loginBtn").click(function(){
            jQuery(".loginForm").show();
            jQuery(".regForm").hide();
        }
    );
    jQuery(".regBtn").click(function(){
            jQuery(".regForm").show();
            jQuery(".loginForm").hide();
        }
    );

    jQuery(".userFormClose").click(function(){
            jQuery(".userForm").hide();
        }
    );
}

/**
 *
 * @access public
 * @return void
 **/
function go_to_wheather(){
	window.location.href="index.php?option=com_content&view=article&layout=wheather&Itemid=74";
}

function in_array(what, where) {
    var a=false;
    for(var i=0; i<where.length; i++) {
        if(what == where[i]) {
          a=true;
          break;
        }
    }
    return a;
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();



	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
/**
 *
 * @access public
 * @return void
 **/
function rm_news(id){
	Set_Cookie('site_news', id, 365, '/', '', '');
}

/**
 *
 * @access public
 * @return void
 **/
function show_full_news(){
	jQuery('#div_news').show();
}

function send_message(user_id) {
	var msg = jQuery('#msg_text').val();
	if(trim(msg)==""||trim(msg)=="Текст сообщения")
		return alert('Сообщение не может быть пустым');
	if(msg.length>1000)
		return alert('Ваше сообщение слишком длинное (больше 1000 символов). Попробуйте сократить его или разбить на несколько частей.');

	show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=add_message&no_html',{ msg: msg, to_user_id: user_id},
		function(data){
			if(!isNaN(data)) {
				jQuery.unblockUI();
				alert("Ошибка при отправке сообщения. Обратитесь к администрации сайта. Код("+data+")");
			} else {
				window.location.href='index.php?option=com_content&view=article&layout=messages&user='+jQuery('#to_user_id').val()+'&Itemid=75';

			}
		}
	);
}

/**
 *
 * @access public
 * @return void
 **/
function del_msg(id) {
	if(id=="")
		return alert('Ошибка при удалении');
	show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=del_message&no_html',{ msg_id: id},
		function(data){
			if(isNaN(data)||data<0) {
				jQuery.unblockUI();
				alert("Ошибка при удалении сообщения. Обратитесь к администрации сайта. Код("+data+")");
			} else {
				window.location.href='index.php?option=com_content&view=article&layout=messages&user='+jQuery('#to_user_id').val()+'&Itemid=75';
			}
		}
	);
}

/**
 *
 * @access public
 * @return void
 **/
function add_quote(id){
	var text = jQuery('#msg_'+id).html();
	text = text.split('<br>').join('\r\n');
	text = text.split('\n').join('\n>');
	text = htmlspecialchars_decode(text);
	jQuery('#msg_text').val(">"+text+"\r\n");
}

function htmlspecialchars_decode (string, quote_style) {
    // Convert special HTML entities back to characters
    //
    // version: 912.1315
    // discuss at: http://phpjs.org/functions/htmlspecialchars_decode    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'
    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined') {
    	quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') {
    // Allow for a single string or an array of string flags        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            } else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded    string = string.replace(/&amp;/g, '&');

    return string;
}

/**
 *
 * @access public
 * @return void
 **/
function read_msg(id){
	if(id=="")
		return alert('Ошибка при удалении');
	show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=read_message&no_html', {user_id:id},
		function(data) {
            jQuery.unblockUI();
			if(data<0) {
				alert("Ошибка. Обратитесь к администрации сайта. Код("+data+")");
			} else {
				jQuery('#cnt_'+id).html(data);
				alert('Все сообщения отмечены как прочитанные');
			}
		}
	);
}

function clear_msg(id){
	if(id=="")
		return alert('Ошибка при удалении');
	show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=clr_message&no_html', {user_id:id},
		function(data){
            jQuery.unblockUI();
			if(data<0) {
				alert("Ошибка при очистке истории. Обратитесь к администрации сайта. Код("+data+")");
			} else {
				jQuery('#cnt_'+id).html('0 (0)');
				alert('История успешно очищена');
			}
		}
	);
}

/**
 *
 * @access public
 * @return void
 **/
function load_msg_paginator(total_page){
	jQuery("#paginator_msg").pagination(total_page,	{
		num_edge_entries: 2,
		items_per_page:10,
		callback:handlePaginationClick,
		next_text: 'Следующая',
		prev_text: 'Предыдущая'
    });
}

function handlePaginationClick(new_page_index, pagination_container) {
    // This selects 20 elements from a content array
    if(jQuery('#first_load').val()==0) {
	    show_block();
	    jQuery('#tbody_msg').load('index2.php?option=com_content&view=article&layout=messages2&no_html', { user:jQuery('#to_user_id').val(), page:new_page_index, limit:10 }, function() {
				jQuery.unblockUI();
			}
		);
	} else
		jQuery('#first_load').val(0);

    return false;
}

/**
 *
 * @access public
 * @return void
 **/
function clr_sel_msgs(){
	var sel_vals = new Array();
	var i = 0;
	jQuery('#msg_tbl :checked').each(function() {
		if(jQuery(this).attr('id')!='ckeck_all')
			sel_vals[i++] = jQuery(this).val();
	});
	if(sel_vals=="")
		return alert('Выберите что-то из списка');
    show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=clr_sel_msgs&no_html', {users:sel_vals.join(',')},
		function(data){
			if(data<0) {
                jQuery.unblockUI();
				alert("Ошибка при очистке истории. Обратитесь к администрации сайта. Код("+data+")");
			} else {
				window.location.href='index.php?option=com_content&view=article&layout=messagesall&Itemid=77';
			}
		}
	);
}

/**
 *
 * @access public
 * @return void
 **/
function read_sel_msgs(){
	var sel_vals = new Array();
	var i = 0;
	jQuery('#msg_tbl :checked').each(function() {
		if(jQuery(this).attr('id')!='ckeck_all')
			sel_vals[i++] = jQuery(this).val();
	});
	if(sel_vals=="")
		return alert('Выберите что-то из списка');
	show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=read_sel_msgs&no_html', { users: sel_vals.join(',')},
		function(data){
			if(data<0) {
                jQuery.unblockUI();
				alert("Ошибка при чтении истории. Обратитесь к администрации сайта. Код("+data+")");
			} else {
				window.location.href='index.php?option=com_content&view=article&layout=messagesall&Itemid=77';
			}
		}
	);
}

/**
 *
 * @access public
 * @return void
 **/
function check_all(id_table){
	jQuery('#'+id_table+' input[type=checkbox]').each(function() {
		if(jQuery(this).attr('id')!='ckeck_all')
			jQuery(this).attr('checked', jQuery('#ckeck_all').attr('checked'));
	});
}

/**
 *
 * @access public
 * @return void
 **/
function del_string(id){
	if(!confirm("Вы уверены, что хотите удалить объявление?"))
		return false;
	/*
	jQuery('#dellnk_'+id).attr('onclick',"return false;");
	jQuery('#delimg_'+id).attr('src',"afu/loading.gif");
	jQuery('#delimg_'+id).attr('title',"Подождите...");
	jQuery('#delimg_'+id).attr('class',"");
	jQuery('.statimg').hide();
	jQuery('#load_div_my_').show();
	*/
	show_block();
	jQuery.post('index2.php?option=com_content&view=category&layout=del_cont&no_html',{act:'del_cont', id:id},
		function(data){
			if(data!=1) {
				jQuery.unblockUI();
				alert("Ошибка при удалении объявления. Обратитесь к администрации сайта.");
				/*
				jQuery('#delimg_'+id).attr('src',"images/cancel_f2.png");
				jQuery('#delimg_'+id).attr('title',"Удалить объявление");
				jQuery('#delimg_'+id).attr('class',"statimg");
				jQuery('.statimg').show();
				jQuery('#load_div_my_').hide();
				*/
			} else
				window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
		}
	);
	return false;
}

function show_block() {
    jQuery.blockUI({
        message: 'Пожалуйста подождите...',
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
        }
    });
}
function block_elem(id) {
 jQuery(id).block({
        message: 'Пожалуйста подождите...',
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
        }
    });
}

function block_elem_small(id) {
 jQuery(id).block({
        message: 'Загрузка...',
        css: {
            border: 'none',
            //padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
        }
    });
}

function del_string2(id){
	if(!confirm("Вы уверены, что хотите удалить объявление?"))
		return false;
    show_block();
    jQuery.post('index2.php?option=com_content&view=category&layout=del_cont&no_html',{act:'del_cont', id:id},
		function(data){
            jQuery.unblockUI();
			if(data!=1) {
				alert("Ошибка при удалении объявления. Обратитесь к администрации сайта.");
			} else
				window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
		}
	);

	return false;
}

	/**
	 *
	 * @access public
	 * @return void
	 **/
function set_status(status_id_in, id) {
	var text="открыть";
	var status_id = jQuery('#hid_'+id).val();
	if(status_id=="")
		return false;
	if(status_id==2)
		text="закрыть";
	if(!confirm("Вы уверены, что хотите "+text+" объявление?"))
		return false;
	show_block();
	jQuery.post('index2.php?option=com_content&view=category&layout=set_status&no_html',{act:'set_status', id:id, status_id:status_id},function(data){
		if(data!=1) {
			jQuery.unblockUI();
			if(data==0)
				alert("Ошибка при обновлении статуса. Обратитесь к администрации сайта.");
			else
				alert(data);
		} else {
			window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
		}
	});
	return false;
}

function set_status2(status_id, id) {
		var text="открыть";
		if(status_id == "")
			return false;
		if(status_id==2)
			text="закрыть";
		if(!confirm("Вы уверены, что хотите "+text+" объявление?")) {
            if(status_id==2)
                jQuery('#statlnk_'+id).attr('checked','checked');
            else if(status_id==1)
                jQuery('#statlnk_'+id).removeAttr('checked');
			return false;
        }
        show_block();
		jQuery.post('index2.php?option=com_content&view=category&layout=set_status&no_html',{act:'set_status', id:id, status_id:status_id}, function(data){
            jQuery.unblockUI();
			if(data != 1) {
				if(data == 0)
					alert("Ошибка при обновлении статуса. Обратитесь к администрации сайта.");
				else
					alert(data);
			}
		});
		return false;
	}

/**
 *
 * @access public
 * @return void
 **/
function set_status_all(){
	var sel_vals = new Array();
	var i = 0;
	jQuery('#my_cont_tbl :checked').each(function() {
		if(jQuery(this).attr('id')!='ckeck_all'&&jQuery(this).attr('class')=='zZz') {
			sel_vals[i++] = jQuery(this).val();
		}
	});
	if(sel_vals=="")
		return alert('Выберите что-то из списка');
	show_block();
	jQuery.post('index2.php?option=com_content&view=category&layout=set_status&no_html',{act:'set_status_all', ids:sel_vals.join(',')},
	function(data){
		if(data!=1) {
			jQuery.unblockUI();
			if(data==0)
				alert("Ошибка при обновлении статуса. Обратитесь к администрации сайта.");
			else
				alert(data);
		} else {
			window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
		}
	});
	return false;
}

/**
 *
 * @access public
 * @return void
 **/
function del_all_cont(){
	var sel_vals = new Array();
	var i = 0;
	jQuery('#my_cont_tbl :checked').each(function() {
		if(jQuery(this).attr('id')!='ckeck_all'&&jQuery(this).attr('class')=='zZz') {
			sel_vals[i++] = jQuery(this).val();
		}
	});
	if(sel_vals=="")
		return alert('Выберите что-то из списка');
	if(!confirm("Вы уверены, что хотите удалить все выбранные объявления?"))
		return false;
	show_block();
	jQuery.post('index2.php?option=com_content&view=category&layout=del_cont&no_html',{act:'del_all', ids:sel_vals.join(',')},
	function(data){
		if(data!=1) {
			jQuery.unblockUI();
			if(data==0)
				alert("Ошибка при удалении объявления. Обратитесь к администрации сайта.");
			else
				alert(data);
		} else {
			window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
		}
	});
	return false;
}

function load_univ_paginator(total_page, limit){
	jQuery("#paginator").pagination(total_page,	{
		num_edge_entries: 2,
		items_per_page:limit,
		callback:handleUnivClick,
		next_text: '>>',
		prev_text: '<<'
    });
}

function handleUnivClick(new_page_index, pagination_container) {
    // This selects 20 elements from a content array
    if(jQuery('#first_load').val()==0) {
		jQuery('#latest_div').html('<img src="afu/loading.gif" style="width:15px; height:15px;">');
	  jQuery('#latest_div').load('index2.php?option=com_content&view=article&layout=latestnews&no_html',
			{page:new_page_index}
		);

	} else
		jQuery('#first_load').val(0);
    return false;
}

function goToLatest(dir, pages) {
	block_elem('div.advContent');
    var page = jQuery('#page').val();
    jQuery('.advRightControl').show();
    if(1*dir==-1) {
    	page=1*page-1;
   }else
    	page=1*page+1;

	if(page==0)
    	jQuery('.advLeftControl').hide();
    else
    	jQuery('.advLeftControl').show();
    if(page+1==pages)
    	jQuery('.advRightControl').hide();
	jQuery('.advContentPad').load('index2.php?option=com_content&view=article&layout=latestnews&no_html',{page:page}, function(){
        jQuery('div.advContent').unblock();
        jQuery('#page').val(page);
    });
    return false;
}

/**
 *
 * @access public
 * @return void
 **/
function rst_string(id){
	if(!confirm("Вы уверены, что хотите обновить дату публикации объявления?"))
		return false;
	show_block();
	jQuery.post('index2.php?option=com_content&view=category&layout=rst_cont&no_html',{act:'rst_one',id:id},
		function(data){
			if(data!=1) {
				jQuery.unblockUI();
				if(data=="2")
					alert("Ошибка при обновлении даты объявления. Обратитесь к администрации сайта.");
				else
					alert(data);
			} else
				window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
		}
	);
	return false;
}

/**
 *
 * @access public
 * @return void
 **/
function rst_all_cont(){
	var sel_vals = new Array();
	var i = 0;
	jQuery('#my_cont_tbl :checked').each(function() {
		if(jQuery(this).attr('id')!='ckeck_all'&&jQuery(this).attr('class')=='zZz') {
			sel_vals[i++] = jQuery(this).val();
		}
	});
	if(sel_vals=="")
		return alert('Выберите что-то из списка');
	show_block();
	jQuery.post('index2.php?option=com_content&view=category&layout=rst_cont&no_html',{act:'rst_all', ids:sel_vals.join(',')},
	function(data){
			if(data!=1) {
				jQuery.unblockUI();
				if(data==2)
					alert("Ошибка при обновлении даты объявления. Обратитесь к администрации сайта.");
				else
					alert(data);
			} else
				window.location.href="/index.php?option=com_content&view=category&id=59&layout=default_my&Itemid=67";
	}
	);
	return false;
}

/**
 *
 * @access public
 * @return void
 **/
function load_same(id){
	show_block();
	jQuery('#same_btn').hide();
	jQuery('#same_articles').load('index2.php?option=com_content&view=article&layout=get_same&no_html',{id:id},
		function(data) {
			jQuery.unblockUI();
		}
	);
}

/**
 *
 * @access public
 * @return void
 **/
function load_arcticle(id){
	jQuery("#div_art_"+id).remove();
	window.location.href='#article_anc';
	jQuery("<div id='div_art_"+id+"'></div>").insertBefore('#article_anc');
	//jQuery("#div_art_"+id).html("<img src='afu/loading.gif' alt='' style='width:15px; height:15px;' />");
    show_block();
	jQuery("#div_art_"+id).load('index2.php?option=com_content&view=article&layout=default&no_html',{id:id},function(){
		jQuery.unblockUI();
        jQuery("#chk_art_"+id).html('<img src="images/checkbox_yes.png">');
		jQuery('.nyroModal', "#div_art_"+id).nyroModal();
	});
}

/**
 *
 * @access public
 * @return void
 **/
function close_article(id){
	jQuery("#div_art_"+id).remove();
	jQuery("#chk_art_"+id).html('');
}

/**
 *
 * @access public
 * @return void
 **/
function set_owner(act, id){
	show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=set_owner&no_html',{act:act, id:id},
		function(data){
			jQuery.unblockUI();
			if(data.err==1) {
				alert(data.err_str);
			}  else {
				jQuery('#span_owner_'+id).html(data.new_html);
			}
		}, 'json'
	);
	return false;
}

function add2favourite(cont_id, to) {
    show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=add2favourite&no_html',{to: to, id: cont_id},
        function(data){
            jQuery.unblockUI();
			if(data.err==1) {
				alert(data.err_str);
			}  else {
                if(to==0) {
                    jQuery('#favourite_lnk').attr('title', "Добавить в избранное. Данное объявление будет находиться в разделе 'Избранные объявления'");
                    jQuery('#favourite_lnk').attr('onclick', "add2favourite("+cont_id+", 1);");
                   // jQuery('#favourite_lnk').click(function() { add2favourite(cont_id, 1); });
                    jQuery('#favourite_lnk').html("<i></i>В избранное");
                    //TODO: Текст ссылки менять!
                } else if(to==1) {
                    jQuery('#favourite_lnk').attr('title', "Убрать объявление из избранного");
                    //jQuery('#favourite_lnk').click(function() { add2favourite(cont_id, 0); });
                    jQuery('#favourite_lnk').attr('onclick', "add2favourite("+cont_id+", 0);");
                    jQuery('#favourite_lnk').html("<i></i>Убрать из избранного");
                }
			}
		}, 'json'
	);
	return false;
}

function delFromFavourite(cont_id) {
    show_block();
	jQuery.post('index2.php?option=com_content&view=article&layout=add2favourite&no_html',{to: 0, id: cont_id},
        function(data){
            jQuery.unblockUI();
			if(data.err==1) {
				alert(data.err_str);
			}  else {
                window.location.href="/index.php?option=com_content&view=category&id=81&layout=default_fav&Itemid=90";
			}
		}, 'json'
	);
	return false;
}

/*$jQuery(document).ready(function() {
jQuery("#asmSelect0").change(function() {$("#city").change();})
})*/
