var bidAmount = 0;

var map = new Object();
var single_item = false;
var bidder = null;
var pinger = null;

var queues = new Array();

/* var lang = new Object(); */

var statusText = new Object();
statusText['active'] = 'active';
statusText['sold'] = 'sold';
statusText['pause'] = 'pause';
statusText['inactive'] = 'inactive';
statusText['wait'] = 'wait';
statusText['not_yet'] = 'not_yet';

/* new translation helper function */
function lang(str)
{
    var ret;
    try {
        ret = lang_arr[str];
    } catch(e) {
        ret = str;
    }
    return ret;
}

/* javascript version of the PHP format_price() in wBids, this doesn't look so nice though :( */
function format_price(price)
{
    var our_price = parseFloat(price);
    our_price = our_price.toFixed(2);
    our_price = our_price.toString();
    our_price = our_price.replace('.', currency_separator);
    if(currency_symbol_pos == 'left')
        return currency_symbol + our_price;
    else
        return our_price + ' ' + currency_symbol;
}

function queueRequest(packFunction, validationFunction, requestInterval, requestTimeout) {
    var method = 'GET';
    var async = 'true';
    var http = null;
    var actionArray = new Array();
    var pack = packFunction;
    var validate = validationFunction;
    var timeout = requestTimeout;
    var interval = requestInterval;
    var last_url = null;
    var last_time = 0;
    var owner = this;

    if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
        try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
        throw new Error( "This browser does not support XMLHttpRequest." );
    };

    http = new XMLHttpRequest();

    queues.push(this);
    var my_id = queues.length-1;
    setInterval('queues['+my_id+'].sendRequest()', requestInterval);

    this.addTarget = function (targetId) {
        actionArray.push(targetId);
    }

    this.removeTarget = function (targetId) {
        var tmp = actionArray;
        actionArray = new Array();
        for(var i=0;i<tmp.length;i++) {
            if(tmp[i] != targetId)
                actionArray.push(tmp[i]);
        }
    }

    this.checker = function() {
        if(http.readyState == 4) {
            if (http.status == 200) {
                validate(owner, http.responseXML);
                last_time = 0;
                last_url = null;
            } else {
                //showMessage('request failure [status: ' + http.status + ']');
            }

            // if we have pending queries, try to send them
            if(actionArray.length || last_url) {
                owner.sendRequest();
            }
        }
    }

    this.sendRequest = function() {
        if((!last_url && actionArray.length) && (http.readyState == 0 || http.readyState == 4)) {
            var url = pack(actionArray);
            url += '&rand='+Math.floor(Math.random()*10000000);
            http.open(method, url, async);
            last_url = url;
            last_time = microtime(true);
        } else if(last_url) {
            if(microtime(true) > (last_time + (timeout/1000))) {
                http.abort();
                http.open(method, last_url, async);
                last_time = microtime(true);
            } else {
                return;
            }
        } else {
            return;
        }
        http.onreadystatechange = owner.checker;
        http.send(null);
    }
}

function wbids_bid_callback(request, xmlInput) {
    if(!xmlInput) {
        alert('No XML input');
        return;
    }
    try {
        var x = xmlInput.getElementsByTagName(xmlText['message'])[0].childNodes[0].nodeValue;
        var id = xmlInput.getElementsByTagName(xmlText["id"])[0].childNodes[0].nodeValue;
        var success = parseInt(xmlInput.getElementsByTagName(xmlText["success"])[0].childNodes[0].nodeValue);
        var bids = parseInt(xmlInput.getElementsByTagName(xmlText["bids"])[0].childNodes[0].nodeValue);

        // show visual feedback
        wbids_message(x);
    } catch(e) {}

    request.removeTarget(id);

    // if the bid succeeded, bob the price!
    if(success) {
        try { document.getElementById('bidsField').innerHTML = bids; } catch(e) {}
    }

    if (typeof map[id] != 'undefined' && success) {
        // remove this id from request
        clearTimeout(map[id].ajaxTimer);
        pinger.addTarget(id);
    }
}

