User = {login: false};

$(document).ready(function() {
    initButtons('bid_button', '/ajax/bid/', mainRefresh, 1000);
    initButtons('vote_button', '/ajax/vote/', voteRefresh, 10000);
    initOrderButtons('order_button');

    if (User.login) {
    	setInterval(UserRefresh, 1000);
    }

    $('#toggle_description').click(toggleDescription);

    initPaymentSystems();
    checkLogin();
    getHelper();
    smsChanger();
    showRules();
    hotKeySubmit();
});

//обновление текущих лотов
function mainRefresh(ids)
{
    $.ajax({
        url: "/ajax/ref_lot/",
        dataType: "json",
        cache: false,
        error: function(data){
            if (data.status == "404") {
                $('.bid_button').hide();
                $('.stop_auc').show();
            }
        },
        success: function(data) {
            if (data.info.length == 0) {
                return;
            }

            $.each(ids, function() {
                var lot = $('#lot_' + this);
                if (!lot.attr('id')) {
                    return;
                }
                var timer = lot.find('.timer');
                var item  = data.info[this];

                if (!item) {
                    timer.text('Закончен');
                    lot.find('.bid_button').val('Продано').attr('disabled', 'disabled');
                    return;
                }

                if (item.t == -1) {
                    lot.find('.bid_button').hide();
                    lot.find('.stop_auc').show();
                    return;
                }

                lot.find('.stop_auc').hide();
                lot.find('.bid_button').show().removeAttr('disabled');

                if (item.t <= item.i) {
                    timer.addClass("endtime");
                } else {
                    timer.removeClass("endtime");
                }
                timer.text(parseTimer(item.t));

                var auser = lot.find('.user');
                auser.text(item.u);
                if (auser.attr('href')) {
                    auser.attr('href', item.u == '--' ?  '#' : '/user/'+ item.u + '/');
                }

                var price = lot.find('.bid');
                if (price.html() != item.p) {
                    var button = lot.find('.bid_button');
                    var tmp = button.attr('name');
                    if (User.login && item.u == User.login) {
                        button.addClass('red_button').attr('name', button.val()).val(tmp);
                    } else if (button.hasClass('red_button')) {
                        button.removeClass('red_button').attr('name', button.val()).val(tmp);
                    }

                    lot.find('.time_increment').html(item.i);
                    lot.find(".bidnow").hide();
                    price.html(item.p).colorFade("#FFE400", 400);

                    //обновление истории ставок, информации об экономии и потраченых деньгах
                    var history = $('#history_' + this);
                    if (!history.attr('id')) { //if table not exists
                        return;
                    }

                    $.getJSON('/ajax/details/?id=' + this, function(data) {
                        if (!data) {
                            return;
                        }
                        //bids
                        var rows = history.find('tbody > tr');
                        $.each(data.bids, function(i, bid) {
                            var cur = rows.eq(i + 1);
                            var n = '<td class="bid_td">' + bid.price + '</td><td>' + bid.login + '</td><td>' + bid.source + '</td>';
                            if (cur.html()) {
                                cur.html(n);
                            } else {
                                history.children('tbody').append($('<tr>' + n + '</tr>'));
                            }
                        });
                        //spend
                        if (data.spend != undefined) {
                            lot.find('.spend').html(data.spend);
                            lot.find('.economy').html(data.economy);
                        }
                    });
                }
            });
        }

     });
}

//обновление предстоящих лотов
function voteRefresh(ids)
{
    $.getJSON('/ajax/ref_vote/', function(data) {
        if (data.length == 0) {
            return;
        }

        $.each(ids, function() {
            var lot = $('#future_' + this);
            if (!lot.attr('id')) {
                return;
            }

            var item  = data[this];
            lot.find('.votes').text(item && item.votes ? item.votes : 0);
            lot.find('.own').html(item && item.own > 0 ? '<div class="my_golos"></div>' : '');
        });
    });
}

