// JavaScript AuctionItem class
function AuctionItem(id, time, isRunning) {
    this._id = id;
    this._time = time;
    this._isRunning = isRunning;
}
AuctionItem.prototype._id;
AuctionItem.prototype._time;
AuctionItem.prototype._isRunning;
AuctionItem.prototype.getId = function() {
    return this._id;
}
AuctionItem.prototype.getTime = function() {
    return this._time;
}
AuctionItem.prototype.setTime = function(time) {
    this._time = time;
}
AuctionItem.prototype.getRunning = function() {
    return this._isRunning;
}
AuctionItem.prototype.setRunning = function(isRunning) {
    this._isRunning = isRunning;
}

// Constants
var anonymousUserRefreshInterval = 2000;
var authenticatedUserRefreshInterval = 1000;

// Global variables
var tickerTimeoutID = null;
var clockTimeoutID = null;
var serverTimeTimeoutID = null;
var auctionBuffer = new Array();
var roundtripStart = null;
var lastSuccessfulRequest = new Date();
var username = null;
var lang = "ro";

$(document).ready(function() { 
//    InitLoginbox();
    refresh_items(0);
    refresh_message();
    //    changeUserDataTab(1);
    document.onkeypress = stopRKey;
});

function stopRKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13)) { return false; }
}

function refresh_message() {
    if ((location.href.indexOf('p=1')) > 0) {
        $.get("/message.aspx?id=" + $("#id_list").text(), function(result) {
            if (result != '') {
                $('#messagebox1').html(result);
                show_message();
            }
        });
    }
    setTimeout(refresh_message, 5 * 60 * 1000);
};

function show_message()
{
  //first slide down and blink the message box
  $("#messagebox1").animate({
  top: $(window).scrollTop()+"px"
  }, 2000 ).fadeOut(100).fadeIn(100);
  
	$(window).scroll(function()
	{
  		$('#messagebox1').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});  
	});

  $("#messagebox1").click(function()
  {
    // $("#object").fadeOut("slow");
      top.location = location.href;
  });
};



