var userAgent = navigator.userAgent.toLowerCase();
var hashHistory = new Array();
var needUpdateFromHash = true;
var hashType = "";
var photos = [];
var checkSearch = false;
var familyArray = new Array();
var ie = ($.browser.msie) ? true : false;
var intervalID = "";

function showModalAway(e,url)
{
//	var regexp = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/g;
//	regexp.lastIndex = 0;
//	var parseURL = regexp.exec(url);
//	var domain = parseURL[6];
//	var localTitle = '<?=$project_name?>';
//	var localDomain = '<?=$cfg['GLOBAL']['domain']?>';
//	var text = "<div style='width: 600px; padding: 20px; padding-top: 10px;'><h2>"+localTitle+" | Переход по внешней ссылке</h2> Вы покидаете сайт "+localDomain+" по внешней ссылке <b>"+url+"</b>, предоставленной одним из участников. <br/>Администрация "+localTitle+" не несет ответственности за содержимое сайта <b>"+domain+"</b> и настоятельно рекомендует <b>не указывать</b> никаких своих данных, имеющих отношение к "+localTitle+" (особенно <b>e-mail</b>, <b>пароль</b> и <b>cookies</b>), на сторонних сайтах. <br/><br/> Кроме того, сайт <b>"+domain+"</b> может содержать вирусы, трояны и другие вредоносные программы, опасные для Вашего компьютера. <br/> Если у Вас нет серьезных оснований доверять этому сайту, лучше всего на него не переходить, даже если Вы якобы получили эту ссылку от одного из Ваших друзей. <br/><br/> Если Вы еще не передумали, нажмите на <a href='"+url+"' id='page'>"+url+"</a>. <br/> Если Вы не хотите рисковать безопасностью Вашего аккаунта и компьютера, нажмите <a href='javascript:closeMessage()'>отмена</a>.</div>";
//	$('#awayDiv').html(text);

        window.open(url);
        e.cancelBubble = true;
        return false;
}

function trim(text) {return (text || "").replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, "");}

function checkUrl()
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'checkUrl',
                'uri' : req_uri,
                'hash' : location.hash.replace("#","")
        },

        function(result, answer)
        {
                if(result['needRedirect'])
                    location.href = result['uri'];
        },true)
}

var KEY = window.KEY = {
  LEFT: 37,
  V: 86,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,
  DEL: 8,
  TAB: 9,
  RETURN: 13,
  ESC: 27,
  PAGEUP: 33,
  PAGEDOWN: 34,
  SPACE: 32,
  HOME: 36,
  END: 35,
  ENTER: 13,
  DELETE: 46,
  BACKSPACE: 8
};

function greyBg(){
        $('.greyBG').mouseenter(function(){
            $(this).css('background-color','#E5E5E5')
        }).mouseleave(function(){
            $(this).css('background-color','');
        });
}

function htmlspecialchars(html) {
      
      html = html.replace(/&/g, "&amp;");
      
      html = html.replace(/</g, "&lt;");
      html = html.replace(/>/g, "&gt;");
      html = html.replace(/"/g, "&quot;");
      
      return html;
}

jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

function hidehint(type,pageid,act,user)
{

	document.getElementById('hintbutton1').style.display=(document.getElementById('hintbutton1').style.display=='none')?'block':'none';
	document.getElementById('hintbutton2').style.display=(document.getElementById('hintbutton2').style.display=='none')?'block':'none';
	document.getElementById('hint').style.display=(document.getElementById('hint').style.display=='none')?'block':'none';

		JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'hidehint', 
			'type': type, 
			'page': pageid,
			'act': act,
			'user': user
		}, 
		function(result, answer) 
		{

		},true);
}


function getElementByName(id)
{
	var ar=document.getElementsByName(id);
	return ar[0];	
}

function checknumeric()
{
if(window.event)
{
  var key = window.event.keyCode; 
  if (key <48 || key >57) window.event.returnValue = false; 
}
}

function FocusIN(obj)
{
  obj.style.backgroundColor="#fff";
}
function FocusOUT(obj)
{
  obj.style.backgroundColor="#fff";
}

function clock() {
if (!document.getElementById && !document.all) return;

var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();

var m;

digital.setSeconds( seconds+1 );

//if (hours <= 9) minutes = "0" + hours;
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;


dispTime =hours + ":" + minutes;

if (hours <= 9) dispTime = "0" + dispTime;

if(document.getElementById('clock')) document.getElementById('clock').innerHTML=dispTime;

setTimeout("clock()", 1000);


}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document;if(d.images){if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){d.MM_p[j]=new Image;d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;document.MM_sr=new Array;for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;if(!x.oSrc) x.oSrc=x.src;x.src=a[i+2];}
}

function validateForm(obj)
{
	if(obj.className=='.ui-button-disabled')
		return;
	obj.className='.ui-button-disabled';
	obj.form.submit();
}

function preload() {
  if (document.images) {
    var imgsrc = preload.arguments;
    arr=new Array(imgsrc.length);
    for (var j=0; j<imgsrc.length; j++) {
      arr[j] = new Image;
      arr[j].src = imgsrc[j];
    }
  }
}

function checkClick(evt,userID) 	
    { 		
        evt = (evt) ? evt : event; 	
        if(evt.button=="0") 		
        { 	
		displayMenu(evt,userID);	
        } 		
    } 

function setCookie(name, value, expires, path, domain, secure) 
{
    if (!name || !value) return false;
    var str = name + '=' + encodeURIComponent(value);

    if (expires) str += '; expires=' + expires.toGMTString();
    if (path)    str += '; path=' + path;
    if (domain)  str += '; domain=' + domain;
    if (secure)  str += '; secure';

    document.cookie = str;
    return true;
}

function changeSearchStyle(selected)
{
	if (selected.className != "search_selected")
	{
		var elements = selected.parentNode.childNodes;
		for (var i = 0; i < elements.length - 1; i++) 
		{
			if (elements[i].className == "search_selected")
				elements[i].className = "search_normal";
		}
		selected.className =  "search_selected";
		document.getElementById("search_in").value = selected.id;

                setCookie("searchActiveType", selected.id, '', "/"); 
	}
}

function lead_zero(val)
{
	return (val <= 9) ? ("0" + val) : val;
}


function changeSection(id,userID, noRefresh, newCount)
{                
        userID = !(userID) ? "" : userID;
        newCount = (newCount) ? newCount : 0;
        
        $("#"+id+"_container").html("<div class='noRecords'><img src='/images/upload.gif' alt=''/></div>")
        if(!noRefresh)
            refresh_records(id, 0, userID,'',newCount);
        
        $('.navi').find("td.enabled").each(function(){
            if($("#"+this.id+'_container:visible').length == 1 && this.id!=id)
            {
                $("#"+this.id+'_container').hide();
                $("#"+this.id+'_container').html(''); 
                $(this).removeClass('enabled');
                $(this).addClass('disabled');
            }
        });

        if($("#"+id+'_container:visible').length ==0)
            {
                $("#"+id+"_container").show();
                $("#"+id).addClass('enabled');
                $("#"+id).removeClass('disabled');
            }
            
        
        $.cookie('sectionID',id);
}

function switchInsert(id, switchedID)
{
    if($("#"+switchedID).hasClass("en"))
        return;
    
    if($("#messageBlock").html() != '')
    {
        $("#messageBlock").html('');
        $("#messageBlock").fadeOut(500);
    }
    
    $("#"+id).find("td.en").each(function(){
        $(this).addClass('dis');
        $(this).removeClass('en');
        $("#"+this.id+'_container').hide();
    });

    $("td#"+switchedID).addClass('en');
    $("td#"+switchedID).removeClass('dis');
    $("#"+switchedID+'_container').show();
    
    hashArray = location.hash.split("/");
    if(hashArray['0'] == "#games")
    {
        location.hash = "games/"+switchedID;

    }
        
}

function checkNew(type)
{
    if($("#"+type+"_container:visible").length == 0 )
        return;
    
    var lastID = $("#"+type+"_container").find("div.recordContainer:first").attr('id').split('_');    
    
    if(!lastID['0'])
        return; 
    
    
    JsHttpRequest.query('/ajax_functions.php',
                {
                        'function': 'checkNew',
                        'id': lastID['0'],
                        'type': type

                },

                function(result, answer)
                {
                    if(result['newMessages'] > 0)
                        {                         
                            $("#newMessageBtn").remove();
                            $('#'+type+'_container').prepend('<div id="newMessageBtn"></div>');
                            $("#newMessageBtn").css({"padding":"15px 0 10px 0"});
                            $("#newMessageBtn").html(result['button']);
                        }

                },true);
}

function changeSection2(contentID, selected, id)
{
        if(id)
            selected = document.getElementById(id);

	if (selected.className != "enabled")
	{
                var elements = selected.parentNode.childNodes;
                var container = document.getElementById(contentID).parentNode;

                if(container)
                {
                    for (var i = 0; i < elements.length; i++)
                    {
                        if (elements[i].className == "enabled")
                            elements[i].className = "disabled";
                    }
                    selected.className =  "enabled";

                    var contentElements = document.getElementById(contentID).parentNode.childNodes;

                    for (var i = 0; i < contentElements.length; i++)
                    {
                        if (contentElements[i].id != contentID)
                                $('#'+contentElements[i].id).hide();
                    }
                    $('#'+contentID).toggle(0);
                }
                $("#insertID").text(contentID);
	}
}

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

