﻿
function GetVerSL() {
    var ver = "";
    var parts = Array("ver-major", "ver-minor", "ver-build", "ver-revision");

    //try firefox etc.
    var nav = navigator.plugins["Silverlight Plug-In"];
    if (nav) {
        for (var i = 0; i < 4; i++) {
            ver += parseInt(nav.description.split(".")[i]).toString();   //getControl().isVersionSupported("2.0"); 
        }
    } else {
        //try the IE one... 
        try {
            var control = new ActiveXObject('AgControl.AgControl');
            //the following would be faster with a binary search. Im kinda sleepy though.
            var vers = Array(1, 0, 0, 0);
            loopMatch(control, vers, 0, 1);
            loopMatch(control, vers, 1, 1);
            loopMatch(control, vers, 2, 10000);
            loopMatch(control, vers, 2, 1000);
            loopMatch(control, vers, 2, 100);
            loopMatch(control, vers, 2, 10);
            loopMatch(control, vers, 2, 1);
            loopMatch(control, vers, 3, 1);
            for (var i = 0; i < 4; i++) {
                ver = vers[i].toString();
            }
        } catch (e) {
        ver = "Silverlight not installed.";
        }
    }
}
function loopMatch(control, vers, idx, inc) {
    while (IsSupported(control, vers)) {
        vers[idx] += inc;
    }
    vers[idx] -= inc;
}
function IsSupported(control, ver) {
    return control.isVersionSupported(ver[0] + "." + ver[1] + "." + ver[2] + "." + ver[3]);
}
        


function showHide(type) {

    if (type == 'signin') {
        new Effect.Move('sign-in-panel', { x: 600, y: 0, mode: 'absolute', duration: 0.5, from: 0, to: 1 });
    } else {
        new Effect.Move('sign-in-panel', { x: 600, y: -300, mode: 'absolute', duration: 0.5 });
    }
    return false;
}

function LoadComments(mediaid) {
    new Ajax.Request('/ajax/comments.ashx',
  {
      method: 'post',
      parameters: { mediaid: mediaid, page: 1,rm: 'loadcomments' },
      onSuccess: function(transport) {
          var response = transport.responseText || "no comment found";

          $('commentlist').innerHTML = response;

      },
      onFailure: function() { alert('Something went wrong...') }
  });

}

function ShowComments(args, context) {
    if (context == "comment") {
        var commentList = $("commentlist");

        if (commentList.innerHTML.length < 10)
            commentList.innerHTML = "<h1 id='comment'>" + KEYcomments + "</h1>"

        commentList.innerHTML += args;
        commentList.style.display = 'block';
        contentBox.value = "";
        $("ajaxLoader").style.display = "none";
        $("status").className = "success";

        if (!moderation)
            $("status").innerHTML = KEYcommentWasSaved;
        else
            $("status").innerHTML = KEYcommentWaitingModeration;
    }
}


function swapDivs(div1, div2) {

    var d1 = $('#' + div1);
    var d2 = $('#' + div2);

    if ($(d1).is(":visible")) {
        d1.hide();
        d2.show();
    }
    else {
        d2.hide();
        d1.show();
     }
}



function addSmile(smile, input) {
    var x = document.getElementById(input);
    x.value = x.value + " " + smile + " ";
    x.focus();
} 





function AddBbCode(v) {
    try {
        if (contentBox.selectionStart) // firefox
        {
            var pretxt = contentBox.value.substring(0, contentBox.selectionStart);
            var therest = contentBox.value.substr(contentBox.selectionEnd);
            var sel = contentBox.value.substring(contentBox.selectionStart, contentBox.selectionEnd);
            contentBox.value = pretxt + "[" + v + "]" + sel + "[/" + v + "]" + therest;
            contentBox.focus();
        }
        else if (document.selection && document.selection.createRange) // IE
        {
            var str = document.selection.createRange().text;
            contentBox.focus();
            var sel = document.selection.createRange();
            sel.text = "[" + v + "]" + str + "[/" + v + "]";
        }
    }
    catch (ex) { }

    return;
}

// Searches the blog based on the entered text and
// searches comments as well if chosen.
function Search(root) {
    var input = $("searchfield");
    var check = $("searchcomments");

    var search = "search.aspx?q=" + encodeURIComponent(input.value);
    if (check != null && check.checked)
        search += "&comment=true";

    top.location.href = root + search;

    return false;
}