function UserRefresh()
{
    $.getJSON('/ajax/ref_user/', function(data) {
        $('#user_balance').html(data.balance);
        if (data.message == 1) {
            $('#mj_messages').addClass("new");
        } else {
            $('#mj_messages').removeClass("new");
        }

        var ab_table = $('#ab_table');

        $.each($('#user_autobids a'), function() {
            var a = $(this);
            var id = a.attr('id').split('_').pop();
            if (!data.autobids[id]) {
                a.remove();
                if ($('#abpoints_' + id).attr('id') || ab_table.attr('id')) {
                    location.reload(true);
                }
            } else {
                a.html(data.autobids[id].points);
                $('#abpoints_' + id).html(data.autobids[id].points);
                if (ab_table.attr('id')) {
                    var bgcolor = $('#ab_tablerow_' + id).css("backgroundColor");

                    var points = $('#ab_tablerow_' + id + ' .abpoints');
                    if (points.html() != data.autobids[id].points) {
                        points.html(data.autobids[id].points)
                            .colorFade("#FFE400", 400);
                    }
                    var cur = $('#ab_tablerow_' + id + ' .abcur');
                    if (cur.html() != data.autobids[id].current_price) {
                        cur.html(data.autobids[id].current_price)
                            .colorFade("#FFE400", 400);
                    }
                }
            }
        });

        $.each(data.autobids, function(i, item) {
            if (!$('#autobid_' + i).attr('id')) {
                $('#user_autobids').append('<a href="/auction/' + i + '/" title="' + item.title + '" id="autobid_' + i + '">' + item.points + '</a> ');
                if ($('#abform_' + i).attr('id') || ab_table.attr('id')) {
                    location.reload(true);
                }
            }
        });
    });
}

//инициализация обновлений
function initButtons(button_class, ajax_url, callback, timeout)
{
    var ids = new Array;
    $('.' + button_class).each(function(i, item) {
        item = $(item);
        ids.push(item.parent().parent().attr('id').split('_').pop()); //add lot ID to array "ids"
        if (User.login) {
            item.click(function() {
                if (!$(this).hasClass("red_button")) {
                    $.getJSON(ajax_url + '?lot=' + ids[i], function(data) {
                        if (data.succsess == '1') {
                            callback.call(null, ids);
                        }

                        if (data.callback) {
                            eval(data.callback + '(' + ids[i] + ')');
                        }
                    });
                }
            }); 
        } else {
            var defaultValue = item.val();
            item.click(function() {
                document.location = '/register/';
            }).hover(function() {
                item.val('Войдите');
            }, function() {
                item.val(defaultValue);
            });
        }
    });

    if (ids.length > 0) {
        (function() {
            callback.call(null, ids);
            setTimeout(arguments.callee, timeout);
        })();
    }
}

function initOrderButtons(button_class)
{
	var ids = new Array;
	$('.' + button_class).each(function(i, item) {
		item = $(item);
		if (User.login) {
			item.click(function() {
				if (!$(this).hasClass("red_button")) {
					var form = $(this).parents("form");
					form.submit();
				}
			}); 
		} else {
			var defaultValue = item.val();
			item.click(function() {
				document.location = '/register/';
			}).hover(function() {
				item.val('Войдите');
			}, function() {
				item.val(defaultValue);
			});
		}
	});
}

// для страницы пополнения счета
function initPaymentSystems()
{
    $("input[name='payment_system']").click(function() {
        $("#payment_extra").val($(this).attr("id"));
    });
}

function succsessBid(id)
{
    $("#lot_" + id).find(".bidnow").show();
}

function failedBid()
{
    return false;
    //alert('Ставка не сделана');
}

//перевести секунды в формат чч:мм:сс
function parseTimer(time)
{
    hours   = Math.floor(time / 3600);
    minutes = Math.floor(time/60 - hours*60);
    seconds = time - hours*3600 - minutes*60;

    return (hours < 10 ? '0' + hours : hours) + ":" + (minutes < 10 ? '0' + minutes : minutes) + ":" + (seconds < 10 ? '0' + seconds : seconds);
}

// проверить на уникальность логин
function checkLogin()
{
    $("#n_newlogin").blur(function() {
        if (vCheckLogin($(this))) {
            $.get('/ajax/check_login/?login=' + $(this).val(), function(result) {
                if (result == "1") {
                    $("#n_newlogin").stop().css({borderColor: "#DEE2E8"})
                    $("#login_mess").html(' <img src="/style/i/login_ok.gif" alt="" /> Логин свободен.');
                } else {
                    $("#login_mess").html(' <img src="/style/i/login_er.gif" alt="" /> Этот логин уже занят.');
                    $("#n_newlogin").colorFade({property: "border-color", colorStart: "#C44C51", colorEnd: "#DEE2E8"})
                }
            });
        } else {
            $("#login_mess").html(' <img src="/style/i/login_er.gif" alt="" /> Неправильный логин.');
            $("#n_newlogin").colorFade({property: "border-color", colorStart: "#C44C51", colorEnd: "#DEE2E8"})
        }
    });
}