function addMessage() {
   
    var message = $("#myMessage").val();
    var type = $.cookie("sectionID");
    var mediaContent = "";
    
    $("#myMessage").val('').css('height','54px');
    if($("#addVideo").val() != "")
        {
            mediaContent = $("#addVideo").val();
            cancelMedia('Video');
        }
    else if($("#addPhoto").val() != "")
        {
            mediaContent = $("#addPhoto").val();
            cancelMedia('Photo');
            $("#addPhotoFile").val('');
        }
        
    message = (mediaContent == "") ? message : message+" "+mediaContent;

    $(".field_left").find("div#search:visible").fadeOut(250, function(){
        $("#messageContainer").fadeIn(250);
    })

    if(type != 'all_records' && type != 'my_records')
        {
            changeSection('all_records');
            type = "all_records";
        }

        JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'addMessage',
			'message': message
		},

		function(result, answer)
		{
			if(result && result["error"])
			{
                                showPopup(result["alert"]['title'], result["alert"]['content']);
                                return;
			}
                        $("#myMessage").css("height", "66px");
                        $("#myMessage").val("");
                        $("#"+type+"_container div:first").before("<div class='noRecords'><img src='/images/upload.gif' alt=''/></div>");
                        refresh_records(type);
		},true);
}

function showRecords(type,page,userID,limit)
{
    var str = ($("#"+type+"_container div.recordContainer:last").attr("id"));
    var id = str.split('_');
    userID = (userID) ? userID : "";
    page = (page) ? page : "0";
    $("#"+type+"_container .nextMsg").html('<img src="/images/upload.gif"/>');
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'refreshRecords',
                        'page': page,
                        'userID': userID,
			'type': type,
                        'messageID' : id['0'],
                        'limit' : limit
		},

		function(result, answer)
		{
                            $("#"+type+"_container .nextMsg").remove();
                            $("#"+type+"_container div.recordContainer:last").after(result);
                            bind();
		},true);
}

function refresh_records(type,page,userID,preload,newCount)
{
    newCount = (newCount) ? newCount : 0;
    preload = (preload) ? 1 : 0;
    userID = (userID) ? userID : "";
    page = (page) ? page : "0";
    if(type == 'all_records' && preload)
        {
            $("#newMessageBtn").html(preloader_source('27px'));
            changeSection(type,'', true)
        }
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'refreshRecords',
                        'page': page,
                        'userID': userID,
                        'newCount': newCount,
			'type': type
		},

		function(result, answer)
		{
                            if(type == 'all_records' && $("#newMessageBtn").html()){
                                $("#newMessageBtn").html('').remove();
                                checkNewMessages=1;
                            }

                            
                            $("#"+type+"_container").html(result);
                            bind();
		},true);
}

function addNewMessages(type,userID)
{
    var lastID = $("#"+type+"_container").find("div.recordContainer:first").attr('id').split('_');    
    userID = (userID) ? userID : "";
    $("#newMessageBtn").html(preloader_source('23px'));
    $("#"+type+"_container").find('div.newRecords').each(function(){
        $(this).removeClass('newRecords');
    });
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getNewMessages',
                        'userID': userID,
			'type': type,
                        'messageID': lastID['0']
		},

		function(result, answer)
		{
                    $("#newMessageBtn").remove();
                    
                    checkNewMessages=1;
                    
                    $("#"+type+"_container").prepend(result);
                    bind();
		},true);
}

function deleteRecordPopup(record, type, e)
{
    e.cancelBubble = true;
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'deleteRecordPopup',
                'id': record,
                'type': type
        },

        function(result, answer)
        {
                showPopup(result['title'], result['content']);
        },true);
}

function deleteRecord(record)
{
    $("#"+record).unbind('click');
    $("#"+record).hide();  
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'deleteRecord',
                'id': record
        },

        function(result, answer)
        {

        },true);
}

function deleteRecordFromDetail(id)
{
   $("div[id^='"+id+"']").hide();

    var el = $("#"+id+"_container")
    closeDetail('personal',el, true);
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'deleteRecord',
			'id': id
		},

		function(result, answer)
		{

		},true);
}

function bind()
{
    $('.recordContainer').bind('mouseenter',function(){
        $(this).css('background-color','#E6F3FB');
        $("#"+this.id+" div.inactive").show();
        $(this).find('.edit_container').show();
    });
    $('.recordContainer').bind('mouseleave',function(){
        $(this).css('background-color','');
        $("#"+this.id+" div.inactive").hide();
        $(this).find('.edit_container').hide();
    });
}


function editCurrentInfo()
{
    var hgt = $('#statusText').outerHeight()+5;
    var wdt = $('#statusText').width()+2;

    $('#currinfo_editor').css({'top':-hgt, 'left':0});

    $('#currinfo_input').css({'height':$('#current_info').height()+12,'width':wdt});
    $('#currinfo_editor').show();
    
    $('textarea#currinfo_input').autoResize({
        animate : true,
        animateDuration : 150,
        extraSpace : 0
    });

    if ($('#current_info span:first').hasClass('no_current_info'))
        {
            window.currinfoEditing = false;
            $('#currinfo_help').show();
            $('#currinfo_cancel').hide();
            $('#currinfo_input').val('');
        }
    else
        {
            window.currinfoEditing = true;
            $('#currinfo_clear').show();
            $('#currinfo_cancel').show();
            str = $('#current_info span:first').text();
            str = str.replace(/\n/gi,' ');
            str = str.replace(/  /gi,' ');
            $('#currinfo_input').val(str);
        }
        
        

    $('#currinfo_input').focus();

    window.currinfoOld = $('#currinfo_input').val;
    window.currinfoKeydown = function(e) {
        if (e.keyCode == KEY.ESC)
            {
              cancelCurrentInfo();
            }
    };
    window.currinfoCheck = function(el) {

        
        if ($('#currinfo_progress').css('display') != 'none') return;

        var txt = trim(el.value);
        if (txt.length > 140) {
          $('#currinfo_clear').hide();
          $('#currinfo_help').hide();
          $('#currinfo_warning').html('Максимальное число символов - 140.');
          $('#currinfo_warning').show();
        } else if (txt.length > 100) {
          $('#currinfo_clear').hide();
          $('#currinfo_help').hide();
          t = 140 - txt.length;
          $('#currinfo_warning').html('Осталось символов: '+t+'.');
          $('#currinfo_warning').show();
        } else if ($('#currinfo_warning').css('display') != 'none') {

          $('#currinfo_warning').hide();
          if(currinfoEditing)
              $('#currinfo_clear').show();
          else
              $('#currinfo_help').show();
        }
    }
    window.currinfoDoSave = function(txt) {
        if (txt == currinfoOld)
        {
            cancelCurrentInfo();
            return;
        }

//        txt = txt.replace(/(\w{17})/igm,'$1 ');
//        txt = txt.replace(/\s+/igm,' ');
        txt = trim(txt).substr(0, 140);
        
        $('#currinfo_help').hide();
        $('#currinfo_clear').hide();
        $('#currinfo_warning').hide();
        $('#currinfo_progress').show();

        JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updateStatus',
			'newStatus': txt
		},

		function(result, answer)
		{
                    
                    t = result['status'] || 'Изменить статус';
                    $('#current_info').html('<span class="' + result['type'] + '_current_info">' + t + '</span>');
                    cancelCurrentInfo();
		},true);

    }
    window.currinfoSave = function(e) {
        e = e || window.event;
        if (e && e.type == 'keydown' && e.keyCode != 10 && e.keyCode != 13) {
          return;
        }
        var txt = $('#currinfo_input').val();
        currinfoDoSave(txt);
    }
    window.currinfoMousedown = function(e) {
        var t = e.target;

        while (t.parentNode) {
          if (t.id == 'currinfo_editor') {
            return;
          }
          t = t.parentNode;
        }
        cancelCurrentInfo();
    }


    $(window).bind('keydown',currinfoKeydown);
    $(document).bind('mousedown',currinfoMousedown);
}

function cancelCurrentInfo()
{
    $('#currinfo_editor').hide();
    $('#currinfo_help').hide();
    $('#currinfo_clear').hide();
    $('#currinfo_cancel').hide();
    $('#currinfo_progress').hide();
    
    $(window).unbind('keydown');
    $(document).unbind('mousedown');
}

/* friends */


function addFriend(userID, el, e)
{
    var container = $(el).parents("div:first");
    container.html('<div class="loading"><img src="/images/upload.gif"/></div>');
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'addFriend',
			'userID': userID
		},

		function(result, answer)
		{
                        container.html(result);
		},true);
                
    if(e)
        e.cancelBubble = true;
}

function returnFriendApplicationPopup(userID)
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'deleteFriendPopup',
                'userID': userID
        },

        function(result, answer)
        {
                showPopup(result['title'], result['content']);
        },true);
}