function refresh_items() {

    // Set longer ticker request interval when user is not authenticated
    // (and therefore cannot place bids and therefore doesn't need most
    // accurate clock readings)
    var userId = $("#user").text();
    var refreshInterval = authenticatedUserRefreshInterval;
    if ((userId == null) || (userId == "") || (userId == "0")) {
        refreshInterval = anonymousUserRefreshInterval;
    }
    try { username = document.getElementById('username').value; }
    catch (err) { }

    try { lang = document.getElementById('env_language').value; }
    catch (err) { }
    
    if (tickerTimeoutID != null) {
        clearTimeout(tickerTimeoutID);
        tickerTimeoutID = null;
    }
    tickerTimeoutID = setTimeout('refresh_items()', refreshInterval);

    var items = $("#id_list").text();
    if (items == '') return;

    var id = $("#id").text();
    var self_best = "Hetkel juhid";
    var self_winner = "Palju &otilde;nne v&otilde;idu puhul!";
    var get_item = "/ticker.aspx?id=" + items + "&ts=" + (new Date()).getTime();
    var syncTimeBoundary = 100;
    roundtripStart = new Date();

    $.get(get_item, "", function(xml) {
        lastSuccessfulRequest = new Date();
        var roundtripTime2 = Math.floor(new Date() - roundtripStart);

        // Lets detect wheather the site is currently active
        var xmlSiteOpened = $("opened", xml).text();
        var siteOpened = true;
        if ((xmlSiteOpened == "0") || (xmlSiteOpened == "false") || (xmlSiteOpened == "no")) {
            siteOpened = false;
        }

        // Get incoming requests timestamp (the time when the request was
        // sent from client side.
        var xmlRequestTimestamp = parseFloat($("rt", xml).text());

        // Calculate request roundtrip time
        var roundtripTime = (new Date()).getTime() - xmlRequestTimestamp;
        if (roundtripTime < 0) {
            roundtripTime = roundtripTime2;
        }

        var time_sync = parseFloat($("ts", xml).text());
        var originalSyncTime = time_sync;
        time_sync = time_sync - roundtripTime;
        time_sync = ((time_sync < 1) || (time_sync > 1000)) ? 1 : time_sync;

        if (tickerTimeoutID != null) {
            clearTimeout(tickerTimeoutID);
            tickerTimeoutID = null;
        }
        var tickInterval = time_sync + (anonymousUserRefreshInterval - authenticatedUserRefreshInterval) + 350;
        tickInterval = ((tickInterval < 1) || (tickInterval > refreshInterval)) ? refreshInterval : tickInterval;
        tickerTimeoutID = setTimeout('refresh_items()', tickInterval);

        if (time_sync >= syncTimeBoundary) {
            if (clockTimeoutID != null) {
                clearTimeout(clockTimeoutID);
            }
            clockTimeoutID = setTimeout("advanceAuctionClocks(" + siteOpened + ", " + time_sync + ", " + roundtripTime + ")", time_sync);
        }

        for (var i = 0; i < auctionBuffer.length; ++i) {
            auctionBuffer[i].setRunning(false);
        }

        var logSecond = false;
        $("ai", xml).each(function(id) {
            var itemid = $("i", this).text();
            var xmlWinner = $("w", this).text();
            var xmlTime = parseFloat($("t", this).text());
            var xmlStatus = $("s", this).text();
            var xmlPrice = $("p", this).text();
            var isRunning = false;

            if (xmlStatus != '') {
                if (xmlStatus != '') $("#item" + itemid + " .status").text(xmlStatus);
                if (xmlStatus == 'running') {
                    $("#item" + itemid + " .activate").hide('slow');
                    isRunning = true;
                }
                if (xmlStatus == 'stopped') {
                    if ($("st", this).text() != '') {
                        $("#item" + itemid + " .activate").text($("st", this).text());
                        $("#item" + itemid + " .activate").show('slow');
                    }
                }
            }
            if (xmlPrice != '') $("#item" + itemid + " .price_num").text(xmlPrice);

            if ((xmlTime != null) && !isNaN(xmlTime)) {
                var isWon = (xmlWinner != '');
                var isLate = ((originalSyncTime - roundtripTime) < 0)
                if (isWon) {
                    isRunning = false;
                }
                var nextDisplayTime = xmlTime;
                /*if ((time_sync < syncTimeBoundary) && isRunning && isLate) {
                nextDisplayTime = xmlTime - 1;
                }*/

                var found = false;
                for (var i = 0; i < auctionBuffer.length; ++i) {
                    if (auctionBuffer[i].getId() == itemid) {
                        found = true;
                        auctionBuffer[i].setTime(nextDisplayTime);
                        auctionBuffer[i].setRunning(isRunning);
                        break;
                    }
                }
                if (found == false) {
                    auctionBuffer.push(new AuctionItem(itemid, nextDisplayTime, isRunning));
                }

                if ((time_sync < syncTimeBoundary) && isRunning) {
                    advance_item_clock(itemid, xmlTime, logSecond, time_sync, roundtripTime);
                }
                logSecond = false;
            }
            if ($("c", this).text() != '') $("#item" + itemid + " .current").text($("c", this).text());

            if ($("l", this).text() != '') {
                if ($("l", this).text() == $("#item" + itemid + " .liider_id").text()) {
                    $("#item" + itemid + " .item_info_best").text(self_best);
                }
            }
            if ($("o", this).text() != '') $("#item" + itemid + " .product_osal").html($("o", this).text());          

            if (xmlWinner != '') {
                $("#item" + itemid + " .buyer").text('Ostja');
                $("#item" + itemid + " .time_left").html('');
                $("#item" + itemid + " .time_left_num").html(xmlWinner);
                //$("#item" + itemid + " .osale").attr("src", "img/" + lang + "/sold.png");
                if ($("#item" + itemid + " .osale") != null)
                    $("#item" + itemid + " .osale").attr("src", "img/" + lang + "/sold.png");
                if ($("#item" + itemid + " .btn_sm") != null)
                    $("#item" + itemid + " .btn_sm").attr("src", "img/" + lang + "/sold.png");
            }
            else {
                // DISABLE BID BUTTON'
                if (username != "") {
                    if ($("c", this).text() != "" && username != "" && $("c", this).text() == username) {
                        if ($("#item" + itemid + " .btn_sm") != null)
                            $("#item" + itemid + " .btn_sm").attr("src", "img/" + lang + "/bid_inactive.png");
                        if ($("#item" + itemid + " .osale") != null)
                            $("#item" + itemid + " .osale").attr("src", "img/" + lang + "/bid_inactive.png");
                    }
                    // ENABLE BID BUTTON
                    else {
                        //alert($("#item" + itemid + " .test"));
                        if ($("#item" + itemid + " .btn_sm") != null)
                            $("#item" + itemid + " .btn_sm").attr("src", "img/" + lang + "/bid.png");
                        if ($("#item" + itemid + " .osale") != null)
                            $("#item" + itemid + " .osale").attr("src", "img/" + lang + "/bid.png");
                    }
                }
            }
        });
        if ($("ct", xml).text() != '') {
            if (serverTimeTimeoutID != null) {
                clearTimeout(serverTimeTimeoutID);
            }
            serverTimeTimeoutID = setTimeout("advanceServerTime('" + $("ct", xml).text() + "')", time_sync);
        }
        /*
        if ($("uid", xml).text() != '') {
        if ($("uid", xml).text() == '0') {

                var f = document.getElementById('userId');
        if (f.value != "0") // kui enne oli kasutaja sisse loginud ning enam mitte, siis teha redirect
        window.location = "default.aspx?msg=sessionExpired";
        }
        }*/
    });

    /*
    var roundtripTime = Math.floor(new Date() - roundtripStart);
    var tickInterval = 1000 - roundtripTime;
    tickInterval = (tickInterval < 1) ? 1 : tickInterval;
    setTimeout('refresh_items()', tickInterval);
    */

    /*$(".auction_items").each(function(id)
    {
    if ($(".status", this).text() == "running")
    {
    $(".time_num", this).text($(".time_num", this).text() - 1);
    $(".item_info_time", this).html(ctime($(".time_num", this).text()));
    }
    });*/
}

