var User = new Object();

// ID пользователя в БД
User.id = null;

// зашел ли пользователь к себе на страницу или чью-то другую
User.isMe=false;

// session id
User.session_id=null;

// может ли пользователь голосовать (по умолчанию false, меняется сразу после подгрузки результатов голосования)
User.allow_voting = false;

// показывает, находимся ли мы на странице редактирования или нет
User.editmode=false;

// загруженные слайды ленты активности
User.loadedSlides = new Array();

// загруженные избранные фото юзера
User.loadedFavPhotos = new Array();


// города
User.cities=[];

// подгрузка пользователей в выбранном городе
User.googleUsersWindow = function(lat, lng) {
    $.getJSON('/execplugin/?plg=profile&plugFunc=get_city_users', {lat:lat, lng:lng}, function(data){
        if(data.users)
        {
            var html=TrimPath.processDOMTemplate("google_window_tpl", data);
            $("#google_window").html(html).fadeIn();
        } else {
            alert('Тут никого нет...');
        }
    });
}

// лента загруженных фотографий (подгрузка при Cycle)
User.favPhotoHistory = function (slide, opts)
{
    $.getJSON('/execplugin/?plg=user&plugFunc=get_favorite_photos_history', {slide:slide, user:User.id}, function(photos){
        if(photos.length>0)
        {
            var html=TrimPath.processDOMTemplate("favphoto_li_tpl", {photos:photos});
            User.loadedFavPhotos.push(slide);
            opts.addSlide(html);
            $('.w_photo .w_ph_rgh[rel="fav"]').show();
        }
    });
}

// функция получения голосов (оценок) за пользователя
User.getVotes = function (id) {
    $.getJSON('/execplugin/?plg=user&plugFunc=getUserVotes', {id:id}, function(response){
        var html=TrimPath.processDOMTemplate('user_voting_tpl',response);
        User.allow_voting = response['allow_voting'];
        $(".ass").html(html);
    });
}

// функция голосования за пользователя
User.addVote = function (user_id, vote) {
    if(User.allow_voting)
    {
        $.getJSON('/execplugin/?plg=user&plugFunc=vote', {id:user_id, vote:vote}, function(response){
            // перегружаем результаты голосования
            User.getVotes(user_id);
        });
    }
}

// функция получения списка регионов страны
User.getCityAreas =  function (country)
{
    $.getJSON( '/execplugin/?plg=profile&plugFunc=getCityareas', {country:country}, function(cityareas){
        $(".cityarea_select").empty();
        for (c in cityareas)
        {
            $(".cityarea_select").append("<option value='"+cityareas[c]['id']+"'>"+cityareas[c]['c_name']+"</option>");
        }
        // подгружаем города первого попавшегося региона
        User.getCities(cityareas[0]['id']);
    });
}

// функция получения списка городов региона
User.getCities =  function (cityarea)
{
    $.getJSON( '/execplugin/?plg=profile&plugFunc=getCities', {cityarea:cityarea}, function(cities){
        $(".city_select").empty();
        for (c in cities)
        {
            $(".city_select").append("<option value='"+cities[c]['id']+"'>"+cities[c]['c_name']+"</option>");
        }
    });
}


// callback функция валидации формы редактирования профиля
User.editFormCallback = function (errors)
{
    $(".profile_validation_errors").remove();
    if(errors)
    {
        for (e in errors)
        {
            $("form .butt4").before("<p class='profile_validation_errors'><label>"+errors[e]['alias']+":</label>"+errors[e]['message']+"</p>");
        }
    }
}

