/* ф-ции для работы с панелями, с табами */

/*
* глобальные переменные отвечающие соответсвенно за:
* - значение фильтра при переходе по вкладкам таблицы
* - знчении категории , к-ую выбрали в выпадающем списке и по к-ой будет выестись фильтрация
*/
sFilterParam = '';
sFilterCategory = 0;

var bAnimationActive = false;
var sSiteTemplatePath = '/system/site_templates/torrentland';
function SlidePanel(id)
{
    if (bAnimationActive)
        return;
        
    //bAnimationActive = true;
    var blueBtn = jQuery('#'+id+' .blue-line');  
    
    bOpen = !blueBtn.hasClass('reverse-line');   
    var panel = jQuery('#'+id);
    var whiteBlock = jQuery('.white-content', panel);
        
    if (bOpen)
    {                                          
        whiteBlock.slideUp(500, function(){     
            panel.addClass('small-panel');   
            blueBtn.addClass('reverse-line');                    
            bAnimationActive = false; 
            
           // panel.html(panel.html());    
        });                                                   
        jQuery('#'+id+' .res-type').css('display', 'none');
    }   
    else
    {                                                  
        panel.removeClass('small-panel');               
        whiteBlock.slideDown(500, function(){
            blueBtn.removeClass('reverse-line');
            bAnimationActive = false;             
            jQuery('#'+id+' .res-type').css('display', 'block');
            
            panel.css('height','1%');  // эта необъяснимая магия нужна для IE7 :)
        });            
    }          
}


/**
* iNum - номер активируемой вкладки
* sTabsDiv - id блока содержащего вкладки над которыми проводятся действия
* sTabPrefix - префикс к id вкладок.
* id вкладки получается: sTabPrefix+iNum 
*/
function SelectTab(iNum, sTabsDiv, sTabPrefix)
{
    
    var arParam = new Array();
    var activeTab = jQuery('#'+sTabsDiv+' .tab-active');
    activeTab = activeTab[0];
    
    sActiveTabId = activeTab.id;
    if (sActiveTabId == sTabPrefix+iNum)
        return;
    
    activeTabContent = jQuery('#'+sActiveTabId+'_content'); 
    activeTabContent.css('display', 'none');
    
    jQuery(activeTab).addClass('tab');
    jQuery(activeTab).removeClass('tab-active');     
    
    jQuery('#'+sTabPrefix+iNum).addClass('tab-active');       
    jQuery('#'+sTabPrefix+iNum).removeClass('tab');
    jQuery('#'+sTabPrefix+iNum+'_content').css('display', 'block');
    
    jQuery('div.table-head').css('height', 'auto');     
    jQuery('div.table-head').css('height', '37px');     
    jQuery('div.tbl-container').css('height', 'auto');     
    jQuery('div.tbl-container').css('height', '1%');     
}




/** СПИСОК **/
function YellowList()
{
    this.tmout = false;
    this.id = '';
    this.arParam = new Array();
    var _this = this;
    
    this.Init = function(id)
    {
        this.id = id;
    }
    this.Select = function(obj, iCategoryId, sComponentName)
    {
        sFilterCategory = iCategoryId;
        sel = jQuery('#'+this.id+' div.center');
        sel = sel[0];
        jQuery(sel).html(jQuery(obj).html());
        this.Close();
        
    }
       
    this.Open = function()
    {
        jQuery('#'+this.id+' div.list-variants').css('display', 'block');
    }      
    this.Close = function()
    {    
        this.tmout = setTimeout(function(){
            jQuery('#'+_this.id+' div.list-variants').css('display', 'none');
        }, 100);  
    }  
    this.OpenClose = function()
    {
        if (jQuery('#'+this.id+' div.list-variants').css('display') == 'none')
        {
            this.Open();
        }
        else
        {
            this.Close();       
        }
    }
} 
////////////////////////////////////


/* кдасс для возможности обновлять контент компонент в режиме Ajax */
function ComponentAjaxMode()
{
    this.arParams = new Array();
    this.sComponentName = '';
    this.sBlockId = '';
    var _this = this;
    this.Init = function(sComponentName, sBlockId)
    {
        this.sComponentName = sComponentName; 
        this.sBlockId = sBlockId;
    }
    
    this.AddParam = function(sIndex, sValue)
    {        
        this.arParams[sIndex] = sValue;
    }
    this.DeleteParam = function(sIndex)
    {   
        delete this.arParams[sIndex];
    }
    this.LoadComponent = function()
    {   
        
        jQuery.ajax({
            type: 'POST',
            url: "/system/ajax_response/component_ajax_mode.php",
            cache: true,
            data: this.SetParam(),
            beforeSend: function() 
            {
                OpenWaitWindow(_this.sBlockId);
            },
            success: function(sComponentData) 
            {   
                CloseWaitWindow();
                if (sComponentData == 'NEED_AUTH')
                {
                    window.location = '/account/login/?back_url='+_this.arParams['sBackUrl'];
                }
                else
                {
                    jQuery('#'+_this.sBlockId).html(sComponentData);                 
                    
                }
                
                return true;
            }
        });
        
        
    }
    this.SetParam = function()
    {
        var sParamForComponent = '{"sComponentName":"'+this.sComponentName+'"';
        var arPrepareParam = new Array();
        var arParams = this.arParams;
        for (sIndex in arParams)
        {
            sPrepareParam = '"'+sIndex+'":"'+arParams[sIndex]+'"';
            arPrepareParam.push(sPrepareParam);            
        }
        if (arPrepareParam.length > 0)
        {
            sParamForComponent += ','+(arPrepareParam.join(','));            
        }
        sParamForComponent += '}';
        
        return eval('(' +sParamForComponent+ ')');
    }
    this.GetParam = function(sIndex)
    {
        return this.arParams[sIndex]
        
    }
    
}    
/** ------ **/
/* ф-ции для работы с popup окнами*/
function OpenLogin(obj)
{
    if (jQuery('#login_tooltip').css('display') == 'none')
    {
        CloseSignup();
        var pos = jQuery(obj).offset();        
        ileft = pos.left - jQuery('#login_tooltip').innerWidth() + $(obj).innerWidth() + 12;
        jQuery('#login_tooltip').css('left', ileft+'px');
        jQuery('#login_tooltip').css('display', 'block');
    }
    else
        jQuery('#login_tooltip').css('display', 'none');
}
function CloseLogin()
{
    jQuery('#login_tooltip').css('display', 'none');
}
function OpenSignup(obj)
{
    if (jQuery('#signup_tooltip').css('display') == 'none')
    {
        CloseLogin();
        var pos = jQuery(obj).offset();
        ileft = pos.left - jQuery('#signup_tooltip').innerWidth() + $(obj).innerWidth() + 10;
        jQuery('#signup_tooltip').css('left', ileft+'px');
        jQuery('#signup_tooltip').css('display', 'block');
    }
    else
        jQuery('#signup_tooltip').css('display', 'none');
}
function CloseSignup()
{
    jQuery('#signup_tooltip').css('display', 'none');
}
function OpenLang(obj)
{
    var pos = jQuery(obj).position(); 
    tooltip = jQuery('#language_tooltip');
    ileft = pos.left - tooltip.innerWidth() + jQuery(obj).innerWidth() + 7;
    itop = pos.top - tooltip.innerHeight(); 
    tooltip.css('top', itop+'px');
    tooltip.css('left', ileft+'px');
    jQuery('#language_tooltip').css('display', 'block');
}
function CloseLang()
{
    jQuery('#language_tooltip').css('display', 'none');
}
function OpenSliderTooltip(obj)
{
    jQuery('#slider_tooltip').css('display', 'block');
    var pos = jQuery(obj).offset();
    ileft = pos.left+10;
    itop = pos.top-10;
    jQuery('#slider_tooltip').css('top', itop+'px');
    jQuery('#slider_tooltip').css('left', ileft+'px');
}
function CloseSliderTooltip()
{
    jQuery('#slider_tooltip').css('display', 'none'); 
}

function OpenWaitWindow(id)
{
    iHeight = jQuery('#'+id).outerHeight();
    iWidth = jQuery('#'+id).outerWidth();
    
    var pos = jQuery('#'+id).offset();
    iLeft = pos.left;
    iTop = pos.top;
    
    jQuery('#waitwindow').css('width', iWidth+'px');
    jQuery('#waitwindow').css('height', iHeight+'px');
    jQuery('#waitwindow').css('top', iTop+'px');
    jQuery('#waitwindow').css('left', iLeft+'px');                       
    jQuery('#waitwindow').css('display', 'block');
    
    anim = jQuery('#waitwindow .animation');
    anim = anim[0];
    animHeight = jQuery(anim).outerHeight(); 
    animTop = parseInt(iHeight/2 - animHeight/2);
    jQuery('#waitwindow .animation').css('margin-top', animTop+'px');
}
function CloseWaitWindow() 
{                                                        
    jQuery('#waitwindow').css('display', 'none');
}

function HoverTableRow(row)
{
    jQuery(row).addClass('hover');
}
function OutTableRow(row)
{
    jQuery(row).removeClass('hover');
}

function ActivateType(obj)
{
    var div = obj.parentNode;
    jQuery('.active-left-btn', div).addClass('left-btn');
    jQuery('.active-left-btn', div).removeClass('active-left-btn');
    jQuery('.active-right-btn', div).addClass('right-btn');
    jQuery('.active-right-btn', div).removeClass('active-right-btn');
    
    firstId = jQuery('.left-btn', div).attr('id');
    secondId = jQuery('.right-btn', div).attr('id');
    jQuery('#'+firstId+'_content').css('display', 'none');
    jQuery('#'+secondId+'_content').css('display', 'none');
    id = obj.id;
    
    jQuery('#'+id+'_content').css('display', 'block');
    if (jQuery(obj).hasClass('left-btn'))
    {
        jQuery(obj).addClass('active-left-btn');
        jQuery(obj).removeClass('left-btn');
    }
    else
    {
        jQuery(obj).addClass('active-right-btn');
        jQuery(obj).removeClass('right-btn');
    }
    
}

