$("#ff_load").ready( function () {
    selectLang();
    SwitchInset();
    //writeExpressLink();
    addSmiles();
    //addMap();

    privateAddBlack();
    privateDel();
    privateFromBlack();

    cloneUploadInputs();
    dellUploadInputs();
    searchSelect();

    UserDetail();

    photofileTopMenu();

    initTagsSuggest();
    
    if ($.browser.safari) {
        $("head").append('<link href="/themes/safari.css" rel="stylesheet" type="text/css"/>');
    }

});

// получить куку
function ff_GetCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
    begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}
// установить куку
function ff_SetCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}
// удалить куку
function ff_KillCookie(name) {
	ff_SetCookie(name, "", -1);
}

var matchCachedIndex = new RegExp("^http:\/\/"+document.location.hostname+(document.location.port?":"+document.location.port:"")+"(\/|\/\\?.*|\/index\.html)?$");
var host = 'http://' + document.location.hostname+(document.location.port?":"+document.location.port:"");
if ((ff_GetCookie('login') || ff_GetCookie('language')!= 'ru' || ff_GetCookie('autologin')) && matchCachedIndex.test(document.location.href)) {
    document.location.href = host + '/index.php';
}

// Показывает див по ID (добавляет класс act)
function showDiv(id) {
    $("#"+id+" a").blur();
    $('#' + id).toggleClass("act");
}

// выбор языков
function selectLang() {
    var block = false;
    $("#ff_select_lang").click(function() {
        $(this).blur();
        $("#ff_lang").attr("class", "langsv");
        block = true;
    });
    $(document).click(function() {
        if(block) {block = false;}
        else {
            if($("#ff_lang").hasClass("langsv")) {
                $("#ff_lang").attr("class", "langs");
            }
        }
    });
}


// показывает скрывает дополнительные опции поиска
function searchSelect() {
    var block = false;
    $("#ff_search_selector").click(function() {
        $(this).blur();
        if($("#ff_search_type").hasClass("dn")) {
            $("#ff_search_type").removeClass("dn");
            block = true;
        }
    });
    $(document).click(function() {
        if(block) {block = false;}
        else {
            if(!$("#ff_search_type").hasClass("dn")) {
                $("#ff_search_type").addClass("dn");
            }
        }
    });
}

// меняет тип поиска
function SearchFrom(name, obj) {
    $("div.search ul li.current").removeClass("current");
    if (obj) $(obj.parentNode).addClass("current");
    $("#ff_search_act").val(name);
    $("#search_ico").attr("class", "text search_pic " + name)
    $("#search_string").focus();
}


// еще Теги (метки)
var hidden_tags = "";
function getAllTags() {
    if (hidden_tags == "") {
        hidden_tags = $("#ff_site_clouds").html();
        $("#ff_site_clouds").html("<div class='center'><img src='/themes/stand_ru/i/loade.gif' alt='' /></div>");
        $("#ff_site_clouds").load($("#ff_show_tags").attr("href"));
        $("#ff_show_tags").html("Свернуть метки");//addClass("dn");
    } else {
        $("#ff_site_clouds").html(hidden_tags);
        $("#ff_show_tags").html("Ещё метки");
        hidden_tags = "";
    }
}


/// ДЛЯ ФОРМЫ АВТОРИЗАЦИИ
// Чистит поля логина и пароля и наоборот
var login_form_focus = false;
function loginFormSelecter() {
    if($.trim($("#ff_auth_login").val()) == "") {
        clearLogin();
    }
    if ($.trim($("#ff_auth_pass").val()) == "") {
        clearPass();
    }

    $("#ff_auth_login").focus(function () {
        clearLogin(true);clearPass(true);
    }).blur( function () {
        if ($(this).val().length == 0) {
            clearLogin();clearPass();
        }
    });

    $("#ff_auth_pass").focus(function () {
        clearPass(true);
    }).blur( function () {
        if ($(this).val().length == 0) {
            clearPass();
        }
    });
}
// чистит/заполняет логин
function clearLogin(flag) {
    if(flag) {
        $("#ff_auth_login").removeClass("auth_login");
        //$("#ff_auth_login").css("background", "#FFF");
    } else {
        $("#ff_auth_login").addClass("auth_login");
        //$("#ff_auth_login").css("background", "#FFF url(/themes/stand_ru/i/triangle.gif) no-repeat -313px -166px");
    }
}
// чистит/заполняет пароль
function clearPass(flag) {
    if (flag) {
        $("#ff_auth_pass").removeClass("auth_pass");
        //$("#ff_auth_pass").css("background", "#FFF");
    } else {
    	$("#ff_auth_pass").addClass("auth_pass");
        //$("#ff_auth_pass").css("background", "#FFF url(/themes/stand_ru/i/triangle.gif) no-repeat -313px -183px");
    }
}
/// ДЛЯ ФОРМЫ АВТОРИЗАЦИИ



/* переключалка вкладок */
function SwitchInset() {
    $("ul.inset_b li, ul.inset_w li").click(function () {
        var ul  = $(this).parent();
        var div = ul.parent();
        var new_text = div.find("div.inset").eq(ul.find("li").index(this));
        var location = $(this).find("a").attr("href");

        ul.find("li.act").removeClass("act");    // делаем активную вкладку не активной
        $(this).addClass("act");                 // делаем выбранную вкладку активной

        if(location) {window.location = location;} // если вкладка является ссылкой

        div.find("div.inset").addClass("dn");    // скрываем все дивы
        new_text.removeClass("dn");              // показываем выбранный див

        //div.find("div.inset input, div.inset textarea, div.inset select").attr("disabled","disabled");  // отключаем все инпуты
        div.find("div.inset input").attr("disabled","disabled");  // отключаем все инпуты
        if(document.getElementById("water_type_0")) document.getElementById("water_type_0").disabled=true;
        if(document.getElementById("water_type_1")) document.getElementById("water_type_1").disabled=true;
        if(document.getElementById("water_type_2")) document.getElementById("water_type_2").disabled=true;
        new_text.find("input:disabled, textarea:disabled, select:disabled").removeAttr("disabled");      // включаем инпуты в выбраной вкладке
    })
}


/* добавление смайликов */
function addSmiles() {
	if($("div.smiles img")) {
	    $("div.smiles img").click(function(){
	        var mess = ($("#for_smiles").attr("value")) ? $("#for_smiles").attr("value") : "";
	        $("#for_smiles").attr("value", mess + $(this).attr("title"));
	        $("#for_smiles").focus();
	    });
	}
}