/* server time hack */
function time() { return (new Date().getTime() / 1000) - self.time_shift; }
window.time_diff = 0; // diff from server time
window.time_shift = 0; // current shift
window.time_el = false;
function updateServerTime(server_time) {
    window.time_diff = time() - server_time;
    if(window.time_diff != 0) {
        self.time_shift += window.time_diff;
        self.time_diff = 0;
    }

    if(!window.server_time_i) {
        updateTime();
        window.server_time_i = setInterval(updateTime, 250);
    }
}

function padNumber(num) {
    if(num < 10) 
        return '0'+num;
    return num;
}
function updateTime()
{
    // update server time
    if(!window.time_el)
        window.time_el = document.getElementById('server_time');
    if(window.time_el) {
        var timezone_offset = 0;
        var tmp = new Date((time() + parseInt(timezone_offset))* 1000);
        window.time_el.innerHTML = padNumber(tmp.getUTCDate())+"."+padNumber(tmp.getUTCMonth()+1)+"."+tmp.getUTCFullYear()+" "+padNumber(tmp.getUTCHours())+":"+padNumber(tmp.getUTCMinutes())+":"+padNumber(tmp.getUTCSeconds());
    }
}
/* server time hack */

function wbids_ping_callback(request, xml)
{
    if(!xml) {
        alert('No XML data');
        return;
    }

    var x=xml.getElementsByTagName(xmlText["item"]);
    var active = xml.getElementsByTagName(xmlText["active"])[0].getElementsByTagName(xmlText["id"]);

    var id;
    var timeLeft;
    var person;
    var price;
    var state;
    var add;
    var refresh;
    var name;
    var time;
    var node;
    var time_field;
    var takuu_wins = 0;
    var takuu_bidstowin = 0;
    /*
    if (x.length != amount) {
        window.location.reload();
    }
    */
    var msec = xml.getElementsByTagName(xmlText["msec"])[0].childNodes[0].nodeValue;
    try {
        var server_time = xml.getElementsByTagName(xmlText["time"])[0].childNodes[0].nodeValue;
        //updateServerTime(server_time);
    } catch(e) { }

    for (var i=0;i<x.length;i++)
    {
    	try {
	        id = x[i].getElementsByTagName(xmlText["id"])[0].childNodes[0].nodeValue;
	        timeLeft = x[i].getElementsByTagName(xmlText["time_left"])[0].childNodes[0].nodeValue;
	        person = x[i].getElementsByTagName(xmlText["last_bidder"])[0].childNodes[0].nodeValue;
	        price = x[i].getElementsByTagName(xmlText["price"])[0].childNodes[0].nodeValue;
	        state = x[i].getElementsByTagName(xmlText["state"])[0].childNodes[0].nodeValue;
	        add = x[i].getElementsByTagName(xmlText["raise_time"])[0].childNodes[0].nodeValue;
	        refresh = x[i].getElementsByTagName(xmlText["refresh_time"])[0].childNodes[0].nodeValue;
	        time_field = x[i].getElementsByTagName(xmlText["time_field"])[0].childNodes[0].nodeValue;
        } catch (e) {
                // reload only if front page
                if(!single_item)
                    window.location.reload();
                else {
                    alert('Virhe tuotteen latauksessa.');
                    return;
                }
        }

        try {
	        takuu_wins = x[i].getElementsByTagName(xmlText["takuu_wins"])[0].childNodes[0].nodeValue;
	        takuu_bidstowin = x[i].getElementsByTagName(xmlText["takuu_bidstowin"])[0].childNodes[0].nodeValue;
        } catch(e) { }

        // remove this id from request
        request.removeTarget(id);

        if (typeof map[id] == 'undefined') {
            //window.location.reload();
            alert('Virhe tuotteen '+id+'latauksessa.');
            return;
        } else {
            if(price != map[id].price && map[id].price > 0) {
                // bob!
                if(map[id].first)
                    wbids_bobprice_big('price'+id, price);
                else
                    wbids_bobprice_small('price'+id, price);
            }
            map[id].price = price;
            map[id].load(person, price, timeLeft, state, add, refresh, msec, time_field, takuu_wins, takuu_bidstowin);
        }

    }

    try { var ol = document.getElementById('bidderList'); } catch(e) {}
    if(ol) {
        try {
            ol = ol.getElementsByTagName('li');
        } catch(e) {}
    }

    if(!single_item) {
        /* check the active items on page are still up to date */
        for(var i=0;i<active.length;i++)
        {
            id = active[i].childNodes[0].nodeValue;
            if(typeof map[id] == 'undefined') {
                window.location.reload();
            }
        }
    } else {
        var y=xml.getElementsByTagName(xmlText["bidder"]);
        for(var j=0;j<y.length;j++) {
            try {
                name = y[j].getElementsByTagName(xmlText["name"])[0].childNodes[0].nodeValue;
                time = y[j].getElementsByTagName(xmlText["time"])[0].childNodes[0].nodeValue;
                node = ol[j];
            } catch(e) {
                //window.location.reload();
            }

            // generate the new list
            if(j == 0)
                node.innerHTML = "\t<strong>"+name+"</strong> <span style=\"font-size: 0.8em; color: #888;\">"+time+"</span>\n";
            else
                node.innerHTML = "\t"+name+" <span style=\"font-size: 0.8em; color: #888;\">"+time+"</span>\n";
        }
    }

}