function LoginHover(obj)
{
    jQuery(obj).addClass('login_hover');
}
function LoginOut(obj)
{
    jQuery(obj).removeClass('login_hover');
}
///////////////////////////////////////


/* ф-ции для добавления в закладки */

/* определяем версию браузера */
function GetBrowserInfo() 
{
    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browserName  = navigator.appName;
    var fullVersion  = ''+parseFloat(navigator.appVersion); 
    var majorVersion = parseInt(navigator.appVersion,10);
    var nameOffset,verOffset,ix;

    // In MSIE, the true version is after "MSIE" in userAgent
    if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
     browserName = "Microsoft Internet Explorer";
     fullVersion = nAgt.substring(verOffset+5);
    }
    // In Opera, the true version is after "Opera" 
    else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
     browserName = "Opera";
     fullVersion = nAgt.substring(verOffset+6);
    }
    // In Chrome, the true version is after "Chrome" 
    else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
     browserName = "Chrome";
     fullVersion = nAgt.substring(verOffset+7);
    }
    // In Safari, the true version is after "Safari" 
    else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
     browserName = "Safari";
     fullVersion = nAgt.substring(verOffset+7);
    }
    // In Firefox, the true version is after "Firefox" 
    else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
     browserName = "Firefox";
     fullVersion = nAgt.substring(verOffset+8);
    }
    // In most other browsers, "name/version" is at the end of userAgent 
    else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) 
    {
     browserName = nAgt.substring(nameOffset,verOffset);
     fullVersion = nAgt.substring(verOffset+1);
     if (browserName.toLowerCase()==browserName.toUpperCase()) {
      browserName = navigator.appName;
     }
    }
    // trim the fullVersion string at semicolon/space if present
    if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
    if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);

    majorVersion = parseInt(''+fullVersion,10);
    if (isNaN(majorVersion)) {
     fullVersion  = ''+parseFloat(navigator.appVersion); 
     majorVersion = parseInt(navigator.appVersion,10);
    }

    return {type:browserName,version:majorVersion};
}
/* осцществляем добавление в закладки */ 
function BookmarkUs(a)
{
    var url = window.document.location;
    var title = window.document.title;
    var b = GetBrowserInfo();
    if( b.type == 'Microsoft Internet Explorer' && 7 > b.version && b.version >= 4 ){
        window.external.AddFavorite(url,title);
    }else if( b.type == 'Opera' ){
        a.href = url;
        a.rel = "sidebar";
        a.title = url+','+title;
        return true;
    }else if( b.type == "Netscape" ){
        window.sidebar.addPanel(title,url,"");
    }else{
        alert("Please, press CTRL+D to add this page to bookmarks.");
    }
    return false;
}

///////////////////////////////////////////////////

/* ф-ции для работы с картинками */

function screenHeight(){
    return jQuery.browser.opera? window.innerHeight : jQuery(window).height();
}                                                        
function screenWidth(){
    return jQuery.browser.opera? window.innerWidth : jQuery(window).width();
}

jQuery.preloadImages = function() {
   jQuery.each (arguments,function (e) {
       jQuery("<img>").attr("src", this);
   }); 
}

function PreloadImages()
{
    jQuery.preloadImages(
        sSiteTemplatePath+ "/images/tooltips/language_head.png", 
        sSiteTemplatePath+ "/images/tooltips/language_body.png",
        sSiteTemplatePath+ "/images/new/slider.png",  
        sSiteTemplatePath+ "/images/tooltips/slider_btn_bg.png",
        sSiteTemplatePath+ "/images/tooltips/comment_bottom.png",
        sSiteTemplatePath+ "/images/tooltips/comment_top.png",
        sSiteTemplatePath+ "/images/tooltips/comment_left.png",
        sSiteTemplatePath+ "/images/tooltips/comment_right.png",
        sSiteTemplatePath+ "/images/header/search_btn_bg.png",
        sSiteTemplatePath+ "/images/header/login_arrow_hover.png",
        sSiteTemplatePath+ "/images/header/signup_bg_hover.png"
        );
}
///////////////////////////////////////

/* ф-ции компонента torrent.filter */

// готовим поисковую фразу для поиска
function PrepareSearchPhraze(sSearchPhraze)
{
    // поисковая фраза может быть только состоять из латинского алфавита    
    var oExp = new RegExp('[^A-Za-z0-9_]+', 'ig');
    var arWords = sSearchPhraze.split(oExp);
    arNeedWords = new Array();
    
    for(i = 0; i < arWords.length; i++ )
    {
        if (arWords[i] != '')
        {
            arNeedWords.push(arWords[i]);
        }
        
    }
    
    var sParsingSearchPhraze = arNeedWords.join('-');
    
    return sParsingSearchPhraze;
}
/*
устанавливаем обработчик на событие OnSubmit
*/ 
function ExecuteSearch()
{    
    var sSearchPhraze = jQuery('#sSearchPhrase').val();
    sParsingSearchPhraze = PrepareSearchPhraze(sSearchPhraze);
    
    sSearchUrl = '/latest/';
    if ( sParsingSearchPhraze.length > 0 && sParsingSearchPhraze!='Search' )
    {       
        var sFilterCategory = jQuery('#sFilterCategory').val();                   
        sSearchUrl = sSearchDir + '-' + sFilterCategory + '/' + sParsingSearchPhraze.toLowerCase() + '/'       
    }
    
    window.location = sSearchUrl;          
} 

var bCategoryAnimationActive = false;
/* в зависимости от выбранной категории ф-ция делает выделенную вкладку */
function SetCategory(id)
{   
    
    jQuery('input[name="sFilterCategory"]').val(id);
    if (bCategoryAnimationActive)
        return false;
        
    bCategoryAnimationActive = true;
    var ar = jQuery('.yellow').get();
    cur = ar[0];
    
    //if (cur.id == id)
        //return;
     
    jQuery(cur).removeClass('yellow');   
    jQuery('#'+id).addClass('yellow');
    bCategoryAnimationActive = false;    
}
jQuery(function()
{          
    function formatItem(row) {
        return row[0] + unescape(" %3Csmall%3E(" + row[1] + ")%3C/small%3E");
    }
    // Подключаем мех-м autocomplete для поля ввода поисковой фразы 
    jQuery("#sSearchPhrase").autocomplete('/system/ajax_response/get_queries.php', {
        delay: 400,
        matchContains: false,
        matchSubset: false,
        cacheLength: 16,
        width: 561,
        formatItem: formatItem,
        max: 8,
        minChars: 2,
        selectFirst: false
        }
    );  
    jQuery("#sSearchPhrase").focus(
        function()
        {               
            if (jQuery(this).val() == 'Search')
            {
                jQuery(this).val('');
            }
            
            
        }
    );
    if (typeof sFilterValue == "undefined")
    {
        sFilterValue = 'all';        
    }
    
    SetCategory(sFilterValue);
    jQuery("#sSearchPhrase").keyup(
        function(oEvent)
        {            
            if (oEvent.keyCode == 13)
            {
                ExecuteSearch();                
            }
        }
    )   
}
)
function SearchHover(obj)
{
    jQuery(obj).addClass('hovered');
}
function SearchOut(obj)
{
    jQuery(obj).removeClass('hovered');
}
/////////////////////////////////////


/* ф-ции компонента torrent.new */ 
function SetNewsHeight(id)
{
    iMaxHeight = 0;
        
    jQuery('#'+id+' .block').each(function() {
        
        iHeight = jQuery(this).height();
        if (iHeight>iMaxHeight)
            iMaxHeight = iHeight;
    });
    jQuery('#'+id+' .block').each(function() {
        jQuery(this).css('height', iMaxHeight+'px');    
    });
}

//////////////////////////////////////

/* ф-ции компонента torrent.detail */ 


/* устанавливаем обработчик на добавлении и удалении "закладки" */ 
function SetBookmarkActionHandler()
{
    jQuery('#bookmarkRemoveLink, #bookmarkAddLink').bind('click',
        function()
        {
            sType = (jQuery(this).attr('id') == 'bookmarkAddLink') ? 'add' : 'remove';
            
            if (sType == 'add' && bIsHaveBookmarkFolder == 'Y')            
            {   
                OpenBookmarkTooltip(jQuery(this));
            }
            else
            {
                jQuery('#bookmarksFolderSelector').toggle();
                BookmarkAction(sType)    
            }
            return false;
            
        }
    )        
}

/* устанавливаем обработчик на добавлении и удалении "обузы" */ 
function SetObuseActionHandler()
{
    jQuery('#obuseAddLink').bind('click', function()
        {
            jQuery.post(
                '/system/ajax_response/obuse_action.php',
                {
                    sActionType: 'add',
                    iTorrentId: iTorrentId
                },
                function()
                {
                    $('#obuseAddLink').css('display', 'none');
                    $('#obuseRemoveLink').css('display', 'inline');
                }
            );
            return false;
        }
    );
    
    jQuery('#obuseRemoveLink').bind('click', function()
        {
            jQuery.post(
                '/system/ajax_response/obuse_action.php',
                {
                    sActionType: 'remove',
                    iTorrentId: iTorrentId
                },
                function()
                {
                    $('#obuseAddLink').css('display', 'inline');
                    $('#obuseRemoveLink').css('display', 'none');
                }
            );
            return false;
        }
    );  
   
}