// запрос на отправку письма для активации мыла
function sendActivateMail()
{
    $.getJSON("/ajax/activate_mail/", function(json){
        if (json['data'] == "1") {
            $("#mail_confirm").show().text('Письмо с инструкциями выслано на ваш E-mail.').colorFade({colorStart: "#00C138", colorEnd: "#fff"}, 400).fadeOut(10000)
        } else {
            $("#mail_confirm").show().text('Ошибка, попробуйте позже.').colorFade({colorStart: "#F53737", colorEnd: "#fff"}, 400).fadeOut(20000)
        }
    })
}

// capcha
function refreshCapcha()
{
    $.get("/ajax/capcha/?r=" + Math.floor(100000000000*Math.random()), function (data) {
        $("#capcha").html(data);
        $("#capcha_key").attr("value", $('#img_code').attr('usemap'));
    });
}

// переключает рамочку на странице лота
function addBorder(_this)
{
    $(".mini a").removeClass("act");
    $(_this).addClass("act");
}

// open/close lot description
function toggleDescription()
{
    if($('#toggle_description').attr('src') == '/style/i/up_07.gif') {
        $('#toggle_description').attr('src', '/style/i/up_08.gif');
    } else {
        $('#toggle_description').attr('src', '/style/i/up_07.gif');
    }
    $('#lot_description').toggle();
}

var zap = false;
function getHelper()
{
    $("#nk_create_msg").keydown(function(event) {
        if (event.keyCode == "13") {
            return false;
        }
    });
    var text = "";
    $("#nk_create_msg").keyup(function(event) {
        if ($("#nk_create_msg").val().length > 2) {
            if(event.keyCode != "40" && event.keyCode != "38" && event.keyCode != "13") {
                $("#real_login").val($("#nk_create_msg").val());
                $.getJSON("/ajax/contact_logins/?name=" + encodeURI($('#nk_create_msg').val()), function(json){
                    if((json['contact'] && json['contact'].length > 0) || (json['others'] && json['others'].length > 0)) {
                        makeLoginTables(json);
                        $("#nk_helper").show();
                        mouseSelectName();
                        if (!zap) {
                            selectName();
                            zap = true
                        }
                    } else {
                        $("#nk_helper").hide();
                    }
                });
            }
        } else {
            $("#nk_helper").hide();
        }
    })



    $("#nk_create_msg").blur(function() {
        $("#nk_helper").hide();
        $("#nk_helper table").remove();
    })

}

function makeLoginTables(data)
{
    var y = 0;
    var text = "";
    if (data['contact'].length > 0) {
        text = text +"<p>Найдено в Адресной книге:</p><table>";
        for (var i = 0; i <data['contact'].length; i++) {
            if(i == 0) {
                text = text + '<tr><td class="act">' + data['contact'][i].login + '</td></tr>';
            } else {
                text = text + '<tr><td>' + data['contact'][i].login + '</td></tr>';
            }
            y++;
        }
        text = text + "</table>";
    }

    if (data['others'].length > 0 && y < 10) {
        text = (data['contact'].length > 0) ? text + "<div></div><table>" : text + "<table>";
        for (var i = 0; i <data['others'].length; i++) {

            if (y < 10) {
                if(i == 0 && data['contact'].length < 1) {
                    text = text + '<tr><td class="act">' + data['others'][i].login + '</td></tr>';
                } else {
                    text = text + '<tr><td>' + data['others'][i].login + '</td></tr>';
                }
            }
            y++;
        }
        text = text + "</table>";
    }

    $("#nk_helper table").remove();
    $("#nk_helper p").remove();
    $("#nk_helper div").remove();
    $("#nk_helper").append(text);
}

