/* Запрос на сохранение страницы перехода после авторизации */
function doSaveSetup(id) {
    $(id).innerHTML = "<br /><img src='/img/loading_cursor.gif' alt='' />";
	
    var params = $('setup-form').serialize();
    new Ajax.Updater(id,'/profile/ajaxSaveSetup/', {method: 'post', parameters: params })
}

/* Додавання прив'язки */
function addAlias(token) {
    new Ajax.Request('/profile/ajaxAddAlias/', {
        method: 'post',
        parameters: 'token='+token,
        onSuccess: function (data) {
            if(data.responseText)
            {
                $('noaliases').hide();
                $('aliases').innerHTML += data.responseText;
            }
        }
    });
}
 
/* Видалення прив'язки */
function deleteAlias(id, confirmStr) {
    jQuery('#alias'+id).fadeTo('fast', 0.5, function() {
        if(!confirm(confirmStr))
        {
            jQuery('#alias'+id).fadeTo('fast', 1);
            return;
        }
        new Ajax.Request('/profile/ajaxDelAlias/', {
            method: 'post',
            parameters: 'alias='+id,
            onSuccess: function (transport) {
                            var objectStr = '#alias'+transport.responseText;
                            var object = jQuery(objectStr);
                            if(object.length > 0)
                            object.slideUp('slow', function() {
                                jQuery(object).remove();
                                if(jQuery('#aliases .alias').length==0)
                                {
                                    $('noaliases').show();
                                }
                            });
                        }
        });
    });
}

/* Проверка на существование такого логина в базе */
function checkLoginExisting(value) {
    $('logincheck').innerHTML = "<br /><img src='/img/loading_cursor.gif' alt='' />";
    new Ajax.Updater('logincheck','/auth/ajaxCheckLoginExisting/', {method: 'post', parameters: '&login='+value })
}

function gamesFavorites(gameId, toDo) {
    new Ajax.Updater('fav','/games/ajaxFav/', {method: 'post', parameters: '&gameId='+gameId+'&toDo='+toDo })
}

/* Работа с избранными видео */
function videoFavorites(videoId, toDo) {
    new Ajax.Updater('fav','/video/ajaxFav/', {method: 'post', parameters: '&videoId='+videoId+'&toDo='+toDo })
}



/* Загрузка видеоконтента */
function loadVideos(type, block) {
    new Ajax.Request('/ajaxSaveCookie/', {method: 'post',parameters: '&blockid='+block+'&blockValue='+type, onFailure:errFunc});
    new Ajax.Updater(block, '/video/ajaxLoadVideos/', {method: 'post', parameters: '&type='+type+'&block='+block })
}

/* Загрузка контента игр */
function loadGames(type, block) {
    new Ajax.Request('/ajaxSaveCookie/', {method: 'post',parameters: '&blockid='+block+'&blockValue='+type, onFailure:errFunc});
    new Ajax.Updater(block, '/games/ajaxLoadGames/', {method: 'post', parameters: '&type='+type+'&block='+block })
}

/* Просмотр приватного сообщения */
function viewPm(id, name, fromid) {
    $(name+'pm'+id).style.display='none'; 
    new Ajax.Updater(name+id,'/profile/ajaxViewPm/', {method: 'post', parameters: '&id='+id+'&name='+name+'&fromid='+fromid })
    $(name+id).style.display = 'block';
}

/* Проверка существования логина */
function checkLogin(value) {
    $('logincheck').innerHTML = "<img src='/img/loading_cursor.gif' alt='Запрос выполняется' />";
    new Ajax.Updater('logincheck','/ajaxCheckLogin/', {method: 'post', parameters: '&login='+value })
}

/* Проверка антиспам */
function checkAnti(value) {
    $('spamcheck').innerHTML = "<img src='/img/loading_cursor.gif' alt='Запрос выполняется' />";
    new Ajax.Updater('spamcheck','/ajaxCheckAnti/', {method: 'post', parameters: '&value='+value })
}

/* Подгрузка гороскопа */
function getHoro(block, value) {
    $(block).innerHTML = "<img src='/img/loading_cursor.gif' alt='Запрос выполняется' />";
    new Ajax.Updater(block,'/ajaxGetHoro/', {method: 'post', parameters: '&value='+value })
}