/* ф-ция для выполнения: добавления и удаления закладок через Ajax */
function BookmarkAction(sType)
{    
    iBookmarkFolderId = -1;
    if (jQuery('#b_foolder').css('display') == 'block')
    {
        iBookmarkFolderId = jQuery('#sel-folder').attr('rel');
        CloseBookmarkTooltip();        
    }    
    
    jQuery.post('/system/ajax_response/bookmark_action.php', 
                {
                    'sActionType':sType,
                    'iTorrentId': iTorrentId,
                    'iBookmarkFolderId': iBookmarkFolderId
                },
                function(sError)
                {                    
                    if (sError.length == 0)
                    {                        
                        jQuery('#bookmarkAddLink, #bookmarkRemoveLink').toggle();
                    }
                    else
                    {
                        if (sError == 'NEED_AUTH')
                        {
                            window.location = '/account/login/?back_url='+sBackUrl;
                        }
                        else
                        {
                            alert(sError);
                        }                        
                    }
                }
    )   
}
/* утсанавливаем обрабочики действий над рейтингом  */
function SetRateAction(sRateType)
{
    var sId = sRateType+'Count';             
    jQuery.post('/system/ajax_response/rate_action.php', 
        {
            'sRateType':sRateType,
            'iTorrentId': iTorrentId
        },
        function(sJsonContent)
        {
            if (sJsonContent.length > 0)
            {
                var oContent = eval('(' + sJsonContent + ')');
                
                if ((oContent.sError).length == 0)
                {   
                    jQuery('#FakeCount, #GoodCount').removeAttr('href');                            
                    var iFakeCount = parseInt(jQuery('#FakeCount').attr('rel'));
                    var iGoodCount = parseInt(jQuery('#GoodCount').attr('rel'));
                    
                    
                    iFakeCount = (sId.indexOf('Fake') > -1) ? iFakeCount + 1 : iFakeCount;
                    iGoodCount = (sId.indexOf('Good') > -1) ? iGoodCount + 1 : iGoodCount;
                    
                    iSumCount = (iGoodCount + iFakeCount == 0) ? 1 : iGoodCount + iFakeCount;
                    
                    
                    iSumCount = Math.floor(iGoodCount / iSumCount * 10);
                    iSumCount = iSumCount > 10 ? 10 : iSumCount;
                    $('div.rating-num').html(iSumCount);
                    $('div.stars img').attr('src', sTemplateFolder+'/images/rating/zvezda'+iSumCount+'.png');
                    
                    var button = $('#'+sId);
                    button
                        .html( button.html().replace( /([^\(\)0-9]+)\([0-9]+\)/,'$1 ('+(sRateType=='Good'?iGoodCount:iFakeCount)+')' ) )
                        .attr( 'rel', (sRateType=='Good'?iGoodCount:iFakeCount) );
                    
                }
                else
                {
                    if (oContent.sError == 'NEED_AUTH')
                    {
                        window.location = '/account/login/?back_url='+sBackUrl;
                    }
                    else
                    {
                        alert(oContent.sError);
                    }                        
                }
            }
        }
    );
}
/* ф-ция осуществляет добавление и удаление торрента из New листа*/
function TorrentActionToNewList()
{
    jQuery('#NewRemoveLink, #NewAddLink').bind('click',
        function()
        {            
            if (typeof sCategoryCode != 'undefined' && typeof (iTorrentTypeItemId * -1) != 'undefined')
            {
                
                sStatusValue = (jQuery(this).attr('id') == 'NewAddLink') ? 'Y' : 'N';            
                
                jQuery.post('/system/ajax_response/new_action.php', 
                    {
                        'sStatusValue':sStatusValue,
                        'arTorrentTypeItemId': iTorrentTypeItemId,
                        'sCategoryCode': sCategoryCode
                    },
                    function(sError)
                    {                    
                        if (sError.length == 0)
                        {                        
                            jQuery('#NewRemoveLink, #NewAddLink').toggle();                        
                        }
                        else
                        {
                            if (sError == 'NEED_AUTH')
                            {
                                window.location = '/account/login/?back_url='+sBackUrl;
                            }
                            else
                            {
                                alert(sError);
                            }                            
                        }
                    }
                )
            }
            
            return false;
            
        }
    )
    
}
/* вешаем обработчик на добавлении, удаление торрента из списка personal rss */
function SetRssActionHandler()
{
    
    // накладываем обработичик на удаление rss списка
    jQuery('a[id*="RssList"]').bind('click', 
            function()
            {                
                var sType = jQuery(this).attr('rel');
                jQuery.get('/system/ajax_response/rss_action.php?sActionType='+sType+'&iTorrentId='+iTorrentId, 
                    function(sError)
                    {                        
                        if (sError.length > 0)
                        {
                            if (sError == 'NEED_AUTH')
                            {
                                window.location.href = "/account/login/?back_url="+sBackUrl;
                            }
                            else
                            {
                                alert(sError);
                            }
                        }
                        else
                        {                           
                           jQuery('#RemoveFromRssList, #AddToRssList').toggle();
                        }
                        
                    }
                )
                
                return false;                
            }            
    )
    
}
/* Открываем список с групами bookmark*/
function OpenBookmarkTooltip(obj)
{
    jQuery('#bookmark_tooltip').css('display', 'block');
    var pos = jQuery(obj).offset();    
    ileft = pos.left-13;
    itop = pos.top+10;
    jQuery('#bookmark_tooltip').css('top', itop+'px');
    jQuery('#bookmark_tooltip').css('left', ileft+'px');
}
/* Закрываем список с групами bookmark*/
function CloseBookmarkTooltip()
{
    jQuery('#bookmark_tooltip').css('display', 'none'); 
}

function CatalogClick(id)
{
    
    var obj = jQuery('#'+id);
    if (obj.css('display') == 'none')
    {
        obj.css('display', 'block');    
    }
    else
    {       
        obj.css('display', 'none');
        jQuery('#'+id+' .catalog-content').css('display', 'none');  
    }
}
function ClickGalleryPhoto(obj, id)
{
    var tooltip = jQuery('#screenshot');
    jQuery('.content', tooltip).html(); 
    iWidth = jQuery('#'+id).width();
    iWidth += 24;
    tooltip.css('width', iWidth+'px');
    jQuery('.content', tooltip).html('<img src="'+jQuery('#'+id).attr('src')+'" alt="" />');   
    
    var pos = jQuery(obj).offset();
    ileft = pos.left-6;
    itop = pos.top+jQuery(obj).height();
    
    if ((ileft+tooltip.width()) > (jQuery(window).scrollLeft() + screenWidth()))
    {
        ileft = jQuery(window).scrollLeft() + screenWidth()-tooltip.width()-30;    
    }                                                                      
    
    tooltip.css('top', itop+'px');
    tooltip.css('left', ileft+'px');
    tooltip.css('display','block');   
}

function HideGalleryPhoto()
{
    jQuery('#screenshot').css('display', 'none');    
}

/*ф-ция для загрузки структуры файлов в торренте*/
function LoadPeerFiles(iTorrentId)
{
    
    if ($('#peer-files-list').children().length == 0)
    {
        $('#peer-files-list').show();
        OpenWaitWindow('peer-files-list');
        $.post('/system/ajax_response/component_ajax_mode.php',
                {
                    'iTorrentId':iTorrentId,
                    'sComponentName': 'torrent.peer_files'
                },
                function(sResult)
                {
                    $('#peer-files-list').html(sResult);
                    CatalogClick('catalog');
                    CloseWaitWindow();                                
                }
        )
    }
    CatalogClick('catalog');
        
}
/* ф-ция получения магнитной ссылки*/
function GetMagnetLink()
{
    sHref = '#';
    $.post('/system/ajax_response/get_magnet_link.php',
                {
                    'iTorrentId':iTorrentId,
                    'sTorrentName':sTorrentName,
                    'sTorrentHash':sTorrentHash
                },
                function(sResult)
                {
                    if (sResult.length > 0)
                    {
                        sHref = sResult;                        
                    }
                    $('#magnet-link').attr('href', sHref);
                    
                }
    )
        
}
/* отображаем блок анноунс-трекеров*/
function GetAnnounceTrackersBlock()
{
    
    $.post('/system/ajax_response/component_ajax_mode.php',
                {
                    'sComponentName' : 'torrent.announce_trackers',
                    'iTorrentId':iTorrentId,
                    'sTorrentHash':sTorrentHash
                },
                function(sResult)
                {
                     $('#announce-container').html(sResult);                     
                }
    )
        
}

//////////////////////////////////////

/* ф-ции компонента torrent.comment */ 
/* ф-ция осуществляет выставление рейтинга для комментария */
function RateComment(sCommentId, iRatePoint)
{   
    var arCommentId = sCommentId.split('_');
    var sCommentType = arCommentId[0]; 
    var iCommentId = arCommentId[1];
    var sRateType = (iRatePoint > 0) ? 'plus' : 'minus';
    jQuery('#ratediv_'+ sCommentId +' a.'+((sRateType == 'plus') ? 'down' : 'up')).removeAttr('href');
    jQuery('#ratediv_'+ sCommentId +' a.'+((sRateType == 'plus') ? 'up' : 'down')).css('display', 'none');
    var iNewRate = parseInt(jQuery('#commrate_'+sCommentId).html()) + parseInt(iRatePoint);
    
    jQuery('#commrate_'+sCommentId).html(iNewRate);
    jQuery.post('/system/ajax_response/rate_comment.php',
                    {
                        sCommentType : sCommentType,
                        iCommentId : iCommentId,
                        iRatePoint : iRatePoint,
                        iCurrentPage : iCurrentPage,         
                        torrentId : iTorrentId
                    },
                    function(sError)
                    {
                        if (sError.length !=0)
                        {
                            alert(sError);
                        }
                       
                    }
        
    
    )    
}
/*
устанавливаем обработчик на событие добавления комментария и ответа на комменарий
*/ 
function PostCommentText(oObjectPost)
{
    var iParentCommentId = 0;
    var iCommentReplyId = -1;
    var sCommentText = '';
    var sType = '';
    if (jQuery(oObjectPost).attr('name') == 'replyComment')
    {
        var arId = jQuery(oObjectPost).attr('id').split('_');        
        iParentCommentId = arId[2];         
        
        sCommentText = jQuery('textarea[name="'+ jQuery(oObjectPost).attr('id') +'"]').val();
        var arRel = jQuery(oObjectPost).attr('rel').split('_');
        iCommentReplyId = arRel[1];
        
    }
    else
    {        
        sCommentText = jQuery('textarea[name="CommentContent"]').val();                
    }
    
    if (sCommentText.trim().length == 0)
    {
        alert('Неоходимо ввести текст');
        return false;        
    }
    OpenWaitWindow('all_comments');   
    
    jQuery.post('/system/ajax_response/comment_action.php', 
            {                 
                'action' : 'post',
                'text': sCommentText, 
                'commentReplyId' : iCommentReplyId, 
                'torrentId' : iTorrentId, 
                'parentId' : iParentCommentId,
                'iCurrentPage' : iCurrentPage
            }, 
        function(sContent)
        {
            CloseWaitWindow();
            if (sContent.length == 0)
            {
                alert('Возникла ошибка при добавления комментария');
            }
            else
            {                
                jQuery('#all_comments').html(sContent);
            }                   
        }
        
    )
        
}

