﻿var tim;
var aucDatas; //json
var req;
var bidReq;
var bidDatas; //json
var checkStamp = 1;

var bigAuctionID;
var smallAuctionIDs;

var loadingFirstJson = true;

// var loggedUser = "<%= Page.User.Identity.Name %>";
// logged user is defined in masterpage

//timing();
// timing is called in default masterpage

var serverURL = location.protocol + "//" + location.host;

var watchStopStart = 0;

var alertCount = 0;
function aa(msg) {
    if (alertCount++ < 2) {
        alert(msg);
    }
}

function timing() {

    if (checkStamp == 0)
    { showLoading(true) }
    checkStamp = 0;

    if (bigAuctionID == undefined)
        bigAuctionID = "";

    if (smallAuctionIDs == undefined)
        smallAuctionIDs = "";
    if ((bigAuctionID + smallAuctionIDs) == "") {
        return; // na teto strance nejsou zadne aukce k nacitani.
    }

    req = new XMLHttpRequest();

    watchStopStart = getTicks();


    if (bigAuctionID + smallAuctionIDs + "" != "") {
        req.open("GET", serverURL + "/cgi/data.ashx?ID=" + bigAuctionID + "&IDs=" + smallAuctionIDs + "&nocache=" + getTicks(), true); //async true
        req.onreadystatechange = function() { myHandler(watchStopStart) };
        req.send(null); //no params


        tim = setTimeout("timing()", 1000);
    }
}

function getTicks() {
    var date = new Date()
    var ticks = date.getTime()
    return ticks;
}

function showLoading(showhide) {
    if (showhide) {
        $("#loadingSlow").show();
    }
    else {
        $("#loadingSlow").hide();
    }
}

var ii = 0;

function myHandler(ticksStart) {

    if (req.readyState == 4 /*complete*/) {
        checkStamp++;
        showLoading(false);
        try {
            aucDatas = eval('(' + req.responseText + ')');
            fillDataToHTML();
            
            var laten = ((getTicks() - ticksStart) / 1000) * 2;
            latenBox = $("#latenVal");
            if (latenBox.length) { // pokud existuje
                if (laten > 0.6) {
                    latenBox.css({ backgroundColor: "#ff0000" });
                } else {
                    latenBox.css({ backgroundColor: "transparent" });
                }
                latenBox.text(laten);
            }
        }

        catch (ex) {
            //alert("Nepodařilo se stáhnout data ve správném formátu\n" + ex);
            //clearTimeout(tim);
        }
        loadingFirstJson = false;
    }
}

function changeWithBlink(obj, newHtml) {
    if (!loadingFirstJson) {
        if (obj.html() != newHtml) {
            obj.html(newHtml);
            obj.css({ backgroundColor: "#ff0000" });
            obj.animate({ opacity: 0 }, 500, "swing", function() { restObj(obj); });
        }
    } else {
        obj.html(newHtml);
    }

}

function restObj(obj, oriColor) {
    obj.css({ opacity: "100" });
    obj.css({ backgroundColor: "transparent" });
}

function fillDataToHTML() {

    for (var auctionIndex in aucDatas) {
        var auctionData = aucDatas[auctionIndex];
        var curPlanedClose = auctionData.strCurrentPlannedClose;
        
        $("#timeRest-" + auctionData.pkAuction).text(curPlanedClose);
        timeRest = $("#timeRest-" + auctionData.pkAuction);

        if (curPlanedClose == "00:00:08" ||
            curPlanedClose == "00:00:07" ||
            curPlanedClose == "00:00:06" ||
            curPlanedClose == "00:00:05" ||
            curPlanedClose == "00:00:04" ||
            curPlanedClose == "00:00:03" ||
            curPlanedClose == "00:00:02" ||
            curPlanedClose == "00:00:01" ||
            curPlanedClose == "00:00:00") {
            timeRest.css({ color: "#F24242" });
        } else {
            timeRest.css({ color: "#424242" });
        }
        
        changeWithBlink($("#currPrice-" + auctionData.pkAuction), formatPrice(auctionData.mnyCurrentPrice)); //
        changeWithBlink($("#LastBidder-" + auctionData.pkAuction), auctionData.fkCurrentBuyer);


        if (auctionData.showReserved) {
            $("#reserved-" + auctionData.pkAuction).show();
        } else {
            $("#reserved-" + auctionData.pkAuction).hide();
        }



        var Envbidbtn = $("#EnvbidBtn-" + auctionData.pkAuction);
        var EnvbidBtnText = $("#EnvbidBtnText-" + auctionData.pkAuction);


        if (auctionData.isAuctionPaused) {
            EnvbidBtnText.html("<span class='bid redbid'>Pozastaveno</span>");
            Envbidbtn.hide();
            EnvbidBtnText.show();
        } else {

            if (auctionData.fkCurrentBuyer == loggedUser || IsUserWinner(auctionData.MultiWinners)) {
                //uzivatel uz tuto aukci vyhral, schovat tlacitko.
                Envbidbtn.hide();

                if (auctionData.fkCurrentBuyer == loggedUser) {
                    EnvbidBtnText.html("<span class='bid purplebid'>vyhráváte</a>");
                } else {
                    EnvbidBtnText.html("<span class='bid goldbid'>Je to vaše</span>");
                }

                EnvbidBtnText.show();
            } else {
                Envbidbtn.show();
                EnvbidBtnText.hide();
            }
        }


        if (auctionData.isAuctionClosed) {
            EnvbidBtnText.html("<span class='bid graybid'>Ukončeno</span>");
            Envbidbtn.hide();
            EnvbidBtnText.show();

            if (isDetailPageFor(auctionData.pkAuction)) {
                document.location = "/finishedAuction.aspx?id=" + auctionData.pkAuction;
            }
        }


        // big auction Only
        var historyTable = $("#bidHistory-" + auctionData.pkAuction);

        historyTable.html(getBidHistoryTable(auctionData.bids));
    }
}