function advance_item_clock(item_id, time, log, sync_time, roundtripTime) {
    $("#item" + item_id + " .time_num").text(time);
    $("#item" + item_id + " .time_left_num").html(ctime(time));
    if (log == true) {
        $.get("PutSec.aspx?sync_time="+ sync_time +"&roundtrip_time="+ roundtripTime +"&ref=" + (new Date()), "", function(xml) { return false; });
    }
}

function advanceAuctionClocks(compensationEnabled, sync_time, roundtripTime) {
    if (compensationEnabled) {
        if (clockTimeoutID != null) {
            clearTimeout(clockTimeoutID);
        }
        clockTimeoutID = setTimeout("advanceAuctionClocks(true, 0, 0)", 1000);
    }
    
    var item = null;
    for (var i = 0; i < auctionBuffer.length; ++i) {
        item = auctionBuffer[i];
        if (item.getRunning()) {
            advance_item_clock(item.getId(), item.getTime(), /*(i==0)*/false, sync_time, roundtripTime);
            if (compensationEnabled) {
                auctionBuffer[i].setTime(item.getTime() - 1);
            }
        }
    }
}

function advanceServerTime(time) {
    if (serverTimeTimeoutID != null) {
        clearTimeout(serverTimeTimeoutID);
        serverTimeTimeoutID = null;
    }
    if (time != null) {
        var timeSplit = time.split(":");
        if (timeSplit.length == 3) {
            var seconds = (parseFloat(timeSplit[0]) * 3600) + (parseFloat(timeSplit[1]) * 60) + parseFloat(timeSplit[2]) + 1;
            var newHour = Math.floor(seconds / 3600);
            seconds -= newHour * 3600;
            var newMinute = Math.floor(seconds / 60);
            seconds -= newMinute * 60;
            var newSecond = seconds;
            if (newSecond >= 60) {
                newMinute++;
                newSecond -= 60;
            }
            if (newMinute >= 60) {
                newHour++;
                newMinute -= 60;
            }
            if (newHour >= 24) {
                newHour -= 24;
            }
            var newTime = twoDigitString(newHour) + ":" + twoDigitString(newMinute) + ":" + twoDigitString(newSecond);
            serverTimeTimeoutID = setTimeout("advanceServerTime('"+ newTime +"')", 1000);
        }
        $(".server_time").text(time);
    }
}