// функция инициализации аплоадера
User.uploaderInit = function (selector) {
    $(selector).fileUpload ({
            'uploader'  : '/js/uploadify/uploader.swf',
            'script'    : '/execplugin/',
            'cancelImg' : '/js/uploadify/cancel.png',
            'auto'      : true,
            'folder'    : 'karamba',
            'fileDataName' : 'avatar_upload',
            'multi': false,
            'fileDesc' : 'JPEG файлы фотографий',
            'fileExt' : '*.jpg;*.jpeg;*.JPEG;*.JPG;',
            'buttonImg' : '/img/flash_butt.png',
            'width': 78,
            'height': 25,
            'wmode': 'transparent',
            'sizeLimit' : 300*1024,
            'scriptData': {'plg':'profile', 'plugFunc': 'uploadAvatar', 'session_id':User.session_id},
            'onComplete' : function (event,queueID,fileObj,response){
                $("#avatar_uploaded_result").val(0);
                switch(parseInt(response))
                {
                    case -1:
                      alert('Ошибка при закачки файла, файл закачан с ошибками.');
                    break;

                    case -2:
                      alert('Файл не является JPEG изобажением.');
                    break;

                    case -3:
                      alert('Закачиваемое изображение не должно превышать 300 Кб.');
                    break;

                    default:                      
                      // инициализируем кроппинг аватарки
                      var sizes=response.split(",");
                      User.avatarWidth=sizes[0];
                      User.avatarHeight=sizes[1];
                      $("#avatar_image").attr("src", "/i/0.jpg?"+Math.random()).load(function(){
                          // инициализируем кроппинг для новой картинки
                          if(User.JCrop)
                          {
                              // удаляем старый JCrop
//                              User.JCrop.destroy(); // не работет нормально, придется вручную это делать
                                $(".jcrop-holder").remove();
                                $("#avatar_image").show();
                          }
                          User.cropinit("#avatar_image");
                      });
                      $("#avatar_preview").attr("src", "/i/0.jpg?"+Math.random());
                      $('#avatar_preview').hide();
                      $("#avatar_uploaded_result").val(1);
                    break;
                }
            }
        });
}

// получение списка моделей по марке фотоаппарата
User.getLabelCameras = function (label)
{
    $.getJSON('/execplugin/?plg=profile&plugFunc=getLabelCameras', {label:label}, function(cameras){
        $("select[name='add_camera']").empty();
        if(cameras.length>0)
        {
            for(c in cameras)
            {
                $("select[name='add_camera']").append("<option value='"+cameras[c]['id']+"'>"+cameras[c]['c_name']+"</option>");
            }
        }
    });
}

// добавление камеры в список камер пользователя
User.addCamera = function (camera)
{
       $.getJSON('/execplugin/?plg=profile&plugFunc=addCamera', {camera:camera}, function(camera){
           if(parseInt(camera['new_id'])>0)
           {
                var html=TrimPath.processDOMTemplate("cameraRowTPL", {id:camera['new_id'], camera:camera['camera']});
                $("#profile_cameras_list").find(".empty").remove();
                $("#profile_cameras_list").append(html);
                $(".cameralabel_select").find("option[disabled='true']").attr('selected', true);
                $("select[name='add_camera']").empty().append("<option>[Выберете марку]</option>");

           }
       });
}

// получение списка моделей по марке объектива
User.getLabelLens = function (label)
{
    $.getJSON('/execplugin/?plg=profile&plugFunc=getLabelLens', {label:label}, function(lens){
        $("select[name='add_lens']").empty();
        if(lens.length>0)
        {
            for(c in lens)
            {
                $("select[name='add_lens']").append("<option value='"+lens[c]['id']+"'>"+lens[c]['c_name']+"</option>");
            }
        }
    });
}

// добавление линзы в список линз пользователя
User.addLens = function (lens)
{
       $.getJSON('/execplugin/?plg=profile&plugFunc=addLens', {lens:lens}, function(lens){
           if(parseInt(lens['new_id'])>0)
           {
                var html=TrimPath.processDOMTemplate("lensRowTPL", {id:lens['new_id'], lens:lens['lens']});
                $("#profile_lens_list").find(".empty").remove();
                $("#profile_lens_list").append(html);
                $("select[name='add_lens']").find("option[disabled='true']").attr('selected', true);
           }
       });
}

// JCROP API
User.JCrop = null;