function wbids_ping_pack(actionArray)
{
    // remove duplicates from actionArray and return the call url
    var tmp = new Array();
    for(var i=0;i<actionArray.length;i++) {
        var dupe = false;
        for(var j=0;j<tmp.length;j++) {
            if(tmp[j] == actionArray[i])
                dupe = true;
        }
        if(!dupe)
            tmp.push(actionArray[i]);
    }

    var ret = 'ping.php?';
    var first = true;
    for(var i=0;i<tmp.length;i++) {
        if(!first)
            ret += '&';
        else
            first = false;

        ret += 'id[]='+tmp[i];
    }
    if(single_item)
        ret += '&list=1';
    return ret;
}

function wbids_bid_pack(actionArray)
{
    // remove duplicates from actionArray and return the call url
    var tmp = new Array();
    for(var i=0;i<actionArray.length;i++) {
        var dupe = false;
        for(var j=0;j<tmp.length;j++) {
            if(tmp[j] == actionArray[i])
                dupe = true;
        }
        if(!dupe)
            tmp.push(actionArray[i]);
    }

    var ret = 'bid.php?';
    var first = true;
    for(var i=0;i<tmp.length;i++) {
        if(!first)
            ret += '&';
        else
            first = false;

        ret += 'prod[]='+tmp[i];
    }
    return ret;
}