function twoDigitString(number) {
    if (number < 10) {
        return ("0" + number);
    } else {
        return ("" + number);
    }
}

function ask_offer(item_id) {
    var tel_num = $("#telnum").text();
    var new_content = '';
    if (tel_num == '') new_content = '<p onclick="hide_alerts()">Selle teenuse kasutamiseks pead olema sisselogitud kasutaja</p>';
    else {
        new_content = '<p>Teenus eemaldab &uuml;he osalemiskorra sinu kontolt</p><p style="margin-top: 5px; margin-bottom: 5px;"><span class="clickable" onclick="send_offer(' + item_id + ')">N&otilde;ustun</span>&nbsp;&nbsp;&nbsp;<span class="clickable" onclick="hide_alerts()">Keeldun</span></p>';
    }
    $("#alerts p").html(new_content);
    $("#alerts").show("fast");
    if (tel_num == '') setTimeout('$("#alerts").hide("fast");', 3000);
}

//offer jscript
function send_offer(item_id) {
    var userId = $("#user").text();
    if ((userId == null) || (userId == "") || (userId == "0")) {
        top.location = "Default.aspx?p=91";
    }
    curbestBidder = $("#item" + item_id + " .current").text();
    if (curbestBidder != "" && username != "" && curbestBidder == username) {
        //alert($("#item" + item_id + " .current").text())
        //alert(username)
        curbestBidder = null;
        return; // break if user best bidder  already
    }
    curbestBidder = null;

    if ($("#item" + item_id + " .btn_sm") != null) {
        if ($("#item" + item_id + " .btn_sm").attr("src") == ("img/" + lang + "/sold.png")) {
            return;
        }
    }
    if ($("#item" + item_id + " .osale") != null) {
        if ($("#item" + item_id + " .osale").attr("src") == ("img/" + lang + "/sold.png")) {
            return;
        }
    }

    $("#alerts").hide("fast");
    /*	
    $("#alerts p").html("tegid pakkumise");
    $("#alerts").show("fast");
    setTimeout('$("#alerts").hide("fast");', 2000);
    */
    $.get("PutBid.aspx", { id: item_id }, function(data) {
        if ($("text", data).text() != '') {
            $("#alerts p").html($("text", data).text());
            $("#alerts").show("fast");
        }
        setTimeout('$("#alerts").hide("fast");', 2000);
        if ($("pakkumine", data).text() != '') $("#item" + item_id + " .liider_id").text($("pakkumine", data).text());
        if ($("credit", data).text() != '') {
            $('.item_curok').text($('credit', data).text());
            $('#txtProgress').val(parseInt($('#txtProgress').val()) + 1);
            var txtToolTip = $('#txtProgressMessage').val();
            txtToolTip = txtToolTip.replace("#bids#", 100 - (parseInt($('#txtProgress').val()) % 100) + '');
            $('#progressbar100').progressBar(parseInt($('#txtProgress').val()) % 100, { titleText: txtToolTip });
        }
        try { $("#dUpdateBuyNow").click(); } catch (err) { }

    });
}