/* осущесвляет открытие формы для ответа */
function ReplyThis(commentId)
{    
    jQuery('#area'+commentId).toggle();
    jQuery('#btn'+commentId).toggle();
}

/* осуществляет открытие формы для редактирования комментария */
function EditThis(commentId)
{   
    if (jQuery('#area-edit'+commentId).css('display') == 'none')
    {   
        jQuery('#area-edit'+commentId+' textarea').val(jQuery('#commentText'+commentId).html());
        jQuery('#commentText'+commentId).html('');
    }
    else
    {   
        jQuery('#commentText'+commentId).html(jQuery('#area-edit'+commentId+' textarea').val());
        jQuery('#area-edit'+commentId+' textarea').val('');
    } 
    jQuery('#area-edit'+commentId).toggle()
    jQuery('#btn-edit'+commentId).toggle();
    
    
}
/* обновляем коммент на backend'е*/
function UpdateCommentText(commentId)
{
    commentText = jQuery('#area-edit'+commentId+' textarea').val();
    
    OpenWaitWindow('com'+commentId);
    jQuery.post('/system/ajax_response/comment_action.php', 
            {
                'action': 'update',          
                'commentId': commentId,        
                'iCurrentPage' : iCurrentPage,
                'torrentId' : iTorrentId, 
                'commentText' : commentText
            },
            function (sError)
            {
                CloseWaitWindow();
                if (sError.length > 0)                
                {
                    alert(sError);
                    return false;
                }
                jQuery('#commentText'+commentId).html(commentText);
                jQuery('#area-edit'+commentId).toggle()
                jQuery('#btn-edit'+commentId).toggle();
            }
    )
    
}
//////////////////////////////////////

/* ф-ции компонента torrent.browse_detail */ 
function GanresShowList()
{
    $('#ganres-hider').css('display', 'block');
    $('#ganres-shower').css('display', 'none');
    $('#ganres-all').removeClass('ganres-one-column');
    $('#ganres-all').addClass('ganres-two-column');
    $('#ganres-all .ganres-hide-col').css('display', 'none');
}
function GanresHideList()
{
    $('#ganres-hider').css('display', 'none');
    $('#ganres-shower').css('display', 'block');
    $('#ganres-all .ganres-hide-col').css('display', '');
    $('#ganres-all').removeClass('ganres-two-column');
    $('#ganres-all').addClass('ganres-one-column');
}
function SHNavigation(id, show)
{
    if (show)
    {
        $('#'+id).css('display', 'block');
        $('#'+id+'_info').css('display', 'block');
    }
    else
    {
        $('#'+id).css('display', 'none');
        $('#'+id+'_info').css('display', 'none');
    }
}
//////////////////////////////////////

/* ф-ции компонента torrent.actor_list */ 
/* осуществляем навигацию по алфавиту по списку актеров через Ajax*/
function NavActorListByLetter(sCurrLetter, oLink)
{   
    $('td.sel, a.sel').removeClass('sel');
    $(oLink).addClass('sel');
    $(oLink).parent().addClass('sel');
    sCurrentAlfabetLetter = sCurrLetter;    
    oComponentActorList.AddParam('sCurrLetter', sCurrLetter); 
    oComponentActorList.AddParam('sCurrPage', 1);
    oComponentActorList.AddParam('iItemsPerPage', iItemsPerPageGlobal);
    oComponentActorList.LoadComponent();
}
function NavActorList(iCurrPage,iItemsPerPage)
{
    if( !iItemsPerPage )
    {
        iItemsPerPage = iItemsPerPageGlobal;
    }else
    {
        iItemsPerPageGlobal = iItemsPerPage;
    }
    oComponentActorList.AddParam('sCurrLetter', sCurrentAlfabetLetter); 
    oComponentActorList.AddParam('sCurrPage', iCurrPage);
    oComponentActorList.AddParam('iItemsPerPage', iItemsPerPage);
    oComponentActorList.LoadComponent();
    
}
function ShowFindWords(sFindStr, sParam)
{    
    return '<strong class="find_words">'+sFindStr+'</strong>';    
}

function GetActorSearchPraze()
{
    var sSearchPhraze = $('#sActorSearchField').val();
    
    sSearchPhraze = sSearchPhraze.toUpperCase();
    sSearchPhraze = sSearchPhraze.replace(' ', '-');
    
    return sSearchPhraze;
    
}
/* поиск по актерам */
function SearchActor()
{
    
    sSearchPhraze = GetActorSearchPraze();
    
    sCurrAlfabet = $('table.alphabet a.sel span').html();
    OpenWaitWindow('actor-list');
    jQuery.post('/system/ajax_response/search_addfilter_item.php', 
            {
                'sAddFilterType' : 'Actor',
                'sDetailLink': '/movies/actor/',
                'sSearchPhraze':sSearchPhraze,
                'sCurrAlfabet': sCurrAlfabet
            },
            function(sContent)
            {                
                CloseWaitWindow();
                oContent = eval('('+ sContent +')');
                sSearchPhraze = GetActorSearchPraze();
                if (oContent.sSearchPhraze == sSearchPhraze)
                {
                    
                    sContent = oContent.sContentHtml;
                    sContent = (sContent.length > 0) ? sContent : '<div rel="search-actor-list"><h2 class="panel-title">Sorry, but no results found</h2></div>';                                    
                    $('div[rel="search-actor-list"]').each(
                        function()
                        {
                            $(this).remove();
                        }
                    );
                    $('#actor-list').html(sContent);
                }
            }
    )
    
}
/* обработчик изменения значения поля Актер*/
function ActorFieldOnChangeHandler()
{    
    $('#sActorSearchField').keyup(
         
        function()
        {   
            CloseWaitWindow();
            
            $('div[rel="search-actor-list"]').each(
                    function()
                    {
                        $(this).remove();
                    }
                );
            if ($('#sActorSearchField').val().length > 1)
            {
                $('#common_author_list').hide().remove();                
                $('.navigation-clearer').hide().remove();                
                
                SearchActor();                
                
            }
            else
            {                
                NavActorList(1);
            }
            
            
        }
    )    
}
//////////////////////////////////////

/* ф-ции компонента torrent.torrent.tvshow_list */ 
/* осуществляем навигацию по алфавиту по списку тв-шоу через Ajax*/
function NavTvShowListByLetter(sCurrLetter, oLink)
{   
    $('td.sel, a.sel').removeClass('sel');
    $(oLink).addClass('sel');
    $(oLink).parent().addClass('sel');
    sCurrentAlfabetLetter = sCurrLetter; 
       
    oComponentTvShowList.AddParam('sCurrLetter', sCurrLetter); 
    oComponentTvShowList.AddParam('sCurrPageAdditional', 1); 
    
    oComponentTvShowList.LoadComponent();
}
function NavTvShowList(iCurrPage)
{
    oComponentTvShowList.AddParam('sCurrLetter', sCurrentAlfabetLetter); 
    oComponentTvShowList.AddParam('sCurrPageAdditional', iCurrPage); 
    oComponentTvShowList.LoadComponent();
    
}


function GetTvSearchPraze()
{
    var sSearchPhraze = $('#sTvShowSearchField').val();
    
    sSearchPhraze = sSearchPhraze.toUpperCase();
    sSearchPhraze = sSearchPhraze.replace(' ', '-');
    
    return sSearchPhraze;
    
}
/* поиск по тв-шоу */
function SearchsTvShow()
{
    
    sSearchPhraze = GetTvSearchPraze();
    
    sCurrAlfabet = $('table.alphabet a.sel span').html();
    OpenWaitWindow('tvshow-list');
    jQuery.post('/system/ajax_response/search_addfilter_item.php', 
            {
                'sAddFilterType' : 'TvShow',
                'sDetailLink': '/tv/tvshow/',
                'sSearchPhraze':sSearchPhraze,
                'sCurrAlfabet': sCurrAlfabet
            },
            function(sContent)
            {                
                CloseWaitWindow();
                oContent = eval('('+ sContent +')');
                sSearchPhraze = GetTvSearchPraze();
                if (oContent.sSearchPhraze == sSearchPhraze)
                {
                    
                    sContent = oContent.sContentHtml;
                    sContent = (sContent.length > 0) ? sContent : '<div rel="search-tvshow-list"><h2 class="panel-title">Sorry, but no results found</h2></div>';                                    
                    $('div[rel="search-tvshow-list"]').each(
                        function()
                        {
                            $(this).remove();
                        }
                    );
                    $('#tvshow-list').html(sContent);
                }
            }
    )
    
}
/* обработчик изменения значения поля Актер*/
function TvShowFieldOnChangeHandler()
{    
    $('#sTvShowSearchField').keyup(
         
        function()
        {   
            CloseWaitWindow();
            
            $('div[rel="search-tvshow-list"]').each(
                    function()
                    {
                        $(this).remove();
                    }
                );
            if ($('#sTvShowSearchField').val().length > 1)
            {
                $('#common_tvshow_list').hide().remove();                
                $('.navigation-clearer').hide().remove();                
                
                SearchsTvShow();                
                
            }
            else
            {                
                 NavTvShowList(1);
            }
            
            
        }
    )    
}
function ClickEpisode(id)
{
    if (jQuery('#'+id).hasClass('episode-close'))
    {
        jQuery('#'+id).addClass('episode-open');
        jQuery('#'+id).removeClass('episode-close');
        
        if ($('#'+id+'-torrents table').length == 0)
        {
            
            OpenWaitWindow(id+'-torrents');
            $.post('/system/ajax_response/get_tv_episod_torrents.php', 
                    {
                        'iEpisodId': $('#'+id+'-torrents').attr('rel')
                    },
                    function(sContent)
                    {
                        CloseWaitWindow();
                        
                        if (sContent.indexOf('table') == -1)
                        {
                            $('#'+id+'-torrents').html('<h2 class="panel-title">Sorry, but no results found</h2>');
                            return false;
                        }
                        
                        $('#'+id+'-torrents').html(sContent);                    
                        
                        
                    }
            );
         }
    }
    else
    {
        jQuery('#'+id).addClass('episode-close');
        jQuery('#'+id).removeClass('episode-open');
    }
}
//////////////////////////////////////