// инициализация JCrop
User.cropinit = function (selector)
{
    if($(selector).length>0)
    {
        User.JCrop = $.Jcrop(selector,{'aspectRatio': 1/1, 'minSize': [100, 100], 'onChange': User.showAvatarThumb, 'onSelect': User.showAvatarThumb});
    }
}

User.showAvatarThumb = function(coords)
{
	var rx = 100 / coords.w;
	var ry = 100 / coords.h;
    $('#avatar_preview').show();
    $("#avatar_edit_coords").val(coords.x+','+coords.y+','+coords.w+','+coords.h);
	$('#avatar_preview').css({
		width: Math.round(rx * User.avatarWidth) + 'px',
		height: Math.round(ry * User.avatarHeight) + 'px',
		marginLeft: '-' + Math.round(rx * coords.x) + 'px',
		marginTop: '-' + Math.round(ry * coords.y) + 'px'
	});
}

// лента активности - подгрузка новых слайдов
User.activityHistory = function (slide, opts)
{
    $.getJSON('/execplugin/?plg=Activity&plugFunc=get_activity_history', {slide:slide}, function(activities){
        if(activities.length>0)
        {
            var html=TrimPath.processDOMTemplate("last_activities_tpl", {activities:activities});
            User.loadedSlides.push(slide);
            opts.addSlide(html);
        }
    });
}

// добавление контакта
User.addContact = function(id, el)
{
    $.getJSON('/execplugin/?plg=user&plugFunc=add_contact', {id:id}, function(response){
        if(parseInt(response)>0) {
            $(el).attr("rel", "del").text("Удалить из контактов");
        }
        else {
            alert('Возникли ошибки при удалении контакта.');
        }
    });
}

// удаление контакта
User.delContact = function(id, el)
{
    if(confirm('Действительно удалить этот контакт?')) {
        $.getJSON('/execplugin/?plg=user&plugFunc=delete_contact', {id:id}, function(response){
            if(parseInt(response)>0) {
                if($(el).hasClass("inline")) {
                    $(el).closest("li").fadeOut();
                    if($("ul.num li:visible").length<2) {
                        window.location.reload();
                    }
                }
                else {
                    $(el).attr("rel", "add").text("Добавить в контакты");
                }
            }
            else {
                alert('Возникли ошибки при удалении контакта.');
            }
        });
    }
}

// добавление автора в игнор
User.addIgnore = function (user, elem) {
    if(confirm('Действительно добавить в игнор?')) {
        $.getJSON('/execplugin/?plg=user&plugFunc=addIgnore', {user:user}, function(response){
            var el=($(elem).attr("target")=="self")? $(elem) : $(elem).closest("p");
            switch(parseInt(response))
            {
                case 1:
                    $(elem).attr("rel", "del");
                    el.text("Не игнорировать автора");
                break;

                case -1:
                    $(elem).attr("rel", "del");
                    el.text("Этот автор уже в избранном");
                break;

                case -2:
                    el.text("Нельзя добавить в игнор самого себя :)");
                break;
            }
        });
    }
}

// удаление автора из избранного
User.removeIgnore = function (user, elem) {
    if(confirm('Действительно удалить из игнора?')) {
        $.getJSON('/execplugin/?plg=user&plugFunc=removeIgnore', {user:user}, function(response){
            var el=($(elem).attr("target")=="self")? $(elem) : $(elem).closest("p");
            switch(parseInt(response))
            {
                case 1:
                    $(elem).attr("rel", "add");
                    el.text("Игнорировать автора");
                break;

                case -1:
                    el.text("Этого автора нет в игноре.");
                break;
            }
        });
    }
}

// перемещение фото из одного альбома в другой
User.movePhoto = function (photo, album)
{
       $.getJSON('/execplugin/?plg=user&plugFunc=movePhoto', {photo:photo, album:album}, function(response){
           if(parseInt(response)!=1) {
               alert('Произошла ошибка при перемещении фотографии в другой альбом.');
           }
       });
}