function returnFriendApplication(userID, el)
{
    var container = $("#friendMsg");
    container.html('<div class="loading"></div>');

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'returnFriendApplication',
			'userID': userID
		},

		function(result, answer)
		{
                        container.html(result);
		},true);
}

function deleteFriend(userID, recordID)
{
    returnFriendApplication(userID);
    $("#"+recordID).html("<b>Удалено</b>");
}

function closeDetail(show, el, changeHash)
{
    changeHash = (changeHash) ? changeHash : false;
    $('#messageBlock').fadeOut(500);

    if(show == "personal")
        {
            hashHistory = new Array();
            hash = "!";
        }
    else if(changeHash)
            hash = hashHistory.pop();

    $(el).parents("div.windows:visible").fadeOut(500,function () {
                $('#'+show).fadeIn(500);
            });

    if(changeHash)
    {
        needUpdateFromHash = false;
        location.hash = hash;
    }
    
    return false;
}

function drawDetailNewWindow(result, show, cookieValue, message)
{
   var time = 300;
   
   if(result)
   {
       $("#serverRequest").text("0");
   }
   else if($("#serverRequest").text() != 1)
   {
       time = 1;
       $("#serverRequest").text("1");
       result = preloader_source();
   }
   else
   {
        return true;
   }

   $('#messageBlock').fadeOut(time);
   $(document).find("td.field_right div.windows:visible").each(function(){
      $(this).fadeOut(time,function () {
                if(result)
                    $("#"+show).html(result);
                
                $("#"+show).fadeIn(time);
                if(message)
                    $('#messageBlock').html(message).fadeIn(time);
                else
                    $('#messageBlock').html('');

                if(cookieValue)
                    $.cookie(show, cookieValue);
            });
   });

   return false;
}

function showUser(userID,e)
{
    var hash = location.hash;

    if (hash != "#users/"+userID)
        {
            hashHistory.push(hash);
            location.hash = "users/"+userID;
        }
    if(e) 
        e.cancelBubble = true;
    
    return false;
}

function showUserFromHash(userID)
{
    if(isNaN(userID))
        return;
 
    var showID = 'users';
    var backOthers = ($("#personalOthers:visible").length == 1) ? "1" : "0";
    if(drawDetailNewWindow('',showID))
    {
        return;
    }
    checkScrolling();
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getUser',
			'userID': userID,
                        'backOthers' : backOthers
		},
		function(result, answer)
		{
                        drawDetailNewWindow(result,showID);
		},true);
}

function sendMessage(userID, back ,e)
{
    var hash = location.hash;

    if (hash != "#message/"+userID)
        {
            hashHistory.push(hash);
            location.hash = "message/"+userID;
            hashType = back;
        }
    if(e)
        e.cancelBubble = true;
}

function sendMessageFromHash(userID)
{
    userID = (userID) ? userID : "";

    var showID = 'usersOthers';
    var closeShowUser = (hashHistory.length == 0 && userID != parentUser) ? 1 : 0;
    var back = (userID == parentUser) ? "personal" : "users";
    back = (hashType == 'personalOthers') ? hashType : back;
    if(drawDetailNewWindow('',showID))
        {
            return;
        }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'sendPrivateMessage',
			'userID': userID,
                        'back': back,
                        'closeShowUser': closeShowUser
		},
		function(result, answer)
		{
                        drawDetailNewWindow(result['text'],showID);
                        hashType = result['close'];
		},true);
}

function sendPM(el, switchBlock)
{
    var userID = ($("#recipient").val()) ? $("#recipient").val() : $("#friends").val();    
    var container = $(el).parents("div.pmContainer");
    var message = container.find("#privateMsg").val();
    var answerID = ($("#answerID").val()) ? $("#answerID").val() : 0 ;
    updateHash = (hashType == "personalOthers" && !switchBlock) ? 0 : 1;

    var preloader = container.find("div.preloader");
    preloader.show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'sendPM',
			'userID': userID,
                        'answerID' : answerID,
                        'message': message
		},
		function(result, answer)
		{
			/*
                    if(result['error']['content'])
                    {
                        preloader.hide();
                        showPopup(result['error']['title'], result['error']['content']);
                    }
                    else
                    */
                    {
                        preloader.hide();
                        if(!updateHash || switchBlock)
                            {
                                updatePmailList();
                            }
                        if(switchBlock)
                        {
                            $("#privateMsg").val('');
                            $("#friends").val('');
                            switchInsert("pm","inbox");
                        }
                        else
                        {
                            closeDetail(hashType, $("#sendBox"), updateHash);
                        }
                        $("#messageBlock").html(result['icon']);
                        $("#messageBlock").fadeIn(500);
                    }
		},true);
}

function showMail(active)
{
    active = active || "inbox";
    var hash = location.hash;
    if (hash != "#mail")
        {
            hashHistory.push(hash);
            hashType = active;
            newPmail('inbox');
            newPmail('invites');
        }
    else
        {
            changeWindow("usersOthers","personalOthers");
            updatePmailList();
            switchInsert("pm",active);
        }
        
    location.hash = "mail";
}

function showMailFromHash()
{
    var showID = 'personalOthers';

    if(drawDetailNewWindow('',showID))
        {
            return;
        }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showMail',
                        'active': hashType
		},
		function(result, answer)
		{
                    drawDetailNewWindow(result,showID);
		},true);
}

function showPM(id, type)
{
    var showID = "usersOthers";
    if(drawDetailNewWindow('',showID))
    {
        return;
    }
    checkScrolling();
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showPM',
                        'type' : type,
                        'mailID' : id
		},
		function(result, answer)
		{
                    drawDetailNewWindow(result['text'],showID);
                    hashType = result['close'];
                    
                    if($("#"+id).hasClass("newMail"))
                    {
                        $("#"+id).removeClass("newMail");
                        newPmail(type);
                    }
		},true);
}

function deletePM(id, type, e)
{
    $("#"+id).hide();
    e.cancelBubble = true;
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'deletePM',
                        'id' : id
		},
		function(result, answer)
		{
                    
		},true);
    
    var countRows = $("#"+type+"_container").find("div.row:visible").length;
    var page = $("#"+type+"Page").text();
    
    if(countRows == 0)
        {
            preloader = preloader_source("100px");
            $("#"+type+"_container").html(preloader);
            if(type == "invites")
            {
                JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showGames',
                        'type' : type,
                        'page' : page,
                        'returnContent' : true
		},
		function(result, answer)
		{
                        $("#"+type+"_container").html(result['content']);
                        checkScrolling();
		},true);
            }
            else
            {
                updatePmail(type,'',page);
            }
        }
        
    newPmail(type)
}

function updatePmail(type, userID, page, el)
{
    if(el)            
        $(el).parents("div:first").find("div.loadingPage").show();
    
    page = (page) ? page : 0;
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updatePmail',
                        'type' : type,
                        'page' : page
		},
		function(result, answer)
		{        
                    $("#"+type+"_container").html(result['content']);
		},true);
}

function newPmail(type)
{
    type = type || "inbox";
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'newPmail'
		},
		function(result, answer)
		{                       
                    $("#newMailCount"+type).text(result[type]);
                    if($("#newMailContainer"+type+":visible").length == 0 && result[type] != 0)
                            $("#newMailContainer"+type).show();
                    else if($("#newMailContainer"+type+":visible").length != 0 && result[type] == 0 )
                            $("#newMailContainer"+type).hide();
		},true);
}

function updatePmailList(page)
{
    page = (page) ? page : 0;
    updatePmail('inbox','',page);
    updatePmail('outbox','',page);
    newPmail('inbox');
}

function showGames(active)
{
    active = active || "new";
    var hash = location.hash;
    if (hash != "#games/"+active)
        {
            hashHistory.push(hash);
        }
        
    location.hash = "games/"+active;
}

function showGamesFromHash(active)
{
    if($("#gamesContainer").length == 1 && $("#personalOthers:visible").length == 1)
    {
        switchInsert("gamesContainer",active);
        return;
    }
    
    var showID = 'personalOthers';
    if(drawDetailNewWindow('',showID))
        {
            return;
        }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showGames',
                        'active': active
		},
		function(result, answer)
		{
                    drawDetailNewWindow(result,showID);
		},true);
}

function showFriends(userID, showID)
{
    var hash = location.hash;

    if (hash != "users/"+userID)
        {
            hashHistory.push(hash);
            location.hash = "friends/"+userID;
        }
}

function showFriendsFromHash(userID, page)
{ 
    var showID = (userID == parentUser) ? 'personalOthers' : 'usersOthers';
    var closeShowUser = (hashHistory.length == 0 && userID != parentUser) ? 1 : 0;
    var id = 'friendsBlock';
    
    if(drawDetailNewWindow('',showID))
        {
            return;
        }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getFriends',
			'userID': userID,
                        'page': page,
                        'parentUser': parentUser,
                        'closeShowUser': closeShowUser,
                        'id' : id
		},
		function(result, answer)
		{
                        drawDetailNewWindow(result,showID);
		},true);
}

