var top_menu_selected;
var menu_timer;
var last_timer;
var subscribe_timer;

function HideRich ( id )
{
    $( '.rich' ).animate ( { height: 'hide', opacity: 'hide' }, 200 );
    $.get ( '/ajax/rich/hide/', { id: id } );
}

function ShowRich ()
{
    $( '.rich' ).animate ( { height: 'show', opacity: 'show' }, 400 );
}

function ActivityToggle ( id )
{
    $( '#activity_toggler_' + id ).toggle (
        function () {
            $( '#activity_folder_' + id ).animate ( { height: 'show' } );
            $.get ( '/ajax/users/set_viewed/', { id: id } );
        },
        function () {
            $( '#activity_folder_' + id ).animate ( { height: 'hide' } );
        } );
}

function Subscribe ( id, obj )
{
    clearTimeout ( subscribe_timer );
    
    $( '#subscribe_result' ).remove ();
    var offset = $( obj ).offset ();
    
    $( 'body' ).append ( '<div id="subscribe_result">Готово</div>' );
    $( '#subscribe_result' )
        .css ( { top: parseInt ( offset.top + 23 ) + 'px', left: parseInt ( offset.left - 26 ) + 'px' } )
        .animate ( { opacity: 'show' }, 150 );
        
    subscribe_timer = setTimeout ( function () {
        $( '#subscribe_result' ).remove ();
    }, 3000 );

    HideCloud();
    
    if ( $( obj ).attr ( 'src' ) == '/images/subscribe_r.gif' )
    {
        $( obj )
            .attr ( 'src', '/images/subscribe_g.gif' )
            .removeAttr ( 'onmouseover' )
            .bind ( 'mouseover', function () { ShowCloud ( "Перестать следить за темой" ) } );
    } else {
        $( obj )
            .attr ( 'src', '/images/subscribe_r.gif' )
            .removeAttr ( 'onmouseover' )
            .bind ( 'mouseover', function () { ShowCloud ( "Cледить за темой" ) } );
    }
    
    $.get ( '/ajax/users/subscribe/', { id: id } );
}

function AccordInit ()
{
    $( '#accordeon_items' ).bind ( 'mouseleave', function () {
        $( 'div.accord_item' ).css ( 'background', 'url(/images/accord_rb.gif) repeat-x top #fff' );
        $( 'div.accord_item' ).find ( 'div' ).hide ();
    } );
}

function AccordHover ( obj, num )
{
    $( 'div.accord_item' ).css ( 'background', 'url(/images/accord_rb.gif) repeat-x top #fff' );
    $( obj ).css ( 'background', 'url(/images/accord_bg.gif) repeat-x left -30px #fff' );
    
    $( 'div.accord_item' ).find ( 'div' ).hide ();
    $( obj ).find ( 'div' ).show ();
    
    var val = 277 * ( num - 1 );
    
    if ( $.browser.msie && $.browser.version < 7 )
	{
	    $( '#accord_pics' ).scrollLeft ( val );
	} else {
	    $( '#accord_pics' ).stop().animate ( { scrollLeft: val }, 150 );
	}
}

function RequestEmail ()
{
    var tpl = '<div style="font-family: \'Trebuchet MS\', Tahoma, sans-serif; font-weight: bold; font-style: italic; font-size: 20px; line-height: 20px; margin-bottom: 8px;">Добро пожаловать!</div>\
               <div style="margin-bottom: 5px">Вы успешно вошли на наш сайт используя свою учетную запись ВКонтакте.</div><div style="margin-bottom: 5px">Для того, чтобы стать полноправным участником Рестоклуба введите свой e-mail (не публикуется).</div>\
               <div style="margin: 14px 0 4px 0; font-weight: bold; color: #757575;">Ваша электронная почта:</div>\
               <input type="text" class="edit" style="padding: 3px; font-size: 14px; margin-bottom: 10px;" id="vk_email" /><br />\
               <input type="button" value="Сохранить" class="button" onclick="SaveVKEmail()" />';
    
    jQuery.facebox ( tpl );
}

function SaveVKEmail ()
{
    var email = $( '#vk_email' ).val();
    $.get ( '/ajax/users/save_email/', { email: email } );
    $( document ).trigger ( 'close.facebox' );
}

