﻿var index = true;

function doBid(id) {
    $.ajax({
        type: "GET",
        url: "/bid.aspx",
        data: "bid=" + id + "&id2=" + Math.random(),
        success: function (msg) {
            var controlChar = msg.substring(0, 1);

            if (controlChar == "x") {
                var bidcount = msg.substring(1);
                $("#userBids").html(bidcount);
                alert("Váš bid byl akceptován.");
            } else {
                alert(msg);
            }
            is_bid = true;
        }
    });
}

function doAutobid(id, amount) {
    $.ajax({
        type: "GET",
        url: "/autobid.aspx",
        data: "id=" + id + "&amount=" + amount + "&id2=" + Math.random(),
        success: function (msg) {
            var controlChar = msg.substring(0, 1);

            if (controlChar == "x") {
                var bidcount = msg.substring(1);
                $("#userBids").html(bidcount);
                alert("Váš autobid byl akceptován.");
            } else {
                alert(msg);
            }
            is_bid = true;
        }
    });
}

function startCounter(isIndex) {
    index = isIndex;
    execute();
    dummy();
}

var success;
var counter = 0;
var timeoutCounter = 0;
var first = true;
var auctions = new Array();
var is_bid = false;
var init_time = -1;

function execute() {
    counter++;
    success = false;
    if (first) {
        ajax_timeout = 0;
    } else {
        ajax_timeout = 1200;
    }

    var ajaxConfig = {
        type: "GET",
        url: "/itemslist.aspx",
        start_time: new Date().getTime(),
        data: "a=a" + Math.random(),
        timeout: ajax_timeout,
        success: function (msg2) {
            var response = eval('(' + msg2 + ')');

            time = response.server_time;

            var end_time = new Date().getTime();
            //console.log(950 - time - (end_time - this.start_time) + " - et: " + end_time + ", st:" + this.start_time + ", time:" + time);
            if (800 - time - (end_time - this.start_time) <= 0 && first == false) {
                //console.log("CHYBA: cas = " + (950 - time - (end_time - this.start_time)));
                return;
            }

            success = true;

            var div = document.createElement("div");
            var auctions_list = response.auctions;
            for (i = 0; i < auctions_list.length; i++) {
                var auction = auctions_list[i];

                if (auctions[auction.id] != null) {
                    if (auctions[auction.id].actual_winner != auction.actual_winner) {
                        auctions[auction.id] = auction;
                        auctions[auction.id].changed = 1;
                    } else {
                        auctions[auction.id] = auction;
                    }
                } else {
                    auctions[auction.id] = auction;
                    auctions[auction.id].changed = 0;
                }

            }
            //console.log(1300 - time - (end_time - this.start_time) + " - et: " + end_time + ", st:" + this.start_time + ", time:" + time);
            setTimeout("execute()", (1300 - time - (end_time - this.start_time)));
            if (first) {
                setTimeout("Countdown.Tick()", (1300 - time - (end_time - this.start_time)));
            }
            first = false;
        }
    };

    $.ajax(ajaxConfig);

    if (first == false) {
        timeoutCounter++;
        setTimeout("checkExecute(" + counter + ")", 800 - (new Date().getTime() - ajaxConfig.start_time));
    }
}

function checkExecute(step) {
    if (success == false) {
        if (timeoutCounter >= counter - 2)
            execute();
    }
}

function setPasswordType(inputField) {
    if (inputField.type == 'text') {
        var passwdField = document.createElement("input");
        passwdField.name = inputField.name;
        passwdField.type = "password";
        passwdField.className = "text login";
        inputField.parentNode.insertBefore(passwdField, inputField);
        inputField.parentNode.removeChild(inputField);
        passwdField.focus();
        passwdField.onblur = function () { if (this.value == '') this.value = 'heslo'; }
    }
}

function dummy() {
    $.ajax({
        type: "GET",
        url: "/dummy.aspx",
        data: "",
        success: function (msg) {
        }
    });
    setTimeout("dummy()", 300000);
}