function showSubscribersStats()
{
    var hash = location.hash;
    

    if (hash != "#rating/subscribers")
        {
            hashHistory.push(hash);
            location.hash = "rating/subscribers";
        }
}

function showSubscribersStatsFromHash()
{
    var showID = 'personalOthers';

    if(drawDetailNewWindow('',showID))
    {
        return;
    }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showSubscribersStats',
                        'page' : 0
		},
		function(result, answer)
		{
                        drawDetailNewWindow(result,showID);
		},true);
}

function showSubscriptions(userID,type, showID)
{
    var hash = location.hash;

    if (hash != "#subscribe/"+userID)
        {
            hashHistory.push(hash);
            location.hash = "subscribe/"+userID;
            hashType = type;
        }
}

function showSubscriptionsFromHash(userID)
{
    showID = (userID != parentUser) ? 'usersOthers' : 'personalOthers';

    type = hashType;
    if(drawDetailNewWindow('',showID))
        {
            return;
        }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getSubscriptions',
                        'type' : type,
                        'parentUser' : parentUser,
			'userID': userID
		},
		function(result, answer)
		{
                        drawDetailNewWindow(result,showID);
		},true);
}

function show_detail_record(record, type, edit, e)
{
    var hash = location.hash;
    if($("#serverRequest").text() == 1)
        return;
    
    recordArray = record.split("_");
    
    if (hash != "#record/"+recordArray['0']+"/"+edit || hash != "#record/"+recordArray['0']+"/")
    {
        hashHistory.push(hash);
        location.hash = "record/"+recordArray['0']+"/"+edit;
        hashType = type;
    }
    else 
    {
        checkScrolling();
    }

    e.cancelBubble = true;
}

function showDetailRecordFromHash(record, edit)
{
    edit = (edit) ? edit : 0;
    showID = (hashType == 'foreign_records') ? 'usersOthers' : 'personalOthers';
    checkScrolling();
    
    if(drawDetailNewWindow('',showID))
    {
        return;
    }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showRecord',
			'id': record,
                        'edit' : edit,
                        'page' : 0,
                        'type' : 'record',
                        'showID' : showID
		},

		function(result, answer)
		{                    
                    drawDetailNewWindow(result,showID);
		},true);
}

function privateInfo(act)
{
    var hash = location.hash;

    if (hash != "#edit/"+act)
        {
            hashHistory.push(hash);
            location.hash = "edit/"+act;
        }
}

function privateInfoFromHash(act)
{
    var showID = 'personalOthers';
    var func = (act == 'design') ? "designSetting" : "getInfoEditing";

    if(drawDetailNewWindow('',showID))
    {
        return;
    }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': func,
                        'act' : act
		},
		function(result, answer)
		{
                        if(act == 'main_info')
                        {
                            familyArray = result['familyArray'];
                        }
                            
                        drawDetailNewWindow(result['content'],showID);
                        if(act == 'design')
                            hideBranding();
		},true);
}

function designCancel(obj){
    var showID = 'personal';

    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'drawBodyStyle'
        },

        function(result, answer)
        {
            $("body").attr('style',result);
            $('#messageBlock').html('');
            closeDetail(showID, obj, true);
            showBranding();
        }
    ,true);
}

function sendGift(id,name)
{
    var hash = location.hash;

    if (hash != "#gift/"+id)
        {
            hashHistory.push(hash);
            location.hash = "gift/"+id;
            hashType = name;
        }
}
function sendGiftFromHash(id)
{
    var showID='usersOthers';
    name = hashType;

    if(drawDetailNewWindow('',showID))
    {
        return;
    }

    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'showGifts',
                'userID': id,
                'userName':name
        },

        function(result, answer)
        {
            drawDetailNewWindow(result,showID);
        },true);
}


function sendGiftForm(giftID,userID){
    
    var showID='usersOthers';
    
    if(drawDetailNewWindow('',showID))
    {
        return;
    }
    
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'sendGiftForm',
                'giftID': giftID,
                'userID': userID
        },

        function(result, answer)
        {
            drawDetailNewWindow(result,showID);
            //changeWindow('gift_win2','gift_win2',result);
        },true)

    /*
    changeWindow('gift_win1','gift_win2',preloader_source(),1);

    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'sendGiftForm',
                'giftID': giftID,
                'userID': userID
        },

        function(result, answer)
        {
            changeWindow('gift_win2','gift_win2',result);
        },true)
        */
}

function changeWindow(win1,win2,result,fadeTime){
      if(fadeTime=='') fadeTime=250;
      $('#'+win1).fadeOut(fadeTime,function () {
          if(result) $('#'+win2).html(result);
          $('#'+win2).fadeIn(500);
      });
}

function sendGiftFinal(giftID,userID,price,isBooster){
    var showID='users';

    var comment = $("#giftComment").val();
    var isPrivate = $("#giftIsPrivate:checked").length;

    if(drawDetailNewWindow('',showID))
    {
        return;
    }

    checkScrolling(1);
    
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'sendGiftFinal',
                'giftID': giftID,
                'userID': userID,
                'price': price,
                'isBooster': isBooster,
                'comment': comment,
                'isPrivate': isPrivate
        },

        function(result, answer)
        {

                hash = hashHistory.pop();
                needUpdateFromHash = false;
                location.hash = hash;

                drawDetailNewWindow(result[1],'usersOthers','',result[0]);

        },true)

}

function sendFeedbackMessage(){
    var msg = $('#fbMessage').val();

    if(jQuery.trim(msg)){
        $('#fbMsgBlock').html(preloader_source());
        $('.preloader').css({height: '90px'});

        JsHttpRequest.query('/ajax_functions.php',
            {
                    'function': 'sendFeedbackMessage',
                    'msg' : msg
            },

            function(result, answer)
            {
                $('#fbMsgBlock').html(result);
            },true)
    }else{
        $('#fbMsgError').stop(true,true).show();
        $('#fbMsgError').html('<img src="/images/icons/spamFriend.png" style="margin-right:5px;"><b>Пожалуйста, напишите сообщение!</b>');
        $('#fbMsgError').fadeTo(1000,0.99).fadeOut(250);
    }
}

function showEmpty(){
    var hash = location.hash;

    if (hash != "#inwork")
        {
            hashHistory.push(hash);
            location.hash = "inwork";
        }
}

function showWorkWindow()
{
    showID = 'personalOthers';

    if(drawDetailNewWindow('',showID))
        {
            return;
        }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showWorkWindow'
		},
		function(result, answer)
		{
                        drawDetailNewWindow(result,showID);
		},true);
}

function showPhoto(userID)
{
    var hash = location.hash;

    if (hash != "#photo/"+userID)
        {
            hashHistory.push(hash);
            location.hash = "photo/"+userID;
        }
    
}

function showPhotoFromHash(userID, showID)
{
    showID = (showID) ? showID : 'usersOthers';
    if(!userID)
        {
            location.hash = "!";
            return;
        }
    if(drawDetailNewWindow('',showID))
        {
            return;
        }
        
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getPhoto',
			'userID': userID

		},
		function(result, answer)
		{
                        drawDetailNewWindow(result,showID);
		},true);
}

function createAlbum(el, userID)
{
    var title = ($("#titleAlbum").val());    
    var container = $(el).parents("div.pmContainer");
    var description = container.find("#descriptionAlbum").val();
    var permissions = $("#permissions").val();
    var preloader = container.find("div.preloader");
    preloader.show();
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function' : 'createAlbum',
			'title' : title,
                        'description' : description,
                        'permissions' : permissions

		},
		function(result, answer)
		{
                    if(result['error'])
                    {
                        preloader.hide();
                        alert(result['error']);
                    }
                    else
                    {                        
                        location.hash= "photo/"+userID+"/"+result['id'];
                        $("#messageBlock").html(result['icon']);
                        $("#messageBlock").fadeIn(500, function(){
                            setTimeout('$("#messageBlock").hide()', 3000);
                        });
                    }
		},true);
}

function updateAlbums(type, userID, page, el)
{
    if(el)            
        $(el).parents("div:first").find("div.loadingPage").show();
    
    updateAlbumsWithPage(userID, page, 'gallery_container');
}

function updateAlbumsWithPage(userID, page, id)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function' : 'updateAlbums',
			'userID' : userID,
                        'page' : page

		},
		function(result, answer)
		{
                    $("#"+id).html(result);
                    checkScrolling();
		},true);
}

function showAlbum(id, page, userID, type)
{
    type = (type) ? type : "";
    hash = "photo/"+userID+"/"+id;
    hash = (type) ? hash+"/"+type : hash;
    var showID = "usersOthers";
    if(drawDetailNewWindow('',showID))
        {
            return;
        }
    checkScrolling();
        
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showPhoto',
			'userID': userID,
                        'id' : id,
                        'page' : page,
                        'type' : type

		},
		function(result, answer)
		{
                        if(result['error'] == false)
                        {
                            photos = result['photos'];
                        }
                            
                        drawDetailNewWindow(result['content'],showID);
		},true);
    
    if(location.hash != "#"+hash)
        {
            hashHistory.push(hash);
            location.hash = hash;
        }
        
}