function VKLoginButton ( api_id )
{
    VK.init ( {
        apiId: api_id,
        nameTransportPath: "/xd_receiver.html"
    });
    
    VK.UI.button ( 'vk_login_button' );
}

function VKLoginButtonP ( api_id )
{
    VK.init ( {
        apiId: api_id,
        nameTransportPath: "/xd_receiver.html"
    });
    
    VK.UI.button ( 'vk_login_button_p' );
}

function VKLogin ()
{
    VK.Auth.login ( function ( response ) {
        if ( response.session ) {
            var code = 'return API.getProfiles({uids: API.getVariable({key: 1280}), fields: "first_name,last_name,sex,photo_medium,photo_big"})[0];';
            VK.Api.call ( 'execute', { 'code': code }, function ( data ) {
                if ( data.response )
                {
                    var r = data.response;
                    
                    if ( r )
                    {
                        var req = { first_name : r.first_name,
                                    last_name  : r.last_name,
                                    sex        : r.sex,
                                    photo      : r.photo_medium,
                                    photo_b    : r.photo_big };
                        
                        $.getJSON ( '/ajax/users/vk_login/', req, function ( data ) {
                            if ( data.result == 'ok' )
                            {
                                window.location.reload ();
                            } else if ( data.result == 'linked' ) {
                                $( document ).trigger ( 'close.facebox' );
                                $( '#user_profile_vk_link' ).replaceWith ( '<div class="uh2" style="margin: 5px 0 15px;">Вы успешно привязали учетную запись ВКонтакте</div>' );
                            } else {
                                alert ( 'Произошла ошибка при авторизации. Вход не удался.' );
                            }
                        } );
                    }
                }
            } );
        }
    }/*, VK.access.FRIENDS*/ );
    
    var tpl = '<div style="font-family: \'Trebuchet MS\', Tahoma, sans-serif; font-weight: bold; font-style: italic; font-size: 20px; line-height: 20px; padding: 4px 0; text-align: center;">Секундочку <img src="/images/ajax3.gif" width="16" height="11" /></div>';
    jQuery.facebox ( tpl );
}

function InitLastVisited ()
{
    $( '#last_link' )
        .click ( function () {
            clearTimeout ( last_timer );
            $( '#top_last_v' ).show();
        } );
        
    $( '#top_last_vi1' )
        .mouseover ( function () {
            clearTimeout ( last_timer );
            $( '#top_last_v' ).show();
        } );
    
    $( '#top_last_vi2' )
        .mouseover ( function () {
            clearTimeout ( last_timer );
            $( '#top_last_v' ).show();
        } );
        
    $( '#top_last_v' )
        .mouseover ( function () {
            clearTimeout ( last_timer );
            $( '#top_last_v' ).show();
        } )
        .mouseout ( function () {
            last_timer = setTimeout ( function () {
                $( '#top_last_v' ).hide();
            }, 400 );
        } );
}

function OrderPlacesList ()
{
    var path = window.location.search;
        path = path.replace ( /order=[a-z]+/, '' );
    
    var order = $( '#places_order_t' ).val();
    
    if ( path == '?' || path == '?&' )
    {
        path = window.location.pathname + '?order=' + order;
    } else {
        if ( path == '' )
        {
            path = window.location.pathname + '?order=' + order;
        } else {
            path = window.location.pathname + path + '&order=' + order;
            path = path.replace ( /\&\&\&/g, '&' );
            path = path.replace ( /\&\&/g,  '&' );
            path = path.replace ( /\?\&/,  '?' );
        }
    }
    
    window.location = path;
}