/* ф-ции компонента cabinet.profile */ 


/* ф-ция открывает окно для отправки сообщения */
function ShowMessageForm()
{
    var obj = $('#SendMessageForm');
    
    itop = $(window).scrollTop() + (screenHeight() - obj.height())/2; 
    ileft = $(window).scrollLeft() + (screenWidth() - obj.width())/2;  
    obj.css('top', itop+'px');
    obj.css('left', ileft+'px');
    obj.css('display', 'block');    
    
    $('#SendMessageForm span[id="MessageAddresse"]').html(sUserNickname);    
    $('#SendMessageForm textarea').val(''); 
       
}

function CloseMess()
{
    var obj = $('#SendMessageForm');  
    obj.css('display', 'none');      
}
/* отправка сообщения польозвателю */
function SendMessage()
{
    var sAddresseNickname = $('#SendMessageForm span[id="MessageAddresse"]').html();
    var sMessageText = $('#MessageText').val();
    if (sMessageText.length > 500)
    {
        alert('Your message must not be greater than 500 symbols');
        return false;
    }
    $.post('/system/ajax_response/private_message_action.php',
                    {
                        sActionType: 'SendMessage',
                        sAddresseNickname: sAddresseNickname,
                        sMessageText : sMessageText,
                        bIsIncome : false                                
                    },
                    function(sError)
                    {
                        if (sError.length !=0)
                        {
                            alert(sError);
                            
                        }
                        else
                        {
                            $('#SendMessageForm').css('display', 'none');;
                            
                        }
                    }
    )
    
    
}
/* осуществляем сортировку списка торрентов в профайле через Ajax*/
function SortUserTorrent(sFiledBy, sSort)
{
    
    oComponentAjaxMode = new ComponentAjaxMode(); 
    oComponentAjaxMode.Init('user_torrent_list', 'user_torrent');
    oComponentAjaxMode.AddParam('sFiledBy', sFiledBy);
    oComponentAjaxMode.AddParam('sSort', sSort);
    oComponentAjaxMode.AddParam('iUserTorrentCount', iUserTorrentCount);
    oComponentAjaxMode.AddParam('iTorrentPageItemCount', iTorrentPageItemCount);
    oComponentAjaxMode.AddParam('iUserId', iUserId);
    oComponentAjaxMode.AddParam('iCurrentPage', 1);
    
    oComponentAjaxMode.LoadComponent();
}

/* осуществляем навигацию списка торрентов в профайле через Ajax*/
function NavUserTorrent(iPageNum)
{   
    oComponentAjaxMode = new ComponentAjaxMode(); 
    oComponentAjaxMode.Init('user_torrent_list', 'user_torrent'); 
    oComponentAjaxMode.AddParam('iUserTorrentCount', iUserTorrentCount);
    oComponentAjaxMode.AddParam('iTorrentPageItemCount', iTorrentPageItemCount);
    oComponentAjaxMode.AddParam('iUserId', iUserId);
    oComponentAjaxMode.AddParam('iCurrentPage', iPageNum);
    
    oComponentAjaxMode.LoadComponent();
}

/* осуществляем навигацию списка комментариев в профайле через Ajax*/
function NavUserComment(iPageNum)
{   
    oComponentAjaxMode = new ComponentAjaxMode(); 
    oComponentAjaxMode.Init('cabinet.latest_comment', 'user_comment'); 
    oComponentAjaxMode.AddParam('sUserNickname', sUserNickname);
    oComponentAjaxMode.AddParam('iTorrentPageItemCount', iTorrentPageItemCount);
    oComponentAjaxMode.AddParam('iUserId', iUserId);
    oComponentAjaxMode.AddParam('iCurrentPage', iPageNum);
    
    oComponentAjaxMode.LoadComponent();
}

function NavStatistic(iPageNum)
{
    oComponentAjaxMode = new ComponentAjaxMode(); 
    oComponentAjaxMode.Init('cabinet.profile', 'reputation_stat_content'); 
    
    oComponentAjaxMode.AddParam('iTorrentPageItemCount', iTorrentPageItemCount);
    oComponentAjaxMode.AddParam('sUserNickname', sUserNickname);
    oComponentAjaxMode.AddParam('iCurrentPage', iPageNum);
    
    oComponentAjaxMode.LoadComponent();
    
}
/* ф-ция удаления торрента*/
function DeleteTorrent(iTorrentId)
{
    $.post('/system/ajax_response/delete_torrent.php', 
            {
                iTorrentId: iTorrentId
            },
            function (sError)
            {                
                
                if (sError.length > 0)
                {
                    if (sError == 'NEED_AUTH')
                    {
                       window.location = '/account/login/?back_url='+sBackUrl;
                    }
                    else
                    {
                        alert(sError);
                    }
                }
            }
    );
    $('#torrent_'+iTorrentId).css('display', 'none').remove();
    
}
function UploadAvatar()
{
    var obj = $('#upload_avatar');
    $('#upload_avatar div.form_error').remove();
    itop = $(window).scrollTop() + (screenHeight() - obj.height())/2; 
    ileft = $(window).scrollLeft() + (screenWidth() - obj.width())/2;  
    obj.css('top', itop+'px');
    obj.css('left', ileft+'px');
    obj.css('display', 'block');      
}
function CloseUploadAvatar()
{
    var obj = $('#upload_avatar');  
    obj.css('display', 'none');      
}

//////////////////////////////////////


//////////////////////////////////////

/* ф-ции компонента torrent.cabinet.private_messages_list */ 
/* ф-ция вышает обработчик на просмотр полного текста сообщения, 
а также отправляет Ajax-запрос на изменение статуса сообщения   */
function ViewFullMessageHandler()
{    
    $('a[id*="UserMessage"]').each(
        function()
        {            
            $(this).bind('click', 
                function()
                {                    
                    var oTd = $(this).parent();
                    var arInfoId = $(this).attr('id').split('_');
                    var iMessageId = arInfoId[1];
                    
                    // получаем полный текст сообщения
                    if (arJsonFullMessage[iMessageId] !== undefined)
                    {                        
                        oTd.text(arJsonFullMessage[iMessageId]);
                        $(this).remove();
                        
                        $('#mess'+iMessageId+'_arr').removeClass('message_close').addClass('message_open');
                        
                        $.post('/system/ajax_response/private_message_action.php',
                            {
                                sActionType: 'UpdateMessageStatus',
                                iMessageId: iMessageId,
                                bIsIncome : bIsIncome                                
                            },
                            function(sError)
                            {
                                if (sError.length !=0)
                                {                                    
                                    ShowError(sError);
                                }
                            }
                            
                        )
                    }
                    
                    return false;
                    
                }
            )
        }
    )
}
/* Отмечаем все сообщения на странице */
function SelectAllMessage()
{
    $('input[name*="MessageCheckbox"]').each(
        function()
        {            
            var sIsCheck =  $('#SelectAllMessage').is(':checked') ? 'checked' : '';
            $(this).attr('checked', sIsCheck);
        }
    );
}
/* Выполняем действия с сообщениями */
function ExecuteMessageAction()
{
    var arMessageId = new Array(); 
    var sActionType = '';
    if (oComponentAjaxMode !== null)   
    {
        sActionType = oComponentAjaxMode.GetParam('sActionType');        
    }
    
    $('a[name*="checkbox_item"]').each(
        function()
        {
            if ($(this).hasClass('checked'))
            {
                var iMessageId = $(this).attr('rel');
                
                
                if (sActionType == 'RemoveMessage')
                {
                    $('#UserMessageItem_'+iMessageId).css('display', 'none').remove();                        
                }
                else if (sActionType == 'AddToNewMessage')
                {
                    if (arJsonFullMessage[iMessageId] !== undefined)
                    {                        
                        var oTd = $(this).parent().prev().prev();
                        
                        var sMessage = arJsonFullMessage[iMessageId];
                        sMessage = sMessage.substr(0, 125);
                        sHtml = '<a class="message_close" id="mess'+iMessageId+'_arr"></a>'+
                                '<div class="message_text" id="mess'+iMessageId+'">'+
                                    '<a href="#" class="mini_mess" id="UserMessage_'+iMessageId+'">'+sMessage+'</a>'
                                '</div>';
                        oTd.html(sHtml);
                        
                        
                    }
                    
                    $(this).removeClass('checked');                   
                    
                }
                $('#ch_all_link').removeClass('checked');
                arMessageId.push(iMessageId); 
            }
        }
    );
    sMessageIds = '';
    var sMessageIds = arMessageId.join(',');
    
    if (sMessageIds.length > 0)
    {
        $.post('/system/ajax_response/private_message_action.php',
                        {
                            sActionType: sActionType,
                            sMessageIds: sMessageIds,
                            bIsIncome : bIsIncome                                
                        },
                        function(sError)
                        {
                            if (sError.length !=0)
                            {
                                ShowError(sError);
                            }
                        }                                
        ) 
    }
    if (sActionType == 'AddToNewMessage')    
    {
        ViewFullMessageHandler();
    }
}
/* удаляем отдельно одно сообщение*/
function DeleteMassageItem(iMessageId)
{
    $('#UserMessageItem_'+iMessageId).css('display', 'none').remove();
    $.post('/system/ajax_response/private_message_action.php',
                    {
                        sActionType: 'RemoveMessage',
                        sMessageIds: iMessageId,
                        bIsIncome : bIsIncome                                
                    },
                    function(sError)
                    {
                        if (sError.length !=0)
                        {
                            ShowError(sError);
                        }
                    }
    )
    
}
/* ф-ция открывает окно для отправки сообщения */
function ShowSendMessageForm(iMessageId)
{
    var obj = $('#SendMessageForm');
    itop = $(window).scrollTop() + (screenHeight() - obj.height())/2; 
    ileft = $(window).scrollLeft() + (screenWidth() - obj.width())/2;  
    obj.css('top', itop+'px');
    obj.css('left', ileft+'px');
    obj.css('display', 'block');    
    
    $('#SendMessageForm span[id="MessageAddresse"]').html($('#AddresseNickname_'+iMessageId).val());    
    $('#SendMessageForm textarea').val(''); 
       
}
/* отправка сообщения польозвателю */
function SendMessage()
{
    var sAddresseNickname = $('#SendMessageForm span[id="MessageAddresse"]').html();
    var sMessageText = $('#MessageText').val();
    if (sMessageText.length > 500)
    {
        alert('Your message must not be greater than 500 symbols');
        return false;
    }
    $.post('/system/ajax_response/private_message_action.php',
                    {
                        sActionType: 'SendMessage',
                        sAddresseNickname: sAddresseNickname,
                        sMessageText : sMessageText,
                        bIsIncome : false                                
                    },
                    function(sError)
                    {
                        if (sError.length !=0)
                        {
                            ShowError(sError);
                        }
                        else
                        {
                            $('#SendMessageForm').css('display', 'none');
                            
                        }
                    }
    )
    
    
}
function CloseMess()
{
    var obj = $('#SendMessageForm');  
    obj.css('display', 'none'); 
}     