// Clears the search fields on focus.
function SearchClear(defaultText) {
    var input = $("searchfield");
    if (input.value == defaultText)
        input.value = "";
    else if (input.value == "")
        input.value = defaultText;
}

function Rate(id, rating) {
    CreateCallback("rating.axd?id=" + id + "&rating=" + rating, RatingCallback);
}

function RatingCallback(response) {
    var rating = response.substring(0, 1);
    var status = response.substring(1);

    if (status == "OK") {
        if (typeof OnRating != "undefined")
            OnRating(rating);

        alert("You rating has been registered. Thank you!");
    }
    else if (status == "HASRATED") {
        alert(KEYhasRated);
    }
    else {
        alert("An error occured while registering your rating. Please try again");
    }
}

/// <summary>
/// Creates a client callback back to the requesting page
/// and calls the callback method with the response as parameter.
/// </summary>
function CreateCallback(url, callback) {
    var http = GetHttpObject();
    http.open("GET", url, true);

    http.onreadystatechange = function() {
        if (http.readyState == 4) {
            if (http.responseText.length > 0 && callback != null)
                callback(http.responseText);
        }
    };

    http.send(null);
}

/// <summary>
/// Creates a XmlHttpRequest object.
/// </summary>
function GetHttpObject() {
    if (typeof XMLHttpRequest != 'undefined')
        return new XMLHttpRequest();

    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) { }
    }

    return false;
}



// Adds a trim method to all strings.
function Equal(first, second) {
    var f = first.toLowerCase().replace(new RegExp(' ', 'gi'), '');
    var s = second.toLowerCase().replace(new RegExp(' ', 'gi'), '');
    return f == s;
}


function getCookieValue(name) {
    var cookie = new String(document.cookie);

    if (cookie != null && cookie.indexOf('comment=') > -1) {
        var start = cookie.indexOf(name + '=') + name.length + 1;
        var end = cookie.indexOf('&', start);
        if (end > start && start > -1)
            return cookie.substring(start, end);
    }

    return null;
}




function sendComplain(trackID, subject, message, form) {
    var d = $('complain_content_progress');
    form['theme'].disabled = true;
    form['message'].disabled = true;
    d.innerHTML = '<IMG src="/img/ico_forward.gif" border="0">';


    var url = mkAbsURL("/ajax/email.ashx");
    var params = {};
    params['id'] = trackID;
    params['rm'] = 'complain';
    params['subject'] = subject;
    params['message'] = message;

    var request = new Ajax.Request(
        url,
        {
            method: 'post',
            postBody: $H(params).toQueryString(),
            onComplete: function(req) {
                swapDivs('complain_content_active', 'complain_sent');
            }
        }
    );
}



function sendComplainToAdmins(f) {
   
    var d = $('#complain_content_progress');

    if (f['subject'].value == 0) {
        alert(SELSUBJECTMESS);
	return false;
    }
    
    if (f['subject'].value == 4) {
	var email = $.trim(f['email'].value);

	if (email.length == 0) {
	    alert(ENTEMAIL);
	    return false;
	}
	
	if (!email.match(/^[\040-\176]+\@[-A-Za-z0-9.]+\.[A-Za-z]+$/)) {
	    alert(EMAILERROR);
	    return false;
	}
    }
    
    if ($.trim(f['message'].value).length == 0) {
        alert(ENTTEXTMESS);
	return false;
    }
    
    // отсылаем сообщение
   // ['subject','message','email'].each(function(fname) { f[fname].disabled = true; });
    d.html('<IMG src=\'/images/ico_forward.gif\' border="0">');

    $.ajax({
        type: "POST",
        url: mkAbsURL("/ajax/email.ashx"),
        data: $(f).serialize(),
        success: function (response) {
            swapDivs('complain_content_active', 'complain_sent');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(OPERATION_ERROR_TRY_AGAIN);
            //alert(xhr.status);
            //alert(thrownError);
        }
    });

   
    
}


