var request_timeout = 10000;
var userInfoArray = new Array(), userInfoShow = 300, userInfoHide = 150, commentBoxShow = 500, lmbShow = 500, settingsShow = 500, settingsHide = 200;

$(document).ready(function(){        
    $(document).pngFix({ blankgif:'/static/i/spacer.gif' });
    attachCommentUserInfoEvent(); 
    attachUserInfoShow($("div.avatar"));
    $('#headmenu').dblclick(function(){ showLoginMyForm(); });
});

function attachCommentUserInfoEvent()
{
    attachUserInfoShow($("td.comment_av").children());
    $("div.userInfoBlock").
        unbind().
        click(function(event){ 
            $(this).hide(userInfoHide); 
            event.stopPropagation(); 
        });
}

function attachUserInfoShow(obj)
{
    obj.unbind().hover(showUserInfoBlock, hideUserInfoBlock).click(showUserInfoBlock);
    obj.children(':first').
        unbind().
        click(function(){ 
            $(this).parent().click(); 
            return false; 
        });
}
              
function setUserInfoBlockData(block, data)
{
    block.html(data);
    block.children('div').
          each(function(){ 
              $(this).children().
                      click(function(event){ 
                          event.stopPropagation(); 
                          return true; 
                      }); 
          });
}
     
function showUserInfoBlock()
{                                                
    var infobox, uid;    
    infobox = $(this).children("div.userInfoBlock");         
    uid = $(this).attr("userid");
        
    if(userInfoArray[uid]){
        setUserInfoBlockData(infobox, userInfoArray[uid]);
    }
    infobox.stop().attr('style', '').show(userInfoShow);
    if(!userInfoArray[uid]){
        getUserInfo(uid, infobox);
    }
    return false;
}
                   
function hideUserInfoBlock()
{                           
    var infobox = $(this).children("div.userInfoBlock");
    infobox.stop().hide(userInfoHide);
}

function showLoginMyForm()
{
    if($.browser.msie && $.browser.version < 8){
        window.location.href = '/my/';
        return;
    }
    $('#loginMyBlock').slideDown(lmbShow);
    try{
        window.getSelection().removeAllRanges();
    }catch(e){}
    //window.location = '#top';
    $('#auth_email_field').focus();
    $.scrollTo('a.logo', 500);
}

function hideLoginMyForm()
{
    $('#loginMyBlock').slideUp(lmbShow);
}

function toggleUserFullInfo()
{
    var obj = $('#user_fullinfo');
    if(obj.attr('loaded') == 'false'){
        obj.attr('loaded', 'true');                           
        obj.html($('#user_fullinfo_load').html() + obj.html());
        attachUserInfoShow($("div.avatar"));
    }
    obj.slideToggle('slow');
}

function settingsToogle(id)
{                              
    if($('#'+id).css('display') != 'none'){
        return;
    }
    $('.settings_block').stop().
        slideUp(settingsHide); /*, function(){ alert('a');
            //$('#'+id).slideDown(settingsShow);
            document.title += '!';
        }); //*/
    setTimeout("$('#"+id+"').slideDown(settingsShow); $.scrollTo('#"+id+"', 500);", settingsHide);
}

function showUserLocation(latitude, longitude, speed)
{
    var uloc = $('#user_location');
    if(!uloc) return;
    
    if(uloc.attr('inited') != 'true'){
        //if(!google.maps.BrowserIsCompatible()) return;
        
        uloc.children('div#user_location_map').html('asd');
        
        /*var latlng = new google.maps.LatLng(latitude, longitude);        
        var mapopts = {
          zoom: 8,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };                                                       
        var map = new google.maps.Map(uloc.children('div#user_location_map'), mapopts);
        */
        
        uloc.attr('inited', 'true');
    }
    uloc.show();
}

function hideUserStatus()
{
}

function showCommentBox(id, text)
{
    var box = $('#'+id);
    if(!box){
        return false;
    }
    var area = box.children('textarea');
    if(!text){
        text = '';
    }
    area.val(text);       
    box.slideDown(commentBoxShow);
    area.focus();
    return true;
}