function ComplaintPost ( id )
{
    var tpl = '<div style="font-family: \'Trebuchet MS\', Tahoma, sans-serif; font-weight: bold; font-style: italic; font-size: 20px; margin-bottom: 4px;">Жалоба на пользователя</div>\
                <table cellspacing="0" class="complaint_form">\
                    <tr>\
                        <td nowrap align="right">Жалуемся на пользователя:</td>\
                        <td style="font-size: 12px; font-weight: bold;">[NICK]</td>\
                    </tr>\
                    <tr>\
                        <td valign="top" nowrap align="right">Подробности жалобы:</td>\
                        <td><textarea class="editarea" style="width: 300px" rows="5" cols="30"></textarea></td>\
                    </tr>\
                    <tr>\
                        <td></td>\
                        <td>\
                            <input type="button" onclick="SendComplaintPost([ID])" value="Отправить в редакцию" class="button" />\
                            <div style="font-family: \'Trebuchet MS\', Tahoma, sans-serif; color: #b00000; font-style: italic; font-size: 12px; margin-top: 7px;">\
                                В редакцию будет отправлен текст записи, на которую Вы жалуетесь.\
                            </div>\
                        </td>\
                    </tr>\
                </table>';
    
    var nick = $( '#post_' + id ).find ( 'div.post_name a:eq(0)' ).text ();
    if ( !nick ) nick = 'Автор скрыт';
    
    tpl = tpl.replace ( '[NICK]', nick );
    tpl = tpl.replace ( '[ID]', id );
    jQuery.facebox ( tpl );
}

function SendComplaintPost ( id )
{
    $.post ( '/uaction/', { action: 'complaint_post', id: id, text: $( '#facebox' ).find ( 'textarea' ).val () }, function () {
        jQuery.facebox ( 'Ваша жалоба отправлена.' );
    } );
}

function ModerAct ( url, obj )
{
    $.get ( url, {}, function () {
        $( obj ).after ( '&nbsp;&nbsp;<span style="color: green; font-size: 11px;">Выполнено</span>' );
    } );
}

function ShowBigPic ( file, w, h, ws, hs, obj )
{
    $( 'div.c_img_th' ).remove ();
    $( 'div.close_p' ).remove ();
    var img = new Image();

    img.onload = function () {
        var offset = $( obj ).offset ();
        $( 'body' ).append ( '<div class="c_img_th" style="top: ' + offset.top + 'px; left: ' + offset.left + 'px; width: ' + ( ws - 2 ) + 'px; height: ' + ( hs - 2 ) + 'px;"></div>' );
        
        var left = offset.left - ( w / 2 - ws / 2 );
        var top  = offset.top - ( h / 2 - hs / 2 );
        
        var oimg = $( this );
        
        $( 'div.c_img_th' ).animate ( { width: w + 'px', height: h + 'px', left: left + 'px', top: top + 'px', borderWidth: '4px' }, 500,
            function () {
                oimg.css ( { display: 'none' } );
                $( 'div.c_img_th' ).append ( oimg );
                oimg.animate ( { opacity: 'show' }, 200 );
                
                var close = $( '<div class="close_p"></div>' );
                close.css ( { top: ( top - 12 ) + 'px', left: ( left + w - 4 ) + 'px' } );
                close.bind ( 'click', function () {
                    $( this ).remove ();
                    $( 'div.c_img_th' ).remove ();
                } );
                
                $( 'body' ).append ( close );
            } );
            
        $( 'div.c_img_th' ).bind ( 'click', function () {
            $( this ).remove ();
            $( 'div.close_p' ).remove ();
        } );
    }
    
    img.src = file;
}

function CheckToShow3D ( id )
{
    var hash = window.location.hash;
    var reg = /3d/;

    if ( reg.test ( hash ) )
    {
        Show3DDialog ( id )
    }
}

function CheckToShowVideo ( id )
{
    var hash = window.location.hash;
    var reg = /video/;

    if ( reg.test ( hash ) )
    {
        ShowVideoDialog ( id )
    }
}

function BlockSubmit ( obj, parent )
{
    $( obj )
        .hide()
        .after ( '<img src="/images/ajax.gif" width="43" height="11" />' );
        
    setTimeout ( function () { $( parent ).submit(); }, 100 );
}

function Login ()
{
    client_request ( 'users', 'login', '', 'POST', false, 'AfterLogin', false, 'login_form' );
}

function AfterLogin ( data )
{
    if ( data.errors )
    {
        $( '#login_errors' ).html ( data.errors );
    } else {
        window.location.reload();
    }
}

function CloudMousePos ()
{
    var cloud = $( '#cloud' );
    var dw    = $().width();
    
    $().bind ( 'mousemove', function ( e ) {
        if ( cloud.css ( 'display' ) == 'block' )
        {
            if ( e.pageX + 200 > dw - 65 )
            {
                if ( e.pageX > dw - 35 )
                {
                    var l = dw - 265;
                } else {
                    var l = e.pageX - 230;
                }
            } else {
                var l = e.pageX + 15;
            }
            
            cloud.css ( 'left', l + 'px' );
            var h = cloud.find ( 'div' ).height();
            cloud.css ( 'top', ( e.pageY - h - 20 ) + 'px' );
            
            cloud.find ( 'iframe' ).css ( 'height', h + 'px' );
        }
    } ); 
}