// Личка - в черный список
function privateAddBlack() {
    $("#ff_private_black").click(function() {
        if ($("td.com_messege input:checked").length > 0) {
            if (window.confirm("Вы действительно хотите переместить выбранные контакты в черный список?")) {
                $("#ff_private_form").attr("action", "/private/blacklist/add/?from=?from=contact_list").submit();
            }
        }
        else {
            alert("Не выделено ни одного контакта.");
            return false;
        }
    })
}

// Личка - удалить
function privateDel() {
    $("#ff_private_del").click(function() {
        if ($("td.com_messege input:checked").length > 0) {
            if (window.confirm("Вы действительно хотите удалить выбранные контакты?")) {
                $("#ff_private_form").submit();
            }
        }
        else {
            alert("Не выделено ни одного контакта.");
            return false;
        }
    })
}

// Личка - из черного списка
function privateFromBlack() {
    $("#ff_private_del_black").click(function() {
        if ($("td.com_messege input:checked").length > 0) {
            if (window.confirm("Вы действительно хотите удалить выбранные контакты из черного списка?")) {
                $("#ff_private_form").attr("action", "/private/blacklist/restore/?from=black_list").submit();
            }
        }
        else {
            alert("Не выделено ни одного контакта.");
            return false;
        }
    })
}

// открывает окно личных сообщений
function openMessageDialog(user)
{
    var params = "width=" + 650 + ", height=" +  570 + ",menubar=no,location=no,resizable=no,scrollbars=no,status=no,titlebar=no";
    myDate = new Date();
    newWin = window.open('/private/dialog/'+user+'/?page=lastPage', 'newWin_'+myDate.getTime(), params);
    newWin.focus();
    if (private_messages_timer) {
        clearTimeout(private_messages_timer);
        private_messages_timer = false;
    }
    private_messages_timer = setTimeout("privateMesseges()", 3000);
}


// вставляет еще поле (загрузка фоток)
var input_for_clone = new Array();
function cloneUploadInputs() {  
    var a = $("a.add_input");
    for (i = 0; i < a.length; i++) {
        var id = "photos_" + a[i].id;
        var obj = id ? $("#"+id+" tr.form:first") : false;
        if (obj) input_for_clone[id] = obj.clone(true);
    }
    $("a.add_input").click(function() {
        var id = "photos_" + $(this).attr("id");
        if ($("#"+id+" tr.form").length < 15) {
            input_for_clone[id].clone(true).insertAfter("#"+id+" tr.form:last").find("input").val("");
            $("#"+id+" a.del").removeClass("dn");
        }
        if ($("#"+id+" tr.form").length > 14) {
            $(this).addClass("dn");
        }
        return false;
    })
}

// удаляет одно поле (загрузка фоток)
function dellUploadInputs() {
    $("a.remove_input").click(function() {
        var id = $(this).parents("table").attr("id");
        $(this).parents("tr").remove();

        if ($("#"+id+" tr.form").length < 2) {
            $("#"+id+" a.remove_input").addClass("dn");
        }
        if ($("#"+id+" tr.form").length < 15) {
            $("#"+id+" a.add_input").removeClass("dn");
        }
        return false;
    })
}


// навигация по стрелочкам
function NavigateThrough() {
    var in_input = false;
    $(document).keydown(function(event){
        if (event.ctrlKey) {
            $("input, textarea").focus(function () {
                in_input = true;
            }).blur(function() {
                in_input = false;
            });
            if (!in_input) {
                if(event.ctrlKey && event.keyCode == 37 && $("#PrevLink").attr('href')) {
                    document.location = $("#PrevLink").attr("href");
                }
                else if(event.ctrlKey && event.keyCode == 39 && $("#NextLink").attr('href')) {
                    document.location = $("#NextLink").attr("href");
                }
            }
        }        
    });
}


// получить ссылку
function getLink(login, album, photo, show) {
    show = (show) ? show : "getlink";
    $('div.popup').removeClass("act");
    showDiv('ff_get_link');
    var photo_id = (photo) ? "&photo_id="+photo : "";
    $("#ff_get_link").load("/popup/?show="+show+"&login="+login+"&album_id="+album+photo_id, function() {
        SwitchInset();
    });
}

// отправить ссылку
function sendLink(login, album, pass, photo, show) {
    show = (show) ? show : "sendlink";
    $('div.popup').removeClass("act");
    showDiv('ff_send_link');
    var photo_id = (photo) ? "&photo_id="+photo : "";
    $("#ff_send_link").load("/popup/?show="+show+"&login="+login+"&album_id="+album+"&pass="+pass+photo_id);
}

// стать лидером
function forTop(login, photo, show) {
    $('div.popup').removeClass("act");
    $('#fortop').addClass("act");
    $('#fortop_center').load('/ajax/phototop/pay/', {photo_id: photo, photo_login: login});
}

//пожаловаться на фото
function getComplaint(photo) {

    alert('Извините, эта функция временно не работает.');
}

// отправить в блог
function sendBlog(login, album) {
    showDiv('ff_send_blog');
    $("#ff_send_blog").load("/popup/?show=albumblog&login="+login+"&album_id="+album);
}

// получить ссылку для конкурса
function getLinkContest(login, concurs_id, photos_id) {
    $('div.popup').removeClass("act");
    showDiv('ff_get_link');
    $("#ff_get_link").load("/popup/?show=contestgetlink&login=" + login + "&contest_id=" + concurs_id + "&contest_photo_id=" + photos_id, function() {
        SwitchInset();
    });
}

// отправить ссылку для конкурса
function sendLinkContest(login, contest_id, photos_id) {
    $('div.popup').removeClass("act");
    showDiv('ff_send_link');
    $("#ff_send_link").load("/popup/?show=contestsendlink&login=" + login + "&contest_id=" + contest_id + "&contest_photo_id=" + photos_id);
}

//фото на мобильный
function getMobile(url){
    var params = "width=780,height=800,menubar=no,location=no,resizable=no,scrollbars=yes";
    newWin = window.open('http://mobile.relax.ru/resizer/?channel=104&url='+url, 'newWin', params);
    newWin.focus();
}

// подтверждение email
function EmailConfirmQIP() {
    $.get("/users/" + MyUser.getLogin() + "/update/confirm/", function(data) {
            alert('Письмо для подтверждения отправлено на регистрационный e-mail: ' + data);
            window.history.back();
    });
}