function mouseSelectName()
{
    $("#nk_helper td").mouseover(function() {
        $("#nk_helper td").removeClass('act');
        $(this).addClass('act');
    });

    $("#nk_helper td").mousedown(function() {
        $("#nk_create_msg").val($(this).text()).focus();
        $("#nk_helper").hide();
        $("#nk_helper table").remove();
    })

}

function selectName()
{
    $("#nk_create_msg").keyup(function(event) {
        if (event.keyCode == "40") {
            var a = nextTdHelper()
            $("#nk_helper td").removeClass('act');
            $("#nk_helper td").eq(a).addClass('act');
        }

        if (event.keyCode == "38") {
            var a = prevTdHelper();
            $("#nk_helper td").removeClass('act');
            $("#nk_helper td").eq(a).addClass('act');
        }

        if (event.keyCode == "13") {
            $(this).val($("#nk_helper td.act").text());
            $("#nk_helper").hide();
            return false;
        }
    });
}



// вернет индекс окрашеной td
function getIndexHelper()
{
    var index = "b";
    $("#nk_helper td").each(function() {
        if($(this).hasClass("act")) {
            index = $("#nk_helper td").index(this);
        }
    })
    return index;
}

// вернет индекс следующей td после окрашеной
function nextTdHelper()
{
    var index = getIndexHelper();
    return ((index + 1) == $("#nk_helper td").length) ? index : (index +1);
}

// вернет индекс предыдущий td после окрашеной
function prevTdHelper()
{
    var index = getIndexHelper();
    return (index == 0) ? index : index - 1;
}

// навигация по стрелочкам
function NavigateThrough() {
    var not_input = true;
     $("input, textarea").focus(function () {
        not_input = false;
    }).blur(function() {
        not_input = true;
    });
    $(document).keydown(function(event){
        if (event.ctrlKey) {
            if (not_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 smsChanger()
{
    $("#sms_operator").change(function() {
        if ($(this).val() != "0") {

            $.getJSON("/ajax/sms_price/?operator_id=" + $(this).val(), function(json){
                if (json['data'] != "0") {
                    $("#smspay").empty();
                    for (var key in json['data']) {
                        $("#smspay").append("<tr><td class='w100'>" + json['data'][key]['phone_number'] + "</td><td align='right'  class='w50'>"+ json['data'][key]['partner_income'] + "</td><td align='right'>" + json['data'][key]['abonent_price'] + "</td></tr>");
                    }
                    $("#marg").colorFade("#DCE1F6")
                }
            })
        }



        //smspay

    })
}

// счетчик символов в полях
function symbolCounter(input, max_count)
{
    resizeTextarea(input);
    var curent_count = input.value.length;

    if(curent_count > max_count) {
        input.value = input.value.substring(0, max_count);
    }
    var itogo = max_count - input.value.length;


    $("#"+$(input).attr("id")+"_symbol").show();
    $("#"+$(input).attr("id")+"_temp").hide();

    $('#'+$(input).attr('id')+'_symbol span').text(itogo);

    if (itogo == "0") {
        $("#"+$(input).attr("id")+"_symbol").hide();
        $("#"+$(input).attr("id")+"_temp").show().addClass('cout_symbol').css('color', '#C00C0D');
    }
}

// изменяет высоту текстарии
function resizeTextarea(input)
{
    if (input.scrollTop > 0) {
        $(input).height($(input).height() + input.scrollTop + 1)
    }
}

function showRules()
{
    $('#index_rule').click(function() {
        if ($(this).height() == '170') {
            $(this).animate({height:28}, 1000);
        } else {
            $(this).animate({height:170}, 1000);
        }

    })
}

function hotKeySubmit()
{
    var form = false;
     $(":text, textarea").focus(function () {
        form = $(this).parents('form');
    }).blur(function() {
        form = false;
    });

    $(document).keyup(function(event){
        if (event.ctrlKey) {
            if (form && event.keyCode == 13) {
                form.submit();
            }
        }
    });
}

function sendComplaint(_this, message_id)
{
    $.post("/ajax/complaint/", {mess_id: message_id}, function(data){
        if (data == "1") {
            $(_this).replaceWith('<span class="small gray">Спасибо. Ваша жалоба отправлена администратору.</span>');
        } else {
            $(_this).replaceWith('<span class="small red">Не удалось. Попробуйте позже.</span>');
        }
    });



}
