if (!window.VK) window.VK = {};

VK.extend = function(target, source, overwrite) {
  for (var key in source) {
    if (overwrite || typeof target[key] === 'undefined') {
      target[key] = source[key];
    }
  }
  return target;
};

VK.extend(VK, {
    
    _token: null,
    _userid: null,
    _album_photos: new Array(),
    _photo_now: null,
    _photos_count: null,
    _photos_startid: 1,
    _now_userid: null,
    _shows_photos: null,
    _album_now: null,
    _wall_count_posts: null
    
}, true);

VK.init = function(options) {
    
    VK._token = options.token;
    VK._userid = options.userid;

};

VK.Api = {
    
    call: function(method, options, callback) {

        var result = new Array();
        for(o in options) {
            result.push(o+'='+options[o]);
        }
        result.push('access_token='+VK._token);
        var params = result.join('&');

        $.ajax({
            url: "https://api.vkontakte.ru/method/"+method,
            dataType: 'jsonp',
            data: params,
            success: function(data){
                callback(data);
                return data;
            }
        });

    }
    
};

VK.Auth = {
    
    check: function(callback) {
        
        if(VK._token && VK._userid) {
            
            VK.Api.call('getProfiles', {uids: VK._userid}, function(data) {
                
                if(data.response[0].uid) {
                    callback(true);
                    return true;
                }
                
            });
            
        }
        
        callback(false);
        return false;
        
    }
        
};