function Vote ( id )
{
    if ( id )
    {
        var f = '_' + id;
    } else {
        var f = '';
    }
    
    if ( typeof ( $( '#vote_form' + f ).find ( 'input:radio:checked' ).val() ) == 'undefined' )
    {
        $( '#vote_form' + f )
            .find ( 'div.vmessage' )
            .remove();
        
        $( '#vote_form' + f ).append ( '<div class="vmessage"><b>Вы ничего не выбрали</b></div>' );
        $( '#vote_form' + f )
            .find ( 'div.vmessage' )
            .animate ( { height: 'show', opacity: 'show' } );
    } else {
        $( '#vote_form' + f ).submit();
    }
}

function ExpandLongString ( obj )
{
    var parent = obj.parentNode;
        parent = parent.parentNode;
    
    $( parent ).children ( 'span:eq(0)' ).hide();
    $( parent ).children ( 'span:eq(1)' ).show();
    $( parent ).children ( 'span:eq(2)' ).show();
}

function CollapseLongString ( obj )
{
    var parent = obj.parentNode;
        parent = parent.parentNode;
    
    $( parent ).children ( 'span:eq(1)' ).hide();
    $( parent ).children ( 'span:eq(2)' ).hide();
    $( parent ).children ( 'span:eq(0)' ).show();
}

function ShowPriceCloud ( price )
{
	var text = 'Примерная стоимость обеда/ужина без напитков на одного посетителя в этом ресторане: <b>' + price + ' р.</b>';
	ShowCloud ( text );
}

function ShowCloud ( text )
{
    $( '#cloud' )
        .find ( 'div' )
        .html ( text )
        .end ()
        .show ();
}

function HideCloud ()
{
    //$().unbind ( 'mousemove' );
	$( '#cloud' ).hide ();
}

function GetTopLeft ( obj )
{
    var top  = obj.offsetTop;
	var left = obj.offsetLeft;

	for ( var parent = obj.offsetParent; parent; parent = parent.offsetParent )
	{
		left += parent.offsetLeft;
		top  += parent.offsetTop;
	}
	
	var data = {
	    top: top,
	    left: left
	}
	
	return data;
}

function GetYScroll ()
{
	return $().height ();
}

function GetXScroll ()
{
	var xScroll = 0;

	if ( window.innerWidth && window.scrollMaxX )
	{
		xScroll = window.innerWidth + window.scrollMaxX;

		var deff = document.documentElement;
		var wff = ( deff && deff.clientWidth ) || document.body.clientWidth || window.innerWidth || self.innerWidth;

		xScroll -= ( window.innerWidth - wff );
	} else if ( document.body.scrollWidth > document.body.offsetWidth ) {
		xScroll = document.body.scrollWidth;
	} else {
		xScroll = document.body.offsetWidth;
	}

	return xScroll;
}

function ShowLoginForm ( api_id )
{
    var tpl = '<div style="font-family: \'Trebuchet MS\', Tahoma, sans-serif; font-weight: bold; font-style: italic; font-size: 20px; line-height: 20px; margin-bottom: 8px;">Вход на сайт</div>\
                <form action="/login/" method="post">\
                    <table cellpadding="0" cellspacing="0">\
                        <tr>\
                            <td align="right" valign="top" style="font-size: 11px; padding: 7px 10px 10px 10px;">E-mail</td>\
                            <td style="padding-bottom: 10px"><input type="text" class="edit" name="email" /></td>\
                            <td valign="top" nowrap style="font-size: 10px; padding: 4px 0 0 8px;"><a href="/register/">Еще не зарегистрированы у нас?</a></td>\
                        </tr>\
                        <tr>\
                            <td align="right" valign="top" style="font-size: 11px; padding: 7px 10px 10px 10px;">Пароль</td>\
                            <td><input type="password" class="edit" name="password" /></td>\
                            <td valign="top" nowrap style="font-size: 10px; padding: 4px 0 0 8px;"><a href="/forgot/">Забыли пароль?</a></td>\
                        </tr>\
                        <tr>\
                            <td></td>\
                            <td style="padding-top: 9px;"><input type="submit" name="submit" value="Войти" class="button" /></td>\
                            <td></td>\
                        </tr>\
                    </table>\
                </form>\
                \
                <div style="border-top: 2px #dedfc9 solid; padding-top: 14px; margin-top: 15px;">\
                    <div style="font-family: \'Trebuchet MS\', Tahoma, sans-serif; font-weight: bold; font-style: italic; font-size: 20px; line-height: 20px; margin-bottom: 8px;">Или войти на сайт, используя ВКонтакте</div>\
                    <div style="padding: 5px 0"><div id="vk_login_button_p" style="margin: auto" onclick="VKLogin();"></div></div>\
                </div>';
    
    jQuery.facebox ( tpl );
    VKLoginButtonP ( api_id );
}