function EmailConfirm() {
    $.get("/users/" + MyUser.getLogin() + "/update/confirm/", function() {
            alert('Письмо с ссылкой для подтверждения выслано на Ваш e-mail');
    });
}

// для звездочек рейтинга
var isVote = 0;
function overStar(pos, Id) {
    isVote = 0;
    var div = document.getElementById('rating_' + Id);
    var stars = div.getElementsByTagName("A");
    var stsus = document.getElementById("status_" + Id);
    var stsus_text = new Array();
    stsus_text[0] = "Хм, стоит вернуться к теории...";
    stsus_text[1] = "Неплохо для новичка";
    stsus_text[2] = "Есть к чему стремится";
    stsus_text[3] = "Работа достойная мастера";
    stsus_text[4] = "Браво, Ваша работа вызывает восхищение!";

    var temp = new Array();
    for (var i = 0; i <= 4; i++) {
        temp[i] = stars[i].className;
    }
    for (var i = 0; i <= pos; i++) {
        stars[i].className = "golos";
        if (stsus) stsus.firstChild.nodeValue = stsus_text[i];
    }
    div.onmouseout = function () {
        if (isVote == 0) {
            for (var i = 0; i <= 4; i++) {
                stars[i].className = temp[i];
            }
            if (stsus) stsus.firstChild.nodeValue = "Проголосовать";
        }
        else {
          if (stsus) stsus.firstChild.nodeValue = "Ваша оценка";
        }
    }
}

// Голосование за фотку
function PhotoVote (user, album_id, photo_id, vote) {
    isVote = 1;
    $.ajax({type: "POST", url: "/ajax/photo_vote/"+user+"/"+album_id+"/"+photo_id+"/", data: "vote="+vote, success: function(msg){
            //$("#ratingAll_"+photo_id).html("").append(msg);
            location.reload();
        }
    });
}

// показать инпут переименования
function showRenameInput(id) {
    $("#rename_"+id).addClass("act");
    $("#rename_"+id+" input").focus();

    $("#rename_"+id+" input").keydown(function(event){
        if(event.keyCode == 13) {
            $("#rename_"+id).removeClass("act");
            $("#rename_"+id+" form").submit;
        }
    });
}


// показать информацию об авторе
function UserDetail() {
    $("#ff_detail").click(function() {
        $("table.userInfo tr.dn").removeClass("dn");
        $(this).addClass("dn");
    });
}

// функция верхнего меню (руки прочь!)
function photofileTopMenu() {
    var id;
    var block;
    var hover = false;
    
    $("#ff_usermenu a").click(function() {
        id = $(this).parent().attr("id");
        block = true;
        if (id) {
            if($(this).parent().attr("tagName") != "SPAN") {
                if($("#"+id).hasClass("act")) {
                    $("#"+id).removeClass("act");
                    hover = false;
                } else {
                    $("#ff_usermenu .act").removeClass("act");
                    $("#"+id).addClass("act");
                    hover = true;
                }
            }
        }
        if (navigator.appName.indexOf("Microsoft") != -1) $("#ff_album_id").css('display', hover ? 'none' : '');
        $(this).blur();
    });
    
    $(document).click(function() {
        if(block) {block = false;}
        else {$(".usermenu .act").removeClass("act");hover = false;$("#ff_album_id").css('display', '');}
    });
    
    $("#ff_usermenu .usermenu").hover(
        function() {
            if(hover){
                $("#ff_usermenu .act").removeClass("act");
                $(this).addClass("act");    
            }
        },
        function() {
            return false;
        }
    )
}


// запрос оригинала фотки
function ShowMePhoto(id, login) {
    if (!ShowMePhoto.ids) ShowMePhoto.ids = new Array();
    $('.popup').removeClass('act');
    if (!ShowMePhoto.ids[id]) {
        var wait = $("<div class='center'><img src='/themes/stand_ru/i/loade.gif' alt='' /></div>");
        $("#ff_show_original_"+id).append(wait);
        showDiv("ff_show_original_"+id);
        wait.remove();
        $('<div class="mar"></div>').load("/popup/?show=protected&login=" + login + "&photo_id=" + id).appendTo($("#ff_show_original_"+id));
        ShowMePhoto.ids[id] = true;
    } else {
        showDiv("ff_show_original_"+id);
    }
}


// отправка СМС за фотку
function showSmsPopup(photo_id, genre, fishy, moderated, password, user)
{
    if (password != '') {
        var file = 4;
    } else if (moderated != 1) {
        var file = 2;
    } else if (fishy == 1) {
        var file = 3;
    } else if (genre == 107 || genre == 29 || genre == 10) {
        var file = 5;
    } else {
        var file = 1;
    }

    if($("#ff_smspop" + photo_id).text() != "") {
        $('#ff_smspop' + photo_id).toggle();
    }
    else {
        $("#ff_smspop" + photo_id).load("/popup/?show=sms&file=" + file + "&photo_id=" + photo_id + "&genre=" + genre + "&login=" + user);
        $('#ff_smspop' + photo_id).toggle();
    }
}

// отправка СМС за фотку в конкурс
function showConcursSmsPopup(photo_id, status, user) {
    if (status == 0) {
        var file = 2;
    } else if (status == 2) {
        var file = 3;
    } else {
        var file = 6;
    }

    if($("#ff_smspop" + photo_id).text() != "") {
        showDiv('ff_smspop' + photo_id);
    }
    else {
        $("#ff_smspop" + photo_id).load("/popup/?show=sms&file=" + file + "&photo_id=" + photo_id + "&login=" + user);
        showDiv('ff_smspop' + photo_id);
    }
}


var private_messages_timer = false;
// проверяет личку
// вызывается в хедере
function privateMesseges() {
    if (private_messages_timer) {
        clearTimeout(private_messages_timer);
        private_messages_timer = false;
    }
    $.ajax({
        type: "GET",
        url: "/private/blink/new/",
        data: "page=lastPage&check=1",
        success: function(msg){
            if(msg != 0) {
                $("#ff_new_letter").html('<a href="/private/" class="link14" title="Есть новые сообщения"></a>');
                $("#ff_count_new_letter").text(msg);
                if ($.browser.msie) {
                    window.setTimeout(function () {
                        window.external.msSiteModeSetIconOverlay("http://photo.qip.ru/images/overlay.ico", "Есть новые сообщения");
                        window.external.msSiteModeActivate();
                    }, 200);
                }
            }
            else {
                $("#ff_new_letter").html('');
                $("#ff_count_new_letter").text("0");
            }
        }
    });
    private_messages_timer = setTimeout("privateMesseges()", 60000);
}