//onFailure: function() { alert('Something went wrong...') },
    function mkAbsURL(relURL) {
        var l = document.location;
        var u = l.protocol + "//" + document.location.hostname + relURL;
        return u;
    }



    function textCopyIE(i) {
        var elt = document.getElementById(i);
        elt.focus();
        var toCopy = elt.value;
        if (window.clipboardData) {
            window.clipboardData.setData('Text', toCopy);
            if (i == 'txt2')
                alert(CODE_COPIED_SUCCESS);
            else
                alert(LINK_COPIED_SUCCESS);
        } else if (window.netscape) {
        alert(PCODE_COPIED_ERROR);
        }
    }




    function textCopyIEipr(elt) {
        textCopyIEiprEx(elt, PCODE_COPIED_SUCCESS, PCODE_COPIED_ERROR);
    }


    function textCopyIEiprEx(elt, succMsg, errMsg) {
        //elt.focus();
        var toCopy = elt.value;
        if (window.clipboardData) {
            window.clipboardData.setData('Text', toCopy);
            alert(succMsg);
        } else if (window.netscape) {
            alert(errMsg);
        }
    }
    
    function showOrHide(divId, onshow, onhide) {
        var d = $(divId);
        if (d.style.display == 'none') {
            new Effect.Appear(d);
            if (onshow) onshow();
        } else {
            new Effect.Fade(d);
            if (onhide) onhide();
        }
    }

    function showOrHideNoEffect(divId, onshow, onhide) {

        var d1 = $('#' + divId);

        if ($(d1).is(":visible")) {
            d1.hide();
        }
        else {
            d1.show();
        }

    }

    function selectText(input) {
        if (input.createTextRange) {
            var oRange = input.createTextRange();
            oRange.moveStart("character", 0);
            oRange.moveEnd("character", 0);
            oRange.select();
        } else if (input.setSelectionRange) {
            input.setSelectionRange(0, input.value.length);
        }

        input.focus();
    };



    /* quick list */
//    function QL_ico_over(oLink) {
//        if (oLink.getAttribute('clicked'))
//            return;
//        var img = oLink.childNodes[0];
//        if (img)
//            img.src = '/images/icon/i_add_down.gif';
//        else
//            oLink.style.background = "url(/images/icon/icons.gif) -72px -48px no-repeat";
//    };


//    function QL_ico_out(oLink) {
//        if (oLink.getAttribute('clicked'))
//            return;
//        var img = oLink.childNodes[0];
//        if (img)
//            img.src = '/images/icon/i_add.gif';
//        else
//            oLink.style.background = "url(/images/icon/icons.gif) -57px -48px no-repeat";
//    };

//    function add_to_quicklist(oLink, track_id) {
//        if (oLink.attributes["clicked"]) {
//            if (oLink.attributes["is_link"])
//                oLink.href = '/quicklist/';
//            else
//                oLink.childNodes[0].href = '/quicklist/';
//            oLink.onclick = null;
//        } else {
//            oLink.onmouseover = null;
//            oLink.onmouseout = null;
//            oLink.setAttribute('clicked', true);

//            oLink.title = QUICK_LIST;
//            oLink.className = "in-qlist";
//            oLink.innerHTML = "&nbsp;В&nbsp;списке&nbsp;";

//            var url = mkAbsURL("/ajax/ajax.ashx");
//            var params = {};
//            params['media_id'] = track_id;
//            params['rm'] = 'quicklist';
//            var request = new Ajax.Request(
//			url,
//			{
//			    method: 'post',
//			    parameters: $H(params).toQueryString(),
//			    onComplete: function(req) {
//			        $('qlist_counter').innerHTML = "(" + req.responseText + ")";
//			        return;
//			    }
//			}
//		);
//        }

//}


//    function QL_ico_clicked(oLink, track_id, lang) {
//        var img = oLink.childNodes[0];
//        if (oLink.attributes["clicked"]) {
//            if (oLink.attributes["is_link"]) oLink.href = lang + '/quicklist/';
//            else oLink.childNodes[0].href = lang + '/quicklist/';
//            oLink.onclick = null;
//            window.location = lang + '/quicklist/';
//        }
//        else {
//            var list_link;
//            if (img) {
//                oLink.removeChild(img);
//                oLink.setAttribute("is_link", true);
//                list_link = oLink;
//            }
//            else {
//                list_link = document.createElement("a");
//                oLink.appendChild(list_link);
//            }
//            oLink.onmouseover = null;
//            oLink.onmouseout = null;
//            oLink.setAttribute('clicked', true);

