/**
 * Common JS for VH
 */

// Определение текущего браузера
var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = (userAgent.indexOf('opera') != -1);
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv  = (userAgent.indexOf('webtv') != -1);
var is_ie     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4    = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_moz    = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon    = (userAgent.indexOf('konqueror') != -1);
var is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4    = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac    = (userAgent.indexOf('mac') != -1);

// замена прототайповского клонирования через старый метод, пока не пофиксят баг в IE
function clonePosition(el, source, options)
{
    var pos = $(source).cumulativeOffset();
    $(el).setStyle({
        left: pos[0] + ( options.offsetLeft ? options.offsetLeft : 0 ) + 'px',
        top: pos[1] + ( options.offsetTop ? options.offsetTop : 0 ) + 'px'
    });
}

function checkFrames()
{
    if(self.parent != self && self.parent.frames.length!=0)
        self.parent.location=document.location;
}

function showAjaxError(error)
{
      if (!Element.visible('transparent_header'))
      {
              Element.show('transparent_header');
              new Effect.Pulsate('transparent_header');
      }
      new Insertion.Bottom('transparent_header', error);
}

function redirect(url)
{
        document.location.href = url;
}

/* Upload Progress */

function UploadProgressMeterStatus(callback) {
    this.callback = callback;
}

UploadProgressMeterStatus.prototype  = {
    getStatus: function(ids) {
        for (id in ids)
        {
            new Ajax.Request("/video/ajax/upload/form/server/?id="+escape(ids[id]),
                    { asynchronous: true });
        }
    }
}

function click_upload(form, question_no)
{
    if (question_no>0 && $('LoadFileQuestion'))
        Element.show('LoadFileQuestion');
}

/**
 * Замена html символов их эквивалентами.
 */