// показ оригинала фоток
function open_window_protection(WindowWidth, WindowHeight, url){
    var params = "width=" + (WindowWidth == 0 ? 800 : WindowWidth+40) + ", height=" + (WindowHeight == 0 ? 700 : WindowHeight+80) + ", menubar=no,location=no,resizable=yes,scrollbars=yes";
    var newWin = window.open(url, '_blank', params);
    newWin.focus();
}

// поворачивает фотку
function rotatePhotos(param, photo_id, album_id) {
    $("#" + photo_id).animate({opacity: 0.4}, 500);
    if(!$("#" + photo_id).hasClass("rotate")) {
        $("#" + photo_id).addClass("rotate");
        $.ajax({
            type: "POST",
            url: '/photo/' + MyUser.getLogin() + '/' + album_id + '/' + photo_id + '/do/',
            data: "access=ajax&act=rotate&album_id=" + album_id +"&param=" + param,
            success: function(msg){
                if(msg == "success"){
                    $("#" + photo_id).removeClass("rotate");
                    var s = $("#"+photo_id+" img").attr("src");
                    $("#"+photo_id+" img").attr("src", (s.indexOf("?") < 0 ? s : s.substr(0, s.indexOf('?')))+"?r="+Math.floor(Math.random()*1000000000));
                }
                else {
                    alert("При попытке повернуть фотографию, возникли ошибки.");
                }
                $("#" + photo_id).animate({opacity: 1}, 500);
            }
        });
    }
}

// подгрузка ватермарка
function showCopyright(page) {
    page = (page) ? page : "copyright";
    if($("#show_copyr").text() == "") {
        $("#show_copyr").append('<div class="center"><img src="/themes/stand_ru/i/loade.gif" alt="" /></div>').load("/users/" + MyUser.getLogin() + "/watermark/", "", function() {
            if(page == "copyright") {
                $("#ff_copyr_reset").remove();
                $("#ff_zag_copyr").remove();
            }
            $("#ff_return").val(page);
            SwitchInset();
            WatermarkInit();
        });
        showDiv('show_copyr');
    }
    else {
        showDiv('show_copyr');
    }
}

// показывает попап запроса на дружбу
function ShowRequestFriending(userId, a_login){
    if($("#ff_friending").text() == "") {
        var pars = 'show=friendingApprove&user_id=' + userId + '&user_login=' + a_login;
        $.get("/popup/?" + pars, function(data){
            $("#ff_friending").append(data);
            $('#ff_friending').toggle();
        });
    }
    else {
        $('#ff_friending').toggle();
    }
}

//подсказки при заполнении тегов
function initTagsSuggest()  {
    if (!$("#ff_photo_tags")) return false;

    var _oldval, _newval;
    var div = $('#ff_tags_suggest');

    $("#ff_photo_tags").focus(function() {
        _oldval = $('#ff_photo_tags').val().toLowerCase();
        _newval = false;
    }).blur(function(e) {
        setTimeout(function() {div.addClass('dn')}, 500);
    }).keydown(function(e) {
        if (e.KeyCode == 38 || e.KeyCode == 40) {
            e.preventDefault();
        }
    }).keyup(function(e) {
        if (e.KeyCode == 38 || e.KeyCode == 40) {
            e.preventDefault();
        }
        _newval = e.target.value.toLowerCase();

        if(_newval != _oldval) {
            var old_arr = _oldval.split(' ');
            var new_arr = _newval.split(' ');
            var word = false;
            var num  = false;

            for(var i=0;i<old_arr.length;i++) {
                if (old_arr[i] != new_arr[i]) {
                    word = new_arr[i];
                    num = i;
                }
            }

            if (word && word.length > 2) {

                $.get('/tags/suggest/', {tag: word}, function(r){
                    var data = eval("(" + r + ")").suggestions;
                    if (data.length < 1) {div.addClass('dn');return;}

                    div.empty().removeClass('dn');
                    for (var i = 0; i < data.length; i++) {
                        $('<a></a>').text(data[i].tag).click(function(e) {
                            new_arr[num] = $(this).text();
                            $('#ff_photo_tags').val(new_arr.join(' '));
                            div.addClass('dn');
                        }).appendTo(div);
                    }
                });
            } else {
                div.addClass('dn');
            }
        }
        _oldval = _newval;
    });
}


function cityLocation(val, type, fn) {
    
    switch (type) {
        case 'country':
            if(val != "0") {
                $("#ff_location_region select").html('<option value="0">Загрузка...</option>');
                $("#ff_location_region").load("/ajax/location/?type=region&value=" + val, {}, fn);
                $("#ff_location_city select").html('<option value="0">Не имеет занчения</option>').attr("disabled", "disabled");
            }
            else {
                $("#ff_location_region select").html('<option value="0">Не имеет занчения</option>').attr("disabled", "disabled");
                $("#ff_location_city select").html('<option value="0">Не имеет занчения</option>').attr("disabled", "disabled");
                
            }
            break;
        case 'region':
            if(val != "0") {
                $("#ff_location_city select").html('<option value="0">Загрузка...</option>');
                $("#ff_location_city").load("/ajax/location/?type=city&value=" + val, {}, fn);
            }
            else {
                $("#ff_location_city select").html('<option value="0">Не имеет занчения</option>').attr("disabled", "disabled");   
            }
            break;
    }
}

function writeExpressLink() {
    var login = ff_GetCookie('express_user');
    if(login != null && location.host == 'photofile.ru') {
        if(login.length == 64) {
            $('#ff_express_photo').html('<div class="hr">&nbsp;</div><a href="\http://express.'+window.location.host+'\/" >Временные фотографии<\/a>');
        }
    }
}


// активирует подсказку для тегов. В разработке
function activTagsHelper() {
    $("#ff_new_tag").keyup(function(event){
        if($(this).val().length > 2) {
            switch(event.keyCode) {
                case(40):
                    nextTagsLink('down');
                break;
                case(38):
                    nextTagsLink('up');
                break;
                case(13):
                    selectTagsLink();
                break;
                default:
                    loadTagsLink($(this).val());
                break;
            }
        }
    });
}