function updateAlbum(userID, id, page, popupID, updatePopup)
{
    var container = $("#photos_container");
    container.find("div.loadingPage").show();
        
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showPhoto',
			'userID': userID,
                        'id' : id,
                        'page' : page,
                        'returnPhotos' : true
		},
		function(result, answer)
		{
                        if($("#photos").hasClass('dis'))
                            switchInsert("photosMain","photos");
                       
                        checkScrolling();
                        container.html(result['content']);    
                        photos = result['photos'];
                        if(updatePopup)
                            showPhotoPopup(popupID);
		},true);
}

function editAlbum(id, el)
{
    var title = ($("#titleAlbum").val());    
    var container = $(el).parents("div.pmContainer");
    var description = container.find("#descriptionAlbum").val();
    var permissions = $("#permissions").val();
    var preloader = container.find("div.preloader");
    preloader.show();
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'editAlbum',
                        'id': id,
			'title': title,
                        'description' : description,
                        'permissions' : permissions
		},
		function(result, answer)
		{ 
                    $("#messageBlock").html(result['icon']);
                    $("#messageBlock").fadeIn(500, function(){
                        setTimeout('$("#messageBlock").hide()', 3000);
                    });
                 
                    preloader.hide();
		},true);
}

function deleteAlbumPopup(id)
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'deleteAlbumPopup',
                'id': id
        },
        function(result, answer)
        {   
            showPopup(result['title'], result['content']);
        },true);
}

function deleteAlbum(id)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'deleteAlbum',
                        'id': id
		},
		function(result, answer)
		{   
                    $("#messageBlock").html(result['icon']);
                    $("#messageBlock").fadeIn(500, function(){
                        setTimeout('$("#messageBlock").hide()', 3000);
                    });
                    
                    if(result['userID'])
                        location.hash = "photo/"+result['userID'];
		},true);
}

function showPhotoPopup(id)
{
    if($("#layer_wrap:visible").length == 0)
        {
            $("#layer_bg").css('display', 'block');
            $("#layer_wrap").css('display', 'block');
            $("#div_container").css('overflow', 'hidden');
            $("#layer_wrap").bind('click', function(e){
                if(e.target.id == 'layer' || e.target.id == 'layer_wrap')
                    closePopup();
            })
        }

    if(!photos['content'][id] && id > 0)
    {
            if(photos['navi']['next'] == 0 && photos['navi']['prev'] == 0 && photos['navi']['page'] == 0)
            {
                showPhotoPopup(1);
            }
            else
                updateAlbum(photos['UserID'], photos['id'], photos['navi']['next'], 1, true);
    }
    else if(id == 0)
    {
            if(photos['navi']['next'] == 0 && photos['navi']['prev'] == 0 && photos['navi']['page'] == 0)
            {
                showPhotoPopup(photos['navi']['prevID']);
            }
            else
                updateAlbum(photos['UserID'], photos['id'], photos['navi']['prev'], photos['navi']['prevID'], true); 
    }
    else 
    {
            content = photos['pattern'].replace('%URL%',photos['content'][id]['URL']).replace('%COMMENTS%',photos['content'][id]['COMMENTS']).replace('%STATLIKES%',photos['content'][id]['STATLIKES']).replace('%DATE%',photos['content'][id]['DATE']).replace('%DESCRIPTION%',photos['content'][id]['DESCRIPTION']).replace('%ACTIONS%',photos['content'][id]['ACTIONS']).replace('%NEXT%',photos['content'][id]['NEXT']).replace('%NEXTIMG%',photos['content'][id]['NEXT']).replace('%PREV%',photos['content'][id]['PREV']).replace('%TITLE%',photos['content'][id]['TITLE']);
            $("#layer").html(content);
            showPhotoComment(photos['content'][id]['ID']);
    }
}

function showPhotoComment(id)
{
    JsHttpRequest.query('/ajax_functions.php',
                {
                        'function': 'getPhotoComments',
                        'photoID': id
                },
                function(result, answer)
                {   
                     $("#photoComments").html(result);
                },true);
}


function photoDesc()
{
    $("#photoDesc").hide();
    $("#photoDescCont").show();
    if($("#photoDescText").html())
        $("#photoDescEdit").val($("#photoDescText").html().replace(/<br>/g,'\n'));
}

function photoDescAdd(id, imageID)
{
    var description = $("#photoDescEdit").val();
    JsHttpRequest.query('/ajax_functions.php',
                {
                        'function': 'photoDescAdd',
                        'imageID': imageID,
                        'id': id,
                        'desc': description
                },
                function(result, answer)
                {   
                     if(result['error'])
                     {
                         alert(result['error']);
                     }
                     else 
                     {
                         $("#photoDesc").html(result['desc']);
                         photos['content'][id]['DESCRIPTION'] = result['source'];
                         photoDescCancel();
                     }
                },true);
}

function photoDescCancel()
{
    $("#photoDescCont").hide();
    $("#photoDesc").show();
}

function deletePhotoPopup(id)
{   
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'deletePhotoPopup',
                'id': id
        },
        function(result, answer)
        {
                showPopup(result['title'], result['content']);
        },true);
}

function deletePhoto(id)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'deletePhoto',
                        'id': photos['content'][id]['ID']
		},
		function(result, answer)
		{   
                     updateAlbum(photos['UserID'], photos['id'], photos['navi']['page'], id , true); 
		},true);
}

function closePopup()
{
    $("#layer_bg").css('display', 'none');
    $("#layer_wrap").css('display', 'none');
    $("#div_container").css('overflow', '');
    $("#layer_wrap").unbind('click');
    resizeMainWindow();
}

function coverAlbum(galleryID, photoID)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'coverAlbum',
                        'galleryID': galleryID,
                        'photoID': photoID
		},
		function(result, answer)
		{   
                     showPopup(result['title'], result['content']);
		},true);
}

function showAlbumsList(id)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getAllAlbumsList',
                        'id' : id,
                        'albumID' : photos['id']
		},
		function(result, answer)
		{   
                    $("#switchPhoto").hide();
                    $("#switchPhoto").after(result);
    		},true);
}

function switchPhotoCancel()
{
    $("#switchPhotoSelect").remove();
    $("#switchPhoto").show();
}

function switchPhoto(id)
{
    var galleryID = $("#albumsLists").val();
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'switchPhoto',
                        'galleryID': galleryID,
                        'id': photos['content'][id]['ID']
		},
		function(result, answer)
		{   
                         updateAlbum(photos['UserID'], photos['id'], photos['navi']['page'], id , true); 
    		},true);
    
}

function imageLike(imageID, statusID, id)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'photoLike',
                        'imageID': imageID,
                        'statusID': statusID,
                        'id': id
		},
		function(result, answer)
		{       
                    $(".photoAction").html(result['likes']);
                    $("#statLikes").html(result['likesStat']);
                    photos['content'][id]['STATLIKES'] = result['likesStat'];
                    photos['content'][id]['ACTIONS'] = result['likes'];
    		},true);

}

function addCommentPhoto(photoID, id, el)
{
    var comment = $(el).parents("div.comments-add-textarea").find(".comments-add-msg");
    var commentMessage = comment.val();
    comment.val('');
    $("#photoComments").prepend("<div class='preloader' style='height: 60px; width:412px;'></div>");
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function' : 'addCommentPhoto',
                'id' : id,
                'photoID': photoID,
                'comment': commentMessage
        },
        function(result, answer)
        {
                if(result['error'])
                {
                        showPopup(result['title'], result['content']);
                        $("#photoComments div.preloader").remove();
                        return;
                }
                $("#photoComments").html(result['content']);
        },true);
}

function quoteMessage(id, type, ev)
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function' : 'quoteMessage',
                'id' : id,
                'type' : type
        },
        function(result, answer)
        {
               $(".quote_"+id).html(result['html']); 
        },true);
        ev.cancelBubble = true;
}

function addLook(id, ev, el)
{
    if($(el).hasClass('lookAddActive'))
        {
            $(el).removeClass('lookAddActive');
            type = -1;
            $("#check_"+id).removeAttr('checked');
            $(el).attr("title","Cледить за комментариями");
        }
        else
        {
            $(el).addClass('lookAddActive');
            type = 1;
            $("#check_"+id).attr('checked','checked');
            $(el).attr("title","Не следить за комментариями");
        }
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'addLook',
                        'id': id,
                        'type': type
		},
		function(result, answer)
		{   
                     
		},true);
                
    if(ev)
            ev.cancelBubble = true;
}

function closePreloader()
{
    $("#photopreloader").hide();
}

function checkAddMessage(event)
{
    if (event.ctrlKey && event.keyCode==KEY.ENTER)
    {
        addMessage();
    }
}
function checkSendMail(event,el)
{
    if (event.ctrlKey && event.keyCode==KEY.ENTER)
    {
        sendPM(el);
    }
}

function checkSend(event){
    if(event.keyCode==KEY.ENTER) 
    {
        searchWithType();
    }
}

function checkBox(id)
{
    $("#pauth_remember.checkbox").toggleClass('checkboxShadow');
    $("#pauth_remember.checkbox").toggleClass('checkboxActive');
    $("#pauth_remember.checkbox").find('input:hidden:first').each(function(){
        val = ($(this).val() == "1") ? '0' : '1';
        $(this).val(val);
    });
}