//            list_link.href = "javascript:void(0);";
//            list_link.title = VIEW_QUICK_LIST;

//            list_link.style.color = "white";
//            oLink.style.width = "50px";
//            list_link.style.backgroundColor = "#73AC04";
//            try {
//                list_link.innerHTML = IN_QUICK_LIST;
//            } catch (e) {
//                list_link.innerText = IN_QUICK_LIST;
//            }
//            var url = mkAbsURL("/ajax/ajax.ashx");
//            var params = {};
//            params['media_id'] = track_id;
//            params['rm'] = 'quicklist';
//          
//            var request = new Ajax.Request(
//			url,
//			{
//			    method: 'post',
//			    parameters: $H(params).toQueryString(),
//			    onComplete: function(req) {
//			        $('qlist_counter').innerHTML = "(" + req.responseText + ")";
//			        return;
//			    }
//			}
//		);
//			
//        }

//    }


//    var Popup = {
//        open: function(options) {
//            this.options = {
//                url: '#',
//                width: 300,
//                height: 300
//            }
//            Object.extend(this.options, options || {});
//            window.open(this.options.url, '', 'width=' + this.options.width + ',height=' + this.options.height);
//        }
//    }


    function AddFavorite(span) {
        var obj = $("button[aria\\-expanded='true']");
        obj.attr('aria-expanded', false);
        obj.parents('a').unbind();
        var params = {};
        params['rm'] = 'addtofav';
        params['id'] = obj.parent().attr('data-video-ids');

        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/ajax.ashx"),
            data: $.param(params),
            success: function (response) {
                var obj = $.parseJSON(response);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(OPERATION_ERROR_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });

        $(span).parents('#shared-addto-menu').unbind();
        $(span).parents('#shared-addto-menu').hide();
        $(obj).parents('a').unbind();
        $(obj).parent().hide();
        $(obj).parent().siblings('.video-in-quicklist').text('Добавлено в избраное');
//        $(obj).parent().siblings('.video-in-quicklist').click(function () {
//            obj.parents('a').click(function (event) {
//                event.preventDefault();
//            });
//            window.location.href = 'http://' + LANG + '/favorite/';
//        });
        $(obj).parent().siblings('.video-in-quicklist').show();
    }

    function saveToQueue(span) {
        var obj = $("button[aria\\-expanded='true']");
        obj.attr('aria-expanded', false);
        obj.parents('a').unbind();
        var params = {};
        params['id'] = obj.parent().attr('data-video-ids');
        params['rm'] = 'quicklist';

        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/ajax.ashx"),
            data: $.param(params),
            success: function (response) {
                var obj = $.parseJSON(response);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(OPERATION_ERROR_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });

        $(span).parents('#shared-addto-menu').unbind();
        $(span).parents('#shared-addto-menu').hide();
        $(obj).parents('a').unbind();
        $(obj).parent().hide();
        $(obj).parent().siblings('.video-in-quicklist').click(function () {
            obj.parents('a').click(function (event) {
                event.preventDefault();
            });
            window.location.href = LANG + '/quicklist/';
        });
        $(obj).parent().siblings('.video-in-quicklist').show();
    }



    //////////////////////////////////////////////////////////////


    function playerNotification(event, params) {
        //    alert('Event ' + event + '; repeat:' + params.repeat);
    };


    function setCookie(name, value, expires, path, domain, secure) {
        var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
			((path) ? "; path=" + path : "") +
				((domain) ? "; domain=" + domain : "") +
				((secure) ? "; secure" : "");
        document.cookie = curCookie;
    }

    function getCookie(name) {
        var dc = document.cookie;
        var prefix = name + "=";
        var begin = dc.indexOf("; " + prefix);
        if (begin == -1) {
            begin = dc.indexOf(prefix);
            if (begin != 0) return null;
        } else
            begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1)
            end = dc.length;
        return unescape(dc.substring(begin + prefix.length, end));
    }


    function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
            document.cookie = name + "=" +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    }

    function fixDate(date) {
        var base = new Date(0);
        var skew = base.getTime();
        if (skew > 0)
            date.setTime(date.getTime() - skew);
    }


    function togglePublished(imgId, trackID) {
        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/ajax.ashx"),
            data: "id=" + trackID + "&rm=publish",
            success: function (response) {
                if (response != "NOTPUBLISHED" && response != "PUBLISHED") {
                    return;
                }
                $('#'+imgId).attr('src',(response == "PUBLISHED" ? '/images/checkbox_a.jpg' : '/images/checkbox.jpg'));
                $("#tt" + trackID).attr('class', (response == "PUBLISHED" ? '' : 'hiddenTrack'));
                return;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert("Ошибка при выполнении. Попробуйте еще раз");
                //alert(xhr.status);
                //alert(thrownError);
            }
        });
    }


    /* Функции для работы с сообщениями */
    function delete_messages(name_element, box) {
        var items = $('input:checked');

        //var items = $A(document.getElementsByName(name_element)).findAll(function(value) { return value.checked });
        if (items.length == 0) {
            alert(NO_SELECTED_MESSAGES);
            return false;
        };
        
        var ids = new Array();
        items.each(function () { ids.push($(this).attr('mid')); });

        var url = mkAbsURL("/messages/?rm=mdel&box=" + box + "&mids=" + ids);
        document.location.href = url;
    }

    function delete_message(id, box) {
        if (!id) {
            alert(UNKNOWN_PARAMETR);
            return false;
        };

        var url = mkAbsURL("/messages/?rm=mdel&box=" + box + "&mids=" + id);
        document.location.href = url;
    }




    function show_spam_form(name_element, canSend, nick, name_div) {

        //if (document.getElementById('indicator').style.display == 'none') {

        if (!$("#indicator").is(':visible')) {

            if (name_element) {
                if (!canSend) {
                    alert(OPERATION_DOES_NOT_EXECUTED);
                    return false;
                }

                var items = $('input:checked');//  $A(document.getElementsByName(name_element)).findAll(function(value) { return value.checked });
                if (items.length == 0) {
                    alert(NO_SELECTED_MESSAGES);
                    return false;
                };
                var a = [];

                items.each(function () {
                    if ($(this).attr("t") == 'User') {
                        a.push($(this).attr("t"));
                    }
                    else
                        $(this).removeAttr('checked');
                });
                var list_nick = a.join(', ');

                //for (i = 0; i < items.length; i++) {
                //    if (items[i].getAttribute('t') == 'User') {
                //        list_nick = list_nick + items[i].getAttribute('nick');
                //        if (i != items.length - 1) { list_nick = list_nick + ', ' }
                //    } else {
                //        items[i].checked = false;
                //    }
                //};
                if (list_nick == '') {
                    alert(COMPLAIN_DOES_NOT_ALLOWED);
                    return false;
                }
                $('#' + name_div + '_list_nick').html(list_nick);
                //document.getElementById(name_div + '_list_nick').innerHTML = list_nick;
            } else {
                $('#' + name_div + '_list_nick').html(nick);
                //document.getElementById(name_div + '_list_nick').innerHTML = nick;
            }
            $('#' + name_div).show();
            $('#' + name_div + '_body').show();
            $('#' + name_div + '_success_send').hide();
            $('#' + name_div + '_text').value = '';
        } else {
            $('#' + name_div + '_body').hide();
            $('#' + name_div + '_success_send').hide();
            $('#' + name_div).show();
        }
    }

    function send_spam_complaint(name_element, canSend, id, name_div) {
        if (!canSend) {
            alert(OPERATION_DOES_NOT_EXECUTED);
            return false;
        }

        var body = $('#' + name_div + '_text');
        if (body.val().length == 0) {
            alert(ENTER_REASON);
            return false;
        };
        var ids = new Array();
        if (name_element) {
            var items = $('input:checked');
            if (items.length == 0) {
                alert(NO_SELECTED_MESSAGES);
                return false;
            };


            items.each(function () {
                if ($(this).attr("t") == 'User') {
                    ids.push($(this).attr("mid"));
                }
                else
                    $(this).removeAttr('checked');
            });
           
          
            if (ids.length == 0) {
                alert(COMPLAIN_DOES_NOT_ALLOWED);
                return false;
            }
        } 
        else {
            ids.push(id);
        }

        $('#' + name_div + '_indicator').show();
        $('#' + name_div + '_body').hide();

        $.ajax({
            type: "POST",
            url: mkAbsURL("/messages/"),
            data: "rm=ssc&mids=" + ids + "&body=" + body.value,
            success: function (response) {
                $('#' + name_div + '_success_send').show();
                $('#' + name_div + '_indicator').hide();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(OPERATION_ERROR_TRY_AGAIN); 
                $('#spam').hide(); $('#' + name_div + '_indicator').hide();
                //alert(xhr.status);
                //alert(thrownError);
            }
        });

        

    }

    function actionBlocked(user_id, my_action) {

        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/ajax.ashx"),
            data: "rm=block&id=" + user_id + "&action=" + my_action,
            success: function (response) {
                if (response != "OK") {
                    return alert(EXECUTIN_ERROR_TRY_AGAIN);
                } else {
                    if (my_action == 'blocked') {
                        $('#link_blocked_del').show();
                        $('#link_blocked_add').hide();
                    } else if (my_action == 'unblocked') {
                        $('#link_blocked_del').hide();
                        $('#link_blocked_add').show();
                    }
                }


            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(OPERATION_ERROR_TRY_AGAIN);
                $('#spam').hide(); $('#' + name_div + '_indicator').hide();
                //alert(xhr.status);
                //alert(thrownError);
            }
        });


        
    }




    function show_blockeds() {
        if (!$("list_blockeds").is(':visible')) {
            var params = {};
            params['rm'] = 'get_blockeds';
  
            $('#button_blocked').hide();

            $.ajax({
                type: "POST",
                url: mkAbsURL('/ajax/ajax.ashx'),
                data: $.param(params),
                success: function (response) {
                    if (response.length == 0) {
                        return alert(EXECUTIN_ERROR_TRY_AGAIN);
                    }
                    else if (response == 'OK') {
                        $("#list_blockeds_body").show();
                        $('#list_blockeds_body').html(BLOCKED_USERS_DOES_NOT_EXISTS);
                        return;
                    } else {
                        var obj = $.parseJSON(response);
                        var body = new String();
                        for (i = 0; i < obj.length; i++) {
                            body += '<input type="checkbox" user_id="' + obj[i].id + '" name="del_blocked" class=\"noborder\" value="' + obj[i].id + '"></input>&nbsp;<a href="' + obj[i].url + '" title="О пользователе ' + obj[i].nick + '"><img src="' + obj[i].icon + '" class="icon" title="О пользователе ' + obj[i].nick + '">&nbsp;<b>' + obj[i].nick + '</b></a><br>';
                        }
                        $('#button_blocked').show();
                        $('#list_blockeds_body').html(body);
                        $('#list_blockeds_body').show();
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    return alert(SENDING_ERROR_TRY_AGAIN);
                    //alert(xhr.status);
                    //alert(thrownError);
                }
            });
            $("#list_blockeds").show();
        }
        else 
        {
            $("#list_blockeds").hide();
        }
    }

    function deleteBlocked() {
        var items = $("input[name=del_blocked]");
        if (items.length == 0) {
            alert(NO_SELECTED_USERS);
            return false;
        };
        var ids = new Array();
        items.each(function () { ids.push($(this).attr('user_id')); })

        var params = {};
        params['rm'] = 'del_blockeds';
        params['del'] = ids;
        var url = mkAbsURL('/ajax/ajax.ashx');

        $.ajax({
            type: "POST",
            url: mkAbsURL('/ajax/ajax.ashx'),
            data: $.param(params,true),
            success: function (response) {
                if (response.length == 0) {
                    return alert(EXECUTIN_ERROR_TRY_AGAIN);
                }
                else if (response == 'OK') {
                    $('#button_blocked').hide();
                    $('#list_blockeds_body').html(SELECTED_USERS_EXCLUDED_FROM_LIST);
                    return;
                } 
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert(SENDING_ERROR_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });
    }

    function show_msg_settings() {
        if (!$("preference").is(':visible')) {
            var params = {};
            params['rm'] = 'get_ms';
          

            $.ajax({
                type: "POST",
                url:  mkAbsURL('/messages/'),
                data: $.param(params),
                success: function (response) {
                    if (response.length == 0) {
                        return alert(EXECUTIN_ERROR_TRY_AGAIN);
                    }
                    else if (response == 'OK') {
                        $('#system').removeAttr('checked');
                        $('#friends').removeAttr('checked');
                    } else {
                        var obj = $.parseJSON(response);
                        if (obj.system == 1) {
                            $('#system').attr('checked', 'checked');
                        }
                        if (obj.friends == 1) {
                            $('#friends').attr('checked', 'checked');
                        }
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    return alert(SENDING_ERROR_TRY_AGAIN);
                    //alert(xhr.status);
                    //alert(thrownError);
                }
            });

           
            $("#preference").show();
        } else {
            $("#preference").hide();
        }

    }

    function save_msg_settings() {

        var params = {};
        params['rm'] = 'save_ms';

        if ($('#system').is(':checked')) {
            params['system'] = 1;
        } else {
            params['system'] = 0;
        }

        if ($('#friends').is('checked')) {
            params['friends'] = 1;
        } else {
           params['friends'] = 0;
        }

        $.ajax({
            type: "POST",
            url: mkAbsURL('/messages/'),
            data: $.param(params),
            success: function (response) {
                if (response.length == 0) {
                    return alert(EXECUTIN_ERROR_TRY_AGAIN);
                }
                else 
                {
                     var obj = $.parseJSON(response);
                     if (obj.status == 'ok') 
                        return alert(SETTINGS_SAVED);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert(SENDING_ERROR_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });


        
    }

    function addFriendMessage(user_id, link, del) {
        var params = "id=" + user_id + "&rm=add&mode=ajax";
        
        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/friend.ashx"),
            data: $.param(params),
            success: function (response) {
                if (response != 'OK') {
                    return alert(EXECUTIN_ERROR_TRY_AGAIN);
                }
                else {
                    if (del) {
                        link.innerHTML = '';
                    } else {
                        var i = document.getElementById("fr_ico");
                        i.src = "/images/ui_friend.jpg";
                        if (link.childNodes.length > 1) {
                            link.childNodes[1].nodeValue = MY_FRIEND;
                        }
                    }
                    link.onclick = null;
                    alert(USER_ADDED_TO_FRENDLITS);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert(SENDING_ERROR_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });


    }

    function delFriend(user_id, link) {
        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/friend.ashx"),
            data: "id=" + user_id + "&rm=del&mode=ajax",
            success: function (response) {
                $('#addToFriend').show();
                $('#fr_ico').hide();
                $('#fr').hide();
                //alert(USER_DELETED_FROM_FRENDLIST);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert(SENDING_ERROR_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });


    }

    function addFriend(user_id, link) {
        $.ajax({
            type: "POST",
            url: mkAbsURL("/ajax/friend.ashx"),
            data: "id=" + user_id + "&rm=add&mode=ajax",
            success: function (response) {
                if (response != 'OK') {
                    return alert(EXECUTIN_ERROR_TRY_AGAIN);
                }
                else {
                    $('#addToFriend').hide();
                    $('#fr_ico').show();
                    $('#fr').show();
                    //link.onclick = null;
                    //alert(USER_ADDED_TO_FRENDLITS);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert(ERROR_REFRESH_PAGE_TRY_AGAIN);
                //alert(xhr.status);
                //alert(thrownError);
            }
        });


    }

    function addToPlaylist(div_id, form_id, after_div_id) {
        var form = document.getElementById(form_id);
        var div = document.getElementById(div_id);
        var adiv = document.getElementById(after_div_id);
        var plId = form["id"].options[form["id"].selectedIndex].value;

        var params = "rm=add&id=" + plId + "&add_track=" + form["add_track"].value;

        if (plId == 0) {
            form.submit();
            return;
        }
       
        $.ajax({
            type: "POST",
            url: mkAbsURL('/ajax/playlist.ashx'),
            data: params,
            success: function (response) {
               
                if (response.length == 0) {
                    return alert(EXECUTIN_ERROR_TRY_AGAIN);
                }
                else {
                    //$('#' + after_div_id).html(response);
                    //$('#' + after_div_id).css("display",'block');
                    adiv.innerHTML = response;
                    adiv.style.display = 'block';
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                //return alert(SENDING_ERROR_TRY_AGAIN);
                alert(xhr.status);
                alert(thrownError);
            }
        });

        
    }



    function postTags(id) {
        $('#indicator' + id).show();
        $.ajax({
            type: "POST",
            url: 'http://' + document.domain + '/ajax/tags.ashx',
            data: 'rm=add2&id=' + id + '&t=' + $('#tags' + id).val(),
            success: function (response) {
                $("#my_tags" + id).html(response);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return alert("Ошибка при выполнении. Попробуйте еще раз");
                //alert(xhr.status);
                //alert(thrownError);
            }
        });


        $('#AddTagsLink' + id).show();
        $('#AddTagsLink' + id).show();
        $('#AddTags' + id).hide();
        $('#my_tags' + id).show();
    }
    function MyTrackLink(obj, id) {
        var mas = ['pub', 'edit'];
        for (var i = 0; i < mas.length; i++) {
            if (mas[i] == obj) {
                $('#' + obj + 'Header' + id).attr('class', 'MyTrackLinkAct');
                $('#' + obj + id).show();
            }
            //            else {
            //                $(mas[i] + 'Header' + id).className = '';
            //                $(mas[i] + id).hide();
            //            }
        }
    }
    function MyTrackLinkClose(obj, id) {
        $('#' + obj + 'Header' + id).attr('class', '');
        $('#' + obj + id).hide();
    }
    function CheckAll(Element, Name) {
        if (Element.checked)
            $(':checkbox').each(function () { $(this).attr('checked', 'checked'); });
        else
            $(':checkbox').each(function () { $(this).removeAttr('checked'); });
    }


    function Rating(userid, mediaid, increase) {
        if (userid > 0) {
            $.post('http://' + document.domain + '/ajax/ajax.ashx', { "rm": 'ratebyid', "userid": userid, "id": mediaid, "increase": increase },
				function (data) {
				    if (data.status == "ok") {
				        $('.watch-ratings-stats-parenthesis').text('(' + VSEGO + ' ' + data.total + ')');
				        $('#total_like').val(data.total_like);
				        $('#total_unlike').val(data.total_unlike);
				        $('.likes-bar').attr("style", "width:" + data.like_percent + '%');
				        $('.dislikes-bar').attr("style", "width:" + data.unlike_percent + '%');
				    }
				}, "json");
        }
        marker(document.getElementById('fv_cmmnd'));
    }

    function marker(_this) {
        var elem = _this.id.split("_")[0];
        if (_this.className == '') hide_it('mn_menu');
        else {
            if (_this.className == 'on')
                return; //hide_it('mn_menu');
            else {
                var elem = _this.id.split("_")[0];
                hide_it('mn_menu');
                _this.className = 'on';
                $('#' + elem).show();
            }
        }
    }

    function hide_it(idd) {
        var object = document.getElementById(idd);
        for (var c = 0; c < object.rows[0].cells.length; c++) {
            object.rows[0].cells[c].className = 'off';
            var element = object.rows[0].cells[c].id.split("_")[0];
            $('#' + element).hide();
            //document.getElementById(element).style.display = 'none';
        }
    }

    setCookie = function (name, val) {
        document.cookie = name + "=" + escape(val) + ";expires=Sat, 31 Dec 2099 23:59:59 GMT;";
    };
    getCookie = function (check_name, return_if_not_found) {
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        for (i = 0; i < a_all_cookies.length; i++) {
            a_temp_cookie = a_all_cookies[i].split('=');
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
            if (cookie_name == check_name) {
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                return cookie_value;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        return return_if_not_found;
    };


    function base_code(data) {
        var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, enc = '';
        do {  // unpack four hexets into three octets using index points in b64
            h1 = b64.indexOf(data.charAt(i++));
            h2 = b64.indexOf(data.charAt(i++));
            h3 = b64.indexOf(data.charAt(i++));
            h4 = b64.indexOf(data.charAt(i++));
            bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
            o1 = bits >> 16 & 0xff;
            o2 = bits >> 8 & 0xff;
            o3 = bits & 0xff;
            if (h3 == 64) enc += String.fromCharCode(o1);
            else if (h4 == 64) enc += String.fromCharCode(o1, o2);
            else enc += String.fromCharCode(o1, o2, o3);
        } while (i < data.length);
        return enc;
    }

    function OpenPopup(lang, userid) {
    $.nyroModalManual({url: lang + '/popup/chat.aspx?userid=' + userid, forceType: 'form', title: 'Чат', minWidth: 700, minHeight: 450 });
    }