/// БОЛЬШОЙ ВОПРОС
/*
function addMap() {
    $("#ff_lol").attr("usemap", "eggs");
    $("body").append('<map name="eggs"><area shape="circle" coords="123, 22, 2" href="/" onclick="showEggs(); this.blur(); return false;" title="Фотофайл" alt="Координаты для червяка"/></map>');
}

function showEggs() {
    $("#site").append('<img src="/themes/stand_ru/i/egg.gif" style="position: absolute; left: 6px; top: 48px" alt="" />');
}
*/
/// БОЛЬШОЙ ВОПРОС

function trim(str) {
    a = str.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};

function htmlspecialchars (strIn){
	strIn = ''+strIn;
    reg_from = '/&/g';
    reg_to = "&amp;";
    var str = strIn.replace(reg_from, reg_to);
    reg_from = /"/g;
    reg_to = "&quot;";
    str = str.replace(reg_from, reg_to);
    reg_from = /'/g;
    reg_to = "&#039;";
    str = str.replace(reg_from, reg_to);
    reg_from = /</g;
    reg_to = "&lt;";
    str = str.replace(reg_from, reg_to);
    reg_from = />/g;
    reg_to = "&gt;";
    return str.replace(reg_from, reg_to);
}

function  CheckComplaints(oForm){
    if((oForm.sReason.value==0) || (oForm.sReason.value==99 && trim(oForm.comments.value)=="")){
        return;
    }
    //oForm.submit();
    $.ajax({type: "POST", data:{'ajax':1, 'sReason':oForm.sReason.value, 'textReason':oForm.textReason.value, 'comments':oForm.comments.value}, url: oForm.action, dataType: "text", async: false, success: SuccessComplaints});
}

function SuccessComplaints() {
    alert("Ваша жалоба была отправлена администратору. Спасибо за участие.");
}

function complainSet(obj){
    obj.form.sReason.value = obj.value;
    obj.form.textReason.value = obj.title;
}

function UserFavoritesCheckAll(){
    if($('#ff_favorite table input.check[@checked=1]').length == $('#ff_favorite table input.check').length){
        $('#ff_select_all').attr('checked',true);
    }
    else{
        $('#ff_select_all').removeAttr('checked');
    }

}

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

// очистка поля ввода
function clearField(obj) {
    obj.value = "";
}

// disable для комментов
var add_button_timeout_id = 0;
function blockAddButton() {

    if (document.getElementById("for_smiles") && $('#for_smiles').val().replace(/\s+/g, '').length > 2) {
        $('#button_submit_comment').attr('disabled', false);
    } else if (document.getElementById("comment_for") && $('#comment_for').val().replace(/\s+/g, '').length > 2 && $('#comment_against').val().replace(/\s+/g, '').length > 2 && $('#comment_general').val().replace(/\s+/g, '').length > 2 && $('#id_vote').val() > 0) {
        $('#button_submit_comment').attr('disabled', false);
    } else {
        $('#button_submit_comment').attr('disabled', true);
    }

    if (add_button_timeout_id != 0) clearTimeout(add_button_timeout_id);

    add_button_timeout_id = setTimeout("blockAddButton();", 250);
}

function wait_blockAddButton() {
    if (add_button_timeout_id != 0) {
        clearTimeout(add_button_timeout_id);
        add_button_timeout_id = setTimeout("blockAddButton();", 3000);
    }
}

// проверка чекбоксов
function check_chb (obj) 
{
	for (var i = 0; i < obj.elements.length; i++) {
		if (obj.elements[i].type == "checkbox" && obj.elements[i].checked) {
			return true;
		}
	}
	return false;
}

// проверка тэгов
function check_tag (str) {
    var re = /[^А-яA-z0-9 _-]+/i;
    if (str == "") return true;
    return str.replace(re, "").length <= 2 ? false : true;
}

// Позиционирование

function getScrollTop() {
    // get scroll - all browser compatible
	var scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}

function getPageSize()
{    
    var xScroll, yScroll;
    
    if (window.innerHeight && window.scrollMaxY) {	
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }	
    
    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight){
        pageHeight = windowHeight;
    } else { 
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth){	
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }
    arrayPageSize = new Array (pageWidth,pageHeight,windowWidth,windowHeight) 
    return arrayPageSize;
}

// Показывает див в центре по ID (добавляет класс act)
var cover;
function showDivCenter(id) {
    if (!cover) {
        cover = document.createElement("div");
        cover.className = "popup_cover";
        //document.body.appendChild(cover);
        
        var obj = document.getElementById(id);
        var parentDiv = obj.parentNode;

        parentDiv.insertBefore(cover, obj);
    }

    PageSize = getPageSize();
        
    cover.style.height = PageSize[1] + "px";
    cover.style.display = "block";

    $("#"+id+" a").blur();
    $('#' + id).toggleClass("act");

    $('#' + id).css("position", "absolute");
    $('#' + id).css("top", (150 + getScrollTop()) + "px");
    $('#' + id).css("left", (PageSize[2]/2 - 230) + "px");
    
    //if (navigator.appName.indexOf("Microsoft") != -1) $('.popup_cover').css("z-index", -1);
}

function hideDivCenter(id, reloadIE) {
    if (arguments.length == 1 && navigator.appName.indexOf("Microsoft") != -1) location.reload();

    cover.style.display = "none";

    $("#"+id+" a").blur();
    $('#' + id).toggleClass("act");
}

// отправить в блог
function downloadAlbum(login, album) {
    showDivCenter('ff_download_album');
    $("#ff_download_album").load("/popup/?show=downloadalbum&login="+login+"&album_id="+album);
}

function getAuthForm() {
    if ($(".popuplogin").length > 0) {
        $(".popuplogin").show();
    } else {
        $("body").prepend('<div class="popuplogin"><b class="closebox" title="Закрыть" onclick="hideAuthForm()"></b><div class="center"><img src="/themes/qip_ru/i/loade.gif" alt="" /></div></div>');
        $(".popuplogin").css("top", (($(window).width() > 800 ? 280 : 100) + getScrollTop()) + "px");
        $(".popuplogin").css("left", $(window).width() > 800 ? "30%" : ($(window).width() - 450) / 2 + "px");
        $(".popuplogin").load("/popup/?show=authform");
    }
    document.getElementById("ff_popup_login").focus();
}

function hideAuthForm() {
    $(".popuplogin").hide();
    $(".demotivatorbox").hide();
}