/* Цитирование личного сообщения */
function pmQuote(id, block) {
    new Ajax.Request('/profile/ajaxPmQuote/', {method: 'post', parameters: '&id='+id, 
        onSuccess: function(transport){
          var response = transport.responseText || "no response text";
          $(block).value = $(block).value + response;
        }
    })
}

/* Отправка личного сообщения */
function sendPm(message, block, id, fromid) {
    $(block).innerHTML = "<img src='/img/loading_cursor.gif' alt='Запрос выполняется' />";
    message = encodeURIComponent(message);
    new Ajax.Updater(block,'/profile/ajaxSendPm/', {method: 'post', parameters: '&message='+message+'&id='+id+'&fromid='+fromid })
}

/* Пейджинг личных сообщений */
function pmRotate(id, fromid, page) {
    new Ajax.Updater('rotate'+id,'/profile/ajaxPmRotate/', {method: 'post', parameters: '&id='+id+'&page='+page+'&fromid='+fromid })
}

/* Оценка видео */
function rateVideo(id, mark) {
    new Ajax.Updater('voting', '/video/ajaxRateVideo/', {method: 'post', parameters: '&id='+id+'&mark='+mark});
}

/* Оценка игры */
function rateGame(id, mark) {
    new Ajax.Updater('voting', '/games/ajaxRateGame/', {method: 'post', parameters: '&id='+id+'&mark='+mark});
}

/* Оценка комментария */
function voteComment(id, currentMark, mark, controller) {
    new Ajax.Updater('c_votes'+id, '/comments/ajaxVoteComment/', {method: 'post', parameters: '&id='+id+'&currentMark='+currentMark+'&mark='+mark+'&cont='+controller});
}

/* Добавление комментария */
function addComment(block, userId, itemId, text, replyId, controller, beforeId) {
    text = encodeURIComponent(text);
    var div = document.createElement('div');
    if (replyId > 0)
    {
        div.setAttribute('class', 'gc-subcomment');
    } else {
        div.setAttribute('class', 'gc-comment');
    }
    new Ajax.Request('/comments/ajaxAddComment/', {method: 'post', parameters: '&userId='+userId+'&itemId='+itemId+'&replyId='+replyId+'&text='+text+'&cont='+controller, 
        onSuccess: function (transport) { 
            var response  = transport.responseText;
            div.innerHTML = response;
            var re        = /\d+/;
            var myArray   = re.exec(response);
            div.setAttribute('id', 'commentBlock'+myArray[0]);
            jQuery('#commentform'+replyId).slideUp('slow', function() {
                if (replyId > 0)
                {
                    $('commentlink'+replyId).style.display='none';
                    $(block).appendChild(div);
                }
                else {
                    $(block).insertBefore(div, $(beforeId));
                }
                jQuery('#commentBlock'+myArray[0]).css('display', 'none');
                
				jQuery('#commentBlock'+myArray[0]).slideDown('slow');
				
				if (typeof jQuery('#nocomments') != 'undefined')
				{
					jQuery('#nocomments').slideUp('fast');
				}

                jQuery('#commenttext'+replyId).css('display', 'block');
                $('commentBlock'+myArray[0]).scrollIntoView(true);
            }); 
        }
    });
}

/* Удаление комментария */
function delComment(block, commentId, controller, replyId) {
    new Ajax.Request('/comments/ajaxDelComment/', {method: 'post', parameters: '&commentId='+commentId+'&cont='+controller, 
        onSuccess: function (transport) {
            if (transport.responseText == 'deleted')
            {
                jQuery('#'+block).slideUp('slow', function() {
                    jQuery('#'+block).remove();
                    jQuery('#delete'+replyId).css('display', 'inline');
                });
            }
            else if (transport.responseText.indexOf('Комментарий удален') >= 0 || transport.responseText.indexOf('Коментар видалено') >= 0)
            {
                jQuery('#'+block).slideUp('slow', function() {
                    $('comment'+commentId).innerHTML = transport.responseText;
                    jQuery('#edit'+commentId).css('display', 'none');
                    jQuery('#delete'+commentId).css('display', 'none');
                    jQuery('#'+block).slideDown('slow');
                });
            }

            //$(block).removeChild('commentBlock'+commentId);
        }
    });
}

/* Ротация новосных категорий */
function changeCategory(id, block) {
    var params = '&blockid='+block+'&blockValue='+id;

    new Ajax.Request('/ajaxSaveCookie/', {method: 'post',parameters:params, onFailure:errFunc});
    new Ajax.Updater(block, '/ajaxChangeCategory/', {method: 'post', onComplete:getFunnyNews, parameters: '&catId='+id})
}