function resizeMainWindow()
{
        var windowHeight = ($("#branding").height() < $(window).height()) ? $(window).height() : $("#branding").height();
        var windowWidth = $(window).width();
        $(".main_container").height(windowHeight-8);
        $("#layer_bg").height(windowHeight);
        $("#layer_wrap").height(windowHeight);
        $("#layer").width(windowWidth);
        $("#div_container").height(windowHeight);
}

function subscriptionAdd(userID, el, e)
{
    var container = $(el).parents("div:first");
    container.html('<div class="loading"></div>');
    
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'subscriptionAdd',
			'userID': userID
		},

		function(result, answer)
		{
                        container.html(result);
		},true);
    e.cancelBubble = true;
}

function subscriptionDelete(userID, el, e)
{
    var container = $(el).parents("div:first");
    container.html('<div class="loading"></div>');

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'subscriptionDelete',
			'userID': userID
		},

		function(result, answer)
		{
                        container.html(result);
		},true);
                
    e.cancelBubble = true;
}

function showAddForm()
{
    $(".commentAddLink").hide();
    $(".commentAdd").fadeIn(250);

}

function addComment(id, el)
{
    var comment = $(el).parents("div.message:first").find(".comments-add-msg");  
    var w = ($("#check_"+id).attr('checked') == true) ? 1 : 0;
    var commentMessage = comment.val();
    $(".lookCheckBox").hide();
    comment.val('');
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function' : 'addComment',
                'id' : id,
                'w' : w,
                'comment': commentMessage
        },
        function(result, answer)
        {
                if(result['error'])
                {
                        showPopup(result['error']['title'], result['error']['content']);
                        return;
                }
                if(w == 0 && $("#look_"+id).hasClass('lookAddActive'))
                    {
                        $("#look_"+id).removeClass('lookAddActive');
                        $("#look_"+id).attr("title","Cледить за комментариями");
                    }
                else if(w == 1 && !$("#look_"+id).hasClass('lookAddActive'))
                    {
                        $("#look_"+id).addClass('lookAddActive');
                        $("#look_"+id).attr("title","Не следить за комментариями");
                    }
                $(".comments-container").html(result);
        },true);
}

function updateAvatar(id){

    var d = new Date();
    $("#others img").remove();
    $("#others td:[width=400]").prepend("<img src='/images/ut_users/small/"+id+".jpg?reload="+d.getTime()+"'>");
    $("#profilePhoto img").attr('src',"/images/ut_users/small/"+id+".jpg?reload="+d.getTime());
    $("#personalOthers").fadeOut(250, function(){
        $("#personal").fadeIn(250);
    });
    location.hash = "!";
}

function updateMainInfo(id)
{
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updateMainInfo',
                        'id' : id
		},
		function(result, answer)
		{
                        $("#fullName").html(result['fullName']);
                        $("#mainInfo").html(result['mainInfo']);
		},true);
}

function updateFriends(type, userID, el, e)
{
    var container = $(el).parents("div:first");
    container.html('<div class="loading" style="height:25px;"></div>');
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updateFriends',
                        'type' : type,
                        'userID' : userID
		},
		function(result, answer)
		{
                    
                    $('#all_container').html('<div class="loading" style="height:52px; line-height: 52px; margin-top: 8px;"><img src="/images/upload.gif"/></div>');
                    updateFriendsBlock('all',result[1],0,$('#all_container div:first'), 0);

//                    $('#online_container').html('<div class="loading" style="height:52px; line-height: 52px; margin-top: 8px;"><img src="/images/upload.gif"/></div>');
//                    updateFriendsBlock('online',result[1],0,$('#online_container div:first'), 0);
                   
                    var newFriendsNummber = $('#newFriendsNumber').html();
                    
                    if(newFriendsNummber == 1) $('span#newFriends').html('');
                    else
                    {
                        newFriendsNummber --;
                        $('#newFriendsNumber').html(newFriendsNummber);
                    }

                    container.html(result[0]);

		},true);
                e.cancelBubble = true;
}

function updateFriendsBlock(type, userID, page, el, scrolling)
{
    scrolling = (scrolling != 0) ? 1 : 0;
    var container = $(el).parents("div.blockContainer:first");
    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updateFriendsBlock',
                        'type' : type,
                        'userID' : userID,
                        'page' : page
		},
		function(result, answer)
		{
                    container.html(result);
                    if(scrolling)
                        checkScrolling();
		},true);
}


function openMoreMenu(el,e)
{
    menu = $(el).parents("div:first").next("div.moreMenu:hidden");
    menu.css('display', 'block');
    
    window.moreMenuMousedown = function(e)
    {
        t=e.target;
        if ($(t).parents("div:first").hasClass('moreMenu'))
            return;
        else
            $(document).find("div.moreMenu").each(function(){
                $(this).fadeOut(300);
                $(document).unbind('mousedown');
            })
    }

    $(document).bind('mousedown',moreMenuMousedown);
    e.cancelBubble = true;
}

function closeMoreMenu(el)
{
    $(el).parents('div.moreMenu').fadeOut(300);
}

function menuClick(e)
{
    e.cancelBubble = true;
}

function updateSearchBlock(type, userID, page, el)
{
    var container = $("#search_result_container");
    var query = $('#search_query').val();

    
    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
                            'function' : 'search',
			'type' : type,
                        'query' : query,
                        'page' : page,
                        'returnContent' : true
		},
		function(result, answer)
		{
                    container.html(result);
                    bind();
		},true);
}

function updateApplicationsBlock(type, userID, page, el)
{
    var container = $(el).parents("div.blockContainer:first");
    container.find("div.loadingPage").show();


    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showGames',
                        'type' : type,
                        'page' : page,
                        'returnContent' : true
		},
		function(result, answer)
		{
                        container.html(result);
                        checkScrolling();
		},true);
}

function updateSubscribeStatsBlock(type, userID, page, el)
{
    var container = $(el).parents("div.blockContainer:first");
    container.find("div.loadingPage").show();


    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showSubscribersStats',
                        'type' : type,
                        'page' : page,
                        'returnContent' : true
		},
		function(result, answer)
		{
                        container.html(result);
                        checkScrolling();
		},true);
}

function updateSubcsribeBlock(type, userID, page, el)
{
    var container = $(el).parents("div.blockContainer:first");
    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getSubscriptions',
                        'page' : page,
                        'type' : type,
                        'userID' : userID,
                        'returnContent' : true
		},
		function(result, answer)
		{
                        container.html(result);
		},true);
}

function updateCommentsBlock(type, messageID, page, el)
{
    var container = $(el).parents("div.comments-container:first");
    
    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showRecord',
                        'page' : page,
                        'id' : messageID,
                        'type' : type,
                        'returnComments' : true
		},
		function(result, answer)
		{
                        container.html(result);
		},true);
}

function updateUsersGifts(type,user,page)
{
    var container = $('#'+type+'_container');
    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updateUsersGifts',
                        'user' : user,
                        'page' : page
		},
		function(result, answer)
		{
                        container.html(result);
		},true);
}

function updateGifts(type,user,page,el)
{
    
    var container = $(el).parents("div.blockContainer:first");
    $(this).parents('.blockContainer');
    
    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'updateGifts',
                        'type' : type,
                        'user' : user,
                        'page' : page
		},
		function(result, answer)
		{
                        container.html(result);
		},true);
}

function searchNoAjax()
{
    if(checkSearch == false)
        {
            return;
        }
        
     $('#search_form').submit();   
}

function searchWithType(page)
{
    if(checkSearch == false)
        {
            return;
        }
    
    var type = $('#search_in').val();
    var query = $('#search_query').val();
    page = (page) ? page : 0;
    var hideId = ($("#search:visible").length == "1") ? "search" : "messageContainer";
    
    $("#"+hideId).fadeOut('1', function(){
        $("#search").html("<div class='noRecords'><img src='/images/upload.gif' alt=''/></div>");
        $("#search").fadeIn('1');
        
        JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'search',
			'type': type,
                        'query': query,
                        'page' : page
		},

		function(result, answer)
		{                     
                    $("#"+hideId).fadeOut('1', function(){
                        $("#search").html(result);
                        $("#search").fadeIn('1');
                    });
                    bind();
		},true);
    });
}

function getPayment(step,paytype,title, paysubtype)
{
    var showID = 'usersOthers';
    paysubtype = (paysubtype) ? paysubtype : '';

    if(drawDetailNewWindow('',showID))
    {
        return;
    }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getPayment',
                        'step' : step,
                        'title' : title,
                        'paytype' : paytype,
                        'paysubtype' : paysubtype
		},
		function(result, answer)
		{
                        checkScrolling();
                        drawDetailNewWindow(result,showID);
		},true);
}