function ChallengeForBattle(login, id_photo) {
    if ($(".popuplogin").length > 0) {
        $(".popuplogin").show();
    } else {
        $("body").prepend('<div class="popuplogin"><b class="closebox" title="Закрыть" onclick="hideChallengeForm()"></b><div class="center"><img src="/themes/qip_ru/i/loade.gif" alt="" /></div></div>');
        $(".popuplogin").css("top", (($(window).width() > 800 ? 280 : 100) + getScrollTop()) + "px");
        $(".popuplogin").css("left", $(window).width() > 800 ? "30%" : ($(window).width() - 450) / 2 + "px");
        $(".popuplogin").load("/popup/?show=challengeforbattle&login="+login+"&id_photo="+id_photo+"&me="+MyUser.getLogin());
    }
}

function hideChallengeForm() {
    $(".popuplogin").hide();
}

// создание и отправка формы
function getNewSubmitForm(){
    var submitForm = document.createElement("form");
    document.body.appendChild(submitForm);
    submitForm.method = "post";
    return submitForm;
}

function createNewFormElement(inputForm, elementName, elementValue){
    var newElement = document.createElement("input");
    newElement.name = elementName;
    newElement.type = "hidden";
    newElement.value = elementValue;
    inputForm.appendChild(newElement);
    return newElement;
}

function PrintAlbumSubmit(url){
    var submitForm = getNewSubmitForm();
    createNewFormElement(submitForm, "action_elements[0]", "all");
    createNewFormElement(submitForm, "ret", location.href);
    submitForm.action= url;
    submitForm.submit();
}

// кнопка печати фоток
function AddToPrintCart(url, photo_data) {
    var parts;
    
    $("#add_to_print_img1").hide();

    $.post(url, {'action_elements[]':photo_data}, function(data, textStatus) {
        if (data.indexOf("OK") == 0) {
            parts = data.split(';');
            $("#add_to_print_msg").fadeIn('fast');
            setTimeout(function(){$("#add_to_print_msg").hide();$("#add_to_print_img1").fadeIn('fast');}, 1500);
            //$("#ff_new_backet").html('<a href="/users/'+ MyUser.getLoMyUsegin() +'/print_cart/"><img src="/images/new_backet.gif" alt="" /></a>');
            $("#print_cart_counter").html("Корзина печати (" + parts[1] + ")");
            $("#print_cart_counter").addClass('full');
        } else if (data.length < 1024) {
            location.href=data;
        } else {
            location.href='./';
        }
    });
}

// удаление фоток
function PrintOrderRemove(photo_id) {
    $.get("/users/" + MyUser.getLogin() + "/print_cart/del/" + photo_id + "/", function(data) {
        if (data.length > 0 && data.length < 11) {
            $("#id_photo_" + data).hide();
            $("#id_nophoto_" + data).show();
            $("input[name='photos[]'][value=" + data + "]").val(0);
            
            if ($("input[name='photos[]']").length == $("input[name='photos[]'][value=0]").length) location.href = "/users/" + MyUser.getLogin() + "/print_cart/";
        }
    });
}

// для звездочек фотомаркета
function overMarketStar(pos) { 
    var div = document.getElementById('rating_0');
    if ($("#id_vote").val() > 0) {
        //div.onmouseout = function () {};
        return;
    }
    var stars = div.getElementsByTagName("A");
    var stsus = document.getElementById("status_0");
    var stsus_text = new Array();
    stsus_text[0] = "Ужасная модель";
    stsus_text[1] = "Плохая модель";
    stsus_text[2] = "Обычная модель";
    stsus_text[3] = "Хорошая модель";
    stsus_text[4] = "Отличная модель!";

    var temp = new Array();
    for (var i = 0; i <= 4; i++) {
        temp[i] = stars[i].className;
    }
    for (var i = 0; i <= pos; i++) {
        stars[i].className = "golos";
        if (stsus) stsus.firstChild.nodeValue = stsus_text[i];
    }
    div.onmouseout = function () {
        if ($("#id_vote").val() == 0) {
            for (var i = 0; i <= 4; i++) {
                stars[i].className = temp[i];
            }
            if (stsus) stsus.firstChild.nodeValue = "Оценить";
        }
        else {
          //stsus.firstChild.nodeValue = "Ваша оценка";
        }
    }
}

function clickMarketStar(pos) { 
    var div = document.getElementById('rating_0');
    $("#id_vote").val(pos + 1);
    var stars = div.getElementsByTagName("A");
    var stsus = document.getElementById("status_0");
    var stsus_text = new Array();
    stsus_text[0] = "Ужасная модель";
    stsus_text[1] = "Плохая модель";
    stsus_text[2] = "Обычная модель";
    stsus_text[3] = "Хорошая модель";
    stsus_text[4] = "Отличная модель!";

    for (var i = 0; i <= 4; i++) {
        stars[i].className = (i <= pos) ? "golos" : "empty";
    }
    if (stsus) stsus.firstChild.nodeValue = stsus_text[pos];
}

function MarketOptionChanged(obj) {
    var el = document.getElementById(obj.id == "id_type" ? "id_producer" : "id_type");
    var test_pair;
    var test_flag;

	if (obj && el) {
		for (var i = 0; i < obj.options.length; i++) {
			if (obj.options[i].selected) {
			    for (var j = 1; j < el.options.length; j++) {
			        if (i > 0) {
    			        test_pair = obj.id == "id_type" ? obj.options[i].value+ ":" + el.options[j].value : el.options[j].value + ":" + obj.options[i].value;
    			        test_flag = false;
    			        for (var k = 0; k < existing_pairs.length; k++) {
    			            if (existing_pairs[k] == test_pair) {
    			                test_flag = true;
    			                break;
    			            }
    			        }
			        } else {
			            test_flag = true;
			        }
		            el.options[j].style.color = test_flag ? "" : "#888888";
		            if (!test_flag && el.options[j].selected) {
		                el.options[j].selected = false;
		                el.options[0].selected = true;
		            }
			    }
			}
		}
	}
}