function HidePopupWindows ()
{
	$( '#photo_bg' ).remove();
	$( '#op_bg' ).remove();
	$( 'div.popup_window' ).remove();
}

function GetNumStrEnd ( cnt, e1, e2, e3 )
{
	var end_str = '';

	end_100 = cnt % 100;
	end_10  = cnt % 10;
	
	if ( end_100 == 11 || end_100 == 12 || end_100 == 13 || end_100 == 14 )
	{
		end_str = e3;
	} else if ( end_10 == 1 ) {
		end_str = e1;
	} else if ( end_10 == 2 || end_10 == 3 || end_10 == 4 ) {
		end_str = e2;
	} else {
		end_str = e3;
	}
	
	return end_str;
}

function PPosterMagenta ()
{
	$( 'table.p_poster_0_container' )
		.find ( 'tr:nth-child(odd)' )
		.addClass ( 'p_poster_0_highlight' );
}

function ChangePosterDate ()
{
	$( '.poster_dates_select > select' ).bind ( 'change', function () {
		if ( $( this ).val() != 0 )
		{
			window.location = '/afisha/' + $( this ).val() + '/';
		}
	} )
}

function GetScrollTop ()
{
    var ht1 = document.documentElement.scrollTop;
	var ht2 = document.body.scrollTop;
	
	if ( ( ht1 == 0 && ht2 > 0 ) || ht1 == ht2 )
	{
		var h = ht2;
	} else if ( ht1 > 0 ) {
		var h = ht1;
	}
	
	return h;
}

function GenPopupPos ( width, height )
{
    var h1 = document.body.offsetHeight;
	
	var h2 = GetScrollTop();
	
	if ( document.documentElement && document.documentElement.clientHeight )
	{
		h1 = document.documentElement.clientHeight;
	}
	
	var top = h1 / 2 - height + h2;
	var left = ( GetXScroll () / 2 - width );
	
	var result = {
	    top  : top,
	    left : left
	};
	
	return result;
}

function ECRating ( id )
{
    if ( $( '#ratingb_' + id + ':visible' ).length == 0 )
    {
        $( '#ratingb_' + id ).animate ( { height: 'show' }, 200 );
        $( '#rrow_' + id )
            .find ( 'div.rating_ar' )
            .hide ();
            
        $( '#rrow_' + id )
            .find ( 'div.rating_aru' )
            .show ();
    } else {
        $( '#ratingb_' + id ).animate ( { height: 'hide' }, 200 );
        $( '#rrow_' + id )
            .find ( 'div.rating_ar' )
            .show ();
            
        $( '#rrow_' + id )
            .find ( 'div.rating_aru' )
            .hide ();
    }
}

function ShowRatingRow ()
{
    var hash = window.location.hash;
    var reg = /rating_[0-9]+/;
    
    if ( reg.test ( hash ) )
    {
        hash = hash.replace ( '#rating_', '' );
    	var scroll = $( '#rrow_' + hash ).offset ();
    	
    	if ( $.browser.msie )
    	{
    	    $( 'html' ).scrollTop ( scroll.top );
    	} else {
    	    $( ( $.browser.safari ? 'body' : 'html' ) ).animate ( { scrollTop: scroll.top }, 'slow' );
    	}
    	
    	ECRating ( hash );
    }
}