/* ф-ция отвечающая за переход по нав. цепочке*/
function NavMessages(iCurrentPage)
{
    oComponentAjaxMode.AddParam('iCurrentPage', iCurrentPage); 
    oComponentAjaxMode.LoadComponent();
    
}
function Checkbox(obj, id)
{
    if ($(obj).hasClass('checked'))
    {
        $(obj).removeClass('checked');
        $('#'+id).attr('checked', false);
    }
    else
    {      
        $(obj).addClass('checked');      
        $('#'+id).attr('checked', true);
    }
}
function CheckAll(obj, block_id)
{
    if ($(obj).hasClass('checked')) 
    {
        $('#'+block_id+' a.checkbox').removeClass('checked');    
        $('#'+block_id+' input').attr('checked', false);    
    }
    else
    {    
        $('#'+block_id+' a.checkbox').addClass('checked');    
        $('#'+block_id+' input').attr('checked', true);      
    }
}
function CheckboxAll (link_id, ch_id)
{
    if ($('#'+link_id).hasClass('checked'))
    {
        Checkbox($('#'+link_id).get(), ch_id);
    }     
}
function ShowError(sError)
{    
    if (sError == 'NEED_AUTH')
    {
        window.location = '/account/login/?back_url='+sBackUrl;
    }
    else
    {
        alert(sError);
    }
}

//////////////////////////////////////


//////////////////////////////////////

/* ф-ции компонента cabinet.vote */ 

function submitFeedback(id, feedback, comment, t_id) {
    
    feedbackValue = getCheckedValue(feedback);
    
    if (feedbackValue == '' && comment == '') {
        alert('Vote is empty!');
        return false;
    }
    
    $.post('/system/ajax_response/vote_action.php', 
            {
                voteId: id, 
                voteValue: feedbackValue, 
                commentText: comment,  
                torrentId: t_id
            },
            function (sResult)
            {   
                oResult = eval('('+sResult+');');
                if (oResult.sError.length > 0)
                {                                    
                    ShowError(oResult.sError);
                }
                
                
            }
    );
    $('tr[name="vote_item_'+id+'"]').each(
        function()
        {
            $(this).css('display', 'none').remove();
            
        }
    )
    
}



function discardSelected() {
    var result = "";
    $('a[name="checkbox"]').each( 
        function () 
        {    
            if ($(this).hasClass('checked'))
            {
                id = $(this).attr('rel');
                $('tr[name="vote_item_'+id+'"]').css('display', 'none').remove();
                result = result + id + ',';
            }    
        }
    );
    result = result.substr(0, result.length-1); 
    
    $.post('/system/ajax_response/vote_action.php', {arVoteId: result},
        function(sResult)
        {
            oResult = eval('('+sResult+');');
            if (oResult.sError.length > 0)
            {                                    
                ShowError(oResult.sError);
            }
            $('#ch_all_link').removeClass('checked');            
        }
    );
}
function ShowError(sError)
{    
    if (sError == 'NEED_AUTH')
    {
        window.location = '/account/login/?back_url='+sBackUrl;
    }
    else
    {
        alert(sError);
    }
}
function AddVoteComment(obj, id)
{
    $(obj).css('display', 'none');
    $('#'+id).css('display', 'block');
}
function RadioClick(link_id, rel)
{                                   
    $("input[rel='"+rel+"']").each(function(){
        id = this.id;
        l_id = id + '_link';
        if (l_id==link_id)
        {
            $('#'+l_id).addClass('radio_checked'); 
            this.checked = true;
        }
        else
        {
            $('#'+l_id).removeClass('radio_checked');     
        }
    });   
}
function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}
function Checkbox(obj, id)
{
    if ($(obj).hasClass('checked'))
    {
        $(obj).removeClass('checked');
        $('#'+id).attr('checked', false);
    }
    else
    {      
        $(obj).addClass('checked');      
        $('#'+id).attr('checked', true);
    }
}
function CheckAll(obj, block_id)
{
    if ($(obj).hasClass('checked')) 
    {
        $('#'+block_id+' a.checkbox').removeClass('checked');    
        $('#'+block_id+' input').attr('checked', false);    
    }
    else
    {    
        $('#'+block_id+' a.checkbox').addClass('checked');    
        $('#'+block_id+' input').attr('checked', true);      
    }
}
function CheckboxAll (link_id, ch_id)
{
    if ($('#'+link_id).hasClass('checked'))
    {
        Checkbox($('#'+link_id).get(), ch_id);
    }     
}

//////////////////////////////////////

//////////////////////////////////////

/* ф-ции компонента cabinet.bookmarks */ 
/* выбираем дейстие над группой закладок */
function SelectFolder(oFolder, iFolderId)
{
    $('#oldFolderId').val(iFolderId);    
    obFolder.Select(oFolder);
    
}
/* ф-ция удаления торрента*/
function DeleteTorrent(iTorrentId)
{
    $.post('/system/ajax_response/bookmark_action.php', 
            {
                iTorrentId: iTorrentId,
                sActionType: 'remove'
            },
            function (sError)
            {
                if (sError.length !=0)
                {                                    
                    if (sError == 'NEED_AUTH')
                    {
                        window.location = '/account/login/?back_url='+sBackUrl;
                    }
                    else
                    {
                        alert(sError);
                    }
                }
                
            }
    );
    $('#torrent_'+iTorrentId).css('display', 'none').remove();
    
}
//////////////////////////////////////


/* ф-ции компонента torrent.tv_additional_info */ 
/* ф-ция получения торрентов для эпизода из сериала */
function GetEpisodTorrent(oLink, iSeasonNum)
{
    $('div.series a.current').removeClass('current').attr('href', '#').attr('onlick', 'GetEpisodTorrent(this); return false;');
    $(oLink).addClass('current').removeAttr('href').removeAttr('onlick');
    var arIds = $(oLink).attr('id').split('_');
    
    OpenWaitWindow('tv-torrent-list'+iSeasonNum);
    
    jQuery.post('/system/ajax_response/get_tv_episod_torrents.php', 
                {
                    'iEpisodId': arIds[1]
                },
                function(sContent)
                {
                    CloseWaitWindow();
                    
                    if (sContent.length < 10)
                    {
                       sContent =  '<table cellspacing="0" cellpadding="0" border="0" class="main">'+
                                        '<tr><td><h2 class="panel-title">Sorry, but no results found</h2></td></tr>'+
                                   '</table>';
                    }
                    $('#tv-torrent-list'+iSeasonNum).html(sContent);                    
                }
    );    
}
/**
* ф-ция выборки вкладки сезонов
*/
function SelectSeason(iSeasonNum, iFirstEpisodId)
{
    SelectTab('season'+iSeasonNum, 'q_tabs', 'tab');
    $('#episod_'+iFirstEpisodId).trigger('click');
}
//////////////////////////////////////

/* ф-ции компонента cabinet.upload_torrent */ 
function SelectYellowListElement(objYellowList, objLink, sType, sValue)
{
    objYellowList.Select(objLink);
    
    $('input[name="'+ sType +'"]').val(sValue);
    if (sType == 'category')
    {        
        $.post('/system/ajax_response/get_subcategory.php', 
                {
                    'iCategoryId':sValue
                },
                function(sContent)
                {
                    if (sContent.length == 0)
                    {
                        alert('Ошибка при поиске подкатегорий');
                        return;
                    }
                    
                    var oList = eval('(' + sContent + ')');
                    var sType = oList.sType;
                    var sHtml = oList.sHtml;
                    sHideType = (sType == 'subcategory') ? 'genre' : 'subcategory';                    
                    $('#'+sHideType).hide();
                    $('input[name="'+sHideType+'"]').val(-1);
                    
                    if (sHtml.length > 0)
                    {
                        $('#'+sType).show();
                        $('#'+sType+'_center').html(eval(sType));
                        $('input[name="'+sType+'"]').val(0);                    
                        $('#'+sType+'-list').html(sHtml);
                        
                    }
                    else
                    {
                        $('input[name="genre"]').val(-1);
                        $('input[name="subcategory"]').val(-1);
                        $('#genre').hide();
                        $('#subcategory').hide();
                        
                    }
                    
                }
        )
        
    }
}

function ChooseElement(objYellowList, sType, iElementId)
{
    $('#'+ sType +'-list a').each(
            function ()
            {
                sId = $(this).attr('rel');
                arId = sId.split('_');
                
                if (iElementId == arId[1])
                {
                    SelectYellowListElement(objYellowList, this, sType, iElementId);
                }
            }
    );
}
//////////////////////////////////////