function hide_alerts() {
    $("#alerts").hide("fast");
}

function ctime(time) {
    var color1 = 't1';
    var color2 = 't2';
    var color3 = 't3';
    var time1 = 45;
    var time2 = 15;

    var msSinceLastRequest = (new Date()).getTime() - lastSuccessfulRequest.getTime();
    if (msSinceLastRequest > 5000) {
        return '<span class="' + color3 + '">Connection lost</span>';
    }

    var result = '';
    var color = '';
    if (time < time1) {
        if (time < time2) {
            color = color3;
            if (time <= 0) {
                result = '<span class="' + color + '">--:--</span>';
                return result;
            }
        }
        else color = color2;
    }
    else color = color1;

    var minut = Math.floor(time / 60);
    var sekund = time - minut * 60;

    if (minut < 10) minut = '0' + minut;
    if (sekund < 10) sekund = '0' + sekund;

    result = result + '<span class="' + color + '">';
    result = result + minut + ':' + sekund;
    result = result + '</span';
    return result;
}

function changeUserDataTab(tab)
{
  /*  if ((location.href.indexOf('p=92')) > location.href.length - 5  ) {                
        $.get("userdata.aspx?id="+ tab,function(result) { 
            if ( result != '' ) {
                $('#userdata').html(result);                
            }
        }); 
    }
    */
};

function fnShowPop(objPop) {
    objPop.style.display = "block";
}

function fnHidePop(objPop) {
    objPop.style.display = "none";
}

function ShowAuction(auctionID) {
    document.getElementById(auctionID).style.display = "block";
}

function HideAuction(auctionID) {
    document.getElementById(auctionID).style.display = "none";
}

function stopRKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13)) { return false; }
}

// document.onkeypress = stopRKey; 

// this function shows the pop-up when user moves the mouse over the link
function Show(evt, interval1, interval2, interval3) {

    var e = (window.event) ? window.event : evt;
    if (document.documentElement && !document.documentElement.scrollTop)
    // IE6 +4.01 but no scrolling going on
    {
        //      alert(document.documentElement.scrollTop);
        x = e.clientX + document.documentElement.scrollLeft;  // get the mouse left position
        y = e.clientY + document.documentElement.scrollTop + 10; // get the mouse top position
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    // IE6 +4.01 and user has scrolled
    {
        //       alert(document.documentElement.scrollTop);
        x = e.clientX + document.documentElement.scrollLeft;  // get the mouse left position
        y = e.clientY + document.documentElement.scrollTop + 10; // get the mouse top position
    }
    else if (document.body && document.body.scrollTop) {
        //   alert(document.documentElement.scrollTop);
        x = e.clientX;   //+ document.body.scrollLeft;  // get the mouse left position
        y = e.clientY;   //+ document.body.scrollTop + 35; // get the mouse top position
    }

    var el = document.getElementById("time_change_content");
    if (el.hasChildNodes())
        el.removeChild(el.lastChild);
    var div1 = document.createElement("div");
    var para1 = document.createElement("p");
    var para2 = document.createElement("p");
    var para3 = document.createElement("p");

    para1.appendChild(document.createTextNode(interval1));
    para2.appendChild(document.createTextNode(interval2));
    para3.appendChild(document.createTextNode(interval3));

    div1.appendChild(para1);
    div1.appendChild(para2);
    div1.appendChild(para3);

    document.getElementById("time_change_content").appendChild(div1);
    document.getElementById("time_change").style.display = "block";
    document.getElementById("time_change").style.top = y + 'px';
    document.getElementById("time_change").style.left = x + 'px';
}
// this function hides the pop-up when user moves the mouse out of the link
function Hide() {
    document.getElementById("time_change").style.display = "none";
}

function fbs_click() { u = location.href; t = document.title; window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); pageTracker._trackEvent('Banners', 'Click', 'FaceBook Upper'); return false; }