function getFunnyNews() {
        jQuery('#photos').attr('display', 'none');
        jQuery('#photos').galleryView({
            panel_width: 335,
            panel_height: 220,
            frame_width: 50,
            frame_height: 50,
            overlay_height: 50
        });
        jQuery('#photos').fadeIn();
}

/* Свертка разделов форума */
function changeTable(id, blockid) {

    var params = '&blockid='+blockid;
    var array = getElementsByName_iefix('tr',blockid);
        
    for (var i=0;i<array.length;i++) {
    
        if (array[i].style.display != 'none') {
            id.className='collapsed';
            array[i].style.display = 'none';
            if (i == 0) {
                new Ajax.Request('/ajaxSaveCookie/', {method: 'post',parameters:params, onFailure:errFunc});
            }
        }
        else {
            if (i == 0) {
                new Ajax.Request('/ajaxSuspendCookie/', {method: 'post',parameters:params, onFailure:errFunc});
            }
            id.className='collapse';
            array[i].style.display = '';
        }
    }
}

loader= new Image(43,11); 
loader.src="/img/ajax-loader.gif";

/*
    Ajax перелистывание страниц комментариев
*/
function doRollPage(page, userid, itemid, controller) {
    $('loading').innerHTML = '<img src='+loader.src+' alt="" />';
    var params = '&page='+page+'&userid='+userid+'&itemid='+itemid;
    new Ajax.Updater('photoComments', '/'+controller+'/ajaxRollPage/', {method: 'post', parameters: params, onSuccess:modifySuccess});
}

/*
    Ajax перелистывание страниц комментариев
*/
function videoAddComment(userId, itemId, message, replyId) {
    $('loading').innerHTML = '<img src='+loader.src+' alt="" />';
    var params = '&userId='+userId+'&itemId='+itemId+'&replyId='+replyId+'&message='+message;
    new Ajax.Updater('photoComments', '/video/ajaxAddComment/', {method: 'post', parameters: params, onSuccess:modifySuccess});
}

/*
    Ajax редактирование комментария
*/
function doEditComment(id, controller) {
    $('comment'+id).innerHTML = "<br /><br /><center><img src='"+loader.src+"' alt='' /></center>";
    new Ajax.Updater('comment'+id, '/comments/ajaxEditComment/', {method: 'post',parameters: '&id='+id+'&where='+controller, onSuccess:modifySuccess, onFailure:errFunc});
}

/**
 * Ajax сохранение отредактированного комментария
 *
 */
function doApplyEdit(id, text, controller) {
    text = encodeURIComponent(text);
    $('comment'+id).innerHTML = "<br /><br /><center><img src='"+loader.srcc+"' alt='' /></center>";
    new Ajax.Updater('comment'+id, '/comments/ajaxApplyEdit/', {method: 'post', parameters: '&text='+text+'&id='+id+'&where='+controller, onSuccess:modifySuccess})
}

/**
 * Ajax отмена изменений редактирования
 *
 */
function doCancelEdit(id, controller) {
    $('comment'+id).innerHTML = "<br /><br /><center><img src='"+loader.src+"' alt='' /></center>";
    new Ajax.Updater('comment'+id, '/comments/ajaxCancelEdit/', {method: 'post', parameters: '&id='+id+'&where='+controller, onSuccess:modifySuccess});
}

/**
 * Ajax HTML 5
 *
 */
function html5setup(status) {
    $('html5info').innerHTML = "<br /><center><img src='"+loader.src+"' alt='' /></center>";
    new Ajax.Updater('html5info', '/video/ajaxhtmlsetup/', {method: 'post', parameters: '&status='+status, onSuccess:modifySuccess});
}

/** 
 * Ajax отправка жалобы
 *
 */
function sendPetition(id, value, reason) {
    value = encodeURIComponent(value);
    $('feedbackform').innerHTML = "<br /><center><img src='/img/loading_cursor.gif' alt='' /></center><br />";
    new Ajax.Updater('feedbackform', '/video/ajaxsendpetition/', {method: 'post', parameters: '&id='+id+'&value='+value+'&reason='+reason, onSuccess:modifySuccess});
}

/*
    В случае успеха ajax-запроса
*/
function modifySuccess() {
    initOEmbed(document.body);
}