/* ф-ции компонента cabinet.history */

function NavDownloadHistory(iCurrentPage)
{
    oComponentDownloadAjaxMode.AddParam('iCurrentPage', iCurrentPage);
    oComponentDownloadAjaxMode.LoadComponent();
}

function NavViewHistory(iCurrentPage)
{
    oComponentViewAjaxMode.AddParam('iCurrentPage', iCurrentPage);
    oComponentViewAjaxMode.LoadComponent();
}

function NavSearchHistory(iCurrentPage)
{
    oComponentSearchAjaxMode.AddParam('iCurrentPage', iCurrentPage);
    oComponentSearchAjaxMode.LoadComponent();
}
//////////////////////////////////////

/* ф-ции компонента cabinet.new */
function ChangeGenre(iTorrentTypeItemId)
{           
    var iGenreId = $('#list-genre'+iTorrentTypeItemId).val();
    $.post('/system/ajax_response/new_action.php', 
            {
                'sCategoryCode':sCategory,
                'sChangeSubCategory': 'Y',
                'iTorrentTypeItemId' : iTorrentTypeItemId,
                'sType' : sFilterParam,
                'iGenreId':iGenreId
            },
            function(sResult)
            {
                
                if (sResult == 'NEED_AUTH')
                {
                    window.location.href = "/account/login/?back_url="+sBackUrl;
                }
                else
                {
                    alert(sResult);
                } 
                
            }
    );
}

function ChangeSubCategory(iTorrentId)
{           
    $.post('/system/ajax_response/new_action.php', 
            {
                'sCategoryCode':sCategory,
                'sChangeSubCategory': 'Y',
                'iTorrentId' : iTorrentId,
                'sType' : sFilterParam,
                'iSubCategoryId':$('#list-subcategory'+iTorrentId).val()
            },
            function(sResult)
            {
                
                if (sResult == 'NEED_AUTH')
                {
                    window.location.href = "/account/login/?back_url="+sBackUrl;
                }
                else
                {
                    alert(sResult);
                }
            }
    );
}

/* слайдер для сезонов */
function SeasonLeft()
{
    iOffset = 100;    
    iLeft = parseInt(jQuery('#season-platform').css('left'));
    iSpace = parseInt(jQuery('#season-hider').width());
    iWidth = parseInt(jQuery('#season-platform').width());
    if (iLeft>=0)
        return;
    iLeft = iLeft+iOffset;
    if (iLeft>=0)
        iLeft = 0;
    jQuery('#season-platform').animate({left: iLeft+'px'}, 200);
        
    jQuery('#s-right').removeClass('season-right-dis');    
    
    if (iLeft == 0)
        jQuery('#s-left').addClass('season-left-dis');    
}
function SeasonRight()
{
    iOffset = 100;    
    iLeft = parseInt(jQuery('#season-platform').css('left'));
    iSpace = parseInt(jQuery('#season-hider').width());
    iWidth = parseInt(jQuery('#season-platform').width());
    
    if (iSpace-iLeft == iWidth)
        return;
        
    iLeft = iLeft-iOffset;
    if (iSpace-iLeft > iWidth)
        iLeft = iSpace-iWidth;
    jQuery('#season-platform').animate({left: iLeft+'px'}, 200);
        
    jQuery('#s-left').removeClass('season-left-dis');    
    
    if (iSpace-iLeft == iWidth)
        jQuery('#s-right').addClass('season-right-dis');    
}

/* ф-ции компонента torrent.music_additional_info*/
function ClickAlbum(id)
{
    if (jQuery('#'+id).hasClass('episode-close'))
    {
        jQuery('#'+id).addClass('episode-open');
        jQuery('#'+id).removeClass('episode-close');
        
        if ($('#'+id+'-torrents table').length == 0)
        {
            
            OpenWaitWindow(id+'-torrents');
            $.post('/system/ajax_response/artist_action.php', 
                    {
                        'sSearchPhraze': $('#'+id+'-torrents').attr('rel')
                    },
                    function(sContent)
                    {
                        CloseWaitWindow();
                        
                        if (sContent.indexOf('table') == -1)
                        {
                            $('#'+id+'-torrents').html('<h2 class="panel-title">Sorry, but no results found</h2>');
                            return false;
                        }
                        
                        $('#'+id+'-torrents').html(sContent);                    
                        
                        
                    }
            );
         }
    }
    else
    {
        jQuery('#'+id).addClass('episode-close');
        jQuery('#'+id).removeClass('episode-open');
    }
}
//////////////////////////////////////

//////////////////////////////////////

/* ф-ции компонента torrent.artist_list */ 
/* осуществляем навигацию по алфавиту по списку актеров через Ajax*/
function NavArtistListByLetter(sCurrLetter, oLink)
{   
    $('td.sel, a.sel').removeClass('sel');
    $(oLink).addClass('sel');
    $(oLink).parent().addClass('sel');
    sCurrentAlfabetLetter = sCurrLetter;    
    oComponentArtistList.AddParam('sCurrLetter', sCurrLetter); 
    oComponentArtistList.AddParam('sCurrPage', 1); 
    oComponentArtistList.LoadComponent();
}
function NavArtistList(iCurrPage)
{
    oComponentArtistList.AddParam('sCurrLetter', sCurrentAlfabetLetter); 
    oComponentArtistList.AddParam('sCurrPage', iCurrPage); 
    oComponentArtistList.LoadComponent();
    
}


function GetArtistSearchPraze()
{
    var sSearchPhraze = $('#sArtistSearchField').val();
    
    sSearchPhraze = sSearchPhraze.toUpperCase();
    sSearchPhraze = sSearchPhraze.replace(' ', '-');
    
    return sSearchPhraze;
    
}
/* поиск по актерам */
function SearchArtist()
{
    
    sSearchPhraze = GetArtistSearchPraze();
    
    sCurrAlfabet = $('table.alphabet a.sel span').html();
    OpenWaitWindow('artist-list');
    jQuery.post('/system/ajax_response/search_addfilter_item.php', 
            {
                'sAddFilterType' : 'Artist',
                'sDetailLink': '/music/artist/',
                'sSearchPhraze':sSearchPhraze,
                'sCurrAlfabet': sCurrAlfabet
            },
            function(sContent)
            {                
                CloseWaitWindow();
                oContent = eval('('+ sContent +')');
                sSearchPhraze = GetArtistSearchPraze();
                if (oContent.sSearchPhraze == sSearchPhraze)
                {
                    
                    sContent = oContent.sContentHtml;
                    sContent = (sContent.length > 0) ? sContent : '<div rel="search-artist-list"><h2 class="panel-title">Sorry, but no results found</h2></div>';                                    
                    $('div[rel="search-artist-list"]').each(
                        function()
                        {
                            $(this).remove();
                        }
                    );
                    $('#artist-list').html(sContent);
                }
            }
    )
    
}
/* обработчик изменения значения поля Актер*/
function ArtistFieldOnChangeHandler()
{    
    $('#sArtistSearchField').keyup(
         
        function()
        {   
            CloseWaitWindow();
            
            $('div[rel="search-artist-list"]').each(
                    function()
                    {
                        $(this).remove();
                    }
                );
            if ($('#sArtistSearchField').val().length > 1)
            {
                $('#common_author_list').hide().remove();                
                $('.navigation-clearer').hide().remove();                
                
                SearchArtist();                
                
            }
            else
            {                
                NavArtistList(1);
            }
            
            
        }
    )    
}
///////////
///////////
/* ф-ции компонента torrent.actor_list*/
function ClickFilm(id)
{
    if (jQuery('#'+id).hasClass('episode-close'))
    {
        jQuery('#'+id).addClass('episode-open');
        jQuery('#'+id).removeClass('episode-close');
        
        if ($('#'+id+'-torrents table').length == 0)
        {
            
            OpenWaitWindow(id+'-torrents');
            $.post('/system/ajax_response/film_action.php', 
                    {
                        'sSearchPhraze': $('#'+id+'-torrents').attr('rel')
                    },
                    function(sContent)
                    {
                        CloseWaitWindow();
                        
                        if (sContent.indexOf('table') == -1)
                        {
                            $('#'+id+'-torrents').html('<h2 class="panel-title">Sorry, but no results found</h2>');
                            return false;
                        }
                        
                        $('#'+id+'-torrents').html(sContent);                    
                        
                        
                    }
            );
         }
    }
    else
    {
        jQuery('#'+id).addClass('episode-close');
        jQuery('#'+id).removeClass('episode-open');
    }
}
// фунция для валидации форм
function ValidateForm(sFormId)
{
    bIsHaveError = false;
    $('.incorrect-email').each(
        function()
        {
            $(this).remove();
        }
    );
    sErrorText = '';
    $('#'+sFormId+' input').each(
        function()
        {
            if ($(this).attr('validate') != '')
            {
                sValue = $(this).val();
                
                switch($(this).attr('validate'))
                {
                    case 'notnull':
                    {
                        if (sValue.length == 0)
                        {
                            $(this).parent().append('<span class="incorrect-email">* Field must not be empty</span>');
                            bIsHaveError = true;
                            //sErrorText += 'Fields must not be empty<br>';
                        }
                        break;
                    }
                    case 'email':
                    {
                        var sFilter=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
                        
                        if (!sFilter.test(sValue))
                        {
                            $(this).parent().append('<span class="incorrect-email">* Incorrect E-mail</span>');
                            bIsHaveError = true;
                            //sErrorText += 'Incorrect E-mail<br>';
                        }
                        break;
                    }
                }
                
            }
        }
    );
    if ($('#'+sFormId+' textarea').val() == '')
    {
        bIsHaveError = true;
        sErrorText += 'Message must not be empty<br>';
        
    }
    if (bIsHaveError)
    {
        $('#feedback_error').html(sErrorText);
        $('#feedback_error').show();
        return false;
    }
    $('#'+sFormId).submit();
    
}
// инстанцируем фото-галлерею
function InitGallery()
{
    $('#galleria').galleria(
            {
                data_source: data,
                image_crop: false,
                frame_color: '#000',
                transition: 'slide',
                hide_dock: false,
                extend: function() {
                    this.$('info,counter').hide();
                },
                carousel: true
            }
        );
        $('td.ph a').each(
            function(index, value)
            {
                var i = index;
                $(value).bind('click', 
                    function()
                    {
                        $('#galleria').galleria({show: i});
                        $('#galleria').css('height', $('body').height());
                        $('#galleria-wrapper').css('height', $('div#wrapper').height());
                        //$('#galleria').css('top', $(window).scrollTop());
                        $('#galleria').css('display', 'block');
                        $('#galleria').css('position', 'fixed');
                        $('#galleria-wrapper').css('display', 'block');
                        return false;
                    }
                )
            }
        );
}
// отображаем превью-картинку у артистов при наведение
function GetActorPreviewImage()
{
    
    $.post('/system/ajax_response/actor_action.php',
            {
                'arActorIds':arActorIds
            },
            function(sResult)
            {
                if (sResult.length > 0)
                {
                    arActorPreview = eval('('+ sResult +')');
                    for(iActorId in arActorPreview)
                    {                    
                        sHtml = '<div id="preview'+iActorId+'" style="display:none; z-index:35;"><img src="'+arActorPreview[iActorId]+'" width="125" height="163"/></div>'
                       
                        $('body').append(sHtml);
                    }
                    ActorPreviewHover();
                    ActorPreviewOut();
                }
            }
    )
}