var cur_img = 0;
var Item_imgs = new Array();
function switch_popup_img(n) {
    n = Number(n);
    if (n < 0 || !document.getElementById("popup_small_" + n)) n = 0;
    $("#id_popup_main_img").attr("src", $("#popup_small_img_" + n).attr("src"));
    if (!Item_imgs[n]) {
        Item_imgs[n] = new Image();
        Item_imgs[n].onload = boom;
        Item_imgs[n].src = $("#popup_small_img_" + n).attr("src").replace("_m", "");
        document.getElementById("id_popup_main_img").height = 200;
        //document.getElementById("id_popup_main_img").style.paddingTop = "100px";
        animate_item_img();
    } else {
        $("#id_popup_main_img").attr("src", Item_imgs[n].src);
    }
    //$("#id_popup_main_img").attr("src", $("#popup_small_img_" + n).attr("src").replace("_m", ""));
    $("li[id^='popup_small_']").removeClass("cur");
    $("#popup_small_" + n).addClass("cur");
    $("#picture_number_placer").html(1+n);
    cur_img = n;
}

function boom () {
    $("#id_popup_main_img").attr("src", this.src);
    document.getElementById("id_popup_main_img").height = Item_imgs[cur_img].height;
}

function animate_item_img () {
    var h = document.getElementById("id_popup_main_img").height;
    var w = document.getElementById("id_popup_main_img").width;
    var dh = 20;
    if (h && h > 0 && h < 400 && w < 500 - dh) {
        document.getElementById("id_popup_main_img").height = h + dh;
        //document.getElementById("id_popup_main_img").style.paddingTop = Math.floor((400 - dh - h) / 2) + "px";
        setTimeout("animate_item_img();", 30);
    } else {
        if (Item_imgs[cur_img].height) document.getElementById("id_popup_main_img").height = Item_imgs[cur_img].height;
        //document.getElementById("id_popup_main_img").style.paddingTop = "";
    }
}


// spam popup
var spmtm;
function show_spam_link () {
    if (spmtm!=undefined) clearTimeout(spmtm);
    $('#red_spam_link').show();
}
function hide_spam_link (delay) {
    if (spmtm!=undefined) clearTimeout(spmtm);
    document.title=delay;
    if (delay == 0) {
        $('#red_spam_link').hide();
    } else {
        spmtm=setTimeout(function(){$('#red_spam_link').hide();}, delay);
    }
}

// photo gallery
function AddToGallery(login, id_photo) {
    $("#id_gallery_add").hide();
    $("#id_gallery_wait").show();

    $.get("/popup/?show=addtogallery&login="+login+"&id_photo="+id_photo, function(data) {});
}