function isDetailPageFor(auid) {
    return (document.location.href.indexOf("/auction.aspx?id=" + auid) > 0);
}



function IsUserWinner(multiWinners) {
    for (var winnerIndex in multiWinners) {

        var winner = multiWinners[winnerIndex];
        if (loggedUser == winner) {
            return true;
        }
    }
    return false;
}

function getBidHistoryTable(bids) {
    var tableHead = "";
    var dataFormat = "<div><span class=\"time\">#dtm#</span><span>#bidvalue#</span><span class=\"user\">#username#</span></div>";
    var dataFormatAlt = "<div class=\"dark\"><span class=\"time\">#dtm#</span><span>#bidvalue#</span><span class=\"user\">#username#</span></div>"
    var altRow = false;
    var tableFoot = "";
    var bidsHtml = "";
    var rowcounter = 0;

    for (var bidIndex in bids) {
        rowcounter++;
        var bidData = bids[bidIndex];
        var bidHtml = "";
        var useDataFormat;
        if (altRow) {
            useDataFormat = dataFormat;
        } else {
            useDataFormat = dataFormatAlt;
        }

        altRow = !altRow;

        bidHtml = useDataFormat.replace("#biddate#", bidData.dtmCreated);
        bidHtml = bidHtml.replace("#bidvalue#", formatPrice(bidData.mnyAuctionPriceAfterBid));
        bidHtml = bidHtml.replace("#username#", bidData.fkUser);
        bidHtml = bidHtml.replace("#dtm#", bidData.dtmCreated);

        bidsHtml += bidHtml;
    }

    if (bidsHtml.length > 0) {
        bidsHtml = tableHead + bidsHtml + tableFoot;
    } else {
        bidsHtml = dataFormat.replace("#biddate#", "...");
        bidsHtml = bidsHtml.replace("#bidvalue#", "Není");
        bidsHtml = bidsHtml.replace("#username#", "příhoz");
        bidsHtml = tableHead + bidsHtml + tableFoot;
    }

    return bidsHtml;
}

function formatPrice(mnyPrice) {

    return mnyPrice.toFixed(2).replace("\.", ",").replace(",00", ",-").replace(/(\d+)(\d{3})/, "$1 $2") + " Kč";

}


function makeBid(auctionID) {
    bidReq = new XMLHttpRequest();
    bidReq.open("GET", serverURL + "/cgi/secure/makeBid.ashx?ID=" + auctionID + "&nocache=" + getTicks(), true); //async true
    bidReq.onreadystatechange = myBidHandler;
    bidReq.send(null); //no params
}

function myBidHandler() {
    if (bidReq.readyState == 4 /*complete*/) {
        checkStamp++;
        showLoading(false);
        try {
            bidDatas = eval('(' + bidReq.responseText + ')');
        }
        catch (ex) {
            niceAlert("Nepodařilo se zjistit stav přihození", ex, false);
            return;
        }
        if (!bidDatas.bidDone) {
            niceAlert("Přihození se nezdařilo.", bidDatas.msg, true);
        } else {
            if (bidDatas.userCredit >= 0)
                $("#userCredit").text(bidDatas.userCredit);
        }
    }
}


function changeToLogin(objA, isChangeToLogin) {

    if (isChangeToLogin) {
        objA.innerHTML = "Přihlásit";
        objA.className = "bluebid";
    } else {
        objA.innerHTML = "Přihodit";
        objA.className = "bid";
    }
}


// GUI functions
function niceAlert(text1, text2, showCredit) {
    var myHtml = "<div style='float:right;color:red;font-weight:bold;cursor:pointer;'>X</div> <center><strong>" + text1 + "</strong><p>" + text2 + "</p>"
    if (showCredit) {
        myHtml += "<br/><a href='/addcredit.aspx'>Kredit můžete zakoupit zde</a>";
    }
    myHtml += "<br/><br/><small>(Okno zavřete kliknutím)</small>   </center>";
    $("#innerPopup").html(myHtml);

    $("#mypopup").stop(true, true).animate({ opacity: "show", top: "50%" }, "slow");
    $("#mypopup").click(function() { hideNice() });
}


function hideNice() {
    $("#mypopup").animate({ opacity: "hide", top: "0" }, "fast");

}

var _mouseX = 0;
var _mouseY = 0;


function niceBubble(myHtml) {
    $("#popDet").html(myHtml);
    $("#popDet").show();
    $("#popDet")[0].style.left = _mouseX + 20 + "px"; // _mouseY;
    $("#popDet")[0].style.top = _mouseY + 20 + "px"; // _mouseY;
}

function hideBubble(objName) {
    $("#popDet").hide();
}

function myFadeOut() {
    $(".fadeout").fadeOut(10000);
}


// startup scripts
jQuery(document).ready(function() {

    myFadeOut();

    $(".login").focus(function() { $(".loginlabelUser").hide(); });
    $(".password").focus(function() { $(".loginlabelPass").hide(); });

    if ($(".login").val() != "") {
        $(".loginlabelUser").hide();
        $(".loginlabelPass").hide();
    }


    $(".box").mousemove(function(e) {
        _mouseX = e.pageX;
        _mouseY = e.pageY;
    });
})