function htmlspecialchars(str)
{
    return str.escapeHTML().replace(/\"/g, "&quot;").replace(/\'/g, "&#039;");
}

/* Функция копирования текста в буфер. Только IE */

function CopyToClipBoard(TextToCopy)
{
    var cliparea = document.getElementById('holdtext');
    cliparea.innerText = TextToCopy;
    Copied = cliparea.createTextRange();
    Copied.execCommand("Copy");
}

function CopyById(ElementId)
{
    var element = document.getElementById(ElementId);
    CopyToClipBoard(element.value);
}

function CreateCopyButton(btnName, copyId)
{
    if (is_ie)
    {
        document.write('<input type="image" src="' + image_path + '/copy.gif" alt="'+btnName+'" onclick="CopyById(\''+copyId+'\');">');
        $(copyId).setStyle({width: '320px'});
    }
}

/* Страница тега */

function setElSel(el)
{
    return el.removeClassName('NoSel').addClassName('Sel');
}

function setElNoSel(el)
{
    return el.removeClassName('Sel').addClassName('NoSel');
}

/*
 * Выделение всех тегов серыми
 */
function select_tags()
{
    $('selectTags').select('span').each(function(el){
        setElNoSel(el);
    })
}

/*
 * Выделение выбранных тегов зеленым
 */

function select_tags_over(sel_el)
{
    var is_sel = true;
    $('selectTags').select('span').each(function(el){
        if (is_sel)
            setElSel(el);
        else
            setElNoSel(el);
        if (el == sel_el)
            is_sel = false;
    })
}
/*
 * Проверка строки тегов на валидность
 */
function check_tags(tag)
{
    var tags = $(tag).value
        .replace(/([^\w\u0400-\u04FF\u0500-\u052F\u2DE0-\u2DFF\uA640-\uA69F\u0590-\u05FF\uFB1D-\uFB40\-\&\'\` ]+)/ig, '')
        .replace(/[\s,\.:\!\?\/\\\|]+/g, ' ');

    tag.value = tags;
    var err_tag = [];
    tags.split(' ').each(function(el){
        if (el.length < 3 || el.length > 25)
            err_tag.push(el);
    });
    return err_tag.length ? err_tag.join('\', \'') : true;
}

function check_copyright_kind_text()
{
    for (i=0; i<const_kind_string.length; i++)
    {
        if ($('copyright').checked && const_kind_string[i] == 'text' && $('copyright_kind_'+i).checked)
        {
            num = $('copyright_kind_text').value.strip().length;
            if (num < 1 || num>80)
                return false;
        }
    }

    return true;
}

function uploadViewVideoLinks(id, text)
{
    Element.update(id, text);
}

function uploadTextareaVideoLinks(id, text)
{
    if ($(id))
        $(id).value = text;
}

/*
 * Функции для обновления страницы
 */
var _refr  = null;

function ReloadPage(timeout)
{
    _refr = setTimeout("reload_page();", timeout*1000);
}

function reload_page()
{
        document.location.reload();
        clearTimeout(_refr);
}

/**
 * Функция для обновления картинки
 */
function UpdateImage(image_id, image_src)
{
    $(image_id).src = image_src == '' ? $(image_id).src : image_src;
}
// запуск аяксового реквеста Ajax.Request
function runAjaxR(url, params)
{
    return new Ajax.Request(
        url,
        {
            method: 'post',
            asynchronous: true,
            parameters: params,
            evalScripts:true
        }
    );
}
// запуск аяксового апдейтера для видео
function runAjaxU_V(cont, url, params, method)
{
    new Ajax.VideoUpdater(cont, url,
        {
            method: method ? method : 'get',
            asynchronous: true,
            parameters: params,
            evalScripts:true
    });
}

/**
 * Удаление друга
 */
function delete_friend(user_id)
{
    runAjaxR("/profile/ajax/delete/friend/", {id: user_id});
}

/**
 * Добавление друга через форму
 */
function add_friend(pars)
{
    runAjaxR("/profile/ajax/add/friend/by/nick/", pars);
}

/**
 * Добавление друга
 */
function subscr_friend(id)
{
    runAjaxR("/profile/ajax/add/friend/", {id: id});
}

/**
 * смена видимости друга через форму
 */
function visible_friend(id, visible)
{
    runAjaxR("/profile/ajax/visible/friend/", {id: id, visible: visible});
}

function friend_update()
{
    slider_ajax_friend();
}
/**
 * Слайдер на аяксе
 */
/*function slider_ajax(block_id, act_url, pars)
{
    new Ajax.Updater(block_id, act_url,
                {
                    method: 'get',
                    parameters: pars
                });

}*/

/**
 * Смена доступа видео при редактировании
 */
function changeAccess(el)
{
    var display = '';
    var frm = el.form;
    if (el.value == 0)
    {
        frm['password'].value = '';
        frm['confirm_password'].value = '';
        display = 'none';
    }

    $('change_pass_form_div').style.display = display;
}
/**
 * Смена статуса продажи видео
 */
function changeSellVideo(el)
{
    if ($(el).checked)
        $('change_sell_form_div').show();
    else
    {
        $('price_video').value = '';
        $('change_sell_form_div').hide();
    }
}
/**
 * Показ сообщения о восстановлении пароля
 */
function view_reset_help(id)
{
    if (!id)
        id = 'reset_help'
    $(id).setStyle({
        left: 55 + 'px',
        top: 25 + 'px'
    });
    $(id).show();
}

/**
 * Функция для создания всплывающего окна
 */

function openMessageDialog(user, msg_id)
{
    // при открытии страницы с сообщениями, убыстряется процесс проверки новых сообщений у юзера в основном окне
    ajax_packet.editAjaxRequest(
        'mes_n_video',
        'profile/ajax/update/count/mes_n_video/',
        {},
        15000,
        reload_block_new_mes_register_callback
    );

    var params = "width=" + 520 + ", height=" +  600 + ",menubar=no,location=no,resizable=no,scrollbars=no,status=no,titlebar=no";
    myDate = new Date();
    pmWin = window.open('/user/'+user+'/send/message/' + (msg_id != null ? '?msg_id=' + msg_id : ''), 'pmWin_'+myDate.getTime(), params);
    pmWin.focus();
}

function acceptInvite(id)
{
    new Ajax.Request("/profile/ajax/invite/accept/",
        {
            method: 'get',
            asynchronous: true,
            parameters: 'id=' + escape(id),
            evalScripts: true,
            onSuccess: function() {
                $('buttons_'+id).hide();
            }
        });
}

function declineInvite(id)
{
    new Ajax.Request("/profile/ajax/invite/decline/",
        {
            method: 'get',
            asynchronous: true,
            parameters: 'id=' + escape(id),
            evalScripts: true,
            onSuccess: function() {
                $('buttons_'+id).hide();
            }
        });
}

// Получение cookie
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

// Сохранение cookie
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function FormListener(k)
{
    if (k)
    {
        ctrl=k.ctrlKey;
        k=k.which;
    }
    else
    {
        k=event.keyCode;
        ctrl=event.ctrlKey;
    }

    if ((k==13 && ctrl) || (k==10))
        if (private_message_submit(document.forms['private_message']))
            document.forms['private_message'].submit();

    document.forms['private_message']['text'].focus();
}

function NewMessagesIcon(play)
{
    var obj = $('profile_messages_ico');

    if (obj)
        if (play)
            obj.removeClassName('LInbox').addClassName('LInboxNew');
        else
            obj.removeClassName('LInboxNew').addClassName('LInbox');
}

function AjaxAddToBlackList(folder)
{
    new Ajax.Updater('black_list', '/profile/ajax/change/folder/',
                        {
                            method: 'post',
                            parameters: 'user_id[]=' + global_user_id +'&contacts_' + folder + '=1',
                            asynchronous:true,
                            evalScripts:true
                        });
}

function UpdateBlackListFlag(text)
{
    var div = document.getElementById('black_list_flag');
    if (div)
    {
        div.innerHTML = text;
    }
}

function contactsAction(action_field)
{
    $(action_field).value = 1;
    $('msg_form').submit();
}

function ajaxUpdateCount()
{
    var countInterval = setInterval(updateCount, 10000);
    updateAjaxCount();
}

function global_counter_callback(ret)
{
    ajaxUpdateSuccess(ret.total_videos, ret.total_broadcast, ret.total_broadcast_view, ret.total_onliners);
}

function updateAjaxCount()
{
    ajax_packet.registerAjaxRequest(
        'global_counter',
        'core/ajax/global/counter/',
        {},
        300000,
        global_counter_callback
    );
}

function ajaxUpdateSuccess(v_total, br_total, br_view, u_online)
{
    $("count_videos").update(v_total);
    $("count_broadcast").update(br_total);
    $("count_broadcast_view").update(br_view);
    $("count_onliners").update(u_online);

    updateCounterLang( );
}

function updateCount()
{
    randomIncrement("count_broadcast", 10);
    randomIncrement("count_broadcast_view", 10);
    randomIncrement("count_onliners", 10);

    updateCounterLang( );
}

function updateCounterLang( )
{
    $("count_onliners_lang").update(numDecline($("count_onliners").innerHTML, lang_count_onliners, lang));
    $("count_broadcast_lang").update(numDecline($("count_broadcast").innerHTML, lang_count_broadcast, lang));
    $("count_broadcast_view_lang").update(numDecline($("count_broadcast_view").innerHTML, lang_count_broadcast_view, lang));
}

function randomIncrement(id, max)
{
    var lastValue = Number($(id).innerHTML);
    var newValue = Math.round(lastValue + max * (1 - 2 * Math.random()));
    $(id).innerHTML = newValue > 0 ? newValue : 1;
}


function numDecline(num, langs, lang)
{
    num = Number(num);
    if (lang != 'rus') {
        if (num == 1)
            return langs.singular;
        else
            return langs.plural;
    }
    else {
        if(num > 10 && Math.floor((num % 100) / 10) == 1)
            return langs.plural;

        result = '';
        var numForm = num % 10;
        if (numForm == 1)
            return langs.nominative;

        if (numForm >= 2 && numForm <= 4)
            return langs.singular;

        if (numForm >= 5 && numForm <= 9 || numForm == 0)
            return langs.plural;
    }
}

function checkEmailList(list, regexp)
{
    var emails = list.value.split(',');
    var err = [];
    var regexp = new RegExp(regexp, 'i');
    emails.each(function(el){
        el = el.trim();
        if (!regexp.test(el))
            err.push(el);
    });
    if (err.length) return err.join(', ');
    else return true;
}

/**
 * Функция для создания окна для отсылки мыла другу
 */

function openFriendMailPopupBroadcast(sid)
{
    openFriendMailPopup(sid, 'broadcast');

}

function openFriendMailPopupVideo(sid)
{
    openFriendMailPopup(sid, 'video');

}

function openFriendMailPopup(sid, type)
{
    var params = "width=" + 350 + ", height=" +  400 + ",menubar=no,location=no,resizable=no,scrollbars=no,status=no,titlebar=no";

    mailWin = window.open('/' + type + '/send/friend/mail/videolink/?id=' + sid, 'mailWin_' + sid, params);
    mailWin.focus();
}

function estimateAdvertise(block_id, video_id)
{
    var min_price_user = 100 * Number($('min_price').value);
    new Ajax.Updater(block_id, '/video/advertise/ajax/count/estimate/',
                        {
                            method: 'get',
                            parameters: 'minprice=' + escape(min_price_user) + "&id=" + video_id,
                            asynchronous:true
                        });
}

function checkPMKey(el)
{
    if (need_captcha)
    {
        var val = el.value
        if (val == '')
        {
            alert(lang_need_captcha);
            return false;
        }
        else if (val.length != 5)
        {
            alert(lang_need_captcha_length);
            return false;
        }
    }
    return true;
}

function sendCaptcha()
{
    if (checkPMKey($('captcha_key')))
    {
        new Ajax.Request("/profile/ajax/send/message/captcha/",
            {
                method: 'get',
                asynchronous: true,
                parameters: 'captcha=' + escape($('captcha_key').value),
                evalScripts:true
            });
    }
}

function disabledAdvertise(id)
{
    new Ajax.Updater("disabled_adv_block", "/video/advertise/ajax/disabled/",
        {
            method: 'get',
            asynchronous: true,
            parameters: 'id=' + escape(id),
            evalScripts:true
        });
}

function enable_advertise(id, fl)
{
    new Ajax.Updater("enable_adv_img_" + id, "/video/advertise/ajax/enabled/",
        {
            method: 'get',
            asynchronous: true,
            parameters: 'id=' + escape(id) + '&enabled=' + escape(fl),
            evalScripts:true
        });
}

/* показывает/скрывает элемент и возвращает виден ли он */

function showElement(id)
{
    if ($(id).style.display == 'none')
    {
        Element.show(id);
        return true;
    }

    Element.hide(id);
    return false;
}

/* показать/скрыть настройки копирайта */

function showCopyright()
{
    is_shown = showElement($('tr_copyright_kind'));
    showElement($('copyrightFlashText'));
    showElement('flashCopyright');

    for (i=0; i<=const_kind_string.length-1; i++)
    {
        if ($('copyright_kind_'+i).checked)
        {
            num = $('copyright_kind_'+i).value;
            field_kind = 'tr_copyright_kind_' + num;
            showElement($(field_kind));

            if (const_kind_string[i] == 'image' && const_kind_string[const_kind] == 'image')
                showElement($('tr_copyright_image_preview'));
        }
    }

    if (is_shown)
        drawCopyFlash(swfCopyFlash, num, const_image_url, $('copyright_kind_text').value);
    else
        $('copyFlash').hide();
}

/* поменять отображаемые свойства копирайта (текст/картинка) */

function changeKindCopyright()
{
    for (i=0; i<=const_kind_string.length-1; i++)
    {
        num = $('copyright_kind_'+i).value;
        if (showElement('tr_copyright_kind_' + num))
        {
            try
            {
                if (const_kind_string[num] == 'text')
                    sendCopyrightText($('copyright_kind_text').value);
                else
                    $('copyFlash').showImg(const_image_url);
            }
            catch (e)
            {
                try
                {
                    console.error('Ошибка в обращении к copyrightFlash.');
                }
                catch (e)
                {}
            }
        }
    }

    if (const_kind_string[const_kind] == 'image')
    {
        showElement($('tr_copyright_image_preview'));
    }
}

function drawCopyFlash(swf, kind, image_url, text)
{
    var so = new SWFObject(swf, "copyFlash", "150", "124", "8", "#ffffff");
    so.addParam('allowFullScreen', false);
    so.addParam('allowScriptAccess', 'always');

    if (const_kind_string[kind] == 'image')
        so.addVariable('logoImg', image_url);
    else
    {
        if (!text) text = const_copyright_text_null;
        so.addVariable('logoText', htmlspecialchars(text));
    }

    so.write("flashCopyright");
}

/* Money Up */

function money_up_show_descript(checkbox, id)
{
    if (checkbox.checked == true)
    {
        Element.show(id);
    }
    else
    {
        Element.hide(id);
    }
}

function main_contacts(section, login, el)
{
    var is_open = $('contacts_content_' + section).readAttribute('is_open');
    var section_el = $('contacts_content_' + section);
    var slide_el = $('contacts_content_slide_' + section);
    if(is_open != "1")
    {
        // меню не открыто. будем открывать
        var load_complete = section_el.readAttribute('load_complete');

        if(load_complete != "1")
        {
            // контент не подгружен. загрузим
            $(el).up('.NoSel').removeClassName('NoSel').addClassName('Loading');
            new Ajax.Updater(section_el, '/profile/ajax/contacts/menu/item/',
                {
                    method: 'get',
                    asynchronous: true,
                    parameters: 'section=' + escape(section) + (login ? '&login=' + escape(login) : '') + '&page=1',
                    evalScripts:true,
                    onSuccess: function() {
                        section_el.writeAttribute('load_complete', "1");
                        $(el).up('.Loading').removeClassName('Loading').addClassName('Sel');
                        section_el.writeAttribute('page', '1');
                    }
            });
        }
        else
            // контент уже загружен. просто откроем
            main_contacts_blind(section, true, el);
    }
    else
        // меню открыто. Закроем.
        main_contacts_blind(section, false, el);
}

function main_contacts_blind(section, open, el)
{
    var slide_el = $('contacts_content_slide_' + section);
    var section_el = $('contacts_content_' + section);
    var is_open = section_el.readAttribute('is_open');
    var slide_process = section_el.readAttribute('slide_process');
    if (slide_process == "1")
        return;

    if (open == true && is_open != "1")
    {
        section_el.writeAttribute('slide_process', '1');
        new Effect.BlindDown(slide_el, {
            beforeStart: function( ) {
                if (el)
                    setElSel($(el).up('.NoSel'));
            },
            afterFinish: function( ) {
                section_el.writeAttribute('is_open', "1");
                section_el.writeAttribute('slide_process', '0');
                slide_el.style.overflow = 'auto';
            }
        });
    }
    else if (open == false && is_open == 1)
    {
        section_el.writeAttribute('slide_process', '1');
        new Effect.BlindUp(slide_el, {
            beforeStart: function( ) {
                if (el)
                    setElNoSel($(el).up('.Sel'));
            },
            afterFinish: function( ) {
                section_el.writeAttribute('is_open', "0");
                section_el.writeAttribute('slide_process', '0');
            }
        });
    }
}

function main_contacts_load_scroll(section, login, scroll_el)
{
    var section_el = $('contacts_content_' + section);
    // уже грузим
    if (section_el.readAttribute('loaded') == '1')
        return;
    section_el.writeAttribute('loaded', '1');
    var page = section_el.readAttribute('page');
    var scroll_top = scroll_el.scrollTop;
    page ++;
    // загрузка след. страницы
    new Ajax.Updater(section_el, '/profile/ajax/contacts/menu/item/',
        {
            method: 'get',
            asynchronous: true,
            parameters: 'section=' + escape(section) + (login ? '&login=' + escape(login) : '') + ('&page=' + escape(page)),
            evalScripts:true,
            onSuccess: function() {
                section_el.writeAttribute('page', page);
                section_el.writeAttribute('loaded', '0');
            },
            insertion: Insertion.Bottom
    });
}

function main_broadcast()
{
    runAjaxU_V('main_video_content', '/broadcast/ajax/main/video/', {}, 'get');
}

function broadcast_delete(id)
{
    runAjaxU_V('main_video_content', '/broadcast/ajax/delete/', {id: id}, 'get');
}

function favorite_delete(videoid)
{
    runAjaxU_V('main_video_content', '/video/ajax/favorite/delete/', {videoid: videoid}, 'get');
}

function external_delete(videoid)
{
    runAjaxU_V('main_video_content', '/video/import/ajax/external/delete/', {videoid: videoid}, 'get');
}

function user_broadcast(login)
{
    runAjaxU_V('main_video_content', '/broadcast/ajax/user/video/', {login: escape(login)}, 'get');
}

function user_favorite(login)
{
    runAjaxU_V('main_video_content', '/video/ajax/user/favorite/', {login: escape(login)}, 'get');
}

function user_community_video(login)
{
    runAjaxU_V('main_video_content', '/community/ajax/user/video/list/', {login: escape(login)}, 'get');
}

function main_videolist()
{
    runAjaxU_V('main_video_content', '/video/folder/ajax/main/folders/list/', {}, 'get');
}

function main_video_favorite()
{
    runAjaxU_V('main_video_content', '/video/ajax/main/favorite/', {}, 'get');
}

function main_video_sort(type)
{
    runAjaxU_V('main_video_content', '/video/ajax/main/video/', {sort: escape(type)}, 'get');
}

function user_video_sort(type, login)
{
    runAjaxU_V('main_video_content', '/video/ajax/user/video/', {sort: escape(type), login: escape(login)}, 'get');
}

function view_video_sort(type, video)
{
    runAjaxU_V('main_video_content', '/video/ajax/video/', {sort: escape(type), videoid: escape(video)}, 'get');
}

function view_import_sort(type, video)
{
    runAjaxU_V('main_video_content', '/video/ajax/video/import/', {sort: escape(type), videoid: escape(video)}, 'get');
}

function lastUserViewVideo(el, video_id)
{
    pp_control.runPopup(el, 'main_video_user_view', {
        showTimeout: 0,
        noMouseEvent: true,
        onFirstShow: function() {
            new Ajax.VideoUpdater("main_video_user_view", "/video/ajax/last/user/view/video/",
                {
                    method: 'get',
                    asynchronous: true,
                    parameters: 'id=' + escape(video_id),
                    evalScripts:true
            });
        }
    });
}

function downloadOriginalFormat(obj, id)
{
    pp_control.runPopup(obj, id, {
        showTimeout: 0,
        onFirstShow: function() {
            new Ajax.Updater(id, "/video/ajax/download/original/format/",
                {
                    method: 'get',
                    asynchronous: true,
                    evalScripts:true
            });
        }
    });
}

function buyOriginalFormat(obj, id, video_id)
{
    pp_control.runPopup(obj, id, {
        showTimeout: 0,
        onFirstShow: function() {
            new Ajax.Updater(id, "/video/ajax/buy/original/format/",
                {
                    method: 'get',
                    asynchronous: true,
                    parameters: 'id=' + escape(video_id),
                    evalScripts:true
            });
        }
    });
}

function buyOriginalLink(id_link, video_id)
{
    new Ajax.Updater(id_link, "/video/ajax/buy/original/link/",
        {
            method: 'get',
            asynchronous: true,
            parameters: 'id=' + escape(video_id),
            evalScripts:true
    });

    pp_control.hidePopup('main_video_download_original');
}

// переключатель ссылок на видео или вещание
// button   - id кнопки
// color_on - true, если нужно переключать цвет в ссылке

function switch_links(button, color_on)
{
    $('videolinkstext').value=videoLinks[button];
    $('videolinkstext').focus();
    $('videolinkstext').select();

    var item = '';
    for (item in videoLinks)
    {
        if ($('videoLink_'+item))
        {
            if (button == item)
            {
                $('videoLink_'+item).removeClassName('NoSel').addClassName('Sel');
                $('videoLink_'+item).down('.PCenter').removeClassName('NoSel').addClassName('Sel');
            }
            else
            {
                $('videoLink_'+item).removeClassName('Sel').addClassName('NoSel');
                $('videoLink_'+item).down('.PCenter').removeClassName('Sel').addClassName('NoSel');
            }
        }
    }

    if (color_on)
    {
        if (button != 'text')
            popup_box_skin(1);
        else
            popup_box_skin(0);
    }
}


function popup_box_skin(show)
{
    if (!show)
        $('video_player_change_box').hide()
    else
    {
        drawColorSkinPreview();
        $('video_player_change_box').show();
    }

};

function popup_choose_skin()
{
    if ($('video_player_links').visible())
    {
        $('video_player_links').hide();
        $('choose_link_player').show();
    }
    else
    {
        drawColorSkinPreview();
        $('video_player_links').show();
        $('choose_link_player').hide();
    }

};

function addQuickListButton(id)
{
    videoListActionButton("quicklist_add_button_" + id, 'id=' + escape(id), "/video/folder/ajax/quick/list/button/add/");
}

function delQuickListButton(id)
{
    videoListActionButton("quicklist_add_button_" + id, 'id=' + escape(id), "/video/folder/ajax/quick/list/button/del/");
}

function addPlayListAction(id, el)
{

    if ($('video_menu_btn_content').visible( ))
    {
        goPlayListAction(el, true);
        return;
    }
    $('video_menu_btn_content').down('div').update('Loading...');

    new Ajax.Updater($('video_menu_btn_content').down('div'), '/video/folder/ajax/load/add/to/playlist/block/',
        {
            method: 'post',
            asynchronous: true,
            parameters: {id: id},
            evalScripts:true,
            onSuccess: function( )
            {
               goPlayListAction(el, false);
            }
        });
}

function goPlayListAction(el, hide)
{
    new Effect.toggle('video_menu_btn_content', 'slide', {
        duration: 0.5,
        beforeStart: function() {
            if (hide)
                el.removeClassName('Sel').addClassName('NoSel');
            else
                el.removeClassName('NoSel').addClassName('Sel');
        }
    });
}

function sendPlayListAddVideo(vid)
{
    quicklist_control.saveToPlayList($('select_playlist'), $('play_list_save_name'), vid, $('video_menu_btn_content').down('div'));
}


function addPlayListActionEnd(el)
{
    new Effect.toggle('video_menu_btn_content', 'slide', {
        delay: 1,
        duration: 0.5,
        beforeFinish: function() {
            el.down('.Sel').removeClassName('Sel').addClassName('NoSel');
        }
    });

}

function addFavorite(id)
{
    videoListActionButton("favorite_add_" + id, 'id=' + escape(id), "/video/ajax/favorite/add/");
}

function delFavorite(id)
{
    videoListActionButton("favorite_add_" + id, 'id=' + escape(id), "/video/ajax/favorite/del/");
}

function videoListActionButton(block_id, param, url)
{
    new Ajax.VideoUpdater(block_id, url,
        {
            method: 'get',
            asynchronous: true,
            parameters: param,
            evalScripts:true
        });
}

function loadingPopup(popup_id, block_id, hide)
{
    if (hide == 1)
    {
        Element.hide(popup_id);
        return;
    }
    var el = $(block_id);
    var pos = el.cumulativeOffset()
    var x = pos[0];
    var y = pos[1];
    var w = Element.getWidth(block_id);
    var h = Element.getHeight(block_id);

    var pw = Element.getWidth(popup_id);
    var ph = Element.getHeight(popup_id);

    $(popup_id).setStyle({'top' : (y + h/2 - ph/2) + "px", 'left': (x + w/2 - pw/2) + "px"});

    Element.show(popup_id);
}

function output_can_min()
{
    temp = (Math.round(start*100000)/100000);
    if (temp >= max_upload_traffic)
    {
        start = max_upload_traffic;
        window.clearInterval(timer);
    }
    else
        start += increase/60;

    $('can_load_min_small').innerHTML = temp;
}

function openFullInfo()
{
    var ids = ["video_info_data", "video_info_rating", "video_info_views", "video_info_links"];
    for (var i=0; i<ids.length; i++)
    {
        Element.show(ids[i]);
    }
}

function changeAvatarType(type, return_url)
{
    var Avatars = new Array();
    Avatars['url']      = $('tr_avatar_url');
    Avatars['kards']    = $('tr_avatar_url');
    Avatars['local']    = $('tr_avatar_local');

    ['tr_avatar_url', 'tr_avatar_local'].each(Element.hide);
    if (type != 'default' ) $(Avatars[type]).show();

    if (type == 'kards')
    {
        window.open('http://avatar.kards.ru/partner/?return_url='+return_url,'Аватары','toolbar=no,resizable=yes,scrollbars=yes,width=820,height=670');
    }
}

function popup_services_info(obj, id)
{
    pp_control.runPopup(
        obj,
        id,
        {showTimeout:0}
    );
}

function openUserInfo(user)
{
    var params = "width=" + 1100 + ", height=" +  600 + ",menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes,titlebar=yes";
    var win = window.open('/user/'+user+'/', 'wuser_'+user, params);
    win.focus();
}



function reload_block_new_mes_register_callback(cnt)
{
    // работаем с новыми личными сообщениями
    if (cnt["PrivateMessages"] <= 0)
    {
        if (cnt["SystemPrivateMessages"] <= 0)
        {
            NewMessagesIcon(0);
            $('count_mes_visibility').hide();
        }
        else
        {
            NewMessagesIcon(1);
            $('count_mes').update(system_private_message_confirm);
            $('count_mes_visibility').show();
        }
    }
    else
    {
        if (count_messages != cnt['PrivateMessages'])
        {
            $('count_mes').update('(' + cnt['PrivateMessages'] + ')');
            $('count_mes_visibility').show();
            NewMessagesIcon(1);
        }
    }

    count_messages = cnt['PrivateMessages'];

    //работаем с новыми видео друзей

    if (cnt['FriendVideos'] <= 0)
    {
        $('count_fr_video_visibility').hide();
    }
    else
    {
        if (count_friends_video != cnt['FriendVideos'])
        {
            $('count_fr_video').update('(' + cnt['FriendVideos'] + ')');
            $('count_fr_video_visibility').show();
        }
    }

    count_friends_video = cnt['FriendVideos'];

    //работаем с новыми видео сообществ

    if (cnt['CommunityVideos'] <= 0)
    {
        $('count_community_subscr_visibility').hide();
    }
    else
    {
        if (count_friends_video != cnt['CommunityVideos'])
        {
            $('count_community_subscr').update('(' + cnt['CommunityVideos'] + ')');
            $('count_community_subscr_visibility').show();
        }
    }

    count_friends_video = cnt['CommunityVideos'];
}

function reload_block_new_mes_register()
{
    ajax_packet.registerAjaxRequest(
        'mes_n_video',
        'profile/ajax/update/count/mes_n_video/',
        {},
        90000,
        reload_block_new_mes_register_callback
    );
}

function EditQuestion(id)
{
    $('category_'+id).style.display = 'block';
    $('answers_'+id).style.display = 'none';
    $('PollScaleShow_'+id).style.display = 'none';
}

function confirmRefillBalance(service_id, message_id)
{
    $(service_id).style.display = 'none';
    $(message_id).style.display = 'block';
}

function addServicesButton(video_id)
{
    $('AddServicesButtonTD_'+video_id).toggleClassName("AddServicesButtonOn")
        .toggleClassName("AddServicesButtonOff");
}

function confirmButton(id)
{
    $(id).toggleClassName('ConfirmButtonOff')
        .toggleClassName('ConfirmButtonOn');
}

function addPlayListButton(video_id)
{
    $('AddPlayListButton').toggleClassName('AddPlayListButtonOn')
        .toggleClassName('AddPlayListButtonOff');
}

function community_action_video(comm_id, video_id, action, onSuccess)
{
    var act_id = 'comm_action_' + video_id;
    var block_act_id = 'comm_action_td_' + video_id;
    var action_url = action == 1 ? "/community/ajax/add/video/" : "/community/ajax/del/video/";
    $(act_id).innerHTML = '...';
    new Ajax.VideoUpdater(block_act_id, action_url, {
            method: 'get',
            asynchronous: true,
            parameters: 'community_id=' + escape(comm_id) + '&video_id=' + escape(video_id) ,
            evalScripts: true,
            onSuccess: (onSuccess ? onSuccess : null)
    });
}

function contest_action_video(contest_id, video_id, action)
{
    var act_id = 'contest_action_' + video_id;
    var block_act_id = 'contest_action_td_' + video_id;
    var action_url = action == 1 ? "/contest/ajax/add/video/" : "/contest/ajax/del/video/";
    $(act_id).innerHTML = '...';
    new Ajax.VideoUpdater(block_act_id, action_url, {
            method: 'get',
            asynchronous: true,
            parameters: 'contest_id=' + escape(contest_id) + '&video_id=' + escape(video_id) ,
            evalScripts: true
    });
}


function changeCountVideoCommunity(count) {
    $('count_video_left').update(count);
    $('count_video_left_link').update(count);
}

function community_join(comm_title, onSuccess)
{
    new Ajax.Request("/community/ajax/join/", {
            method: 'get',
            asynchronous: true,
            parameters: 'name=' + escape(comm_title),
            evalScripts: true,
            onSuccess: (onSuccess ? onSuccess : null)
    });
}

function community_video_post(section, comm)
{
    if (section == 'new')
    {
        window.location = '/community/post/video/new/?community=' + escape(comm);
        return;
    }
    loadingPopup("community_post_video_popup", "community_content", 0);

    new Ajax.VideoUpdater("community_content", "/community/ajax/post/video/menu/change/", {
            method: 'post',
            asynchronous: true,
            parameters: 'section=' + escape(section) + '&community=' + escape(comm),
            evalScripts:true,
            onSuccess: function() {
                loadingPopup("community_post_video_popup", "community_content", 1);
            }
    });
}

function contest_video_post(section, id)
{
    loadingPopup("contest_post_video_popup", "contest_content", 0);

    new Ajax.VideoUpdater("contest_content", "/contest/ajax/post/video/menu/change/", {
            method: 'post',
            asynchronous: true,
            parameters: 'section=' + escape(section) + '&contest=' + escape(id),
            evalScripts:true,
            onSuccess: function() {
                loadingPopup("contest_post_video_popup", "contest_content", 1);
            }
    });
}

function view_sms_help(el, fl)
{
    if (fl == 0)
    {
        Element.hide('sms_operators_info');
        return;
    }
    clonePosition($('sms_operators_info'), el, {
        offsetLeft: -230,
        offsetTop: 15
    });

    Element.show('sms_operators_info');
}

function view_resources_help(el, fl)
{
    if (fl == 0)
    {
        Element.hide('videoimport_resources_hint');
        return;
    }
    clonePosition($('videoimport_resources_hint'), $(el), {
        offsetLeft: -230,
        offsetTop: 15
    });

    Element.show('videoimport_resources_hint');
}

function checkIsMy(){
    return true;
}

/**
 * Скрытие - показ tr с элементами формы name_els
 */

function viewFieldTr(ch_el, name_els, fl)
{
    name_els.each(function(s){
        $(s).setStyle(
            {display : (fl ? '' : 'none')}
        );
    });
}

/*
 * Поддержка макроса VideoMacro
 */

function toggle_wikiVP(video_id, proxy, parameters)
{
    if ($('wikiVP_player_'+video_id).visible())
    {
        $('wikiVP_player_'+video_id).hide();
        $('wikiVP_frame_'+video_id).show();
    }
    else
    {
        if (!$('wikiVP_player_'+video_id).hasClassName('ajaxLoaded'))
        {
            if (!parameters)
                parameters  = {};
            parameters.id = video_id;
            new Ajax.Updater('wikiVP_player_'+video_id, (proxy ? proxy : '/video/player/wiki/ajax/load'), { parameters : parameters,
                    onComplete : function(req, json) {  !$('wikiVP_player_'+video_id).addClassName('ajaxLoaded'); }, evalScripts : true  })
        }

        $('wikiVP_frame_'+video_id).hide();
        $('wikiVP_player_'+video_id).show();
    }
    return false;
}

/*
 * Поддержка макроса BroadcastMacro
 */

function toggle_wikiBP(broadcast_id)
{
    if ($('wikiBP_player_'+broadcast_id).visible())
    {
        $('wikiBP_player_'+broadcast_id).hide();
        $('wikiBP_frame_'+broadcast_id).show();
    }
    else
    {
        if (!$('wikiBP_player_'+broadcast_id).hasClassName('ajaxLoaded'))
            new Ajax.Updater('wikiBP_player_'+broadcast_id, '/broadcast/player/wiki/ajax/load', { parameters : { id : broadcast_id },
                    onComplete : function(req, json) {  !$('wikiBP_player_'+broadcast_id).addClassName('ajaxLoaded'); }, evalScripts : true  })

        $('wikiBP_frame_'+broadcast_id).hide();
        $('wikiBP_player_'+broadcast_id).show();
    }
    return false;
}

/*
 * Выделение группы checkbox
 */

function selectAllCheckBox(item, form, mask)
{
    var arr = document.getElementsByName(mask);
    var check = item.checked ? true : false;

    for (var i=0; i<arr.length; i++)
    {
        arr[i].checked = check;
    }
}



/**
 * Событие при посте пароля в вещании
 */
function broadcastPassPost(id, pass)
{
    broadcast_control.passSend(pass);
    loadChat(id, pass);
}

// Кроссбраузерная привязка события
function addEvent(obj, evType, fn, useCapture)
{
    if (obj.addEventListener)
    {
        obj.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (obj.attachEvent)
    {
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    }
    return false;
}

function setVideoPasswordClick()
{
    new Effect.toggle('pass_form_div');
}

function checkCanSetVideoPassword(video_id)
{
    if ($('pass_form_div').visible())
    {
        setVideoPasswordClick();
        return;
    }
    var param = {
        id: escape(video_id)
    };

    new Ajax.Request(
        '/video/ajax/check/can/set/video/password/', {
            method: 'post',
            asynchronous: true,
            parameters: param,
            evalScripts:true
        }
    );
}

function ignoreUser(id, moderator, link)
{
    var msg = moderator ? str_moder_ignore_confirm : str_user_ignore_confirm;
    if (confirm(msg))
    {
        ignoreComment = link ? $(link).up('div.ChatLine').down('span.TextRow').innerHTML : '';
        new Ajax.Request(
            '/profile/ajax/user/ignore/', {
                method: 'post',
                parameters: { user: id, text: ignoreComment }
            }
        );
        if (!moderator)
            alert(str_user_ignored);
    }
}

function rgb2hex(rgb) {
  var i,h='#', x='0123456789ABCDEF';
    for (i=1; i <= 3; i++){
      n  = parseInt(rgb[i]);
      h += x.charAt(n>>4) + x.charAt(n&15);
    }
  return h;
}

function loadQuestionForm(block_id, ticket, lang, color_scheme, form_params)
{
    var params = {'ticket': escape(ticket), 'lang' : escape(lang), 'color_scheme' : escape(color_scheme)};
    params = Object.extend(params, form_params);
    new Ajax.Updater(block_id, "/user/iframe/question/form/", {
            method: 'post',
            asynchronous: true,
            parameters: params,
            evalScripts:true
    });
}

function postQuestionForm(form)
{
    drawQuestionForm($(form).serialize(true));
}

function updateUserFriends (user_id) {
    updateShortLongList("user_friends", "/profile/friends/simple/", user_id);
}

function updateUserSubscribers (user_id) {
    updateShortLongList("user_subscribers", "/profile/subscribers/simple/", user_id);
}

function updateUserAssociate (user_id) {
    updateShortLongList("user_associate", "/profile/associate/simple/", user_id);
}

function updateShortLongList (pfx, action, user_id) {
    loadingPopup(pfx + "_popup_loading", pfx+"_list_short", 0);
    $(pfx+"_linkcontainer_more").onclick = function () {return false;}

    new Ajax.Updater(pfx+"_list_long", action+"?uid="+escape(user_id),
        {
            method:         'get',
            asynchronous:   true,
            onSuccess: function(transport){
                loadingPopup(pfx+"_popup_loading", pfx+"_list_short", 1);

                $(pfx+"_list_short").style.display = "none";
                $(pfx+"_linkcontainer_more").style.display = "none";

                $(pfx+"_list_long").style.display = "block";
                $(pfx+"_linkcontainer_less").style.display = "block";

                $(pfx+"_linkcontainer_more").onclick = function () {
                    $(pfx+"_list_short").style.display = "none";
                    $(pfx+"_linkcontainer_more").style.display = "none";
                    $(pfx+"_list_long").style.display = "block";
                    $(pfx+"_linkcontainer_less").style.display = "block";
                }

                $(pfx+"_linkcontainer_less").onclick = function () {
                    $(pfx+"_list_long").style.display = "none";
                    $(pfx+"_linkcontainer_less").style.display = "none";
                    $(pfx+"_list_short").style.display = "block";
                    $(pfx+"_linkcontainer_more").style.display = "block";
                }
        }
    });
}

function changeLicensefee(box, id, value, arr)
{
    $(id).innerHTML = arr[box.options[box.selectedIndex].value];
}

function CommUpdateFunction(text_id, status_id, max_len)
{
    UpdateBarFunction(text_id, status_id, 'PostCommStatusBar', 'PostCommStatus', max_len);
}

function DescUpdateFunction(text_id, status_id, max_len)
{
    UpdateBarFunction(text_id, status_id, 'PostCommStatusBar', 'PostCommStatus', max_len);
}

function UpdateBarFunction(text_id, status_id, main_class, slave_class, max_len)
{
    if (!max_len)
        max_len = 300;

    var text = $(text_id).getValue();
    var percent = Math.ceil(text.length * 100 / max_len);

    if (percent > 100)
        percent = 100;

    var progress = $(status_id);

    if (percent > 90)
        progress.className = main_class + ' ' + slave_class + 'Error';
    else if (percent > 60)
        progress.className = main_class + ' ' + slave_class + 'Warning';
    else
        progress.className = main_class;

    progress.style.width = percent + '%';
}

// вывод ошибки при превышении числа символов в строке ввода
function CommonUpdateLimitFunction(text_id, max_len, error)
{
    if (!max_len)
        max_len = 300;

    var text = $(text_id).getValue();
    if (text.length >= max_len)
        alert(error);
}

function tabmenu_select(name, num, total) {
    if (num != undefined && num != null) {
        setCookie('main_tab', num, 0, '/');
    }
    else {
        num = getCookie('main_tab');
    }

    if (num >= total || num <= 0) {
        num = 0;
    }

    tabmenu_display(name, -1, total);
    tabmenu_display(name, num < 0 || num >= total ? 0 : num, total);
}

function tabmenu_display(name, num, total) {
    var j;

    for (j = 0; j < total; j++) {
        $('tabmenu_'+name+'_title_'+j).className = (num == j ? 'Sel' : '');
        var space = $('tabmenu_'+name+'_space_'+j);
        var content = $('tabmenu_'+name+'_content_'+j);
        num == j ? space.show() : space.hide();
        num == j ? content.show() : content.hide();
    }
}

function makeFriends(login) {
    var params = "width=" + 350 + ", height=" +  400 + ",menubar=no,location=no,resizable=no,scrollbars=no,status=no,titlebar=no";

    mailWin = window.open('/profile/make/friends/?login=' + login, 'mailWin_' + login, params);
    mailWin.focus();

}

// вывод сообщения об ошибке при попытке короновать видео без фрейма
function koth_error_none_frame(redirect){
    alert(str_koth_none_frame);
    if (redirect) document.location.href = redirect;
}

function debug(msg)
{
    $('debug').innerHTML += msg + "<br>";

}

function money_up_switch(video_id, flag)
{
    $('MoneyUpSwitch').hide();
    $('MoneyUpSwitchLoad').show();
    new Ajax.Updater('MoneyUpSwitch', '/video/ajax/money/up/switch/',
                        {
                            method: 'get',
                            parameters: 'id=' + escape(video_id) + '&on=' + escape(flag),
                            onSuccess: function() {
                                $('MoneyUpSwitchLoad').hide();
                                $('MoneyUpSwitch').show();
                            }
                        }
                    );

}

function changeImportBlock(obj)
{
    var sValue = obj.options[obj.selectedIndex].value;

    if (sValue <= 0)
        sValue = 1;

    for(var i=1; i<3; i++)
        if (sValue == i)
            $('importBlock'+i).show();
        else
            $('importBlock'+i).hide();
}

function drawColorSkinPreview()
{
    videoPreview = videoLinks['html'].replace(/width=\"400\"/g, 'width=\"100\"');
    videoPreview = videoPreview.replace(/height=\"330\"/g, 'height=\"82\"');
    $('colorSkinPreview').innerHTML = null;
    $('colorSkinPreview').innerHTML = videoPreview;
}

function changeSkinColorLink(color, title)
{
    skinColor = color;

    str = $('videolinkstext').value;
    $('videolinkstext').value = str.replace(/skin_color.*?\.xml/g, 'skin_color_'+color+'.xml');

    videoLinks['html'] = videoLinks['html'].replace(/skin_color.*?\.xml/g, 'skin_color_'+color+'.xml');
    videoLinks['bb'] = videoLinks['bb'].replace(/skin_color.*?\.xml/g, 'skin_color_'+color+'.xml');
    videoLinks['lj'] = videoLinks['lj'].replace(/skin_color.*?\.xml/g, 'skin_color_'+color+'.xml');

    $('presetColorPlayer').innerHTML = title;

    drawColorSkinPreview();
}

function saveSkinColorLink()
{
    new Ajax.Request("/video/ajax/save/user/skin/color/",
        {
            method: 'get',
            asynchronous: true,
            parameters: 'color=' + escape(skinColor)
        });

    popup_choose_skin();
}

function show_saved_list()
{
    new Ajax.Updater('ShortFolderList', '/video/folder/folders/list/short/',
                        {
                            asynchronous:true,
                            evalScripts:true
                        }
                    );
}

function ajaxClearVideoPassword(video_id, object_kind)
{
    $('passwordLinksText').hide();
    $('passwordClearlink').hide();
    $('passwordClearLoad').show();
    $('pass_form_div').hide();
    action_path = (object_kind == 'video' ? '/video' : '/broadcast') + '/ajax/clear/password/';
    new Ajax.Updater('passwordLinksText', action_path,
                        {
                            method: 'get',
                            parameters: 'id=' + escape(video_id),
                            onSuccess: function() {
                                $('passwordClearLoad').hide();
                                $('passwordLinksText').show();
                            }
                        }
                    );

}

function ajaxMainPeriodicalUpdaterBroadcast( )
{
    new Ajax.PeriodicalUpdater('main_broadcast_ajaxable_block', '/broadcast/ajax/view/top/_/main/',
        {
            method      : 'get'
          , frequency   : 60
          , decay  	    : 1
        }
    );
}

function videoSWFDraw(swf, w, h, file, auto, small, quick_play, noLogo, authorized, skin_xml, color_skin_xml)
{
    var bgcolor = '';

    if ($('hideflashcolor'))
    {
        bgcolor = $('hideflashcolor').getStyle('color');
        var matches = bgcolor.match(/rgb\(([0-9]+),\s*([0-9]+),\s*([0-9]+)\)/)
        if (matches)
            bgcolor = rgb2hex(matches);
    }

    var so = new SWFObject(swf, "video", w, h, "8", bgcolor);
    so.addVariable('file', file);
    so.addVariable('autoStart', auto);
    if (small)
        so.addVariable('is_small', "true");
    if (quick_play)
        so.addVariable('quicklist_play', "true");
    so.addParam('allowFullScreen', true);
    so.addParam('allowScriptAccess', 'always');
    so.addParam('wmode', 'window');
    if (noLogo)
        so.addVariable('noLogo', '1');
    if (authorized)
        so.addVariable('auth', '1');
    else
        so.addVariable('auth', '0');

    so.addVariable('str_lang', lang);
    so.addVariable('xmldatasource', skin_xml);
    so.addVariable('xmlsource', color_skin_xml);

    return so;
}

function uploadError(err) {

    if (typeof err == 'object')
    {
        var errors = '';
	    for (var i in err)
	       errors = errors + "Ошибка: " + err[i] + "\n";
	    alert(errors);
	}
    else
    {
        if (typeof err == 'string' && err)
            showAjaxError(err);
    }
}

function uploadBegin() {

    $('tr_upload_title_input',
      'tr_upload_rubric_input',
      'tr_upload_tags_input',
      'tr_upload_tags_description',
      'tr_upload_video_description',
      'tr_upload_file_description',
      'tr_upload_month_description',
      'tr_upload_desc_input',
      'tr_upload_attention_text',
      'tr_upload_image_submit'
      ).invoke('hide');

    if ($('tr_upload_random_news'))
        $('tr_upload_random_news').hide();
    $("upload_file_flash").setStyle({height: 88 + 'px'});
    if ($('flashcontent_test'))
    {
        $('flashcontent_test').setStyle({
            width: 362 + 'px',
            height: 90 + 'px',
            margin: 0 + ' auto'
        });
    };
    $('upload_progress_info').show();
}

function uploadFinished(file_id){
    if (file_id)
       window.location = '/video/edit/upload/?id=' + file_id + '&ktulhu=1';
}

function uploadFilePreSubmit(form)
{
    //получение хэша полей формы
    var param = $(form).serialize(
        {getHash: true}
    );
    $("upload_file_flash").chkInfo(param);
}

/*function mainProfileShadowShow()
{
    var cont = $('MainProfileDiv').down('table');
    var pos = cont.cumulativeOffset();
    $('MainProfileShadowDiv').setStyle({
        left: pos[0] + 3 + 'px',
        top: pos[1] + 3 + 'px',
        width: cont.getWidth() + 'px',
        height: cont.getHeight() + 'px'
    });
    $('MainProfileShadowDiv').show();
}*/

function icoQuickUp(event)
{
    Event.element(event).up('div').removeClassName('NoSel').addClassName('Sel');
}

function icoQuickOver(event)
{
    icoQuickUp(event);
}

function icoQuickOut(event)
{
    Event.element(event).up('div').removeClassName('Sel').addClassName('NoSel');
}

function addQuickList(event)
{
    var el = Event.element(event).up('div');
    var id = el.readAttribute('vid');
    if (id)
        videoListActionButton("quicklist_add_" + id, 'id=' + escape(id), "/video/folder/ajax/video/add/");
}

function icoQuickBindJS(container)
{
    var func = function(el)
        {
            var ico = el.down('div');
            if (ico.down('img'))
                return;

            var _img = document.createElement('img');
            _img = $(_img);
            _img.src = image_path + '/dot_t.gif';
            ico.appendChild(_img);

            var _title = str_add_quicklist_on;
            if (ico.hasClassName('Off'))
                _title = str_add_quicklist_off;
            else
            {
                ico.observe('mouseup', icoQuickUp)
                   .observe('mouseover', icoQuickOver)
                   .observe('mouseout', icoQuickOut)
                   .observe('click', addQuickList);
            }
            ico.writeAttribute({
                title: _title,
                alt: _title
            });
        }
    if (container)
    {
        if ($(container).hasClassName('QuickAddIco'))
            func($(container));
        else
            $(container).select('div.QuickAddIco').each(
                function(el) {
                    func(el);
                }
            );
    }
    else
        $$('div.QuickAddIco').each(
            function(el) {
                func(el);
            }

        );
}

// Класс обертка над аяксовым запросом с запуском привязки иконок видео quick листа к js функциям
Ajax.VideoRequest = Class.create(Ajax.Request, {

    initialize: function($super, url, options) {

        options = Object.clone(options);

        var onComplete = options.onComplete;
        options.onComplete = (function(response, json) {
            if (Object.isFunction(onComplete)) onComplete(response, json);
            icoQuickBindJS();
        }).bind(this);

        $super(url, options);
    }

});

// Класс обертка над аяксовым апдейтером с запуском привязки иконок видео quick листа к js функциям
Ajax.VideoUpdater = Class.create(Ajax.Updater, {

    initialize: function($super, container, url, options) {

        options = Object.clone(options);

        var onComplete = options.onComplete;
        options.onComplete = (function(response, json) {
            if (Object.isFunction(onComplete)) onComplete(response, json);
            icoQuickBindJS(container);
        }).bind(this);

        $super(container, url, options);
    }

});

function checkLoginForm(form)
{
    var login = form['login'];
    var vlogin = login.value.trim();
    var password = form['password'];
    var vpassword = password.value.trim();
    var str_min = new Template(str_form_errors.strmin);
    var str_max = new Template(str_form_errors.strmax);
    if (vlogin=='')
        return new Array(login, str_login, str_form_errors.notnull);
    if (vlogin.length<2)
        return new Array(login, str_login, str_min.evaluate({min: 2}));
    if (vlogin.length>60)
        return new Array(login, str_login, str_max.evaluate({max: 60}));
    if (vpassword=='')
        return new Array(password, str_password, str_form_errors.notnull);
    if (vpassword.length<2)
        return new Array(password, str_password, str_min.evaluate({min: 2}));
    if (vpassword.length>60)
        return new Array(password, str_password, str_max.evaluate({max: 60}));
}

function systemMessageClose(kind, id)
{
    new Ajax.Updater('system_message_block', '/profile/ajax/system/message/read/',
                {
                    method: 'get',
                    parameters: 'kind=' + kind + '&id=' + escape(id),
                    onSuccess: function() {
                    }
                }
            );

}

function sendCopyrightText(_txt)
{
    try
    {
        if (!_txt) _txt = const_copyright_text_null;
        $('copyFlash').setText(1 + _txt);
    }
    catch (e)
    {
        try
        {
            console.error('Ошибка в обращении к copyrightFlash.');
        }
        catch (e)
        {}
    }
}

function changeCopyrightCheck()
{
    if ($('copyright').checked)
        $('copyright').checked = false;
    else
        $('copyright').checked = true;
}

function fixPNG(myImage) // correctly handle PNG transparency in Win IE 5.5 or higher.
{
        if (window.ie55up)
        {
                var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
                var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
                var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
                var imgStyle = "display:inline-block;" + myImage.style.cssText
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
                strNewHTML += " style=\"" + "width:" + myImage.width + "px; height:" + myImage.height + "px;" + imgStyle + ";"
                strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                strNewHTML += "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
                myImage.outerHTML = strNewHTML
        }
}

function fixPNGAlpha(myImage) // correctly handle PNG transparency in Win IE 5.5 or higher.
{
        if (window.ie55up)
        {
                var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
                var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
                var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' ";
                var imgStyle = "width:" + myImage.width + "px; height:" + myImage.height + "px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + myImage.src + "', sizingMethod='scale'); " + myImage.style.cssText;
                var strNewHTML = "<img src=\"" + image_path + "/blank.gif\" " + imgID + imgClass + imgTitle;
                strNewHTML += " style=\"" + imgStyle + "\" />";
                myImage.outerHTML = strNewHTML;
        }
}

function fixBgAlpha(myElement, eBgUrl) // correctly handle PNG transparency in Win IE 5.5 or higher.
{
        if (window.ie55up)
        {
                e = $(myElement);
                e.style.background = 'url(http://pics.smotri.com/blank.gif) no-repeat top left';
                e.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + eBgUrl + "', sizingMethod='image')";
                e.contentEditable = true;
        }
}

function statsExternalResourceDraw(video_id)
{
    $('external_resource_block').show();
    $('external_resource_block').update(str_loading);
    new Ajax.Updater('external_resource_block', '/public_stat/ajax/external/video/view/stats/', {
        method: 'get',
        parameters: 'id=' + escape(video_id),
        onSuccess: function() {
        }
    });
}