// pereposting
function RebuildIcons(all) {
    var i, n, icon;
    var icons = new Array();
	var data = {title: encodeURIComponent(document.title), url: encodeURIComponent(location.href)};

	var projects = [
		{id: 'memory',        name: 'Memori',       link: 'http://memori.qip.ru/link/?sm=1&u_data[url]=' + data.url + '&u_data[name]=' + data.title},
		{id: 'bobrdobr',      name: 'БобрДобр',     link: 'http://bobrdobr.ru/addext.html?url=' + data.url + '&title=' + data.title},
		{id: 'google',        name: 'Google',       link: 'http://www.google.com/bookmarks/mark?op=add&bkmk=' + data.url + '&title=' + data.title},
		{id: 'yandex',        name: 'Яндекс',       link: 'http://zakladki.yandex.ru/userarea/links/addfromfav.asp?bAddLink_x=1&lurl=' + data.url + '&lname=' + data.title},
		{id: 'twitter',       name: 'Twitter',      link: 'http://twitter.com/home?status=' + data.title + ' ' + data.url},
		{id: 'delicious',     name: 'Delicious',    link: 'http://del.icio.us/post?v=4&noui&jump=close&url=' + data.url + '&title=' + data.title},
		{id: 'yahoo',         name: 'Yahoo!',       link: 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' + data.url + '&t=' + data.title},
//		{id: 'texst20',       name: 'Текст 2.0',    link: 'http://text20.ru/add/?source=' + data.url + '&title=' + data.title + '&text='},
		{id: 'news2',         name: 'News 2',       link: 'http://news2.ru/add_story.php?url=' + data.url},
		{id: 'myspace',       name: 'MySpace',      link: 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + data.url + '&t=' + data.title + '&c=%3Ca+href%3D%22' + data.url + '%3E' + data.title + '%3C%2Fa%3E%0A'},
		{id: 'mistervong',    name: 'Мистер Вонг',  link: 'http://www.mister-wong.ru/index.php?action=addurl&bm_url=' + data.url + '&bm_description=' + data.title},
		{id: 'moemesto',      name: 'Моё Место',    link: 'http://moemesto.ru/post.php?url=' + data.url + '&title=' + data.title},
		{id: 'cmi2',          name: 'СМИ 2',        link: 'http://smi2.ru/add/?url=' + data.url + '&precaption=' + data.title},
		{id: 'bаау',          name: 'Baay!',        link: 'http://www.vaau.ru/submit/?action=step2&url=' + data.url},
		{id: 'liveint',       name: 'LiveInternet', link: 'http://www.liveinternet.ru/journal_post.php?action=n_add&cnurl=' + data.url + '&cntitle=' + data.title},
		{id: 'ruspace',       name: 'RuSpace',      link: 'http://www.ruspace.ru/index.php?link=bookmark&action=bookmarkNew&bm=1&url=' + data.url + '&title=' + data.title},
		{id: 'bookmarks100',  name: 'Сто закладок', link: 'http://www.100zakladok.ru/save/?bmurl=' + data.url + '&bmtitle=' + data.title},
		{id: 'mblogi',        name: 'Мблоги',       link: 'http://mblogi.qip.ru/knopka/?url=' + data.url + '&title=' + data.title},
		{id: 'odnoklassniki', name: 'Одноклассники',    link: 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st._surl=' + data.url},
		{id: 'mailru',        name: 'Mail.ru',      link: 'http://connect.mail.ru/share?share_url=' + data.url}
	];
	
	if (pref_icons.length < 1) {
        icons = ff_GetCookie("preficons");
        if (icons) pref_icons = icons.split("|");
	}
	
	sample_icons = new Array("odnoklassniki", "mailru", "memory", "yandex", "google", "delicious", "yahoo", "twitter", "mblogi");
	
	$("#id_small_icons a.icon:not(.morelink)").remove();

	n = 0;
	icons = new Array();
    while (n < sample_icons.length) {
        icons[n] = pref_icons.length < 1 ? sample_icons[n] : pref_icons.pop();
        n++;
    }
       
    for (n = icons.length - 1; n >= 0; n--) {
        for (i = 0; i < projects.length; i++) {
            if (projects[i].id == icons[n]) {
                $("#id_small_icons").prepend('<a href="' + projects[i].link + '" target="_blank" title="' + projects[i].name + '" class="icon ' + projects[i].id + '"></a> ');
            }            
        }
    }
    
    if (all) {
        $("#id_icons").append('<div style="width: 102px; display: block; float: left; margin: 0; margin-top: 5px; font-size: 90%"><b>Закладки</b></div>');

        for (i = 0; i < projects.length; i++) {
            $("#id_icons").append('<a href="' + projects[i].link + '" onclick="ClickIcon(\'' + projects[i].id + '\')" target="_blank" title="' + projects[i].name + '" style="width: 102px; display: block; float: left; margin: 0; margin-top: 5px; font-size: 90%"><i class="icon ' + projects[i].id + '" style="width: 18px; height: 18px; display: block; float: left; margin: 0; margin-right: 3px;"></i>' + projects[i].name + '</a>');
        }
    }
}

function ShowMore(flag) {
    if (timeout_icons) {
        clearTimeout(timeout_icons);
        timeout_icons = 0;
    }
    if (flag) {
        $("#id_icons").show();
    } else {
        timeout_icons = setTimeout('$("#id_icons").hide()', 1000);
    }
}

function ClickIcon(icon) {
    var icons = ff_GetCookie("preficons");

    if (icons) {
        if (pref_icons.length < 1) pref_icons = icons.split("|");
        if (pref_icons.join("|").indexOf(icon) == -1 && pref_icons.push(icon) > 9) pref_icons.shift();
    } else {
        pref_icons = new Array(icon);
    }
    
    ff_SetCookie("preficons", pref_icons.join("|"), 180);
    RebuildIcons(false);
}

function pccCounter() {
    new Image().src = "http://counter.yadro.ru/hit;pics.qip.ru?r/;u/download/QipShot;"+Math.random();
}

/* user photo selector */
function group_set_album(id) {
    var str_album = '#id_add' + id + 'box select[name="id_album"]';
    var str_photo = '#id_add' + id + 'box select[name="id_photo"]';

    if ($(str_album).length > 0) {
        var id_album = $(str_album).val();
        $(str_photo + ' option[value!="0"]').remove();
        $.get("/ajax/albumphotos/?id_album=" + id_album, function(data){
            for(var i = 0; i < data.length; i++) {
                $('<option value="' + data[i].id  + '">' + data[i].title + '</option>').appendTo(str_photo).attr('ext', data[i].ext);
            }
        }, "json");

        if (id != 'cover') $('#id_preview_' + id).attr('src', $('#id_preview_' + id).attr('src').replace(/\/[0-9]+\/small\/[0-9a-z\.]*$/i, "/" + id_album + "/small/" + js_albums[id_album]));
    } else {
        setTimeout("group_set_album('" + id + "')", 200);
    }
}

function group_set_photo(id) {
    var str_album = '#id_add' + id + 'box select[name="id_album"]';
    var str_photo = '#id_add' + id + 'box select[name="id_photo"]';
    var id_album = $(str_album).val();
    var id_photo = $(str_photo).val();
    var new_preview = '';
    if (id_photo == 0) {
        if (id != 'cover') new_preview = "/" + id_album + "/small/" + js_albums[id_album];
    } else {
        new_preview = "/" + id_album + "/small/" + id_photo + '.' + $(str_photo + ' option:selected').attr('ext');
    }
    if (new_preview != '') $('#id_preview_' + id).attr('src', $('#id_preview_' + id).attr('src').replace(/\/[0-9]+\/small\/[0-9a-z\.]*$/i, new_preview));
}

function MainNewsBlock() {
   $.get("http://photo.qip.ru/static/main_news.xml",
   function(data){
     var item = $(data).find("item");
     var s = '';
     var link, title, image;
     for (var i = 0;i < Math.min(2, item.length);i++) {
         link = $(item[i]).find("link").text();
         title = $(item[i]).find("title").text();
         image = $(item[i]).find("enclosure").attr('url');
         s += '<li><p>';
         s += '<a href="'+link+'" target="_blank"><img width="93" height="67" alt="'+title+'" title="'+title+'" src="'+image+'"></a><a href="'+link+'" target="_blank">'+title+'</a>';
         s += '</p><div class="clear"></div><p></p></li>';
     }
     $("#news_qip_nova ul").append(s);
   }, "xml");
}
$("#news_qip_nova").ready(function(){MainNewsBlock();});

function MakeDemotivator(login, id_photo) {
    if ($(".demotivatorbox").length > 0) {
        $(".demotivatorbox").html('<b onclick="hideDemotivatorForm()" title="Закрыть" class="closebox"></b><div class="center"><img src="/themes/qip_ru/i/loade.gif" alt="" /></div>');
        $(".demotivatorbox").show();
    } else {
        $("#" + id_photo).prepend('<div class="demotivatorbox"><b onclick="hideDemotivatorForm()" title="Закрыть" class="closebox"></b><div class="center"><img src="/themes/qip_ru/i/loade.gif" alt="" /></div></div>');
        //$(".demotivatorbox").css("top", (($(window).width() > 800 ? 280 : 100) + getScrollTop()) + "px");
        //$(".demotivatorbox").css("left", $(window).width() / 2 + "px");
    }
    var pos = $("#photo_preview_image").attr('src').indexOf("?");
    var query = pos > -1 ? $("#photo_preview_image").attr('src').substr(pos) : "";
    $(".demotivatorbox").load("/popup/?show=demotivator&login="+login+"&id_photo="+id_photo+"&query="+encodeURIComponent(query));
}

function hideDemotivatorForm() {
    $(".demotivatorbox").hide();
}

function ContestVotingForm(id_contest) {
    if ($(".popuplogin").length > 0) {
        $(".popuplogin").show();
    } else {
        $("body").prepend('<div class="popuplogin"><b class="closebox" title="Закрыть" onclick="hideContestVotingForm()"></b><div class="center"><img src="/themes/qip_ru/i/loade.gif" alt="" /></div></div>');
        $(".popuplogin").css("top", (($(window).width() > 800 ? 280 : 100) + getScrollTop()) + "px");
        $(".popuplogin").css("left", $(window).width() > 800 ? "30%" : ($(window).width() - 450) / 2 + "px");
        $(".popuplogin").load("/popup/?show=contestvoting&id_contest="+id_contest);
    }
}

function hideContestVotingForm() {
    $(".popuplogin").hide();
}