var Countdown = {

    Tick: function () {
        var start_time = new Date().getTime();
        st = "-" + start_time;
        st = parseInt(st.substring(st.length - 3, st.length), 10);

        if (init_time == -1) init_time = st;

        setTimeout("Countdown.Tick()", 1000 - (st - init_time));

        //$('#testDiv').html($('#testDiv').html() + st + "-" + init_time + "<br />");

        var list = $('.countdown');

        for (var i = 0; i < list.length; i++) {
            id = parseInt(list[i].id.replace("time", ""), 10);
            auction_time = Countdown.DescTime(list[i].innerHTML);

            if (auctions[id] != null) {
                auction = auctions[id];
                if ($("#username" + auction.id).text() != auction.actual_winner ||
                    compareSeconds(auction.time_remaining, 10) ||
                    compareSeconds(auction_time, 10) ||
                    auction.time_remaining.indexOf(":") == -1 ||
                    auction_time.indexOf(":") == -1 ||
                    is_bid == true) {
                    //$('#testDiv').html($('#testDiv').html() + auction.id + "-" +parseInt(auction.time_remaining.split(":")[2], 10)+"-<br />");

                    if ($("#price" + id).length > 0) {
                        if (typeof auction.auction_bids == 'undefined') {
                            auction.auction_bids = new Array();
                        }

                        auction_time = Countdown.DescTime(auction.time_remaining);
                        //$("#time" + auction.id).text(auction.time_remaining);
                        $("#price" + auction.id).text(auction.current_price);
                        $("#current" + auction.id).text(auction.current_price);
                        $("#username" + auction.id).text(auction.actual_winner);
                        if (!index && auction.auction_bids.length > 0) {
                            var res = auction.auction_bids;
                            $("#resultTable" + auction.id).html("<tr><th>Čas</th><th>Cena</th><th>Uživatel</th><th>&nbsp;</th></tr>");
                            var htmlAdd = "<tr><th style=\"text-align: center;\">Čas</th><th style=\"text-align: center;\">Cena</th><th style=\"text-align: right;\">Uživatel</th><th>&nbsp;</th></tr>";
                            for (j = 0; j < res.length; j++) {
                                if (res[j] == null) break;

                                var row = res[j];
                                if (j == 0) {
                                    act_price = row.new_price;
                                    act_winner = row.login;
                                    act_auto = row.is_autobid;
                                    htmlAdd = htmlAdd + "<tr style=\"font-weight: bold;\">";
                                }
                                else {
                                    htmlAdd = htmlAdd + "<tr>";
                                }

                                if (row.is_autobid == "0") {
                                    auto = "";
                                } else {
                                    auto = "A";
                                }

                                htmlAdd = htmlAdd + "<td style=\"text-align: center;\">" + row.time + "</td><td style=\"text-align: center;\">" + row.new_price + "</td><td style=\"text-align: right;\">" + row.login + "</td><td>" + (row.smiley != "" ? "<img src=\"/img/smiley/" + row.smiley + ".png\" alt=\"smiley\" /> " : "") + auto + "</td></tr>";
                            }

                            $("#resultTable" + auction.id).html(htmlAdd);
                        }
                    }
                    auctions[id].changed = 0;
                }
            }

            list[i].innerHTML = auction_time;

            if (parseInt(auction_time.split(":")[2], 10) < 31 &&
                            parseInt(auction_time.split(":")[0], 10) == 0 &&
                            parseInt(auction_time.split(":")[1], 10) == 0) {
                $("#time" + id).addClass('red');
            } else {
                $("#time" + id).removeClass('red');
            }

            if (parseInt(auction_time.split(":")[2], 10) < 1 &&
                            parseInt(auction_time.split(":")[0], 10) <= 0 &&
                            parseInt(auction_time.split(":")[1], 10) <= 0) {
                $("#time" + id).text("0:00:00");
                $("#bid" + id + " input").val("Prodáno");
                $("#bid" + id).removeClass();
                $("#bid" + id).addClass('submitRed');
            } else {
                $("#bid" + id).removeClass();
                $("#bid" + id + " input").val("Přihodit");
                $("#bid" + id).addClass('submitGreen');
            }

        }
        is_bid = false;

        //var end_time = new Date().getTime();
        //setTimeout("Countdown.Tick()", 1000 - (end_time - start_time));
    },

    DescTime: function (time) {

        this.Trim(time);

        if (time.indexOf(":") == -1) return time;

        if (time && time.length > 0) {

            var hours = parseInt(time.split(":")[0], 10)
            var minutes = parseInt(time.split(":")[1], 10)
            var seconds = parseInt(time.split(":")[2], 10)

            seconds -= 1;

            if (seconds <= -1) {
                seconds = 59;
                minutes -= 1;
            }

            if (minutes <= -1) {
                minutes = 59;
                hours -= 1;
            }

            if (hours < 0) {
                return "0:00:00";
            }

            time = hours + ":" + (minutes > 9 ? minutes : "0" + minutes) + ":" + (seconds > 9 ? seconds : "0" + seconds)

            return time;
        }
    },

    Trim: function (val) {
        return val.replace(/^\s+|\s+$/g, "");
    }
};

function compareSeconds(time, compared) {
    if (parseInt(time.split(":")[2], 10) < compared &&
        parseInt(time.split(":")[0], 10) <= 0 &&
        parseInt(time.split(":")[1], 10) <= 0) {

        return true;
    } else {
        return false;
    }
}

function buyNow(id) {

    if (confirm("Opravdu chcete koupit produkt?")) {
        $.ajax({
            type: "GET",
            url: "/buyNow.aspx",
            data: "bid=" + id + "&id2=" + Math.random(),
            success: function (msg) {
                alert(msg);
            }
        });
    }
}