function ActorPreviewHover()
{
    $('a[id*="actor"]').mouseover( 
        function(e) 
        {
            
            iLeft = e.pageX;
            iTop = e.pageY - 170;
            var pos = jQuery(this).position(); 
            
            arIds = $(this).attr('id').split('_');            
            iActorId = arIds[1];
            $('#preview'+iActorId).css(
                            {
                                'display' : 'block',
                                'position' : 'absolute',
                                'left' : iLeft,
                                'top' : iTop
                            });
        }
    );
}
function ActorPreviewOut()
{    
    
    $('a[id*="actor"]').mouseout( 
        function(e) 
        {
            arIds = $(this).attr('id').split('_'); 
            iActorId = arIds[1];
            $('#preview'+iActorId).css('display', 'none');

        }
    );
}
// выводим мини-блок с детальной инфой
function ShowDeatilBlock(oLink)
{   
    arData = $(oLink).attr('rel').split('_');
    var iTorrentId = arData[0];
    sCategoryCode = arData[1];
    sTorrentName = arData[2];
    
    if (typeof $('#detail_wrapper'+iTorrentId).html() != "string")
    {
       // OpenWaitWindow('torrent_'+iTorrentId);
        
        $.post('/system/ajax_response/get_detail_info.php', 
                {
                    'iTorrentId':iTorrentId,
                    'sTorrentName':sTorrentName,
                    'sCategoryCode':sCategoryCode                
                },
                function(sResult)
                {                
                    if (sResult.length < 20)
                    {
                        window.location = $('#detail-link' + iTorrentId).attr('href');
                    }
                    else
                    {   
                        $('#torrent_' + iTorrentId).after(                            
                            '<tr class="sep" rel="table_info'+iTorrentId+'"><td colspan="14"></td></tr>'+
                            '<tr rel="table_info'+iTorrentId+'"><td colspan="14" class="detail" >'+
                            '<div id="detail_wrapper'+iTorrentId+'">'+                            
                            '</div>'+
                            '</td></tr>'
                            
                        );
                            
                        $('#detail_wrapper'+iTorrentId).html(sResult);
                        browse = GetBrowserInfo();
                        if (browse.type == 'IE' && browse.version == 6)
                        {
                            DD_belatedPNG.fix('div.downloads div.content');                               
                        }
                        
                        //CloseWaitWindow();                                    
                    }
                }
        );
    }
    else
    {   
        $('tr[rel*="table_info'+iTorrentId+'"]').remove();
    }
    
}
///////////
/* ф-ции компонента torrent.advanced_search*/
// ф-ция иницилизации стилизованных селлектов для advanced search 
function initCusel()
{
    $(function()
    {
        $('span.advanced a').click(function () {
          if ($("div.advancedSearch").is(":hidden")) {
            $("div.advancedSearch").slideDown("slow");
          } else {
            $("div.advancedSearch").slideUp("slow");
          }
          return false;
        });
        
        var params = {changedEl:"#type-sel", visRows:100, scrollArrows: false, checkZIndex: true}
        cuSel(params);
        params = {changedEl:"#mode-sel", visRows:100, scrollArrows: false}
        cuSel(params);
        params = {changedEl:"#sort-by", visRows:100, scrollArrows: false}
        cuSel(params);
        params = {changedEl:"#sort-order", visRows:100, scrollArrows: false}
        cuSel(params);
        if (bIsUseAdvancedSearch == 'N' && $('#sSearchPhrase').val() == 'Search')
        {
            $("div.advancedSearch").hide();
        }else{
            $("div.advancedSearch").show();
        }
        
    });
    
    jQuery("#sAdvancedSearchPhrase").focus(
        function()
        {               
            if (jQuery(this).val() == 'Enter text for search')
            {
                jQuery(this).val('');
            }
            
            
        }
    );
    
    jQuery("#sAdvancedSearchPhrase").keyup(
        function(oEvent)
        {            
            if (oEvent.keyCode == 13)
            {
                ExecuteAdvancedSearch();                
            }
        }
    )
}
// ф-ция обновляет общее число сидов и личей у торрента
function RefreshSeedAndLeech(iTorrentId)
{
    $('#seed'+iTorrentId).html('...');
    $('#leech'+iTorrentId).html('...');
    
    /*$.post('/system/ajax_response/refresh_torrent_peers.php', 
                {
                    'iTorrentId' : iTorrentId                    
                }, 
                function(sContent)
                {
                    if (sContent.length == 0)
                    {
                        alert('Error refresh seedd and leeches');
                        return false;
                    }
                    oContent = eval('(' + sContent + ')');
                    
                    $('#seed'+iTorrentId).html(oContent.TorrentSeedCount);                    
                    $('#leech'+iTorrentId).html(oContent.TorrentLeechCount);
                }
    )*/
}
// ф-ция для выполненя расширенного поиска
function ExecuteAdvancedSearch()
{
    var sSearchPhraze = $('#sAdvancedSearchPhrase').val();
    
    sParsingSearchPhraze = PrepareSearchPhraze(sSearchPhraze);
    
    sSearchUrl = '/latest/';
    if (sParsingSearchPhraze.length > 0)
    {       
        
        var sFilterCategory = $('#sFilterCategory').val();
        var sMode = $('#mode-sel').val();
        var sField = $('#sort-by').val();
        var sOrder = $('#sort-order').val();
        var sGetParams = '?mode=' + sMode + '&field=' + sField + '&sort=' + sOrder;
        sSearchUrl = '/search-' + $('#type-sel').val() + '/' + sParsingSearchPhraze.toLowerCase() + '/' + sGetParams;                                  
    }
    
    window.location = sSearchUrl;
}

///////////   

/* ----- функции компонента tvshows.calendar ----- */
// постраничная прокрутка
function navigateTvShowsCalendar(pageNum){
    /*$.ajax({
        url : '/system/ajax_response/component_ajax_mode.php',
        data : {
            'sComponentName' : 'tvshows.calendar'
        },
        type : 'POST',
        dataType : 'html'
    });*/
}


//////////////////////////////////////
jQuery(document).ready(
    function()
    {   
        setTimeout(
            function()
            {   
               PreloadImages();
            }, 500
        );
        
        var form = $('#auth_form');
        var validateSignUpForm = function (){
            var globalerror = false;
            form.find('.input').each(function (){
                var th = $(this);
                var element = th.find('input');
                var currenterror = false;
                if( element.val()=='' ){
                    currenterror = true;
                }else{
                    switch ( element.attr('name') ){
                        case 'arRegisterData[UserNickname]':
                            if ( element.val().length<3 )
                                currenterror = true;
                        break;
                        case 'arRegisterData[UserEmail]':
                            if ( element.val().length<3 || !(/^[a-zA-Z0-9_\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/.test(element.val())) )
                                currenterror = true;
                        break;
                        case 'arRegisterData[UserPassword]':
                            if ( element.val().length<PASSWORD_MIN_LENGTH )
                                currenterror = true;
                        break;
                        case 'arRegisterData[UserConfirmPassword]':
                            if ( form.find('input[name=arRegisterData\[UserPassword\]]').val() != element.val() )
                                currenterror = true;
                        break;
                    }
                }
                if ( currenterror ){
                    th.next().removeClass('input-validation-correct').addClass('input-validation-incorrect');
                    globalerror = true;
                }else{
                    th.next().removeClass('input-validation-incorrect').addClass('input-validation-correct');
                }
            });
            return globalerror ? false : true;
        }
        form.submit(function (){
            if ( !validateSignUpForm() )
                return false;
        }).find('input[name^=arRegisterData]')
            .change(function(){validateSignUpForm();})
            .keyup(function(){validateSignUpForm();})
        validateSignUpForm();
    
        var cutFunction = function (){
            var th = $(this);
            if ( th.val().length>60000 ){
                var scrollTop = th.scrollTop();
                th.val(th.val().substr(0,60000));
                th.scrollTop(scrollTop);
            }
        }
        $('.textarea-maxlength').keyup(cutFunction).blur(cutFunction).change(cutFunction);
        
        $('.search-type').click(function (event){
            if( $(event.target).parents('.search-type-select').length==0 ){
                $('.search-type-select').toggle();
            }
        });
        $('.search-type-item').hover(function (){
            $(this).addClass('search-type-item-hover');
        },function (){
            $(this).removeClass('search-type-item-hover');
        }).click(function (){
            $('#sFilterCategory').val($(this).attr('id').substr(7));
            $('.search-type-text').text($(this).text());
            $('.search-type-select').hide();
        });
        $(document).click(function (event){
            var target = $(event.target);
            if( target.hasClass('search-type')==false && target.parents('.search-type').length==0 ){
                $('.search-type-select').hide();
            }
        });
        
    }
);