function bidItem(id)
{
    // id of Item
    this.id = id;
    // time when bidding is done
    this.stoptime = new Date();

    this.oldPrice = lang('LOADING');

    this.priceField = document.getElementById("price" + this.id);
    this.lastBidderField = document.getElementById("lastbidder" + this.id);
    this.secsLeftField = document.getElementById("timeleft" + this.id);
    this.raiseTimeField = document.getElementById("add" + this.id);

    // savings counter is NOT essential, so try/catch it
    try { 
        this.savingsWorthReal = document.getElementById("savings_worth_real" + this.id);
        if(this.savingsWorthReal)
            this.savingsWorthReal = this.savingsWorthReal.value;

        this.savingsWorthField = document.getElementById("savings_worth" + this.id);
        this.savingsPriceField = document.getElementById("savings_price" + this.id);
        this.savingsSavingsField = document.getElementById("savings_savings" + this.id);
    } catch(e) { }

    // takuu feature is NOT essential, so try/catch it also
    try {
        this.takuuWinsField = document.getElementById("takuu_wins" + this.id);
        this.takuuBidsToWinField = document.getElementById("takuu_bidstowin" + this.id);
    } catch(e) { }

    this.first = 0;
    this.price = 0;

    this.ping = function () {
        var timeLeft = Math.floor((this.stoptime.getTime() - (new Date()).getTime()) / 1000);
        if (timeLeft > 15) {
        	if (this.secsLeftField.className != 'time1') {
        		this.secsLeftField.className = 'time1';
        	}
            this.secsLeftField.innerHTML = parseTime(timeLeft);
            this.timer = setTimeout("map["+this.id+"].ping()", 250);
        } else if (timeLeft > 0) {
        	if (this.secsLeftField.className != 'timelow') {
        		this.secsLeftField.className = 'timelow';
        	}
            this.secsLeftField.innerHTML = parseTime(timeLeft);
            this.timer = setTimeout("map["+this.id+"].ping()", 250);
        }
        else {
            this.secsLeftField.innerHTML = lang('CHECKING')+'...';
        }
    }

    this.load = function (bidder, price, timeLeft, status, add, refresh, msec, opens, takuu_wins, takuu_bidstowin) {
        clearTimeout(this.timer);
        clearTimeout(this.ajaxTimer);

        // savings
        if(this.savingsPriceField && this.savingsSavingsField) {
            var savings = eval(parseFloat(this.savingsWorthReal) - parseFloat(price));
            this.savingsPriceField.innerHTML = format_price(price);
            this.savingsSavingsField.innerHTML = format_price(savings);
        }

        // takuu
        if(this.takuuWinsField && this.takuuBidsToWinField) {
            this.takuuWinsField.innerHTML = takuu_wins;
            this.takuuBidsToWinField.innerHTML = takuu_bidstowin;
        }

        if (this.oldPrice != price) {
	        if(map[id].first)
	            wbids_bobprice_big('price'+this.id, price);
	        else
	            wbids_bobprice_small('price'+this.id, price);
        } else {
            this.priceField.innerHTML = format_price(price);
        }

        this.oldPrice = price;
        if (status == 'active' || status == 'not_yet') {
            this.stoptime = new Date(new Date().getTime() + (timeLeft * 1000) - msec);
            try { this.lastBidderField.innerHTML = bidder;  } catch(e) {}
            try { this.raiseTimeField.innerHTML = parseTime(add);  } catch(e) {}
            this.ajaxTimer = setTimeout('pinger.addTarget(' + this.id + ')', refresh * 1000);
            this.ping();
        }
        else if (status == 'pause') {
            try { this.lastBidderField.innerHTML = bidder; } catch(e) {}
            if(this.raiseTimeField)
                this.raiseTimeField.innerHTML = parseTime(add);
            this.secsLeftField.innerHTML = parseTime(timeLeft);
            this.ajaxTimer = setTimeout('pinger.addTarget(' + this.id + ')', refresh * 1000);
        }
        else if (status == 'sold') {
            try { this.lastBidderField.innerHTML = bidder; } catch(e) {}
            //if(this.raiseTimeField)
            //    this.raiseTimeField.innerHTML = lang('GRATZ_WINNER');
            if(this.raiseTimeField)
                this.raiseTimeField.innerHTML = parseTime(add);
            this.secsLeftField.innerHTML = lang('SOLD');
        }
        else if (status == 'wait') {
            try { this.lastBidderField.innerHTML = lang('WAITING_FOR_BIDS'); } catch (e) {}
            if(this.raiseTimeField)
                this.raiseTimeField.innerHTML = parseTime(add);
            //this.secsLeftField.innerHTML = '<span class="open_time">' + timeLeft + '<span>';
            this.secsLeftField.innerHTML = '<span class="open_time">' + opens + '<span>';
            this.timer = setTimeout('pinger.addTarget(' + this.id + ')', refresh * 1000);
        }

    }
}

function parseTime(inputSeconds) {
    var seconds = inputSeconds % 60;
    inputSeconds = (inputSeconds - seconds) / 60;
    var minutes = inputSeconds % 60;
    inputSeconds = (inputSeconds - minutes) / 60;
    var hours = inputSeconds;
    var returnString = '';
    if (hours > 0) {
        returnString = hours + " tuntia ";
    }
    if (minutes > 0) {
        returnString = returnString + minutes + " min ";
    }
    returnString = returnString + seconds + " sek ";
    return returnString;
}

function selectItem(el) {
    location.href = "managebots.php?item_id="+el.value;
}

function microtime(get_as_float) {
    var now = new Date().getTime() / 1000;
    var s = parseInt(now);
    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

/* vim:set et sw=4 sts=4: */