function postCommentError(id)
{                                  
    $('#'+id+'_load').hide();
    $('#'+id+'_submit').attr('disabled', false);
    alert('Ошибка отправки комментария.\n\nМожно попробовать повторить отправку через пару секунд.');
}

function delCommentError(id, comm_id)
{  
    $('#'+id+'_'+comm_id+'_load').hide();
    alert('Ошибка удаления комментария.\n\nМожно попробовать повторить удаление через пару секунд.');                   
}

function getUserInfo(id, obj)
{
    var url = '/users/u'+id+'/ajajinfo/';
    $.ajax({ url: url, type: 'GET', timeout: request_timeout, dataType: 'json', data: {},
               success: function(data, stxt, xhr){
                   if(!xhr.status){
                       return;
                   }
                   if(data.status == 'ok'){
                       setUserInfoBlockData($(obj), data.html);
                       userInfoArray[id] = data.html;
                   }
               }
           });
    return true;
}
                             
function getComments(id, type, to, page)
{
    var url = '';
    if(type == 'u'){
        url = '/users/u'+to+'/ajajcomment/';
    }
    if(type == 'a'){
        url = '/photos/ajajcommentalbum/a'+to+'/';
    }
    if(!url){
        return false;
    }                   
    $('#'+id+'_pages_load').show();              
    $.ajax({ url: url, type: 'POST', timeout: request_timeout, dataType: 'json', data: {cpage: 'page'+page},
                   success: function(data, stxt, xhr){
                       if(!xhr.status){
                           $('#'+id+'_pages_load').hide();
                           return;
                       }
                       if(data.status == 'ok'){
                           $('#'+id).html(data.html);
                           attachCommentUserInfoEvent();   
                           //$.scrollTo('#'+id+' > tr:first', 500);
                           $.scrollTo($('#'+id+'_box').parent(), 500);
                       }                           
                   },
                   error: function(){ $('#'+id+'_pages_load').hide(); }
           });
}

function postComment(id, type, to, text)
{
    var url = '';
    if(type == 'u'){
        url = '/users/u'+to+'/ajajcomment/';
    }
    if(type == 'a'){
        url = '/photos/ajajcommentalbum/a'+to+'/';
    }
    if(!url){
        return false;
    }              
    if(text == undefined){
        text = $('#'+id+'_area').val(); 
    }
    if(text.replace(/\s/gi, '') == ''){
        alert('Пустой комментарий никому не интересен ;)');
        return false;
    }
    $('#'+id+'_load').show();
    $('#'+id+'_submit').attr('disabled', true);
    $.ajax({ url: url, type: 'POST', timeout: request_timeout, dataType: 'json', data: {text: text},
                   success: function(data, stxt, xhr){
                       if(!xhr.status){
                           postCommentError(id);
                           return;
                       }
                       if(data.status == 'ok'){
                           $('#'+id).html(data.html);
                           attachCommentUserInfoEvent();
                       }
                       var box;
                       if(box = $('#'+id+'_box')){
                           //box.children('textarea').val('');
                           box.hide('medium');
                       }
                       $('#'+id+'_load').hide();
                       $('#'+id+'_submit').attr('disabled', false);
                   },
                   error: function(){ postCommentError(id); } 
           });
    return true;
}

function delComment(id, type, to, comm_id)
{
    var url = '';
    if(type == 'u'){
        url = '/users/u'+to+'/ajajdelcomment/';
    }
    if(!url){
        return false;
    }                   
    $('#'+id+'_'+comm_id+'_load').show();   
    $.ajax({ url: url, type: 'POST', timeout: request_timeout, dataType: 'json', data: { id: comm_id},
               success: function(data, stxt, xhr){
                   if(!xhr.status){
                       delCommentError(id, comm_id);
                       return;
                   }
                   $('#'+id+'_'+comm_id+'_load').show();   
                   if(data.status == 'ok'){                        
                       $('#'+id+'_'+comm_id).html(data.html);    
                       attachCommentUserInfoEvent();  
                   }
               },
               error: function(){ delCommentError(id, comm_id); }
           });
    return true;
}

;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);
  