VK.face = {
    
    load_user_page: function(userid) {
     
        $("#albums_header").hide();
        $("#albums_layer").hide();
        $("#profile_layer").show();
        
        VK.face.load_profile(userid);
        VK.face.load_friends(userid);
        VK.face.load_all_photos(userid);
        VK.face.load_followers(userid);
        VK.face.load_wall(userid, 0);
        
        VK._now_userid = userid;
       
    },
    
    format_profiles: function(data, callback) {
        
        var result = new Array();
        
        $.each(data.response, function(key,value){
           
           result[value.uid] = {name: value.first_name+' '+value.last_name, photo_rec: value.photo_rec};
           
        });
        
        callback(result);
        
    },
    
    format_date: function(time) {
      
        var s_date = new Date(parseInt(time)*1000);
        var minutes = s_date.getMinutes();
        var hours = s_date.getHours();
        var date = s_date.getDate();
        var month = s_date.getMonth()+1;
        if(minutes < 10) {
            minutes = "0"+minutes;
        }
        if(hours < 10) {
            hours = "0"+hours;
        }
        if(date < 10) {
            date = "0"+date;
        }
        if(month < 10) {
            month = "0"+month;
        }
        return date+'.'+month+'.'+s_date.getFullYear()+' в '+hours+':'+minutes;
      
    },
    
    load_wall: function(userid, offset) {
        
        VK.Api.call('wall.get', {owner_id: userid, count: 20, offset: offset}, function(data) {

            if(offset == 0) {
                $("#wall_posts").html('');
            }
            
            VK._wall_count_posts = data.response[0];
            
            if(VK._wall_count_posts-offset > 20) {
                $("#wall_more").show();
                $("#wall_more a").attr('onClick', 'VK.face.load_wall('+VK._now_userid+', '+(offset+20)+');');
            } else {
                $("#wall_more").hide();
            }
            
            var from_ids = new Array();
            
            $.each(data.response, function(key,value) {
               
               if(value.from_id) {
                   from_ids.push(value.from_id);
               }
               
            });
            
            VK.Api.call('getProfiles', {uids: from_ids.join(','), fields: 'photo_rec'}, function(data2) {

                VK.face.format_profiles(data2, function(ids_name) {
                    
                    $.each(data.response, function(key,value) {
                        
                        if(value.from_id) {

                            var f_date = VK.face.format_date(value.date);
                            
                            var attachs = '';
                            if( $.isArray(value.attachments) ) {
                                attachs = '<div class="wall_post_attachs">';
                                $.each(value.attachments, function(attach_key, attach_value) {
                                    if(attach_value.type == "video") {
                                        attachs += '<div class="wall_post_attach_video"><a href="javascript:void(0);" onClick="alert(\'Открываем видео ... (понарошку)\');"><img src="'+attach_value.video.image+'" /></a></div>';
                                    }
                                    if(attach_value.type == "link") {
                                        var parts = attach_value.link.url.replace('//', '/').split('/');
                                        attachs += '<div class="wall_post_attach_link">Ссылка: <a href="'+attach_value.link.url+'" target="_blank">'+parts[1]+'</a></div>';
                                    }
                                    if(attach_value.type == "photo") {
                                        attachs += '<div class="wall_post_attach_photo"><a href="javascript:void(0);" onClick="alert(\'Открываем фото ... (понарошку)\');"><img src="'+attach_value.photo.src+'" /></a></div>';
                                    }
                                    if(attach_value.type == "graffiti") {
                                        attachs += '<div class="wall_post_attach_graffiti"><a href="javascript:void(0);" onClick="alert(\'Открываем граффити ... (понарошку)\');"><img src="'+attach_value.graffiti.src+'" /></a></div>';
                                    }
                                    if(attach_value.type == "audio") {
                                        attachs += '<div class="wall_post_attach_audio"><b>Аудио: '+attach_value.audio.performer+' - '+attach_value.audio.title+'</b></div>';
                                    }
                                });
                                attachs += '</div><div style="clear: both;"></div>';
                            }
                            
                            $("#wall_posts").append('<div class="wall_post"><div class="wall_post_photo"><a href="javascript:void(0);" onClick="VK.face.load_user_page('+value.from_id+');"><img class="border_radius_5px" src="'+ids_name[value.from_id].photo_rec+'"></a></div><div class="wall_post_detail" id="wall_post_detail_'+value.id+'"><div class="wall_post_author"><a href="javascript:void(0);" onClick="VK.face.load_user_page('+value.from_id+');">'+ids_name[value.from_id].name+'</a></div><div class="wall_post_text">'+value.text+attachs+'</div><div class="wall_post_time_and_likes"><div class="wall_post_time">'+f_date+'</div><div class="wall_post_likes">'+value.likes.count+'</div></div></div></div>');

                            if( value.comments.count > 0 ) {
                                VK.Api.call('wall.getComments', {owner_id: userid, sort: 'asc', post_id: value.id}, function(data_comm) {
                                    
                                       var comm_from_ids = new Array();
                                       $.each(data_comm.response, function(comm_key,comm_value) {

                                          if(comm_value.uid) {
                                              comm_from_ids.push(comm_value.uid);
                                          }

                                       });
                                       
                                       VK.Api.call('getProfiles', {uids: comm_from_ids.join(','), fields: 'photo_rec'}, function(data_prof) {
                                           
                                           VK.face.format_profiles(data_prof, function(comm_ids_name) {
                                       
                                               // var count_comms = data_comm.response[0];
                                               var count_comms = data_comm.response.length-1;
                                               if(count_comms > 3) {
                                                   $("#wall_post_detail_"+value.id).append('<div style="padding-top: 25px;" id="wall_post_more_'+value.id+'"><div class="gray_box" style="width: 525px; height: 40px;"><div class="gray_box_center"><a href="javascript:void(0);" onClick="VK.face.show_all_replies('+value.id+');">Show all '+count_comms+' replies</a></div></div></div>');
                                               } else {
                                                   $("#wall_post_detail_"+value.id).append('<div style="padding-top: 25px;"></div>');
                                               }

                                               $("#wall_post_detail_"+value.id).append('<div id="wall_post_comments_'+value.id+'" style="padding-top: 10px;"></div>');

                                               var i = 0;
                                               var hide = '';
                                               $.each(data_comm.response, function(comm_key, comm_value) {

                                                   if(comm_value.uid) {

                                                       if( i < count_comms-3) {

                                                           hide = ' style="display: none;"';
                                                       } else {
                                                           hide = '';
                                                       }

                                                       var date = VK.face.format_date(comm_value.date);

                                                       $("#wall_post_comments_"+value.id).append('<div class="wall_post_comment"'+hide+'><div><div class="wall_post_photo"><a href="javascript:void(0);" onClick="VK.face.load_user_page('+comm_value.uid+');"><img class="border_radius_5px" src="'+comm_ids_name[comm_value.uid].photo_rec+'"></a></div></div><div class="wall_post_comment_detail"><div class="wall_post_author"><a href="javascript:void(0);" onClick="VK.face.load_user_page('+comm_value.uid+');">'+comm_ids_name[comm_value.uid].name+'</a></div><div class="wall_post_text">'+comm_value.text+'</div><div class="wall_post_time_and_likes"><div class="wall_post_time">'+date+'</div></div></div></div>');
                                                       i++;
                                                   }
                                               });
                                               
                                           });
                                           
                                       });
                                });
                            }

                        }

                    });
                    
                });
               
            });
            
        });

    },
    
    show_all_replies: function(id) {
        $('#wall_post_comments_'+id+' > .wall_post_comment').show();
        $('#wall_post_more_'+id+'').html('');
    },
    
    show_main_photo: function(system) {
        
        if(VK._album_now != -6 || VK._now_userid != VK._userid) {
        
            VK.Api.call('photos.get', {uid:VK._now_userid, aid: -6}, function(data) {

                VK._album_photos = data.response;
                VK._photos_count = data.response.length;
                VK._photos_now = VK._photos_count-1;
                VK._photos_startid = 0;
                VK._album_now = -6;

                if(!system) {
                    VK.face.photo.show(VK._album_photos[VK._photos_count-1].src_big, '', VK._photos_count-1);
                } else {
                    $("#counter_photos").html(VK._photos_count);
                }

            });
        
        } else if(!system) {
            VK.face.photo.show(VK._album_photos[VK._photos_count-1].src_big, '', VK._photos_count-1);
        }
        
    },
    
    load_profile: function(uid) {
        
        VK.Api.call('getProfiles', {uids: uid, fields: 'photo_big,screen_name,counters,bdate'}, function(data) {
            
            if(data.response) {

                pdata = data.response[0];

                if(uid == VK._userid) {

                    $("#user_profile").attr("onClick", "VK.face.load_user_page('"+pdata.uid+"');");
                    $("#user_profile").html(pdata.first_name+" "+pdata.last_name);
                }
                if(pdata.photo_big) {
                    $("#user_photo").attr("src", pdata.photo_big);

                }
                $("#user_name").html(pdata.first_name+" "+pdata.last_name);

                if(pdata.counters.user_videos) {
                    $("#counter_videos").html(pdata.counters.user_videos);
                }

                if(pdata.counters.audios) {
                    $("#counter_audio").html(pdata.counters.audios);
                }

                if(pdata.counters.friends) {
                    $("#counter_friends").html(pdata.counters.friends);
                }
                
                $("#albums_count").html(pdata.counters.albums+" albums");
                $("#counter_albums").html(pdata.counters.albums);
                
                VK.face.show_main_photo(true);
                
                $("#lnk_counter_photos").attr("onClick", 'VK.face.load_album('+uid+', -6);');
                $("#lnk_counter_albums").attr("onClick", 'VK.face.load_user_albums('+uid+');');
                
                $("#bdate").html(pdata.bdate);
            }
        });
        
    },
    
    load_user_albums: function(uid) {

        $("#album_photos").html('');
        $("#profile_layer").hide();
        $("#albums_header").show();
        $("#albums_layer").show();
        $("#albums div").remove();
        $("#albums").show();
        $("#photos_count").html('?');
        
        VK.Api.call('photos.getAlbums', {uid:uid}, function(data) {
          $.each(data.response, function(k,v) {
              
                $("#albums").append('<div class="album_title"><a href="javascript:void(0);" onClick="VK.face.load_album('+uid+', '+v.aid+');">'+v.title+'</a></div>');
                $("#albums").append('<div id="album_photos_'+v.aid+'" class="album_photo_container" style="text-align: left;"></div>');
                
                VK.Api.call('photos.get', {uid:uid, aid: v.aid, limit:4}, function(data2) {

                   $.each(data2.response, function(k2,v2) {
                       if(v2.src) {
                           $("#album_photos_"+v.aid).append('<div class="album_photo_row"><a href="javascript:void(0);" onClick="VK.face.load_album('+uid+', '+v.aid+', function() { VK.face.photo.show(\''+v2.src_big+'\', \'\', '+k2+'); });"><img src="'+v2.src+'" /></a></div>'); 
                       }
                   });
                   
                });
              
          });
          
        });
        
    },
    
    load_friends: function (uid) {
        
        VK.Api.call('friends.get', {uid: uid, count: 6, fields: 'photo_rec'}, function(data) {

            var table_friends='';
            var i = 0;
            $.each(data.response, function(key,value) {

                i++;

                if(i==1) table_friends += '<tr>';
                if(i==4) table_friends += '</tr><tr>';
                if(i==7) table_friends += '</tr>';

                table_friends += '<td class="friends_td"><a href="javascript:void(0);" onClick="VK.face.load_user_page('+data.response[i-1].uid+');"><img class="border_radius_5px" src="'+data.response[i-1].photo_rec+'" /><br />'+data.response[i-1].first_name+'</a></td>';


            });

            $("#friends").html(table_friends);

        }); 
        
    },
    
    load_all_photos: function (uid) {
        
        VK.Api.call('photos.getAll', {owner_id: uid, count: 4}, function(data) {
                $("#all_photos").html('');
                $.each(data.response, function(k,v) {
                    if(v.src_small) {
                        $("#all_photos").append('<td class="view_all_photos_table_photo border_radius_5px"><a href="javascript:void(0);" onClick="alert(\'Не нашел я подходящего метода в API для данного блока. Это сообщение было оставлено в 02:20 20.10.2011\');"><img src="'+v.src+'" /></a></td><td class="clean_place"></td>'); 
                    } 
                });

        }); 
        
    },
    
    load_followers: function (uid) {
        
        VK.Api.call('subscriptions.getFollowers', {uid: uid, count: 6}, function(data) {
            
            $("#counter_followers").html(data.response.count);
            $("#followers").html('');         

            var followers = new Array();
            $.each(data.response.users, function(key,value) {
                followers.push(value);
            });
            VK.Api.call('getProfiles', {uids: followers.join(','), fields: 'photo_rec'}, function(data) {
                
                var i = 0;
                $.each(data.response, function(key,value) {
                    
                    i++;

                    if(i==1) $("#followers").html($("#followers").html()+'<tr>');
                    if(i==4) $("#followers").html($("#followers").html()+'</tr><tr>');
                    if(i==7) $("#followers").html($("#followers").html()+'</tr>');
                    
                    $("#followers").append('<td class="friends_td"><a href="javascript:void(0);" onClick="VK.face.load_user_page('+value.uid+');"><img src="'+value.photo_rec+'" /><br />'+value.first_name+'</a></td>');
                    
                });
                
            });

        });
        
    },
    
    back_to_profile: function() {
      
        $("#profile_layer").show();
        $("#albums_header").hide();
        $("#albums_layer").hide();
        $("#album_photos").html('');
      
    },
    
    load_album: function(uid, aid, callback) {
        
        $("#albums").hide();
        $("#album_photos").html('');
        $("#profile_layer").hide();
        $("#albums_header").show();
        $("#albums_layer").show();
        
        var method = 'photos.getUserPhotos';
        var params_api = {uid: uid, count: 100};
        
        if(aid >= 1 || aid == -6) {
            params_api = {uid:uid, aid: aid, l1imit: 24};
            method = "photos.get";
        }
        
        VK.Api.call(method, params_api, function(data) {
                $("#album_photos").html('');
                var i = 0;
                $.each(data.response, function(k,v) {
                    
                    if(v.src_small && i <= 23) {
                        i++;
                        $("#album_photos").append('<div class="album_photo_row"><a href="javascript:void(0);" onClick="VK.face.photo.show(\''+v.src_big+'\', \''+v.text+'\', '+k+');"><img src="'+v.src+'" /></a></div>'); 
                    } 
                });
                $("#photos_count").html((data.response.length-1)+" photos");
                VK._photos_count = data.response.length-1;
                VK._album_photos = data.response;
                VK._photos_startid = 1;
                // alert(i+" ::: "+VK._photos_count);
                if(VK._photos_count > i-1) {
                    VK._shows_photos = 24;
                    $("#album_photos").append('<div id="album_more" class="gray_box album_more"><div class="gray_box_center" style="padding-left: 250px;"><a href="javascript:void(0);" onClick="VK.face.load_album_more(25);">More photos</a></div></div>');
                }
                if(aid >= 1) {
                    VK._photos_startid = 0;
                    VK._photos_count++;
                    $("#photos_count").html((VK._photos_count)+" photos");
                }
                if(aid == -6) {
                    VK._photos_startid = 0;
                    VK._photos_count++;
                    $("#photos_count").html((VK._photos_count)+" photos");
                }
                VK._album_now = aid;
                callback();

        });
        
    },
    
    load_album_more: function(startid) {
        
        $("#album_more").remove();
        
        if( VK._photos_count-VK._shows_photos > 24 ) {
           
            for(var i = startid; i < VK._shows_photos+25; i++) {
                var v = VK._album_photos[i];
                $("#album_photos").append('<div class="album_photo_row"><a href="javascript:void(0);" onClick="VK.face.photo.show(\''+v.src_big+'\', \''+v.text+'\', '+i+');"><img src="'+v.src+'" /></a></div>');
            }
            $("#album_photos").append('<div id="album_more" class="gray_box album_more"><div class="gray_box_center" style="padding-left: 250px;"><a href="javascript:void(0);" onClick="VK.face.load_album_more('+(VK._shows_photos+25)+');">More photos</a></div></div>');
            VK._shows_photos += 24;
        } else {
            var last = VK._photos_count-VK._shows_photos;
            for(var i = startid; i < VK._shows_photos+last; i++) {
                var v = VK._album_photos[i];
                $("#album_photos").append('<div class="album_photo_row"><a href="javascript:void(0);" onClick="VK.face.photo.show(\''+v.src_big+'\', \''+v.text+'\', '+i+');"><img src="'+v.src+'" /></a></div>');
            }
        }
        
    },
    
    shadow: {
        show: function() {
        
            if(!$("body").find("#shadow").is("div"))
            {
                if(!$.browser.msie)
                    $("body").append("<div id='shadow'></div>");
                else
                    $("body").append("<div id='shadow'><iframe scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%; filter:alpha(opacity=0)'></iframe></div>");
            }
            $("#shadow").fadeIn("fast");
        
        },
        
        hide: function() {
            $("#shadow").fadeOut("fast");
        }
    },
    
    photo: {
        
        show: function(src, text, i) {
        
            VK.face.shadow.show();

            $("body").append("<div id='photo_layer'><div id='photo' class='border_radius_5px'><div id='photo_content'><a href='javascript:void(0);' onClick='VK.face.photo.next();'><img id='photo_main' src='"+src+"' /></a><br /><br /><div id='photo_desc'>"+text+"</div><div id='photo_counters'>Photo "+(VK._photos_startid==0 ? i+1:i)+" of "+VK._photos_count+"</div></div></div><div id='photo_prev' onClick='VK.face.photo.prev();'><img src='/images/prev.png' /></div><div id='photo_close' onClick='VK.face.photo.hide();'><img src='/images/close.png' /></div></div>");
            $("#photo_layer").fadeIn("fast");
        
            var w_width = $(window).width();
            var w_height = $(window).height();
        
            var p_width = $("#photo").width();
            var p_height = $("#photo").height();
        
            var c_width = ((w_width-p_width)/2);
        
            $("#photo_layer").css('width', w_width);
            $("#photo_layer").css('height', w_height);
        
            $("#photo_prev").css('width', c_width);
            $("#photo_close").css('width', c_width);
            $("#photo_close").css('left', c_width+p_width);
            $("#photo").css('left', c_width);
            
            VK._photo_now = i;
        
        }, 
    
        hide: function() {
            
            $("#photo_layer").fadeOut("fast")
            VK.face.shadow.hide();
            $("#photo_layer").remove();
        
        },
        
        prev: function() {
            if(VK._photos_startid==0 && VK._photo_now-1 == VK._photos_count-1) {
                VK._photo_now--;
            }
            var previd=null;
            if(VK._photo_now-1 < VK._photos_startid) {
                previd = VK._photos_count-1+VK._photos_startid;
            } else {
                previd = VK._photo_now-1;
            }
            
            var nphoto = previd;
            if(VK._photos_startid == 0) {
                nphoto++;
            }
            
            var prevphoto = VK._album_photos[previd];
            $("#photo_main").attr("src", prevphoto.src_big);
            if(VK._photos_startid != 0) {
                $("#photo_desc").html(prevphoto.text);
            } else {
                $("#photo_desc").html('');
            }
            $("#photo_counters").html('Photo '+nphoto+' of '+VK._photos_count);
            VK._photo_now = previd;
            
        },
        
        next: function() {

            if(VK._photos_startid==0 && VK._photo_now+1 == VK._photos_count) {
                VK._photo_now++;
            }
            var nextid = null;
            if(VK._photo_now+1 >= VK._photos_count+VK._photos_startid) {
                nextid = VK._photos_startid;
            } else {
                nextid = VK._photo_now+1;
            }
            
            var nphoto = nextid;
            if(VK._photos_startid == 0) {
                nphoto++;
            }
                
            var nextphoto = VK._album_photos[nextid];
            $("#photo_main").attr("src", nextphoto.src_big);
            if(VK._photos_startid != 0) {
                $("#photo_desc").html(nextphoto.text);
            } else {
                $("#photo_desc").html('');
            }
            $("#photo_counters").html('Photo '+nphoto+' of '+VK._photos_count);
            VK._photo_now = nextid;
            
        }
        
    }
    
};

$(window).keydown(function(event) {

    if (event.keyCode == '27') {
	VK.face.photo.hide();
    }
    
    if (event.keyCode == '39') {
	VK.face.photo.next();
    }
    
    if (event.keyCode == '37') {
	VK.face.photo.prev();
    }
    
    

});