function applyEdit(id, el)
{
    var container = $(el).parents('div.message:first').find('div.msg-row-text');
    var message = $('#messageEditor').val();
    var containerEdit = $(el).parents('div#editFunctions');
    var updateAllRec = ($('#'+id+'_all_records').length == 0) ? false : true;
    var updateMyRec = ($('#'+id+'_my_records').length == 0) ? false : true;
    containerEdit.html('<img src="/images/upload.gif"/>');

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'applyEdit',
			'message': message,
                        'messageID': id
		},

		function(result, answer)
		{
                        if(result['error'])
                        {
                            containerEdit.html(result['editFunctions']);
                            showPopup(result['error']['title'], result['error']['content']);
                            return;
                        }
                        
                        $('#messageEditor').hide();
                        container.html(result['message']);
                        container.show();
                        containerEdit.html('');
                        containerEdit.hide();
                        $("div.editContainer").show();
                        if(updateAllRec)
                            $('#'+id+'_all_records div.msg-row-text').html(result['shortMessage']);
                        if(updateMyRec)
                            $('#'+id+'_my_records div.msg-row-text').html(result['shortMessage']);

		},true);
}

function cancelEdit(id, el)
{
    containerEdit = $(el).parents('div.message:first').find('div#editFunctions');
    containerEdit.html('<img src="/images/upload.gif"/>');
    containerEdit.hide();
    containerEdit.html('');
    $("#messageEditor").hide();
    $("#messageText").show();
    $("div.editContainer").show();
}

function editMessage(id, el)
{
    var container = $(el).parents('div.message:first').find('div.msg-row-text');
    var containerTextarea = $("#messageEditor");
    var containerEdit = $(el).parents('div.message:first').find('div#editFunctions');
    
    $("div.editContainer").hide();
    containerEdit.html('<img src="/images/upload.gif"/>');
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'editMessage',
                        'messageID': id
		},

		function(result, answer)
		{
                        containerTextarea.height(container.height());
                        autoResizeTextarea("textarea#messageEditor");
                        containerTextarea.val(result['message']);
                        containerTextarea.show();
                        container.hide();
                        containerEdit.html(result['editFunctions']);
                        containerEdit.show();
		},true);

}

function autoResizeTextarea(id)
{
    $(id).autoResize({
        onResize : function() {
            $(this).css({opacity:0.8});
        },
        animateCallback : function() {
            $(this).css({opacity:1});
        },
        animateDuration : 150,
        extraSpace : 0
    });
}

function preloader_source(height){
    height = (height) ? height : "150px";
    return "<div class='preloader' style='height: "+height+"'></div>";
}


function getNewPhotos(data)
{
 
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'getNewPhotos',
                'data': data
        },
        function(result, answer)
        {
            $("#newPhotos").html(result);
        },true)

        
}

function commentDeletePopup(id, type)
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'deleteCommentPopup',
                'id': id,
                'type': type
        },

        function(result, answer)
        {
                showPopup(result['title'], result['content']);
        },true);
}

function commentDelete(id, type)
{
    $(".comment_"+id).hide();
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function' : 'deleteComment',
                'type' : type,
                'id' : id
        },
        function(result, answer)
        {
        },true);
}

function needLoginBox(e){
    if($("#needAuthTxt:visible").length == 0)
        {
            $("#needAuthEr").text('');
            $("#needAuthTxt").show();
            $("#auth_name").focus();
        }
    else
        $("#auth_name").focus();
    
    if(e) e.cancelBubble = true;
}

function setNewDesign(designID,style,obj){
    $('.block').removeClass('selected_picture');
    $(obj).addClass('selected_picture');

    $("body").attr('style',style);
    $("#desID").val(designID);
}

function designSave(obj){
    var showID = 'personal';
    var designID=$('#desID').val();

    if(drawDetailNewWindow('','personalOthers'))
    {
        return;
    }

    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'saveDesign',
                'designID': designID
        },

        function(result, answer)
        {
            closeDetail(showID, $('.preloader'), true);
            $('#messageBlock').html(result);
            $('#messageBlock').stop(true,true).fadeIn(1000);
        }
    ,true);

    $("#serverRequest").text('');
}

function updateDesign(p1,p2,page,el)
{
    var container = $(el).parents("div.blockContainer:first");
    var designID=$('#desID').val();
    $(this).parents('.blockContainer');

    container.find("div.loadingPage").show();

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'getDesign',
                        'p1' : p1,
                        'selectedDesign' : designID,
                        'page' : page
		},
		function(result, answer)
		{
                        container.html(result);
		},true);
}

function updateFamilyList(el)
{
    var gender = $(el).val();
    var container = $("select[name=FamilyStatus]").parent();

    container.html("<img src='/images/upload.gif' alt=''>");
    container.html(familyArray[gender]);
}

function showFriendsList(el, active)
{
    el = (el) ? el : $("select[name=FamilyStatus]");
    var gender = ($(":radio[name=Gender]").filter(":checked").val() == 1) ? 0 : 1;
    var id = $(el).val();
   
    if($("#friendUserID").length==1)
        {
            $("#friendUserID").remove();
        }
        
    if(familyArray['showFriends'][id] == 0 || id == 0)
        return;

    if(!familyArray['friendsList'])
        {
            JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showFriendsList',
                        'id' : $(el).val()
		},
		function(result, answer)
		{
                        familyArray['friendsList'] = result;
                        $(el).after(familyArray['friendsList'][gender]);
                        $("#friendUserID").val(active);
		},true);
        }
    else
        {
            $(el).after(familyArray['friendsList'][gender]);
            $("#friendUserID").val(active);
            
        }
}

function checkRelations()
{
    var userID = $('#friendUserID').val();
    var relationID = $("select[name=FamilyStatus]").val();

    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'addRelation',
                'userID' : userID,
                'relationID' : relationID
        },
        function(result, answer)
        {
                
        },true);  
}

function recordLike(id,status,event){

    switch(status){
        case  1:
            if($('.like_button_'+id).hasClass('likeActive'))
            {
                $('.like_button_'+id).removeClass('likeActive');
                $('.com_like_'+id).removeClass('likeActiveSmall');
                $('.com_like_'+id).addClass('like');
                updateLike = false;
            }
            else
            {
                $('.like_button_'+id).addClass('likeActive');
                $('.dislike_button_'+id).removeClass('dislikeActive');
                updateLike = true;
                if($('.com_dislike_'+id).hasClass('dislikeActiveSmall'))
                {
                    $('.com_dislike_'+id).removeClass('dislikeActiveSmall');
                    $('.com_dislike_'+id).addClass('dislike');
                }
            }
        break;
        case -1:
            if($('.dislike_button_'+id).hasClass('dislikeActive'))
            {
                $('.dislike_button_'+id).removeClass('dislikeActive');
                $('.com_dislike_'+id).removeClass('dislikeActiveSmall');
                $('.com_dislike_'+id).addClass('dislike');
                updateDislike = false;
            }
            else
            {
                $('.like_button_'+id).removeClass('likeActive');
                $('.dislike_button_'+id).addClass('dislikeActive');
                updateDislike = true;
                if($('.com_like_'+id).hasClass('likeActiveSmall'))
                {
                    $('.com_like_'+id).removeClass('likeActiveSmall');
                    $('.com_like_'+id).addClass('like');
                }
            }
        break;
    }

    JsHttpRequest.query('/ajax_functions.php',
		{
			'function' : 'recordLike',
                        'messageID' : id,
                        'statusID' : status
		},
		function(result, answer)
		{
                    if(result['val1']==0)
                        $(result['id1']).stop(true,true).hide();
                    else
                        {
                            if(status != 1 && updateDislike)
                                {
                                    $('.com_dislike_'+id).addClass('dislikeActiveSmall');
                                    $('.com_dislike_'+id).removeClass('dislike');
                                }
                            $(result['id1']).stop(true,true).html(result['val1']).fadeIn(500);
                        }

                    if(result['val2']==0)
                        $(result['id2']).stop(true,true).hide();
                    else
                        {
                            if(status == 1 && updateLike)
                                {
                                    $('.com_like_'+id).addClass('likeActiveSmall');
                                    $('.com_like_'+id).removeClass('like');
                                }
                            $(result['id2']).stop(true,true).html(result['val2']).fadeIn(500);
                        }
                        
		},true);

    event.cancelBubble = true;
    return;
}

function showApp(userID, messageID, e)
{
    showUser(userID,e);
    type = "invites";
    JsHttpRequest.query('/ajax_functions.php',
		{
			'function': 'showPM',
                        'type' : type,
                        'mailID' : messageID
		},
		function(result, answer)
		{
                    if($("#"+messageID).hasClass("newMail"))
                    {
                        $("#"+messageID).removeClass("newMail");
                        newPmail(type);
                    }
		},true);
    e.cancelBubble = true;
    
    return false;
}

function showRules()
{
    window.open('/xml/main/rules/?id=11','_blank','scrollbars=yes,toolbar=no,status=no,resizable=no,width=516,height=600');
}

function trim(text) {return (text || "").replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, "");}

function checkScrolling(h)
{
    if(!h){
        h = $(window).height()/3;
    }
    
    if(h < $(window).scrollTop())
        $("html:not(:animated)"+( ! $.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop : 0});
}

function showLookCheckBox(el)
{
    var checkBox = $(el).parents("div.blockContainer:first").find("div.lookCheckBox");
    if(checkBox.css('display') == "none")
        checkBox.css('display','block');
}

function showFullText(obj,event){
            $(obj).parent().hide();
            $(obj).parent().next().show();
            event.cancelBubble = true;
        }

function hideFullText(obj,event){
    $(obj).parent().hide();
    $(obj).parent().prev().show();
    event.cancelBubble = true;
}

function showMediaList()
{
    $('#addMediaRowsContainer').show();
    $('#addMediaRowsContainer').bind('mouseleave', function(){
        $(this).fadeOut(500);
    });
    $('#addMediaRowsContainer').bind('mouseenter', function(){
        $(this).show();
    });
}

function showMedia(type)
{
    $("#addPhotoFile").val('');
    $(".addMedia").hide();
    $(".add"+type).show();
    $('#addMediaRowsContainer').hide();
}

function cancelMedia(type)
{
    $(".addMedia").show();
    $(".add"+type).hide();
    $("#add"+type).val('');
}

function fnSelect(el)
{
    if (document.selection) { 
        var range = document.body.createTextRange(); 
        range.moveToElementText(el); 
        range.select();
    } 
    else if (window.getSelection) { 
        var range = document.createRange(); 
        range.selectNode(el); 
        window.getSelection().addRange(range); 
    } 
}

function loadIframe(frame)
{
    if(frame.id != "imageForm")
    {
        frame.id = "imageForm";
        return;
    }
    var str = "";
    var error = false;
    var doc = (ie && $.browser.version != "9.0") ? frame.contentWindow.document : frame.contentDocument;
    if(ie && $.browser.version != "9.0")
    {
        str = doc.body.innerText.replace('\n','').replace(/^(.*URL=\")+|(\".*)+$/g, '');
        error = (str.indexOf('http://') == -1) ? true : false;
    }
    else 
    {
        if(doc.documentElement.attributes['1'] == undefined)
            error = true;
        else    
            str = doc.documentElement.attributes['1'].value;
    }
    
    if(str && !error)
    {
        updateImageInput(str);
    }
    else if(error)
    {
        JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'getLoadFileError'
        },
        function(result, answer)
        {
            showPopup(result['title'], result['content']);
        },true);
    }
    
    $(".loadFileProcess").hide();
}

function submitImageForm()
{
    if($("#addPhotoFile").val())
        {
            $("#loadImage").submit();
            $(".loadFileProcess").show();
        }
}

function updateImageInput(txt)
{
    $("#addPhoto").val(txt);
}

function updateRecomendBlock(e, el, type, userID)
{
    e.cancelBubble = true;
    var updateContainer = false;
    $(el).html('<div class="loading"></div>');
    $(el).removeClass("ignorList");
    $(el).removeClass("subscribeAdd");
    var container = $(el).parents("div.row");
    $("#subscriptionsStat_container").oneTime('1s', function(){
            container.hide();
            updateContainer = ($("#subscriptionsStat_container div.row:visible").length == 0) ? true : false;
            if(updateContainer)
                $("#subscriptionsStat_container").html('<div class="loading"></div>');
            
            JsHttpRequest.query('/ajax_functions.php',
                {
                        'function': 'updateRecomendBlock',
                        'type' : type,
                        'userID' : userID,
                        'updateContainer' : updateContainer
                },
                function(result, answer)
                {
                    if(result['content'])
                        $("#subscriptionsStat_container").html(result);
                    else if(result['hideContainer'])
                        $("#recomendBlock").remove();

                },true);
    });
}

function authOILogin() {
    $("#openIDform").show();
    $("#i_openid").focus();
    return false;
}

function readMe(messageID)
{   
    JsHttpRequest.query('/ajax_functions.php',
                {
                        'function': 'readMe',
                        'messageID' : messageID
                },
                function(result, answer)
                {
                        changeSection('read_me',result, false, 1);
                },true);
}

function getReadMePopup(messageID, ev)
{
    if(ev)
        ev.cancelBubble = true;
        
    JsHttpRequest.query('/ajax_functions.php',
                {
                        'function': 'getReadMePopup',
                        'messageID' : messageID
                },
                function(result, answer)
                {
                    hideVideoIframes();
                    $("#dialog-modal").remove();
                    var div = '<div id="dialog-modal" title="'+result['title']+'" style="display:none;">'+result['content']+'</div>';
                    $("body").append(div);
                    $(function() {
                        $("#dialog-modal").dialog({
                            modal: true,
                            resizable: false,
                            width: 478,
                            minHeight: 90,
                            draggable: false,
                            close: function(ev, ui) {showVideoIframes();clearInterval(intervalID)}
                        });
                    });
                    if(result['error']) 
                        {
                            intervalID = setInterval("timer("+messageID+")", 1000);
                        }
                },true);
}               

function timer(messageID)
{   
    var s = ($("#s").text() == "00") ? 59 : $("#s").text()-1;
    if(s <= 9 && s >= 0)
        s = "0"+s;
    else if(s == 59)
        {
            var m = ($("#m").text() == "00") ? 59 : $("#m").text() - 1;
            if(m <= 9 && m >= 0)
                m = "0"+m;
            else if(m == 59)
            {
                var h = $("#h").text();
                if(h == "00")
                    m = "00";
                else
                {
                    h = "0"+(h-1);
                }
                $("#h").text(h);
            }
            $("#m").text(m);
        }
    $("#s").text(s);
    
    if($("#s").text() == "00" && $("#m").text() == "00" && $("#h").text() == "00")
    {
        $("#dialog-modal").dialog('close');
        getReadMePopup(messageID);
        return;
    }
}

function showPopup(title, content, height, ev)
{
    if(ev)
        ev.cancelBubble = true;
    hideVideoIframes();
    content = content || preloader_source(height);
    $("#dialog-modal").remove();
    var div = '<div id="dialog-modal" title="'+title+'" style="display:none;">'+content+'</div>';
    $("body").append(div);
    $(function() {
        $("#dialog-modal").dialog({
            modal: true,
            resizable: false,
            width: 478,
            minHeight: 90,
            height: height,
            draggable: false,
            close: function(ev, ui) {showVideoIframes();}
        });
    });
}

function hideVideoIframes()
{
    $("iframe.videoIframe").each(function(){
        $(this).hide();
        $(this).after("<div class='divVideoIframe'></div>");
    });
}

function showVideoIframes()
{
    $("div.divVideoIframe").each(function(){
        $(this).remove();
    });
    $("iframe.videoIframe").each(function(){
        $(this).show();
    });
}

function showCompletePopup(type)
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'showCompletePopup',
                'type' : type
        },
        function(result, answer)
        {
                showModalBox(result['title'], result['content']);
        },true);
}

function showNews(id)
{
    var hash = location.hash;

    if (hash != "#news/"+id)
        {
            hashHistory.push(hash);
            location.hash = "news/"+id;
        }
    return false;
}

function showNewsFromHash(id)
{
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'getNews',
                'id' : id
        },
        function(result, answer)
        {
                $(".news").html(result);
        },true);
    
    return false;
}

function showNewsLine(page)
{
    $("#content .newsNavigation").html('');
    $("#content .newsNavigation").addClass('loading');
    JsHttpRequest.query('/ajax_functions.php',
        {
                'function': 'showNewsLine',
                'page' : page
        },
        function(result, answer)
        {
                $("#content .newsNavigation").remove();
                $("#content").append(result);
        },true);
    
    return false;
}

function newsClose()
{
    $(".news").html('');
    location.hash = "!";
}

function showMoreGames()
{
    $("#containerGames").height('auto');
    $("#moreButton").remove();
}

function socialDialog()
{
    $("#dialog-modal").remove();
    var div = '<div id="dialog-modal" title="Popup" style="display:none;">Do you already have a StumbleUpon account?</div>';
    $("body").append(div);
    $(function() {
        $( "#dialog:ui-dialog" ).dialog( "destroy" );
        $( "#dialog-modal" ).dialog({
                modal: true,
                resizable: false,
                width: 400,
                height: 200,
                draggable: false,
                buttons: {
                        "Нет": function() {
                                location.href = '/register';
                        },
                        "Да": function() {
                                location.href = '/index2.php';
                        }
                }
        });
    });
}

function hideBranding()
{
    if($("#branding").length == 1)
        {
            JsHttpRequest.query('/ajax_functions.php',
            {
                    'function': 'drawBodyStyle',
                    'showBranding' : false
                    
            },
            function(result, answer)
            {
                $("body").attr('style',result);
                $("#branding").hide();
            },true);
        }
            
}

function showBranding()
{
    if($("#branding").length == 1)
            $("#branding").show();
}

function openChat()
{
    if(document.getElementById("chatContainer") != null)
    {
        if ( document.getElementById("chatContainer").style.display == "block" )
                logoutChat();
        else
                loginChat(false);
    }
    else
    {
        JsHttpRequest.query('/chat_functions.php',
        {
                'function': 'openChat'
        },
        function(result, answer)
        {
            $(".mainInfo").prepend(result);
            if($("#chatUsersCount").css('display') == "none")
                        $("#chatUsersCount").show();
        },true);
    }
}
